hexsha
stringlengths
40
40
repo
stringlengths
4
114
path
stringlengths
6
369
license
sequence
language
stringclasses
1 value
identifier
stringlengths
1
123
original_docstring
stringlengths
8
49.2k
docstring
stringlengths
5
8.63k
docstring_tokens
sequence
code
stringlengths
25
988k
code_tokens
sequence
short_docstring
stringlengths
0
6.18k
short_docstring_tokens
sequence
comment
sequence
parameters
list
docstring_params
dict
46ecf95b937c6b183bc81e5ef82ba23b5e55657a
kbss/web-db-manager
db-manager-rest-api/src/main/java/org/kbss/webdb/dto/ColumnDto.java
[ "Apache-2.0" ]
Java
ColumnDto
/** * * @author Serhii Krivtsov * */
@author Serhii Krivtsov
[ "@author", "Serhii", "Krivtsov" ]
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class ColumnDto { private Integer columnSize; private String name; // TODO: enum private String type; public Integer getColumnSize() { return columnSize; } public void setColumnSize(Integer columnSize) { this.columnSize = columnSize; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String toString() { return "ColumnDto [columnSize=" + columnSize + ", name=" + name + ", type=" + type + "]"; } }
[ "@", "XmlRootElement", "@", "XmlAccessorType", "(", "XmlAccessType", ".", "FIELD", ")", "public", "class", "ColumnDto", "{", "private", "Integer", "columnSize", ";", "private", "String", "name", ";", "private", "String", "type", ";", "public", "Integer", "getColumnSize", "(", ")", "{", "return", "columnSize", ";", "}", "public", "void", "setColumnSize", "(", "Integer", "columnSize", ")", "{", "this", ".", "columnSize", "=", "columnSize", ";", "}", "public", "String", "getName", "(", ")", "{", "return", "name", ";", "}", "public", "void", "setName", "(", "String", "name", ")", "{", "this", ".", "name", "=", "name", ";", "}", "public", "String", "getType", "(", ")", "{", "return", "type", ";", "}", "public", "void", "setType", "(", "String", "type", ")", "{", "this", ".", "type", "=", "type", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "ColumnDto [columnSize=", "\"", "+", "columnSize", "+", "\"", ", name=", "\"", "+", "name", "+", "\"", ", type=", "\"", "+", "type", "+", "\"", "]", "\"", ";", "}", "}" ]
@author Serhii Krivtsov
[ "@author", "Serhii", "Krivtsov" ]
[ "// TODO: enum" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
46f31178c5ce1732a2a11e41ca3a838be589d517
brickviking/TinkersConstruct
src/main/java/slimeknights/tconstruct/library/events/teleport/SlimeslingTeleportEvent.java
[ "MIT" ]
Java
SlimeslingTeleportEvent
/** Event fired when an entity teleports using a slimesling */
Event fired when an entity teleports using a slimesling
[ "Event", "fired", "when", "an", "entity", "teleports", "using", "a", "slimesling" ]
@Cancelable public class SlimeslingTeleportEvent extends EntityTeleportEvent { @Getter private final ItemStack sling; public SlimeslingTeleportEvent(Entity entity, double targetX, double targetY, double targetZ, ItemStack sling) { super(entity, targetX, targetY, targetZ); this.sling = sling; } }
[ "@", "Cancelable", "public", "class", "SlimeslingTeleportEvent", "extends", "EntityTeleportEvent", "{", "@", "Getter", "private", "final", "ItemStack", "sling", ";", "public", "SlimeslingTeleportEvent", "(", "Entity", "entity", ",", "double", "targetX", ",", "double", "targetY", ",", "double", "targetZ", ",", "ItemStack", "sling", ")", "{", "super", "(", "entity", ",", "targetX", ",", "targetY", ",", "targetZ", ")", ";", "this", ".", "sling", "=", "sling", ";", "}", "}" ]
Event fired when an entity teleports using a slimesling
[ "Event", "fired", "when", "an", "entity", "teleports", "using", "a", "slimesling" ]
[]
[ { "param": "EntityTeleportEvent", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "EntityTeleportEvent", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
46fa4fb9d896155a09277fdf104eb94d938786f5
henrywu2019/aws-athena-query-federation
athena-federation-sdk/src/main/java/com/amazonaws/athena/connector/lambda/security/FederatedIdentity.java
[ "Apache-2.0" ]
Java
FederatedIdentity
/** * Defines the identity of the Athena caller. This is used in many of the SDK's request objects to convey to your * connector or UDF the identity of the caller that triggered the subsequent Lambda invocation. */
Defines the identity of the Athena caller. This is used in many of the SDK's request objects to convey to your connector or UDF the identity of the caller that triggered the subsequent Lambda invocation.
[ "Defines", "the", "identity", "of", "the", "Athena", "caller", ".", "This", "is", "used", "in", "many", "of", "the", "SDK", "'", "s", "request", "objects", "to", "convey", "to", "your", "connector", "or", "UDF", "the", "identity", "of", "the", "caller", "that", "triggered", "the", "subsequent", "Lambda", "invocation", "." ]
public class FederatedIdentity { public final String id; public final String principal; public final String account; @JsonCreator public FederatedIdentity(@JsonProperty("id") String id, @JsonProperty("principal") String principal, @JsonProperty("account") String account) { this.id = id; this.principal = principal; this.account = account; } @JsonProperty("id") public String getId() { return id; } @JsonProperty("principal") public String getPrincipal() { return principal; } @JsonProperty("account") public String getAccount() { return account; } }
[ "public", "class", "FederatedIdentity", "{", "public", "final", "String", "id", ";", "public", "final", "String", "principal", ";", "public", "final", "String", "account", ";", "@", "JsonCreator", "public", "FederatedIdentity", "(", "@", "JsonProperty", "(", "\"", "id", "\"", ")", "String", "id", ",", "@", "JsonProperty", "(", "\"", "principal", "\"", ")", "String", "principal", ",", "@", "JsonProperty", "(", "\"", "account", "\"", ")", "String", "account", ")", "{", "this", ".", "id", "=", "id", ";", "this", ".", "principal", "=", "principal", ";", "this", ".", "account", "=", "account", ";", "}", "@", "JsonProperty", "(", "\"", "id", "\"", ")", "public", "String", "getId", "(", ")", "{", "return", "id", ";", "}", "@", "JsonProperty", "(", "\"", "principal", "\"", ")", "public", "String", "getPrincipal", "(", ")", "{", "return", "principal", ";", "}", "@", "JsonProperty", "(", "\"", "account", "\"", ")", "public", "String", "getAccount", "(", ")", "{", "return", "account", ";", "}", "}" ]
Defines the identity of the Athena caller.
[ "Defines", "the", "identity", "of", "the", "Athena", "caller", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
46ff2de1f24d3a9b6ff15878c388c10ab782f648
anniiebaii/cs56-games-poker
src/edu/ucsb/cs56/projects/games/poker/CompareHands.java
[ "MIT" ]
Java
CompareHands
/** * Class that Compares Hands between Players */
Class that Compares Hands between Players
[ "Class", "that", "Compares", "Hands", "between", "Players" ]
public class CompareHands implements Serializable{ /** * ArrayList to hold each Player's hand, index = player number */ private ArrayList<Card> cardHand1; private ArrayList<Card> cardHand2; private ArrayList<ArrayList<Card>> hands; private ArrayList<Player> players; private int ties; /** * Multiplayer Compare Hands Constructor * supports dynamic arraylist for any number of players * @param ArrayList of all participating Players * @param table the cards that are on the table * */ public CompareHands(ArrayList<Player> Players, TableCards table) { // initialize ArrayLists // nested ArrayList; hands[0] = cards of player 0 // EX: hands = [ [card1, card2...], [card1, card2...] ] hands = new ArrayList<ArrayList<Card>>(Players.size()); players = Players; // for each player, get their hand and put it into ArrayList hands for (int i = 0; i < Players.size(); i ++) { // collection to store cards ArrayList<Card> cards = new ArrayList<Card>(); // get player at current index Player current = Players.get(i); // get current player's hand and add to cards cards.addAll(current.getHand()); cards.addAll(table.getFlopCards()); cards.add(table.getTurnCard()); // add player's cards into their hand hands.add(cards); } } /** * compareHands multiplayer function * Returns winner's player index (ex: winner = player 3, returns 2 because of indexing) * Returns 0 if there is a tie for the highest hand value **/ public int compareHands() { int max_value = -1; int winner = 0; ties = 0; for (ArrayList<Card> hand : hands) { int value = calculateValue(hand); int idx = hands.indexOf(hand); if (value > max_value) { // reset max value max_value = value; // replace previous winner if (players.get(idx).status == 1) { winner = hands.indexOf(hand); } // if exceeded highest hand, tie = 0 ties = 0; } // if equal highest hand, add to ties else if (value == max_value) { winner = 0 ; ties++; } } return winner; } // returns number of players tie public int numberOfTies() { return ties; } /** * This method is used if both hands are the same type * Hand is either this or the otherhand * recursion: Either 1 if called 1st, 2 if called 2nd * func won't work as intended if given a different number * @param c this is the array of cards * @param recursion MUST BE A 1 OR A 2 IF YOU WANT THIS TO WORK * @return int returns an integer */ private int sameHandUpdated(ArrayList<Card> c, int recursion) { ArrayList<Card> cards_tmp = new ArrayList<Card>(); Card yourCard = c.get(0); if (recursion==1) { if (c.get(1).getValue()>yourCard.getValue()) yourCard = c.get(1); cards_tmp.add(yourCard); for (int i=2; i<c.size(); i++) cards_tmp.add(c.get(i)); return calculateValue(cards_tmp); } if (recursion==2) { if (c.get(1).getValue()<yourCard.getValue()) yourCard = c.get(1); cards_tmp.add(yourCard); for(int i=2; i<c.size(); i++) cards_tmp.add(c.get(i)); return calculateValue(cards_tmp); } return -1; // Should only pass in 1 or 2 in parameter } /** * Method that finds the type of hand the player has * @param player the cards that belong to the players * @return int */ public int calculateValue(ArrayList<Card> player) { if(isStraightFlush(player)) return 8; else if(isFourOfAKind(player)) return 7; else if(isFullHouse(player)) return 6; else if(isFlush(player)) return 5; else if(isStraight(player)) return 4; else if(isThreeOfAKind(player)) return 3; else if(isTwoPair(player)) return 2; else if(isOnePair(player)) return 1; else return 0; } /** * Method that explicitly names the player's hand. * @param player: the cards belonging to the player. * @return String */ public String calculateValueToString(ArrayList<Card> player){ if(isStraightFlush(player)) return ("Straight Flush"); else if(isFourOfAKind(player)) return ("Four of a Kind"); else if(isFullHouse(player)) return ("Full House"); else if(isFlush(player)) return ("Flush"); else if(isStraight(player)) return ("Straight"); else if(isThreeOfAKind(player)) return ("Three of a Kind"); else if(isTwoPair(player)) return ("Two Pair"); else if(isOnePair(player)) return ("Pair"); else return ("Mix"); } /** * compareMessage for multiplayer **/ public String compareMessage(){ // get winner's index in hands ArrayList int winner = this.compareHands(); ArrayList<Card> winning_hand = hands.get(winner); String message; /** if it is not a TIE **/ if (winner >= 0) { // get winner's cards if (players.size() == 2) { message = calculateValueToString(winning_hand) + " beats " + calculateValueToString(hands.get(1-winner)) + "!"; } else message = calculateValueToString(winning_hand) + " beats all!"; } else { message = "It's a tie with " + calculateValueToString(winning_hand); } return message; } /** * @param player the cards belonging to the player * @return sortedHand */ public ArrayList<Integer> sortHand(ArrayList<Card> player) { ArrayList<Integer> sortedHand = new ArrayList<Integer>(); for (int i = 0; i < player.size(); i++) { sortedHand.add(player.get(i).getValue()); } Collections.sort(sortedHand); return sortedHand; } /** Returns boolean for if the hand is a straight flush * @param player Cards belonging to the player * @return boolean */ private boolean isStraightFlush(ArrayList<Card> player){ int straightFlushCounter=0; int spadeCounter=0; int clubsCounter=0; int heartCounter=0; int diamondCounter=0; ArrayList<Integer> spades=new ArrayList<Integer>(); ArrayList<Integer> clubs=new ArrayList<Integer>(); ArrayList<Integer> diamonds=new ArrayList<Integer>(); ArrayList<Integer> hearts=new ArrayList<Integer>(); for(Card c: player){ //Sort the hand into seperate arrayLists defined by suits. if(c.getSuit()=="S"){ spadeCounter++; spades.add(c.getValue()); } else if(c.getSuit()=="C"){ clubsCounter++; clubs.add(c.getValue()); } else if(c.getSuit()=="D"){ diamondCounter++; diamonds.add(c.getValue()); } else if(c.getSuit()=="H"){ heartCounter++; hearts.add(c.getValue()); } } int i=0; removeDuplicates(spades); removeDuplicates(clubs); removeDuplicates(diamonds); removeDuplicates(hearts); if(spadeCounter>=5){ Collections.sort(spades); if (spades.get(spades.size()-1 ) == 14) //if the top value is an ace, use the method below if (isLowestRankingStraight(spades)) return true; for (i = 0; i < spadeCounter-5; i++) { if(spades.get(i)==(spades.get(i+1)-1) && spades.get(i)==(spades.get(i+2)-2) && spades.get(i)==(spades.get(i+3)-3) && spades.get(i)==(spades.get(i+4)-4)) straightFlushCounter=4; } } else if(clubsCounter>=5){ Collections.sort(clubs); if (clubs.get(clubs.size()-1 ) == 14) //if the top value is an ace, use the method below if (isLowestRankingStraight(clubs)) return true; for (i = 0; i < clubsCounter-5; i++) { if(clubs.get(i)==(clubs.get(i+1)-1) && clubs.get(i)==(clubs.get(i+2)-2) && clubs.get(i)==(clubs.get(i+3)-3) && clubs.get(i)==(clubs.get(i+4)-4)) straightFlushCounter=4; } } else if(heartCounter>=5){ if (hearts.get(hearts.size()-1 ) == 14) //if the top value is an ace, use the method below if (isLowestRankingStraight(hearts)) return true; Collections.sort(hearts); for (i = 0; i < heartCounter-5; i++) { if(spades.get(i)==(hearts.get(i+1)-1) && hearts.get(i)==(hearts.get(i+2)-2) && hearts.get(i)==(hearts.get(i+3)-3) && hearts.get(i)==(hearts.get(i+4)-4)) straightFlushCounter=4; } } else if(diamondCounter>=5){ if (diamonds.get(diamonds.size()-1 ) == 14) //if the top value is an ace, use the method below if (isLowestRankingStraight(diamonds)) return true; Collections.sort(diamonds); for (i = 0; i < diamondCounter-5; i++) { if(diamonds.get(i)==(diamonds.get(i+1)-1) && diamonds.get(i)==(diamonds.get(i+2)-2) && diamonds.get(i)==(diamonds.get(i+3)-3) && diamonds.get(i)==(diamonds.get(i+4)-4)) straightFlushCounter=4; } } else return false; if(straightFlushCounter==4) return true; else return false; } /** Returns boolean for if the hand has a four of a kind. * @param player the cards belonging to the player * @return boolean */ private boolean isFourOfAKind(ArrayList<Card> player) { ArrayList<Integer> sortedHand=sortHand(player); int quadCounter=0; for(int i=0;i<player.size()-3;i++) { if(sortedHand.get(i)==sortedHand.get(i+1) && sortedHand.get(i+1) ==sortedHand.get(i+2) && sortedHand.get(i+2)==sortedHand.get(i+3)) { quadCounter=3; } } if(quadCounter==3) return true; else return false; } /** Returns boolean for if the hand is a full house. * @param player the cards belonging to the player * @return boolean */ private boolean isFullHouse(ArrayList<Card> player) { ArrayList<Integer> sortedHand=sortHand(player); int doubleCounter=0; int tripleCounter=0; for(int i=0;i<player.size()-1;i++) { if(sortedHand.get(i)==sortedHand.get(i+1)) { if(tripleCounter==1) { sortedHand.remove(i+1); sortedHand.remove(i); tripleCounter++; break; } else { if(i==1) tripleCounter=0; else tripleCounter++; } } else tripleCounter=0; } if(tripleCounter==2) { sortedHand.trimToSize(); int size=sortedHand.size(); for(int i=0;i<(size-1);i++) { if(sortedHand.get(i)==sortedHand.get(i+1)) doubleCounter++; } } else return false; if(doubleCounter>=1) return true; else return false; } /** Returns boolean for if the hand is a flush. * @param player the cards belonging to the player * @return boolean */ private boolean isFlush(ArrayList<Card> player) { int spadeCounter=0; int cloverCounter=0; int heartCounter=0; int diamondCounter=0; for(Card c: player){ if(c.getSuit()=="S") spadeCounter++; else if(c.getSuit()=="C") cloverCounter++; else if(c.getSuit()=="D") diamondCounter++; else heartCounter++; } if(spadeCounter>=5 || cloverCounter>=5 || diamondCounter>=5 || heartCounter>=5) return true; else return false; } /** Returns boolean for if the hand is a straight. * @param player the card belonging to the player * @return boolean */ private boolean isStraight(ArrayList<Card> player) { ArrayList<Integer> sortedHand=sortHand(player); removeDuplicates(sortedHand); if (sortedHand.get(sortedHand.size()-1 ) == 14) //if the top value is an ace, use the method below if (isLowestRankingStraight(sortedHand)) return true; int straightCounter=0; for(int i=0;i<player.size()-4;i++) { if(sortedHand.get(i)==(sortedHand.get(i+1)-1) && sortedHand.get(i)==(sortedHand.get(i+2)-2) && sortedHand.get(i)==(sortedHand.get(i+3)-3) && sortedHand.get(i)==(sortedHand.get(i+4)-4)) { straightCounter=4; } } return(straightCounter==4); } /** *Used when checking for Straights. Ace has a value of 14 * but technically it should also have a value of one. This method covers this. * @param sortedHand a hand that is already sorted from lowest to highest * @return boolean */ private boolean isLowestRankingStraight(ArrayList<Integer> sortedHand) { for (int i = 0; i<sortedHand.size()-3; i++) { if (sortedHand.get(0) == 2 && //has 2 sortedHand.get(1) == 3 && //has 3 sortedHand.get(2) == 4 && //has 4 sortedHand.get(3) == 5 ) //has 5 return true; } return false; } /** * Method that removes duplicate integers from an arrayList. * If the hand is sorted, it stays sorted. * @param sortedHand it is sorted, but it doesn't have to be. * @return sortedHand a hand without duplicates. */ private ArrayList<Integer> removeDuplicates(ArrayList<Integer> sortedHand) { ArrayList<Integer> deDupList = new ArrayList<>(); for(Integer i : sortedHand){ if(! (deDupList.contains(i) ) ){ deDupList.add(i); } } sortedHand = deDupList; return sortedHand; } /** Returns boolean for if the hand has three of a kind. * @param player the cards belonging to the player * @return boolean */ private boolean isThreeOfAKind(ArrayList<Card> player) { if(isFullHouse(player)){ return false; } ArrayList<Integer> sortedHand= sortHand(player); int tripleCounter=0; for(int i=0;i<player.size()-1;i++) { if(sortedHand.get(i)==sortedHand.get(i+1)) tripleCounter++; else { if(tripleCounter==1) tripleCounter=0; } } if(tripleCounter==2) return true; else return false; } /** Returns boolean for if the hand has two pairs. * @param player the cards that belong to the player * @return boolean */ private boolean isTwoPair(ArrayList<Card> player) { ArrayList<Integer> sortedHand=new ArrayList<Integer>(); sortedHand=sortHand(player); int pair1Counter=0; int pair2Counter=0; int pair1Int=100; int pair2Int=100; for(int i=0;i<player.size()-1;i++) { if(sortedHand.get(i)==sortedHand.get(i+1)){ if(sortedHand.get(i)==pair1Int || sortedHand.get(i)==pair2Int){ return false; } else if(pair1Counter==1){ pair2Counter++; pair2Int=sortedHand.get(i); } else{ pair1Counter++; pair1Int=sortedHand.get(i); } } } return(pair1Counter==1 && pair2Counter>=1); } /** Returns boolean for if the hand has only one pair. * @param player cards that belong to the player * @return boolean */ private boolean isOnePair(ArrayList<Card> player) { ArrayList<Integer> sortedHand=new ArrayList<Integer>(); sortedHand=sortHand(player); int pairCounter=0; for(int i=0;i<player.size()-1;i++) { if(sortedHand.get(i)==sortedHand.get(i+1)) pairCounter++; } if(pairCounter==1) return true; else return false; } /** * Returns suit occurring the most in a hand * @return char representing the suit */ private char getMostCommonSuit(ArrayList<Card> hand) { int heartsCounter = 0; int diamondsCounter = 0; int spadesCounter = 0; int clubsCounter = 0; for (int i = 0; i < hand.size(); i++) { switch (hand.get(i).getSuit().charAt(0)) { case 'H': heartsCounter++; break; case 'D': diamondsCounter++; break; case 'S': spadesCounter++; break; case 'C': clubsCounter++; break; } } int max_occurrences = Math.max(heartsCounter, Math.max(diamondsCounter, Math.max(spadesCounter, clubsCounter))); if (max_occurrences == heartsCounter) { return 'H'; } else if (max_occurrences == diamondsCounter) { return 'D'; } else if (max_occurrences == spadesCounter) { return 'S'; } return 'C'; } /** * Determines the better hand of two straight flushes * @return 1 if the player wins, 0 if the opponent wins, 2 if it is a tie */ private int straightFlushTie() { ArrayList<Integer> sortedHand1 = sortHand(cardHand1); ArrayList<Integer> sortedHand2 = sortHand(cardHand2); char mostCommonSuit1 = getMostCommonSuit(cardHand1); char mostCommonSuit2 = getMostCommonSuit(cardHand2); int maxCardHand1 = 0; int maxCardHand2 = 0; for (int i = cardHand1.size() - 1; i >= 0; i--) { if (cardHand1.get(i).getSuit().charAt(0) == mostCommonSuit1 && cardHand1.get(i).getValue() > maxCardHand1) { maxCardHand1 = cardHand1.get(i).getValue(); } if (cardHand2.get(i).getSuit().charAt(0) == mostCommonSuit2 && cardHand2.get(i).getValue() > maxCardHand2) { maxCardHand2 = cardHand2.get(i).getValue(); } } if (maxCardHand1 > maxCardHand2) return 1; else if (maxCardHand2 > maxCardHand1) return 0; else return 2; } /** * Determines the better hand of two four of a kinds * @return 1 if the player wins, 0 if the opponent wins */ private int fourOfAKindTie() { int fourOfAKind1 = 0; int fourOfAKind2 = 0; ArrayList<Integer> sortedHand1 = sortHand(cardHand1); ArrayList<Integer> sortedHand2 = sortHand(cardHand2); for (int i = 0; i < sortedHand1.size(); i++) { if (Collections.frequency(sortedHand1, sortedHand1.get(i)) == 4) fourOfAKind1 = sortedHand1.get(i); if (Collections.frequency(sortedHand2, sortedHand2.get(i)) == 4) fourOfAKind2 = sortedHand2.get(i); } if (fourOfAKind1 > fourOfAKind2) return 1; return 0; } /** * Determines the better hand of two full houses * @return 1 if the player wins, 0 if the opponent wins */ private int fullHouseTie() { return threeOfAKindTie(); } /** * Determines the better hand of two flushes * @return 1 if the player wins, 0 if the opponent wins, 2 if it is a tie */ private int flushTie() { char mostCommonSuit1 = getMostCommonSuit(cardHand1); char mostCommonSuit2 = getMostCommonSuit(cardHand2); ArrayList<Integer> flushCards1 = new ArrayList<Integer>(); ArrayList<Integer> flushCards2 = new ArrayList<Integer>(); for (int i = 0; i < cardHand1.size(); i++) { if (cardHand1.get(i).getSuit().charAt(0) == mostCommonSuit1) flushCards1.add(cardHand1.get(i).getValue()); if (cardHand2.get(i).getSuit().charAt(0) == mostCommonSuit2) flushCards2.add(cardHand2.get(i).getValue()); } Collections.sort(flushCards1); Collections.sort(flushCards2); int flush1_index = flushCards1.size() - 1; int flush2_index = flushCards2.size() - 1; while ((flush1_index >= 0) && (flush2_index >= 0)) { if (flushCards1.get(flush1_index) > flushCards2.get(flush2_index)) { return 1; } else if (flushCards2.get(flush2_index) > flushCards1.get(flush1_index)) { return 0; } else { flush1_index--; flush2_index--; } } return 2; // players have exact same cards for flush } /** * Determines the better hand of two straights * @return 1 if the player wins, 0 if the opponent wins, 2 if it is a tie */ private int straightTie() { ArrayList<Integer> sortedHand1 = sortHand(cardHand1); ArrayList<Integer> sortedHand2 = sortHand(cardHand2); removeDuplicates(sortedHand1); removeDuplicates(sortedHand2); int straightEndIndex1 = 0; int straightEndIndex2 = 0; for (int i = 0; i < sortedHand1.size() - 4; i++) { if(sortedHand1.get(i)==(sortedHand1.get(i + 1) - 1) && sortedHand1.get(i)==(sortedHand1.get(i + 2) - 2) && sortedHand1.get(i)==(sortedHand1.get(i + 3) - 3) && sortedHand1.get(i)==(sortedHand1.get(i + 4) - 4)) { straightEndIndex1 = i + 4; } if(sortedHand2.get(i)==(sortedHand2.get(i + 1) - 1) && sortedHand2.get(i)==(sortedHand2.get(i + 2) - 2) && sortedHand2.get(i)==(sortedHand2.get(i + 3) - 3) && sortedHand2.get(i)==(sortedHand2.get(i + 4) - 4)) { straightEndIndex2 = i + 4; } } if (sortedHand1.get(straightEndIndex1) > sortedHand2.get(straightEndIndex2)) return 1; else if (sortedHand2.get(straightEndIndex2) > sortedHand2.get(straightEndIndex2)) return 0; return 2; } /** * Determines the better hand of two three of a kinds * @return 1 if the player wins, 0 if the opponent wins, 2 if it is a tie */ private int threeOfAKindTie() { int threeOfAKind1 = 0; int threeOfAKind2 = 0; ArrayList<Integer> sortedHand1 = sortHand(cardHand1); ArrayList<Integer> sortedHand2 = sortHand(cardHand2); for (int i = 0; i < sortedHand1.size(); i++) { if (Collections.frequency(sortedHand1, sortedHand1.get(i)) == 3 && sortedHand1.get(i) > threeOfAKind1) threeOfAKind1 = sortedHand1.get(i); if (Collections.frequency(sortedHand2, sortedHand2.get(i)) == 3 && sortedHand2.get(i) > threeOfAKind2) threeOfAKind2 = sortedHand2.get(i); } if (threeOfAKind1 > threeOfAKind2) return 1; return 0; } /** * Determines the better hand of two two pairs * @return 1 if the player wins, 0 if the opponent wins, 2 if it is a tie */ private int twoPairTie() { ArrayList<Integer> sortedHand1 = sortHand(cardHand1); ArrayList<Integer> sortedHand2 = sortHand(cardHand2); ArrayList<Integer> pairsHand1 = new ArrayList<Integer>(); // each entry represents a pair (a 4 means a pair of 4's) ArrayList<Integer> pairsHand2 = new ArrayList<Integer>(); for (int i = 0; i < sortedHand1.size(); i++) { if ((Collections.frequency(sortedHand1, sortedHand1.get(i)) == 2) && (!pairsHand1.contains(sortedHand1.get(i)))) { pairsHand1.add(sortedHand1.get(i)); } if ((Collections.frequency(sortedHand2, sortedHand2.get(i)) == 2) && (!pairsHand2.contains(sortedHand2.get(i)))) { pairsHand2.add(sortedHand2.get(i)); } } int pairsHand1_index = pairsHand1.size() - 1; int pairsHand2_index = pairsHand2.size() - 1; int maxNumPairs = 2; // only want to compare two highest pairs from each hand while (maxNumPairs > 0) { if (pairsHand1.get(pairsHand1_index) > pairsHand2.get(pairsHand2_index)) { return 1; } else if (pairsHand2.get(pairsHand2_index) > pairsHand1.get(pairsHand1_index)) { return 0; } else { pairsHand1_index--; pairsHand2_index--; } } // if both pairs are the same, check the fifth card in each hand int fifthCardHand1 = 0; int fifthCardHand2 = 0; for (int i = sortedHand1.size() - 1; i >= 0; i--) { if (!pairsHand1.contains(sortedHand1.get(i))) { fifthCardHand1 = sortedHand1.get(i); } if (!pairsHand2.contains(sortedHand2.get(i))) { fifthCardHand2 = sortedHand2.get(i); } } if (fifthCardHand1 > fifthCardHand2) return 1; else if (fifthCardHand2 > fifthCardHand1) return 0; return 2; } /** * Determines the better hand of two pairs * @return 1 if the player wins, 0 if the opponent wins, 2 if it is a tie */ private int pairTie() { ArrayList<Integer> sortedHand1 = sortHand(cardHand1); ArrayList<Integer> sortedHand2 = sortHand(cardHand2); int pair1 = 0; int pair2 = 0; for (int i = sortedHand1.size() - 1; i >= 0; i--) { if ((Collections.frequency(sortedHand1, sortedHand1.get(i)) == 2) && (pair1 == 0)) { pair1 = sortedHand1.get(i); } if ((Collections.frequency(sortedHand2, sortedHand2.get(i)) == 2) && (pair2 == 0)) { pair2 = sortedHand2.get(i); } } if (pair1 > pair2) return 1; else if (pair2 > pair1) return 0; sortedHand1.remove(new Integer(pair1)); sortedHand1.remove(new Integer(pair1)); sortedHand2.remove(new Integer(pair2)); sortedHand2.remove(new Integer(pair2)); int hand1_index = sortedHand1.size() - 1; int hand2_index = sortedHand2.size() - 1; int cardsExamined = 0; while ((hand1_index >= 0) && (hand2_index >= 0) && (cardsExamined < 3)) { if (sortedHand1.get(hand1_index) > sortedHand2.get(hand2_index)) { return 1; } else if (sortedHand2.get(hand2_index) > sortedHand1.get(hand1_index)) { return 0; } else { hand1_index--; hand2_index--; cardsExamined++; } } return 2; } /** * Determines the winner when there is no clear hand using the high card * @return 1 if the player wins, 0 if the opponent wins, 2 if it is a tie */ private int highCardTie() { ArrayList<Integer> sortedHand1 = sortHand(cardHand1); ArrayList<Integer> sortedHand2 = sortHand(cardHand2); for (int i = sortedHand1.size() - 1; i > sortedHand1.size() - 6; i--) { if (sortedHand1.get(i) > sortedHand2.get(i)) return 1; else if (sortedHand2.get(i) > sortedHand1.get(i)) return 0; } return 2; } }
[ "public", "class", "CompareHands", "implements", "Serializable", "{", "/**\n * ArrayList to hold each Player's hand, index = player number\n */", "private", "ArrayList", "<", "Card", ">", "cardHand1", ";", "private", "ArrayList", "<", "Card", ">", "cardHand2", ";", "private", "ArrayList", "<", "ArrayList", "<", "Card", ">", ">", "hands", ";", "private", "ArrayList", "<", "Player", ">", "players", ";", "private", "int", "ties", ";", "/**\n * Multiplayer Compare Hands Constructor\n * supports dynamic arraylist for any number of players\n * @param ArrayList of all participating Players\n * @param table the cards that are on the table\n *\n */", "public", "CompareHands", "(", "ArrayList", "<", "Player", ">", "Players", ",", "TableCards", "table", ")", "{", "hands", "=", "new", "ArrayList", "<", "ArrayList", "<", "Card", ">", ">", "(", "Players", ".", "size", "(", ")", ")", ";", "players", "=", "Players", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "Players", ".", "size", "(", ")", ";", "i", "++", ")", "{", "ArrayList", "<", "Card", ">", "cards", "=", "new", "ArrayList", "<", "Card", ">", "(", ")", ";", "Player", "current", "=", "Players", ".", "get", "(", "i", ")", ";", "cards", ".", "addAll", "(", "current", ".", "getHand", "(", ")", ")", ";", "cards", ".", "addAll", "(", "table", ".", "getFlopCards", "(", ")", ")", ";", "cards", ".", "add", "(", "table", ".", "getTurnCard", "(", ")", ")", ";", "hands", ".", "add", "(", "cards", ")", ";", "}", "}", "/**\n * compareHands multiplayer function\n * Returns winner's player index (ex: winner = player 3, returns 2 because of indexing)\n * Returns 0 if there is a tie for the highest hand value\n **/", "public", "int", "compareHands", "(", ")", "{", "int", "max_value", "=", "-", "1", ";", "int", "winner", "=", "0", ";", "ties", "=", "0", ";", "for", "(", "ArrayList", "<", "Card", ">", "hand", ":", "hands", ")", "{", "int", "value", "=", "calculateValue", "(", "hand", ")", ";", "int", "idx", "=", "hands", ".", "indexOf", "(", "hand", ")", ";", "if", "(", "value", ">", "max_value", ")", "{", "max_value", "=", "value", ";", "if", "(", "players", ".", "get", "(", "idx", ")", ".", "status", "==", "1", ")", "{", "winner", "=", "hands", ".", "indexOf", "(", "hand", ")", ";", "}", "ties", "=", "0", ";", "}", "else", "if", "(", "value", "==", "max_value", ")", "{", "winner", "=", "0", ";", "ties", "++", ";", "}", "}", "return", "winner", ";", "}", "public", "int", "numberOfTies", "(", ")", "{", "return", "ties", ";", "}", "/**\n * This method is used if both hands are the same type\n * Hand is either this or the otherhand\n * recursion: Either 1 if called 1st, 2 if called 2nd\n * func won't work as intended if given a different number\n * @param c this is the array of cards\n * @param recursion MUST BE A 1 OR A 2 IF YOU WANT THIS TO WORK\n * @return int returns an integer\n */", "private", "int", "sameHandUpdated", "(", "ArrayList", "<", "Card", ">", "c", ",", "int", "recursion", ")", "{", "ArrayList", "<", "Card", ">", "cards_tmp", "=", "new", "ArrayList", "<", "Card", ">", "(", ")", ";", "Card", "yourCard", "=", "c", ".", "get", "(", "0", ")", ";", "if", "(", "recursion", "==", "1", ")", "{", "if", "(", "c", ".", "get", "(", "1", ")", ".", "getValue", "(", ")", ">", "yourCard", ".", "getValue", "(", ")", ")", "yourCard", "=", "c", ".", "get", "(", "1", ")", ";", "cards_tmp", ".", "add", "(", "yourCard", ")", ";", "for", "(", "int", "i", "=", "2", ";", "i", "<", "c", ".", "size", "(", ")", ";", "i", "++", ")", "cards_tmp", ".", "add", "(", "c", ".", "get", "(", "i", ")", ")", ";", "return", "calculateValue", "(", "cards_tmp", ")", ";", "}", "if", "(", "recursion", "==", "2", ")", "{", "if", "(", "c", ".", "get", "(", "1", ")", ".", "getValue", "(", ")", "<", "yourCard", ".", "getValue", "(", ")", ")", "yourCard", "=", "c", ".", "get", "(", "1", ")", ";", "cards_tmp", ".", "add", "(", "yourCard", ")", ";", "for", "(", "int", "i", "=", "2", ";", "i", "<", "c", ".", "size", "(", ")", ";", "i", "++", ")", "cards_tmp", ".", "add", "(", "c", ".", "get", "(", "i", ")", ")", ";", "return", "calculateValue", "(", "cards_tmp", ")", ";", "}", "return", "-", "1", ";", "}", "/**\n * Method that finds the type of hand the player has\n * @param player the cards that belong to the players\n * @return int\n */", "public", "int", "calculateValue", "(", "ArrayList", "<", "Card", ">", "player", ")", "{", "if", "(", "isStraightFlush", "(", "player", ")", ")", "return", "8", ";", "else", "if", "(", "isFourOfAKind", "(", "player", ")", ")", "return", "7", ";", "else", "if", "(", "isFullHouse", "(", "player", ")", ")", "return", "6", ";", "else", "if", "(", "isFlush", "(", "player", ")", ")", "return", "5", ";", "else", "if", "(", "isStraight", "(", "player", ")", ")", "return", "4", ";", "else", "if", "(", "isThreeOfAKind", "(", "player", ")", ")", "return", "3", ";", "else", "if", "(", "isTwoPair", "(", "player", ")", ")", "return", "2", ";", "else", "if", "(", "isOnePair", "(", "player", ")", ")", "return", "1", ";", "else", "return", "0", ";", "}", "/**\n * Method that explicitly names the player's hand.\n * @param player: the cards belonging to the player.\n * @return String\n */", "public", "String", "calculateValueToString", "(", "ArrayList", "<", "Card", ">", "player", ")", "{", "if", "(", "isStraightFlush", "(", "player", ")", ")", "return", "(", "\"", "Straight Flush", "\"", ")", ";", "else", "if", "(", "isFourOfAKind", "(", "player", ")", ")", "return", "(", "\"", "Four of a Kind", "\"", ")", ";", "else", "if", "(", "isFullHouse", "(", "player", ")", ")", "return", "(", "\"", "Full House", "\"", ")", ";", "else", "if", "(", "isFlush", "(", "player", ")", ")", "return", "(", "\"", "Flush", "\"", ")", ";", "else", "if", "(", "isStraight", "(", "player", ")", ")", "return", "(", "\"", "Straight", "\"", ")", ";", "else", "if", "(", "isThreeOfAKind", "(", "player", ")", ")", "return", "(", "\"", "Three of a Kind", "\"", ")", ";", "else", "if", "(", "isTwoPair", "(", "player", ")", ")", "return", "(", "\"", "Two Pair", "\"", ")", ";", "else", "if", "(", "isOnePair", "(", "player", ")", ")", "return", "(", "\"", "Pair", "\"", ")", ";", "else", "return", "(", "\"", "Mix", "\"", ")", ";", "}", "/**\n * compareMessage for multiplayer\n **/", "public", "String", "compareMessage", "(", ")", "{", "int", "winner", "=", "this", ".", "compareHands", "(", ")", ";", "ArrayList", "<", "Card", ">", "winning_hand", "=", "hands", ".", "get", "(", "winner", ")", ";", "String", "message", ";", "/** if it is not a TIE **/", "if", "(", "winner", ">=", "0", ")", "{", "if", "(", "players", ".", "size", "(", ")", "==", "2", ")", "{", "message", "=", "calculateValueToString", "(", "winning_hand", ")", "+", "\"", " beats ", "\"", "+", "calculateValueToString", "(", "hands", ".", "get", "(", "1", "-", "winner", ")", ")", "+", "\"", "!", "\"", ";", "}", "else", "message", "=", "calculateValueToString", "(", "winning_hand", ")", "+", "\"", " beats all!", "\"", ";", "}", "else", "{", "message", "=", "\"", "It's a tie with ", "\"", "+", "calculateValueToString", "(", "winning_hand", ")", ";", "}", "return", "message", ";", "}", "/**\n * @param player the cards belonging to the player\n * @return sortedHand\n */", "public", "ArrayList", "<", "Integer", ">", "sortHand", "(", "ArrayList", "<", "Card", ">", "player", ")", "{", "ArrayList", "<", "Integer", ">", "sortedHand", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "player", ".", "size", "(", ")", ";", "i", "++", ")", "{", "sortedHand", ".", "add", "(", "player", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ")", ";", "}", "Collections", ".", "sort", "(", "sortedHand", ")", ";", "return", "sortedHand", ";", "}", "/**\n Returns boolean for if the hand is a straight flush\n * @param player Cards belonging to the player\n * @return boolean\n */", "private", "boolean", "isStraightFlush", "(", "ArrayList", "<", "Card", ">", "player", ")", "{", "int", "straightFlushCounter", "=", "0", ";", "int", "spadeCounter", "=", "0", ";", "int", "clubsCounter", "=", "0", ";", "int", "heartCounter", "=", "0", ";", "int", "diamondCounter", "=", "0", ";", "ArrayList", "<", "Integer", ">", "spades", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "ArrayList", "<", "Integer", ">", "clubs", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "ArrayList", "<", "Integer", ">", "diamonds", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "ArrayList", "<", "Integer", ">", "hearts", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "for", "(", "Card", "c", ":", "player", ")", "{", "if", "(", "c", ".", "getSuit", "(", ")", "==", "\"", "S", "\"", ")", "{", "spadeCounter", "++", ";", "spades", ".", "add", "(", "c", ".", "getValue", "(", ")", ")", ";", "}", "else", "if", "(", "c", ".", "getSuit", "(", ")", "==", "\"", "C", "\"", ")", "{", "clubsCounter", "++", ";", "clubs", ".", "add", "(", "c", ".", "getValue", "(", ")", ")", ";", "}", "else", "if", "(", "c", ".", "getSuit", "(", ")", "==", "\"", "D", "\"", ")", "{", "diamondCounter", "++", ";", "diamonds", ".", "add", "(", "c", ".", "getValue", "(", ")", ")", ";", "}", "else", "if", "(", "c", ".", "getSuit", "(", ")", "==", "\"", "H", "\"", ")", "{", "heartCounter", "++", ";", "hearts", ".", "add", "(", "c", ".", "getValue", "(", ")", ")", ";", "}", "}", "int", "i", "=", "0", ";", "removeDuplicates", "(", "spades", ")", ";", "removeDuplicates", "(", "clubs", ")", ";", "removeDuplicates", "(", "diamonds", ")", ";", "removeDuplicates", "(", "hearts", ")", ";", "if", "(", "spadeCounter", ">=", "5", ")", "{", "Collections", ".", "sort", "(", "spades", ")", ";", "if", "(", "spades", ".", "get", "(", "spades", ".", "size", "(", ")", "-", "1", ")", "==", "14", ")", "if", "(", "isLowestRankingStraight", "(", "spades", ")", ")", "return", "true", ";", "for", "(", "i", "=", "0", ";", "i", "<", "spadeCounter", "-", "5", ";", "i", "++", ")", "{", "if", "(", "spades", ".", "get", "(", "i", ")", "==", "(", "spades", ".", "get", "(", "i", "+", "1", ")", "-", "1", ")", "&&", "spades", ".", "get", "(", "i", ")", "==", "(", "spades", ".", "get", "(", "i", "+", "2", ")", "-", "2", ")", "&&", "spades", ".", "get", "(", "i", ")", "==", "(", "spades", ".", "get", "(", "i", "+", "3", ")", "-", "3", ")", "&&", "spades", ".", "get", "(", "i", ")", "==", "(", "spades", ".", "get", "(", "i", "+", "4", ")", "-", "4", ")", ")", "straightFlushCounter", "=", "4", ";", "}", "}", "else", "if", "(", "clubsCounter", ">=", "5", ")", "{", "Collections", ".", "sort", "(", "clubs", ")", ";", "if", "(", "clubs", ".", "get", "(", "clubs", ".", "size", "(", ")", "-", "1", ")", "==", "14", ")", "if", "(", "isLowestRankingStraight", "(", "clubs", ")", ")", "return", "true", ";", "for", "(", "i", "=", "0", ";", "i", "<", "clubsCounter", "-", "5", ";", "i", "++", ")", "{", "if", "(", "clubs", ".", "get", "(", "i", ")", "==", "(", "clubs", ".", "get", "(", "i", "+", "1", ")", "-", "1", ")", "&&", "clubs", ".", "get", "(", "i", ")", "==", "(", "clubs", ".", "get", "(", "i", "+", "2", ")", "-", "2", ")", "&&", "clubs", ".", "get", "(", "i", ")", "==", "(", "clubs", ".", "get", "(", "i", "+", "3", ")", "-", "3", ")", "&&", "clubs", ".", "get", "(", "i", ")", "==", "(", "clubs", ".", "get", "(", "i", "+", "4", ")", "-", "4", ")", ")", "straightFlushCounter", "=", "4", ";", "}", "}", "else", "if", "(", "heartCounter", ">=", "5", ")", "{", "if", "(", "hearts", ".", "get", "(", "hearts", ".", "size", "(", ")", "-", "1", ")", "==", "14", ")", "if", "(", "isLowestRankingStraight", "(", "hearts", ")", ")", "return", "true", ";", "Collections", ".", "sort", "(", "hearts", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "heartCounter", "-", "5", ";", "i", "++", ")", "{", "if", "(", "spades", ".", "get", "(", "i", ")", "==", "(", "hearts", ".", "get", "(", "i", "+", "1", ")", "-", "1", ")", "&&", "hearts", ".", "get", "(", "i", ")", "==", "(", "hearts", ".", "get", "(", "i", "+", "2", ")", "-", "2", ")", "&&", "hearts", ".", "get", "(", "i", ")", "==", "(", "hearts", ".", "get", "(", "i", "+", "3", ")", "-", "3", ")", "&&", "hearts", ".", "get", "(", "i", ")", "==", "(", "hearts", ".", "get", "(", "i", "+", "4", ")", "-", "4", ")", ")", "straightFlushCounter", "=", "4", ";", "}", "}", "else", "if", "(", "diamondCounter", ">=", "5", ")", "{", "if", "(", "diamonds", ".", "get", "(", "diamonds", ".", "size", "(", ")", "-", "1", ")", "==", "14", ")", "if", "(", "isLowestRankingStraight", "(", "diamonds", ")", ")", "return", "true", ";", "Collections", ".", "sort", "(", "diamonds", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "diamondCounter", "-", "5", ";", "i", "++", ")", "{", "if", "(", "diamonds", ".", "get", "(", "i", ")", "==", "(", "diamonds", ".", "get", "(", "i", "+", "1", ")", "-", "1", ")", "&&", "diamonds", ".", "get", "(", "i", ")", "==", "(", "diamonds", ".", "get", "(", "i", "+", "2", ")", "-", "2", ")", "&&", "diamonds", ".", "get", "(", "i", ")", "==", "(", "diamonds", ".", "get", "(", "i", "+", "3", ")", "-", "3", ")", "&&", "diamonds", ".", "get", "(", "i", ")", "==", "(", "diamonds", ".", "get", "(", "i", "+", "4", ")", "-", "4", ")", ")", "straightFlushCounter", "=", "4", ";", "}", "}", "else", "return", "false", ";", "if", "(", "straightFlushCounter", "==", "4", ")", "return", "true", ";", "else", "return", "false", ";", "}", "/**\n Returns boolean for if the hand has a four of a kind.\n * @param player the cards belonging to the player\n * @return boolean\n */", "private", "boolean", "isFourOfAKind", "(", "ArrayList", "<", "Card", ">", "player", ")", "{", "ArrayList", "<", "Integer", ">", "sortedHand", "=", "sortHand", "(", "player", ")", ";", "int", "quadCounter", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "player", ".", "size", "(", ")", "-", "3", ";", "i", "++", ")", "{", "if", "(", "sortedHand", ".", "get", "(", "i", ")", "==", "sortedHand", ".", "get", "(", "i", "+", "1", ")", "&&", "sortedHand", ".", "get", "(", "i", "+", "1", ")", "==", "sortedHand", ".", "get", "(", "i", "+", "2", ")", "&&", "sortedHand", ".", "get", "(", "i", "+", "2", ")", "==", "sortedHand", ".", "get", "(", "i", "+", "3", ")", ")", "{", "quadCounter", "=", "3", ";", "}", "}", "if", "(", "quadCounter", "==", "3", ")", "return", "true", ";", "else", "return", "false", ";", "}", "/**\n Returns boolean for if the hand is a full house.\n * @param player the cards belonging to the player\n * @return boolean\n */", "private", "boolean", "isFullHouse", "(", "ArrayList", "<", "Card", ">", "player", ")", "{", "ArrayList", "<", "Integer", ">", "sortedHand", "=", "sortHand", "(", "player", ")", ";", "int", "doubleCounter", "=", "0", ";", "int", "tripleCounter", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "player", ".", "size", "(", ")", "-", "1", ";", "i", "++", ")", "{", "if", "(", "sortedHand", ".", "get", "(", "i", ")", "==", "sortedHand", ".", "get", "(", "i", "+", "1", ")", ")", "{", "if", "(", "tripleCounter", "==", "1", ")", "{", "sortedHand", ".", "remove", "(", "i", "+", "1", ")", ";", "sortedHand", ".", "remove", "(", "i", ")", ";", "tripleCounter", "++", ";", "break", ";", "}", "else", "{", "if", "(", "i", "==", "1", ")", "tripleCounter", "=", "0", ";", "else", "tripleCounter", "++", ";", "}", "}", "else", "tripleCounter", "=", "0", ";", "}", "if", "(", "tripleCounter", "==", "2", ")", "{", "sortedHand", ".", "trimToSize", "(", ")", ";", "int", "size", "=", "sortedHand", ".", "size", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "(", "size", "-", "1", ")", ";", "i", "++", ")", "{", "if", "(", "sortedHand", ".", "get", "(", "i", ")", "==", "sortedHand", ".", "get", "(", "i", "+", "1", ")", ")", "doubleCounter", "++", ";", "}", "}", "else", "return", "false", ";", "if", "(", "doubleCounter", ">=", "1", ")", "return", "true", ";", "else", "return", "false", ";", "}", "/**\n Returns boolean for if the hand is a flush.\n * @param player the cards belonging to the player\n * @return boolean\n */", "private", "boolean", "isFlush", "(", "ArrayList", "<", "Card", ">", "player", ")", "{", "int", "spadeCounter", "=", "0", ";", "int", "cloverCounter", "=", "0", ";", "int", "heartCounter", "=", "0", ";", "int", "diamondCounter", "=", "0", ";", "for", "(", "Card", "c", ":", "player", ")", "{", "if", "(", "c", ".", "getSuit", "(", ")", "==", "\"", "S", "\"", ")", "spadeCounter", "++", ";", "else", "if", "(", "c", ".", "getSuit", "(", ")", "==", "\"", "C", "\"", ")", "cloverCounter", "++", ";", "else", "if", "(", "c", ".", "getSuit", "(", ")", "==", "\"", "D", "\"", ")", "diamondCounter", "++", ";", "else", "heartCounter", "++", ";", "}", "if", "(", "spadeCounter", ">=", "5", "||", "cloverCounter", ">=", "5", "||", "diamondCounter", ">=", "5", "||", "heartCounter", ">=", "5", ")", "return", "true", ";", "else", "return", "false", ";", "}", "/**\n Returns boolean for if the hand is a straight.\n * @param player the card belonging to the player\n * @return boolean\n */", "private", "boolean", "isStraight", "(", "ArrayList", "<", "Card", ">", "player", ")", "{", "ArrayList", "<", "Integer", ">", "sortedHand", "=", "sortHand", "(", "player", ")", ";", "removeDuplicates", "(", "sortedHand", ")", ";", "if", "(", "sortedHand", ".", "get", "(", "sortedHand", ".", "size", "(", ")", "-", "1", ")", "==", "14", ")", "if", "(", "isLowestRankingStraight", "(", "sortedHand", ")", ")", "return", "true", ";", "int", "straightCounter", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "player", ".", "size", "(", ")", "-", "4", ";", "i", "++", ")", "{", "if", "(", "sortedHand", ".", "get", "(", "i", ")", "==", "(", "sortedHand", ".", "get", "(", "i", "+", "1", ")", "-", "1", ")", "&&", "sortedHand", ".", "get", "(", "i", ")", "==", "(", "sortedHand", ".", "get", "(", "i", "+", "2", ")", "-", "2", ")", "&&", "sortedHand", ".", "get", "(", "i", ")", "==", "(", "sortedHand", ".", "get", "(", "i", "+", "3", ")", "-", "3", ")", "&&", "sortedHand", ".", "get", "(", "i", ")", "==", "(", "sortedHand", ".", "get", "(", "i", "+", "4", ")", "-", "4", ")", ")", "{", "straightCounter", "=", "4", ";", "}", "}", "return", "(", "straightCounter", "==", "4", ")", ";", "}", "/**\n *Used when checking for Straights. Ace has a value of 14\n * but technically it should also have a value of one. This method covers this.\n * @param sortedHand a hand that is already sorted from lowest to highest\n * @return boolean\n */", "private", "boolean", "isLowestRankingStraight", "(", "ArrayList", "<", "Integer", ">", "sortedHand", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "sortedHand", ".", "size", "(", ")", "-", "3", ";", "i", "++", ")", "{", "if", "(", "sortedHand", ".", "get", "(", "0", ")", "==", "2", "&&", "sortedHand", ".", "get", "(", "1", ")", "==", "3", "&&", "sortedHand", ".", "get", "(", "2", ")", "==", "4", "&&", "sortedHand", ".", "get", "(", "3", ")", "==", "5", ")", "return", "true", ";", "}", "return", "false", ";", "}", "/**\n * Method that removes duplicate integers from an arrayList.\n * If the hand is sorted, it stays sorted.\n * @param sortedHand it is sorted, but it doesn't have to be.\n * @return sortedHand a hand without duplicates.\n */", "private", "ArrayList", "<", "Integer", ">", "removeDuplicates", "(", "ArrayList", "<", "Integer", ">", "sortedHand", ")", "{", "ArrayList", "<", "Integer", ">", "deDupList", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "Integer", "i", ":", "sortedHand", ")", "{", "if", "(", "!", "(", "deDupList", ".", "contains", "(", "i", ")", ")", ")", "{", "deDupList", ".", "add", "(", "i", ")", ";", "}", "}", "sortedHand", "=", "deDupList", ";", "return", "sortedHand", ";", "}", "/**\n Returns boolean for if the hand has three of a kind.\n * @param player the cards belonging to the player\n * @return boolean\n */", "private", "boolean", "isThreeOfAKind", "(", "ArrayList", "<", "Card", ">", "player", ")", "{", "if", "(", "isFullHouse", "(", "player", ")", ")", "{", "return", "false", ";", "}", "ArrayList", "<", "Integer", ">", "sortedHand", "=", "sortHand", "(", "player", ")", ";", "int", "tripleCounter", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "player", ".", "size", "(", ")", "-", "1", ";", "i", "++", ")", "{", "if", "(", "sortedHand", ".", "get", "(", "i", ")", "==", "sortedHand", ".", "get", "(", "i", "+", "1", ")", ")", "tripleCounter", "++", ";", "else", "{", "if", "(", "tripleCounter", "==", "1", ")", "tripleCounter", "=", "0", ";", "}", "}", "if", "(", "tripleCounter", "==", "2", ")", "return", "true", ";", "else", "return", "false", ";", "}", "/**\n Returns boolean for if the hand has two pairs.\n * @param player the cards that belong to the player\n * @return boolean\n */", "private", "boolean", "isTwoPair", "(", "ArrayList", "<", "Card", ">", "player", ")", "{", "ArrayList", "<", "Integer", ">", "sortedHand", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "sortedHand", "=", "sortHand", "(", "player", ")", ";", "int", "pair1Counter", "=", "0", ";", "int", "pair2Counter", "=", "0", ";", "int", "pair1Int", "=", "100", ";", "int", "pair2Int", "=", "100", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "player", ".", "size", "(", ")", "-", "1", ";", "i", "++", ")", "{", "if", "(", "sortedHand", ".", "get", "(", "i", ")", "==", "sortedHand", ".", "get", "(", "i", "+", "1", ")", ")", "{", "if", "(", "sortedHand", ".", "get", "(", "i", ")", "==", "pair1Int", "||", "sortedHand", ".", "get", "(", "i", ")", "==", "pair2Int", ")", "{", "return", "false", ";", "}", "else", "if", "(", "pair1Counter", "==", "1", ")", "{", "pair2Counter", "++", ";", "pair2Int", "=", "sortedHand", ".", "get", "(", "i", ")", ";", "}", "else", "{", "pair1Counter", "++", ";", "pair1Int", "=", "sortedHand", ".", "get", "(", "i", ")", ";", "}", "}", "}", "return", "(", "pair1Counter", "==", "1", "&&", "pair2Counter", ">=", "1", ")", ";", "}", "/**\n Returns boolean for if the hand has only one pair.\n * @param player cards that belong to the player\n * @return boolean\n */", "private", "boolean", "isOnePair", "(", "ArrayList", "<", "Card", ">", "player", ")", "{", "ArrayList", "<", "Integer", ">", "sortedHand", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "sortedHand", "=", "sortHand", "(", "player", ")", ";", "int", "pairCounter", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "player", ".", "size", "(", ")", "-", "1", ";", "i", "++", ")", "{", "if", "(", "sortedHand", ".", "get", "(", "i", ")", "==", "sortedHand", ".", "get", "(", "i", "+", "1", ")", ")", "pairCounter", "++", ";", "}", "if", "(", "pairCounter", "==", "1", ")", "return", "true", ";", "else", "return", "false", ";", "}", "/**\n * Returns suit occurring the most in a hand\n * @return char representing the suit\n */", "private", "char", "getMostCommonSuit", "(", "ArrayList", "<", "Card", ">", "hand", ")", "{", "int", "heartsCounter", "=", "0", ";", "int", "diamondsCounter", "=", "0", ";", "int", "spadesCounter", "=", "0", ";", "int", "clubsCounter", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "hand", ".", "size", "(", ")", ";", "i", "++", ")", "{", "switch", "(", "hand", ".", "get", "(", "i", ")", ".", "getSuit", "(", ")", ".", "charAt", "(", "0", ")", ")", "{", "case", "'H'", ":", "heartsCounter", "++", ";", "break", ";", "case", "'D'", ":", "diamondsCounter", "++", ";", "break", ";", "case", "'S'", ":", "spadesCounter", "++", ";", "break", ";", "case", "'C'", ":", "clubsCounter", "++", ";", "break", ";", "}", "}", "int", "max_occurrences", "=", "Math", ".", "max", "(", "heartsCounter", ",", "Math", ".", "max", "(", "diamondsCounter", ",", "Math", ".", "max", "(", "spadesCounter", ",", "clubsCounter", ")", ")", ")", ";", "if", "(", "max_occurrences", "==", "heartsCounter", ")", "{", "return", "'H'", ";", "}", "else", "if", "(", "max_occurrences", "==", "diamondsCounter", ")", "{", "return", "'D'", ";", "}", "else", "if", "(", "max_occurrences", "==", "spadesCounter", ")", "{", "return", "'S'", ";", "}", "return", "'C'", ";", "}", "/**\n * Determines the better hand of two straight flushes\n * @return 1 if the player wins, 0 if the opponent wins, 2 if it is a tie\n */", "private", "int", "straightFlushTie", "(", ")", "{", "ArrayList", "<", "Integer", ">", "sortedHand1", "=", "sortHand", "(", "cardHand1", ")", ";", "ArrayList", "<", "Integer", ">", "sortedHand2", "=", "sortHand", "(", "cardHand2", ")", ";", "char", "mostCommonSuit1", "=", "getMostCommonSuit", "(", "cardHand1", ")", ";", "char", "mostCommonSuit2", "=", "getMostCommonSuit", "(", "cardHand2", ")", ";", "int", "maxCardHand1", "=", "0", ";", "int", "maxCardHand2", "=", "0", ";", "for", "(", "int", "i", "=", "cardHand1", ".", "size", "(", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "cardHand1", ".", "get", "(", "i", ")", ".", "getSuit", "(", ")", ".", "charAt", "(", "0", ")", "==", "mostCommonSuit1", "&&", "cardHand1", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ">", "maxCardHand1", ")", "{", "maxCardHand1", "=", "cardHand1", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ";", "}", "if", "(", "cardHand2", ".", "get", "(", "i", ")", ".", "getSuit", "(", ")", ".", "charAt", "(", "0", ")", "==", "mostCommonSuit2", "&&", "cardHand2", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ">", "maxCardHand2", ")", "{", "maxCardHand2", "=", "cardHand2", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ";", "}", "}", "if", "(", "maxCardHand1", ">", "maxCardHand2", ")", "return", "1", ";", "else", "if", "(", "maxCardHand2", ">", "maxCardHand1", ")", "return", "0", ";", "else", "return", "2", ";", "}", "/**\n * Determines the better hand of two four of a kinds\n * @return 1 if the player wins, 0 if the opponent wins\n */", "private", "int", "fourOfAKindTie", "(", ")", "{", "int", "fourOfAKind1", "=", "0", ";", "int", "fourOfAKind2", "=", "0", ";", "ArrayList", "<", "Integer", ">", "sortedHand1", "=", "sortHand", "(", "cardHand1", ")", ";", "ArrayList", "<", "Integer", ">", "sortedHand2", "=", "sortHand", "(", "cardHand2", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "sortedHand1", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "Collections", ".", "frequency", "(", "sortedHand1", ",", "sortedHand1", ".", "get", "(", "i", ")", ")", "==", "4", ")", "fourOfAKind1", "=", "sortedHand1", ".", "get", "(", "i", ")", ";", "if", "(", "Collections", ".", "frequency", "(", "sortedHand2", ",", "sortedHand2", ".", "get", "(", "i", ")", ")", "==", "4", ")", "fourOfAKind2", "=", "sortedHand2", ".", "get", "(", "i", ")", ";", "}", "if", "(", "fourOfAKind1", ">", "fourOfAKind2", ")", "return", "1", ";", "return", "0", ";", "}", "/**\n * Determines the better hand of two full houses\n * @return 1 if the player wins, 0 if the opponent wins\n */", "private", "int", "fullHouseTie", "(", ")", "{", "return", "threeOfAKindTie", "(", ")", ";", "}", "/**\n * Determines the better hand of two flushes\n * @return 1 if the player wins, 0 if the opponent wins, 2 if it is a tie\n */", "private", "int", "flushTie", "(", ")", "{", "char", "mostCommonSuit1", "=", "getMostCommonSuit", "(", "cardHand1", ")", ";", "char", "mostCommonSuit2", "=", "getMostCommonSuit", "(", "cardHand2", ")", ";", "ArrayList", "<", "Integer", ">", "flushCards1", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "ArrayList", "<", "Integer", ">", "flushCards2", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "cardHand1", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "cardHand1", ".", "get", "(", "i", ")", ".", "getSuit", "(", ")", ".", "charAt", "(", "0", ")", "==", "mostCommonSuit1", ")", "flushCards1", ".", "add", "(", "cardHand1", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ")", ";", "if", "(", "cardHand2", ".", "get", "(", "i", ")", ".", "getSuit", "(", ")", ".", "charAt", "(", "0", ")", "==", "mostCommonSuit2", ")", "flushCards2", ".", "add", "(", "cardHand2", ".", "get", "(", "i", ")", ".", "getValue", "(", ")", ")", ";", "}", "Collections", ".", "sort", "(", "flushCards1", ")", ";", "Collections", ".", "sort", "(", "flushCards2", ")", ";", "int", "flush1_index", "=", "flushCards1", ".", "size", "(", ")", "-", "1", ";", "int", "flush2_index", "=", "flushCards2", ".", "size", "(", ")", "-", "1", ";", "while", "(", "(", "flush1_index", ">=", "0", ")", "&&", "(", "flush2_index", ">=", "0", ")", ")", "{", "if", "(", "flushCards1", ".", "get", "(", "flush1_index", ")", ">", "flushCards2", ".", "get", "(", "flush2_index", ")", ")", "{", "return", "1", ";", "}", "else", "if", "(", "flushCards2", ".", "get", "(", "flush2_index", ")", ">", "flushCards1", ".", "get", "(", "flush1_index", ")", ")", "{", "return", "0", ";", "}", "else", "{", "flush1_index", "--", ";", "flush2_index", "--", ";", "}", "}", "return", "2", ";", "}", "/**\n * Determines the better hand of two straights\n * @return 1 if the player wins, 0 if the opponent wins, 2 if it is a tie\n */", "private", "int", "straightTie", "(", ")", "{", "ArrayList", "<", "Integer", ">", "sortedHand1", "=", "sortHand", "(", "cardHand1", ")", ";", "ArrayList", "<", "Integer", ">", "sortedHand2", "=", "sortHand", "(", "cardHand2", ")", ";", "removeDuplicates", "(", "sortedHand1", ")", ";", "removeDuplicates", "(", "sortedHand2", ")", ";", "int", "straightEndIndex1", "=", "0", ";", "int", "straightEndIndex2", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "sortedHand1", ".", "size", "(", ")", "-", "4", ";", "i", "++", ")", "{", "if", "(", "sortedHand1", ".", "get", "(", "i", ")", "==", "(", "sortedHand1", ".", "get", "(", "i", "+", "1", ")", "-", "1", ")", "&&", "sortedHand1", ".", "get", "(", "i", ")", "==", "(", "sortedHand1", ".", "get", "(", "i", "+", "2", ")", "-", "2", ")", "&&", "sortedHand1", ".", "get", "(", "i", ")", "==", "(", "sortedHand1", ".", "get", "(", "i", "+", "3", ")", "-", "3", ")", "&&", "sortedHand1", ".", "get", "(", "i", ")", "==", "(", "sortedHand1", ".", "get", "(", "i", "+", "4", ")", "-", "4", ")", ")", "{", "straightEndIndex1", "=", "i", "+", "4", ";", "}", "if", "(", "sortedHand2", ".", "get", "(", "i", ")", "==", "(", "sortedHand2", ".", "get", "(", "i", "+", "1", ")", "-", "1", ")", "&&", "sortedHand2", ".", "get", "(", "i", ")", "==", "(", "sortedHand2", ".", "get", "(", "i", "+", "2", ")", "-", "2", ")", "&&", "sortedHand2", ".", "get", "(", "i", ")", "==", "(", "sortedHand2", ".", "get", "(", "i", "+", "3", ")", "-", "3", ")", "&&", "sortedHand2", ".", "get", "(", "i", ")", "==", "(", "sortedHand2", ".", "get", "(", "i", "+", "4", ")", "-", "4", ")", ")", "{", "straightEndIndex2", "=", "i", "+", "4", ";", "}", "}", "if", "(", "sortedHand1", ".", "get", "(", "straightEndIndex1", ")", ">", "sortedHand2", ".", "get", "(", "straightEndIndex2", ")", ")", "return", "1", ";", "else", "if", "(", "sortedHand2", ".", "get", "(", "straightEndIndex2", ")", ">", "sortedHand2", ".", "get", "(", "straightEndIndex2", ")", ")", "return", "0", ";", "return", "2", ";", "}", "/**\n * Determines the better hand of two three of a kinds\n * @return 1 if the player wins, 0 if the opponent wins, 2 if it is a tie\n */", "private", "int", "threeOfAKindTie", "(", ")", "{", "int", "threeOfAKind1", "=", "0", ";", "int", "threeOfAKind2", "=", "0", ";", "ArrayList", "<", "Integer", ">", "sortedHand1", "=", "sortHand", "(", "cardHand1", ")", ";", "ArrayList", "<", "Integer", ">", "sortedHand2", "=", "sortHand", "(", "cardHand2", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "sortedHand1", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "Collections", ".", "frequency", "(", "sortedHand1", ",", "sortedHand1", ".", "get", "(", "i", ")", ")", "==", "3", "&&", "sortedHand1", ".", "get", "(", "i", ")", ">", "threeOfAKind1", ")", "threeOfAKind1", "=", "sortedHand1", ".", "get", "(", "i", ")", ";", "if", "(", "Collections", ".", "frequency", "(", "sortedHand2", ",", "sortedHand2", ".", "get", "(", "i", ")", ")", "==", "3", "&&", "sortedHand2", ".", "get", "(", "i", ")", ">", "threeOfAKind2", ")", "threeOfAKind2", "=", "sortedHand2", ".", "get", "(", "i", ")", ";", "}", "if", "(", "threeOfAKind1", ">", "threeOfAKind2", ")", "return", "1", ";", "return", "0", ";", "}", "/**\n * Determines the better hand of two two pairs\n * @return 1 if the player wins, 0 if the opponent wins, 2 if it is a tie\n */", "private", "int", "twoPairTie", "(", ")", "{", "ArrayList", "<", "Integer", ">", "sortedHand1", "=", "sortHand", "(", "cardHand1", ")", ";", "ArrayList", "<", "Integer", ">", "sortedHand2", "=", "sortHand", "(", "cardHand2", ")", ";", "ArrayList", "<", "Integer", ">", "pairsHand1", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "ArrayList", "<", "Integer", ">", "pairsHand2", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "sortedHand1", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "(", "Collections", ".", "frequency", "(", "sortedHand1", ",", "sortedHand1", ".", "get", "(", "i", ")", ")", "==", "2", ")", "&&", "(", "!", "pairsHand1", ".", "contains", "(", "sortedHand1", ".", "get", "(", "i", ")", ")", ")", ")", "{", "pairsHand1", ".", "add", "(", "sortedHand1", ".", "get", "(", "i", ")", ")", ";", "}", "if", "(", "(", "Collections", ".", "frequency", "(", "sortedHand2", ",", "sortedHand2", ".", "get", "(", "i", ")", ")", "==", "2", ")", "&&", "(", "!", "pairsHand2", ".", "contains", "(", "sortedHand2", ".", "get", "(", "i", ")", ")", ")", ")", "{", "pairsHand2", ".", "add", "(", "sortedHand2", ".", "get", "(", "i", ")", ")", ";", "}", "}", "int", "pairsHand1_index", "=", "pairsHand1", ".", "size", "(", ")", "-", "1", ";", "int", "pairsHand2_index", "=", "pairsHand2", ".", "size", "(", ")", "-", "1", ";", "int", "maxNumPairs", "=", "2", ";", "while", "(", "maxNumPairs", ">", "0", ")", "{", "if", "(", "pairsHand1", ".", "get", "(", "pairsHand1_index", ")", ">", "pairsHand2", ".", "get", "(", "pairsHand2_index", ")", ")", "{", "return", "1", ";", "}", "else", "if", "(", "pairsHand2", ".", "get", "(", "pairsHand2_index", ")", ">", "pairsHand1", ".", "get", "(", "pairsHand1_index", ")", ")", "{", "return", "0", ";", "}", "else", "{", "pairsHand1_index", "--", ";", "pairsHand2_index", "--", ";", "}", "}", "int", "fifthCardHand1", "=", "0", ";", "int", "fifthCardHand2", "=", "0", ";", "for", "(", "int", "i", "=", "sortedHand1", ".", "size", "(", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "!", "pairsHand1", ".", "contains", "(", "sortedHand1", ".", "get", "(", "i", ")", ")", ")", "{", "fifthCardHand1", "=", "sortedHand1", ".", "get", "(", "i", ")", ";", "}", "if", "(", "!", "pairsHand2", ".", "contains", "(", "sortedHand2", ".", "get", "(", "i", ")", ")", ")", "{", "fifthCardHand2", "=", "sortedHand2", ".", "get", "(", "i", ")", ";", "}", "}", "if", "(", "fifthCardHand1", ">", "fifthCardHand2", ")", "return", "1", ";", "else", "if", "(", "fifthCardHand2", ">", "fifthCardHand1", ")", "return", "0", ";", "return", "2", ";", "}", "/**\n * Determines the better hand of two pairs\n * @return 1 if the player wins, 0 if the opponent wins, 2 if it is a tie\n */", "private", "int", "pairTie", "(", ")", "{", "ArrayList", "<", "Integer", ">", "sortedHand1", "=", "sortHand", "(", "cardHand1", ")", ";", "ArrayList", "<", "Integer", ">", "sortedHand2", "=", "sortHand", "(", "cardHand2", ")", ";", "int", "pair1", "=", "0", ";", "int", "pair2", "=", "0", ";", "for", "(", "int", "i", "=", "sortedHand1", ".", "size", "(", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "(", "Collections", ".", "frequency", "(", "sortedHand1", ",", "sortedHand1", ".", "get", "(", "i", ")", ")", "==", "2", ")", "&&", "(", "pair1", "==", "0", ")", ")", "{", "pair1", "=", "sortedHand1", ".", "get", "(", "i", ")", ";", "}", "if", "(", "(", "Collections", ".", "frequency", "(", "sortedHand2", ",", "sortedHand2", ".", "get", "(", "i", ")", ")", "==", "2", ")", "&&", "(", "pair2", "==", "0", ")", ")", "{", "pair2", "=", "sortedHand2", ".", "get", "(", "i", ")", ";", "}", "}", "if", "(", "pair1", ">", "pair2", ")", "return", "1", ";", "else", "if", "(", "pair2", ">", "pair1", ")", "return", "0", ";", "sortedHand1", ".", "remove", "(", "new", "Integer", "(", "pair1", ")", ")", ";", "sortedHand1", ".", "remove", "(", "new", "Integer", "(", "pair1", ")", ")", ";", "sortedHand2", ".", "remove", "(", "new", "Integer", "(", "pair2", ")", ")", ";", "sortedHand2", ".", "remove", "(", "new", "Integer", "(", "pair2", ")", ")", ";", "int", "hand1_index", "=", "sortedHand1", ".", "size", "(", ")", "-", "1", ";", "int", "hand2_index", "=", "sortedHand2", ".", "size", "(", ")", "-", "1", ";", "int", "cardsExamined", "=", "0", ";", "while", "(", "(", "hand1_index", ">=", "0", ")", "&&", "(", "hand2_index", ">=", "0", ")", "&&", "(", "cardsExamined", "<", "3", ")", ")", "{", "if", "(", "sortedHand1", ".", "get", "(", "hand1_index", ")", ">", "sortedHand2", ".", "get", "(", "hand2_index", ")", ")", "{", "return", "1", ";", "}", "else", "if", "(", "sortedHand2", ".", "get", "(", "hand2_index", ")", ">", "sortedHand1", ".", "get", "(", "hand1_index", ")", ")", "{", "return", "0", ";", "}", "else", "{", "hand1_index", "--", ";", "hand2_index", "--", ";", "cardsExamined", "++", ";", "}", "}", "return", "2", ";", "}", "/**\n * Determines the winner when there is no clear hand using the high card\n * @return 1 if the player wins, 0 if the opponent wins, 2 if it is a tie\n */", "private", "int", "highCardTie", "(", ")", "{", "ArrayList", "<", "Integer", ">", "sortedHand1", "=", "sortHand", "(", "cardHand1", ")", ";", "ArrayList", "<", "Integer", ">", "sortedHand2", "=", "sortHand", "(", "cardHand2", ")", ";", "for", "(", "int", "i", "=", "sortedHand1", ".", "size", "(", ")", "-", "1", ";", "i", ">", "sortedHand1", ".", "size", "(", ")", "-", "6", ";", "i", "--", ")", "{", "if", "(", "sortedHand1", ".", "get", "(", "i", ")", ">", "sortedHand2", ".", "get", "(", "i", ")", ")", "return", "1", ";", "else", "if", "(", "sortedHand2", ".", "get", "(", "i", ")", ">", "sortedHand1", ".", "get", "(", "i", ")", ")", "return", "0", ";", "}", "return", "2", ";", "}", "}" ]
Class that Compares Hands between Players
[ "Class", "that", "Compares", "Hands", "between", "Players" ]
[ "// initialize ArrayLists", "// nested ArrayList; hands[0] = cards of player 0", "// EX: hands = [ [card1, card2...], [card1, card2...] ]", "// for each player, get their hand and put it into ArrayList hands", "// collection to store cards", "// get player at current index", "// get current player's hand and add to cards", "// add player's cards into their hand", "// reset max value", "// replace previous winner", "// if exceeded highest hand, tie = 0", "// if equal highest hand, add to ties", "// returns number of players tie", "// Should only pass in 1 or 2 in parameter", "// get winner's index in hands ArrayList", "// get winner's cards", "//Sort the hand into seperate arrayLists defined by suits.", "//if the top value is an ace, use the method below", "//if the top value is an ace, use the method below", "//if the top value is an ace, use the method below", "//if the top value is an ace, use the method below", "//if the top value is an ace, use the method below", "//has 2", "//has 3", "//has 4", "//has 5", "// players have exact same cards for flush", "// each entry represents a pair (a 4 means a pair of 4's)", "// only want to compare two highest pairs from each hand", "// if both pairs are the same, check the fifth card in each hand" ]
[ { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
20000e4d05fd5a2b4c0c69f50032af6a91ac5aa5
Moeritsen/avnav
mobac/testsrc/src/mobac/mapsources/mappacks/avnavbase/ExtendedXmlMapSource.java
[ "MIT" ]
Java
ExtendedXmlMapSource
/** * Example map source template. */
Example map source template.
[ "Example", "map", "source", "template", "." ]
public class ExtendedXmlMapSource extends AbstractHttpMapSource implements ValidationEventHandler { public ExtendedXmlMapSource() { super("LoaderMapSource", 0, 17, TileImageType.PNG, TileUpdate.None); } @Override public String getTileUrl(int zoom, int tilex, int tiley) { return null; } @Override public byte[] getTileData(int zoom, int x, int y, LoadMethod loadMethod) throws IOException, TileException, InterruptedException { InputStream is=this.getClass().getResourceAsStream("Default.png"); byte[] buffer=new byte[10000]; is.read(buffer, 0, buffer.length); return buffer; } @Override public String toString() { return "DummySource - do not use!"; } @Override //some dirty trick here - this method is called after we have been loaded public void setLoaderInfo(MapSourceLoaderInfo loaderInfo) { super.setLoaderInfo(loaderInfo); init(); loadCustomMapSources(); } private Unmarshaller unmarshaller=null; private void init() { try { Class<?>[] customMapClasses = new Class[] { CustomMapSource.class, CustomWmsMapSource.class, CustomMultiLayerMapSource.class, CustomCloudMade.class, CustomLocalTileFilesMapSource.class, CustomLocalTileZipMapSource.class, CustomLocalTileSQliteMapSource.class, ExCustomWmsMapSource.class, ExCustomMultiLayerMapSource.class , ExCustomMapSource.class}; JAXBContext context = JAXBContext.newInstance(customMapClasses); unmarshaller = context.createUnmarshaller(); unmarshaller.setEventHandler(this); } catch (JAXBException e) { throw new RuntimeException("Unable to create JAXB context for custom map sources", e); } } /** * we extend extend the features of the mapsources that mobac provides... */ private void loadCustomMapSources() { MapSourcesManager mapSourcesManager=MapSourcesManager.getInstance(); File mapSourcesDir = Settings.getInstance().getMapSourcesDirectory(); if (mapSourcesDir == null || !mapSourcesDir.isDirectory()) throw new RuntimeException("Map sources directory is unset"); File[] customMapSourceFiles = mapSourcesDir.listFiles(new FileExtFilter(".exml")); Arrays.sort(customMapSourceFiles); for (File f : customMapSourceFiles) { try { MapSource customMapSource; Object o = unmarshaller.unmarshal(f); if (o instanceof WrappedMapSource) customMapSource = ((WrappedMapSource) o).getMapSource(); else customMapSource = (MapSource) o; customMapSource.setLoaderInfo(new MapSourceLoaderInfo(LoaderType.XML, f)); if (!(customMapSource instanceof FileBasedMapSource) && customMapSource.getTileImageType() == null) log.warn("A problem occured while loading \"" + f.getName() + "\": tileType is null - some atlas formats will produce an error!"); log.trace("Custom map source loaded: " + customMapSource + " from file \"" + f.getName() + "\""); mapSourcesManager.addMapSource(customMapSource); } catch (Exception e) { log.error("failed to load custom map source \"" + f.getName() + "\": " + e.getMessage(), e); } } } public boolean handleEvent(ValidationEvent event) { ValidationEventLocator loc = event.getLocator(); String file = loc.getURL().getFile(); try { file = URLDecoder.decode(file, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } int lastSlash = file.lastIndexOf('/'); if (lastSlash > 0) file = file.substring(lastSlash + 1); String errorMsg = event.getMessage(); if (errorMsg == null) { Throwable t = event.getLinkedException(); while (t != null && errorMsg == null) { errorMsg = t.getMessage(); t = t.getCause(); } } JOptionPane .showMessageDialog(null, "<html><h3>Failed to load a custom map</h3><p><i>" + errorMsg + "</i></p><br><p>file: \"<b>" + file + "</b>\"<br>line/column: <i>" + loc.getLineNumber() + "/" + loc.getColumnNumber() + "</i></p>", "Error: custom map loading failed", JOptionPane.ERROR_MESSAGE); log.error(event.toString()); return false; } }
[ "public", "class", "ExtendedXmlMapSource", "extends", "AbstractHttpMapSource", "implements", "ValidationEventHandler", "{", "public", "ExtendedXmlMapSource", "(", ")", "{", "super", "(", "\"", "LoaderMapSource", "\"", ",", "0", ",", "17", ",", "TileImageType", ".", "PNG", ",", "TileUpdate", ".", "None", ")", ";", "}", "@", "Override", "public", "String", "getTileUrl", "(", "int", "zoom", ",", "int", "tilex", ",", "int", "tiley", ")", "{", "return", "null", ";", "}", "@", "Override", "public", "byte", "[", "]", "getTileData", "(", "int", "zoom", ",", "int", "x", ",", "int", "y", ",", "LoadMethod", "loadMethod", ")", "throws", "IOException", ",", "TileException", ",", "InterruptedException", "{", "InputStream", "is", "=", "this", ".", "getClass", "(", ")", ".", "getResourceAsStream", "(", "\"", "Default.png", "\"", ")", ";", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "10000", "]", ";", "is", ".", "read", "(", "buffer", ",", "0", ",", "buffer", ".", "length", ")", ";", "return", "buffer", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "DummySource - do not use!", "\"", ";", "}", "@", "Override", "public", "void", "setLoaderInfo", "(", "MapSourceLoaderInfo", "loaderInfo", ")", "{", "super", ".", "setLoaderInfo", "(", "loaderInfo", ")", ";", "init", "(", ")", ";", "loadCustomMapSources", "(", ")", ";", "}", "private", "Unmarshaller", "unmarshaller", "=", "null", ";", "private", "void", "init", "(", ")", "{", "try", "{", "Class", "<", "?", ">", "[", "]", "customMapClasses", "=", "new", "Class", "[", "]", "{", "CustomMapSource", ".", "class", ",", "CustomWmsMapSource", ".", "class", ",", "CustomMultiLayerMapSource", ".", "class", ",", "CustomCloudMade", ".", "class", ",", "CustomLocalTileFilesMapSource", ".", "class", ",", "CustomLocalTileZipMapSource", ".", "class", ",", "CustomLocalTileSQliteMapSource", ".", "class", ",", "ExCustomWmsMapSource", ".", "class", ",", "ExCustomMultiLayerMapSource", ".", "class", ",", "ExCustomMapSource", ".", "class", "}", ";", "JAXBContext", "context", "=", "JAXBContext", ".", "newInstance", "(", "customMapClasses", ")", ";", "unmarshaller", "=", "context", ".", "createUnmarshaller", "(", ")", ";", "unmarshaller", ".", "setEventHandler", "(", "this", ")", ";", "}", "catch", "(", "JAXBException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Unable to create JAXB context for custom map sources", "\"", ",", "e", ")", ";", "}", "}", "/**\r\n\t * we extend extend the features of the mapsources that mobac provides...\r\n\t */", "private", "void", "loadCustomMapSources", "(", ")", "{", "MapSourcesManager", "mapSourcesManager", "=", "MapSourcesManager", ".", "getInstance", "(", ")", ";", "File", "mapSourcesDir", "=", "Settings", ".", "getInstance", "(", ")", ".", "getMapSourcesDirectory", "(", ")", ";", "if", "(", "mapSourcesDir", "==", "null", "||", "!", "mapSourcesDir", ".", "isDirectory", "(", ")", ")", "throw", "new", "RuntimeException", "(", "\"", "Map sources directory is unset", "\"", ")", ";", "File", "[", "]", "customMapSourceFiles", "=", "mapSourcesDir", ".", "listFiles", "(", "new", "FileExtFilter", "(", "\"", ".exml", "\"", ")", ")", ";", "Arrays", ".", "sort", "(", "customMapSourceFiles", ")", ";", "for", "(", "File", "f", ":", "customMapSourceFiles", ")", "{", "try", "{", "MapSource", "customMapSource", ";", "Object", "o", "=", "unmarshaller", ".", "unmarshal", "(", "f", ")", ";", "if", "(", "o", "instanceof", "WrappedMapSource", ")", "customMapSource", "=", "(", "(", "WrappedMapSource", ")", "o", ")", ".", "getMapSource", "(", ")", ";", "else", "customMapSource", "=", "(", "MapSource", ")", "o", ";", "customMapSource", ".", "setLoaderInfo", "(", "new", "MapSourceLoaderInfo", "(", "LoaderType", ".", "XML", ",", "f", ")", ")", ";", "if", "(", "!", "(", "customMapSource", "instanceof", "FileBasedMapSource", ")", "&&", "customMapSource", ".", "getTileImageType", "(", ")", "==", "null", ")", "log", ".", "warn", "(", "\"", "A problem occured while loading ", "\\\"", "\"", "+", "f", ".", "getName", "(", ")", "+", "\"", "\\\"", ": tileType is null - some atlas formats will produce an error!", "\"", ")", ";", "log", ".", "trace", "(", "\"", "Custom map source loaded: ", "\"", "+", "customMapSource", "+", "\"", " from file ", "\\\"", "\"", "+", "f", ".", "getName", "(", ")", "+", "\"", "\\\"", "\"", ")", ";", "mapSourcesManager", ".", "addMapSource", "(", "customMapSource", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"", "failed to load custom map source ", "\\\"", "\"", "+", "f", ".", "getName", "(", ")", "+", "\"", "\\\"", ": ", "\"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "}", "public", "boolean", "handleEvent", "(", "ValidationEvent", "event", ")", "{", "ValidationEventLocator", "loc", "=", "event", ".", "getLocator", "(", ")", ";", "String", "file", "=", "loc", ".", "getURL", "(", ")", ".", "getFile", "(", ")", ";", "try", "{", "file", "=", "URLDecoder", ".", "decode", "(", "file", ",", "\"", "UTF-8", "\"", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "int", "lastSlash", "=", "file", ".", "lastIndexOf", "(", "'/'", ")", ";", "if", "(", "lastSlash", ">", "0", ")", "file", "=", "file", ".", "substring", "(", "lastSlash", "+", "1", ")", ";", "String", "errorMsg", "=", "event", ".", "getMessage", "(", ")", ";", "if", "(", "errorMsg", "==", "null", ")", "{", "Throwable", "t", "=", "event", ".", "getLinkedException", "(", ")", ";", "while", "(", "t", "!=", "null", "&&", "errorMsg", "==", "null", ")", "{", "errorMsg", "=", "t", ".", "getMessage", "(", ")", ";", "t", "=", "t", ".", "getCause", "(", ")", ";", "}", "}", "JOptionPane", ".", "showMessageDialog", "(", "null", ",", "\"", "<html><h3>Failed to load a custom map</h3><p><i>", "\"", "+", "errorMsg", "+", "\"", "</i></p><br><p>file: ", "\\\"", "<b>", "\"", "+", "file", "+", "\"", "</b>", "\\\"", "<br>line/column: <i>", "\"", "+", "loc", ".", "getLineNumber", "(", ")", "+", "\"", "/", "\"", "+", "loc", ".", "getColumnNumber", "(", ")", "+", "\"", "</i></p>", "\"", ",", "\"", "Error: custom map loading failed", "\"", ",", "JOptionPane", ".", "ERROR_MESSAGE", ")", ";", "log", ".", "error", "(", "event", ".", "toString", "(", ")", ")", ";", "return", "false", ";", "}", "}" ]
Example map source template.
[ "Example", "map", "source", "template", "." ]
[ "//some dirty trick here - this method is called after we have been loaded\r" ]
[ { "param": "AbstractHttpMapSource", "type": null }, { "param": "ValidationEventHandler", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractHttpMapSource", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "ValidationEventHandler", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
20026d2f8e867cbd9a93adecb0141041c4ad71f0
dts-ait/sproute-json-route-format
src/main/java/at/ac/ait/ariadne/routeformat/instruction/RoadInstruction.java
[ "CC0-1.0" ]
Java
RoadInstruction
/** * A {@link RoadInstruction} contains episodes with classic-style turn * navigations for street-based modes of transport such as walking, cycling and * driving (keep straight, turn left/right, make a u-turn). * <p> * In its minimal form it consists of a position, a {@link #getSubType()} and at * least one of {@link #getOntoStreetName()} and {@link #getOntoFormOfWay()}. * <p> * Exemplary EBNF of how this instruction can be transformed into human-readable * text and what's mandatory / optional. Elements ending with STRING are * terminal (not defined any further). * <p> * UNTIL_LANDMARK_STRING must be retrieved from the next {@link Instruction}, it * can be a classic landmark or also the type of the next instruction, e.g. * roundabout. * * <pre> * {@code * ROAD_INSTRUCTION = ROUTE_START | ROUTE_START_UNMENTIONED | ROUTE_END | STRAIGHT | TURN | U_TURN | SWITCH_SIDE_OF_ROAD; * * ROUTE_START = "Start", [LANDMARK_PART], "on", NAME_TYPE, [HEADING], [CONTINUE]; * ROUTE_START_UNMENTIONED = [LANDMARK_PART], "on", NAME_TYPE, [HEADING], [CONTINUE]; * STRAIGHT = [LANDMARK_PART], "Go straight", [CROSSING_PART], "on", NAME_TYPE, [HEADING], [CONTINUE]; * TURN = [LANDMARK_PART], "Turn", ["slight"], DIRECTION, [CROSSING_PART], "on", NAME_TYPE, [HEADING], [CONTINUE]; * U_TURN = [LANDMARK_PART], "Make a u-turn", [CROSSING_PART], "on", NAME_TYPE, [HEADING], [CONTINUE]; * SWITCH_SIDE_OF_ROAD = [LANDMARK_PART], "Switch to the", DIRECTION, "side of", NAME_TYPE, [CROSSING_PART], [HEADING], [CONTINUE]; * ROUTE_END = "You reached your destination", [LANDMARK_PART], "on", NAME_TYPE; * * NAME_TYPE = [STREET_NAME_STRING], [FORM_OF_WAY_STRING], [onto the bridge], [into the TUNNEL_STRING]; * CROSSING_PART = "over the intersection" | "at the traffic light" | ... * HEADING = "heading", COMPASS_STRING; * * CONTINUE = "and continue", [ROAD_SIDE], ["for", UNIT], [CONFIRMATION_LANDMARK_PART], [UNTIL]; (* at least one of the options *) * ROAD_SIDE = "on the", "left" | "right", "side of the road; * UNIT = [DISTANCE_STRING], [TIME_STRING]; (* at least one of the two *) * UNTIL = "until", [INTERSECTING_ROAD_STRING], [UNTIL_LANDMARK_PART]; * * LANDMARK_PART = PREPOSITION, LANDMARK_STRING; * CONFIRMATION_LANDMARK_PART = CONFIRMATION_PREPOSITION, CONFIRMATION_LANDMARK_STRING; * UNTIL_LANDMARK_PART = PREPOSITION, UNTIL_LANDMARK_STRING; * * PREPOSITION = "before" | "at" | "after"; * CONFIRMATION_PREPOSITION = "towards" | "through" | "along" | "past"; * * DIRECTION = "left" | "right"; * } * </pre> * * @author AIT Austrian Institute of Technology GmbH */
A RoadInstruction contains episodes with classic-style turn navigations for street-based modes of transport such as walking, cycling and driving (keep straight, turn left/right, make a u-turn). In its minimal form it consists of a position, a #getSubType() and at least one of #getOntoStreetName() and #getOntoFormOfWay(). Exemplary EBNF of how this instruction can be transformed into human-readable text and what's mandatory / optional. Elements ending with STRING are terminal (not defined any further). UNTIL_LANDMARK_STRING must be retrieved from the next Instruction, it can be a classic landmark or also the type of the next instruction, e.g. roundabout. DIRECTION = "left" | "right"; } @author AIT Austrian Institute of Technology GmbH
[ "A", "RoadInstruction", "contains", "episodes", "with", "classic", "-", "style", "turn", "navigations", "for", "street", "-", "based", "modes", "of", "transport", "such", "as", "walking", "cycling", "and", "driving", "(", "keep", "straight", "turn", "left", "/", "right", "make", "a", "u", "-", "turn", ")", ".", "In", "its", "minimal", "form", "it", "consists", "of", "a", "position", "a", "#getSubType", "()", "and", "at", "least", "one", "of", "#getOntoStreetName", "()", "and", "#getOntoFormOfWay", "()", ".", "Exemplary", "EBNF", "of", "how", "this", "instruction", "can", "be", "transformed", "into", "human", "-", "readable", "text", "and", "what", "'", "s", "mandatory", "/", "optional", ".", "Elements", "ending", "with", "STRING", "are", "terminal", "(", "not", "defined", "any", "further", ")", ".", "UNTIL_LANDMARK_STRING", "must", "be", "retrieved", "from", "the", "next", "Instruction", "it", "can", "be", "a", "classic", "landmark", "or", "also", "the", "type", "of", "the", "next", "instruction", "e", ".", "g", ".", "roundabout", ".", "DIRECTION", "=", "\"", "left", "\"", "|", "\"", "right", "\"", ";", "}", "@author", "AIT", "Austrian", "Institute", "of", "Technology", "GmbH" ]
@JsonInclude(Include.NON_ABSENT) public class RoadInstruction extends Instruction<RoadInstruction> { public enum SubType { ROUTE_START, /** * This instruction is the first in a route, but the instruction should * not mention this explicitly. A use case for this type is e.g. * rerouting: in the background a new route is calculated but from the * perspective of the user this is not a route start */ ROUTE_START_UNMENTIONED, ROUTE_END, STRAIGHT, TURN, U_TURN, /** * Instruction for switching the side of a road - typically one and the * same - and continuing in the <b>same</b> direction. The change can * happen at a junction or on the open road. Typically relevant for foot * and bicycle traffic using zebra crossings or bicycle crossings, but * it is also possible that this is just a recommended place to cross * the road (without any marked crossing). */ SWITCH_SIDE_OF_ROAD } private SubType subType; private Optional<GeneralizedModeOfTransportType> modeOfTransport = Optional.empty(); private Optional<TurnDirection> turnDirection = Optional.empty(); private Optional<CompassDirection> compassDirection = Optional.empty(); private Optional<Boolean> roadChange = Optional.empty(); private Optional<String> ontoStreetName = Optional.empty(); private Optional<FormOfWay> ontoFormOfWay = Optional.empty(); private Optional<Boolean> enterBridge = Optional.empty(); private Optional<Tunnel> enterTunnel = Optional.empty(); private Optional<Boolean> ontoRightSideOfRoad = Optional.empty(); private Optional<RoadCrossing> crossing = Optional.empty(); private Optional<Integer> continueMeters = Optional.empty(), continueSeconds = Optional.empty(); private Optional<String> continueUntilIntersectingStreetName = Optional.empty(); private Optional<Landmark> landmark = Optional.empty(), confirmationLandmark = Optional.empty(); // -- getters @JsonProperty(required = true) public SubType getSubType() { return subType; } /** * @return the mode of transport for the turn (walk left, cycle left,..) */ public Optional<GeneralizedModeOfTransportType> getModeOfTransport() { return modeOfTransport; } /** * @return the turn direction relative to the direction until this point */ public Optional<TurnDirection> getTurnDirection() { return turnDirection; } /** * @return the heading after this point */ public Optional<CompassDirection> getCompassDirection() { return compassDirection; } /** @return <code>true</code> if the road name or type has changed */ public Optional<Boolean> getRoadChange() { return roadChange; } public Optional<String> getOntoStreetName() { return ontoStreetName; } public Optional<FormOfWay> getOntoFormOfWay() { return ontoFormOfWay; } /** * @return information if this instruction marks the entrance to a bridge */ public Optional<Boolean> getEnterBridge() { return enterBridge; } /** * @return information if this instruction marks the entrance to a tunnal * (and which kind of tunnel) */ public Optional<Tunnel> getEnterTunnel() { return enterTunnel; } /** * Defines the side of the road where the route continues. This is mostly * relevant for pedestrians and maybe also for cyclists (e.g. when * bidirectional cycle paths run along a road on both sides). For other * modes of transport an empty Optional shall be returned. * * @return <code>true</code> for the right side, <code>false</code> for the * left side of the road (in moving direction), empty if unknown or * not relevant */ public Optional<Boolean> getOntoRightSideOfRoad() { return ontoRightSideOfRoad; } /** * @return a {@link RoadCrossing} in case the instruction starts with a road * crossing */ public Optional<RoadCrossing> getCrossing() { return crossing; } public Optional<Integer> getContinueMeters() { return continueMeters; } public Optional<Integer> getContinueSeconds() { return continueSeconds; } /** * @return the name of an intersecting road at the end of the current * instruction, i.e. the place where the next instruction is */ public Optional<String> getContinueUntilIntersectingStreetName() { return continueUntilIntersectingStreetName; } /** * @return the landmark at begin of the instruction, i.e. at the turn, or at * the begin (for {@link SubType#ROUTE_START}) or at the end (for * {@link SubType#ROUTE_END}) of the route. At the same time this * landmark is the continue-landmark for the previous instruction, * i.e. the landmark after {@link #getContinueMeters()}. */ public Optional<Landmark> getLandmark() { return landmark; } /** * @return a landmark between this and the next instruction (or a global * landmark in the general direction after this instruction) that * helps users to stay on track */ public Optional<Landmark> getConfirmationLandmark() { return confirmationLandmark; } // -- setters public RoadInstruction setSubType(SubType subType) { this.subType = subType; return this; } public RoadInstruction setModeOfTransport(GeneralizedModeOfTransportType modeOfTransport) { this.modeOfTransport = Optional.ofNullable(modeOfTransport); return this; } public RoadInstruction setTurnDirection(TurnDirection turnDirection) { this.turnDirection = Optional.ofNullable(turnDirection); return this; } public RoadInstruction setCompassDirection(CompassDirection compassDirection) { this.compassDirection = Optional.ofNullable(compassDirection); return this; } public RoadInstruction setRoadChange(Boolean roadChange) { this.roadChange = Optional.ofNullable(roadChange); return this; } public RoadInstruction setOntoStreetName(String ontoStreetName) { this.ontoStreetName = Optional.ofNullable(ontoStreetName); return this; } public RoadInstruction setOntoFormOfWay(FormOfWay ontoFormOfWay) { this.ontoFormOfWay = Optional.ofNullable(ontoFormOfWay); return this; } public RoadInstruction setEnterBridge(Boolean enterBridge) { this.enterBridge = Optional.ofNullable(enterBridge); return this; } public RoadInstruction setEnterTunnel(Tunnel enterTunnel) { this.enterTunnel = Optional.ofNullable(enterTunnel); return this; } public RoadInstruction setOntoRightSideOfRoad(Boolean ontoRightSideOfRoad) { this.ontoRightSideOfRoad = Optional.ofNullable(ontoRightSideOfRoad); return this; } public RoadInstruction setCrossing(RoadCrossing crossing) { this.crossing = Optional.ofNullable(crossing); return this; } public RoadInstruction setContinueMeters(Integer continueMeters) { this.continueMeters = Optional.ofNullable(continueMeters); return this; } public RoadInstruction setContinueSeconds(Integer continueSeconds) { this.continueSeconds = Optional.ofNullable(continueSeconds); return this; } public RoadInstruction setContinueUntilIntersectingStreetName(String continueUntilIntersectingStreetName) { this.continueUntilIntersectingStreetName = Optional.ofNullable(continueUntilIntersectingStreetName); return this; } /** * @param landmark * the landmark at the start point, end point, or decision point */ public RoadInstruction setLandmark(Landmark landmark) { this.landmark = Optional.ofNullable(landmark); return this; } public RoadInstruction setConfirmationLandmark(Landmark confirmationLandmark) { this.confirmationLandmark = Optional.ofNullable(confirmationLandmark); return this; } // -- /** * either street name or form of way must be present */ public static RoadInstruction createMinimalRouteStart(GeoJSONCoordinate position, Optional<String> ontoStreetName, Optional<FormOfWay> ontoFormOfWay) { return new RoadInstruction().setPosition(position).setSubType(SubType.ROUTE_START) .setOntoStreetName(ontoStreetName.orElse(null)).setOntoFormOfWay(ontoFormOfWay.orElse(null)); } /** * either street name or form of way must be present */ public static RoadInstruction createMinimalOnRoute(GeoJSONCoordinate position, TurnDirection turnDirection, Optional<String> ontoStreetName, Optional<FormOfWay> ontoFormOfWay) { return new RoadInstruction().setPosition(position).setSubType(getSubType(turnDirection)) .setTurnDirection(turnDirection).setOntoStreetName(ontoStreetName.orElse(null)) .setOntoFormOfWay(ontoFormOfWay.orElse(null)); } /** * either street name or form of way (of the destination) must be present */ public static RoadInstruction createMinimalRouteEnd(GeoJSONCoordinate position, Optional<String> onStreetName, Optional<FormOfWay> onFormOfWay) { return new RoadInstruction().setPosition(position).setSubType(SubType.ROUTE_END) .setOntoStreetName(onStreetName.orElse(null)).setOntoFormOfWay(onFormOfWay.orElse(null)); } private static SubType getSubType(TurnDirection turnDirection) { if (turnDirection == TurnDirection.U_TURN) return SubType.U_TURN; else if (turnDirection == TurnDirection.STRAIGHT) return SubType.STRAIGHT; else return SubType.TURN; } @Override public void validate() { super.validate(); Preconditions.checkArgument(subType != null, "subType is mandatory but missing"); Preconditions.checkArgument(ontoStreetName.isPresent() || ontoFormOfWay.isPresent(), "at least one onto-type is required"); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((compassDirection == null) ? 0 : compassDirection.hashCode()); result = prime * result + ((confirmationLandmark == null) ? 0 : confirmationLandmark.hashCode()); result = prime * result + ((continueMeters == null) ? 0 : continueMeters.hashCode()); result = prime * result + ((continueSeconds == null) ? 0 : continueSeconds.hashCode()); result = prime * result + ((continueUntilIntersectingStreetName == null) ? 0 : continueUntilIntersectingStreetName.hashCode()); result = prime * result + ((crossing == null) ? 0 : crossing.hashCode()); result = prime * result + ((enterBridge == null) ? 0 : enterBridge.hashCode()); result = prime * result + ((enterTunnel == null) ? 0 : enterTunnel.hashCode()); result = prime * result + ((landmark == null) ? 0 : landmark.hashCode()); result = prime * result + ((modeOfTransport == null) ? 0 : modeOfTransport.hashCode()); result = prime * result + ((ontoFormOfWay == null) ? 0 : ontoFormOfWay.hashCode()); result = prime * result + ((ontoRightSideOfRoad == null) ? 0 : ontoRightSideOfRoad.hashCode()); result = prime * result + ((ontoStreetName == null) ? 0 : ontoStreetName.hashCode()); result = prime * result + ((roadChange == null) ? 0 : roadChange.hashCode()); result = prime * result + ((subType == null) ? 0 : subType.hashCode()); result = prime * result + ((turnDirection == null) ? 0 : turnDirection.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; RoadInstruction other = (RoadInstruction) obj; if (compassDirection == null) { if (other.compassDirection != null) return false; } else if (!compassDirection.equals(other.compassDirection)) return false; if (confirmationLandmark == null) { if (other.confirmationLandmark != null) return false; } else if (!confirmationLandmark.equals(other.confirmationLandmark)) return false; if (continueMeters == null) { if (other.continueMeters != null) return false; } else if (!continueMeters.equals(other.continueMeters)) return false; if (continueSeconds == null) { if (other.continueSeconds != null) return false; } else if (!continueSeconds.equals(other.continueSeconds)) return false; if (continueUntilIntersectingStreetName == null) { if (other.continueUntilIntersectingStreetName != null) return false; } else if (!continueUntilIntersectingStreetName.equals(other.continueUntilIntersectingStreetName)) return false; if (crossing == null) { if (other.crossing != null) return false; } else if (!crossing.equals(other.crossing)) return false; if (enterBridge == null) { if (other.enterBridge != null) return false; } else if (!enterBridge.equals(other.enterBridge)) return false; if (enterTunnel == null) { if (other.enterTunnel != null) return false; } else if (!enterTunnel.equals(other.enterTunnel)) return false; if (landmark == null) { if (other.landmark != null) return false; } else if (!landmark.equals(other.landmark)) return false; if (modeOfTransport == null) { if (other.modeOfTransport != null) return false; } else if (!modeOfTransport.equals(other.modeOfTransport)) return false; if (ontoFormOfWay == null) { if (other.ontoFormOfWay != null) return false; } else if (!ontoFormOfWay.equals(other.ontoFormOfWay)) return false; if (ontoRightSideOfRoad == null) { if (other.ontoRightSideOfRoad != null) return false; } else if (!ontoRightSideOfRoad.equals(other.ontoRightSideOfRoad)) return false; if (ontoStreetName == null) { if (other.ontoStreetName != null) return false; } else if (!ontoStreetName.equals(other.ontoStreetName)) return false; if (roadChange == null) { if (other.roadChange != null) return false; } else if (!roadChange.equals(other.roadChange)) return false; if (subType != other.subType) return false; if (turnDirection == null) { if (other.turnDirection != null) return false; } else if (!turnDirection.equals(other.turnDirection)) return false; return true; } @Override public String toString() { return super.toString() + " -> RoadInstruction [subType=" + subType + ", modeOfTransport=" + modeOfTransport + ", turnDirection=" + turnDirection + ", compassDirection=" + compassDirection + ", roadChange=" + roadChange + ", ontoStreetName=" + ontoStreetName + ", ontoFormOfWay=" + ontoFormOfWay + ", enterBridge=" + enterBridge + ", enterTunnel=" + enterTunnel + ", ontoRightSideOfRoad=" + ontoRightSideOfRoad + ", continueMeters=" + continueMeters + ", continueSeconds=" + continueSeconds + ", continueUntilIntersectingStreetName=" + continueUntilIntersectingStreetName + ", landmark=" + landmark + ", confirmationLandmark=" + confirmationLandmark + "]"; } }
[ "@", "JsonInclude", "(", "Include", ".", "NON_ABSENT", ")", "public", "class", "RoadInstruction", "extends", "Instruction", "<", "RoadInstruction", ">", "{", "public", "enum", "SubType", "{", "ROUTE_START", ",", "/**\n * This instruction is the first in a route, but the instruction should\n * not mention this explicitly. A use case for this type is e.g.\n * rerouting: in the background a new route is calculated but from the\n * perspective of the user this is not a route start\n */", "ROUTE_START_UNMENTIONED", ",", "ROUTE_END", ",", "STRAIGHT", ",", "TURN", ",", "U_TURN", ",", "/**\n * Instruction for switching the side of a road - typically one and the\n * same - and continuing in the <b>same</b> direction. The change can\n * happen at a junction or on the open road. Typically relevant for foot\n * and bicycle traffic using zebra crossings or bicycle crossings, but\n * it is also possible that this is just a recommended place to cross\n * the road (without any marked crossing).\n */", "SWITCH_SIDE_OF_ROAD", "}", "private", "SubType", "subType", ";", "private", "Optional", "<", "GeneralizedModeOfTransportType", ">", "modeOfTransport", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "TurnDirection", ">", "turnDirection", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "CompassDirection", ">", "compassDirection", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "Boolean", ">", "roadChange", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "String", ">", "ontoStreetName", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "FormOfWay", ">", "ontoFormOfWay", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "Boolean", ">", "enterBridge", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "Tunnel", ">", "enterTunnel", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "Boolean", ">", "ontoRightSideOfRoad", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "RoadCrossing", ">", "crossing", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "Integer", ">", "continueMeters", "=", "Optional", ".", "empty", "(", ")", ",", "continueSeconds", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "String", ">", "continueUntilIntersectingStreetName", "=", "Optional", ".", "empty", "(", ")", ";", "private", "Optional", "<", "Landmark", ">", "landmark", "=", "Optional", ".", "empty", "(", ")", ",", "confirmationLandmark", "=", "Optional", ".", "empty", "(", ")", ";", "@", "JsonProperty", "(", "required", "=", "true", ")", "public", "SubType", "getSubType", "(", ")", "{", "return", "subType", ";", "}", "/**\n * @return the mode of transport for the turn (walk left, cycle left,..)\n */", "public", "Optional", "<", "GeneralizedModeOfTransportType", ">", "getModeOfTransport", "(", ")", "{", "return", "modeOfTransport", ";", "}", "/**\n * @return the turn direction relative to the direction until this point\n */", "public", "Optional", "<", "TurnDirection", ">", "getTurnDirection", "(", ")", "{", "return", "turnDirection", ";", "}", "/**\n * @return the heading after this point\n */", "public", "Optional", "<", "CompassDirection", ">", "getCompassDirection", "(", ")", "{", "return", "compassDirection", ";", "}", "/** @return <code>true</code> if the road name or type has changed */", "public", "Optional", "<", "Boolean", ">", "getRoadChange", "(", ")", "{", "return", "roadChange", ";", "}", "public", "Optional", "<", "String", ">", "getOntoStreetName", "(", ")", "{", "return", "ontoStreetName", ";", "}", "public", "Optional", "<", "FormOfWay", ">", "getOntoFormOfWay", "(", ")", "{", "return", "ontoFormOfWay", ";", "}", "/**\n * @return information if this instruction marks the entrance to a bridge\n */", "public", "Optional", "<", "Boolean", ">", "getEnterBridge", "(", ")", "{", "return", "enterBridge", ";", "}", "/**\n * @return information if this instruction marks the entrance to a tunnal\n * (and which kind of tunnel)\n */", "public", "Optional", "<", "Tunnel", ">", "getEnterTunnel", "(", ")", "{", "return", "enterTunnel", ";", "}", "/**\n * Defines the side of the road where the route continues. This is mostly\n * relevant for pedestrians and maybe also for cyclists (e.g. when\n * bidirectional cycle paths run along a road on both sides). For other\n * modes of transport an empty Optional shall be returned.\n * \n * @return <code>true</code> for the right side, <code>false</code> for the\n * left side of the road (in moving direction), empty if unknown or\n * not relevant\n */", "public", "Optional", "<", "Boolean", ">", "getOntoRightSideOfRoad", "(", ")", "{", "return", "ontoRightSideOfRoad", ";", "}", "/**\n * @return a {@link RoadCrossing} in case the instruction starts with a road\n * crossing\n */", "public", "Optional", "<", "RoadCrossing", ">", "getCrossing", "(", ")", "{", "return", "crossing", ";", "}", "public", "Optional", "<", "Integer", ">", "getContinueMeters", "(", ")", "{", "return", "continueMeters", ";", "}", "public", "Optional", "<", "Integer", ">", "getContinueSeconds", "(", ")", "{", "return", "continueSeconds", ";", "}", "/**\n * @return the name of an intersecting road at the end of the current\n * instruction, i.e. the place where the next instruction is\n */", "public", "Optional", "<", "String", ">", "getContinueUntilIntersectingStreetName", "(", ")", "{", "return", "continueUntilIntersectingStreetName", ";", "}", "/**\n * @return the landmark at begin of the instruction, i.e. at the turn, or at\n * the begin (for {@link SubType#ROUTE_START}) or at the end (for\n * {@link SubType#ROUTE_END}) of the route. At the same time this\n * landmark is the continue-landmark for the previous instruction,\n * i.e. the landmark after {@link #getContinueMeters()}.\n */", "public", "Optional", "<", "Landmark", ">", "getLandmark", "(", ")", "{", "return", "landmark", ";", "}", "/**\n * @return a landmark between this and the next instruction (or a global\n * landmark in the general direction after this instruction) that\n * helps users to stay on track\n */", "public", "Optional", "<", "Landmark", ">", "getConfirmationLandmark", "(", ")", "{", "return", "confirmationLandmark", ";", "}", "public", "RoadInstruction", "setSubType", "(", "SubType", "subType", ")", "{", "this", ".", "subType", "=", "subType", ";", "return", "this", ";", "}", "public", "RoadInstruction", "setModeOfTransport", "(", "GeneralizedModeOfTransportType", "modeOfTransport", ")", "{", "this", ".", "modeOfTransport", "=", "Optional", ".", "ofNullable", "(", "modeOfTransport", ")", ";", "return", "this", ";", "}", "public", "RoadInstruction", "setTurnDirection", "(", "TurnDirection", "turnDirection", ")", "{", "this", ".", "turnDirection", "=", "Optional", ".", "ofNullable", "(", "turnDirection", ")", ";", "return", "this", ";", "}", "public", "RoadInstruction", "setCompassDirection", "(", "CompassDirection", "compassDirection", ")", "{", "this", ".", "compassDirection", "=", "Optional", ".", "ofNullable", "(", "compassDirection", ")", ";", "return", "this", ";", "}", "public", "RoadInstruction", "setRoadChange", "(", "Boolean", "roadChange", ")", "{", "this", ".", "roadChange", "=", "Optional", ".", "ofNullable", "(", "roadChange", ")", ";", "return", "this", ";", "}", "public", "RoadInstruction", "setOntoStreetName", "(", "String", "ontoStreetName", ")", "{", "this", ".", "ontoStreetName", "=", "Optional", ".", "ofNullable", "(", "ontoStreetName", ")", ";", "return", "this", ";", "}", "public", "RoadInstruction", "setOntoFormOfWay", "(", "FormOfWay", "ontoFormOfWay", ")", "{", "this", ".", "ontoFormOfWay", "=", "Optional", ".", "ofNullable", "(", "ontoFormOfWay", ")", ";", "return", "this", ";", "}", "public", "RoadInstruction", "setEnterBridge", "(", "Boolean", "enterBridge", ")", "{", "this", ".", "enterBridge", "=", "Optional", ".", "ofNullable", "(", "enterBridge", ")", ";", "return", "this", ";", "}", "public", "RoadInstruction", "setEnterTunnel", "(", "Tunnel", "enterTunnel", ")", "{", "this", ".", "enterTunnel", "=", "Optional", ".", "ofNullable", "(", "enterTunnel", ")", ";", "return", "this", ";", "}", "public", "RoadInstruction", "setOntoRightSideOfRoad", "(", "Boolean", "ontoRightSideOfRoad", ")", "{", "this", ".", "ontoRightSideOfRoad", "=", "Optional", ".", "ofNullable", "(", "ontoRightSideOfRoad", ")", ";", "return", "this", ";", "}", "public", "RoadInstruction", "setCrossing", "(", "RoadCrossing", "crossing", ")", "{", "this", ".", "crossing", "=", "Optional", ".", "ofNullable", "(", "crossing", ")", ";", "return", "this", ";", "}", "public", "RoadInstruction", "setContinueMeters", "(", "Integer", "continueMeters", ")", "{", "this", ".", "continueMeters", "=", "Optional", ".", "ofNullable", "(", "continueMeters", ")", ";", "return", "this", ";", "}", "public", "RoadInstruction", "setContinueSeconds", "(", "Integer", "continueSeconds", ")", "{", "this", ".", "continueSeconds", "=", "Optional", ".", "ofNullable", "(", "continueSeconds", ")", ";", "return", "this", ";", "}", "public", "RoadInstruction", "setContinueUntilIntersectingStreetName", "(", "String", "continueUntilIntersectingStreetName", ")", "{", "this", ".", "continueUntilIntersectingStreetName", "=", "Optional", ".", "ofNullable", "(", "continueUntilIntersectingStreetName", ")", ";", "return", "this", ";", "}", "/**\n * @param landmark\n * the landmark at the start point, end point, or decision point\n */", "public", "RoadInstruction", "setLandmark", "(", "Landmark", "landmark", ")", "{", "this", ".", "landmark", "=", "Optional", ".", "ofNullable", "(", "landmark", ")", ";", "return", "this", ";", "}", "public", "RoadInstruction", "setConfirmationLandmark", "(", "Landmark", "confirmationLandmark", ")", "{", "this", ".", "confirmationLandmark", "=", "Optional", ".", "ofNullable", "(", "confirmationLandmark", ")", ";", "return", "this", ";", "}", "/**\n * either street name or form of way must be present\n */", "public", "static", "RoadInstruction", "createMinimalRouteStart", "(", "GeoJSONCoordinate", "position", ",", "Optional", "<", "String", ">", "ontoStreetName", ",", "Optional", "<", "FormOfWay", ">", "ontoFormOfWay", ")", "{", "return", "new", "RoadInstruction", "(", ")", ".", "setPosition", "(", "position", ")", ".", "setSubType", "(", "SubType", ".", "ROUTE_START", ")", ".", "setOntoStreetName", "(", "ontoStreetName", ".", "orElse", "(", "null", ")", ")", ".", "setOntoFormOfWay", "(", "ontoFormOfWay", ".", "orElse", "(", "null", ")", ")", ";", "}", "/**\n * either street name or form of way must be present\n */", "public", "static", "RoadInstruction", "createMinimalOnRoute", "(", "GeoJSONCoordinate", "position", ",", "TurnDirection", "turnDirection", ",", "Optional", "<", "String", ">", "ontoStreetName", ",", "Optional", "<", "FormOfWay", ">", "ontoFormOfWay", ")", "{", "return", "new", "RoadInstruction", "(", ")", ".", "setPosition", "(", "position", ")", ".", "setSubType", "(", "getSubType", "(", "turnDirection", ")", ")", ".", "setTurnDirection", "(", "turnDirection", ")", ".", "setOntoStreetName", "(", "ontoStreetName", ".", "orElse", "(", "null", ")", ")", ".", "setOntoFormOfWay", "(", "ontoFormOfWay", ".", "orElse", "(", "null", ")", ")", ";", "}", "/**\n * either street name or form of way (of the destination) must be present\n */", "public", "static", "RoadInstruction", "createMinimalRouteEnd", "(", "GeoJSONCoordinate", "position", ",", "Optional", "<", "String", ">", "onStreetName", ",", "Optional", "<", "FormOfWay", ">", "onFormOfWay", ")", "{", "return", "new", "RoadInstruction", "(", ")", ".", "setPosition", "(", "position", ")", ".", "setSubType", "(", "SubType", ".", "ROUTE_END", ")", ".", "setOntoStreetName", "(", "onStreetName", ".", "orElse", "(", "null", ")", ")", ".", "setOntoFormOfWay", "(", "onFormOfWay", ".", "orElse", "(", "null", ")", ")", ";", "}", "private", "static", "SubType", "getSubType", "(", "TurnDirection", "turnDirection", ")", "{", "if", "(", "turnDirection", "==", "TurnDirection", ".", "U_TURN", ")", "return", "SubType", ".", "U_TURN", ";", "else", "if", "(", "turnDirection", "==", "TurnDirection", ".", "STRAIGHT", ")", "return", "SubType", ".", "STRAIGHT", ";", "else", "return", "SubType", ".", "TURN", ";", "}", "@", "Override", "public", "void", "validate", "(", ")", "{", "super", ".", "validate", "(", ")", ";", "Preconditions", ".", "checkArgument", "(", "subType", "!=", "null", ",", "\"", "subType is mandatory but missing", "\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "ontoStreetName", ".", "isPresent", "(", ")", "||", "ontoFormOfWay", ".", "isPresent", "(", ")", ",", "\"", "at least one onto-type is required", "\"", ")", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "final", "int", "prime", "=", "31", ";", "int", "result", "=", "super", ".", "hashCode", "(", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "compassDirection", "==", "null", ")", "?", "0", ":", "compassDirection", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "confirmationLandmark", "==", "null", ")", "?", "0", ":", "confirmationLandmark", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "continueMeters", "==", "null", ")", "?", "0", ":", "continueMeters", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "continueSeconds", "==", "null", ")", "?", "0", ":", "continueSeconds", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "continueUntilIntersectingStreetName", "==", "null", ")", "?", "0", ":", "continueUntilIntersectingStreetName", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "crossing", "==", "null", ")", "?", "0", ":", "crossing", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "enterBridge", "==", "null", ")", "?", "0", ":", "enterBridge", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "enterTunnel", "==", "null", ")", "?", "0", ":", "enterTunnel", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "landmark", "==", "null", ")", "?", "0", ":", "landmark", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "modeOfTransport", "==", "null", ")", "?", "0", ":", "modeOfTransport", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "ontoFormOfWay", "==", "null", ")", "?", "0", ":", "ontoFormOfWay", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "ontoRightSideOfRoad", "==", "null", ")", "?", "0", ":", "ontoRightSideOfRoad", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "ontoStreetName", "==", "null", ")", "?", "0", ":", "ontoStreetName", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "roadChange", "==", "null", ")", "?", "0", ":", "roadChange", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "subType", "==", "null", ")", "?", "0", ":", "subType", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "turnDirection", "==", "null", ")", "?", "0", ":", "turnDirection", ".", "hashCode", "(", ")", ")", ";", "return", "result", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "this", "==", "obj", ")", "return", "true", ";", "if", "(", "!", "super", ".", "equals", "(", "obj", ")", ")", "return", "false", ";", "if", "(", "getClass", "(", ")", "!=", "obj", ".", "getClass", "(", ")", ")", "return", "false", ";", "RoadInstruction", "other", "=", "(", "RoadInstruction", ")", "obj", ";", "if", "(", "compassDirection", "==", "null", ")", "{", "if", "(", "other", ".", "compassDirection", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "compassDirection", ".", "equals", "(", "other", ".", "compassDirection", ")", ")", "return", "false", ";", "if", "(", "confirmationLandmark", "==", "null", ")", "{", "if", "(", "other", ".", "confirmationLandmark", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "confirmationLandmark", ".", "equals", "(", "other", ".", "confirmationLandmark", ")", ")", "return", "false", ";", "if", "(", "continueMeters", "==", "null", ")", "{", "if", "(", "other", ".", "continueMeters", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "continueMeters", ".", "equals", "(", "other", ".", "continueMeters", ")", ")", "return", "false", ";", "if", "(", "continueSeconds", "==", "null", ")", "{", "if", "(", "other", ".", "continueSeconds", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "continueSeconds", ".", "equals", "(", "other", ".", "continueSeconds", ")", ")", "return", "false", ";", "if", "(", "continueUntilIntersectingStreetName", "==", "null", ")", "{", "if", "(", "other", ".", "continueUntilIntersectingStreetName", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "continueUntilIntersectingStreetName", ".", "equals", "(", "other", ".", "continueUntilIntersectingStreetName", ")", ")", "return", "false", ";", "if", "(", "crossing", "==", "null", ")", "{", "if", "(", "other", ".", "crossing", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "crossing", ".", "equals", "(", "other", ".", "crossing", ")", ")", "return", "false", ";", "if", "(", "enterBridge", "==", "null", ")", "{", "if", "(", "other", ".", "enterBridge", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "enterBridge", ".", "equals", "(", "other", ".", "enterBridge", ")", ")", "return", "false", ";", "if", "(", "enterTunnel", "==", "null", ")", "{", "if", "(", "other", ".", "enterTunnel", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "enterTunnel", ".", "equals", "(", "other", ".", "enterTunnel", ")", ")", "return", "false", ";", "if", "(", "landmark", "==", "null", ")", "{", "if", "(", "other", ".", "landmark", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "landmark", ".", "equals", "(", "other", ".", "landmark", ")", ")", "return", "false", ";", "if", "(", "modeOfTransport", "==", "null", ")", "{", "if", "(", "other", ".", "modeOfTransport", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "modeOfTransport", ".", "equals", "(", "other", ".", "modeOfTransport", ")", ")", "return", "false", ";", "if", "(", "ontoFormOfWay", "==", "null", ")", "{", "if", "(", "other", ".", "ontoFormOfWay", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "ontoFormOfWay", ".", "equals", "(", "other", ".", "ontoFormOfWay", ")", ")", "return", "false", ";", "if", "(", "ontoRightSideOfRoad", "==", "null", ")", "{", "if", "(", "other", ".", "ontoRightSideOfRoad", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "ontoRightSideOfRoad", ".", "equals", "(", "other", ".", "ontoRightSideOfRoad", ")", ")", "return", "false", ";", "if", "(", "ontoStreetName", "==", "null", ")", "{", "if", "(", "other", ".", "ontoStreetName", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "ontoStreetName", ".", "equals", "(", "other", ".", "ontoStreetName", ")", ")", "return", "false", ";", "if", "(", "roadChange", "==", "null", ")", "{", "if", "(", "other", ".", "roadChange", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "roadChange", ".", "equals", "(", "other", ".", "roadChange", ")", ")", "return", "false", ";", "if", "(", "subType", "!=", "other", ".", "subType", ")", "return", "false", ";", "if", "(", "turnDirection", "==", "null", ")", "{", "if", "(", "other", ".", "turnDirection", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "turnDirection", ".", "equals", "(", "other", ".", "turnDirection", ")", ")", "return", "false", ";", "return", "true", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "super", ".", "toString", "(", ")", "+", "\"", " -> RoadInstruction [subType=", "\"", "+", "subType", "+", "\"", ", modeOfTransport=", "\"", "+", "modeOfTransport", "+", "\"", ", turnDirection=", "\"", "+", "turnDirection", "+", "\"", ", compassDirection=", "\"", "+", "compassDirection", "+", "\"", ", roadChange=", "\"", "+", "roadChange", "+", "\"", ", ontoStreetName=", "\"", "+", "ontoStreetName", "+", "\"", ", ontoFormOfWay=", "\"", "+", "ontoFormOfWay", "+", "\"", ", enterBridge=", "\"", "+", "enterBridge", "+", "\"", ", enterTunnel=", "\"", "+", "enterTunnel", "+", "\"", ", ontoRightSideOfRoad=", "\"", "+", "ontoRightSideOfRoad", "+", "\"", ", continueMeters=", "\"", "+", "continueMeters", "+", "\"", ", continueSeconds=", "\"", "+", "continueSeconds", "+", "\"", ", continueUntilIntersectingStreetName=", "\"", "+", "continueUntilIntersectingStreetName", "+", "\"", ", landmark=", "\"", "+", "landmark", "+", "\"", ", confirmationLandmark=", "\"", "+", "confirmationLandmark", "+", "\"", "]", "\"", ";", "}", "}" ]
A {@link RoadInstruction} contains episodes with classic-style turn navigations for street-based modes of transport such as walking, cycling and driving (keep straight, turn left/right, make a u-turn).
[ "A", "{", "@link", "RoadInstruction", "}", "contains", "episodes", "with", "classic", "-", "style", "turn", "navigations", "for", "street", "-", "based", "modes", "of", "transport", "such", "as", "walking", "cycling", "and", "driving", "(", "keep", "straight", "turn", "left", "/", "right", "make", "a", "u", "-", "turn", ")", "." ]
[ "// -- getters", "// -- setters", "// --" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
200371a192e55a23b98f52d63912a23b167d4b01
PlayBoyFly/ribbon
ribbon-core/src/main/java/com/netflix/client/LoadBalancerContext.java
[ "Apache-2.0" ]
Java
LoadBalancerContext
/** * A class contains APIs intended to be used be load balancing client which is subclass of this class. * * @author awang * * @param <T> Type of the request * @param <S> Type of the response */
A class contains APIs intended to be used be load balancing client which is subclass of this class. @author awang @param Type of the request @param Type of the response
[ "A", "class", "contains", "APIs", "intended", "to", "be", "used", "be", "load", "balancing", "client", "which", "is", "subclass", "of", "this", "class", ".", "@author", "awang", "@param", "Type", "of", "the", "request", "@param", "Type", "of", "the", "response" ]
public abstract class LoadBalancerContext<T extends ClientRequest, S extends IResponse> implements IClientConfigAware { private static final Logger logger = LoggerFactory.getLogger(LoadBalancerContext.class); protected String clientName = "default"; protected String vipAddresses; protected int maxAutoRetriesNextServer = DefaultClientConfigImpl.DEFAULT_MAX_AUTO_RETRIES_NEXT_SERVER; protected int maxAutoRetries = DefaultClientConfigImpl.DEFAULT_MAX_AUTO_RETRIES; protected LoadBalancerErrorHandler<? super T, ? super S> errorHandler = new DefaultLoadBalancerErrorHandler<ClientRequest, IResponse>(); boolean okToRetryOnAllOperations = DefaultClientConfigImpl.DEFAULT_OK_TO_RETRY_ON_ALL_OPERATIONS.booleanValue(); private ILoadBalancer lb; private volatile Timer tracer; public LoadBalancerContext() { } /** * Delegate to {@link #initWithNiwsConfig(IClientConfig)} * @param clientConfig */ public LoadBalancerContext(IClientConfig clientConfig) { initWithNiwsConfig(clientConfig); } /** * Set necessary parameters from client configuration and register with Servo monitors. */ @Override public void initWithNiwsConfig(IClientConfig clientConfig) { if (clientConfig == null) { return; } clientName = clientConfig.getClientName(); if (clientName == null) { clientName = "default"; } vipAddresses = clientConfig.resolveDeploymentContextbasedVipAddresses(); maxAutoRetries = clientConfig.getPropertyAsInteger(CommonClientConfigKey.MaxAutoRetries, DefaultClientConfigImpl.DEFAULT_MAX_AUTO_RETRIES); maxAutoRetriesNextServer = clientConfig.getPropertyAsInteger(CommonClientConfigKey.MaxAutoRetriesNextServer,maxAutoRetriesNextServer); okToRetryOnAllOperations = clientConfig.getPropertyAsBoolean(CommonClientConfigKey.OkToRetryOnAllOperations, okToRetryOnAllOperations); tracer = getExecuteTracer(); Monitors.registerObject("Client_" + clientName, this); } protected Timer getExecuteTracer() { if (tracer == null) { synchronized(this) { if (tracer == null) { tracer = Monitors.newTimer(clientName + "_OperationTimer", TimeUnit.MILLISECONDS); } } } return tracer; } public String getClientName() { return clientName; } public ILoadBalancer getLoadBalancer() { return lb; } public void setLoadBalancer(ILoadBalancer lb) { this.lb = lb; } public int getMaxAutoRetriesNextServer() { return maxAutoRetriesNextServer; } public void setMaxAutoRetriesNextServer(int maxAutoRetriesNextServer) { this.maxAutoRetriesNextServer = maxAutoRetriesNextServer; } public int getMaxAutoRetries() { return maxAutoRetries; } public void setMaxAutoRetries(int maxAutoRetries) { this.maxAutoRetries = maxAutoRetries; } protected Throwable getDeepestCause(Throwable e) { if(e != null) { int infiniteLoopPreventionCounter = 10; while (e.getCause() != null && infiniteLoopPreventionCounter > 0) { infiniteLoopPreventionCounter--; e = e.getCause(); } } return e; } private boolean isPresentAsCause(Throwable throwableToSearchIn, Class<? extends Throwable> throwableToSearchFor) { return isPresentAsCauseHelper(throwableToSearchIn, throwableToSearchFor) != null; } static Throwable isPresentAsCauseHelper(Throwable throwableToSearchIn, Class<? extends Throwable> throwableToSearchFor) { int infiniteLoopPreventionCounter = 10; while (throwableToSearchIn != null && infiniteLoopPreventionCounter > 0) { infiniteLoopPreventionCounter--; if (throwableToSearchIn.getClass().isAssignableFrom( throwableToSearchFor)) { return throwableToSearchIn; } else { throwableToSearchIn = throwableToSearchIn.getCause(); } } return null; } /** * Test if certain exception classes exist as a cause in a Throwable */ public static boolean isPresentAsCause(Throwable throwableToSearchIn, Collection<Class<? extends Throwable>> throwableToSearchFor) { int infiniteLoopPreventionCounter = 10; while (throwableToSearchIn != null && infiniteLoopPreventionCounter > 0) { infiniteLoopPreventionCounter--; for (Class<? extends Throwable> c: throwableToSearchFor) { if (throwableToSearchIn.getClass().isAssignableFrom(c)) { return true; } } throwableToSearchIn = throwableToSearchIn.getCause(); } return false; } protected ClientException generateNIWSException(String uri, Throwable e){ ClientException niwsClientException; if (isPresentAsCause(e, java.net.SocketTimeoutException.class)) { niwsClientException = generateTimeoutNIWSException(uri, e); }else if (e.getCause() instanceof java.net.UnknownHostException){ niwsClientException = new ClientException( ClientException.ErrorType.UNKNOWN_HOST_EXCEPTION, "Unable to execute RestClient request for URI:" + uri, e); }else if (e.getCause() instanceof java.net.ConnectException){ niwsClientException = new ClientException( ClientException.ErrorType.CONNECT_EXCEPTION, "Unable to execute RestClient request for URI:" + uri, e); }else if (e.getCause() instanceof java.net.NoRouteToHostException){ niwsClientException = new ClientException( ClientException.ErrorType.NO_ROUTE_TO_HOST_EXCEPTION, "Unable to execute RestClient request for URI:" + uri, e); }else if (e instanceof ClientException){ niwsClientException = (ClientException)e; }else { niwsClientException = new ClientException( ClientException.ErrorType.GENERAL, "Unable to execute RestClient request for URI:" + uri, e); } return niwsClientException; } private boolean isPresentAsCause(Throwable throwableToSearchIn, Class<? extends Throwable> throwableToSearchFor, String messageSubStringToSearchFor) { Throwable throwableFound = isPresentAsCauseHelper(throwableToSearchIn, throwableToSearchFor); if(throwableFound != null) { return throwableFound.getMessage().contains(messageSubStringToSearchFor); } return false; } private ClientException generateTimeoutNIWSException(String uri, Throwable e){ ClientException niwsClientException; if (isPresentAsCause(e, java.net.SocketTimeoutException.class, "Read timed out")) { niwsClientException = new ClientException( ClientException.ErrorType.READ_TIMEOUT_EXCEPTION, "Unable to execute RestClient request for URI:" + uri + ":" + getDeepestCause(e).getMessage(), e); } else { niwsClientException = new ClientException( ClientException.ErrorType.SOCKET_TIMEOUT_EXCEPTION, "Unable to execute RestClient request for URI:" + uri + ":" + getDeepestCause(e).getMessage(), e); } return niwsClientException; } /** * This is called after a response is received or an exception is thrown from the client * to update related stats. */ protected void noteRequestCompletion(ServerStats stats, ClientRequest request, IResponse response, Throwable e, long responseTime) { try { if (stats != null) { stats.decrementActiveRequestsCount(); stats.incrementNumRequests(); stats.noteResponseTime(responseTime); if (response != null) { stats.clearSuccessiveConnectionFailureCount(); } } } catch (Throwable ex) { logger.error("Unexpected exception", ex); } } /** * This is usually called just before client execute a request. */ protected void noteOpenConnection(ServerStats serverStats, ClientRequest request) { if (serverStats == null) { return; } try { serverStats.incrementActiveRequestsCount(); } catch (Throwable e) { logger.info("Unable to note Server Stats:", e); } } /** * Derive scheme and port from a partial URI. For example, for HTTP based client, the URI with * only path "/" should return "http" and 80, whereas the URI constructed with scheme "https" and * path "/" should return * "https" and 443. This method is called by {@link #computeFinalUriWithLoadBalancer(ClientRequest)} * to get the complete executable URI. * */ protected Pair<String, Integer> deriveSchemeAndPortFromPartialUri(T request) { URI theUrl = request.getUri(); boolean isSecure = false; String scheme = theUrl.getScheme(); if (scheme != null) { isSecure = scheme.equalsIgnoreCase("https"); } int port = theUrl.getPort(); if (port < 0 && !isSecure){ port = 80; } else if (port < 0 && isSecure){ port = 443; } if (scheme == null){ if (isSecure) { scheme = "https"; } else { scheme = "http"; } } return new Pair<String, Integer>(scheme, port); } /** * Get the default port of the target server given the scheme of vip address if it is available. * Subclass should override it to provider protocol specific default port number if any. * * @param scheme from the vip address. null if not present. * @return 80 if scheme is http, 443 if scheme is https, -1 else. */ protected int getDefaultPortFromScheme(String scheme) { if (scheme == null) { return -1; } if (scheme.equals("http")) { return 80; } else if (scheme.equals("https")) { return 443; } else { return -1; } } /** * Derive the host and port from virtual address if virtual address is indeed contains the actual host * and port of the server. This is the final resort to compute the final URI in {@link #computeFinalUriWithLoadBalancer(ClientRequest)} * if there is no load balancer available and the request URI is incomplete. Sub classes can override this method * to be more accurate or throws ClientException if it does not want to support virtual address to be the * same as physical server address. * <p> * The virtual address is used by certain load balancers to filter the servers of the same function * to form the server pool. * */ protected Pair<String, Integer> deriveHostAndPortFromVipAddress(String vipAddress) throws URISyntaxException, ClientException { Pair<String, Integer> hostAndPort = new Pair<String, Integer>(null, -1); URI uri = new URI(vipAddress); String scheme = uri.getScheme(); if (scheme == null) { uri = new URI("http://" + vipAddress); } String host = uri.getHost(); if (host == null) { throw new ClientException("Unable to derive host/port from vip address " + vipAddress); } int port = uri.getPort(); if (port < 0) { port = getDefaultPortFromScheme(scheme); } if (port < 0) { throw new ClientException("Unable to derive host/port from vip address " + vipAddress); } hostAndPort.setFirst(host); hostAndPort.setSecond(port); return hostAndPort; } private boolean isVipRecognized(String vipEmbeddedInUri) { if (vipEmbeddedInUri == null) { return false; } if (vipAddresses == null) { return false; } String[] addresses = vipAddresses.split(","); for (String address: addresses) { if (vipEmbeddedInUri.equalsIgnoreCase(address.trim())) { return true; } } return false; } /** * Compute the final URI from a partial URI in the request. The following steps are performed: * * <li> if host is missing and there is a load balancer, get the host/port from server chosen from load balancer * <li> if host is missing and there is no load balancer, try to derive host/port from virtual address set with the client * <li> if host is present and the authority part of the URI is a virtual address set for the client, * and there is a load balancer, get the host/port from server chosen from load balancer * <li> if host is present but none of the above applies, interpret the host as the actual physical address * <li> if host is missing but none of the above applies, throws ClientException * * @param original Original URI passed from caller * @return new request with the final URI */ @SuppressWarnings("unchecked") protected T computeFinalUriWithLoadBalancer(T original) throws ClientException{ URI theUrl = original.getUri(); if (theUrl == null){ throw new ClientException(ClientException.ErrorType.GENERAL, "NULL URL passed in"); } String host = theUrl.getHost(); Pair<String, Integer> schemeAndPort = deriveSchemeAndPortFromPartialUri(original); String scheme = schemeAndPort.first(); int port = schemeAndPort.second(); // Various Supported Cases // The loadbalancer to use and the instances it has is based on how it was registered // In each of these cases, the client might come in using Full Url or Partial URL ILoadBalancer lb = getLoadBalancer(); Object loadBalancerKey = original.getLoadBalancerKey(); if (host == null){ // Partial URL Case // well we have to just get the right instances from lb - or we fall back if (lb != null){ Server svc = lb.chooseServer(loadBalancerKey); if (svc == null){ throw new ClientException(ClientException.ErrorType.GENERAL, "LoadBalancer returned null Server for :" + clientName); } host = svc.getHost(); port = svc.getPort(); if (host == null){ throw new ClientException(ClientException.ErrorType.GENERAL, "Invalid Server for :" + svc); } if (logger.isDebugEnabled()){ logger.debug(clientName + " using LB returned Server:" + svc + "for request:" + theUrl); } } else { // No Full URL - and we dont have a LoadBalancer registered to // obtain a server // if we have a vipAddress that came with the registration, we // can use that else we // bail out if (vipAddresses != null && vipAddresses.contains(",")) { throw new ClientException( ClientException.ErrorType.GENERAL, this.clientName + "Partial URI of (" + theUrl + ") has been sent in to RestClient (with no LB) to be executed." + " Also, there are multiple vipAddresses and hence RestClient cant pick" + "one vipAddress to complete this partial uri"); } else if (vipAddresses != null) { try { Pair<String,Integer> hostAndPort = deriveHostAndPortFromVipAddress(vipAddresses); host = hostAndPort.first(); port = hostAndPort.second(); } catch (URISyntaxException e) { throw new ClientException( ClientException.ErrorType.GENERAL, this.clientName + "Partial URI of (" + theUrl + ") has been sent in to RestClient (with no LB) to be executed." + " Also, the configured/registered vipAddress is unparseable (to determine host and port)"); } }else{ throw new ClientException( ClientException.ErrorType.GENERAL, this.clientName + " has no LoadBalancer registered and passed in a partial URL request (with no host:port)." + " Also has no vipAddress registered"); } } } else { // Full URL Case // This could either be a vipAddress or a hostAndPort or a real DNS // if vipAddress or hostAndPort, we just have to consult the loadbalancer // but if it does not return a server, we should just proceed anyways // and assume its a DNS // For restClients registered using a vipAddress AND executing a request // by passing in the full URL (including host and port), we should only // consult lb IFF the URL passed is registered as vipAddress in Discovery boolean shouldInterpretAsVip = false; if (lb != null) { shouldInterpretAsVip = isVipRecognized(original.getUri().getAuthority()); } if (shouldInterpretAsVip) { Server svc = lb.chooseServer(loadBalancerKey); if (svc != null){ host = svc.getHost(); port = svc.getPort(); if (host == null){ throw new ClientException(ClientException.ErrorType.GENERAL, "Invalid Server for :" + svc); } if (logger.isDebugEnabled()){ logger.debug("using LB returned Server:" + svc + "for request:" + theUrl); } }else{ // just fall back as real DNS if (logger.isDebugEnabled()){ logger.debug(host + ":" + port + " assumed to be a valid VIP address or exists in the DNS"); } } } else { // consult LB to obtain vipAddress backed instance given full URL //Full URL execute request - where url!=vipAddress if (logger.isDebugEnabled()){ logger.debug("Using full URL passed in by caller (not using LB/Discovery):" + theUrl); } } } // end of creating final URL if (host == null){ throw new ClientException(ClientException.ErrorType.GENERAL,"Request contains no HOST to talk to"); } // just verify that at this point we have a full URL try { StringBuilder sb = new StringBuilder(); sb.append(scheme).append("://"); if (!Strings.isNullOrEmpty(theUrl.getRawUserInfo())) { sb.append(theUrl.getRawUserInfo()).append("@"); } sb.append(host); if (port >= 0) { sb.append(":").append(port); } sb.append(theUrl.getRawPath()); if (!Strings.isNullOrEmpty(theUrl.getRawQuery())) { sb.append("?").append(theUrl.getRawQuery()); } if (!Strings.isNullOrEmpty(theUrl.getRawFragment())) { sb.append("#").append(theUrl.getRawFragment()); } URI newURI = new URI(sb.toString()); return (T) original.replaceUri(newURI); } catch (URISyntaxException e) { throw new ClientException(ClientException.ErrorType.GENERAL, e.getMessage()); } } protected boolean isRetriable(T request) { if (request.isRetriable()) { return true; } else { boolean retryOkayOnOperation = okToRetryOnAllOperations; IClientConfig overriddenClientConfig = request.getOverrideConfig(); if (overriddenClientConfig != null) { retryOkayOnOperation = overriddenClientConfig.getPropertyAsBoolean(CommonClientConfigKey.RequestSpecificRetryOn, okToRetryOnAllOperations); } return retryOkayOnOperation; } } protected int getRetriesNextServer(IClientConfig overriddenClientConfig) { int numRetries = maxAutoRetriesNextServer; if (overriddenClientConfig != null) { numRetries = overriddenClientConfig.getPropertyAsInteger(CommonClientConfigKey.MaxAutoRetriesNextServer, maxAutoRetriesNextServer); } return numRetries; } public final ServerStats getServerStats(Server server) { ServerStats serverStats = null; ILoadBalancer lb = this.getLoadBalancer(); if (lb instanceof AbstractLoadBalancer){ LoadBalancerStats lbStats = ((AbstractLoadBalancer) lb).getLoadBalancerStats(); serverStats = lbStats.getSingleServerStat(server); } return serverStats; } protected int getNumberRetriesOnSameServer(IClientConfig overriddenClientConfig) { int numRetries = maxAutoRetries; if (overriddenClientConfig!=null){ try { numRetries = overriddenClientConfig.getPropertyAsInteger(CommonClientConfigKey.MaxAutoRetries, maxAutoRetries); } catch (Exception e) { logger.warn("Invalid maxRetries requested for RestClient:" + this.clientName); } } return numRetries; } protected boolean handleSameServerRetry(URI uri, int currentRetryCount, int maxRetries, Throwable e) { if (currentRetryCount > maxRetries) { return false; } logger.debug("Exception while executing request which is deemed retry-able, retrying ..., SAME Server Retry Attempt#: {}, URI: {}", currentRetryCount, uri); return true; } public final LoadBalancerErrorHandler<? super T, ? super S> getErrorHandler() { return errorHandler; } public final void setErrorHandler( LoadBalancerErrorHandler<? super T, ? super S> errorHandler) { this.errorHandler = errorHandler; } public final boolean isOkToRetryOnAllOperations() { return okToRetryOnAllOperations; } public final void setOkToRetryOnAllOperations(boolean okToRetryOnAllOperations) { this.okToRetryOnAllOperations = okToRetryOnAllOperations; } }
[ "public", "abstract", "class", "LoadBalancerContext", "<", "T", "extends", "ClientRequest", ",", "S", "extends", "IResponse", ">", "implements", "IClientConfigAware", "{", "private", "static", "final", "Logger", "logger", "=", "LoggerFactory", ".", "getLogger", "(", "LoadBalancerContext", ".", "class", ")", ";", "protected", "String", "clientName", "=", "\"", "default", "\"", ";", "protected", "String", "vipAddresses", ";", "protected", "int", "maxAutoRetriesNextServer", "=", "DefaultClientConfigImpl", ".", "DEFAULT_MAX_AUTO_RETRIES_NEXT_SERVER", ";", "protected", "int", "maxAutoRetries", "=", "DefaultClientConfigImpl", ".", "DEFAULT_MAX_AUTO_RETRIES", ";", "protected", "LoadBalancerErrorHandler", "<", "?", "super", "T", ",", "?", "super", "S", ">", "errorHandler", "=", "new", "DefaultLoadBalancerErrorHandler", "<", "ClientRequest", ",", "IResponse", ">", "(", ")", ";", "boolean", "okToRetryOnAllOperations", "=", "DefaultClientConfigImpl", ".", "DEFAULT_OK_TO_RETRY_ON_ALL_OPERATIONS", ".", "booleanValue", "(", ")", ";", "private", "ILoadBalancer", "lb", ";", "private", "volatile", "Timer", "tracer", ";", "public", "LoadBalancerContext", "(", ")", "{", "}", "/**\n * Delegate to {@link #initWithNiwsConfig(IClientConfig)}\n * @param clientConfig\n */", "public", "LoadBalancerContext", "(", "IClientConfig", "clientConfig", ")", "{", "initWithNiwsConfig", "(", "clientConfig", ")", ";", "}", "/**\n * Set necessary parameters from client configuration and register with Servo monitors.\n */", "@", "Override", "public", "void", "initWithNiwsConfig", "(", "IClientConfig", "clientConfig", ")", "{", "if", "(", "clientConfig", "==", "null", ")", "{", "return", ";", "}", "clientName", "=", "clientConfig", ".", "getClientName", "(", ")", ";", "if", "(", "clientName", "==", "null", ")", "{", "clientName", "=", "\"", "default", "\"", ";", "}", "vipAddresses", "=", "clientConfig", ".", "resolveDeploymentContextbasedVipAddresses", "(", ")", ";", "maxAutoRetries", "=", "clientConfig", ".", "getPropertyAsInteger", "(", "CommonClientConfigKey", ".", "MaxAutoRetries", ",", "DefaultClientConfigImpl", ".", "DEFAULT_MAX_AUTO_RETRIES", ")", ";", "maxAutoRetriesNextServer", "=", "clientConfig", ".", "getPropertyAsInteger", "(", "CommonClientConfigKey", ".", "MaxAutoRetriesNextServer", ",", "maxAutoRetriesNextServer", ")", ";", "okToRetryOnAllOperations", "=", "clientConfig", ".", "getPropertyAsBoolean", "(", "CommonClientConfigKey", ".", "OkToRetryOnAllOperations", ",", "okToRetryOnAllOperations", ")", ";", "tracer", "=", "getExecuteTracer", "(", ")", ";", "Monitors", ".", "registerObject", "(", "\"", "Client_", "\"", "+", "clientName", ",", "this", ")", ";", "}", "protected", "Timer", "getExecuteTracer", "(", ")", "{", "if", "(", "tracer", "==", "null", ")", "{", "synchronized", "(", "this", ")", "{", "if", "(", "tracer", "==", "null", ")", "{", "tracer", "=", "Monitors", ".", "newTimer", "(", "clientName", "+", "\"", "_OperationTimer", "\"", ",", "TimeUnit", ".", "MILLISECONDS", ")", ";", "}", "}", "}", "return", "tracer", ";", "}", "public", "String", "getClientName", "(", ")", "{", "return", "clientName", ";", "}", "public", "ILoadBalancer", "getLoadBalancer", "(", ")", "{", "return", "lb", ";", "}", "public", "void", "setLoadBalancer", "(", "ILoadBalancer", "lb", ")", "{", "this", ".", "lb", "=", "lb", ";", "}", "public", "int", "getMaxAutoRetriesNextServer", "(", ")", "{", "return", "maxAutoRetriesNextServer", ";", "}", "public", "void", "setMaxAutoRetriesNextServer", "(", "int", "maxAutoRetriesNextServer", ")", "{", "this", ".", "maxAutoRetriesNextServer", "=", "maxAutoRetriesNextServer", ";", "}", "public", "int", "getMaxAutoRetries", "(", ")", "{", "return", "maxAutoRetries", ";", "}", "public", "void", "setMaxAutoRetries", "(", "int", "maxAutoRetries", ")", "{", "this", ".", "maxAutoRetries", "=", "maxAutoRetries", ";", "}", "protected", "Throwable", "getDeepestCause", "(", "Throwable", "e", ")", "{", "if", "(", "e", "!=", "null", ")", "{", "int", "infiniteLoopPreventionCounter", "=", "10", ";", "while", "(", "e", ".", "getCause", "(", ")", "!=", "null", "&&", "infiniteLoopPreventionCounter", ">", "0", ")", "{", "infiniteLoopPreventionCounter", "--", ";", "e", "=", "e", ".", "getCause", "(", ")", ";", "}", "}", "return", "e", ";", "}", "private", "boolean", "isPresentAsCause", "(", "Throwable", "throwableToSearchIn", ",", "Class", "<", "?", "extends", "Throwable", ">", "throwableToSearchFor", ")", "{", "return", "isPresentAsCauseHelper", "(", "throwableToSearchIn", ",", "throwableToSearchFor", ")", "!=", "null", ";", "}", "static", "Throwable", "isPresentAsCauseHelper", "(", "Throwable", "throwableToSearchIn", ",", "Class", "<", "?", "extends", "Throwable", ">", "throwableToSearchFor", ")", "{", "int", "infiniteLoopPreventionCounter", "=", "10", ";", "while", "(", "throwableToSearchIn", "!=", "null", "&&", "infiniteLoopPreventionCounter", ">", "0", ")", "{", "infiniteLoopPreventionCounter", "--", ";", "if", "(", "throwableToSearchIn", ".", "getClass", "(", ")", ".", "isAssignableFrom", "(", "throwableToSearchFor", ")", ")", "{", "return", "throwableToSearchIn", ";", "}", "else", "{", "throwableToSearchIn", "=", "throwableToSearchIn", ".", "getCause", "(", ")", ";", "}", "}", "return", "null", ";", "}", "/**\n * Test if certain exception classes exist as a cause in a Throwable \n */", "public", "static", "boolean", "isPresentAsCause", "(", "Throwable", "throwableToSearchIn", ",", "Collection", "<", "Class", "<", "?", "extends", "Throwable", ">", ">", "throwableToSearchFor", ")", "{", "int", "infiniteLoopPreventionCounter", "=", "10", ";", "while", "(", "throwableToSearchIn", "!=", "null", "&&", "infiniteLoopPreventionCounter", ">", "0", ")", "{", "infiniteLoopPreventionCounter", "--", ";", "for", "(", "Class", "<", "?", "extends", "Throwable", ">", "c", ":", "throwableToSearchFor", ")", "{", "if", "(", "throwableToSearchIn", ".", "getClass", "(", ")", ".", "isAssignableFrom", "(", "c", ")", ")", "{", "return", "true", ";", "}", "}", "throwableToSearchIn", "=", "throwableToSearchIn", ".", "getCause", "(", ")", ";", "}", "return", "false", ";", "}", "protected", "ClientException", "generateNIWSException", "(", "String", "uri", ",", "Throwable", "e", ")", "{", "ClientException", "niwsClientException", ";", "if", "(", "isPresentAsCause", "(", "e", ",", "java", ".", "net", ".", "SocketTimeoutException", ".", "class", ")", ")", "{", "niwsClientException", "=", "generateTimeoutNIWSException", "(", "uri", ",", "e", ")", ";", "}", "else", "if", "(", "e", ".", "getCause", "(", ")", "instanceof", "java", ".", "net", ".", "UnknownHostException", ")", "{", "niwsClientException", "=", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "UNKNOWN_HOST_EXCEPTION", ",", "\"", "Unable to execute RestClient request for URI:", "\"", "+", "uri", ",", "e", ")", ";", "}", "else", "if", "(", "e", ".", "getCause", "(", ")", "instanceof", "java", ".", "net", ".", "ConnectException", ")", "{", "niwsClientException", "=", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "CONNECT_EXCEPTION", ",", "\"", "Unable to execute RestClient request for URI:", "\"", "+", "uri", ",", "e", ")", ";", "}", "else", "if", "(", "e", ".", "getCause", "(", ")", "instanceof", "java", ".", "net", ".", "NoRouteToHostException", ")", "{", "niwsClientException", "=", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "NO_ROUTE_TO_HOST_EXCEPTION", ",", "\"", "Unable to execute RestClient request for URI:", "\"", "+", "uri", ",", "e", ")", ";", "}", "else", "if", "(", "e", "instanceof", "ClientException", ")", "{", "niwsClientException", "=", "(", "ClientException", ")", "e", ";", "}", "else", "{", "niwsClientException", "=", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "GENERAL", ",", "\"", "Unable to execute RestClient request for URI:", "\"", "+", "uri", ",", "e", ")", ";", "}", "return", "niwsClientException", ";", "}", "private", "boolean", "isPresentAsCause", "(", "Throwable", "throwableToSearchIn", ",", "Class", "<", "?", "extends", "Throwable", ">", "throwableToSearchFor", ",", "String", "messageSubStringToSearchFor", ")", "{", "Throwable", "throwableFound", "=", "isPresentAsCauseHelper", "(", "throwableToSearchIn", ",", "throwableToSearchFor", ")", ";", "if", "(", "throwableFound", "!=", "null", ")", "{", "return", "throwableFound", ".", "getMessage", "(", ")", ".", "contains", "(", "messageSubStringToSearchFor", ")", ";", "}", "return", "false", ";", "}", "private", "ClientException", "generateTimeoutNIWSException", "(", "String", "uri", ",", "Throwable", "e", ")", "{", "ClientException", "niwsClientException", ";", "if", "(", "isPresentAsCause", "(", "e", ",", "java", ".", "net", ".", "SocketTimeoutException", ".", "class", ",", "\"", "Read timed out", "\"", ")", ")", "{", "niwsClientException", "=", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "READ_TIMEOUT_EXCEPTION", ",", "\"", "Unable to execute RestClient request for URI:", "\"", "+", "uri", "+", "\"", ":", "\"", "+", "getDeepestCause", "(", "e", ")", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "else", "{", "niwsClientException", "=", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "SOCKET_TIMEOUT_EXCEPTION", ",", "\"", "Unable to execute RestClient request for URI:", "\"", "+", "uri", "+", "\"", ":", "\"", "+", "getDeepestCause", "(", "e", ")", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "return", "niwsClientException", ";", "}", "/**\n * This is called after a response is received or an exception is thrown from the client\n * to update related stats. \n */", "protected", "void", "noteRequestCompletion", "(", "ServerStats", "stats", ",", "ClientRequest", "request", ",", "IResponse", "response", ",", "Throwable", "e", ",", "long", "responseTime", ")", "{", "try", "{", "if", "(", "stats", "!=", "null", ")", "{", "stats", ".", "decrementActiveRequestsCount", "(", ")", ";", "stats", ".", "incrementNumRequests", "(", ")", ";", "stats", ".", "noteResponseTime", "(", "responseTime", ")", ";", "if", "(", "response", "!=", "null", ")", "{", "stats", ".", "clearSuccessiveConnectionFailureCount", "(", ")", ";", "}", "}", "}", "catch", "(", "Throwable", "ex", ")", "{", "logger", ".", "error", "(", "\"", "Unexpected exception", "\"", ",", "ex", ")", ";", "}", "}", "/**\n * This is usually called just before client execute a request.\n */", "protected", "void", "noteOpenConnection", "(", "ServerStats", "serverStats", ",", "ClientRequest", "request", ")", "{", "if", "(", "serverStats", "==", "null", ")", "{", "return", ";", "}", "try", "{", "serverStats", ".", "incrementActiveRequestsCount", "(", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "logger", ".", "info", "(", "\"", "Unable to note Server Stats:", "\"", ",", "e", ")", ";", "}", "}", "/**\n * Derive scheme and port from a partial URI. For example, for HTTP based client, the URI with \n * only path \"/\" should return \"http\" and 80, whereas the URI constructed with scheme \"https\" and\n * path \"/\" should return\n * \"https\" and 443. This method is called by {@link #computeFinalUriWithLoadBalancer(ClientRequest)}\n * to get the complete executable URI.\n * \n */", "protected", "Pair", "<", "String", ",", "Integer", ">", "deriveSchemeAndPortFromPartialUri", "(", "T", "request", ")", "{", "URI", "theUrl", "=", "request", ".", "getUri", "(", ")", ";", "boolean", "isSecure", "=", "false", ";", "String", "scheme", "=", "theUrl", ".", "getScheme", "(", ")", ";", "if", "(", "scheme", "!=", "null", ")", "{", "isSecure", "=", "scheme", ".", "equalsIgnoreCase", "(", "\"", "https", "\"", ")", ";", "}", "int", "port", "=", "theUrl", ".", "getPort", "(", ")", ";", "if", "(", "port", "<", "0", "&&", "!", "isSecure", ")", "{", "port", "=", "80", ";", "}", "else", "if", "(", "port", "<", "0", "&&", "isSecure", ")", "{", "port", "=", "443", ";", "}", "if", "(", "scheme", "==", "null", ")", "{", "if", "(", "isSecure", ")", "{", "scheme", "=", "\"", "https", "\"", ";", "}", "else", "{", "scheme", "=", "\"", "http", "\"", ";", "}", "}", "return", "new", "Pair", "<", "String", ",", "Integer", ">", "(", "scheme", ",", "port", ")", ";", "}", "/**\n * Get the default port of the target server given the scheme of vip address if it is available. \n * Subclass should override it to provider protocol specific default port number if any.\n * \n * @param scheme from the vip address. null if not present.\n * @return 80 if scheme is http, 443 if scheme is https, -1 else.\n */", "protected", "int", "getDefaultPortFromScheme", "(", "String", "scheme", ")", "{", "if", "(", "scheme", "==", "null", ")", "{", "return", "-", "1", ";", "}", "if", "(", "scheme", ".", "equals", "(", "\"", "http", "\"", ")", ")", "{", "return", "80", ";", "}", "else", "if", "(", "scheme", ".", "equals", "(", "\"", "https", "\"", ")", ")", "{", "return", "443", ";", "}", "else", "{", "return", "-", "1", ";", "}", "}", "/**\n * Derive the host and port from virtual address if virtual address is indeed contains the actual host \n * and port of the server. This is the final resort to compute the final URI in {@link #computeFinalUriWithLoadBalancer(ClientRequest)}\n * if there is no load balancer available and the request URI is incomplete. Sub classes can override this method\n * to be more accurate or throws ClientException if it does not want to support virtual address to be the\n * same as physical server address.\n * <p>\n * The virtual address is used by certain load balancers to filter the servers of the same function \n * to form the server pool. \n * \n */", "protected", "Pair", "<", "String", ",", "Integer", ">", "deriveHostAndPortFromVipAddress", "(", "String", "vipAddress", ")", "throws", "URISyntaxException", ",", "ClientException", "{", "Pair", "<", "String", ",", "Integer", ">", "hostAndPort", "=", "new", "Pair", "<", "String", ",", "Integer", ">", "(", "null", ",", "-", "1", ")", ";", "URI", "uri", "=", "new", "URI", "(", "vipAddress", ")", ";", "String", "scheme", "=", "uri", ".", "getScheme", "(", ")", ";", "if", "(", "scheme", "==", "null", ")", "{", "uri", "=", "new", "URI", "(", "\"", "http://", "\"", "+", "vipAddress", ")", ";", "}", "String", "host", "=", "uri", ".", "getHost", "(", ")", ";", "if", "(", "host", "==", "null", ")", "{", "throw", "new", "ClientException", "(", "\"", "Unable to derive host/port from vip address ", "\"", "+", "vipAddress", ")", ";", "}", "int", "port", "=", "uri", ".", "getPort", "(", ")", ";", "if", "(", "port", "<", "0", ")", "{", "port", "=", "getDefaultPortFromScheme", "(", "scheme", ")", ";", "}", "if", "(", "port", "<", "0", ")", "{", "throw", "new", "ClientException", "(", "\"", "Unable to derive host/port from vip address ", "\"", "+", "vipAddress", ")", ";", "}", "hostAndPort", ".", "setFirst", "(", "host", ")", ";", "hostAndPort", ".", "setSecond", "(", "port", ")", ";", "return", "hostAndPort", ";", "}", "private", "boolean", "isVipRecognized", "(", "String", "vipEmbeddedInUri", ")", "{", "if", "(", "vipEmbeddedInUri", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "vipAddresses", "==", "null", ")", "{", "return", "false", ";", "}", "String", "[", "]", "addresses", "=", "vipAddresses", ".", "split", "(", "\"", ",", "\"", ")", ";", "for", "(", "String", "address", ":", "addresses", ")", "{", "if", "(", "vipEmbeddedInUri", ".", "equalsIgnoreCase", "(", "address", ".", "trim", "(", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "/**\n * Compute the final URI from a partial URI in the request. The following steps are performed:\n * \n * <li> if host is missing and there is a load balancer, get the host/port from server chosen from load balancer\n * <li> if host is missing and there is no load balancer, try to derive host/port from virtual address set with the client\n * <li> if host is present and the authority part of the URI is a virtual address set for the client, \n * and there is a load balancer, get the host/port from server chosen from load balancer\n * <li> if host is present but none of the above applies, interpret the host as the actual physical address\n * <li> if host is missing but none of the above applies, throws ClientException\n * \n * @param original Original URI passed from caller\n * @return new request with the final URI \n */", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "protected", "T", "computeFinalUriWithLoadBalancer", "(", "T", "original", ")", "throws", "ClientException", "{", "URI", "theUrl", "=", "original", ".", "getUri", "(", ")", ";", "if", "(", "theUrl", "==", "null", ")", "{", "throw", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "GENERAL", ",", "\"", "NULL URL passed in", "\"", ")", ";", "}", "String", "host", "=", "theUrl", ".", "getHost", "(", ")", ";", "Pair", "<", "String", ",", "Integer", ">", "schemeAndPort", "=", "deriveSchemeAndPortFromPartialUri", "(", "original", ")", ";", "String", "scheme", "=", "schemeAndPort", ".", "first", "(", ")", ";", "int", "port", "=", "schemeAndPort", ".", "second", "(", ")", ";", "ILoadBalancer", "lb", "=", "getLoadBalancer", "(", ")", ";", "Object", "loadBalancerKey", "=", "original", ".", "getLoadBalancerKey", "(", ")", ";", "if", "(", "host", "==", "null", ")", "{", "if", "(", "lb", "!=", "null", ")", "{", "Server", "svc", "=", "lb", ".", "chooseServer", "(", "loadBalancerKey", ")", ";", "if", "(", "svc", "==", "null", ")", "{", "throw", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "GENERAL", ",", "\"", "LoadBalancer returned null Server for :", "\"", "+", "clientName", ")", ";", "}", "host", "=", "svc", ".", "getHost", "(", ")", ";", "port", "=", "svc", ".", "getPort", "(", ")", ";", "if", "(", "host", "==", "null", ")", "{", "throw", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "GENERAL", ",", "\"", "Invalid Server for :", "\"", "+", "svc", ")", ";", "}", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "clientName", "+", "\"", " using LB returned Server:", "\"", "+", "svc", "+", "\"", "for request:", "\"", "+", "theUrl", ")", ";", "}", "}", "else", "{", "if", "(", "vipAddresses", "!=", "null", "&&", "vipAddresses", ".", "contains", "(", "\"", ",", "\"", ")", ")", "{", "throw", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "GENERAL", ",", "this", ".", "clientName", "+", "\"", "Partial URI of (", "\"", "+", "theUrl", "+", "\"", ") has been sent in to RestClient (with no LB) to be executed.", "\"", "+", "\"", " Also, there are multiple vipAddresses and hence RestClient cant pick", "\"", "+", "\"", "one vipAddress to complete this partial uri", "\"", ")", ";", "}", "else", "if", "(", "vipAddresses", "!=", "null", ")", "{", "try", "{", "Pair", "<", "String", ",", "Integer", ">", "hostAndPort", "=", "deriveHostAndPortFromVipAddress", "(", "vipAddresses", ")", ";", "host", "=", "hostAndPort", ".", "first", "(", ")", ";", "port", "=", "hostAndPort", ".", "second", "(", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "GENERAL", ",", "this", ".", "clientName", "+", "\"", "Partial URI of (", "\"", "+", "theUrl", "+", "\"", ") has been sent in to RestClient (with no LB) to be executed.", "\"", "+", "\"", " Also, the configured/registered vipAddress is unparseable (to determine host and port)", "\"", ")", ";", "}", "}", "else", "{", "throw", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "GENERAL", ",", "this", ".", "clientName", "+", "\"", " has no LoadBalancer registered and passed in a partial URL request (with no host:port).", "\"", "+", "\"", " Also has no vipAddress registered", "\"", ")", ";", "}", "}", "}", "else", "{", "boolean", "shouldInterpretAsVip", "=", "false", ";", "if", "(", "lb", "!=", "null", ")", "{", "shouldInterpretAsVip", "=", "isVipRecognized", "(", "original", ".", "getUri", "(", ")", ".", "getAuthority", "(", ")", ")", ";", "}", "if", "(", "shouldInterpretAsVip", ")", "{", "Server", "svc", "=", "lb", ".", "chooseServer", "(", "loadBalancerKey", ")", ";", "if", "(", "svc", "!=", "null", ")", "{", "host", "=", "svc", ".", "getHost", "(", ")", ";", "port", "=", "svc", ".", "getPort", "(", ")", ";", "if", "(", "host", "==", "null", ")", "{", "throw", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "GENERAL", ",", "\"", "Invalid Server for :", "\"", "+", "svc", ")", ";", "}", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"", "using LB returned Server:", "\"", "+", "svc", "+", "\"", "for request:", "\"", "+", "theUrl", ")", ";", "}", "}", "else", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "host", "+", "\"", ":", "\"", "+", "port", "+", "\"", " assumed to be a valid VIP address or exists in the DNS", "\"", ")", ";", "}", "}", "}", "else", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"", "Using full URL passed in by caller (not using LB/Discovery):", "\"", "+", "theUrl", ")", ";", "}", "}", "}", "if", "(", "host", "==", "null", ")", "{", "throw", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "GENERAL", ",", "\"", "Request contains no HOST to talk to", "\"", ")", ";", "}", "try", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "scheme", ")", ".", "append", "(", "\"", "://", "\"", ")", ";", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "theUrl", ".", "getRawUserInfo", "(", ")", ")", ")", "{", "sb", ".", "append", "(", "theUrl", ".", "getRawUserInfo", "(", ")", ")", ".", "append", "(", "\"", "@", "\"", ")", ";", "}", "sb", ".", "append", "(", "host", ")", ";", "if", "(", "port", ">=", "0", ")", "{", "sb", ".", "append", "(", "\"", ":", "\"", ")", ".", "append", "(", "port", ")", ";", "}", "sb", ".", "append", "(", "theUrl", ".", "getRawPath", "(", ")", ")", ";", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "theUrl", ".", "getRawQuery", "(", ")", ")", ")", "{", "sb", ".", "append", "(", "\"", "?", "\"", ")", ".", "append", "(", "theUrl", ".", "getRawQuery", "(", ")", ")", ";", "}", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "theUrl", ".", "getRawFragment", "(", ")", ")", ")", "{", "sb", ".", "append", "(", "\"", "#", "\"", ")", ".", "append", "(", "theUrl", ".", "getRawFragment", "(", ")", ")", ";", "}", "URI", "newURI", "=", "new", "URI", "(", "sb", ".", "toString", "(", ")", ")", ";", "return", "(", "T", ")", "original", ".", "replaceUri", "(", "newURI", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "ClientException", "(", "ClientException", ".", "ErrorType", ".", "GENERAL", ",", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "protected", "boolean", "isRetriable", "(", "T", "request", ")", "{", "if", "(", "request", ".", "isRetriable", "(", ")", ")", "{", "return", "true", ";", "}", "else", "{", "boolean", "retryOkayOnOperation", "=", "okToRetryOnAllOperations", ";", "IClientConfig", "overriddenClientConfig", "=", "request", ".", "getOverrideConfig", "(", ")", ";", "if", "(", "overriddenClientConfig", "!=", "null", ")", "{", "retryOkayOnOperation", "=", "overriddenClientConfig", ".", "getPropertyAsBoolean", "(", "CommonClientConfigKey", ".", "RequestSpecificRetryOn", ",", "okToRetryOnAllOperations", ")", ";", "}", "return", "retryOkayOnOperation", ";", "}", "}", "protected", "int", "getRetriesNextServer", "(", "IClientConfig", "overriddenClientConfig", ")", "{", "int", "numRetries", "=", "maxAutoRetriesNextServer", ";", "if", "(", "overriddenClientConfig", "!=", "null", ")", "{", "numRetries", "=", "overriddenClientConfig", ".", "getPropertyAsInteger", "(", "CommonClientConfigKey", ".", "MaxAutoRetriesNextServer", ",", "maxAutoRetriesNextServer", ")", ";", "}", "return", "numRetries", ";", "}", "public", "final", "ServerStats", "getServerStats", "(", "Server", "server", ")", "{", "ServerStats", "serverStats", "=", "null", ";", "ILoadBalancer", "lb", "=", "this", ".", "getLoadBalancer", "(", ")", ";", "if", "(", "lb", "instanceof", "AbstractLoadBalancer", ")", "{", "LoadBalancerStats", "lbStats", "=", "(", "(", "AbstractLoadBalancer", ")", "lb", ")", ".", "getLoadBalancerStats", "(", ")", ";", "serverStats", "=", "lbStats", ".", "getSingleServerStat", "(", "server", ")", ";", "}", "return", "serverStats", ";", "}", "protected", "int", "getNumberRetriesOnSameServer", "(", "IClientConfig", "overriddenClientConfig", ")", "{", "int", "numRetries", "=", "maxAutoRetries", ";", "if", "(", "overriddenClientConfig", "!=", "null", ")", "{", "try", "{", "numRetries", "=", "overriddenClientConfig", ".", "getPropertyAsInteger", "(", "CommonClientConfigKey", ".", "MaxAutoRetries", ",", "maxAutoRetries", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "warn", "(", "\"", "Invalid maxRetries requested for RestClient:", "\"", "+", "this", ".", "clientName", ")", ";", "}", "}", "return", "numRetries", ";", "}", "protected", "boolean", "handleSameServerRetry", "(", "URI", "uri", ",", "int", "currentRetryCount", ",", "int", "maxRetries", ",", "Throwable", "e", ")", "{", "if", "(", "currentRetryCount", ">", "maxRetries", ")", "{", "return", "false", ";", "}", "logger", ".", "debug", "(", "\"", "Exception while executing request which is deemed retry-able, retrying ..., SAME Server Retry Attempt#: {}, URI: {}", "\"", ",", "currentRetryCount", ",", "uri", ")", ";", "return", "true", ";", "}", "public", "final", "LoadBalancerErrorHandler", "<", "?", "super", "T", ",", "?", "super", "S", ">", "getErrorHandler", "(", ")", "{", "return", "errorHandler", ";", "}", "public", "final", "void", "setErrorHandler", "(", "LoadBalancerErrorHandler", "<", "?", "super", "T", ",", "?", "super", "S", ">", "errorHandler", ")", "{", "this", ".", "errorHandler", "=", "errorHandler", ";", "}", "public", "final", "boolean", "isOkToRetryOnAllOperations", "(", ")", "{", "return", "okToRetryOnAllOperations", ";", "}", "public", "final", "void", "setOkToRetryOnAllOperations", "(", "boolean", "okToRetryOnAllOperations", ")", "{", "this", ".", "okToRetryOnAllOperations", "=", "okToRetryOnAllOperations", ";", "}", "}" ]
A class contains APIs intended to be used be load balancing client which is subclass of this class.
[ "A", "class", "contains", "APIs", "intended", "to", "be", "used", "be", "load", "balancing", "client", "which", "is", "subclass", "of", "this", "class", "." ]
[ "// Various Supported Cases", "// The loadbalancer to use and the instances it has is based on how it was registered", "// In each of these cases, the client might come in using Full Url or Partial URL", "// Partial URL Case", "// well we have to just get the right instances from lb - or we fall back", "// No Full URL - and we dont have a LoadBalancer registered to", "// obtain a server", "// if we have a vipAddress that came with the registration, we", "// can use that else we", "// bail out", "// Full URL Case", "// This could either be a vipAddress or a hostAndPort or a real DNS", "// if vipAddress or hostAndPort, we just have to consult the loadbalancer", "// but if it does not return a server, we should just proceed anyways", "// and assume its a DNS", "// For restClients registered using a vipAddress AND executing a request", "// by passing in the full URL (including host and port), we should only", "// consult lb IFF the URL passed is registered as vipAddress in Discovery", "// just fall back as real DNS", "// consult LB to obtain vipAddress backed instance given full URL", "//Full URL execute request - where url!=vipAddress", "// end of creating final URL", "// just verify that at this point we have a full URL" ]
[ { "param": "IClientConfigAware", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IClientConfigAware", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
20039414531cf0006faa9814b46c37f352178bce
vchoudhari45/codingcargo
src/main/java/com/vc/hard/SerializeAndDeserializeNAryTree.java
[ "Apache-2.0" ]
Java
SerializeAndDeserializeNAryTree
/* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; } }; */
Definition for a Node. class Node { public int val; public List children. public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List _children) { val = _val; children = _children; } }.
[ "Definition", "for", "a", "Node", ".", "class", "Node", "{", "public", "int", "val", ";", "public", "List", "children", ".", "public", "Node", "()", "{}", "public", "Node", "(", "int", "_val", ")", "{", "val", "=", "_val", ";", "}", "public", "Node", "(", "int", "_val", "List", "_children", ")", "{", "val", "=", "_val", ";", "children", "=", "_children", ";", "}", "}", "." ]
class SerializeAndDeserializeNAryTree { // Encodes a tree to a single string. public String serialize(Node root) { StringBuilder sb = new StringBuilder(); serialize(root, sb); return sb.toString(); } private void serialize(Node root, StringBuilder sb) { if(root == null) { sb.append("NULL "); } else { int size = root.children.size(); sb.append(root.val); sb.append(","); sb.append(size); sb.append(" "); for(Node child: root.children) { serialize(child, sb); } } } // Decodes your encoded data to tree. public Node deserialize(String data) { String[] arr = data.split(" "); Queue<String> q = new LinkedList<>(); for(String d: arr) q.offer(d); return deserialize(q); } private Node deserialize(Queue<String> q) { String e = q.poll(); if(e.equals("NULL")) return null; else { String[] qArr = e.split(","); int val = Integer.parseInt(qArr[0]); int size = Integer.parseInt(qArr[1]); List<Node> children = new ArrayList<>(); Node node = new Node(val, children); for(int i = 0; i < size; i++) { children.add(deserialize(q)); } return node; } } }
[ "class", "SerializeAndDeserializeNAryTree", "{", "public", "String", "serialize", "(", "Node", "root", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "serialize", "(", "root", ",", "sb", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "private", "void", "serialize", "(", "Node", "root", ",", "StringBuilder", "sb", ")", "{", "if", "(", "root", "==", "null", ")", "{", "sb", ".", "append", "(", "\"", "NULL ", "\"", ")", ";", "}", "else", "{", "int", "size", "=", "root", ".", "children", ".", "size", "(", ")", ";", "sb", ".", "append", "(", "root", ".", "val", ")", ";", "sb", ".", "append", "(", "\"", ",", "\"", ")", ";", "sb", ".", "append", "(", "size", ")", ";", "sb", ".", "append", "(", "\"", " ", "\"", ")", ";", "for", "(", "Node", "child", ":", "root", ".", "children", ")", "{", "serialize", "(", "child", ",", "sb", ")", ";", "}", "}", "}", "public", "Node", "deserialize", "(", "String", "data", ")", "{", "String", "[", "]", "arr", "=", "data", ".", "split", "(", "\"", " ", "\"", ")", ";", "Queue", "<", "String", ">", "q", "=", "new", "LinkedList", "<", ">", "(", ")", ";", "for", "(", "String", "d", ":", "arr", ")", "q", ".", "offer", "(", "d", ")", ";", "return", "deserialize", "(", "q", ")", ";", "}", "private", "Node", "deserialize", "(", "Queue", "<", "String", ">", "q", ")", "{", "String", "e", "=", "q", ".", "poll", "(", ")", ";", "if", "(", "e", ".", "equals", "(", "\"", "NULL", "\"", ")", ")", "return", "null", ";", "else", "{", "String", "[", "]", "qArr", "=", "e", ".", "split", "(", "\"", ",", "\"", ")", ";", "int", "val", "=", "Integer", ".", "parseInt", "(", "qArr", "[", "0", "]", ")", ";", "int", "size", "=", "Integer", ".", "parseInt", "(", "qArr", "[", "1", "]", ")", ";", "List", "<", "Node", ">", "children", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "Node", "node", "=", "new", "Node", "(", "val", ",", "children", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "children", ".", "add", "(", "deserialize", "(", "q", ")", ")", ";", "}", "return", "node", ";", "}", "}", "}" ]
Definition for a Node.
[ "Definition", "for", "a", "Node", "." ]
[ "// Encodes a tree to a single string.", "// Decodes your encoded data to tree." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
200541a904d4fb7ec3b92cc9bbad3e1939f6ef9d
kggold4/algorithms
src/algorithms_1/practice/FibonacciMatrix.java
[ "MIT" ]
Java
FibonacciMatrix
/** * calculate fibonacci numbers with matrices * complexity = O(log n) */
calculate fibonacci numbers with matrices complexity = O(log n)
[ "calculate", "fibonacci", "numbers", "with", "matrices", "complexity", "=", "O", "(", "log", "n", ")" ]
public class FibonacciMatrix { private static final int[][] F = { {1,1}, {1,0} }; public static long fibonacciMatrix(int n) { int[][] ans = F; int[][] A = F; while(n != 0) { if(n % 2 == 1) ans = multipleMatrix2D(ans, A); A = multipleMatrix2D(A, A); n /= 2; } return ans[1][1]; } /** * multiple by two 2D matrix * Complexity = O(1) * @param mat1 * @param mat2 * @return */ public static int[][] multipleMatrix2D(int[][] mat1, int[][] mat2) { int[][] ans = new int[2][2]; for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { ans[i][j] = mat1[i][0] * mat2[0][j] + mat1[i][1] * mat2[1][j]; } } return ans; } public static void main(String[] args) { long n = fibonacciMatrix(40); System.out.println(n); } }
[ "public", "class", "FibonacciMatrix", "{", "private", "static", "final", "int", "[", "]", "[", "]", "F", "=", "{", "{", "1", ",", "1", "}", ",", "{", "1", ",", "0", "}", "}", ";", "public", "static", "long", "fibonacciMatrix", "(", "int", "n", ")", "{", "int", "[", "]", "[", "]", "ans", "=", "F", ";", "int", "[", "]", "[", "]", "A", "=", "F", ";", "while", "(", "n", "!=", "0", ")", "{", "if", "(", "n", "%", "2", "==", "1", ")", "ans", "=", "multipleMatrix2D", "(", "ans", ",", "A", ")", ";", "A", "=", "multipleMatrix2D", "(", "A", ",", "A", ")", ";", "n", "/=", "2", ";", "}", "return", "ans", "[", "1", "]", "[", "1", "]", ";", "}", "/**\n * multiple by two 2D matrix\n * Complexity = O(1)\n * @param mat1\n * @param mat2\n * @return\n */", "public", "static", "int", "[", "]", "[", "]", "multipleMatrix2D", "(", "int", "[", "]", "[", "]", "mat1", ",", "int", "[", "]", "[", "]", "mat2", ")", "{", "int", "[", "]", "[", "]", "ans", "=", "new", "int", "[", "2", "]", "[", "2", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "2", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "2", ";", "j", "++", ")", "{", "ans", "[", "i", "]", "[", "j", "]", "=", "mat1", "[", "i", "]", "[", "0", "]", "*", "mat2", "[", "0", "]", "[", "j", "]", "+", "mat1", "[", "i", "]", "[", "1", "]", "*", "mat2", "[", "1", "]", "[", "j", "]", ";", "}", "}", "return", "ans", ";", "}", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "long", "n", "=", "fibonacciMatrix", "(", "40", ")", ";", "System", ".", "out", ".", "println", "(", "n", ")", ";", "}", "}" ]
calculate fibonacci numbers with matrices complexity = O(log n)
[ "calculate", "fibonacci", "numbers", "with", "matrices", "complexity", "=", "O", "(", "log", "n", ")" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
200577d4233ce2762f1c44dba0879714f23e2304
snaekobbi/jsass
src/main/java/io/bit3/jsass/Compiler.java
[ "MIT" ]
Java
Compiler
/** * The compiler compiles SCSS files, strings and contexts. */
The compiler compiles SCSS files, strings and contexts.
[ "The", "compiler", "compiles", "SCSS", "files", "strings", "and", "contexts", "." ]
public class Compiler { /** * sass library adapter. */ private final NativeAdapter adapter; /** * Create new compiler. */ public Compiler() { FunctionArgumentSignatureFactory functionArgumentSignatureFactory = new FunctionArgumentSignatureFactory(); FunctionWrapperFactory functionWrapperFactory = new FunctionWrapperFactory(functionArgumentSignatureFactory); adapter = new NativeAdapter(functionWrapperFactory); } /** * Compile string. * * @param string The input string. * @param options The compile options. * @return The compilation output. * @throws CompilationException If the compilation failed. */ public Output compileString(String string, Options options) throws CompilationException { return compileString(string, null, null, options); } /** * Compile string. * * @param string The input string. * @param inputPath The input path. * @param outputPath The output path. * @param options The compile options. * @return The compilation output. * @throws CompilationException If the compilation failed. */ public Output compileString(String string, URI inputPath, URI outputPath, Options options) throws CompilationException { StringContext context = new StringContext(string, inputPath, outputPath, options); return compile(context); } /** * Compile file. * * @param inputPath The input path. * @param outputPath The output path. * @param options The compile options. * @return The compilation output. * @throws CompilationException If the compilation failed. */ public Output compileFile(URI inputPath, URI outputPath, Options options) throws CompilationException { FileContext context = new FileContext(inputPath, outputPath, options); return compile(context); } /** * Compile context. * * @param context The context. * @return The compilation output. * @throws UnsupportedContextException If the given context is not supported. * @throws CompilationException If the compilation failed. */ public Output compile(Context context) throws CompilationException { Objects.requireNonNull(context, "Parameter context must not be null"); if (context instanceof FileContext) { return compile((FileContext) context); } if (context instanceof StringContext) { return compile((StringContext) context); } throw new UnsupportedContextException(context); } /** * Compile a string context. * * @param context The string context. * @return The compilation output. * @throws CompilationException If the compilation failed. */ public Output compile(StringContext context) throws CompilationException { final ImportStack importStack = new ImportStack(); return postProcess(adapter.compile(context, importStack)); } /** * Compile file. * * @param context The file context. * @return The compilation output. * @throws CompilationException If the compilation failed. */ public Output compile(FileContext context) throws CompilationException { final ImportStack importStack = new ImportStack(); return postProcess(adapter.compile(context, importStack)); } private Output postProcess(Output output) { final String sourceMap = output.getSourceMap(); if (null == sourceMap) { return output; } final Json json = Json.read(sourceMap); final Json sources = json.at("sources"); if (null != sources && sources.isArray()) { final List<Json> list = sources.asJsonList(); list.removeIf(item -> item.isString() && ( item.asString().endsWith("JSASS_CUSTOM.scss") || item.asString().endsWith("JSASS_PRE_IMPORT.scss") || item.asString().endsWith("JSASS_POST_IMPORT.scss") )); } final Json sourcesContent = json.at("sourcesContent"); if (null != sourcesContent && sourcesContent.isArray()) { final List<Json> list = sourcesContent.asJsonList(); list.removeIf(item -> item.isString() && ( item.asString().startsWith("$jsass") )); } return new Output(output.getCss(), json.toString()); } public static String sass2scss(String source, int options) { return NativeAdapter.sass2scss(source, options); } }
[ "public", "class", "Compiler", "{", "/**\n * sass library adapter.\n */", "private", "final", "NativeAdapter", "adapter", ";", "/**\n * Create new compiler.\n */", "public", "Compiler", "(", ")", "{", "FunctionArgumentSignatureFactory", "functionArgumentSignatureFactory", "=", "new", "FunctionArgumentSignatureFactory", "(", ")", ";", "FunctionWrapperFactory", "functionWrapperFactory", "=", "new", "FunctionWrapperFactory", "(", "functionArgumentSignatureFactory", ")", ";", "adapter", "=", "new", "NativeAdapter", "(", "functionWrapperFactory", ")", ";", "}", "/**\n * Compile string.\n *\n * @param string The input string.\n * @param options The compile options.\n * @return The compilation output.\n * @throws CompilationException If the compilation failed.\n */", "public", "Output", "compileString", "(", "String", "string", ",", "Options", "options", ")", "throws", "CompilationException", "{", "return", "compileString", "(", "string", ",", "null", ",", "null", ",", "options", ")", ";", "}", "/**\n * Compile string.\n *\n * @param string The input string.\n * @param inputPath The input path.\n * @param outputPath The output path.\n * @param options The compile options.\n * @return The compilation output.\n * @throws CompilationException If the compilation failed.\n */", "public", "Output", "compileString", "(", "String", "string", ",", "URI", "inputPath", ",", "URI", "outputPath", ",", "Options", "options", ")", "throws", "CompilationException", "{", "StringContext", "context", "=", "new", "StringContext", "(", "string", ",", "inputPath", ",", "outputPath", ",", "options", ")", ";", "return", "compile", "(", "context", ")", ";", "}", "/**\n * Compile file.\n *\n * @param inputPath The input path.\n * @param outputPath The output path.\n * @param options The compile options.\n * @return The compilation output.\n * @throws CompilationException If the compilation failed.\n */", "public", "Output", "compileFile", "(", "URI", "inputPath", ",", "URI", "outputPath", ",", "Options", "options", ")", "throws", "CompilationException", "{", "FileContext", "context", "=", "new", "FileContext", "(", "inputPath", ",", "outputPath", ",", "options", ")", ";", "return", "compile", "(", "context", ")", ";", "}", "/**\n * Compile context.\n *\n * @param context The context.\n * @return The compilation output.\n * @throws UnsupportedContextException If the given context is not supported.\n * @throws CompilationException If the compilation failed.\n */", "public", "Output", "compile", "(", "Context", "context", ")", "throws", "CompilationException", "{", "Objects", ".", "requireNonNull", "(", "context", ",", "\"", "Parameter context must not be null", "\"", ")", ";", "if", "(", "context", "instanceof", "FileContext", ")", "{", "return", "compile", "(", "(", "FileContext", ")", "context", ")", ";", "}", "if", "(", "context", "instanceof", "StringContext", ")", "{", "return", "compile", "(", "(", "StringContext", ")", "context", ")", ";", "}", "throw", "new", "UnsupportedContextException", "(", "context", ")", ";", "}", "/**\n * Compile a string context.\n *\n * @param context The string context.\n * @return The compilation output.\n * @throws CompilationException If the compilation failed.\n */", "public", "Output", "compile", "(", "StringContext", "context", ")", "throws", "CompilationException", "{", "final", "ImportStack", "importStack", "=", "new", "ImportStack", "(", ")", ";", "return", "postProcess", "(", "adapter", ".", "compile", "(", "context", ",", "importStack", ")", ")", ";", "}", "/**\n * Compile file.\n *\n * @param context The file context.\n * @return The compilation output.\n * @throws CompilationException If the compilation failed.\n */", "public", "Output", "compile", "(", "FileContext", "context", ")", "throws", "CompilationException", "{", "final", "ImportStack", "importStack", "=", "new", "ImportStack", "(", ")", ";", "return", "postProcess", "(", "adapter", ".", "compile", "(", "context", ",", "importStack", ")", ")", ";", "}", "private", "Output", "postProcess", "(", "Output", "output", ")", "{", "final", "String", "sourceMap", "=", "output", ".", "getSourceMap", "(", ")", ";", "if", "(", "null", "==", "sourceMap", ")", "{", "return", "output", ";", "}", "final", "Json", "json", "=", "Json", ".", "read", "(", "sourceMap", ")", ";", "final", "Json", "sources", "=", "json", ".", "at", "(", "\"", "sources", "\"", ")", ";", "if", "(", "null", "!=", "sources", "&&", "sources", ".", "isArray", "(", ")", ")", "{", "final", "List", "<", "Json", ">", "list", "=", "sources", ".", "asJsonList", "(", ")", ";", "list", ".", "removeIf", "(", "item", "->", "item", ".", "isString", "(", ")", "&&", "(", "item", ".", "asString", "(", ")", ".", "endsWith", "(", "\"", "JSASS_CUSTOM.scss", "\"", ")", "||", "item", ".", "asString", "(", ")", ".", "endsWith", "(", "\"", "JSASS_PRE_IMPORT.scss", "\"", ")", "||", "item", ".", "asString", "(", ")", ".", "endsWith", "(", "\"", "JSASS_POST_IMPORT.scss", "\"", ")", ")", ")", ";", "}", "final", "Json", "sourcesContent", "=", "json", ".", "at", "(", "\"", "sourcesContent", "\"", ")", ";", "if", "(", "null", "!=", "sourcesContent", "&&", "sourcesContent", ".", "isArray", "(", ")", ")", "{", "final", "List", "<", "Json", ">", "list", "=", "sourcesContent", ".", "asJsonList", "(", ")", ";", "list", ".", "removeIf", "(", "item", "->", "item", ".", "isString", "(", ")", "&&", "(", "item", ".", "asString", "(", ")", ".", "startsWith", "(", "\"", "$jsass", "\"", ")", ")", ")", ";", "}", "return", "new", "Output", "(", "output", ".", "getCss", "(", ")", ",", "json", ".", "toString", "(", ")", ")", ";", "}", "public", "static", "String", "sass2scss", "(", "String", "source", ",", "int", "options", ")", "{", "return", "NativeAdapter", ".", "sass2scss", "(", "source", ",", "options", ")", ";", "}", "}" ]
The compiler compiles SCSS files, strings and contexts.
[ "The", "compiler", "compiles", "SCSS", "files", "strings", "and", "contexts", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
2008b54a18b4ec3a9e038b215e7afb42a72b039c
Y-sir/spark-cn
sql/core/target/java/org/apache/spark/sql/execution/streaming/state/SymmetricHashJoinStateManager.java
[ "BSD-2-Clause", "Apache-2.0", "CC0-1.0", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
Java
SymmetricHashJoinStateManager
/** * Helper class to manage state required by a single side of {@link StreamingSymmetricHashJoinExec}. * The interface of this class is basically that of a multi-map: * - Get: Returns an iterator of multiple values for given key * - Append: Append a new value to the given key * - Remove Data by predicate: Drop any state using a predicate condition on keys or values * <p> * param: joinSide Defines the join side * param: inputValueAttributes Attributes of the input row which will be stored as value * param: joinKeys Expressions to generate rows that will be used to key the value rows * param: stateInfo Information about how to retrieve the correct version of state * param: storeConf Configuration for the state store. * param: hadoopConf Hadoop configuration for reading state data from storage * <p> * Internally, the key -> multiple values is stored in two {@link StateStore}s. * - Store 1 ({@link KeyToNumValuesStore}) maintains mapping between key -> number of values * - Store 2 ({@link KeyWithIndexToValueStore}) maintains mapping between (key, index) -> value * - Put: update count in KeyToNumValuesStore, * insert new (key, count) -> value in KeyWithIndexToValueStore * - Get: read count from KeyToNumValuesStore, * read each of the n values in KeyWithIndexToValueStore * - Remove state by predicate on keys: * scan all keys in KeyToNumValuesStore to find keys that do match the predicate, * delete from key from KeyToNumValuesStore, delete values in KeyWithIndexToValueStore * - Remove state by condition on values: * scan all [(key, index) -> value] in KeyWithIndexToValueStore to find values that match * the predicate, delete corresponding (key, indexToDelete) from KeyWithIndexToValueStore * by overwriting with the value of (key, maxIndex), and removing [(key, maxIndex), * decrement corresponding num values in KeyToNumValuesStore */
Helper class to manage state required by a single side of StreamingSymmetricHashJoinExec.
[ "Helper", "class", "to", "manage", "state", "required", "by", "a", "single", "side", "of", "StreamingSymmetricHashJoinExec", "." ]
public class SymmetricHashJoinStateManager implements org.apache.spark.internal.Logging { static public interface StateStoreType { } static public scala.collection.Seq<java.lang.String> allStateStoreNames (scala.collection.Seq<org.apache.spark.sql.execution.streaming.StreamingSymmetricHashJoinHelper.JoinSide> joinSides) { throw new RuntimeException(); } public org.apache.spark.sql.execution.streaming.StreamingSymmetricHashJoinHelper.JoinSide joinSide () { throw new RuntimeException(); } // not preceding public SymmetricHashJoinStateManager (org.apache.spark.sql.execution.streaming.StreamingSymmetricHashJoinHelper.JoinSide joinSide, scala.collection.Seq<org.apache.spark.sql.catalyst.expressions.Attribute> inputValueAttributes, scala.collection.Seq<org.apache.spark.sql.catalyst.expressions.Expression> joinKeys, scala.Option<org.apache.spark.sql.execution.streaming.StatefulOperatorStateInfo> stateInfo, org.apache.spark.sql.execution.streaming.state.StateStoreConf storeConf, org.apache.hadoop.conf.Configuration hadoopConf) { throw new RuntimeException(); } /** Get all the values of a key */ public scala.collection.Iterator<org.apache.spark.sql.catalyst.expressions.UnsafeRow> get (org.apache.spark.sql.catalyst.expressions.UnsafeRow key) { throw new RuntimeException(); } /** Append a new value to the key */ public void append (org.apache.spark.sql.catalyst.expressions.UnsafeRow key, org.apache.spark.sql.catalyst.expressions.UnsafeRow value) { throw new RuntimeException(); } /** * Remove using a predicate on keys. * <p> * This produces an iterator over the (key, value) pairs satisfying condition(key), where the * underlying store is updated as a side-effect of producing next. * <p> * This implies the iterator must be consumed fully without any other operations on this manager * or the underlying store being interleaved. * @param removalCondition (undocumented) * @return (undocumented) */ public scala.collection.Iterator<org.apache.spark.sql.execution.streaming.state.UnsafeRowPair> removeByKeyCondition (scala.Function1<org.apache.spark.sql.catalyst.expressions.UnsafeRow, java.lang.Object> removalCondition) { throw new RuntimeException(); } /** * Remove using a predicate on values. * <p> * At a high level, this produces an iterator over the (key, value) pairs such that value * satisfies the predicate, where producing an element removes the value from the state store * and producing all elements with a given key updates it accordingly. * <p> * This implies the iterator must be consumed fully without any other operations on this manager * or the underlying store being interleaved. * @param removalCondition (undocumented) * @return (undocumented) */ public scala.collection.Iterator<org.apache.spark.sql.execution.streaming.state.UnsafeRowPair> removeByValueCondition (scala.Function1<org.apache.spark.sql.catalyst.expressions.UnsafeRow, java.lang.Object> removalCondition) { throw new RuntimeException(); } /** Commit all the changes to all the state stores */ public void commit () { throw new RuntimeException(); } /** Abort any changes to the state stores if needed */ public void abortIfNeeded () { throw new RuntimeException(); } /** Get the combined metrics of all the state stores */ public org.apache.spark.sql.execution.streaming.state.StateStoreMetrics metrics () { throw new RuntimeException(); } }
[ "public", "class", "SymmetricHashJoinStateManager", "implements", "org", ".", "apache", ".", "spark", ".", "internal", ".", "Logging", "{", "static", "public", "interface", "StateStoreType", "{", "}", "static", "public", "scala", ".", "collection", ".", "Seq", "<", "java", ".", "lang", ".", "String", ">", "allStateStoreNames", "(", "scala", ".", "collection", ".", "Seq", "<", "org", ".", "apache", ".", "spark", ".", "sql", ".", "execution", ".", "streaming", ".", "StreamingSymmetricHashJoinHelper", ".", "JoinSide", ">", "joinSides", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "public", "org", ".", "apache", ".", "spark", ".", "sql", ".", "execution", ".", "streaming", ".", "StreamingSymmetricHashJoinHelper", ".", "JoinSide", "joinSide", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "public", "SymmetricHashJoinStateManager", "(", "org", ".", "apache", ".", "spark", ".", "sql", ".", "execution", ".", "streaming", ".", "StreamingSymmetricHashJoinHelper", ".", "JoinSide", "joinSide", ",", "scala", ".", "collection", ".", "Seq", "<", "org", ".", "apache", ".", "spark", ".", "sql", ".", "catalyst", ".", "expressions", ".", "Attribute", ">", "inputValueAttributes", ",", "scala", ".", "collection", ".", "Seq", "<", "org", ".", "apache", ".", "spark", ".", "sql", ".", "catalyst", ".", "expressions", ".", "Expression", ">", "joinKeys", ",", "scala", ".", "Option", "<", "org", ".", "apache", ".", "spark", ".", "sql", ".", "execution", ".", "streaming", ".", "StatefulOperatorStateInfo", ">", "stateInfo", ",", "org", ".", "apache", ".", "spark", ".", "sql", ".", "execution", ".", "streaming", ".", "state", ".", "StateStoreConf", "storeConf", ",", "org", ".", "apache", ".", "hadoop", ".", "conf", ".", "Configuration", "hadoopConf", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "/** Get all the values of a key */", "public", "scala", ".", "collection", ".", "Iterator", "<", "org", ".", "apache", ".", "spark", ".", "sql", ".", "catalyst", ".", "expressions", ".", "UnsafeRow", ">", "get", "(", "org", ".", "apache", ".", "spark", ".", "sql", ".", "catalyst", ".", "expressions", ".", "UnsafeRow", "key", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "/** Append a new value to the key */", "public", "void", "append", "(", "org", ".", "apache", ".", "spark", ".", "sql", ".", "catalyst", ".", "expressions", ".", "UnsafeRow", "key", ",", "org", ".", "apache", ".", "spark", ".", "sql", ".", "catalyst", ".", "expressions", ".", "UnsafeRow", "value", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "/**\n * Remove using a predicate on keys.\n * <p>\n * This produces an iterator over the (key, value) pairs satisfying condition(key), where the\n * underlying store is updated as a side-effect of producing next.\n * <p>\n * This implies the iterator must be consumed fully without any other operations on this manager\n * or the underlying store being interleaved.\n * @param removalCondition (undocumented)\n * @return (undocumented)\n */", "public", "scala", ".", "collection", ".", "Iterator", "<", "org", ".", "apache", ".", "spark", ".", "sql", ".", "execution", ".", "streaming", ".", "state", ".", "UnsafeRowPair", ">", "removeByKeyCondition", "(", "scala", ".", "Function1", "<", "org", ".", "apache", ".", "spark", ".", "sql", ".", "catalyst", ".", "expressions", ".", "UnsafeRow", ",", "java", ".", "lang", ".", "Object", ">", "removalCondition", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "/**\n * Remove using a predicate on values.\n * <p>\n * At a high level, this produces an iterator over the (key, value) pairs such that value\n * satisfies the predicate, where producing an element removes the value from the state store\n * and producing all elements with a given key updates it accordingly.\n * <p>\n * This implies the iterator must be consumed fully without any other operations on this manager\n * or the underlying store being interleaved.\n * @param removalCondition (undocumented)\n * @return (undocumented)\n */", "public", "scala", ".", "collection", ".", "Iterator", "<", "org", ".", "apache", ".", "spark", ".", "sql", ".", "execution", ".", "streaming", ".", "state", ".", "UnsafeRowPair", ">", "removeByValueCondition", "(", "scala", ".", "Function1", "<", "org", ".", "apache", ".", "spark", ".", "sql", ".", "catalyst", ".", "expressions", ".", "UnsafeRow", ",", "java", ".", "lang", ".", "Object", ">", "removalCondition", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "/** Commit all the changes to all the state stores */", "public", "void", "commit", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "/** Abort any changes to the state stores if needed */", "public", "void", "abortIfNeeded", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "/** Get the combined metrics of all the state stores */", "public", "org", ".", "apache", ".", "spark", ".", "sql", ".", "execution", ".", "streaming", ".", "state", ".", "StateStoreMetrics", "metrics", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "}" ]
Helper class to manage state required by a single side of {@link StreamingSymmetricHashJoinExec}.
[ "Helper", "class", "to", "manage", "state", "required", "by", "a", "single", "side", "of", "{", "@link", "StreamingSymmetricHashJoinExec", "}", "." ]
[ "// not preceding" ]
[ { "param": "org.apache.spark.internal.Logging", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "org.apache.spark.internal.Logging", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
20107003ba4f1fc5bb8e3b674364fd601b00b1ef
Lemaf/tms2image
src/main/java/br/ufla/tmsmap/T2.java
[ "MIT" ]
Java
T2
/** * Created by rthoth on 15/03/16. */
Created by rthoth on 15/03/16.
[ "Created", "by", "rthoth", "on", "15", "/", "03", "/", "16", "." ]
public class T2<T1, T2> { public final T1 _1; public final T2 _2; public T2(T1 _1, T2 _2) { this._1 = _1; this._2 = _2; } }
[ "public", "class", "T2", "<", "T1", ",", "T2", ">", "{", "public", "final", "T1", "_1", ";", "public", "final", "T2", "_2", ";", "public", "T2", "(", "T1", "_1", ",", "T2", "_2", ")", "{", "this", ".", "_1", "=", "_1", ";", "this", ".", "_2", "=", "_2", ";", "}", "}" ]
Created by rthoth on 15/03/16.
[ "Created", "by", "rthoth", "on", "15", "/", "03", "/", "16", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
202401b1633b5944ca9f51f5dbe4a644e7b898ce
vibbits/psimi
calimocho/src/main/java/org/hupo/psi/calimocho/model/DefaultCalimochoDocument.java
[ "CC-BY-4.0" ]
Java
DefaultCalimochoDocument
/** * TODO document this ! * * @author Bruno Aranda (baranda@ebi.ac.uk) * @version $Id$ * @since TODO add POM version */
@author Bruno Aranda (baranda@ebi.ac.uk) @version $Id$ @since TODO add POM version
[ "@author", "Bruno", "Aranda", "(", "baranda@ebi", ".", "ac", ".", "uk", ")", "@version", "$Id$", "@since", "TODO", "add", "POM", "version" ]
public class DefaultCalimochoDocument implements CalimochoDocument { private List<Row> rows; public DefaultCalimochoDocument() { rows = new ArrayList<Row>( ); } public List<Row> getRows() { return rows; } public void setRows( List<Row> rows ) { this.rows = rows; } }
[ "public", "class", "DefaultCalimochoDocument", "implements", "CalimochoDocument", "{", "private", "List", "<", "Row", ">", "rows", ";", "public", "DefaultCalimochoDocument", "(", ")", "{", "rows", "=", "new", "ArrayList", "<", "Row", ">", "(", ")", ";", "}", "public", "List", "<", "Row", ">", "getRows", "(", ")", "{", "return", "rows", ";", "}", "public", "void", "setRows", "(", "List", "<", "Row", ">", "rows", ")", "{", "this", ".", "rows", "=", "rows", ";", "}", "}" ]
TODO document this !
[ "TODO", "document", "this", "!" ]
[]
[ { "param": "CalimochoDocument", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "CalimochoDocument", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2026ef895c85825a9a282d13492b0c0b4c5c3c0b
verluci/reversi_bot-A4
src/main/java/com/github/verluci/reversi/game/agents/MCTSAIAgent.java
[ "MIT" ]
Java
MCTSAIAgent
/** * This class contains a GPU accelerated Othello AI based on the MCTS algorithm. * https://en.wikipedia.org/wiki/Monte_Carlo_tree_search * * For the explanation of the data allocation process see the function MCTSHelper.getOptimalMoveUsingOpenCL() * in the package com.github.verluci.reversi.gpgpu; * * For the explanation of the executed kernel-code on the graphics-device see resources/mcts_reversi_kernel.cl */
This class contains a GPU accelerated Othello AI based on the MCTS algorithm. For the explanation of the data allocation process see the function MCTSHelper.getOptimalMoveUsingOpenCL() in the package com.github.verluci.reversi.gpgpu. For the explanation of the executed kernel-code on the graphics-device see resources/mcts_reversi_kernel.cl
[ "This", "class", "contains", "a", "GPU", "accelerated", "Othello", "AI", "based", "on", "the", "MCTS", "algorithm", ".", "For", "the", "explanation", "of", "the", "data", "allocation", "process", "see", "the", "function", "MCTSHelper", ".", "getOptimalMoveUsingOpenCL", "()", "in", "the", "package", "com", ".", "github", ".", "verluci", ".", "reversi", ".", "gpgpu", ".", "For", "the", "explanation", "of", "the", "executed", "kernel", "-", "code", "on", "the", "graphics", "-", "device", "see", "resources", "/", "mcts_reversi_kernel", ".", "cl" ]
public class MCTSAIAgent extends AIAgent { private final GraphicsDevice graphicsDevice; /** * Constructor for MCTSAIAgent * @param graphicsDevice The graphics device the games should be simulated on. */ public MCTSAIAgent(GraphicsDevice graphicsDevice) { this.graphicsDevice = graphicsDevice; } /** * @param board The board on which the optimal tile should be found on. * @return The most optimal tile the MCTS-ai could find. */ @Override protected Tile findOptimalMove(GameBoard board) { // Retrieve all possible moves from the current board. var moves = board.getTilesWithState(TileState.POSSIBLE_MOVE); // Put the moves in the following array: [ move_count, move1, move2, move3, move4, 0, 0, 0, ... ] int[] possibleMoves = new int[board.getXSize() * board.getYSize() + 1]; possibleMoves[0] = moves.size(); for (int i = 0; i < moves.size(); i++) { var move = moves.get(i); possibleMoves[i+1] = (move.getYCoordinate() * board.getXSize()) + move.getXCoordinate(); } // Retrieve the player tiles as a 64-bit (u)long. long player1 = board.getPlayerTilesLongValue(Game.getTileStateUsingPlayer(player)); long player2 = board.getPlayerTilesLongValue(Game.getInvertedTileStateUsingPlayer(player)); // Choose the amount of simulations based on the current state of the game and the strength of the GraphicsDevice. int threadCount = MCTSHelper.calculateThreadCount(graphicsDevice, board); // Estimate the most optimal move with OpenCL using the provided GraphicsDevice and threadCount. int move = MCTSHelper.getOptimalMoveUsingOpenCL(graphicsDevice, player1, player2, possibleMoves, threadCount); // Convert the retrieved optimal tile-index to an x and y coordinate int x = move % board.getXSize(); int y = move / board.getXSize(); // Return the estimated optimal move. return board.getTile(x, y); } /** * setGame() is overriden in MCTSAIAgent because the MCTSAIAgent only works for OthelloGame. * @param game The game this agent should play in. */ @Override public void setGame(Game game) { if(game instanceof OthelloGame) super.setGame(game); else throw new IllegalArgumentException("This MCTS-AI can only be used for Othello/Reversi!"); } }
[ "public", "class", "MCTSAIAgent", "extends", "AIAgent", "{", "private", "final", "GraphicsDevice", "graphicsDevice", ";", "/**\n * Constructor for MCTSAIAgent\n * @param graphicsDevice The graphics device the games should be simulated on.\n */", "public", "MCTSAIAgent", "(", "GraphicsDevice", "graphicsDevice", ")", "{", "this", ".", "graphicsDevice", "=", "graphicsDevice", ";", "}", "/**\n * @param board The board on which the optimal tile should be found on.\n * @return The most optimal tile the MCTS-ai could find.\n */", "@", "Override", "protected", "Tile", "findOptimalMove", "(", "GameBoard", "board", ")", "{", "var", "moves", "=", "board", ".", "getTilesWithState", "(", "TileState", ".", "POSSIBLE_MOVE", ")", ";", "int", "[", "]", "possibleMoves", "=", "new", "int", "[", "board", ".", "getXSize", "(", ")", "*", "board", ".", "getYSize", "(", ")", "+", "1", "]", ";", "possibleMoves", "[", "0", "]", "=", "moves", ".", "size", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "moves", ".", "size", "(", ")", ";", "i", "++", ")", "{", "var", "move", "=", "moves", ".", "get", "(", "i", ")", ";", "possibleMoves", "[", "i", "+", "1", "]", "=", "(", "move", ".", "getYCoordinate", "(", ")", "*", "board", ".", "getXSize", "(", ")", ")", "+", "move", ".", "getXCoordinate", "(", ")", ";", "}", "long", "player1", "=", "board", ".", "getPlayerTilesLongValue", "(", "Game", ".", "getTileStateUsingPlayer", "(", "player", ")", ")", ";", "long", "player2", "=", "board", ".", "getPlayerTilesLongValue", "(", "Game", ".", "getInvertedTileStateUsingPlayer", "(", "player", ")", ")", ";", "int", "threadCount", "=", "MCTSHelper", ".", "calculateThreadCount", "(", "graphicsDevice", ",", "board", ")", ";", "int", "move", "=", "MCTSHelper", ".", "getOptimalMoveUsingOpenCL", "(", "graphicsDevice", ",", "player1", ",", "player2", ",", "possibleMoves", ",", "threadCount", ")", ";", "int", "x", "=", "move", "%", "board", ".", "getXSize", "(", ")", ";", "int", "y", "=", "move", "/", "board", ".", "getXSize", "(", ")", ";", "return", "board", ".", "getTile", "(", "x", ",", "y", ")", ";", "}", "/**\n * setGame() is overriden in MCTSAIAgent because the MCTSAIAgent only works for OthelloGame.\n * @param game The game this agent should play in.\n */", "@", "Override", "public", "void", "setGame", "(", "Game", "game", ")", "{", "if", "(", "game", "instanceof", "OthelloGame", ")", "super", ".", "setGame", "(", "game", ")", ";", "else", "throw", "new", "IllegalArgumentException", "(", "\"", "This MCTS-AI can only be used for Othello/Reversi!", "\"", ")", ";", "}", "}" ]
This class contains a GPU accelerated Othello AI based on the MCTS algorithm.
[ "This", "class", "contains", "a", "GPU", "accelerated", "Othello", "AI", "based", "on", "the", "MCTS", "algorithm", "." ]
[ "// Retrieve all possible moves from the current board.", "// Put the moves in the following array: [ move_count, move1, move2, move3, move4, 0, 0, 0, ... ]", "// Retrieve the player tiles as a 64-bit (u)long.", "// Choose the amount of simulations based on the current state of the game and the strength of the GraphicsDevice.", "// Estimate the most optimal move with OpenCL using the provided GraphicsDevice and threadCount.", "// Convert the retrieved optimal tile-index to an x and y coordinate", "// Return the estimated optimal move." ]
[ { "param": "AIAgent", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AIAgent", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
202dc8a91c46305fa2a713058d8c11c3179f09eb
InterTurstCo/ActiveFrame5
CM5/Core/gui-client-impl/src/main/java/ru/intertrust/cm/core/gui/impl/client/form/widget/hyperlink/LinkedDomainObjectHyperlinkWidget.java
[ "Apache-2.0" ]
Java
LinkedDomainObjectHyperlinkWidget
/** * @author Yaroslav Bondarchuk * Date: 14.01.14 * Time: 10:25 */
@author Yaroslav Bondarchuk Date: 14.01.14 Time: 10:25
[ "@author", "Yaroslav", "Bondarchuk", "Date", ":", "14", ".", "01", ".", "14", "Time", ":", "10", ":", "25" ]
@ComponentName("linked-domain-object-hyperlink") public class LinkedDomainObjectHyperlinkWidget extends TooltipWidget implements HyperlinkStateChangedEventHandler, HasLinkedFormMappings { private LinkedDomainObjectHyperlinkConfig config; public LinkedDomainObjectHyperlinkWidget() { } @Override public Component createNew() { return new LinkedDomainObjectHyperlinkWidget(); } @Override public void setValue(Object value) { //TODO: Implementation required } @Override public void disable(Boolean isDisabled) { //TODO: Implementation required } @Override public void reset() { //TODO: Implementation required } @Override public void applyFilter(String value) { //TODO: Implementation required } @Override public Object getValueTextRepresentation() { return getValue(); } public void setCurrentState(WidgetState currentState) { LinkedDomainObjectHyperlinkState state = (LinkedDomainObjectHyperlinkState) currentState; config = ((LinkedDomainObjectHyperlinkState) currentState).getWidgetConfig(); initialData = currentState; LinkedHashMap<Id, String> listValues = state.getListValues(); HyperlinkNoneEditablePanel panel = (HyperlinkNoneEditablePanel) impl; panel.displayHyperlinks(listValues, WidgetUtil.shouldDrawTooltipButton(state)); } @Override public Object getValue() { return null; } @Override public WidgetState createNewState() { LinkedDomainObjectHyperlinkState state = new LinkedDomainObjectHyperlinkState(); return state; } @Override public WidgetState getFullClientStateCopy() { LinkedDomainObjectHyperlinkState currentState = getInitialData(); LinkedDomainObjectHyperlinkState state = new LinkedDomainObjectHyperlinkState(); state.setWidgetConfig(config); state.setConfig(currentState.getConfig()); state.setSelectedIds(currentState.getIds()); return state; } @Override protected boolean isChanged() { return false; } @Override protected Widget asEditableWidget(WidgetState state) { localEventBus.addHandler(HyperlinkStateChangedEvent.TYPE, this); localEventBus.addHandler(ShowTooltipEvent.TYPE, this); LinkedDomainObjectHyperlinkState linkedDomainObjectHyperlinkState = (LinkedDomainObjectHyperlinkState) state; SelectionStyleConfig selectionStyleConfig = linkedDomainObjectHyperlinkState.getWidgetConfig().getSelectionStyleConfig(); boolean hyperlinkInModalWindow = linkedDomainObjectHyperlinkState.getWidgetConfig().isModalWindow(); return new HyperlinkNoneEditablePanel(selectionStyleConfig, localEventBus, false, linkedDomainObjectHyperlinkState.getTypeTitleMap(), this).withHyperlinkModalWindow(hyperlinkInModalWindow); } @Override protected Widget asNonEditableWidget(WidgetState state) { return asEditableWidget(state); } //TODO common method @Override public void onHyperlinkStateChangedEvent(HyperlinkStateChangedEvent event) { final HyperlinkDisplay hyperlinkDisplay = event.getHyperlinkDisplay(); Id id = event.getId(); List<Id> ids = new ArrayList<Id>(); ids.add(id); String collectionName = config.getCollectionRefConfig() == null ? null : config.getCollectionRefConfig().getName(); RepresentationRequest request = new RepresentationRequest(ids, config.getSelectionPatternConfig().getValue(), collectionName, config.getFormattingConfig()); Command command = new Command("getRepresentationForOneItem", getName(), request); BusinessUniverseServiceAsync.Impl.executeCommand(command, new AsyncCallback<Dto>() { @Override public void onSuccess(Dto result) { RepresentationResponse response = (RepresentationResponse) result; String representation = response.getRepresentation(); Id id = response.getId(); LinkedHashMap<Id, String> listValues = getUpdatedHyperlinks(id, representation); LinkedDomainObjectHyperlinkState state = getInitialData(); hyperlinkDisplay.displayHyperlinks(listValues, WidgetUtil.shouldDrawTooltipButton(state)); } @Override public void onFailure(Throwable caught) { GWT.log("something was going wrong while obtaining hyperlink", caught); } }); } private LinkedHashMap<Id, String> getUpdatedHyperlinks(Id id, String representation) { LinkedDomainObjectHyperlinkState state = getInitialData(); LinkedHashMap<Id, String> listValues = state.getListValues(); listValues.put(id, representation); return listValues; } @Override protected String getTooltipHandlerName() { return getName(); } @Override public LinkedFormMappingConfig getLinkedFormMappingConfig() { return config.getLinkedFormMappingConfig(); } @Override public LinkedFormConfig getLinkedFormConfig() { return config.getLinkedFormConfig(); } }
[ "@", "ComponentName", "(", "\"", "linked-domain-object-hyperlink", "\"", ")", "public", "class", "LinkedDomainObjectHyperlinkWidget", "extends", "TooltipWidget", "implements", "HyperlinkStateChangedEventHandler", ",", "HasLinkedFormMappings", "{", "private", "LinkedDomainObjectHyperlinkConfig", "config", ";", "public", "LinkedDomainObjectHyperlinkWidget", "(", ")", "{", "}", "@", "Override", "public", "Component", "createNew", "(", ")", "{", "return", "new", "LinkedDomainObjectHyperlinkWidget", "(", ")", ";", "}", "@", "Override", "public", "void", "setValue", "(", "Object", "value", ")", "{", "}", "@", "Override", "public", "void", "disable", "(", "Boolean", "isDisabled", ")", "{", "}", "@", "Override", "public", "void", "reset", "(", ")", "{", "}", "@", "Override", "public", "void", "applyFilter", "(", "String", "value", ")", "{", "}", "@", "Override", "public", "Object", "getValueTextRepresentation", "(", ")", "{", "return", "getValue", "(", ")", ";", "}", "public", "void", "setCurrentState", "(", "WidgetState", "currentState", ")", "{", "LinkedDomainObjectHyperlinkState", "state", "=", "(", "LinkedDomainObjectHyperlinkState", ")", "currentState", ";", "config", "=", "(", "(", "LinkedDomainObjectHyperlinkState", ")", "currentState", ")", ".", "getWidgetConfig", "(", ")", ";", "initialData", "=", "currentState", ";", "LinkedHashMap", "<", "Id", ",", "String", ">", "listValues", "=", "state", ".", "getListValues", "(", ")", ";", "HyperlinkNoneEditablePanel", "panel", "=", "(", "HyperlinkNoneEditablePanel", ")", "impl", ";", "panel", ".", "displayHyperlinks", "(", "listValues", ",", "WidgetUtil", ".", "shouldDrawTooltipButton", "(", "state", ")", ")", ";", "}", "@", "Override", "public", "Object", "getValue", "(", ")", "{", "return", "null", ";", "}", "@", "Override", "public", "WidgetState", "createNewState", "(", ")", "{", "LinkedDomainObjectHyperlinkState", "state", "=", "new", "LinkedDomainObjectHyperlinkState", "(", ")", ";", "return", "state", ";", "}", "@", "Override", "public", "WidgetState", "getFullClientStateCopy", "(", ")", "{", "LinkedDomainObjectHyperlinkState", "currentState", "=", "getInitialData", "(", ")", ";", "LinkedDomainObjectHyperlinkState", "state", "=", "new", "LinkedDomainObjectHyperlinkState", "(", ")", ";", "state", ".", "setWidgetConfig", "(", "config", ")", ";", "state", ".", "setConfig", "(", "currentState", ".", "getConfig", "(", ")", ")", ";", "state", ".", "setSelectedIds", "(", "currentState", ".", "getIds", "(", ")", ")", ";", "return", "state", ";", "}", "@", "Override", "protected", "boolean", "isChanged", "(", ")", "{", "return", "false", ";", "}", "@", "Override", "protected", "Widget", "asEditableWidget", "(", "WidgetState", "state", ")", "{", "localEventBus", ".", "addHandler", "(", "HyperlinkStateChangedEvent", ".", "TYPE", ",", "this", ")", ";", "localEventBus", ".", "addHandler", "(", "ShowTooltipEvent", ".", "TYPE", ",", "this", ")", ";", "LinkedDomainObjectHyperlinkState", "linkedDomainObjectHyperlinkState", "=", "(", "LinkedDomainObjectHyperlinkState", ")", "state", ";", "SelectionStyleConfig", "selectionStyleConfig", "=", "linkedDomainObjectHyperlinkState", ".", "getWidgetConfig", "(", ")", ".", "getSelectionStyleConfig", "(", ")", ";", "boolean", "hyperlinkInModalWindow", "=", "linkedDomainObjectHyperlinkState", ".", "getWidgetConfig", "(", ")", ".", "isModalWindow", "(", ")", ";", "return", "new", "HyperlinkNoneEditablePanel", "(", "selectionStyleConfig", ",", "localEventBus", ",", "false", ",", "linkedDomainObjectHyperlinkState", ".", "getTypeTitleMap", "(", ")", ",", "this", ")", ".", "withHyperlinkModalWindow", "(", "hyperlinkInModalWindow", ")", ";", "}", "@", "Override", "protected", "Widget", "asNonEditableWidget", "(", "WidgetState", "state", ")", "{", "return", "asEditableWidget", "(", "state", ")", ";", "}", "@", "Override", "public", "void", "onHyperlinkStateChangedEvent", "(", "HyperlinkStateChangedEvent", "event", ")", "{", "final", "HyperlinkDisplay", "hyperlinkDisplay", "=", "event", ".", "getHyperlinkDisplay", "(", ")", ";", "Id", "id", "=", "event", ".", "getId", "(", ")", ";", "List", "<", "Id", ">", "ids", "=", "new", "ArrayList", "<", "Id", ">", "(", ")", ";", "ids", ".", "add", "(", "id", ")", ";", "String", "collectionName", "=", "config", ".", "getCollectionRefConfig", "(", ")", "==", "null", "?", "null", ":", "config", ".", "getCollectionRefConfig", "(", ")", ".", "getName", "(", ")", ";", "RepresentationRequest", "request", "=", "new", "RepresentationRequest", "(", "ids", ",", "config", ".", "getSelectionPatternConfig", "(", ")", ".", "getValue", "(", ")", ",", "collectionName", ",", "config", ".", "getFormattingConfig", "(", ")", ")", ";", "Command", "command", "=", "new", "Command", "(", "\"", "getRepresentationForOneItem", "\"", ",", "getName", "(", ")", ",", "request", ")", ";", "BusinessUniverseServiceAsync", ".", "Impl", ".", "executeCommand", "(", "command", ",", "new", "AsyncCallback", "<", "Dto", ">", "(", ")", "{", "@", "Override", "public", "void", "onSuccess", "(", "Dto", "result", ")", "{", "RepresentationResponse", "response", "=", "(", "RepresentationResponse", ")", "result", ";", "String", "representation", "=", "response", ".", "getRepresentation", "(", ")", ";", "Id", "id", "=", "response", ".", "getId", "(", ")", ";", "LinkedHashMap", "<", "Id", ",", "String", ">", "listValues", "=", "getUpdatedHyperlinks", "(", "id", ",", "representation", ")", ";", "LinkedDomainObjectHyperlinkState", "state", "=", "getInitialData", "(", ")", ";", "hyperlinkDisplay", ".", "displayHyperlinks", "(", "listValues", ",", "WidgetUtil", ".", "shouldDrawTooltipButton", "(", "state", ")", ")", ";", "}", "@", "Override", "public", "void", "onFailure", "(", "Throwable", "caught", ")", "{", "GWT", ".", "log", "(", "\"", "something was going wrong while obtaining hyperlink", "\"", ",", "caught", ")", ";", "}", "}", ")", ";", "}", "private", "LinkedHashMap", "<", "Id", ",", "String", ">", "getUpdatedHyperlinks", "(", "Id", "id", ",", "String", "representation", ")", "{", "LinkedDomainObjectHyperlinkState", "state", "=", "getInitialData", "(", ")", ";", "LinkedHashMap", "<", "Id", ",", "String", ">", "listValues", "=", "state", ".", "getListValues", "(", ")", ";", "listValues", ".", "put", "(", "id", ",", "representation", ")", ";", "return", "listValues", ";", "}", "@", "Override", "protected", "String", "getTooltipHandlerName", "(", ")", "{", "return", "getName", "(", ")", ";", "}", "@", "Override", "public", "LinkedFormMappingConfig", "getLinkedFormMappingConfig", "(", ")", "{", "return", "config", ".", "getLinkedFormMappingConfig", "(", ")", ";", "}", "@", "Override", "public", "LinkedFormConfig", "getLinkedFormConfig", "(", ")", "{", "return", "config", ".", "getLinkedFormConfig", "(", ")", ";", "}", "}" ]
@author Yaroslav Bondarchuk Date: 14.01.14 Time: 10:25
[ "@author", "Yaroslav", "Bondarchuk", "Date", ":", "14", ".", "01", ".", "14", "Time", ":", "10", ":", "25" ]
[ "//TODO: Implementation required", "//TODO: Implementation required", "//TODO: Implementation required", "//TODO: Implementation required", "//TODO common method" ]
[ { "param": "TooltipWidget", "type": null }, { "param": "HyperlinkStateChangedEventHandler, HasLinkedFormMappings", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "TooltipWidget", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "HyperlinkStateChangedEventHandler, HasLinkedFormMappings", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
202e75a5e2ef26e0a7fc8b8fc007db027caa2700
djey47/tduf
lib-unlimited/src/main/java/fr/tduf/libunlimited/common/game/helper/GameEngineHelper.java
[ "Apache-2.0" ]
Java
GameEngineHelper
/** * Provides methods helping with some game engine specificities */
Provides methods helping with some game engine specificities
[ "Provides", "methods", "helping", "with", "some", "game", "engine", "specificities" ]
public class GameEngineHelper { private GameEngineHelper() {} /** * Converts strings exceeding 8 characters to 8 characters with ASCII code hack. Used for material names, cameras. * Overlapping strings have their ASCII code added to the begin of the String (modulo 8) * e.g FORDGT_02 => xORDGT_0 * F <=> 70, 2 <=> 50, so the first character will be replaced by x <=> (70 + 50) * * @param toBeNormalized - String to be normalized, if necessary * @return normalized string */ public static String normalizeString(String toBeNormalized) { final int MAX_SIZE = 8; if (toBeNormalized == null) { return null; } if (toBeNormalized.length() <= MAX_SIZE) { return toBeNormalized; } char[] basePart = toBeNormalized.substring(0, MAX_SIZE).toCharArray(); char[] overlappingPart = toBeNormalized.substring(MAX_SIZE).toCharArray(); for (int i = 0 ; i < overlappingPart.length ; i++) { basePart[i % MAX_SIZE] += overlappingPart[i]; } return new String(basePart); } }
[ "public", "class", "GameEngineHelper", "{", "private", "GameEngineHelper", "(", ")", "{", "}", "/**\n * Converts strings exceeding 8 characters to 8 characters with ASCII code hack. Used for material names, cameras.\n * Overlapping strings have their ASCII code added to the begin of the String (modulo 8)\n * e.g FORDGT_02 => xORDGT_0\n * F <=> 70, 2 <=> 50, so the first character will be replaced by x <=> (70 + 50)\n *\n * @param toBeNormalized - String to be normalized, if necessary\n * @return normalized string\n */", "public", "static", "String", "normalizeString", "(", "String", "toBeNormalized", ")", "{", "final", "int", "MAX_SIZE", "=", "8", ";", "if", "(", "toBeNormalized", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "toBeNormalized", ".", "length", "(", ")", "<=", "MAX_SIZE", ")", "{", "return", "toBeNormalized", ";", "}", "char", "[", "]", "basePart", "=", "toBeNormalized", ".", "substring", "(", "0", ",", "MAX_SIZE", ")", ".", "toCharArray", "(", ")", ";", "char", "[", "]", "overlappingPart", "=", "toBeNormalized", ".", "substring", "(", "MAX_SIZE", ")", ".", "toCharArray", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "overlappingPart", ".", "length", ";", "i", "++", ")", "{", "basePart", "[", "i", "%", "MAX_SIZE", "]", "+=", "overlappingPart", "[", "i", "]", ";", "}", "return", "new", "String", "(", "basePart", ")", ";", "}", "}" ]
Provides methods helping with some game engine specificities
[ "Provides", "methods", "helping", "with", "some", "game", "engine", "specificities" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
202f79c84bbd660a9168db650f9e20e46cf211c4
Chrisdanyk/test
reservation/src/main/java/org/reservation/web/service/ReservationService.java
[ "Apache-2.0" ]
Java
ReservationService
/** * * @author Ben Kafirongo */
@author Ben Kafirongo
[ "@author", "Ben", "Kafirongo" ]
public class ReservationService extends AbstractService<reservation> { public ReservationService() { super(reservation.class); } @Override protected Predicate[] getSearchPredicates(Root<reservation> root, reservation example) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
[ "public", "class", "ReservationService", "extends", "AbstractService", "<", "reservation", ">", "{", "public", "ReservationService", "(", ")", "{", "super", "(", "reservation", ".", "class", ")", ";", "}", "@", "Override", "protected", "Predicate", "[", "]", "getSearchPredicates", "(", "Root", "<", "reservation", ">", "root", ",", "reservation", "example", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "Not supported yet.", "\"", ")", ";", "}", "}" ]
@author Ben Kafirongo
[ "@author", "Ben", "Kafirongo" ]
[ "//To change body of generated methods, choose Tools | Templates.\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
2032e6dd13ded1e46b3602037877ee18ddd7d8ad
marstona/ovh-java-sdk
ovh-java-sdk-vps/src/main/java/net/minidev/ovh/api/secondarydns/OvhSecondaryDNSNameServer.java
[ "BSD-3-Clause" ]
Java
OvhSecondaryDNSNameServer
/** * A structure describing informations about available nameserver for secondary dns */
A structure describing informations about available nameserver for secondary dns
[ "A", "structure", "describing", "informations", "about", "available", "nameserver", "for", "secondary", "dns" ]
public class OvhSecondaryDNSNameServer { /** * the name server * * canBeNull */ public String hostname; /** * canBeNull */ public String ipv6; /** * canBeNull */ public String ip; }
[ "public", "class", "OvhSecondaryDNSNameServer", "{", "/**\n\t * the name server\n\t *\n\t * canBeNull\n\t */", "public", "String", "hostname", ";", "/**\n\t * canBeNull\n\t */", "public", "String", "ipv6", ";", "/**\n\t * canBeNull\n\t */", "public", "String", "ip", ";", "}" ]
A structure describing informations about available nameserver for secondary dns
[ "A", "structure", "describing", "informations", "about", "available", "nameserver", "for", "secondary", "dns" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
2034f033807e48066f9131613e72a927f853c5e9
adrianeboyd/ANNIS
annis-gui/src/main/java/annis/gui/converter/TreeSetConverter.java
[ "Apache-2.0" ]
Java
TreeSetConverter
/** * * @author Thomas Krause <krauseto@hu-berlin.de> */
@author Thomas Krause
[ "@author", "Thomas", "Krause" ]
public class TreeSetConverter implements Converter<Object, TreeSet> { @Override public TreeSet convertToModel(Object value, Class<? extends TreeSet> targetType, Locale locale) throws ConversionException { TreeSet<String> result = new TreeSet<>(CaseSensitiveOrder.INSTANCE); if(value instanceof Collection<?>) { for(Object item : (Collection<?>) value) { if(item instanceof String) { result.add((String) item); } } Preconditions.checkState(result.size() == ((Collection) value).size(), "Collection which was used with the TreeSetConverter had duplicate entries."); } else if(value instanceof String) { result.add((String) value); } else { throw new IllegalStateException("Value used in the TreeSetConverter is neither a Collection of Strings nor a String"); } return result; } @Override public Object convertToPresentation(TreeSet value, Class<? extends Object> targetType, Locale locale) throws ConversionException { return value; } @Override public Class<TreeSet> getModelType() { return TreeSet.class; } @Override public Class<Object> getPresentationType() { return Object.class; } }
[ "public", "class", "TreeSetConverter", "implements", "Converter", "<", "Object", ",", "TreeSet", ">", "{", "@", "Override", "public", "TreeSet", "convertToModel", "(", "Object", "value", ",", "Class", "<", "?", "extends", "TreeSet", ">", "targetType", ",", "Locale", "locale", ")", "throws", "ConversionException", "{", "TreeSet", "<", "String", ">", "result", "=", "new", "TreeSet", "<", ">", "(", "CaseSensitiveOrder", ".", "INSTANCE", ")", ";", "if", "(", "value", "instanceof", "Collection", "<", "?", ">", ")", "{", "for", "(", "Object", "item", ":", "(", "Collection", "<", "?", ">", ")", "value", ")", "{", "if", "(", "item", "instanceof", "String", ")", "{", "result", ".", "add", "(", "(", "String", ")", "item", ")", ";", "}", "}", "Preconditions", ".", "checkState", "(", "result", ".", "size", "(", ")", "==", "(", "(", "Collection", ")", "value", ")", ".", "size", "(", ")", ",", "\"", "Collection which was used with the TreeSetConverter had duplicate entries.", "\"", ")", ";", "}", "else", "if", "(", "value", "instanceof", "String", ")", "{", "result", ".", "add", "(", "(", "String", ")", "value", ")", ";", "}", "else", "{", "throw", "new", "IllegalStateException", "(", "\"", "Value used in the TreeSetConverter is neither a Collection of Strings nor a String", "\"", ")", ";", "}", "return", "result", ";", "}", "@", "Override", "public", "Object", "convertToPresentation", "(", "TreeSet", "value", ",", "Class", "<", "?", "extends", "Object", ">", "targetType", ",", "Locale", "locale", ")", "throws", "ConversionException", "{", "return", "value", ";", "}", "@", "Override", "public", "Class", "<", "TreeSet", ">", "getModelType", "(", ")", "{", "return", "TreeSet", ".", "class", ";", "}", "@", "Override", "public", "Class", "<", "Object", ">", "getPresentationType", "(", ")", "{", "return", "Object", ".", "class", ";", "}", "}" ]
@author Thomas Krause <krauseto@hu-berlin.de>
[ "@author", "Thomas", "Krause", "<krauseto@hu", "-", "berlin", ".", "de", ">" ]
[]
[ { "param": "Converter<Object, TreeSet>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Converter<Object, TreeSet>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
358d3cde6ad48e2b04f60e4623f4a988a2cbaaf5
isabella232/hsql1
HSQL/src/org/hsqldb1/jdbc/jdbcStatement.java
[ "DOC" ]
Java
jdbcStatement
/** * <!-- start generic documentation --> * The object used for executing a static SQL statement * and returning the results it produces. * <P> * By default, only one <code>ResultSet</code> object per <code>Statement</code> * object can be open at the same time. Therefore, if the reading of one * <code>ResultSet</code> object is interleaved * with the reading of another, each must have been generated by * different <code>Statement</code> objects. All execution methods in the * <code>Statement</code> interface implicitly close a statment's current * <code>ResultSet</code> object if an open one exists.<p> * <!-- end generic documentation--> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3><p> * * <b>JRE 1.1.x Notes:</b> <p> * * In general, JDBC 2 support requires Java 1.2 and above, and JDBC3 requires * Java 1.4 and above. In HSQLDB, support for methods introduced in different * versions of JDBC depends on the JDK version used for compiling and building * HSQLDB.<p> * * Since 1.7.0, all JDBC 2 methods can be called while executing under the * version 1.1.x * <em>Java Runtime Environment</em><sup><font size="-2">TM</font></sup>. * However, in addition to this technique requiring explicit casts to the * org.hsqldb.jdbcXXX classes, some of these method calls require * <code>int</code> values that are defined only in the JDBC 2 or greater * version of the {@link java.sql.ResultSet ResultSet} interface. For this * reason these values are defined in {@link jdbcResultSet jdbcResultSet}.<p> * * In a JRE 1.1.x environment, calling JDBC 2 methods that take or return the * JDBC2-only <code>ResultSet</code> values can be achieved by referring * to them in parameter specifications and return value comparisons, * respectively, as follows: <p> * * <pre class="JavaCodeExample"> * jdbcResultSet.FETCH_FORWARD * jdbcResultSet.TYPE_FORWARD_ONLY * jdbcResultSet.TYPE_SCROLL_INSENSITIVE * jdbcResultSet.CONCUR_READ_ONLY * //etc. * </pre> <p> * * However, please note that code written to use HSQLDB JDBC 2 features under * JDK 1.1.x will not be compatible for use with other JDBC 2 drivers. Please * also note that this feature is offered solely as a convenience to developers * who must work under JDK 1.1.x due to operating constraints, yet wish to * use some of the more advanced features available under the JDBC 2 * specification. <p> * * (fredt@users)<br> * (boucherb@users)<p> * * </div> * <!-- end release-specific documentation --> * * @author boucherb@users * @author fredt@user * @version 1.8.0 * @see jdbcConnection#createStatement * @see jdbcResultSet */
The object used for executing a static SQL statement and returning the results it produces. By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists. HSQLDB-Specific Information: In general, JDBC 2 support requires Java 1.2 and above, and JDBC3 requires Java 1.4 and above. In HSQLDB, support for methods introduced in different versions of JDBC depends on the JDK version used for compiling and building HSQLDB. Since 1.7.0, all JDBC 2 methods can be called while executing under the version 1.1.x Java Runtime EnvironmentTM. However, in addition to this technique requiring explicit casts to the org.hsqldb.jdbcXXX classes, some of these method calls require int values that are defined only in the JDBC 2 or greater version of the java.sql.ResultSet ResultSet interface. For this reason these values are defined in jdbcResultSet jdbcResultSet. In a JRE 1.1.x environment, calling JDBC 2 methods that take or return the JDBC2-only ResultSet values can be achieved by referring to them in parameter specifications and return value comparisons, respectively, as follows: However, please note that code written to use HSQLDB JDBC 2 features under JDK 1.1.x will not be compatible for use with other JDBC 2 drivers. Please also note that this feature is offered solely as a convenience to developers who must work under JDK 1.1.x due to operating constraints, yet wish to use some of the more advanced features available under the JDBC 2 specification. (fredt@users) (boucherb@users)
[ "The", "object", "used", "for", "executing", "a", "static", "SQL", "statement", "and", "returning", "the", "results", "it", "produces", ".", "By", "default", "only", "one", "ResultSet", "object", "per", "Statement", "object", "can", "be", "open", "at", "the", "same", "time", ".", "Therefore", "if", "the", "reading", "of", "one", "ResultSet", "object", "is", "interleaved", "with", "the", "reading", "of", "another", "each", "must", "have", "been", "generated", "by", "different", "Statement", "objects", ".", "All", "execution", "methods", "in", "the", "Statement", "interface", "implicitly", "close", "a", "statment", "'", "s", "current", "ResultSet", "object", "if", "an", "open", "one", "exists", ".", "HSQLDB", "-", "Specific", "Information", ":", "In", "general", "JDBC", "2", "support", "requires", "Java", "1", ".", "2", "and", "above", "and", "JDBC3", "requires", "Java", "1", ".", "4", "and", "above", ".", "In", "HSQLDB", "support", "for", "methods", "introduced", "in", "different", "versions", "of", "JDBC", "depends", "on", "the", "JDK", "version", "used", "for", "compiling", "and", "building", "HSQLDB", ".", "Since", "1", ".", "7", ".", "0", "all", "JDBC", "2", "methods", "can", "be", "called", "while", "executing", "under", "the", "version", "1", ".", "1", ".", "x", "Java", "Runtime", "EnvironmentTM", ".", "However", "in", "addition", "to", "this", "technique", "requiring", "explicit", "casts", "to", "the", "org", ".", "hsqldb", ".", "jdbcXXX", "classes", "some", "of", "these", "method", "calls", "require", "int", "values", "that", "are", "defined", "only", "in", "the", "JDBC", "2", "or", "greater", "version", "of", "the", "java", ".", "sql", ".", "ResultSet", "ResultSet", "interface", ".", "For", "this", "reason", "these", "values", "are", "defined", "in", "jdbcResultSet", "jdbcResultSet", ".", "In", "a", "JRE", "1", ".", "1", ".", "x", "environment", "calling", "JDBC", "2", "methods", "that", "take", "or", "return", "the", "JDBC2", "-", "only", "ResultSet", "values", "can", "be", "achieved", "by", "referring", "to", "them", "in", "parameter", "specifications", "and", "return", "value", "comparisons", "respectively", "as", "follows", ":", "However", "please", "note", "that", "code", "written", "to", "use", "HSQLDB", "JDBC", "2", "features", "under", "JDK", "1", ".", "1", ".", "x", "will", "not", "be", "compatible", "for", "use", "with", "other", "JDBC", "2", "drivers", ".", "Please", "also", "note", "that", "this", "feature", "is", "offered", "solely", "as", "a", "convenience", "to", "developers", "who", "must", "work", "under", "JDK", "1", ".", "1", ".", "x", "due", "to", "operating", "constraints", "yet", "wish", "to", "use", "some", "of", "the", "more", "advanced", "features", "available", "under", "the", "JDBC", "2", "specification", ".", "(", "fredt@users", ")", "(", "boucherb@users", ")" ]
public class jdbcStatement implements Statement { /** * Whether this Statement has been explicitly closed. A jdbcConnection * object now explicitly closes all of its open jdbcXXXStatement objects * when it is closed. */ volatile boolean isClosed; /** Is escape processing enabled? */ private boolean isEscapeProcessing = true; /** The connection used to execute this statement. */ protected jdbcConnection connection; /** The maximum number of rows to generate when executing this statement. */ protected int maxRows; /** The result of executing this statement. */ protected Result resultIn; /** The result set type obtained by executing this statement. */ protected int rsType = jdbcResultSet.TYPE_FORWARD_ONLY; /** Used by this statement to communicate non-batched requests. */ protected Result resultOut = new Result(ResultConstants.SQLEXECDIRECT); /** Use by this statement to communicate batched execution requests */ protected Result batchResultOut = null; // boucherb@users // NOTE: // This method is synchronized since resultIn is an instance attribute // and thus it is theoretically possible that a race condition occurs // in which a different thread executes fetchResult(sql), replacing // resultIn before it gets assigned propery to the new result set. // fredt - this class is not supposed to be called multi-threaded - // For example, if two threads call execute() then both call getResult() in // the wrong order, the ResultSet object for one call could actually belong // to the other call. /** * <!-- start generic documentation --> * Executes the given SQL statement, which returns a single * <code>ResultSet</code> object. <p> * <!-- end generic documentation --> * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * This method should not be used for statements other than SELECT queries.<p> * * Including 1.7.2, HSQLDB does not throw an exception when the statement * is a DDL statement or an UPDATE or DELETE statement. This will certainly * change in future version. * </div> * <!-- end release-specific documentation --> * * @param sql an SQL statement to be sent to the database, typically a * static SQL <code>SELECT</code> statement * @return a <code>ResultSet</code> object that contains the data produced * by the given query; never <code>null</code> * @exception SQLException if a database access error occurs or the given * SQL statement produces anything other than a single * <code>ResultSet</code> object */ public ResultSet executeQuery(String sql) throws SQLException { checkClosed(); connection.clearWarningsNoCheck(); fetchResult(sql); return new jdbcResultSet(this, resultIn, connection.connProperties, connection.isNetConn); } /** * <!-- start generic documentation --> * Executes the given SQL statement, which may be an <code>INSERT</code>, * <code>UPDATE</code>, or <code>DELETE</code> statement or an * SQL statement that returns nothing, such as an SQL DDL statement. <p> * <!-- end generic documentation --> * * @param sql an SQL <code>INSERT</code>, <code>UPDATE</code> or * <code>DELETE</code> statement or an SQL statement that returns nothing * @return either the row count for <code>INSERT</code>, <code>UPDATE</code> * or <code>DELETE</code> statements, or <code>0</code> for SQL statements * that return nothing * @exception SQLException if a database access error occurs or the given * SQL statement produces a <code>ResultSet</code> object */ public int executeUpdate(String sql) throws SQLException { checkClosed(); connection.clearWarningsNoCheck(); fetchResult(sql); if (resultIn == null || resultIn.isData()) { /** * @todo: - fredt@users - check for type of statement _must_ be done * in the engine and error returned _without_ executing */ throw new SQLException( Trace.getMessage(Trace.jdbcStatement_executeUpdate)); } else if (resultIn.isError()) { Util.throwError(resultIn); } return resultIn.getUpdateCount(); } /** * <!-- start generic documentation --> * Releases this <code>Statement</code> object's database * and JDBC resources immediately instead of waiting for * this to happen when it is automatically closed. * It is generally good practice to release resources as soon as * you are finished with them to avoid tying up database * resources. * <P> * Calling the method <code>close</code> on a <code>Statement</code> * object that is already closed has no effect. * <P> * <B>Note:</B> A <code>Statement</code> object is automatically closed * when it is garbage collected. When a <code>Statement</code> object is * closed, its current <code>ResultSet</code> object, if one exists, is * also closed. <p> * <!-- end generic documentation --> * * @exception SQLException if a database access error occurs */ public synchronized void close() throws SQLException { if (isClosed) { return; } batchResultOut = null; connection = null; resultIn = null; resultOut = null; isClosed = true; } //---------------------------------------------------------------------- /** * <!-- start generic documentation --> * Retrieves the maximum number of bytes that can be * returned for character and binary column values in a <code>ResultSet</code> * object produced by this <code>Statement</code> object. * This limit applies only to <code>BINARY</code>, * <code>VARBINARY</code>, <code>LONGVARBINARY</code>, <code>CHAR</code>, * <code>VARCHAR</code>, and <code>LONGVARCHAR</code> * columns. If the limit is exceeded, the excess data is silently * discarded. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Including 1.7.2, HSQLDB always returns zero, meaning there * is no limit. * </div> * <!-- end release-specific documentation --> * * @return the current column size limit for columns storing character and * binary values; zero means there is no limit * @exception SQLException if a database access error occurs * @see #setMaxFieldSize */ public int getMaxFieldSize() throws SQLException { checkClosed(); return 0; } /** * <!-- start generic documentation --> * Sets the limit for the maximum number of bytes in a <code>ResultSet</code> * column storing character or binary values to * the given number of bytes. This limit applies * only to <code>BINARY</code>, <code>VARBINARY</code>, * <code>LONGVARBINARY</code>, <code>CHAR</code>, <code>VARCHAR</code>, and * <code>LONGVARCHAR</code> fields. If the limit is exceeded, the excess data * is silently discarded. For maximum portability, use values * greater than 256. <p> * <!-- emd generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Including 1.7.2, calls to this method are simply ignored; HSQLDB always * stores the full number of bytes when dealing with any of the field types * mentioned above. These types all have an absolute maximum element upper * bound determined by the Java array index limit * java.lang.Integer.MAX_VALUE. For XXXBINARY types, this translates to * Integer.MAX_VALUE bytes. For XXXCHAR types, this translates to * 2 * Integer.MAX_VALUE bytes (2 bytes / character) * </div> * <!-- end release-specific documentation --> * * @param max the new column size limit in bytes; zero means there is no limit * @exception SQLException if a database access error occurs * or the condition max >= 0 is not satisfied * @see #getMaxFieldSize */ public void setMaxFieldSize(int max) throws SQLException { checkClosed(); if (max < 0) { throw Util.sqlException(Trace.INVALID_JDBC_ARGUMENT); } } /** * <!-- start generic documentation --> * Retrieves the maximum number of rows that a * <code>ResultSet</code> object produced by this * <code>Statement</code> object can contain. If this limit is exceeded, * the excess rows are silently dropped. <p> * <!-- start generic documentation --> * * @return the current maximum number of rows for a <code>ResultSet</code> * object produced by this <code>Statement</code> object; * zero means there is no limit * @exception SQLException if a database access error occurs * @see #setMaxRows */ public int getMaxRows() throws SQLException { checkClosed(); return maxRows; } /** * <!-- start generic documentation --> * Sets the limit for the maximum number of rows that any * <code>ResultSet</code> object can contain to the given number. * If the limit is exceeded, the excess * rows are silently dropped. <p> * <!-- end generic documentation --> * * @param max the new max rows limit; zero means there is no limit * @exception SQLException if a database access error occurs * or the condition max >= 0 is not satisfied * @see #getMaxRows */ public void setMaxRows(int max) throws SQLException { checkClosed(); if (max < 0) { throw Util.sqlException(Trace.INVALID_JDBC_ARGUMENT); } maxRows = max; } /** * <!-- start generic documentation --> * Sets escape processing on or off. * If escape scanning is on (the default), the driver will do * escape substitution before sending the SQL statement to the database. * * Note: Since prepared statements have usually been parsed prior * to making this call, disabling escape processing for * <code>PreparedStatements</code> objects will have no effect. <p> * <!-- end generic documentation --> * * @param enable <code>true</code> to enable escape processing; * <code>false</code> to disable it * @exception SQLException if a database access error occurs */ public void setEscapeProcessing(boolean enable) throws SQLException { checkClosed(); isEscapeProcessing = enable; } /** * <!-- start generic documentation --> * Retrieves the number of seconds the driver will * wait for a <code>Statement</code> object to execute. If the * limit is exceeded, an <code>SQLException</code> is thrown. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Including 1.7.2, HSQLDB always returns zero, meaning there * is no limit. * </div> * <!-- end release-specific documentation --> * * @return the current query timeout limit in seconds; zero means there is * no limit * @exception SQLException if a database access error occurs * @see #setQueryTimeout */ public int getQueryTimeout() throws SQLException { checkClosed(); return 0; } /** * <!-- start generic documentation --> * Sets the number of seconds the driver will wait for a * <code>Statement</code> object to execute to the given number of seconds. * If the limit is exceeded, an <code>SQLException</code> is thrown. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Including 1.7.2, calls to this method are ignored; HSQLDB waits an * unlimited amount of time for statement execution * requests to return. * </div> * <!-- end release-specific documentation --> * * @param seconds the new query timeout limit in seconds; zero means * there is no limit * @exception SQLException if a database access error occurs * or the condition seconds >= 0 is not satisfied * @see #getQueryTimeout */ public void setQueryTimeout(int seconds) throws SQLException { checkClosed(); if (seconds < 0) { throw Util.sqlException(Trace.INVALID_JDBC_ARGUMENT); } } /** * <!-- start generic documentation --> * Cancels this <code>Statement</code> object if both the DBMS and * driver support aborting an SQL statement. * This method can be used by one thread to cancel a statement that * is being executed by another thread. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Including 1.7.2, HSQLDB does <i>not</i> support aborting a SQL * statement; calls to this method are ignored. * </div> * <!-- end release-specific documentation --> * * @exception SQLException if a database access error occurs */ public void cancel() throws SQLException { checkClosed(); } /** * <!-- start generic documentation --> * Retrieves the first warning reported by calls on this <code>Statement</code> object. * Subsequent <code>Statement</code> object warnings will be chained to this * <code>SQLWarning</code> object. * * <p>The warning chain is automatically cleared each time * a statement is (re)executed. This method may not be called on a closed * <code>Statement</code> object; doing so will cause an <code>SQLException</code> * to be thrown. * * <P><B>Note:</B> If you are processing a <code>ResultSet</code> object, any * warnings associated with reads on that <code>ResultSet</code> object * will be chained on it rather than on the <code>Statement</code> * object that produced it. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Including 1.7.2, HSQLDB never produces Statement warnings; * this method always returns null. * </div> * <!-- end release-specific documentation --> * * @return the first <code>SQLWarning</code> object or <code>null</code> * if there are no warnings * @exception SQLException if a database access error occurs or this * method is called on a closed statement */ public SQLWarning getWarnings() throws SQLException { checkClosed(); return null; } /** * <!-- start generic documentation --> * Clears all the warnings reported on this <code>Statement</code> * object. After a call to this method, * the method <code>getWarnings</code> will return * <code>null</code> until a new warning is reported for this * <code>Statement</code> object. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Including HSQLDB 1.7.2, <code>SQLWarning</code> objects are * never produced for Statement Objects; calls to this method are * ignored. * </div> * <!-- end release-specific documentation --> * * @exception SQLException if a database access error occurs */ public void clearWarnings() throws SQLException { checkClosed(); } /** * <!-- start generic documentation --> * Sets the SQL cursor name to the given <code>String</code>, which * will be used by subsequent <code>Statement</code> object * <code>execute</code> methods. This name can then be * used in SQL positioned update or delete statements to identify the * current row in the <code>ResultSet</code> object generated by this * statement. If the database does not support positioned update/delete, * this method is a noop. To insure that a cursor has the proper isolation * level to support updates, the cursor's <code>SELECT</code> statement * should have the form <code>SELECT FOR UPDATE</code>. If * <code>FOR UPDATE</code> is not present, positioned updates may fail. * * <P><B>Note:</B> By definition, the execution of positioned updates and * deletes must be done by a different <code>Statement</code> object than * the one that generated the <code>ResultSet</code> object being used for * positioning. Also, cursor names must be unique within a connection. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Including 1.7.2, HSQLDB does not support named cursors, * updateable results or table locking via <code>SELECT FOR UPDATE</code>; * calls to this method are ignored. * </div> * <!-- end release-specific documentation --> * * @param name the new cursor name, which must be unique within * a connection * @exception SQLException if a database access error occurs */ public void setCursorName(String name) throws SQLException { checkClosed(); } //----------------------- Multiple Results -------------------------- /** * <!-- start generic documentation --> * Executes the given SQL statement, which may return multiple results. * In some (uncommon) situations, a single SQL statement may return * multiple result sets and/or update counts. Normally you can ignore * this unless you are (1) executing a stored procedure that you know may * return multiple results or (2) you are dynamically executing an * unknown SQL string. * <P> * The <code>execute</code> method executes an SQL statement and indicates the * form of the first result. You must then use the methods * <code>getResultSet</code> or <code>getUpdateCount</code> * to retrieve the result, and <code>getMoreResults</code> to * move to any subsequent result(s). <p> * <!-- end generic documentation --> * * @param sql any SQL statement * @return <code>true</code> if the first result is a <code>ResultSet</code> * object; <code>false</code> if it is an update count or there are * no results * @exception SQLException if a database access error occurs * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults */ public boolean execute(String sql) throws SQLException { checkClosed(); connection.clearWarningsNoCheck(); fetchResult(sql); return resultIn.isData(); } /** * <!-- start generic documentation --> * Retrieves the current result as a <code>ResultSet</code> object. * This method should be called only once per result. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Without an interceding call to executeXXX, each invocation of this * method will produce a new, initialized ResultSet instance referring to * the current result, if any. * </div> * <!-- end release-specific documentation --> * * @return the current result as a <code>ResultSet</code> object or * <code>null</code> if the result is an update count or there * are no more results * @exception SQLException if a database access error occurs * @see #execute */ public ResultSet getResultSet() throws SQLException { checkClosed(); return resultIn == null || !resultIn.isData() ? null : new jdbcResultSet(this, resultIn, connection.connProperties, connection.isNetConn); } /** * <!-- start generic documentation --> * Retrieves the current result as an update count; * if the result is a <code>ResultSet</code> object or there are no more results, -1 * is returned. This method should be called only once per result. <p> * <!-- end generic documentation --> * * @return the current result as an update count; -1 if the current result is a * <code>ResultSet</code> object or there are no more results * @exception SQLException if a database access error occurs * @see #execute */ public int getUpdateCount() throws SQLException { // fredt - omit checkClosed() in order to be able to handle the result of a // SHUTDOWN query // checkClosed(); return (resultIn == null || resultIn.isData()) ? -1 : resultIn .getUpdateCount(); } /** * <!-- start generic documentation --> * Moves to this <code>Statement</code> object's next result, returns * <code>true</code> if it is a <code>ResultSet</code> object, and * implicitly closes any current <code>ResultSet</code> * object(s) obtained with the method <code>getResultSet</code>. * * <P>There are no more results when the following is true: * <PRE> * <code>(!getMoreResults() && (getUpdateCount() == -1)</code> * </PRE> <p> * <!-- end generic documentation --> * * @return <code>true</code> if the next result is a <code>ResultSet</code> * object; <code>false</code> if it is an update count or there are * no more results * @exception SQLException if a database access error occurs * @see #execute */ public boolean getMoreResults() throws SQLException { checkClosed(); resultIn = null; return false; } //--------------------------JDBC 2.0----------------------------- /** * <!-- start generic documentation --> * Gives the driver a hint as to the direction in which * rows will be processed in <code>ResultSet</code> * objects created using this <code>Statement</code> object. The * default value is <code>ResultSet.FETCH_FORWARD</code>. * <P> * Note that this method sets the default fetch direction for * result sets generated by this <code>Statement</code> object. * Each result set has its own methods for getting and setting * its own fetch direction. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Including 1.7.2, HSQLDB supports only <code>FETCH_FORWARD</code>. <p> * * Setting any other value will throw an <code>SQLException</code> * stating that the operation is not supported. * </div> * <!-- end release-specific documentation --> * * @param direction the initial direction for processing rows * @exception SQLException if a database access error occurs * or the given direction * is not one of <code>ResultSet.FETCH_FORWARD</code>, * <code>ResultSet.FETCH_REVERSE</code>, or * <code>ResultSet.FETCH_UNKNOWN</code> <p> * * HSQLDB throws for all values except <code>FETCH_FORWARD</code> * @since JDK 1.2 (JDK 1.1.x developers: read the new overview * for jdbcStatement) * @see #getFetchDirection */ public void setFetchDirection(int direction) throws SQLException { checkClosed(); if (direction != jdbcResultSet.FETCH_FORWARD) { throw Util.notSupported(); } } /** * <!-- start generic documentation --> * Retrieves the direction for fetching rows from * database tables that is the default for result sets * generated from this <code>Statement</code> object. * If this <code>Statement</code> object has not set * a fetch direction by calling the method <code>setFetchDirection</code>, * the return value is implementation-specific. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Including 1.7.2, HSQLDB always returns FETCH_FORWARD. * </div> * <!-- end release-specific documentation --> * * @return the default fetch direction for result sets generated * from this <code>Statement</code> object * @exception SQLException if a database access error occurs * @since JDK 1.2 (JDK 1.1.x developers: read the new overview * for jdbcStatement) * @see #setFetchDirection */ public int getFetchDirection() throws SQLException { checkClosed(); return jdbcResultSet.FETCH_FORWARD; } /** * <!-- start generic documentation --> * Gives the JDBC driver a hint as to the number of rows that should * be fetched from the database when more rows are needed. The number * of rows specified affects only result sets created using this * statement. If the value specified is zero, then the hint is ignored. * The default value is zero. <p> * <!-- start generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Including 1.7.2, calls to this method are ignored; * HSQLDB fetches each result completely as part of * executing its statement. * </div> * <!-- end release-specific documentation --> * * @param rows the number of rows to fetch * @exception SQLException if a database access error occurs, or the * condition 0 <= <code>rows</code> <= <code>this.getMaxRows()</code> * is not satisfied. <p> * * HSQLDB never throws an exception, since calls to this method * are always ignored. * @since JDK 1.2 (JDK 1.1.x developers: read the new overview * for jdbcStatement) * @see #getFetchSize */ public void setFetchSize(int rows) throws SQLException { checkClosed(); } /** * <!-- start generic documentation --> * Retrieves the number of result set rows that is the default * fetch size for <code>ResultSet</code> objects * generated from this <code>Statement</code> object. * If this <code>Statement</code> object has not set * a fetch size by calling the method <code>setFetchSize</code>, * the return value is implementation-specific. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <b>HSQLDB-Specific Information</b> <p> * * Including 1.7.2, this method always returns 0. * HSQLDB fetches each result completely as part of * executing its statement * </div> * <!-- end release-specific documentation --> * * @return the default fetch size for result sets generated * from this <code>Statement</code> object * @exception SQLException if a database access error occurs * @since JDK 1.2 (JDK 1.1.x developers: read the new overview * for jdbcStatement) * @see #setFetchSize */ public int getFetchSize() throws SQLException { checkClosed(); return 0; } /** * <!-- start generic documentation --> * Retrieves the result set concurrency for <code>ResultSet</code> objects * generated by this <code>Statement</code> object. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Including 1.7.2, HSQLDB supports only * <code>CONCUR_READ_ONLY</code> concurrency. * </div> * <!-- end release-specific documentation --> * * @return either <code>ResultSet.CONCUR_READ_ONLY</code> or * <code>ResultSet.CONCUR_UPDATABLE</code> (not supported) * @exception SQLException if a database access error occurs * @since JDK 1.2 (JDK 1.1.x developers: read the new overview * for jdbcStatement) */ public int getResultSetConcurrency() throws SQLException { checkClosed(); return jdbcResultSet.CONCUR_READ_ONLY; } /** * <!-- start generic documentation --> * Retrieves the result set type for <code>ResultSet</code> objects * generated by this <code>Statement</code> object. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.0 and later versions support <code>TYPE_FORWARD_ONLY</code> * and <code>TYPE_SCROLL_INSENSITIVE</code>. * </div> * <!-- end release-specific documentation --> * * @return one of <code>ResultSet.TYPE_FORWARD_ONLY</code>, * <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or * <code>ResultSet.TYPE_SCROLL_SENSITIVE</code> (not supported) <p> * * <b>Note:</b> Up to and including 1.7.1, HSQLDB never returns * <code>TYPE_SCROLL_SENSITIVE</code> * @exception SQLException if a database access error occurs * @since JDK 1.2 (JDK 1.1.x developers: read the new overview * for jdbcStatement) */ public int getResultSetType() throws SQLException { // fredt - omit checkClosed() in order to be able to handle the result of a // SHUTDOWN query // checkClosed(); return rsType; } /** * <!-- start generic documentation --> * Adds the given SQL command to the current list of commmands for this * <code>Statement</code> object. The commands in this list can be * executed as a batch by calling the method <code>executeBatch</code>. * <P> * <B>NOTE:</B> This method is optional. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, this feature is supported. * </div> * <!-- end release-specific documentation --> * * @param sql typically this is a static SQL <code>INSERT</code> or * <code>UPDATE</code> statement * @exception SQLException if a database access error occurs, or the * driver does not support batch updates * @see #executeBatch * @since JDK 1.2 (JDK 1.1.x developers: read the new overview * for jdbcStatement) */ public void addBatch(String sql) throws SQLException { checkClosed(); if (isEscapeProcessing) { sql = connection.nativeSQL(sql); } if (batchResultOut == null) { batchResultOut = new Result(ResultConstants.BATCHEXECDIRECT, new int[]{ Types.VARCHAR }, 0); } batchResultOut.add(new Object[]{ sql }); } /** * <!-- start generic documentation --> * Empties this <code>Statement</code> object's current list of * SQL commands. * <P> * <B>NOTE:</B> This method is optional. <p> * <!-- start generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with HSQLDB 1.7.2, this feature is supported. * </div> * <!-- end release-specific documentation --> * * @exception SQLException if a database access error occurs or the * driver does not support batch updates * @see #addBatch * @since JDK 1.2 (JDK 1.1.x developers: read the new overview * for jdbcStatement) */ public void clearBatch() throws SQLException { checkClosed(); if (batchResultOut != null) { batchResultOut.clear(); } } /** * <!-- start generic documentation --> * Submits a batch of commands to the database for execution and * if all commands execute successfully, returns an array of update counts. * The <code>int</code> elements of the array that is returned are ordered * to correspond to the commands in the batch, which are ordered * according to the order in which they were added to the batch. * The elements in the array returned by the method <code>executeBatch</code> * may be one of the following: * <OL> * <LI>A number greater than or equal to zero -- indicates that the * command was processed successfully and is an update count giving the * number of rows in the database that were affected by the command's * execution * <LI>A value of <code>SUCCESS_NO_INFO</code> -- indicates that the command was * processed successfully but that the number of rows affected is * unknown * <P> * If one of the commands in a batch update fails to execute properly, * this method throws a <code>BatchUpdateException</code>, and a JDBC * driver may or may not continue to process the remaining commands in * the batch. However, the driver's behavior must be consistent with a * particular DBMS, either always continuing to process commands or never * continuing to process commands. If the driver continues processing * after a failure, the array returned by the method * <code>BatchUpdateException.getUpdateCounts</code> * will contain as many elements as there are commands in the batch, and * at least one of the elements will be the following: * <P> * <LI>A value of <code>EXECUTE_FAILED</code> -- indicates that the command failed * to execute successfully and occurs only if a driver continues to * process commands after a command fails * </OL> * <P> * A driver is not required to implement this method. * The possible implementations and return values have been modified in * the Java 2 SDK, Standard Edition, version 1.3 to * accommodate the option of continuing to proccess commands in a batch * update after a <code>BatchUpdateException</code> obejct has been thrown. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with HSQLDB 1.7.2, this feature is supported. <p> * * HSQLDB stops execution of commands in a batch when one of the commands * results in an exception. The size of the returned array equals the * number of commands that were executed successfully.<p> * * When the product is built under the JAVA1 target, an exception * is never thrown and it is the responsibility of the client software to * check the size of the returned update count array to determine if any * batch items failed. To build and run under the JAVA2 target, JDK/JRE * 1.3 or higher must be used. * </div> * <!-- end release-specific documentation --> * * @return an array of update counts containing one element for each * command in the batch. The elements of the array are ordered according * to the order in which commands were added to the batch. * @exception SQLException if a database access error occurs or the * driver does not support batch statements. Throws * {@link java.sql.BatchUpdateException} * (a subclass of <code>java.sql.SQLException</code>) if one of the commands * sent to the database fails to execute properly or attempts to return a * result set. * @since JDK 1.3 (JDK 1.1.x developers: read the new overview * for jdbcStatement) */ public int[] executeBatch() throws SQLException { int[] updateCounts; int batchCount; HsqlException he; checkClosed(); connection.clearWarningsNoCheck(); if (batchResultOut == null) { batchResultOut = new Result(ResultConstants.BATCHEXECDIRECT, new int[]{ Types.VARCHAR }, 0); } batchCount = batchResultOut.getSize(); try { resultIn = connection.sessionProxy.execute(batchResultOut); } catch (HsqlException e) { batchResultOut.clear(); throw Util.sqlException(e); } batchResultOut.clear(); if (resultIn.isError()) { Util.throwError(resultIn); } updateCounts = resultIn.getUpdateCounts(); //#ifdef JAVA2FULL if (updateCounts.length != batchCount) { throw new BatchUpdateException("failed batch", updateCounts); } //#else /* if (updateCounts.length != batchCount) { throw new SQLException("failed batch, update count: " + updateCounts, ""); } */ //#endif JAVA2 return updateCounts; } /** * <!-- start generic documentation --> * Retrieves the <code>Connection</code> object * that produced this <code>Statement</code> object. <p> * <!-- end generic documentation --> * * @return the connection that produced this statement * @exception SQLException if a database access error occurs * @since JDK 1.2 (JDK 1.1.x developers: read the new overview * for jdbcStatement) */ public Connection getConnection() throws SQLException { checkClosed(); return connection; } //--------------------------JDBC 3.0----------------------------- /** * <!-- start generic documentation --> * Moves to this <code>Statement</code> object's next result, deals with * any current <code>ResultSet</code> object(s) according to the instructions * specified by the given flag, and returns * <code>true</code> if the next result is a <code>ResultSet</code> object. * * <P>There are no more results when the following is true: * <PRE> * <code>(!getMoreResults() && (getUpdateCount() == -1)</code> * </PRE> <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>, * stating that the function is not supported. * </div> * <!-- end release-specific documentation --> * * @param current one of the following <code>Statement</code> * constants indicating what should happen to current * <code>ResultSet</code> objects obtained using the method * <code>getResultSet</code: * <code>CLOSE_CURRENT_RESULT</code>, * <code>KEEP_CURRENT_RESULT</code>, or * <code>CLOSE_ALL_RESULTS</code> * @return <code>true</code> if the next result is a <code>ResultSet</code> * object; <code>false</code> if it is an update count or there are no * more results * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQLDB 1.7 * @see #execute */ //#ifdef JAVA4 public boolean getMoreResults(int current) throws SQLException { throw Util.notSupported(); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves any auto-generated keys created as a result of executing this * <code>Statement</code> object. If this <code>Statement</code> object did * not generate any keys, an empty <code>ResultSet</code> * object is returned. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>, * stating that the function is not supported. * </div> * <!-- end release-specific documentation --> * * @return a <code>ResultSet</code> object containing the auto-generated key(s) * generated by the execution of this <code>Statement</code> object * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQLDB 1.7 */ //#ifdef JAVA4 public ResultSet getGeneratedKeys() throws SQLException { throw Util.notSupported(); } //#endif JAVA4 /** * <!-- start generic documentation --> * Executes the given SQL statement and signals the driver with the * given flag about whether the * auto-generated keys produced by this <code>Statement</code> object * should be made available for retrieval. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>, * stating that the function is not supported. * </div> * <!-- end release-specific documentation --> * * @param sql must be an SQL <code>INSERT</code>, <code>UPDATE</code> or * <code>DELETE</code> statement or an SQL statement that * returns nothing * @param autoGeneratedKeys a flag indicating whether auto-generated keys * should be made available for retrieval; * one of the following constants: * <code>Statement.RETURN_GENERATED_KEYS</code> * <code>Statement.NO_GENERATED_KEYS</code> * @return either the row count for <code>INSERT</code>, <code>UPDATE</code> * or <code>DELETE</code> statements, or <code>0</code> for SQL * statements that return nothing * @exception SQLException if a database access error occurs, the given * SQL statement returns a <code>ResultSet</code> object, or * the given constant is not one of those allowed * @since JDK 1.4, HSQLDB 1.7 */ //#ifdef JAVA4 public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { throw Util.notSupported(); } //#endif JAVA4 /** * <!-- start generic documentation --> * Executes the given SQL statement and signals the driver that the * auto-generated keys indicated in the given array should be made available * for retrieval. The driver will ignore the array if the SQL statement * is not an <code>INSERT</code> statement. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>, * stating that the function is not supported. * </div> * <!-- end release-specific documentation --> * * @param sql an SQL <code>INSERT</code>, <code>UPDATE</code> or * <code>DELETE</code> statement or an SQL statement that returns nothing, * such as an SQL DDL statement * @param columnIndexes an array of column indexes indicating the columns * that should be returned from the inserted row * @return either the row count for <code>INSERT</code>, <code>UPDATE</code>, * or <code>DELETE</code> statements, or 0 for SQL statements * that return nothing * @exception SQLException if a database access error occurs or the SQL * statement returns a <code>ResultSet</code> object * @since JDK 1.4, HSQLDB 1.7 */ //#ifdef JAVA4 public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { throw Util.notSupported(); } //#endif JAVA4 /** * <!-- start generic documentation --> * Executes the given SQL statement and signals the driver that the * auto-generated keys indicated in the given array should be made available * for retrieval. The driver will ignore the array if the SQL statement * is not an <code>INSERT</code> statement. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>, * stating that the function is not supported. * </div> * <!-- end release-specific documentation --> * * @param sql an SQL <code>INSERT</code>, <code>UPDATE</code> or * <code>DELETE</code> statement or an SQL statement that returns nothing * @param columnNames an array of the names of the columns that should be * returned from the inserted row * @return either the row count for <code>INSERT</code>, <code>UPDATE</code>, * or <code>DELETE</code> statements, or 0 for SQL statements * that return nothing * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQLDB 1.7 */ //#ifdef JAVA4 public int executeUpdate(String sql, String[] columnNames) throws SQLException { throw Util.notSupported(); } //#endif JAVA4 /** * <!-- start generic documentation --> * Executes the given SQL statement, which may return multiple results, * and signals the driver that any * auto-generated keys should be made available * for retrieval. The driver will ignore this signal if the SQL statement * is not an <code>INSERT</code> statement. * <P> * In some (uncommon) situations, a single SQL statement may return * multiple result sets and/or update counts. Normally you can ignore * this unless you are (1) executing a stored procedure that you know may * return multiple results or (2) you are dynamically executing an * unknown SQL string. * <P> * The <code>execute</code> method executes an SQL statement and indicates the * form of the first result. You must then use the methods * <code>getResultSet</code> or <code>getUpdateCount</code> * to retrieve the result, and <code>getMoreResults</code> to * move to any subsequent result(s). <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>, * stating that the function is not supported. * </div> * <!-- end release-specific documentation --> * * @param sql any SQL statement * @param autoGeneratedKeys a constant indicating whether auto-generated * keys should be made available for retrieval using the method * <code>getGeneratedKeys</code>; one of the following constants: * <code>Statement.RETURN_GENERATED_KEYS</code> or * <code>Statement.NO_GENERATED_KEYS</code> * @return <code>true</code> if the first result is a <code>ResultSet</code> * object; <code>false</code> if it is an update count or there are * no results * @exception SQLException if a database access error occurs * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * @see #getGeneratedKeys * @since JDK 1.4, HSQLDB 1.7 */ //#ifdef JAVA4 public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { throw Util.notSupported(); } //#endif JAVA4 /** * <!-- start generic documentation --> * Executes the given SQL statement, which may return multiple results, * and signals the driver that the * auto-generated keys indicated in the given array should be made available * for retrieval. This array contains the indexes of the columns in the * target table that contain the auto-generated keys that should be made * available. The driver will ignore the array if the given SQL statement * is not an <code>INSERT</code> statement. * <P> * Under some (uncommon) situations, a single SQL statement may return * multiple result sets and/or update counts. Normally you can ignore * this unless you are (1) executing a stored procedure that you know may * return multiple results or (2) you are dynamically executing an * unknown SQL string. * <P> * The <code>execute</code> method executes an SQL statement and indicates the * form of the first result. You must then use the methods * <code>getResultSet</code> or <code>getUpdateCount</code> * to retrieve the result, and <code>getMoreResults</code> to * move to any subsequent result(s). <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>, * stating that the function is not supported. * </div> * <!-- end release-specific documentation --> * * @param sql any SQL statement * @param columnIndexes an array of the indexes of the columns in the * inserted row that should be made available for retrieval by a * call to the method <code>getGeneratedKeys</code> * @return <code>true</code> if the first result is a <code>ResultSet</code> * object; <code>false</code> if it is an update count or there * are no results * @exception SQLException if a database access error occurs * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * @since JDK 1.4, HSQLDB 1.7 */ //#ifdef JAVA4 public boolean execute(String sql, int[] columnIndexes) throws SQLException { throw Util.notSupported(); } //#endif JAVA4 /** * <!-- start generic documentation --> * Executes the given SQL statement, which may return multiple results, * and signals the driver that the * auto-generated keys indicated in the given array should be made available * for retrieval. This array contains the names of the columns in the * target table that contain the auto-generated keys that should be made * available. The driver will ignore the array if the given SQL statement * is not an <code>INSERT</code> statement. * <P> * In some (uncommon) situations, a single SQL statement may return * multiple result sets and/or update counts. Normally you can ignore * this unless you are (1) executing a stored procedure that you know may * return multiple results or (2) you are dynamically executing an * unknown SQL string. * <P> * The <code>execute</code> method executes an SQL statement and indicates the * form of the first result. You must then use the methods * <code>getResultSet</code> or <code>getUpdateCount</code> * to retrieve the result, and <code>getMoreResults</code> to * move to any subsequent result(s). <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>, * stating that the function is not supported. * </div> * <!-- end release-specific documentation --> * * @param sql any SQL statement * @param columnNames an array of the names of the columns in the inserted * row that should be made available for retrieval by a call to the * method <code>getGeneratedKeys</code> * @return <code>true</code> if the next result is a <code>ResultSet</code> * object; <code>false</code> if it is an update count or there * are no more results * @exception SQLException if a database access error occurs * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * @see #getGeneratedKeys * @since JDK 1.4, HSQLDB 1.7 */ //#ifdef JAVA4 public boolean execute(String sql, String[] columnNames) throws SQLException { throw Util.notSupported(); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the result set holdability for <code>ResultSet</code> objects * generated by this <code>Statement</code> object. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, this method returns HOLD_CURSORS_OVER_COMMIT * </div> * <!-- end release-specific documentation --> * * @return either <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or * <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code> * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQLDB 1.7 */ //#ifdef JAVA4 public int getResultSetHoldability() throws SQLException { return jdbcResultSet.HOLD_CURSORS_OVER_COMMIT; } //#endif JAVA4 // -------------------- Internal Implementation ---------------------------- /** * Constructs a new jdbcStatement with the specified connection and * result type. * * @param c the connection on which this statement will execute * @param type the kind of results this will return */ jdbcStatement(jdbcConnection c, int type) { // PRE: assume connection is not null and is not closed // PRE: assume type is a valid result set type code connection = c; rsType = type; } /** * Retrieves whether this statement is closed. */ synchronized public boolean isClosed() { return isClosed; } /** * An internal check for closed statements. * * @throws SQLException when the connection is closed */ void checkClosed() throws SQLException { if (isClosed) { throw Util.sqlException(Trace.STATEMENT_IS_CLOSED); } if (connection.isClosed) { throw Util.sqlException(Trace.CONNECTION_IS_CLOSED); } } /** * Internal result producer for jdbcStatement (sqlExecDirect mode). <p> * * @param sql a character sequence representing the SQL to be executed * @throws SQLException when a database access error occurs */ private void fetchResult(String sql) throws SQLException { if (isEscapeProcessing) { sql = connection.nativeSQL(sql); } resultIn = null; resultOut.setMainString(sql); resultOut.setMaxRows(maxRows); try { resultIn = connection.sessionProxy.execute(resultOut); if (resultIn.isError()) { throw new HsqlException(resultIn); } } catch (HsqlException e) { throw Util.sqlException(e); } } //#ifdef JAVA6 public void setPoolable(boolean poolable) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public boolean isPoolable() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public <T> T unwrap(Class<T> iface) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public boolean isWrapperFor(Class<?> iface) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } //#endif JAVA6 }
[ "public", "class", "jdbcStatement", "implements", "Statement", "{", "/**\n * Whether this Statement has been explicitly closed. A jdbcConnection\n * object now explicitly closes all of its open jdbcXXXStatement objects\n * when it is closed.\n */", "volatile", "boolean", "isClosed", ";", "/** Is escape processing enabled? */", "private", "boolean", "isEscapeProcessing", "=", "true", ";", "/** The connection used to execute this statement. */", "protected", "jdbcConnection", "connection", ";", "/** The maximum number of rows to generate when executing this statement. */", "protected", "int", "maxRows", ";", "/** The result of executing this statement. */", "protected", "Result", "resultIn", ";", "/** The result set type obtained by executing this statement. */", "protected", "int", "rsType", "=", "jdbcResultSet", ".", "TYPE_FORWARD_ONLY", ";", "/** Used by this statement to communicate non-batched requests. */", "protected", "Result", "resultOut", "=", "new", "Result", "(", "ResultConstants", ".", "SQLEXECDIRECT", ")", ";", "/** Use by this statement to communicate batched execution requests */", "protected", "Result", "batchResultOut", "=", "null", ";", "/**\n * <!-- start generic documentation -->\n * Executes the given SQL statement, which returns a single\n * <code>ResultSet</code> object. <p>\n * <!-- end generic documentation -->\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * This method should not be used for statements other than SELECT queries.<p>\n *\n * Including 1.7.2, HSQLDB does not throw an exception when the statement\n * is a DDL statement or an UPDATE or DELETE statement. This will certainly\n * change in future version.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @param sql an SQL statement to be sent to the database, typically a\n * static SQL <code>SELECT</code> statement\n * @return a <code>ResultSet</code> object that contains the data produced\n * by the given query; never <code>null</code>\n * @exception SQLException if a database access error occurs or the given\n * SQL statement produces anything other than a single\n * <code>ResultSet</code> object\n */", "public", "ResultSet", "executeQuery", "(", "String", "sql", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "connection", ".", "clearWarningsNoCheck", "(", ")", ";", "fetchResult", "(", "sql", ")", ";", "return", "new", "jdbcResultSet", "(", "this", ",", "resultIn", ",", "connection", ".", "connProperties", ",", "connection", ".", "isNetConn", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Executes the given SQL statement, which may be an <code>INSERT</code>,\n * <code>UPDATE</code>, or <code>DELETE</code> statement or an\n * SQL statement that returns nothing, such as an SQL DDL statement. <p>\n * <!-- end generic documentation -->\n *\n * @param sql an SQL <code>INSERT</code>, <code>UPDATE</code> or\n * <code>DELETE</code> statement or an SQL statement that returns nothing\n * @return either the row count for <code>INSERT</code>, <code>UPDATE</code>\n * or <code>DELETE</code> statements, or <code>0</code> for SQL statements\n * that return nothing\n * @exception SQLException if a database access error occurs or the given\n * SQL statement produces a <code>ResultSet</code> object\n */", "public", "int", "executeUpdate", "(", "String", "sql", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "connection", ".", "clearWarningsNoCheck", "(", ")", ";", "fetchResult", "(", "sql", ")", ";", "if", "(", "resultIn", "==", "null", "||", "resultIn", ".", "isData", "(", ")", ")", "{", "/**\n * @todo: - fredt@users - check for type of statement _must_ be done\n * in the engine and error returned _without_ executing\n */", "throw", "new", "SQLException", "(", "Trace", ".", "getMessage", "(", "Trace", ".", "jdbcStatement_executeUpdate", ")", ")", ";", "}", "else", "if", "(", "resultIn", ".", "isError", "(", ")", ")", "{", "Util", ".", "throwError", "(", "resultIn", ")", ";", "}", "return", "resultIn", ".", "getUpdateCount", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Releases this <code>Statement</code> object's database\n * and JDBC resources immediately instead of waiting for\n * this to happen when it is automatically closed.\n * It is generally good practice to release resources as soon as\n * you are finished with them to avoid tying up database\n * resources.\n * <P>\n * Calling the method <code>close</code> on a <code>Statement</code>\n * object that is already closed has no effect.\n * <P>\n * <B>Note:</B> A <code>Statement</code> object is automatically closed\n * when it is garbage collected. When a <code>Statement</code> object is\n * closed, its current <code>ResultSet</code> object, if one exists, is\n * also closed. <p>\n * <!-- end generic documentation -->\n *\n * @exception SQLException if a database access error occurs\n */", "public", "synchronized", "void", "close", "(", ")", "throws", "SQLException", "{", "if", "(", "isClosed", ")", "{", "return", ";", "}", "batchResultOut", "=", "null", ";", "connection", "=", "null", ";", "resultIn", "=", "null", ";", "resultOut", "=", "null", ";", "isClosed", "=", "true", ";", "}", "/**\n * <!-- start generic documentation -->\n * Retrieves the maximum number of bytes that can be\n * returned for character and binary column values in a <code>ResultSet</code>\n * object produced by this <code>Statement</code> object.\n * This limit applies only to <code>BINARY</code>,\n * <code>VARBINARY</code>, <code>LONGVARBINARY</code>, <code>CHAR</code>,\n * <code>VARCHAR</code>, and <code>LONGVARCHAR</code>\n * columns. If the limit is exceeded, the excess data is silently\n * discarded. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Including 1.7.2, HSQLDB always returns zero, meaning there\n * is no limit.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @return the current column size limit for columns storing character and\n * binary values; zero means there is no limit\n * @exception SQLException if a database access error occurs\n * @see #setMaxFieldSize\n */", "public", "int", "getMaxFieldSize", "(", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "return", "0", ";", "}", "/**\n * <!-- start generic documentation -->\n * Sets the limit for the maximum number of bytes in a <code>ResultSet</code>\n * column storing character or binary values to\n * the given number of bytes. This limit applies\n * only to <code>BINARY</code>, <code>VARBINARY</code>,\n * <code>LONGVARBINARY</code>, <code>CHAR</code>, <code>VARCHAR</code>, and\n * <code>LONGVARCHAR</code> fields. If the limit is exceeded, the excess data\n * is silently discarded. For maximum portability, use values\n * greater than 256. <p>\n * <!-- emd generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Including 1.7.2, calls to this method are simply ignored; HSQLDB always\n * stores the full number of bytes when dealing with any of the field types\n * mentioned above. These types all have an absolute maximum element upper\n * bound determined by the Java array index limit\n * java.lang.Integer.MAX_VALUE. For XXXBINARY types, this translates to\n * Integer.MAX_VALUE bytes. For XXXCHAR types, this translates to\n * 2 * Integer.MAX_VALUE bytes (2 bytes / character)\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @param max the new column size limit in bytes; zero means there is no limit\n * @exception SQLException if a database access error occurs\n * or the condition max >= 0 is not satisfied\n * @see #getMaxFieldSize\n */", "public", "void", "setMaxFieldSize", "(", "int", "max", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "if", "(", "max", "<", "0", ")", "{", "throw", "Util", ".", "sqlException", "(", "Trace", ".", "INVALID_JDBC_ARGUMENT", ")", ";", "}", "}", "/**\n * <!-- start generic documentation -->\n * Retrieves the maximum number of rows that a\n * <code>ResultSet</code> object produced by this\n * <code>Statement</code> object can contain. If this limit is exceeded,\n * the excess rows are silently dropped. <p>\n * <!-- start generic documentation -->\n *\n * @return the current maximum number of rows for a <code>ResultSet</code>\n * object produced by this <code>Statement</code> object;\n * zero means there is no limit\n * @exception SQLException if a database access error occurs\n * @see #setMaxRows\n */", "public", "int", "getMaxRows", "(", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "return", "maxRows", ";", "}", "/**\n * <!-- start generic documentation -->\n * Sets the limit for the maximum number of rows that any\n * <code>ResultSet</code> object can contain to the given number.\n * If the limit is exceeded, the excess\n * rows are silently dropped. <p>\n * <!-- end generic documentation -->\n *\n * @param max the new max rows limit; zero means there is no limit\n * @exception SQLException if a database access error occurs\n * or the condition max >= 0 is not satisfied\n * @see #getMaxRows\n */", "public", "void", "setMaxRows", "(", "int", "max", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "if", "(", "max", "<", "0", ")", "{", "throw", "Util", ".", "sqlException", "(", "Trace", ".", "INVALID_JDBC_ARGUMENT", ")", ";", "}", "maxRows", "=", "max", ";", "}", "/**\n * <!-- start generic documentation -->\n * Sets escape processing on or off.\n * If escape scanning is on (the default), the driver will do\n * escape substitution before sending the SQL statement to the database.\n *\n * Note: Since prepared statements have usually been parsed prior\n * to making this call, disabling escape processing for\n * <code>PreparedStatements</code> objects will have no effect. <p>\n * <!-- end generic documentation -->\n *\n * @param enable <code>true</code> to enable escape processing;\n * <code>false</code> to disable it\n * @exception SQLException if a database access error occurs\n */", "public", "void", "setEscapeProcessing", "(", "boolean", "enable", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "isEscapeProcessing", "=", "enable", ";", "}", "/**\n * <!-- start generic documentation -->\n * Retrieves the number of seconds the driver will\n * wait for a <code>Statement</code> object to execute. If the\n * limit is exceeded, an <code>SQLException</code> is thrown. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Including 1.7.2, HSQLDB always returns zero, meaning there\n * is no limit.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @return the current query timeout limit in seconds; zero means there is\n * no limit\n * @exception SQLException if a database access error occurs\n * @see #setQueryTimeout\n */", "public", "int", "getQueryTimeout", "(", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "return", "0", ";", "}", "/**\n * <!-- start generic documentation -->\n * Sets the number of seconds the driver will wait for a\n * <code>Statement</code> object to execute to the given number of seconds.\n * If the limit is exceeded, an <code>SQLException</code> is thrown. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Including 1.7.2, calls to this method are ignored; HSQLDB waits an\n * unlimited amount of time for statement execution\n * requests to return.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @param seconds the new query timeout limit in seconds; zero means\n * there is no limit\n * @exception SQLException if a database access error occurs\n * or the condition seconds >= 0 is not satisfied\n * @see #getQueryTimeout\n */", "public", "void", "setQueryTimeout", "(", "int", "seconds", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "if", "(", "seconds", "<", "0", ")", "{", "throw", "Util", ".", "sqlException", "(", "Trace", ".", "INVALID_JDBC_ARGUMENT", ")", ";", "}", "}", "/**\n * <!-- start generic documentation -->\n * Cancels this <code>Statement</code> object if both the DBMS and\n * driver support aborting an SQL statement.\n * This method can be used by one thread to cancel a statement that\n * is being executed by another thread. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Including 1.7.2, HSQLDB does <i>not</i> support aborting a SQL\n * statement; calls to this method are ignored.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @exception SQLException if a database access error occurs\n */", "public", "void", "cancel", "(", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Retrieves the first warning reported by calls on this <code>Statement</code> object.\n * Subsequent <code>Statement</code> object warnings will be chained to this\n * <code>SQLWarning</code> object.\n *\n * <p>The warning chain is automatically cleared each time\n * a statement is (re)executed. This method may not be called on a closed\n * <code>Statement</code> object; doing so will cause an <code>SQLException</code>\n * to be thrown.\n *\n * <P><B>Note:</B> If you are processing a <code>ResultSet</code> object, any\n * warnings associated with reads on that <code>ResultSet</code> object\n * will be chained on it rather than on the <code>Statement</code>\n * object that produced it. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Including 1.7.2, HSQLDB never produces Statement warnings;\n * this method always returns null.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @return the first <code>SQLWarning</code> object or <code>null</code>\n * if there are no warnings\n * @exception SQLException if a database access error occurs or this\n * method is called on a closed statement\n */", "public", "SQLWarning", "getWarnings", "(", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "return", "null", ";", "}", "/**\n * <!-- start generic documentation -->\n * Clears all the warnings reported on this <code>Statement</code>\n * object. After a call to this method,\n * the method <code>getWarnings</code> will return\n * <code>null</code> until a new warning is reported for this\n * <code>Statement</code> object. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Including HSQLDB 1.7.2, <code>SQLWarning</code> objects are\n * never produced for Statement Objects; calls to this method are\n * ignored.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @exception SQLException if a database access error occurs\n */", "public", "void", "clearWarnings", "(", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Sets the SQL cursor name to the given <code>String</code>, which\n * will be used by subsequent <code>Statement</code> object\n * <code>execute</code> methods. This name can then be\n * used in SQL positioned update or delete statements to identify the\n * current row in the <code>ResultSet</code> object generated by this\n * statement. If the database does not support positioned update/delete,\n * this method is a noop. To insure that a cursor has the proper isolation\n * level to support updates, the cursor's <code>SELECT</code> statement\n * should have the form <code>SELECT FOR UPDATE</code>. If\n * <code>FOR UPDATE</code> is not present, positioned updates may fail.\n *\n * <P><B>Note:</B> By definition, the execution of positioned updates and\n * deletes must be done by a different <code>Statement</code> object than\n * the one that generated the <code>ResultSet</code> object being used for\n * positioning. Also, cursor names must be unique within a connection. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Including 1.7.2, HSQLDB does not support named cursors,\n * updateable results or table locking via <code>SELECT FOR UPDATE</code>;\n * calls to this method are ignored.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @param name the new cursor name, which must be unique within\n * a connection\n * @exception SQLException if a database access error occurs\n */", "public", "void", "setCursorName", "(", "String", "name", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Executes the given SQL statement, which may return multiple results.\n * In some (uncommon) situations, a single SQL statement may return\n * multiple result sets and/or update counts. Normally you can ignore\n * this unless you are (1) executing a stored procedure that you know may\n * return multiple results or (2) you are dynamically executing an\n * unknown SQL string.\n * <P>\n * The <code>execute</code> method executes an SQL statement and indicates the\n * form of the first result. You must then use the methods\n * <code>getResultSet</code> or <code>getUpdateCount</code>\n * to retrieve the result, and <code>getMoreResults</code> to\n * move to any subsequent result(s). <p>\n * <!-- end generic documentation -->\n *\n * @param sql any SQL statement\n * @return <code>true</code> if the first result is a <code>ResultSet</code>\n * object; <code>false</code> if it is an update count or there are\n * no results\n * @exception SQLException if a database access error occurs\n * @see #getResultSet\n * @see #getUpdateCount\n * @see #getMoreResults\n */", "public", "boolean", "execute", "(", "String", "sql", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "connection", ".", "clearWarningsNoCheck", "(", ")", ";", "fetchResult", "(", "sql", ")", ";", "return", "resultIn", ".", "isData", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Retrieves the current result as a <code>ResultSet</code> object.\n * This method should be called only once per result. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Without an interceding call to executeXXX, each invocation of this\n * method will produce a new, initialized ResultSet instance referring to\n * the current result, if any.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @return the current result as a <code>ResultSet</code> object or\n * <code>null</code> if the result is an update count or there\n * are no more results\n * @exception SQLException if a database access error occurs\n * @see #execute\n */", "public", "ResultSet", "getResultSet", "(", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "return", "resultIn", "==", "null", "||", "!", "resultIn", ".", "isData", "(", ")", "?", "null", ":", "new", "jdbcResultSet", "(", "this", ",", "resultIn", ",", "connection", ".", "connProperties", ",", "connection", ".", "isNetConn", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Retrieves the current result as an update count;\n * if the result is a <code>ResultSet</code> object or there are no more results, -1\n * is returned. This method should be called only once per result. <p>\n * <!-- end generic documentation -->\n *\n * @return the current result as an update count; -1 if the current result is a\n * <code>ResultSet</code> object or there are no more results\n * @exception SQLException if a database access error occurs\n * @see #execute\n */", "public", "int", "getUpdateCount", "(", ")", "throws", "SQLException", "{", "return", "(", "resultIn", "==", "null", "||", "resultIn", ".", "isData", "(", ")", ")", "?", "-", "1", ":", "resultIn", ".", "getUpdateCount", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Moves to this <code>Statement</code> object's next result, returns\n * <code>true</code> if it is a <code>ResultSet</code> object, and\n * implicitly closes any current <code>ResultSet</code>\n * object(s) obtained with the method <code>getResultSet</code>.\n *\n * <P>There are no more results when the following is true:\n * <PRE>\n * <code>(!getMoreResults() && (getUpdateCount() == -1)</code>\n * </PRE> <p>\n * <!-- end generic documentation -->\n *\n * @return <code>true</code> if the next result is a <code>ResultSet</code>\n * object; <code>false</code> if it is an update count or there are\n * no more results\n * @exception SQLException if a database access error occurs\n * @see #execute\n */", "public", "boolean", "getMoreResults", "(", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "resultIn", "=", "null", ";", "return", "false", ";", "}", "/**\n * <!-- start generic documentation -->\n * Gives the driver a hint as to the direction in which\n * rows will be processed in <code>ResultSet</code>\n * objects created using this <code>Statement</code> object. The\n * default value is <code>ResultSet.FETCH_FORWARD</code>.\n * <P>\n * Note that this method sets the default fetch direction for\n * result sets generated by this <code>Statement</code> object.\n * Each result set has its own methods for getting and setting\n * its own fetch direction. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Including 1.7.2, HSQLDB supports only <code>FETCH_FORWARD</code>. <p>\n *\n * Setting any other value will throw an <code>SQLException</code>\n * stating that the operation is not supported.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @param direction the initial direction for processing rows\n * @exception SQLException if a database access error occurs\n * or the given direction\n * is not one of <code>ResultSet.FETCH_FORWARD</code>,\n * <code>ResultSet.FETCH_REVERSE</code>, or\n * <code>ResultSet.FETCH_UNKNOWN</code> <p>\n *\n * HSQLDB throws for all values except <code>FETCH_FORWARD</code>\n * @since JDK 1.2 (JDK 1.1.x developers: read the new overview\n * for jdbcStatement)\n * @see #getFetchDirection\n */", "public", "void", "setFetchDirection", "(", "int", "direction", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "if", "(", "direction", "!=", "jdbcResultSet", ".", "FETCH_FORWARD", ")", "{", "throw", "Util", ".", "notSupported", "(", ")", ";", "}", "}", "/**\n * <!-- start generic documentation -->\n * Retrieves the direction for fetching rows from\n * database tables that is the default for result sets\n * generated from this <code>Statement</code> object.\n * If this <code>Statement</code> object has not set\n * a fetch direction by calling the method <code>setFetchDirection</code>,\n * the return value is implementation-specific. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Including 1.7.2, HSQLDB always returns FETCH_FORWARD.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @return the default fetch direction for result sets generated\n * from this <code>Statement</code> object\n * @exception SQLException if a database access error occurs\n * @since JDK 1.2 (JDK 1.1.x developers: read the new overview\n * for jdbcStatement)\n * @see #setFetchDirection\n */", "public", "int", "getFetchDirection", "(", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "return", "jdbcResultSet", ".", "FETCH_FORWARD", ";", "}", "/**\n * <!-- start generic documentation -->\n * Gives the JDBC driver a hint as to the number of rows that should\n * be fetched from the database when more rows are needed. The number\n * of rows specified affects only result sets created using this\n * statement. If the value specified is zero, then the hint is ignored.\n * The default value is zero. <p>\n * <!-- start generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Including 1.7.2, calls to this method are ignored;\n * HSQLDB fetches each result completely as part of\n * executing its statement.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @param rows the number of rows to fetch\n * @exception SQLException if a database access error occurs, or the\n * condition 0 <= <code>rows</code> <= <code>this.getMaxRows()</code>\n * is not satisfied. <p>\n *\n * HSQLDB never throws an exception, since calls to this method\n * are always ignored.\n * @since JDK 1.2 (JDK 1.1.x developers: read the new overview\n * for jdbcStatement)\n * @see #getFetchSize\n */", "public", "void", "setFetchSize", "(", "int", "rows", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Retrieves the number of result set rows that is the default\n * fetch size for <code>ResultSet</code> objects\n * generated from this <code>Statement</code> object.\n * If this <code>Statement</code> object has not set\n * a fetch size by calling the method <code>setFetchSize</code>,\n * the return value is implementation-specific. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <b>HSQLDB-Specific Information</b> <p>\n *\n * Including 1.7.2, this method always returns 0.\n * HSQLDB fetches each result completely as part of\n * executing its statement\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @return the default fetch size for result sets generated\n * from this <code>Statement</code> object\n * @exception SQLException if a database access error occurs\n * @since JDK 1.2 (JDK 1.1.x developers: read the new overview\n * for jdbcStatement)\n * @see #setFetchSize\n */", "public", "int", "getFetchSize", "(", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "return", "0", ";", "}", "/**\n * <!-- start generic documentation -->\n * Retrieves the result set concurrency for <code>ResultSet</code> objects\n * generated by this <code>Statement</code> object. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Including 1.7.2, HSQLDB supports only\n * <code>CONCUR_READ_ONLY</code> concurrency.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @return either <code>ResultSet.CONCUR_READ_ONLY</code> or\n * <code>ResultSet.CONCUR_UPDATABLE</code> (not supported)\n * @exception SQLException if a database access error occurs\n * @since JDK 1.2 (JDK 1.1.x developers: read the new overview\n * for jdbcStatement)\n */", "public", "int", "getResultSetConcurrency", "(", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "return", "jdbcResultSet", ".", "CONCUR_READ_ONLY", ";", "}", "/**\n * <!-- start generic documentation -->\n * Retrieves the result set type for <code>ResultSet</code> objects\n * generated by this <code>Statement</code> object. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * HSQLDB 1.7.0 and later versions support <code>TYPE_FORWARD_ONLY</code>\n * and <code>TYPE_SCROLL_INSENSITIVE</code>.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @return one of <code>ResultSet.TYPE_FORWARD_ONLY</code>,\n * <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or\n * <code>ResultSet.TYPE_SCROLL_SENSITIVE</code> (not supported) <p>\n *\n * <b>Note:</b> Up to and including 1.7.1, HSQLDB never returns\n * <code>TYPE_SCROLL_SENSITIVE</code>\n * @exception SQLException if a database access error occurs\n * @since JDK 1.2 (JDK 1.1.x developers: read the new overview\n * for jdbcStatement)\n */", "public", "int", "getResultSetType", "(", ")", "throws", "SQLException", "{", "return", "rsType", ";", "}", "/**\n * <!-- start generic documentation -->\n * Adds the given SQL command to the current list of commmands for this\n * <code>Statement</code> object. The commands in this list can be\n * executed as a batch by calling the method <code>executeBatch</code>.\n * <P>\n * <B>NOTE:</B> This method is optional. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Starting with 1.7.2, this feature is supported.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @param sql typically this is a static SQL <code>INSERT</code> or\n * <code>UPDATE</code> statement\n * @exception SQLException if a database access error occurs, or the\n * driver does not support batch updates\n * @see #executeBatch\n * @since JDK 1.2 (JDK 1.1.x developers: read the new overview\n * for jdbcStatement)\n */", "public", "void", "addBatch", "(", "String", "sql", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "if", "(", "isEscapeProcessing", ")", "{", "sql", "=", "connection", ".", "nativeSQL", "(", "sql", ")", ";", "}", "if", "(", "batchResultOut", "==", "null", ")", "{", "batchResultOut", "=", "new", "Result", "(", "ResultConstants", ".", "BATCHEXECDIRECT", ",", "new", "int", "[", "]", "{", "Types", ".", "VARCHAR", "}", ",", "0", ")", ";", "}", "batchResultOut", ".", "add", "(", "new", "Object", "[", "]", "{", "sql", "}", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Empties this <code>Statement</code> object's current list of\n * SQL commands.\n * <P>\n * <B>NOTE:</B> This method is optional. <p>\n * <!-- start generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Starting with HSQLDB 1.7.2, this feature is supported.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @exception SQLException if a database access error occurs or the\n * driver does not support batch updates\n * @see #addBatch\n * @since JDK 1.2 (JDK 1.1.x developers: read the new overview\n * for jdbcStatement)\n */", "public", "void", "clearBatch", "(", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "if", "(", "batchResultOut", "!=", "null", ")", "{", "batchResultOut", ".", "clear", "(", ")", ";", "}", "}", "/**\n * <!-- start generic documentation -->\n * Submits a batch of commands to the database for execution and\n * if all commands execute successfully, returns an array of update counts.\n * The <code>int</code> elements of the array that is returned are ordered\n * to correspond to the commands in the batch, which are ordered\n * according to the order in which they were added to the batch.\n * The elements in the array returned by the method <code>executeBatch</code>\n * may be one of the following:\n * <OL>\n * <LI>A number greater than or equal to zero -- indicates that the\n * command was processed successfully and is an update count giving the\n * number of rows in the database that were affected by the command's\n * execution\n * <LI>A value of <code>SUCCESS_NO_INFO</code> -- indicates that the command was\n * processed successfully but that the number of rows affected is\n * unknown\n * <P>\n * If one of the commands in a batch update fails to execute properly,\n * this method throws a <code>BatchUpdateException</code>, and a JDBC\n * driver may or may not continue to process the remaining commands in\n * the batch. However, the driver's behavior must be consistent with a\n * particular DBMS, either always continuing to process commands or never\n * continuing to process commands. If the driver continues processing\n * after a failure, the array returned by the method\n * <code>BatchUpdateException.getUpdateCounts</code>\n * will contain as many elements as there are commands in the batch, and\n * at least one of the elements will be the following:\n * <P>\n * <LI>A value of <code>EXECUTE_FAILED</code> -- indicates that the command failed\n * to execute successfully and occurs only if a driver continues to\n * process commands after a command fails\n * </OL>\n * <P>\n * A driver is not required to implement this method.\n * The possible implementations and return values have been modified in\n * the Java 2 SDK, Standard Edition, version 1.3 to\n * accommodate the option of continuing to proccess commands in a batch\n * update after a <code>BatchUpdateException</code> obejct has been thrown. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Starting with HSQLDB 1.7.2, this feature is supported. <p>\n *\n * HSQLDB stops execution of commands in a batch when one of the commands\n * results in an exception. The size of the returned array equals the\n * number of commands that were executed successfully.<p>\n *\n * When the product is built under the JAVA1 target, an exception\n * is never thrown and it is the responsibility of the client software to\n * check the size of the returned update count array to determine if any\n * batch items failed. To build and run under the JAVA2 target, JDK/JRE\n * 1.3 or higher must be used.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @return an array of update counts containing one element for each\n * command in the batch. The elements of the array are ordered according\n * to the order in which commands were added to the batch.\n * @exception SQLException if a database access error occurs or the\n * driver does not support batch statements. Throws\n * {@link java.sql.BatchUpdateException}\n * (a subclass of <code>java.sql.SQLException</code>) if one of the commands\n * sent to the database fails to execute properly or attempts to return a\n * result set.\n * @since JDK 1.3 (JDK 1.1.x developers: read the new overview\n * for jdbcStatement)\n */", "public", "int", "[", "]", "executeBatch", "(", ")", "throws", "SQLException", "{", "int", "[", "]", "updateCounts", ";", "int", "batchCount", ";", "HsqlException", "he", ";", "checkClosed", "(", ")", ";", "connection", ".", "clearWarningsNoCheck", "(", ")", ";", "if", "(", "batchResultOut", "==", "null", ")", "{", "batchResultOut", "=", "new", "Result", "(", "ResultConstants", ".", "BATCHEXECDIRECT", ",", "new", "int", "[", "]", "{", "Types", ".", "VARCHAR", "}", ",", "0", ")", ";", "}", "batchCount", "=", "batchResultOut", ".", "getSize", "(", ")", ";", "try", "{", "resultIn", "=", "connection", ".", "sessionProxy", ".", "execute", "(", "batchResultOut", ")", ";", "}", "catch", "(", "HsqlException", "e", ")", "{", "batchResultOut", ".", "clear", "(", ")", ";", "throw", "Util", ".", "sqlException", "(", "e", ")", ";", "}", "batchResultOut", ".", "clear", "(", ")", ";", "if", "(", "resultIn", ".", "isError", "(", ")", ")", "{", "Util", ".", "throwError", "(", "resultIn", ")", ";", "}", "updateCounts", "=", "resultIn", ".", "getUpdateCounts", "(", ")", ";", "if", "(", "updateCounts", ".", "length", "!=", "batchCount", ")", "{", "throw", "new", "BatchUpdateException", "(", "\"", "failed batch", "\"", ",", "updateCounts", ")", ";", "}", "/*\n if (updateCounts.length != batchCount) {\n throw new SQLException(\"failed batch, update count: \"\n + updateCounts, \"\");\n }\n*/", "return", "updateCounts", ";", "}", "/**\n * <!-- start generic documentation -->\n * Retrieves the <code>Connection</code> object\n * that produced this <code>Statement</code> object. <p>\n * <!-- end generic documentation -->\n *\n * @return the connection that produced this statement\n * @exception SQLException if a database access error occurs\n * @since JDK 1.2 (JDK 1.1.x developers: read the new overview\n * for jdbcStatement)\n */", "public", "Connection", "getConnection", "(", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "return", "connection", ";", "}", "/**\n * <!-- start generic documentation -->\n * Moves to this <code>Statement</code> object's next result, deals with\n * any current <code>ResultSet</code> object(s) according to the instructions\n * specified by the given flag, and returns\n * <code>true</code> if the next result is a <code>ResultSet</code> object.\n *\n * <P>There are no more results when the following is true:\n * <PRE>\n * <code>(!getMoreResults() && (getUpdateCount() == -1)</code>\n * </PRE> <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * HSQLDB 1.7.2 does not support this feature. <p>\n *\n * Calling this method always throws an <code>SQLException</code>,\n * stating that the function is not supported.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @param current one of the following <code>Statement</code>\n * constants indicating what should happen to current\n * <code>ResultSet</code> objects obtained using the method\n * <code>getResultSet</code:\n * <code>CLOSE_CURRENT_RESULT</code>,\n * <code>KEEP_CURRENT_RESULT</code>, or\n * <code>CLOSE_ALL_RESULTS</code>\n * @return <code>true</code> if the next result is a <code>ResultSet</code>\n * object; <code>false</code> if it is an update count or there are no\n * more results\n * @exception SQLException if a database access error occurs\n * @since JDK 1.4, HSQLDB 1.7\n * @see #execute\n */", "public", "boolean", "getMoreResults", "(", "int", "current", ")", "throws", "SQLException", "{", "throw", "Util", ".", "notSupported", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Retrieves any auto-generated keys created as a result of executing this\n * <code>Statement</code> object. If this <code>Statement</code> object did\n * not generate any keys, an empty <code>ResultSet</code>\n * object is returned. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * HSQLDB 1.7.2 does not support this feature. <p>\n *\n * Calling this method always throws an <code>SQLException</code>,\n * stating that the function is not supported.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @return a <code>ResultSet</code> object containing the auto-generated key(s)\n * generated by the execution of this <code>Statement</code> object\n * @exception SQLException if a database access error occurs\n * @since JDK 1.4, HSQLDB 1.7\n */", "public", "ResultSet", "getGeneratedKeys", "(", ")", "throws", "SQLException", "{", "throw", "Util", ".", "notSupported", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Executes the given SQL statement and signals the driver with the\n * given flag about whether the\n * auto-generated keys produced by this <code>Statement</code> object\n * should be made available for retrieval. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * HSQLDB 1.7.2 does not support this feature. <p>\n *\n * Calling this method always throws an <code>SQLException</code>,\n * stating that the function is not supported.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @param sql must be an SQL <code>INSERT</code>, <code>UPDATE</code> or\n * <code>DELETE</code> statement or an SQL statement that\n * returns nothing\n * @param autoGeneratedKeys a flag indicating whether auto-generated keys\n * should be made available for retrieval;\n * one of the following constants:\n * <code>Statement.RETURN_GENERATED_KEYS</code>\n * <code>Statement.NO_GENERATED_KEYS</code>\n * @return either the row count for <code>INSERT</code>, <code>UPDATE</code>\n * or <code>DELETE</code> statements, or <code>0</code> for SQL\n * statements that return nothing\n * @exception SQLException if a database access error occurs, the given\n * SQL statement returns a <code>ResultSet</code> object, or\n * the given constant is not one of those allowed\n * @since JDK 1.4, HSQLDB 1.7\n */", "public", "int", "executeUpdate", "(", "String", "sql", ",", "int", "autoGeneratedKeys", ")", "throws", "SQLException", "{", "throw", "Util", ".", "notSupported", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Executes the given SQL statement and signals the driver that the\n * auto-generated keys indicated in the given array should be made available\n * for retrieval. The driver will ignore the array if the SQL statement\n * is not an <code>INSERT</code> statement. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * HSQLDB 1.7.2 does not support this feature. <p>\n *\n * Calling this method always throws an <code>SQLException</code>,\n * stating that the function is not supported.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @param sql an SQL <code>INSERT</code>, <code>UPDATE</code> or\n * <code>DELETE</code> statement or an SQL statement that returns nothing,\n * such as an SQL DDL statement\n * @param columnIndexes an array of column indexes indicating the columns\n * that should be returned from the inserted row\n * @return either the row count for <code>INSERT</code>, <code>UPDATE</code>,\n * or <code>DELETE</code> statements, or 0 for SQL statements\n * that return nothing\n * @exception SQLException if a database access error occurs or the SQL\n * statement returns a <code>ResultSet</code> object\n * @since JDK 1.4, HSQLDB 1.7\n */", "public", "int", "executeUpdate", "(", "String", "sql", ",", "int", "[", "]", "columnIndexes", ")", "throws", "SQLException", "{", "throw", "Util", ".", "notSupported", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Executes the given SQL statement and signals the driver that the\n * auto-generated keys indicated in the given array should be made available\n * for retrieval. The driver will ignore the array if the SQL statement\n * is not an <code>INSERT</code> statement. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * HSQLDB 1.7.2 does not support this feature. <p>\n *\n * Calling this method always throws an <code>SQLException</code>,\n * stating that the function is not supported.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @param sql an SQL <code>INSERT</code>, <code>UPDATE</code> or\n * <code>DELETE</code> statement or an SQL statement that returns nothing\n * @param columnNames an array of the names of the columns that should be\n * returned from the inserted row\n * @return either the row count for <code>INSERT</code>, <code>UPDATE</code>,\n * or <code>DELETE</code> statements, or 0 for SQL statements\n * that return nothing\n * @exception SQLException if a database access error occurs\n * @since JDK 1.4, HSQLDB 1.7\n */", "public", "int", "executeUpdate", "(", "String", "sql", ",", "String", "[", "]", "columnNames", ")", "throws", "SQLException", "{", "throw", "Util", ".", "notSupported", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Executes the given SQL statement, which may return multiple results,\n * and signals the driver that any\n * auto-generated keys should be made available\n * for retrieval. The driver will ignore this signal if the SQL statement\n * is not an <code>INSERT</code> statement.\n * <P>\n * In some (uncommon) situations, a single SQL statement may return\n * multiple result sets and/or update counts. Normally you can ignore\n * this unless you are (1) executing a stored procedure that you know may\n * return multiple results or (2) you are dynamically executing an\n * unknown SQL string.\n * <P>\n * The <code>execute</code> method executes an SQL statement and indicates the\n * form of the first result. You must then use the methods\n * <code>getResultSet</code> or <code>getUpdateCount</code>\n * to retrieve the result, and <code>getMoreResults</code> to\n * move to any subsequent result(s). <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * HSQLDB 1.7.2 does not support this feature. <p>\n *\n * Calling this method always throws an <code>SQLException</code>,\n * stating that the function is not supported.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @param sql any SQL statement\n * @param autoGeneratedKeys a constant indicating whether auto-generated\n * keys should be made available for retrieval using the method\n * <code>getGeneratedKeys</code>; one of the following constants:\n * <code>Statement.RETURN_GENERATED_KEYS</code> or\n * <code>Statement.NO_GENERATED_KEYS</code>\n * @return <code>true</code> if the first result is a <code>ResultSet</code>\n * object; <code>false</code> if it is an update count or there are\n * no results\n * @exception SQLException if a database access error occurs\n * @see #getResultSet\n * @see #getUpdateCount\n * @see #getMoreResults\n * @see #getGeneratedKeys\n * @since JDK 1.4, HSQLDB 1.7\n */", "public", "boolean", "execute", "(", "String", "sql", ",", "int", "autoGeneratedKeys", ")", "throws", "SQLException", "{", "throw", "Util", ".", "notSupported", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Executes the given SQL statement, which may return multiple results,\n * and signals the driver that the\n * auto-generated keys indicated in the given array should be made available\n * for retrieval. This array contains the indexes of the columns in the\n * target table that contain the auto-generated keys that should be made\n * available. The driver will ignore the array if the given SQL statement\n * is not an <code>INSERT</code> statement.\n * <P>\n * Under some (uncommon) situations, a single SQL statement may return\n * multiple result sets and/or update counts. Normally you can ignore\n * this unless you are (1) executing a stored procedure that you know may\n * return multiple results or (2) you are dynamically executing an\n * unknown SQL string.\n * <P>\n * The <code>execute</code> method executes an SQL statement and indicates the\n * form of the first result. You must then use the methods\n * <code>getResultSet</code> or <code>getUpdateCount</code>\n * to retrieve the result, and <code>getMoreResults</code> to\n * move to any subsequent result(s). <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * HSQLDB 1.7.2 does not support this feature. <p>\n *\n * Calling this method always throws an <code>SQLException</code>,\n * stating that the function is not supported.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @param sql any SQL statement\n * @param columnIndexes an array of the indexes of the columns in the\n * inserted row that should be made available for retrieval by a\n * call to the method <code>getGeneratedKeys</code>\n * @return <code>true</code> if the first result is a <code>ResultSet</code>\n * object; <code>false</code> if it is an update count or there\n * are no results\n * @exception SQLException if a database access error occurs\n * @see #getResultSet\n * @see #getUpdateCount\n * @see #getMoreResults\n * @since JDK 1.4, HSQLDB 1.7\n */", "public", "boolean", "execute", "(", "String", "sql", ",", "int", "[", "]", "columnIndexes", ")", "throws", "SQLException", "{", "throw", "Util", ".", "notSupported", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Executes the given SQL statement, which may return multiple results,\n * and signals the driver that the\n * auto-generated keys indicated in the given array should be made available\n * for retrieval. This array contains the names of the columns in the\n * target table that contain the auto-generated keys that should be made\n * available. The driver will ignore the array if the given SQL statement\n * is not an <code>INSERT</code> statement.\n * <P>\n * In some (uncommon) situations, a single SQL statement may return\n * multiple result sets and/or update counts. Normally you can ignore\n * this unless you are (1) executing a stored procedure that you know may\n * return multiple results or (2) you are dynamically executing an\n * unknown SQL string.\n * <P>\n * The <code>execute</code> method executes an SQL statement and indicates the\n * form of the first result. You must then use the methods\n * <code>getResultSet</code> or <code>getUpdateCount</code>\n * to retrieve the result, and <code>getMoreResults</code> to\n * move to any subsequent result(s). <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * HSQLDB 1.7.2 does not support this feature. <p>\n *\n * Calling this method always throws an <code>SQLException</code>,\n * stating that the function is not supported.\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @param sql any SQL statement\n * @param columnNames an array of the names of the columns in the inserted\n * row that should be made available for retrieval by a call to the\n * method <code>getGeneratedKeys</code>\n * @return <code>true</code> if the next result is a <code>ResultSet</code>\n * object; <code>false</code> if it is an update count or there\n * are no more results\n * @exception SQLException if a database access error occurs\n * @see #getResultSet\n * @see #getUpdateCount\n * @see #getMoreResults\n * @see #getGeneratedKeys\n * @since JDK 1.4, HSQLDB 1.7\n */", "public", "boolean", "execute", "(", "String", "sql", ",", "String", "[", "]", "columnNames", ")", "throws", "SQLException", "{", "throw", "Util", ".", "notSupported", "(", ")", ";", "}", "/**\n * <!-- start generic documentation -->\n * Retrieves the result set holdability for <code>ResultSet</code> objects\n * generated by this <code>Statement</code> object. <p>\n * <!-- end generic documentation -->\n *\n * <!-- start release-specific documentation -->\n * <div class=\"ReleaseSpecificDocumentation\">\n * <h3>HSQLDB-Specific Information:</h3> <p>\n *\n * Starting with 1.7.2, this method returns HOLD_CURSORS_OVER_COMMIT\n * </div>\n * <!-- end release-specific documentation -->\n *\n * @return either <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or\n * <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>\n * @exception SQLException if a database access error occurs\n * @since JDK 1.4, HSQLDB 1.7\n */", "public", "int", "getResultSetHoldability", "(", ")", "throws", "SQLException", "{", "return", "jdbcResultSet", ".", "HOLD_CURSORS_OVER_COMMIT", ";", "}", "/**\n * Constructs a new jdbcStatement with the specified connection and\n * result type.\n *\n * @param c the connection on which this statement will execute\n * @param type the kind of results this will return\n */", "jdbcStatement", "(", "jdbcConnection", "c", ",", "int", "type", ")", "{", "connection", "=", "c", ";", "rsType", "=", "type", ";", "}", "/**\n * Retrieves whether this statement is closed.\n */", "synchronized", "public", "boolean", "isClosed", "(", ")", "{", "return", "isClosed", ";", "}", "/**\n * An internal check for closed statements.\n *\n * @throws SQLException when the connection is closed\n */", "void", "checkClosed", "(", ")", "throws", "SQLException", "{", "if", "(", "isClosed", ")", "{", "throw", "Util", ".", "sqlException", "(", "Trace", ".", "STATEMENT_IS_CLOSED", ")", ";", "}", "if", "(", "connection", ".", "isClosed", ")", "{", "throw", "Util", ".", "sqlException", "(", "Trace", ".", "CONNECTION_IS_CLOSED", ")", ";", "}", "}", "/**\n * Internal result producer for jdbcStatement (sqlExecDirect mode). <p>\n *\n * @param sql a character sequence representing the SQL to be executed\n * @throws SQLException when a database access error occurs\n */", "private", "void", "fetchResult", "(", "String", "sql", ")", "throws", "SQLException", "{", "if", "(", "isEscapeProcessing", ")", "{", "sql", "=", "connection", ".", "nativeSQL", "(", "sql", ")", ";", "}", "resultIn", "=", "null", ";", "resultOut", ".", "setMainString", "(", "sql", ")", ";", "resultOut", ".", "setMaxRows", "(", "maxRows", ")", ";", "try", "{", "resultIn", "=", "connection", ".", "sessionProxy", ".", "execute", "(", "resultOut", ")", ";", "if", "(", "resultIn", ".", "isError", "(", ")", ")", "{", "throw", "new", "HsqlException", "(", "resultIn", ")", ";", "}", "}", "catch", "(", "HsqlException", "e", ")", "{", "throw", "Util", ".", "sqlException", "(", "e", ")", ";", "}", "}", "public", "void", "setPoolable", "(", "boolean", "poolable", ")", "throws", "SQLException", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "Not supported yet.", "\"", ")", ";", "}", "public", "boolean", "isPoolable", "(", ")", "throws", "SQLException", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "Not supported yet.", "\"", ")", ";", "}", "public", "<", "T", ">", "T", "unwrap", "(", "Class", "<", "T", ">", "iface", ")", "throws", "SQLException", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "Not supported yet.", "\"", ")", ";", "}", "public", "boolean", "isWrapperFor", "(", "Class", "<", "?", ">", "iface", ")", "throws", "SQLException", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "Not supported yet.", "\"", ")", ";", "}", "}" ]
<!-- start generic documentation --> The object used for executing a static SQL statement and returning the results it produces.
[ "<!", "--", "start", "generic", "documentation", "--", ">", "The", "object", "used", "for", "executing", "a", "static", "SQL", "statement", "and", "returning", "the", "results", "it", "produces", "." ]
[ "// boucherb@users", "// NOTE:", "// This method is synchronized since resultIn is an instance attribute", "// and thus it is theoretically possible that a race condition occurs", "// in which a different thread executes fetchResult(sql), replacing", "// resultIn before it gets assigned propery to the new result set.", "// fredt - this class is not supposed to be called multi-threaded -", "// For example, if two threads call execute() then both call getResult() in", "// the wrong order, the ResultSet object for one call could actually belong", "// to the other call.", "//----------------------------------------------------------------------", "//----------------------- Multiple Results --------------------------", "// fredt - omit checkClosed() in order to be able to handle the result of a", "// SHUTDOWN query", "// checkClosed();", "//--------------------------JDBC 2.0-----------------------------", "// fredt - omit checkClosed() in order to be able to handle the result of a", "// SHUTDOWN query", "// checkClosed();", "//#ifdef JAVA2FULL", "//#else", "//#endif JAVA2", "//--------------------------JDBC 3.0-----------------------------", "//#ifdef JAVA4", "//#endif JAVA4", "//#ifdef JAVA4", "//#endif JAVA4", "//#ifdef JAVA4", "//#endif JAVA4", "//#ifdef JAVA4", "//#endif JAVA4", "//#ifdef JAVA4", "//#endif JAVA4", "//#ifdef JAVA4", "//#endif JAVA4", "//#ifdef JAVA4", "//#endif JAVA4", "//#ifdef JAVA4", "//#endif JAVA4", "//#ifdef JAVA4", "//#endif JAVA4", "// -------------------- Internal Implementation ----------------------------", "// PRE: assume connection is not null and is not closed", "// PRE: assume type is a valid result set type code", "//#ifdef JAVA6", "//#endif JAVA6" ]
[ { "param": "Statement", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Statement", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3598123da8208e03667f6f980bcfdc0dfa7cad57
minfrin/directory-studio
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/impl/Bookmark.java
[ "Apache-2.0" ]
Java
Bookmark
/** * Default implementation if IBookmark. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */
Default implementation if IBookmark. @author Apache Directory Project
[ "Default", "implementation", "if", "IBookmark", ".", "@author", "Apache", "Directory", "Project" ]
public class Bookmark implements IBookmark { /** The serialVersionUID. */ private static final long serialVersionUID = 2914726541167255499L; /** The connection. */ private IBrowserConnection connection; /** The bookmark parameter. */ private BookmarkParameter bookmarkParameter; /** The bookmark entry. */ private DelegateEntry bookmarkEntry; /** * Creates a new instance of Bookmark. */ protected Bookmark() { } /** * Creates a new instance of Bookmark. * * @param connection the connection * @param bookmarkParameter the bookmark parameter */ public Bookmark( IBrowserConnection connection, BookmarkParameter bookmarkParameter ) { this.connection = connection; this.bookmarkParameter = bookmarkParameter; this.bookmarkEntry = new BookmarkEntry( connection, bookmarkParameter.getDn() ); } /** * Creates a new instance of Bookmark. * * @param connection the connection * @param dn the target Dn * @param name the symbolic name */ public Bookmark( IBrowserConnection connection, Dn dn, String name ) { this.connection = connection; this.bookmarkParameter = new BookmarkParameter( dn, name ); this.bookmarkEntry = new BookmarkEntry( connection, dn ); } /** * {@inheritDoc} */ public Dn getDn() { return this.bookmarkParameter.getDn(); } /** * {@inheritDoc} */ public void setDn( Dn dn ) { this.bookmarkParameter.setDn( dn ); this.fireBookmarkUpdated( BookmarkUpdateEvent.Detail.BOOKMARK_UPDATED ); } /** * {@inheritDoc} */ public String getName() { return this.bookmarkParameter.getName(); } /** * {@inheritDoc} */ public void setName( String name ) { this.bookmarkParameter.setName( name ); this.fireBookmarkUpdated( BookmarkUpdateEvent.Detail.BOOKMARK_UPDATED ); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public Object getAdapter( Class adapter ) { Class<?> clazz = ( Class<?> ) adapter; if ( clazz.isAssignableFrom( ISearchPageScoreComputer.class ) ) { return new LdapSearchPageScoreComputer(); } if ( clazz.isAssignableFrom( Connection.class ) ) { return getBrowserConnection().getConnection(); } if ( clazz.isAssignableFrom( IBrowserConnection.class ) ) { return getBrowserConnection(); } if ( clazz.isAssignableFrom( IEntry.class ) ) { return getEntry(); } if ( clazz.isAssignableFrom( IBookmark.class ) ) { return this; } return null; } private void fireBookmarkUpdated( BookmarkUpdateEvent.Detail detail ) { if ( this.getName() != null && !"".equals( this.getName() ) ) { //$NON-NLS-1$ EventRegistry.fireBookmarkUpdated( new BookmarkUpdateEvent( this, detail ), this ); } } /** * {@inheritDoc} */ public BookmarkParameter getBookmarkParameter() { return bookmarkParameter; } /** * {@inheritDoc} */ public void setBookmarkParameter( BookmarkParameter bookmarkParameter ) { this.bookmarkParameter = bookmarkParameter; } /** * {@inheritDoc} */ public IBrowserConnection getBrowserConnection() { return this.connection; } /** * {@inheritDoc} */ public IEntry getEntry() { return this.bookmarkEntry; } /** * {@inheritDoc} */ public String toString() { return this.getName(); } }
[ "public", "class", "Bookmark", "implements", "IBookmark", "{", "/** The serialVersionUID. */", "private", "static", "final", "long", "serialVersionUID", "=", "2914726541167255499L", ";", "/** The connection. */", "private", "IBrowserConnection", "connection", ";", "/** The bookmark parameter. */", "private", "BookmarkParameter", "bookmarkParameter", ";", "/** The bookmark entry. */", "private", "DelegateEntry", "bookmarkEntry", ";", "/**\n * Creates a new instance of Bookmark.\n */", "protected", "Bookmark", "(", ")", "{", "}", "/**\n * Creates a new instance of Bookmark.\n *\n * @param connection the connection\n * @param bookmarkParameter the bookmark parameter\n */", "public", "Bookmark", "(", "IBrowserConnection", "connection", ",", "BookmarkParameter", "bookmarkParameter", ")", "{", "this", ".", "connection", "=", "connection", ";", "this", ".", "bookmarkParameter", "=", "bookmarkParameter", ";", "this", ".", "bookmarkEntry", "=", "new", "BookmarkEntry", "(", "connection", ",", "bookmarkParameter", ".", "getDn", "(", ")", ")", ";", "}", "/**\n * Creates a new instance of Bookmark.\n *\n * @param connection the connection\n * @param dn the target Dn\n * @param name the symbolic name\n */", "public", "Bookmark", "(", "IBrowserConnection", "connection", ",", "Dn", "dn", ",", "String", "name", ")", "{", "this", ".", "connection", "=", "connection", ";", "this", ".", "bookmarkParameter", "=", "new", "BookmarkParameter", "(", "dn", ",", "name", ")", ";", "this", ".", "bookmarkEntry", "=", "new", "BookmarkEntry", "(", "connection", ",", "dn", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "public", "Dn", "getDn", "(", ")", "{", "return", "this", ".", "bookmarkParameter", ".", "getDn", "(", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "public", "void", "setDn", "(", "Dn", "dn", ")", "{", "this", ".", "bookmarkParameter", ".", "setDn", "(", "dn", ")", ";", "this", ".", "fireBookmarkUpdated", "(", "BookmarkUpdateEvent", ".", "Detail", ".", "BOOKMARK_UPDATED", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "public", "String", "getName", "(", ")", "{", "return", "this", ".", "bookmarkParameter", ".", "getName", "(", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "public", "void", "setName", "(", "String", "name", ")", "{", "this", ".", "bookmarkParameter", ".", "setName", "(", "name", ")", ";", "this", ".", "fireBookmarkUpdated", "(", "BookmarkUpdateEvent", ".", "Detail", ".", "BOOKMARK_UPDATED", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "public", "Object", "getAdapter", "(", "Class", "adapter", ")", "{", "Class", "<", "?", ">", "clazz", "=", "(", "Class", "<", "?", ">", ")", "adapter", ";", "if", "(", "clazz", ".", "isAssignableFrom", "(", "ISearchPageScoreComputer", ".", "class", ")", ")", "{", "return", "new", "LdapSearchPageScoreComputer", "(", ")", ";", "}", "if", "(", "clazz", ".", "isAssignableFrom", "(", "Connection", ".", "class", ")", ")", "{", "return", "getBrowserConnection", "(", ")", ".", "getConnection", "(", ")", ";", "}", "if", "(", "clazz", ".", "isAssignableFrom", "(", "IBrowserConnection", ".", "class", ")", ")", "{", "return", "getBrowserConnection", "(", ")", ";", "}", "if", "(", "clazz", ".", "isAssignableFrom", "(", "IEntry", ".", "class", ")", ")", "{", "return", "getEntry", "(", ")", ";", "}", "if", "(", "clazz", ".", "isAssignableFrom", "(", "IBookmark", ".", "class", ")", ")", "{", "return", "this", ";", "}", "return", "null", ";", "}", "private", "void", "fireBookmarkUpdated", "(", "BookmarkUpdateEvent", ".", "Detail", "detail", ")", "{", "if", "(", "this", ".", "getName", "(", ")", "!=", "null", "&&", "!", "\"", "\"", ".", "equals", "(", "this", ".", "getName", "(", ")", ")", ")", "{", "EventRegistry", ".", "fireBookmarkUpdated", "(", "new", "BookmarkUpdateEvent", "(", "this", ",", "detail", ")", ",", "this", ")", ";", "}", "}", "/**\n * {@inheritDoc}\n */", "public", "BookmarkParameter", "getBookmarkParameter", "(", ")", "{", "return", "bookmarkParameter", ";", "}", "/**\n * {@inheritDoc}\n */", "public", "void", "setBookmarkParameter", "(", "BookmarkParameter", "bookmarkParameter", ")", "{", "this", ".", "bookmarkParameter", "=", "bookmarkParameter", ";", "}", "/**\n * {@inheritDoc}\n */", "public", "IBrowserConnection", "getBrowserConnection", "(", ")", "{", "return", "this", ".", "connection", ";", "}", "/**\n * {@inheritDoc}\n */", "public", "IEntry", "getEntry", "(", ")", "{", "return", "this", ".", "bookmarkEntry", ";", "}", "/**\n * {@inheritDoc}\n */", "public", "String", "toString", "(", ")", "{", "return", "this", ".", "getName", "(", ")", ";", "}", "}" ]
Default implementation if IBookmark.
[ "Default", "implementation", "if", "IBookmark", "." ]
[ "//$NON-NLS-1$" ]
[ { "param": "IBookmark", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IBookmark", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35a39939661d2bff1fd2753c0d973acd302b7839
jaebradley/leetcode
src/main/java/problems/DecodeString.java
[ "MIT" ]
Java
DecodeString
/** * https://leetcode.com/problems/decode-string/description/ * algorithms * Medium (42.04%) * Total Accepted: 51.9K * Total Submissions: 123.4K * Testcase Example: '"3[a]2[bc]"' Given an encoded string, return it's decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. Examples: s = "3[a]2[bc]", return "aaabcbc". s = "3[a2[c]]", return "accaccacc". s = "2[abc]3[cd]ef", return "abcabccdcdcdef". */
Given an encoded string, return it's decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
[ "Given", "an", "encoded", "string", "return", "it", "'", "s", "decoded", "string", ".", "The", "encoding", "rule", "is", ":", "k", "[", "encoded_string", "]", "where", "the", "encoded_string", "inside", "the", "square", "brackets", "is", "being", "repeated", "exactly", "k", "times", ".", "Note", "that", "k", "is", "guaranteed", "to", "be", "a", "positive", "integer", ".", "You", "may", "assume", "that", "the", "input", "string", "is", "always", "valid", ";", "No", "extra", "white", "spaces", "square", "brackets", "are", "well", "-", "formed", "etc", ".", "Furthermore", "you", "may", "assume", "that", "the", "original", "data", "does", "not", "contain", "any", "digits", "and", "that", "digits", "are", "only", "for", "those", "repeat", "numbers", "k", ".", "For", "example", "there", "won", "'", "t", "be", "input", "like", "3a", "or", "2", "[", "4", "]", "." ]
public class DecodeString { public static String decodeString(String s) { StringBuilder result = new StringBuilder(); Stack<Integer> counts = new Stack<>(); Stack<StringBuilder> results = new Stack<>(); int currentCount = 1; int index = 0; while (index < s.length()) { char c = s.charAt(index); if (Character.isDigit(c)) { counts.push(currentCount); results.push(result); StringBuilder countSb = new StringBuilder(); while (Character.isDigit(c)) { countSb.append(c); index++; c = s.charAt(index); } result = new StringBuilder(); currentCount = Integer.valueOf(countSb.toString()); } else if (Character.isLetter(c)) { result.append(c); } else if (c == ']') { StringBuilder lastResult = results.pop(); for (int j = 0; j < currentCount; j++) { lastResult.append(result); } result = lastResult; currentCount = counts.pop(); } index++; } return result.toString(); } }
[ "public", "class", "DecodeString", "{", "public", "static", "String", "decodeString", "(", "String", "s", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "Stack", "<", "Integer", ">", "counts", "=", "new", "Stack", "<", ">", "(", ")", ";", "Stack", "<", "StringBuilder", ">", "results", "=", "new", "Stack", "<", ">", "(", ")", ";", "int", "currentCount", "=", "1", ";", "int", "index", "=", "0", ";", "while", "(", "index", "<", "s", ".", "length", "(", ")", ")", "{", "char", "c", "=", "s", ".", "charAt", "(", "index", ")", ";", "if", "(", "Character", ".", "isDigit", "(", "c", ")", ")", "{", "counts", ".", "push", "(", "currentCount", ")", ";", "results", ".", "push", "(", "result", ")", ";", "StringBuilder", "countSb", "=", "new", "StringBuilder", "(", ")", ";", "while", "(", "Character", ".", "isDigit", "(", "c", ")", ")", "{", "countSb", ".", "append", "(", "c", ")", ";", "index", "++", ";", "c", "=", "s", ".", "charAt", "(", "index", ")", ";", "}", "result", "=", "new", "StringBuilder", "(", ")", ";", "currentCount", "=", "Integer", ".", "valueOf", "(", "countSb", ".", "toString", "(", ")", ")", ";", "}", "else", "if", "(", "Character", ".", "isLetter", "(", "c", ")", ")", "{", "result", ".", "append", "(", "c", ")", ";", "}", "else", "if", "(", "c", "==", "']'", ")", "{", "StringBuilder", "lastResult", "=", "results", ".", "pop", "(", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "currentCount", ";", "j", "++", ")", "{", "lastResult", ".", "append", "(", "result", ")", ";", "}", "result", "=", "lastResult", ";", "currentCount", "=", "counts", ".", "pop", "(", ")", ";", "}", "index", "++", ";", "}", "return", "result", ".", "toString", "(", ")", ";", "}", "}" ]
https://leetcode.com/problems/decode-string/description algorithms Medium (42.04%) Total Accepted: 51.9K Total Submissions: 123.4K Testcase Example: '"3[a]2[bc]"'
[ "https", ":", "//", "leetcode", ".", "com", "/", "problems", "/", "decode", "-", "string", "/", "description", "algorithms", "Medium", "(", "42", ".", "04%", ")", "Total", "Accepted", ":", "51", ".", "9K", "Total", "Submissions", ":", "123", ".", "4K", "Testcase", "Example", ":", "'", "\"", "3", "[", "a", "]", "2", "[", "bc", "]", "\"", "'" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
35a45d51c9f5b937f4b5d698f29396f4af69031a
hellgate75/dataflow-flow-centric-poc
dataflow-core-lib-logging/src/main/java/com/dataflow/core/lib/logger/domain/TransactionInstanceCache.java
[ "CC0-1.0" ]
Java
TransactionInstanceCache
/** * * This class defines instances of the logger data based on thread ID. * */
This class defines instances of the logger data based on thread ID.
[ "This", "class", "defines", "instances", "of", "the", "logger", "data", "based", "on", "thread", "ID", "." ]
public class TransactionInstanceCache { private Long threadId; private LocalDateTime lastAccessed; private ApplicationLogSummary curentLogSet; private Hashtable<String, OperationalData> pendingEvents = new Hashtable<String, OperationalData>(); private LogLevel onetimeLogLevel = LogLevel.ERROR; private String indexName; /** * @param threadId * @param lastAccessed * @param curentLogSet * @param pendingEvents * @param onetimeLogLevel * @param indexName */ public TransactionInstanceCache(Long threadId, LocalDateTime lastAccessed, ApplicationLogSummary curentLogSet, Hashtable<String, OperationalData> pendingEvents, LogLevel onetimeLogLevel, String indexName) { this.threadId = threadId; this.lastAccessed = lastAccessed; this.curentLogSet = curentLogSet; this.pendingEvents = pendingEvents; this.onetimeLogLevel = onetimeLogLevel; this.indexName = indexName; } public TransactionInstanceCache() { } /** * @return the threadId */ public Long getThreadId() { return threadId; } /** * @param threadId the threadId to set */ public void setThreadId(Long threadId) { this.threadId = threadId; } /** * @return the lastAccessed */ public LocalDateTime getLastAccessed() { return lastAccessed; } /** * @param lastAccessed the lastAccessed to set */ public void setLastAccessed(LocalDateTime lastAccessed) { this.lastAccessed = lastAccessed; } /** * @return the curentLogSet */ public ApplicationLogSummary getCurentLogSet() { return curentLogSet; } /** * @param curentLogSet the curentLogSet to set */ public void setCurentLogSet(ApplicationLogSummary curentLogSet) { this.curentLogSet = curentLogSet; } /** * @return the pendingEvents */ public Hashtable<String, OperationalData> getPendingEvents() { return pendingEvents; } /** * @param pendingEvents the pendingEvents to set */ public void setPendingEvents(Hashtable<String, OperationalData> pendingEvents) { this.pendingEvents = pendingEvents; } /** * @return the onetimeLogLevel */ public LogLevel getOnetimeLogLevel() { return onetimeLogLevel; } /** * @param onetimeLogLevel the onetimeLogLevel to set */ public void setOnetimeLogLevel(LogLevel onetimeLogLevel) { this.onetimeLogLevel = onetimeLogLevel; } /** * @return the indexName */ public String getIndexName() { return indexName; } /** * @param indexName the indexName to set */ public void setIndexName(String indexName) { this.indexName = indexName; } }
[ "public", "class", "TransactionInstanceCache", "{", "private", "Long", "threadId", ";", "private", "LocalDateTime", "lastAccessed", ";", "private", "ApplicationLogSummary", "curentLogSet", ";", "private", "Hashtable", "<", "String", ",", "OperationalData", ">", "pendingEvents", "=", "new", "Hashtable", "<", "String", ",", "OperationalData", ">", "(", ")", ";", "private", "LogLevel", "onetimeLogLevel", "=", "LogLevel", ".", "ERROR", ";", "private", "String", "indexName", ";", "/**\n\t * @param threadId\n\t * @param lastAccessed\n\t * @param curentLogSet\n\t * @param pendingEvents\n\t * @param onetimeLogLevel\n\t * @param indexName\n\t */", "public", "TransactionInstanceCache", "(", "Long", "threadId", ",", "LocalDateTime", "lastAccessed", ",", "ApplicationLogSummary", "curentLogSet", ",", "Hashtable", "<", "String", ",", "OperationalData", ">", "pendingEvents", ",", "LogLevel", "onetimeLogLevel", ",", "String", "indexName", ")", "{", "this", ".", "threadId", "=", "threadId", ";", "this", ".", "lastAccessed", "=", "lastAccessed", ";", "this", ".", "curentLogSet", "=", "curentLogSet", ";", "this", ".", "pendingEvents", "=", "pendingEvents", ";", "this", ".", "onetimeLogLevel", "=", "onetimeLogLevel", ";", "this", ".", "indexName", "=", "indexName", ";", "}", "public", "TransactionInstanceCache", "(", ")", "{", "}", "/**\n\t * @return the threadId\n\t */", "public", "Long", "getThreadId", "(", ")", "{", "return", "threadId", ";", "}", "/**\n\t * @param threadId the threadId to set\n\t */", "public", "void", "setThreadId", "(", "Long", "threadId", ")", "{", "this", ".", "threadId", "=", "threadId", ";", "}", "/**\n\t * @return the lastAccessed\n\t */", "public", "LocalDateTime", "getLastAccessed", "(", ")", "{", "return", "lastAccessed", ";", "}", "/**\n\t * @param lastAccessed the lastAccessed to set\n\t */", "public", "void", "setLastAccessed", "(", "LocalDateTime", "lastAccessed", ")", "{", "this", ".", "lastAccessed", "=", "lastAccessed", ";", "}", "/**\n\t * @return the curentLogSet\n\t */", "public", "ApplicationLogSummary", "getCurentLogSet", "(", ")", "{", "return", "curentLogSet", ";", "}", "/**\n\t * @param curentLogSet the curentLogSet to set\n\t */", "public", "void", "setCurentLogSet", "(", "ApplicationLogSummary", "curentLogSet", ")", "{", "this", ".", "curentLogSet", "=", "curentLogSet", ";", "}", "/**\n\t * @return the pendingEvents\n\t */", "public", "Hashtable", "<", "String", ",", "OperationalData", ">", "getPendingEvents", "(", ")", "{", "return", "pendingEvents", ";", "}", "/**\n\t * @param pendingEvents the pendingEvents to set\n\t */", "public", "void", "setPendingEvents", "(", "Hashtable", "<", "String", ",", "OperationalData", ">", "pendingEvents", ")", "{", "this", ".", "pendingEvents", "=", "pendingEvents", ";", "}", "/**\n\t * @return the onetimeLogLevel\n\t */", "public", "LogLevel", "getOnetimeLogLevel", "(", ")", "{", "return", "onetimeLogLevel", ";", "}", "/**\n\t * @param onetimeLogLevel the onetimeLogLevel to set\n\t */", "public", "void", "setOnetimeLogLevel", "(", "LogLevel", "onetimeLogLevel", ")", "{", "this", ".", "onetimeLogLevel", "=", "onetimeLogLevel", ";", "}", "/**\n\t * @return the indexName\n\t */", "public", "String", "getIndexName", "(", ")", "{", "return", "indexName", ";", "}", "/**\n\t * @param indexName the indexName to set\n\t */", "public", "void", "setIndexName", "(", "String", "indexName", ")", "{", "this", ".", "indexName", "=", "indexName", ";", "}", "}" ]
This class defines instances of the logger data based on thread ID.
[ "This", "class", "defines", "instances", "of", "the", "logger", "data", "based", "on", "thread", "ID", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
35a59d99749a0910bc42274b50d4e57ab1a3cf0f
johnmasiello/Lyrics-Grabber
app/src/main/java/com/example/john/lyricsbuddy/PaddedBackgroundColorSpan.java
[ "Apache-2.0" ]
Java
PaddedBackgroundColorSpan
/** * Created by john on 3/27/18. * Adds padding to backgroundColorSpan * https://medium.com/@tokudu/android-adding-padding-to-backgroundcolorspan-179ab4fae187 */
Created by john on 3/27/18.
[ "Created", "by", "john", "on", "3", "/", "27", "/", "18", "." ]
class PaddedBackgroundColorSpan implements LineBackgroundSpan { private int mPadding = 0; private int mBackgroundColor = Color.WHITE; private Rect mBgRect; public static final float LINE_SPACING_MULTIPLIER = 1.2f; private static final int JUSTIFY_CENTER = 0; private static final int JUSTIFY_FULL = 1; private final int alignment = JUSTIFY_FULL; PaddedBackgroundColorSpan(int padding, int backgroundColor) { this.mPadding = padding; this.mBackgroundColor = backgroundColor; mBgRect = new Rect(); } @Override public void drawBackground(Canvas c, Paint p, int left, int right, int top, int baseline, int bottom, CharSequence text, int start, int end, int lnum) { final int paintColor = p.getColor(); Paint.FontMetricsInt fmi = p.getFontMetricsInt(); int inflatePadding = (int) (mPadding * 1.5f); int lesserPadding = (int)((fmi.bottom - fmi.top) * (LINE_SPACING_MULTIPLIER - 1.0f)) >> 1; int paddingTop, paddingBottom; paddingTop = paddingBottom = lesserPadding + 2; switch (alignment) { case JUSTIFY_CENTER: final int textWidth = Math.round(p.measureText(text, start, end)); final int midH = (left + right) >> 1; // Draw the background... // Assuming center alignment of text mBgRect.set(midH - (textWidth >> 1) - inflatePadding, baseline + fmi.top - paddingTop, midH + (textWidth >> 1) + inflatePadding, baseline + fmi.bottom + paddingBottom); break; case JUSTIFY_FULL: default: mBgRect.set(left - inflatePadding, baseline + fmi.top - paddingTop, right + inflatePadding, baseline + fmi.bottom + paddingBottom); } p.setColor(mBackgroundColor); c.drawRect(mBgRect, p); p.setColor(paintColor); } }
[ "class", "PaddedBackgroundColorSpan", "implements", "LineBackgroundSpan", "{", "private", "int", "mPadding", "=", "0", ";", "private", "int", "mBackgroundColor", "=", "Color", ".", "WHITE", ";", "private", "Rect", "mBgRect", ";", "public", "static", "final", "float", "LINE_SPACING_MULTIPLIER", "=", "1.2f", ";", "private", "static", "final", "int", "JUSTIFY_CENTER", "=", "0", ";", "private", "static", "final", "int", "JUSTIFY_FULL", "=", "1", ";", "private", "final", "int", "alignment", "=", "JUSTIFY_FULL", ";", "PaddedBackgroundColorSpan", "(", "int", "padding", ",", "int", "backgroundColor", ")", "{", "this", ".", "mPadding", "=", "padding", ";", "this", ".", "mBackgroundColor", "=", "backgroundColor", ";", "mBgRect", "=", "new", "Rect", "(", ")", ";", "}", "@", "Override", "public", "void", "drawBackground", "(", "Canvas", "c", ",", "Paint", "p", ",", "int", "left", ",", "int", "right", ",", "int", "top", ",", "int", "baseline", ",", "int", "bottom", ",", "CharSequence", "text", ",", "int", "start", ",", "int", "end", ",", "int", "lnum", ")", "{", "final", "int", "paintColor", "=", "p", ".", "getColor", "(", ")", ";", "Paint", ".", "FontMetricsInt", "fmi", "=", "p", ".", "getFontMetricsInt", "(", ")", ";", "int", "inflatePadding", "=", "(", "int", ")", "(", "mPadding", "*", "1.5f", ")", ";", "int", "lesserPadding", "=", "(", "int", ")", "(", "(", "fmi", ".", "bottom", "-", "fmi", ".", "top", ")", "*", "(", "LINE_SPACING_MULTIPLIER", "-", "1.0f", ")", ")", ">>", "1", ";", "int", "paddingTop", ",", "paddingBottom", ";", "paddingTop", "=", "paddingBottom", "=", "lesserPadding", "+", "2", ";", "switch", "(", "alignment", ")", "{", "case", "JUSTIFY_CENTER", ":", "final", "int", "textWidth", "=", "Math", ".", "round", "(", "p", ".", "measureText", "(", "text", ",", "start", ",", "end", ")", ")", ";", "final", "int", "midH", "=", "(", "left", "+", "right", ")", ">>", "1", ";", "mBgRect", ".", "set", "(", "midH", "-", "(", "textWidth", ">>", "1", ")", "-", "inflatePadding", ",", "baseline", "+", "fmi", ".", "top", "-", "paddingTop", ",", "midH", "+", "(", "textWidth", ">>", "1", ")", "+", "inflatePadding", ",", "baseline", "+", "fmi", ".", "bottom", "+", "paddingBottom", ")", ";", "break", ";", "case", "JUSTIFY_FULL", ":", "default", ":", "mBgRect", ".", "set", "(", "left", "-", "inflatePadding", ",", "baseline", "+", "fmi", ".", "top", "-", "paddingTop", ",", "right", "+", "inflatePadding", ",", "baseline", "+", "fmi", ".", "bottom", "+", "paddingBottom", ")", ";", "}", "p", ".", "setColor", "(", "mBackgroundColor", ")", ";", "c", ".", "drawRect", "(", "mBgRect", ",", "p", ")", ";", "p", ".", "setColor", "(", "paintColor", ")", ";", "}", "}" ]
Created by john on 3/27/18.
[ "Created", "by", "john", "on", "3", "/", "27", "/", "18", "." ]
[ "// Draw the background...", "// Assuming center alignment of text" ]
[ { "param": "LineBackgroundSpan", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "LineBackgroundSpan", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35adab28b06f748329cde2457f64853e0d60b2aa
linux-china/ali-oss-java-cli
src/main/java/org/mvnsearch/ali/oss/spring/shell/converters/ObjectKeyConverter.java
[ "MIT" ]
Java
ObjectKeyConverter
/** * object key converter * * @author linux_china */
object key converter @author linux_china
[ "object", "key", "converter", "@author", "linux_china" ]
public class ObjectKeyConverter implements Converter<ObjectKey> { /** * aliyun OSS service */ private AliyunOssService aliyunOssService; /** * inject aliyun oss service * * @param aliyunOssService aliyun oss service */ public void setAliyunOssService(AliyunOssService aliyunOssService) { this.aliyunOssService = aliyunOssService; } /** * Indicates whether this converter supports the given type in the given option context * * @param type the type being checked * @param optionContext a non-<code>null</code> string that customises the * behaviour of this converter for a given {@link org.springframework.shell.core.annotation.CliOption} of a given * {@link org.springframework.shell.core.annotation.CliCommand}; the contents will have special meaning to this * converter (e.g. be a comma-separated list of keywords known to this * converter) * @return see above */ public boolean supports(Class<?> type, String optionContext) { return type.getCanonicalName().equals(ObjectKey.class.getCanonicalName()); } /** * Converts from the given String value to type T * * @param value the value to convert * @param targetType the type being converted to; can't be <code>null</code> * @param optionContext a non-<code>null</code> string that customises the * behaviour of this converter for a given {@link org.springframework.shell.core.annotation.CliOption} of a given * {@link org.springframework.shell.core.annotation.CliCommand}; the contents will have special meaning to this * converter (e.g. be a comma-separated list of keywords known to this * converter) * @return see above * @throws RuntimeException if the given value could not be converted */ @SuppressWarnings("unchecked") public ObjectKey convertFromText(String value, Class<?> targetType, String optionContext) { Class<ObjectKey> enumClass = (Class<ObjectKey>) targetType; try { ObjectKey bucket = enumClass.newInstance(); bucket.setKey(value); return bucket; } catch (Exception ignore) { } return null; } /** * Populates the given list with the possible completions * * @param completions the list to populate; can't be <code>null</code> * @param targetType the type of parameter for which a string is being entered * @param existingData what the user has typed so far * @param optionContext a non-<code>null</code> string that customises the * behaviour of this converter for a given {@link org.springframework.shell.core.annotation.CliOption} of a given * {@link org.springframework.shell.core.annotation.CliCommand}; the contents will have special meaning to this * converter (e.g. be a comma-separated list of keywords known to this * converter) * @param target target method * @return <code>true</code> if all the added completions are complete * values, or <code>false</code> if the user can press TAB to add further * information to some or all of them */ public boolean getAllPossibleValues(List<Completion> completions, Class<?> targetType, String existingData, String optionContext, MethodTarget target) { OSSUri objectUri = OssOperationCommands.currentBucket; if (existingData != null && existingData.startsWith("oss://")) { return true; } try { String bucketName = objectUri.getBucket(); String key = objectUri.getFilePath(); ObjectListing objectListing = aliyunOssService.list(bucketName, key + existingData, 40); for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) { String candidate = objectSummary.getKey(); if (key != null && candidate.startsWith(key)) { candidate = candidate.replace(key, ""); } if (existingData == null || "".equals(existingData) || candidate.startsWith(existingData) || existingData.startsWith(candidate) || candidate.toUpperCase().startsWith(existingData.toUpperCase()) || existingData.toUpperCase().startsWith(candidate.toUpperCase())) { completions.add(new Completion(candidate)); } } } catch (Exception e) { e.printStackTrace(); } return true; } }
[ "public", "class", "ObjectKeyConverter", "implements", "Converter", "<", "ObjectKey", ">", "{", "/**\n * aliyun OSS service\n */", "private", "AliyunOssService", "aliyunOssService", ";", "/**\n * inject aliyun oss service\n *\n * @param aliyunOssService aliyun oss service\n */", "public", "void", "setAliyunOssService", "(", "AliyunOssService", "aliyunOssService", ")", "{", "this", ".", "aliyunOssService", "=", "aliyunOssService", ";", "}", "/**\n * Indicates whether this converter supports the given type in the given option context\n *\n * @param type the type being checked\n * @param optionContext a non-<code>null</code> string that customises the\n * behaviour of this converter for a given {@link org.springframework.shell.core.annotation.CliOption} of a given\n * {@link org.springframework.shell.core.annotation.CliCommand}; the contents will have special meaning to this\n * converter (e.g. be a comma-separated list of keywords known to this\n * converter)\n * @return see above\n */", "public", "boolean", "supports", "(", "Class", "<", "?", ">", "type", ",", "String", "optionContext", ")", "{", "return", "type", ".", "getCanonicalName", "(", ")", ".", "equals", "(", "ObjectKey", ".", "class", ".", "getCanonicalName", "(", ")", ")", ";", "}", "/**\n * Converts from the given String value to type T\n *\n * @param value the value to convert\n * @param targetType the type being converted to; can't be <code>null</code>\n * @param optionContext a non-<code>null</code> string that customises the\n * behaviour of this converter for a given {@link org.springframework.shell.core.annotation.CliOption} of a given\n * {@link org.springframework.shell.core.annotation.CliCommand}; the contents will have special meaning to this\n * converter (e.g. be a comma-separated list of keywords known to this\n * converter)\n * @return see above\n * @throws RuntimeException if the given value could not be converted\n */", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "public", "ObjectKey", "convertFromText", "(", "String", "value", ",", "Class", "<", "?", ">", "targetType", ",", "String", "optionContext", ")", "{", "Class", "<", "ObjectKey", ">", "enumClass", "=", "(", "Class", "<", "ObjectKey", ">", ")", "targetType", ";", "try", "{", "ObjectKey", "bucket", "=", "enumClass", ".", "newInstance", "(", ")", ";", "bucket", ".", "setKey", "(", "value", ")", ";", "return", "bucket", ";", "}", "catch", "(", "Exception", "ignore", ")", "{", "}", "return", "null", ";", "}", "/**\n * Populates the given list with the possible completions\n *\n * @param completions the list to populate; can't be <code>null</code>\n * @param targetType the type of parameter for which a string is being entered\n * @param existingData what the user has typed so far\n * @param optionContext a non-<code>null</code> string that customises the\n * behaviour of this converter for a given {@link org.springframework.shell.core.annotation.CliOption} of a given\n * {@link org.springframework.shell.core.annotation.CliCommand}; the contents will have special meaning to this\n * converter (e.g. be a comma-separated list of keywords known to this\n * converter)\n * @param target target method\n * @return <code>true</code> if all the added completions are complete\n * values, or <code>false</code> if the user can press TAB to add further\n * information to some or all of them\n */", "public", "boolean", "getAllPossibleValues", "(", "List", "<", "Completion", ">", "completions", ",", "Class", "<", "?", ">", "targetType", ",", "String", "existingData", ",", "String", "optionContext", ",", "MethodTarget", "target", ")", "{", "OSSUri", "objectUri", "=", "OssOperationCommands", ".", "currentBucket", ";", "if", "(", "existingData", "!=", "null", "&&", "existingData", ".", "startsWith", "(", "\"", "oss://", "\"", ")", ")", "{", "return", "true", ";", "}", "try", "{", "String", "bucketName", "=", "objectUri", ".", "getBucket", "(", ")", ";", "String", "key", "=", "objectUri", ".", "getFilePath", "(", ")", ";", "ObjectListing", "objectListing", "=", "aliyunOssService", ".", "list", "(", "bucketName", ",", "key", "+", "existingData", ",", "40", ")", ";", "for", "(", "OSSObjectSummary", "objectSummary", ":", "objectListing", ".", "getObjectSummaries", "(", ")", ")", "{", "String", "candidate", "=", "objectSummary", ".", "getKey", "(", ")", ";", "if", "(", "key", "!=", "null", "&&", "candidate", ".", "startsWith", "(", "key", ")", ")", "{", "candidate", "=", "candidate", ".", "replace", "(", "key", ",", "\"", "\"", ")", ";", "}", "if", "(", "existingData", "==", "null", "||", "\"", "\"", ".", "equals", "(", "existingData", ")", "||", "candidate", ".", "startsWith", "(", "existingData", ")", "||", "existingData", ".", "startsWith", "(", "candidate", ")", "||", "candidate", ".", "toUpperCase", "(", ")", ".", "startsWith", "(", "existingData", ".", "toUpperCase", "(", ")", ")", "||", "existingData", ".", "toUpperCase", "(", ")", ".", "startsWith", "(", "candidate", ".", "toUpperCase", "(", ")", ")", ")", "{", "completions", ".", "add", "(", "new", "Completion", "(", "candidate", ")", ")", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "true", ";", "}", "}" ]
object key converter @author linux_china
[ "object", "key", "converter", "@author", "linux_china" ]
[]
[ { "param": "Converter<ObjectKey>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Converter<ObjectKey>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35b33a6d38dca317e7ac18b6b48dda2490d857cf
welkinbai/learn-mybatis
src/test/java/me/welkinbai/mybatis/withoutspring/SettingsTest.java
[ "MIT" ]
Java
SettingsTest
/** * Created by welkinbai on 2017/1/3. */
Created by welkinbai on 2017/1/3.
[ "Created", "by", "welkinbai", "on", "2017", "/", "1", "/", "3", "." ]
public class SettingsTest { private SqlSession sqlSession; private SqlSessionFactory sqlSessionFactory; @Before public void setUp() throws Exception { init(); } private void init() throws IOException { String resource = "mybatisconfig_test_settings.xml";//指定xml配置文件的路径 InputStream inputStream = Resources.getResourceAsStream(resource);//使用资源工具类加载配置文件到流中 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//通过一个配置文件的流来创建Factory对象 this.sqlSessionFactory = sqlSessionFactory; sqlSession = sqlSessionFactory.openSession(); } /* * 测试方法(steps): * 1.mybatisconfig_test_settings.xml cacheEnabled->false * 2.run this unit test and see sql executed twice * 3.mybatisconfig_test_settings.xml cacheEnabled->true * 4.run this unit test again and see sql executed once * */ @Test public void testCloseCache() throws Exception { SqlSession sqlSession2; sqlSession2 = this.sqlSessionFactory.openSession(); try { CityMapper city = sqlSession.getMapper(CityMapper.class); System.out.println(city.selectById(1).getName()); sqlSession.close(); CityMapper city2 = sqlSession2.getMapper(CityMapper.class); System.out.println(city2.selectById(1).getName()); } finally { sqlSession.close(); sqlSession2.close(); } } /* * 测试方法(steps): * 1. CityMapper.xml insert useGeneratedKeys="true"->just remove it * 2. change mybatisconfig_test_settings.xml useGeneratedKeys->true * 3. run this unit test and see city.getId() return right number. useGeneratedKeys config take effect. * 4. add useGeneratedKeys="false" to CityMapper.xml insert * 5. run this unit test again and see useGeneratedKeys in CityMapper.xml cover useGeneratedKeys in mybatisconfig_test_settings.xml * */ @Test public void testUseGeneratedKeys() throws Exception { try { CityMapper cityMapper = sqlSession.getMapper(CityMapper.class); City city = new City(); city.setName("test_use_generated_keys"); city.setCountryCode("CHN"); city.setPopulation(122); city.setDistrict("wuhan"); cityMapper.insert(city); System.out.println(city.getId()); } finally { sqlSession.close(); } } /* * 测试方法(steps): * 1. change mybatisconfig_test_settings.xml autoMappingBehavior->NONE * 2. run this unit test and see result. * 3. change mybatisconfig_test_settings.xml autoMappingBehavior->PARTIAL * 4. run this unit test and see result. * 5. change mybatisconfig_test_settings.xml autoMappingBehavior->FULL * 6. run this unit test and see result. * 7. you can change selectByIdWithoutResultMap and selectByIdWithAssociationResult SQL,resultMap and see what happens * 8. you can add autoMapping="true" into resultMap,and see what happens * */ @Test public void testAutoMappingBehavior() throws Exception { try { CityMapper cityMapper = sqlSession.getMapper(CityMapper.class); City city = cityMapper.selectByIdWithoutResultMap(1); System.out.println(city); City city2 = cityMapper.selectByIdWithAssociationResult(1); System.out.println(city2); } finally { sqlSession.close(); } } /* * 测试方法(steps): * 1. change mybatisconfig_test_settings.xml autoMappingUnknownColumnBehavior->FAILING * 2. run this unit test and see result. * 3. change mybatisconfig_test_settings.xml autoMappingUnknownColumnBehavior->WARNING * 4. run this unit test and see result. * 5. change mybatisconfig_test_settings.xml autoMappingUnknownColumnBehavior->NONE * 6. run this unit test and see result. * */ @Test public void testAutoMappingUnknownColumnBehavior() throws Exception { try { CityMapper cityMapper = sqlSession.getMapper(CityMapper.class); City city = cityMapper.selectByIdWithUnknownColumnResult(1); System.out.println(city); } finally { sqlSession.close(); } } }
[ "public", "class", "SettingsTest", "{", "private", "SqlSession", "sqlSession", ";", "private", "SqlSessionFactory", "sqlSessionFactory", ";", "@", "Before", "public", "void", "setUp", "(", ")", "throws", "Exception", "{", "init", "(", ")", ";", "}", "private", "void", "init", "(", ")", "throws", "IOException", "{", "String", "resource", "=", "\"", "mybatisconfig_test_settings.xml", "\"", ";", "InputStream", "inputStream", "=", "Resources", ".", "getResourceAsStream", "(", "resource", ")", ";", "SqlSessionFactory", "sqlSessionFactory", "=", "new", "SqlSessionFactoryBuilder", "(", ")", ".", "build", "(", "inputStream", ")", ";", "this", ".", "sqlSessionFactory", "=", "sqlSessionFactory", ";", "sqlSession", "=", "sqlSessionFactory", ".", "openSession", "(", ")", ";", "}", "/*\r\n * 测试方法(steps):\r\n * 1.mybatisconfig_test_settings.xml cacheEnabled->false\r\n * 2.run this unit test and see sql executed twice\r\n * 3.mybatisconfig_test_settings.xml cacheEnabled->true\r\n * 4.run this unit test again and see sql executed once\r\n * */", "@", "Test", "public", "void", "testCloseCache", "(", ")", "throws", "Exception", "{", "SqlSession", "sqlSession2", ";", "sqlSession2", "=", "this", ".", "sqlSessionFactory", ".", "openSession", "(", ")", ";", "try", "{", "CityMapper", "city", "=", "sqlSession", ".", "getMapper", "(", "CityMapper", ".", "class", ")", ";", "System", ".", "out", ".", "println", "(", "city", ".", "selectById", "(", "1", ")", ".", "getName", "(", ")", ")", ";", "sqlSession", ".", "close", "(", ")", ";", "CityMapper", "city2", "=", "sqlSession2", ".", "getMapper", "(", "CityMapper", ".", "class", ")", ";", "System", ".", "out", ".", "println", "(", "city2", ".", "selectById", "(", "1", ")", ".", "getName", "(", ")", ")", ";", "}", "finally", "{", "sqlSession", ".", "close", "(", ")", ";", "sqlSession2", ".", "close", "(", ")", ";", "}", "}", "/*\r\n * 测试方法(steps):\r\n * 1. CityMapper.xml insert useGeneratedKeys=\"true\"->just remove it\r\n * 2. change mybatisconfig_test_settings.xml useGeneratedKeys->true\r\n * 3. run this unit test and see city.getId() return right number. useGeneratedKeys config take effect.\r\n * 4. add useGeneratedKeys=\"false\" to CityMapper.xml insert\r\n * 5. run this unit test again and see useGeneratedKeys in CityMapper.xml cover useGeneratedKeys in mybatisconfig_test_settings.xml\r\n * */", "@", "Test", "public", "void", "testUseGeneratedKeys", "(", ")", "throws", "Exception", "{", "try", "{", "CityMapper", "cityMapper", "=", "sqlSession", ".", "getMapper", "(", "CityMapper", ".", "class", ")", ";", "City", "city", "=", "new", "City", "(", ")", ";", "city", ".", "setName", "(", "\"", "test_use_generated_keys", "\"", ")", ";", "city", ".", "setCountryCode", "(", "\"", "CHN", "\"", ")", ";", "city", ".", "setPopulation", "(", "122", ")", ";", "city", ".", "setDistrict", "(", "\"", "wuhan", "\"", ")", ";", "cityMapper", ".", "insert", "(", "city", ")", ";", "System", ".", "out", ".", "println", "(", "city", ".", "getId", "(", ")", ")", ";", "}", "finally", "{", "sqlSession", ".", "close", "(", ")", ";", "}", "}", "/*\r\n * 测试方法(steps):\r\n * 1. change mybatisconfig_test_settings.xml autoMappingBehavior->NONE\r\n * 2. run this unit test and see result.\r\n * 3. change mybatisconfig_test_settings.xml autoMappingBehavior->PARTIAL\r\n * 4. run this unit test and see result.\r\n * 5. change mybatisconfig_test_settings.xml autoMappingBehavior->FULL\r\n * 6. run this unit test and see result.\r\n * 7. you can change selectByIdWithoutResultMap and selectByIdWithAssociationResult SQL,resultMap and see what happens\r\n * 8. you can add autoMapping=\"true\" into resultMap,and see what happens\r\n * */", "@", "Test", "public", "void", "testAutoMappingBehavior", "(", ")", "throws", "Exception", "{", "try", "{", "CityMapper", "cityMapper", "=", "sqlSession", ".", "getMapper", "(", "CityMapper", ".", "class", ")", ";", "City", "city", "=", "cityMapper", ".", "selectByIdWithoutResultMap", "(", "1", ")", ";", "System", ".", "out", ".", "println", "(", "city", ")", ";", "City", "city2", "=", "cityMapper", ".", "selectByIdWithAssociationResult", "(", "1", ")", ";", "System", ".", "out", ".", "println", "(", "city2", ")", ";", "}", "finally", "{", "sqlSession", ".", "close", "(", ")", ";", "}", "}", "/*\r\n * 测试方法(steps):\r\n * 1. change mybatisconfig_test_settings.xml autoMappingUnknownColumnBehavior->FAILING\r\n * 2. run this unit test and see result.\r\n * 3. change mybatisconfig_test_settings.xml autoMappingUnknownColumnBehavior->WARNING\r\n * 4. run this unit test and see result.\r\n * 5. change mybatisconfig_test_settings.xml autoMappingUnknownColumnBehavior->NONE\r\n * 6. run this unit test and see result.\r\n * */", "@", "Test", "public", "void", "testAutoMappingUnknownColumnBehavior", "(", ")", "throws", "Exception", "{", "try", "{", "CityMapper", "cityMapper", "=", "sqlSession", ".", "getMapper", "(", "CityMapper", ".", "class", ")", ";", "City", "city", "=", "cityMapper", ".", "selectByIdWithUnknownColumnResult", "(", "1", ")", ";", "System", ".", "out", ".", "println", "(", "city", ")", ";", "}", "finally", "{", "sqlSession", ".", "close", "(", ")", ";", "}", "}", "}" ]
Created by welkinbai on 2017/1/3.
[ "Created", "by", "welkinbai", "on", "2017", "/", "1", "/", "3", "." ]
[ "//指定xml配置文件的路径\r", "//使用资源工具类加载配置文件到流中\r", "//通过一个配置文件的流来创建Factory对象\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
35b4ecb35b19634806f7afe576506142c3f412f2
williamleif/PSRToolbox
src/afest/datastructures/tree/decision/DTNode.java
[ "Apache-2.0" ]
Java
DTNode
/** * Class to represent the data contained in a decision tree node. * @param <R> Type used to identify features in points. * @param <C> Type of object contained in the Node. */
Class to represent the data contained in a decision tree node. @param Type used to identify features in points. @param Type of object contained in the Node.
[ "Class", "to", "represent", "the", "data", "contained", "in", "a", "decision", "tree", "node", ".", "@param", "Type", "used", "to", "identify", "features", "in", "points", ".", "@param", "Type", "of", "object", "contained", "in", "the", "Node", "." ]
public class DTNode<R extends Serializable, C extends Serializable> extends BinaryTreeNode<DTNode<R, C>> implements Serializable { private static final long serialVersionUID = 1L; private ISplit<R> fSplit; private C fContent; /** * Construct a node with the following properties. */ public DTNode() { fSplit = null; fContent = null; } /** * Return true if the element is contained in the split, false otherwise. * @param <T> Type of points extending IPoint<R>. * @param element element to verify membership. * @return true if the element is contained in the split, false otherwise. */ public <T extends IPoint<R>> boolean split(T element) { if (fSplit == null) { throw new DecisionTreeException("No split contained in this node!"); } return fSplit.contains(element); } /** * Set the split of this node to the given split. * @param <T> Type of split for IPoint<R>. * @param split split used to separate elements in the node. */ public <T extends ISplit<R>> void setSplit(T split) { fSplit = split; } /** * Return the content of the leaf. * @return the content of the leaf. */ public C getContent() { if (fContent == null) { throw new DecisionTreeException("No label contained in this node!"); } return fContent; } /** * Set the label of the node to the given label. * @param content content to be returned by this node. */ public void setContent(C content) { fContent = content; } }
[ "public", "class", "DTNode", "<", "R", "extends", "Serializable", ",", "C", "extends", "Serializable", ">", "extends", "BinaryTreeNode", "<", "DTNode", "<", "R", ",", "C", ">", ">", "implements", "Serializable", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "private", "ISplit", "<", "R", ">", "fSplit", ";", "private", "C", "fContent", ";", "/**\n\t * Construct a node with the following properties.\n\t */", "public", "DTNode", "(", ")", "{", "fSplit", "=", "null", ";", "fContent", "=", "null", ";", "}", "/**\n\t * Return true if the element is contained in the split, false otherwise.\n\t * @param <T> Type of points extending IPoint<R>.\n\t * @param element element to verify membership.\n\t * @return true if the element is contained in the split, false otherwise.\n\t */", "public", "<", "T", "extends", "IPoint", "<", "R", ">", ">", "boolean", "split", "(", "T", "element", ")", "{", "if", "(", "fSplit", "==", "null", ")", "{", "throw", "new", "DecisionTreeException", "(", "\"", "No split contained in this node!", "\"", ")", ";", "}", "return", "fSplit", ".", "contains", "(", "element", ")", ";", "}", "/**\n\t * Set the split of this node to the given split.\n\t * @param <T> Type of split for IPoint<R>.\n\t * @param split split used to separate elements in the node.\n\t */", "public", "<", "T", "extends", "ISplit", "<", "R", ">", ">", "void", "setSplit", "(", "T", "split", ")", "{", "fSplit", "=", "split", ";", "}", "/**\n\t * Return the content of the leaf.\n\t * @return the content of the leaf.\n\t */", "public", "C", "getContent", "(", ")", "{", "if", "(", "fContent", "==", "null", ")", "{", "throw", "new", "DecisionTreeException", "(", "\"", "No label contained in this node!", "\"", ")", ";", "}", "return", "fContent", ";", "}", "/**\n\t * Set the label of the node to the given label.\n\t * @param content content to be returned by this node. \n\t */", "public", "void", "setContent", "(", "C", "content", ")", "{", "fContent", "=", "content", ";", "}", "}" ]
Class to represent the data contained in a decision tree node.
[ "Class", "to", "represent", "the", "data", "contained", "in", "a", "decision", "tree", "node", "." ]
[]
[ { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35b6d41d72d55ad209df462544e606c01702555b
SkygearIO/skygear-SDK-Android
skygear/src/main/java/io/skygear/skygear/SetDisableUserRequest.java
[ "Apache-2.0" ]
Java
SetDisableUserRequest
/** * The Disable Skygear User Request. */
The Disable Skygear User Request.
[ "The", "Disable", "Skygear", "User", "Request", "." ]
public class SetDisableUserRequest extends Request { /** * Returns a new request to enable the specified user account. * * @param userID the user id */ public static SetDisableUserRequest enableUserRequest(@NonNull String userID) { return new SetDisableUserRequest(userID, false, null, null); } /** * Returns a new request to disable the specified user account. * * @param userID the user id */ public static SetDisableUserRequest disableUserRequest(@NonNull String userID) { return new SetDisableUserRequest(userID, true, null, null); } /** * Returns a new request to disable the specified user account. * * @param userID the user id * @param message the message to be shown to user * @param expiry the date and time when the user is automatically enabled */ public static SetDisableUserRequest disableUserRequest(@NonNull String userID, @Nullable String message, @Nullable Date expiry) { return new SetDisableUserRequest(userID, true, message, expiry); } /** * Instantiates a new Set Disable User Request. * * @param userID the user id * @param disabled whether the user is disabled * @param message the message to be shown to user * @param expiry the date and time when the user is automatically enabled */ public SetDisableUserRequest(@NonNull String userID, Boolean disabled, @Nullable String message, @Nullable Date expiry) { super("auth:disable:set"); this.data = new HashMap<>(); this.data.put("auth_id", userID); this.data.put("disabled", disabled); if (message != null) { this.data.put("message", message); } if (expiry != null) { this.data.put("expiry", DateSerializer.stringFromDate(expiry)); } } }
[ "public", "class", "SetDisableUserRequest", "extends", "Request", "{", "/**\n * Returns a new request to enable the specified user account.\n *\n * @param userID the user id\n */", "public", "static", "SetDisableUserRequest", "enableUserRequest", "(", "@", "NonNull", "String", "userID", ")", "{", "return", "new", "SetDisableUserRequest", "(", "userID", ",", "false", ",", "null", ",", "null", ")", ";", "}", "/**\n * Returns a new request to disable the specified user account.\n *\n * @param userID the user id\n */", "public", "static", "SetDisableUserRequest", "disableUserRequest", "(", "@", "NonNull", "String", "userID", ")", "{", "return", "new", "SetDisableUserRequest", "(", "userID", ",", "true", ",", "null", ",", "null", ")", ";", "}", "/**\n * Returns a new request to disable the specified user account.\n *\n * @param userID the user id\n * @param message the message to be shown to user\n * @param expiry the date and time when the user is automatically enabled\n */", "public", "static", "SetDisableUserRequest", "disableUserRequest", "(", "@", "NonNull", "String", "userID", ",", "@", "Nullable", "String", "message", ",", "@", "Nullable", "Date", "expiry", ")", "{", "return", "new", "SetDisableUserRequest", "(", "userID", ",", "true", ",", "message", ",", "expiry", ")", ";", "}", "/**\n * Instantiates a new Set Disable User Request.\n *\n * @param userID the user id\n * @param disabled whether the user is disabled\n * @param message the message to be shown to user\n * @param expiry the date and time when the user is automatically enabled\n */", "public", "SetDisableUserRequest", "(", "@", "NonNull", "String", "userID", ",", "Boolean", "disabled", ",", "@", "Nullable", "String", "message", ",", "@", "Nullable", "Date", "expiry", ")", "{", "super", "(", "\"", "auth:disable:set", "\"", ")", ";", "this", ".", "data", "=", "new", "HashMap", "<", ">", "(", ")", ";", "this", ".", "data", ".", "put", "(", "\"", "auth_id", "\"", ",", "userID", ")", ";", "this", ".", "data", ".", "put", "(", "\"", "disabled", "\"", ",", "disabled", ")", ";", "if", "(", "message", "!=", "null", ")", "{", "this", ".", "data", ".", "put", "(", "\"", "message", "\"", ",", "message", ")", ";", "}", "if", "(", "expiry", "!=", "null", ")", "{", "this", ".", "data", ".", "put", "(", "\"", "expiry", "\"", ",", "DateSerializer", ".", "stringFromDate", "(", "expiry", ")", ")", ";", "}", "}", "}" ]
The Disable Skygear User Request.
[ "The", "Disable", "Skygear", "User", "Request", "." ]
[]
[ { "param": "Request", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Request", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35bdbd1f36407cac8e692fb642cacd2497e50682
ThalesGroup/fido_uaf_certification_adapter
src/main/java/org/gemalto/com/uaf/JwtAuthenticationParams.java
[ "Apache-2.0" ]
Java
JwtAuthenticationParams
/** * JWT authentication params specific for application */
JWT authentication params specific for application
[ "JWT", "authentication", "params", "specific", "for", "application" ]
public class JwtAuthenticationParams { private final String jwtTokenHeader; private final JwtSecret secret; private final String tenantIdParamKey; private final List<String> roles; public JwtAuthenticationParams(String jwtTokenHeader, JwtSecret secret, String tenantIdParamKey, List<String> roles) { this.jwtTokenHeader = jwtTokenHeader; this.secret = secret; this.tenantIdParamKey = tenantIdParamKey; this.roles = roles; } public String getJwtTokenHeader() { return jwtTokenHeader; } public JwtSecret getSecret() { return secret; } public String getTenantIdParamKey() { return tenantIdParamKey; } public List<String> getRoles() { return roles; } }
[ "public", "class", "JwtAuthenticationParams", "{", "private", "final", "String", "jwtTokenHeader", ";", "private", "final", "JwtSecret", "secret", ";", "private", "final", "String", "tenantIdParamKey", ";", "private", "final", "List", "<", "String", ">", "roles", ";", "public", "JwtAuthenticationParams", "(", "String", "jwtTokenHeader", ",", "JwtSecret", "secret", ",", "String", "tenantIdParamKey", ",", "List", "<", "String", ">", "roles", ")", "{", "this", ".", "jwtTokenHeader", "=", "jwtTokenHeader", ";", "this", ".", "secret", "=", "secret", ";", "this", ".", "tenantIdParamKey", "=", "tenantIdParamKey", ";", "this", ".", "roles", "=", "roles", ";", "}", "public", "String", "getJwtTokenHeader", "(", ")", "{", "return", "jwtTokenHeader", ";", "}", "public", "JwtSecret", "getSecret", "(", ")", "{", "return", "secret", ";", "}", "public", "String", "getTenantIdParamKey", "(", ")", "{", "return", "tenantIdParamKey", ";", "}", "public", "List", "<", "String", ">", "getRoles", "(", ")", "{", "return", "roles", ";", "}", "}" ]
JWT authentication params specific for application
[ "JWT", "authentication", "params", "specific", "for", "application" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
35bfb27e4f665ac6c37720f23bbe9371988304b1
bl4ckic3/format-corpus
tools/fidget/src/test/java/org/opf_labs/fmts/AllFidgetTests.java
[ "Apache-2.0" ]
Java
AllFidgetTests
/** * Test suite class to run all tests, plus holds test helper methods * * @author <a href="mailto:carl@openplanetsfoundation.org">Carl Wilson</a>.</p> * <a href="https://github.com/carlwilson">carlwilson AT github</a>.</p> * @version 0.1 * * Created 2 Nov 2012:11:54:06 */
Test suite class to run all tests, plus holds test helper methods @author Carl Wilson. carlwilson AT github. @version 0.1
[ "Test", "suite", "class", "to", "run", "all", "tests", "plus", "holds", "test", "helper", "methods", "@author", "Carl", "Wilson", ".", "carlwilson", "AT", "github", ".", "@version", "0", ".", "1" ]
@RunWith(Suite.class) @SuiteClasses({ OldTikaSigTesterTest.class, TikaResourceHelperTest.class, MimeInfoUtilsTest.class, GovDocsTest.class }) public class AllFidgetTests { private static final String PERCIPIO_XML = "percipio.pdf.xml"; private static final String TIKA_CUSTOM = "custom-mimetypes.xml"; private static final String TIKA_MIME_PATH = "org/apache/tika/mime/"; private final static String OPF_FMT_PATH = "org/opf_labs/fmts/"; private final static String GOVDOCS_PATH = OPF_FMT_PATH + "govdocs/"; private final static String GOVDOCS_ZIP_PATH = GOVDOCS_PATH + "zip"; private final static String GOVDOCS_DIR_PATH = GOVDOCS_PATH + "dir"; private static final String XML_EXT = "xml"; private static final String PERCIPIO_XML_PATH = TIKA_MIME_PATH + PERCIPIO_XML; private static final String TIKA_CUSTOM_PATH = TIKA_MIME_PATH + TIKA_CUSTOM; /** * @return the Percipo XML file * @throws URISyntaxException when looking up the test resource goes wrong... */ public static final File getPercepioXml() throws URISyntaxException { return getResourceAsFile(PERCIPIO_XML_PATH); } /** * @return the Tika Custom MIME Types file * @throws URISyntaxException when looking up the test resource goes wrong... */ public static final File getTikaCustom() throws URISyntaxException { return getResourceAsFile(TIKA_CUSTOM_PATH); } /** * @return all of the files * @throws URISyntaxException when looking up the test resource goes wrong... */ public static final Collection<File> getCustomSigTestFile() throws URISyntaxException { return getResourceFilesByExt(TIKA_MIME_PATH, true, XML_EXT); } /** * @return the zip based GovDocsDirectories test dir * @throws URISyntaxException when looking up the test resource goes wrong... */ public static final File getGovDocsZip() throws URISyntaxException { return getResourceAsFile(GOVDOCS_ZIP_PATH); } /** * @return the Directory based GovDocsDirectories test dir * @throws URISyntaxException when looking up the test resource goes wrong... */ public static final File getGovDocsDir() throws URISyntaxException { return getResourceAsFile(GOVDOCS_DIR_PATH); } /** * @param resName * the name of the resource to retrieve a file for * @return the java.io.File for the named resource * @throws URISyntaxException * if the named resource can't be converted to a URI */ public final static File getResourceAsFile(String resName) throws URISyntaxException { return new File(ClassLoader.getSystemResource(resName).toURI()); } @SuppressWarnings("unused") private final static Collection<File> getResourceFiles(String resName, boolean recurse) throws URISyntaxException { return getResourceFilesByExt(resName, recurse, null); } private final static Collection<File> getResourceFilesByExt(String resName, boolean recurse, String ext) throws URISyntaxException { File root = getResourceAsFile(resName); return FileUtils.listFiles(root, new String[]{ext}, recurse); } }
[ "@", "RunWith", "(", "Suite", ".", "class", ")", "@", "SuiteClasses", "(", "{", "OldTikaSigTesterTest", ".", "class", ",", "TikaResourceHelperTest", ".", "class", ",", "MimeInfoUtilsTest", ".", "class", ",", "GovDocsTest", ".", "class", "}", ")", "public", "class", "AllFidgetTests", "{", "private", "static", "final", "String", "PERCIPIO_XML", "=", "\"", "percipio.pdf.xml", "\"", ";", "private", "static", "final", "String", "TIKA_CUSTOM", "=", "\"", "custom-mimetypes.xml", "\"", ";", "private", "static", "final", "String", "TIKA_MIME_PATH", "=", "\"", "org/apache/tika/mime/", "\"", ";", "private", "final", "static", "String", "OPF_FMT_PATH", "=", "\"", "org/opf_labs/fmts/", "\"", ";", "private", "final", "static", "String", "GOVDOCS_PATH", "=", "OPF_FMT_PATH", "+", "\"", "govdocs/", "\"", ";", "private", "final", "static", "String", "GOVDOCS_ZIP_PATH", "=", "GOVDOCS_PATH", "+", "\"", "zip", "\"", ";", "private", "final", "static", "String", "GOVDOCS_DIR_PATH", "=", "GOVDOCS_PATH", "+", "\"", "dir", "\"", ";", "private", "static", "final", "String", "XML_EXT", "=", "\"", "xml", "\"", ";", "private", "static", "final", "String", "PERCIPIO_XML_PATH", "=", "TIKA_MIME_PATH", "+", "PERCIPIO_XML", ";", "private", "static", "final", "String", "TIKA_CUSTOM_PATH", "=", "TIKA_MIME_PATH", "+", "TIKA_CUSTOM", ";", "/**\n\t * @return the Percipo XML file\n\t * @throws URISyntaxException when looking up the test resource goes wrong...\n\t */", "public", "static", "final", "File", "getPercepioXml", "(", ")", "throws", "URISyntaxException", "{", "return", "getResourceAsFile", "(", "PERCIPIO_XML_PATH", ")", ";", "}", "/**\n\t * @return the Tika Custom MIME Types file\n\t * @throws URISyntaxException when looking up the test resource goes wrong...\n\t */", "public", "static", "final", "File", "getTikaCustom", "(", ")", "throws", "URISyntaxException", "{", "return", "getResourceAsFile", "(", "TIKA_CUSTOM_PATH", ")", ";", "}", "/**\n\t * @return all of the files\n\t * @throws URISyntaxException when looking up the test resource goes wrong...\n\t */", "public", "static", "final", "Collection", "<", "File", ">", "getCustomSigTestFile", "(", ")", "throws", "URISyntaxException", "{", "return", "getResourceFilesByExt", "(", "TIKA_MIME_PATH", ",", "true", ",", "XML_EXT", ")", ";", "}", "/**\n\t * @return the zip based GovDocsDirectories test dir\n\t * @throws URISyntaxException when looking up the test resource goes wrong...\n\t */", "public", "static", "final", "File", "getGovDocsZip", "(", ")", "throws", "URISyntaxException", "{", "return", "getResourceAsFile", "(", "GOVDOCS_ZIP_PATH", ")", ";", "}", "/**\n\t * @return the Directory based GovDocsDirectories test dir\n\t * @throws URISyntaxException when looking up the test resource goes wrong...\n\t */", "public", "static", "final", "File", "getGovDocsDir", "(", ")", "throws", "URISyntaxException", "{", "return", "getResourceAsFile", "(", "GOVDOCS_DIR_PATH", ")", ";", "}", "/**\n\t * @param resName\n\t * the name of the resource to retrieve a file for\n\t * @return the java.io.File for the named resource\n\t * @throws URISyntaxException\n\t * if the named resource can't be converted to a URI\n\t */", "public", "final", "static", "File", "getResourceAsFile", "(", "String", "resName", ")", "throws", "URISyntaxException", "{", "return", "new", "File", "(", "ClassLoader", ".", "getSystemResource", "(", "resName", ")", ".", "toURI", "(", ")", ")", ";", "}", "@", "SuppressWarnings", "(", "\"", "unused", "\"", ")", "private", "final", "static", "Collection", "<", "File", ">", "getResourceFiles", "(", "String", "resName", ",", "boolean", "recurse", ")", "throws", "URISyntaxException", "{", "return", "getResourceFilesByExt", "(", "resName", ",", "recurse", ",", "null", ")", ";", "}", "private", "final", "static", "Collection", "<", "File", ">", "getResourceFilesByExt", "(", "String", "resName", ",", "boolean", "recurse", ",", "String", "ext", ")", "throws", "URISyntaxException", "{", "File", "root", "=", "getResourceAsFile", "(", "resName", ")", ";", "return", "FileUtils", ".", "listFiles", "(", "root", ",", "new", "String", "[", "]", "{", "ext", "}", ",", "recurse", ")", ";", "}", "}" ]
Test suite class to run all tests, plus holds test helper methods
[ "Test", "suite", "class", "to", "run", "all", "tests", "plus", "holds", "test", "helper", "methods" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
35c1a9340b03b58bce74ca5eefe093990929f472
jakarta99/fcb-web
src/main/java/tw/com/fcb/sample/weifan/web/LanguageServlet.java
[ "Apache-2.0" ]
Java
LanguageServlet
/** * Servlet implementation class LanguageServlet */
Servlet implementation class LanguageServlet
[ "Servlet", "implementation", "class", "LanguageServlet" ]
@WebServlet("/language") public class LanguageServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LanguageServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out = response.getWriter(); String seq = request.getParameter("seq"); String func = request.getParameter("func"); String level = request.getParameter("level"); List<Language> result = new ArrayList<Language>(); DataBaseService DB = new DataBaseService(); Language Lan = new Language(); response.setContentType("text/html; charset=utf-8"); switch (func) { //find all case "1" : try { result = DB.findAll(); for(int i = 0; i < result.size(); i++){ out.println(result.get(i).toString()+"<br>"); } } catch (Exception e) { // TODO Auto-generated catch block out.print("資料庫錯誤"); e.printStackTrace(); } break; //insert case "2" : try { Lan = DB.findByID(1); Lan.setSeq(Integer.valueOf(seq)); DB.Insert(Lan); out.println("新增資料 : "+ Lan.toString()+"<br>"); } catch (Exception e1) { // TODO Auto-generated catch block out.print("資料庫錯誤"); e1.printStackTrace(); } break; //update case "3" : try { Lan = DB.findByID(Integer.valueOf(seq)); out.println("原始資料為 : "+ Lan.toString()+"<br>"); Lan.setLevel(LanguageLevelEnum.valueOf(level)); out.println("更新資料為 : "+ Lan.toString()+"<br>"); DB.Update(Lan); } catch (Exception e) { // TODO Auto-generated catch block out.print("資料庫錯誤"); e.printStackTrace(); } break; //delete case "4" : try { DB.Delete(Integer.valueOf(seq)); out.println("成功刪除資料"); } catch (Exception e) { // TODO Auto-generated catch block out.print("資料庫錯誤"); e.printStackTrace(); } break; //find by id case "5" : try { Lan = DB.findByID(Integer.valueOf(seq)); out.println("資料為 : "+ Lan.toString()+"<br>"); } catch (Exception e) { // TODO Auto-generated catch block out.print("資料庫錯誤"); e.printStackTrace(); } break; } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
[ "@", "WebServlet", "(", "\"", "/language", "\"", ")", "public", "class", "LanguageServlet", "extends", "HttpServlet", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "/**\r\n * @see HttpServlet#HttpServlet()\r\n */", "public", "LanguageServlet", "(", ")", "{", "super", "(", ")", ";", "}", "/**\r\n\t * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)\r\n\t */", "protected", "void", "doGet", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "ServletException", ",", "IOException", "{", "PrintWriter", "out", "=", "response", ".", "getWriter", "(", ")", ";", "String", "seq", "=", "request", ".", "getParameter", "(", "\"", "seq", "\"", ")", ";", "String", "func", "=", "request", ".", "getParameter", "(", "\"", "func", "\"", ")", ";", "String", "level", "=", "request", ".", "getParameter", "(", "\"", "level", "\"", ")", ";", "List", "<", "Language", ">", "result", "=", "new", "ArrayList", "<", "Language", ">", "(", ")", ";", "DataBaseService", "DB", "=", "new", "DataBaseService", "(", ")", ";", "Language", "Lan", "=", "new", "Language", "(", ")", ";", "response", ".", "setContentType", "(", "\"", "text/html; charset=utf-8", "\"", ")", ";", "switch", "(", "func", ")", "{", "case", "\"", "1", "\"", ":", "try", "{", "result", "=", "DB", ".", "findAll", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "size", "(", ")", ";", "i", "++", ")", "{", "out", ".", "println", "(", "result", ".", "get", "(", "i", ")", ".", "toString", "(", ")", "+", "\"", "<br>", "\"", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "out", ".", "print", "(", "\"", "資料庫錯誤\");\r", "", "", "", "e", ".", "printStackTrace", "(", ")", ";", "}", "break", ";", "case", "\"", "2", "\"", ":", "try", "{", "Lan", "=", "DB", ".", "findByID", "(", "1", ")", ";", "Lan", ".", "setSeq", "(", "Integer", ".", "valueOf", "(", "seq", ")", ")", ";", "DB", ".", "Insert", "(", "Lan", ")", ";", "out", ".", "println", "(", "\"", "新增資料 : \"+ Lan.t", "o", "S", "rin", "g", "()+\"<br>", "\"", ")", ";", "\r", "", "", "", "", "}", "catch", "(", "Exception", "e1", ")", "{", "out", ".", "print", "(", "\"", "資料庫錯誤\");\r", "", "", "", "e1", ".", "printStackTrace", "(", ")", ";", "}", "break", ";", "case", "\"", "3", "\"", ":", "try", "{", "Lan", "=", "DB", ".", "findByID", "(", "Integer", ".", "valueOf", "(", "seq", ")", ")", ";", "out", ".", "println", "(", "\"", "原始資料為 : \"+ Lan.toS", "t", "r", "ng(", ")", "+\"<br>\")", ";", "\r", "", "", "", "", "", "", "Lan", ".", "setLevel", "(", "LanguageLevelEnum", ".", "valueOf", "(", "level", ")", ")", ";", "out", ".", "println", "(", "\"", "更新資料為 : \"+ Lan.toS", "t", "r", "ng(", ")", "+\"<br>\")", ";", "\r", "", "", "", "", "", "", "DB", ".", "Update", "(", "Lan", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "out", ".", "print", "(", "\"", "資料庫錯誤\");\r", "", "", "", "e", ".", "printStackTrace", "(", ")", ";", "}", "break", ";", "case", "\"", "4", "\"", ":", "try", "{", "DB", ".", "Delete", "(", "Integer", ".", "valueOf", "(", "seq", ")", ")", ";", "out", ".", "println", "(", "\"", "成功刪除資料\");\r", "", "", "", "}", "catch", "(", "Exception", "e", ")", "{", "out", ".", "print", "(", "\"", "資料庫錯誤\");\r", "", "", "", "e", ".", "printStackTrace", "(", ")", ";", "}", "break", ";", "case", "\"", "5", "\"", ":", "try", "{", "Lan", "=", "DB", ".", "findByID", "(", "Integer", ".", "valueOf", "(", "seq", ")", ")", ";", "out", ".", "println", "(", "\"", "資料為 : \"+ Lan", ".", "t", "Str", "i", "ng()+\"<b", "r", ">", "\"", ")", ";\r", "", "", "", "}", "catch", "(", "Exception", "e", ")", "{", "out", ".", "print", "(", "\"", "資料庫錯誤\");\r", "", "", "", "e", ".", "printStackTrace", "(", ")", ";", "}", "break", ";", "}", "}", "/**\r\n\t * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)\r\n\t */", "protected", "void", "doPost", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "ServletException", ",", "IOException", "{", "doGet", "(", "request", ",", "response", ")", ";", "}", "}" ]
Servlet implementation class LanguageServlet
[ "Servlet", "implementation", "class", "LanguageServlet" ]
[ "// TODO Auto-generated constructor stub\r", "// TODO Auto-generated method stub\r", "//find all\r", "// TODO Auto-generated catch block\r", "//insert\r", "// TODO Auto-generated catch block\r", "//update\r", "// TODO Auto-generated catch block\r", "//delete\r", "// TODO Auto-generated catch block\r", "//find by id\r", "// TODO Auto-generated catch block\r", "// TODO Auto-generated method stub\r" ]
[ { "param": "HttpServlet", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "HttpServlet", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35c247869cd7db0f4fc6563f88022dfbc8c3f207
xfsnow/android
CognitoBjs/app/libs/aws-android-sdk-core/src/main/java/com/amazonaws/event/ProgressReportingInputStream.java
[ "Apache-2.0" ]
Java
ProgressReportingInputStream
/** * Simple InputStream wrapper that occasionally notifies a progress listener * about the number of bytes transferred. * <p> * This class could be used for both Amazon S3 and Amazon Glacier clients. The * legacy Amazon Amazon S3 * com.amazonaws.services.s3.internal.ProgressReportingInputStream has been * deprecated in favor of this new class. * </p> */
Simple InputStream wrapper that occasionally notifies a progress listener about the number of bytes transferred. This class could be used for both Amazon S3 and Amazon Glacier clients. The legacy Amazon Amazon S3 com.amazonaws.services.s3.internal.ProgressReportingInputStream has been deprecated in favor of this new class.
[ "Simple", "InputStream", "wrapper", "that", "occasionally", "notifies", "a", "progress", "listener", "about", "the", "number", "of", "bytes", "transferred", ".", "This", "class", "could", "be", "used", "for", "both", "Amazon", "S3", "and", "Amazon", "Glacier", "clients", ".", "The", "legacy", "Amazon", "Amazon", "S3", "com", ".", "amazonaws", ".", "services", ".", "s3", ".", "internal", ".", "ProgressReportingInputStream", "has", "been", "deprecated", "in", "favor", "of", "this", "new", "class", "." ]
public class ProgressReportingInputStream extends SdkFilterInputStream { /** Constant to represent 1KB. */ private static final int BYTES_IN_KB = 1024; /** Constant to represent the Notification Threshold in KB. */ private static final int THRESHOLD_IN_KB = 8; /** The threshold of bytes between notifications. */ private int notificationThreshold = THRESHOLD_IN_KB * BYTES_IN_KB; /** The listener callback executor */ private final ProgressListenerCallbackExecutor listenerCallbackExecutor; /** * The number of bytes read that the listener hasn't been notified about * yet. */ private int unnotifiedByteCount; /** * True if this stream should fire a completed progress event when the * stream runs out. */ private boolean fireCompletedEvent; /** * Creates a new progress reporting input stream that simply wraps the * specified input stream and uses the specified listener callback executor * to asynchronously notify the listener about the number of bytes * transferred. * * @param in The input stream to wrap. * @param listenerCallbackExecutor The listener callback executor that wraps * the listener to notify about progress. */ public ProgressReportingInputStream(final InputStream in, final ProgressListenerCallbackExecutor listenerCallbackExecutor) { super(in); this.listenerCallbackExecutor = listenerCallbackExecutor; } /** * Sets the number of Kbytes that need to be written before updates to the * listener occur. * * @param threshold Number of Kbytes that needs to be written before * write update notification occurs. */ public void setNotificationThreshold(final int threshold) { this.notificationThreshold = threshold * BYTES_IN_KB; } /** * Sets whether this input stream should fire an event with code * {@link ProgressEvent#COMPLETED_EVENT_CODE} when this stream runs out of * data. By default, completed events are not fired by this stream. * * @param fireCompletedEvent Whether this input stream should fire an event * to indicate that the stream has been fully read. */ public void setFireCompletedEvent(boolean fireCompletedEvent) { this.fireCompletedEvent = fireCompletedEvent; } /** * Returns whether this input stream should fire an event with code * {@link ProgressEvent#COMPLETED_EVENT_CODE} when this stream runs out of * data. By default, completed events are not fired by this stream. * * @return Whether this input stream should fire an event to indicate that * the stream has been fully read. */ public boolean getFireCompletedEvent() { return fireCompletedEvent; } @Override public int read() throws IOException { int data = super.read(); if (data == -1) { notifyCompleted(); } else { notify(1); } return data; } @Override public void reset() throws IOException { super.reset(); ProgressEvent event = new ProgressEvent(unnotifiedByteCount); event.setEventCode(ProgressEvent.RESET_EVENT_CODE); listenerCallbackExecutor.progressChanged(event); unnotifiedByteCount = 0; } @Override public int read(byte[] b, int off, int len) throws IOException { int bytesRead = super.read(b, off, len); if (bytesRead == -1) notifyCompleted(); if (bytesRead != -1) notify(bytesRead); return bytesRead; } @Override public void close() throws IOException { if (unnotifiedByteCount > 0) { listenerCallbackExecutor.progressChanged(new ProgressEvent(unnotifiedByteCount)); unnotifiedByteCount = 0; } super.close(); } private void notifyCompleted() { if (!fireCompletedEvent) return; ProgressEvent event = new ProgressEvent(unnotifiedByteCount); event.setEventCode(ProgressEvent.COMPLETED_EVENT_CODE); unnotifiedByteCount = 0; listenerCallbackExecutor.progressChanged(event); } private void notify(int bytesRead) { unnotifiedByteCount += bytesRead; if (unnotifiedByteCount >= this.notificationThreshold) { listenerCallbackExecutor.progressChanged(new ProgressEvent(unnotifiedByteCount)); unnotifiedByteCount = 0; } } }
[ "public", "class", "ProgressReportingInputStream", "extends", "SdkFilterInputStream", "{", "/** Constant to represent 1KB. */", "private", "static", "final", "int", "BYTES_IN_KB", "=", "1024", ";", "/** Constant to represent the Notification Threshold in KB. */", "private", "static", "final", "int", "THRESHOLD_IN_KB", "=", "8", ";", "/** The threshold of bytes between notifications. */", "private", "int", "notificationThreshold", "=", "THRESHOLD_IN_KB", "*", "BYTES_IN_KB", ";", "/** The listener callback executor */", "private", "final", "ProgressListenerCallbackExecutor", "listenerCallbackExecutor", ";", "/**\n * The number of bytes read that the listener hasn't been notified about\n * yet.\n */", "private", "int", "unnotifiedByteCount", ";", "/**\n * True if this stream should fire a completed progress event when the\n * stream runs out.\n */", "private", "boolean", "fireCompletedEvent", ";", "/**\n * Creates a new progress reporting input stream that simply wraps the\n * specified input stream and uses the specified listener callback executor\n * to asynchronously notify the listener about the number of bytes\n * transferred.\n *\n * @param in The input stream to wrap.\n * @param listenerCallbackExecutor The listener callback executor that wraps\n * the listener to notify about progress.\n */", "public", "ProgressReportingInputStream", "(", "final", "InputStream", "in", ",", "final", "ProgressListenerCallbackExecutor", "listenerCallbackExecutor", ")", "{", "super", "(", "in", ")", ";", "this", ".", "listenerCallbackExecutor", "=", "listenerCallbackExecutor", ";", "}", "/**\n * Sets the number of Kbytes that need to be written before updates to the\n * listener occur.\n *\n * @param threshold Number of Kbytes that needs to be written before\n * write update notification occurs.\n */", "public", "void", "setNotificationThreshold", "(", "final", "int", "threshold", ")", "{", "this", ".", "notificationThreshold", "=", "threshold", "*", "BYTES_IN_KB", ";", "}", "/**\n * Sets whether this input stream should fire an event with code\n * {@link ProgressEvent#COMPLETED_EVENT_CODE} when this stream runs out of\n * data. By default, completed events are not fired by this stream.\n *\n * @param fireCompletedEvent Whether this input stream should fire an event\n * to indicate that the stream has been fully read.\n */", "public", "void", "setFireCompletedEvent", "(", "boolean", "fireCompletedEvent", ")", "{", "this", ".", "fireCompletedEvent", "=", "fireCompletedEvent", ";", "}", "/**\n * Returns whether this input stream should fire an event with code\n * {@link ProgressEvent#COMPLETED_EVENT_CODE} when this stream runs out of\n * data. By default, completed events are not fired by this stream.\n *\n * @return Whether this input stream should fire an event to indicate that\n * the stream has been fully read.\n */", "public", "boolean", "getFireCompletedEvent", "(", ")", "{", "return", "fireCompletedEvent", ";", "}", "@", "Override", "public", "int", "read", "(", ")", "throws", "IOException", "{", "int", "data", "=", "super", ".", "read", "(", ")", ";", "if", "(", "data", "==", "-", "1", ")", "{", "notifyCompleted", "(", ")", ";", "}", "else", "{", "notify", "(", "1", ")", ";", "}", "return", "data", ";", "}", "@", "Override", "public", "void", "reset", "(", ")", "throws", "IOException", "{", "super", ".", "reset", "(", ")", ";", "ProgressEvent", "event", "=", "new", "ProgressEvent", "(", "unnotifiedByteCount", ")", ";", "event", ".", "setEventCode", "(", "ProgressEvent", ".", "RESET_EVENT_CODE", ")", ";", "listenerCallbackExecutor", ".", "progressChanged", "(", "event", ")", ";", "unnotifiedByteCount", "=", "0", ";", "}", "@", "Override", "public", "int", "read", "(", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "int", "bytesRead", "=", "super", ".", "read", "(", "b", ",", "off", ",", "len", ")", ";", "if", "(", "bytesRead", "==", "-", "1", ")", "notifyCompleted", "(", ")", ";", "if", "(", "bytesRead", "!=", "-", "1", ")", "notify", "(", "bytesRead", ")", ";", "return", "bytesRead", ";", "}", "@", "Override", "public", "void", "close", "(", ")", "throws", "IOException", "{", "if", "(", "unnotifiedByteCount", ">", "0", ")", "{", "listenerCallbackExecutor", ".", "progressChanged", "(", "new", "ProgressEvent", "(", "unnotifiedByteCount", ")", ")", ";", "unnotifiedByteCount", "=", "0", ";", "}", "super", ".", "close", "(", ")", ";", "}", "private", "void", "notifyCompleted", "(", ")", "{", "if", "(", "!", "fireCompletedEvent", ")", "return", ";", "ProgressEvent", "event", "=", "new", "ProgressEvent", "(", "unnotifiedByteCount", ")", ";", "event", ".", "setEventCode", "(", "ProgressEvent", ".", "COMPLETED_EVENT_CODE", ")", ";", "unnotifiedByteCount", "=", "0", ";", "listenerCallbackExecutor", ".", "progressChanged", "(", "event", ")", ";", "}", "private", "void", "notify", "(", "int", "bytesRead", ")", "{", "unnotifiedByteCount", "+=", "bytesRead", ";", "if", "(", "unnotifiedByteCount", ">=", "this", ".", "notificationThreshold", ")", "{", "listenerCallbackExecutor", ".", "progressChanged", "(", "new", "ProgressEvent", "(", "unnotifiedByteCount", ")", ")", ";", "unnotifiedByteCount", "=", "0", ";", "}", "}", "}" ]
Simple InputStream wrapper that occasionally notifies a progress listener about the number of bytes transferred.
[ "Simple", "InputStream", "wrapper", "that", "occasionally", "notifies", "a", "progress", "listener", "about", "the", "number", "of", "bytes", "transferred", "." ]
[]
[ { "param": "SdkFilterInputStream", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "SdkFilterInputStream", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35cbe32343c64c341c20c77a1bda1f321e77e463
GaganGupta19/Stock-Hawk
app/src/main/java/com/sam_chordas/android/stockhawk/service/StockIntentService.java
[ "MIT" ]
Java
StockIntentService
/** * Created by sam_chordas on 10/1/15. */
Created by sam_chordas on 10/1/15.
[ "Created", "by", "sam_chordas", "on", "10", "/", "1", "/", "15", "." ]
public class StockIntentService extends IntentService { public static final String EXTRA_TAG = "tag"; public static final String EXTRA_SYMBOL = "symbol"; public static final String ACTION_INIT = "init"; public static final String ACTION_ADD = "add"; public StockIntentService(){ super(StockIntentService.class.getName()); } public StockIntentService(String name) { super(name); } @Override protected void onHandleIntent(Intent intent) { Log.d(StockIntentService.class.getSimpleName(), getResources().getString(R.string.stockIntentService)); StockTaskService stockTaskService = new StockTaskService(this); Bundle args = new Bundle(); if (intent.getStringExtra(EXTRA_TAG).equals(ACTION_ADD)){ String[] symbol = intent.getStringExtra(EXTRA_SYMBOL).split("\\s+"); args.putString(EXTRA_SYMBOL, symbol[0]); } // We can call OnRunTask from the intent service to force it to run immediately instead of // scheduling a task. stockTaskService.onRunTask(new TaskParams(intent.getStringExtra(EXTRA_TAG), args)); } }
[ "public", "class", "StockIntentService", "extends", "IntentService", "{", "public", "static", "final", "String", "EXTRA_TAG", "=", "\"", "tag", "\"", ";", "public", "static", "final", "String", "EXTRA_SYMBOL", "=", "\"", "symbol", "\"", ";", "public", "static", "final", "String", "ACTION_INIT", "=", "\"", "init", "\"", ";", "public", "static", "final", "String", "ACTION_ADD", "=", "\"", "add", "\"", ";", "public", "StockIntentService", "(", ")", "{", "super", "(", "StockIntentService", ".", "class", ".", "getName", "(", ")", ")", ";", "}", "public", "StockIntentService", "(", "String", "name", ")", "{", "super", "(", "name", ")", ";", "}", "@", "Override", "protected", "void", "onHandleIntent", "(", "Intent", "intent", ")", "{", "Log", ".", "d", "(", "StockIntentService", ".", "class", ".", "getSimpleName", "(", ")", ",", "getResources", "(", ")", ".", "getString", "(", "R", ".", "string", ".", "stockIntentService", ")", ")", ";", "StockTaskService", "stockTaskService", "=", "new", "StockTaskService", "(", "this", ")", ";", "Bundle", "args", "=", "new", "Bundle", "(", ")", ";", "if", "(", "intent", ".", "getStringExtra", "(", "EXTRA_TAG", ")", ".", "equals", "(", "ACTION_ADD", ")", ")", "{", "String", "[", "]", "symbol", "=", "intent", ".", "getStringExtra", "(", "EXTRA_SYMBOL", ")", ".", "split", "(", "\"", "\\\\", "s+", "\"", ")", ";", "args", ".", "putString", "(", "EXTRA_SYMBOL", ",", "symbol", "[", "0", "]", ")", ";", "}", "stockTaskService", ".", "onRunTask", "(", "new", "TaskParams", "(", "intent", ".", "getStringExtra", "(", "EXTRA_TAG", ")", ",", "args", ")", ")", ";", "}", "}" ]
Created by sam_chordas on 10/1/15.
[ "Created", "by", "sam_chordas", "on", "10", "/", "1", "/", "15", "." ]
[ "// We can call OnRunTask from the intent service to force it to run immediately instead of", "// scheduling a task." ]
[ { "param": "IntentService", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IntentService", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35d3dcfc52ff13969b58906566522595c506bf3b
wanglei339/wms-test
wms-rpc/src/main/java/com/lsh/wms/rpc/service/rule/ShelfLifeRestService.java
[ "Apache-2.0" ]
Java
ShelfLifeRestService
/** * Created by lixin-mac on 16/8/10. */
Created by lixin-mac on 16/8/10.
[ "Created", "by", "lixin", "-", "mac", "on", "16", "/", "8", "/", "10", "." ]
@Service(protocol = "rest") @Path("rule") @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) @Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) public class ShelfLifeRestService implements IShelfLifeRestService{ private static Logger logger = LoggerFactory.getLogger(ItemRestService.class); @Autowired private ShelfLifeRpcService shelfLifeRpcService; @POST @Path("getShelflifeRuleList") public String getShelflifeRuleList(Map<String, Object> mapQuery) { return JsonUtils.SUCCESS(shelfLifeRpcService.getShelflifeRuleList(mapQuery)); } @POST @Path("getShelflifeRuleCount") public String getShelflifeRuleCount(Map<String, Object> mapQuery) { return JsonUtils.SUCCESS(shelfLifeRpcService.getShelflifeRuleCount(mapQuery)); } @POST @Path("updateShelflifeRule") public String updateShelflifeRule(BaseinfoShelflifeRule shelflifeRule) { try { shelfLifeRpcService.updateShelflifeRule(shelflifeRule); }catch (Exception e) { logger.error(e.getCause()!=null ? e.getCause().getMessage():e.getMessage()); return JsonUtils.TOKEN_ERROR("update failed"); } return JsonUtils.SUCCESS(); } @POST @Path("insertShelflifeRule") public String insertShelflifeRule(BaseinfoShelflifeRule shelflifeRule) { try { shelfLifeRpcService.insertShelflifeRule(shelflifeRule); }catch (Exception e) { logger.error(e.getCause()!=null ? e.getCause().getMessage():e.getMessage()); return JsonUtils.TOKEN_ERROR("create failed"); } return JsonUtils.SUCCESS(); } @POST @Path("deleteShelflifeRule") public String deleteShelflifeRule(BaseinfoShelflifeRule shelflifeRule) { try { shelfLifeRpcService.deleteShelflifeRule(shelflifeRule); }catch (Exception e) { logger.error(e.getCause()!=null ? e.getCause().getMessage():e.getMessage()); return JsonUtils.TOKEN_ERROR("delete failed"); } return JsonUtils.SUCCESS(); } @GET @Path("getShelflifeRule") public String getShelflifeRule(@QueryParam("ruleId") Long ruleId) { return JsonUtils.SUCCESS(shelfLifeRpcService.getShelflifeRule(ruleId)); } }
[ "@", "Service", "(", "protocol", "=", "\"", "rest", "\"", ")", "@", "Path", "(", "\"", "rule", "\"", ")", "@", "Consumes", "(", "{", "MediaType", ".", "APPLICATION_JSON", ",", "MediaType", ".", "TEXT_XML", "}", ")", "@", "Produces", "(", "{", "ContentType", ".", "APPLICATION_JSON_UTF_8", ",", "ContentType", ".", "TEXT_XML_UTF_8", "}", ")", "public", "class", "ShelfLifeRestService", "implements", "IShelfLifeRestService", "{", "private", "static", "Logger", "logger", "=", "LoggerFactory", ".", "getLogger", "(", "ItemRestService", ".", "class", ")", ";", "@", "Autowired", "private", "ShelfLifeRpcService", "shelfLifeRpcService", ";", "@", "POST", "@", "Path", "(", "\"", "getShelflifeRuleList", "\"", ")", "public", "String", "getShelflifeRuleList", "(", "Map", "<", "String", ",", "Object", ">", "mapQuery", ")", "{", "return", "JsonUtils", ".", "SUCCESS", "(", "shelfLifeRpcService", ".", "getShelflifeRuleList", "(", "mapQuery", ")", ")", ";", "}", "@", "POST", "@", "Path", "(", "\"", "getShelflifeRuleCount", "\"", ")", "public", "String", "getShelflifeRuleCount", "(", "Map", "<", "String", ",", "Object", ">", "mapQuery", ")", "{", "return", "JsonUtils", ".", "SUCCESS", "(", "shelfLifeRpcService", ".", "getShelflifeRuleCount", "(", "mapQuery", ")", ")", ";", "}", "@", "POST", "@", "Path", "(", "\"", "updateShelflifeRule", "\"", ")", "public", "String", "updateShelflifeRule", "(", "BaseinfoShelflifeRule", "shelflifeRule", ")", "{", "try", "{", "shelfLifeRpcService", ".", "updateShelflifeRule", "(", "shelflifeRule", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "e", ".", "getCause", "(", ")", "!=", "null", "?", "e", ".", "getCause", "(", ")", ".", "getMessage", "(", ")", ":", "e", ".", "getMessage", "(", ")", ")", ";", "return", "JsonUtils", ".", "TOKEN_ERROR", "(", "\"", "update failed", "\"", ")", ";", "}", "return", "JsonUtils", ".", "SUCCESS", "(", ")", ";", "}", "@", "POST", "@", "Path", "(", "\"", "insertShelflifeRule", "\"", ")", "public", "String", "insertShelflifeRule", "(", "BaseinfoShelflifeRule", "shelflifeRule", ")", "{", "try", "{", "shelfLifeRpcService", ".", "insertShelflifeRule", "(", "shelflifeRule", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "e", ".", "getCause", "(", ")", "!=", "null", "?", "e", ".", "getCause", "(", ")", ".", "getMessage", "(", ")", ":", "e", ".", "getMessage", "(", ")", ")", ";", "return", "JsonUtils", ".", "TOKEN_ERROR", "(", "\"", "create failed", "\"", ")", ";", "}", "return", "JsonUtils", ".", "SUCCESS", "(", ")", ";", "}", "@", "POST", "@", "Path", "(", "\"", "deleteShelflifeRule", "\"", ")", "public", "String", "deleteShelflifeRule", "(", "BaseinfoShelflifeRule", "shelflifeRule", ")", "{", "try", "{", "shelfLifeRpcService", ".", "deleteShelflifeRule", "(", "shelflifeRule", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "e", ".", "getCause", "(", ")", "!=", "null", "?", "e", ".", "getCause", "(", ")", ".", "getMessage", "(", ")", ":", "e", ".", "getMessage", "(", ")", ")", ";", "return", "JsonUtils", ".", "TOKEN_ERROR", "(", "\"", "delete failed", "\"", ")", ";", "}", "return", "JsonUtils", ".", "SUCCESS", "(", ")", ";", "}", "@", "GET", "@", "Path", "(", "\"", "getShelflifeRule", "\"", ")", "public", "String", "getShelflifeRule", "(", "@", "QueryParam", "(", "\"", "ruleId", "\"", ")", "Long", "ruleId", ")", "{", "return", "JsonUtils", ".", "SUCCESS", "(", "shelfLifeRpcService", ".", "getShelflifeRule", "(", "ruleId", ")", ")", ";", "}", "}" ]
Created by lixin-mac on 16/8/10.
[ "Created", "by", "lixin", "-", "mac", "on", "16", "/", "8", "/", "10", "." ]
[]
[ { "param": "IShelfLifeRestService", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IShelfLifeRestService", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35da040c0dc591ed02107517c7101c5a4557a56f
rohankumardubey/metron
metron-streaming/Metron-Common/src/main/java/org/apache/metron/hbase/Connector.java
[ "Apache-2.0" ]
Java
Connector
/** * Created by cstella on 1/29/16. */
Created by cstella on 1/29/16.
[ "Created", "by", "cstella", "on", "1", "/", "29", "/", "16", "." ]
public abstract class Connector { protected TableConfig tableConf; protected String _quorum; protected String _port; public Connector(final TableConfig conf, String _quorum, String _port) throws IOException { this.tableConf = conf; this._quorum = _quorum; this._port = _port; } public abstract void put(Put put) throws IOException; public abstract void close(); }
[ "public", "abstract", "class", "Connector", "{", "protected", "TableConfig", "tableConf", ";", "protected", "String", "_quorum", ";", "protected", "String", "_port", ";", "public", "Connector", "(", "final", "TableConfig", "conf", ",", "String", "_quorum", ",", "String", "_port", ")", "throws", "IOException", "{", "this", ".", "tableConf", "=", "conf", ";", "this", ".", "_quorum", "=", "_quorum", ";", "this", ".", "_port", "=", "_port", ";", "}", "public", "abstract", "void", "put", "(", "Put", "put", ")", "throws", "IOException", ";", "public", "abstract", "void", "close", "(", ")", ";", "}" ]
Created by cstella on 1/29/16.
[ "Created", "by", "cstella", "on", "1", "/", "29", "/", "16", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
35da4e73cee14f001bd5becc2df96b7b31e5b005
msdgwzhy6/glide
library/src/main/java/com/bumptech/glide/GlideContext.java
[ "Apache-2.0" ]
Java
GlideContext
/** * Global context for all loads in Glide containing and exposing the various registries and classes * required to load resources. */
Global context for all loads in Glide containing and exposing the various registries and classes required to load resources.
[ "Global", "context", "for", "all", "loads", "in", "Glide", "containing", "and", "exposing", "the", "various", "registries", "and", "classes", "required", "to", "load", "resources", "." ]
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public class GlideContext extends ContextWrapper implements ComponentCallbacks2 { private final Handler mainHandler; private final Registry registry; private final ImageViewTargetFactory imageViewTargetFactory; private final RequestOptions options; private final Engine engine; private final ComponentCallbacks2 componentCallbacks; public GlideContext(Context context, Registry registry, ImageViewTargetFactory imageViewTargetFactory, RequestOptions options, Engine engine, ComponentCallbacks2 componentCallbacks) { super(context.getApplicationContext()); this.registry = registry; this.imageViewTargetFactory = imageViewTargetFactory; this.options = options; this.engine = engine; this.componentCallbacks = componentCallbacks; mainHandler = new Handler(Looper.getMainLooper()); } public RequestOptions getOptions() { return options; } public <X> Target<X> buildImageViewTarget(ImageView imageView, Class<X> transcodeClass) { return imageViewTargetFactory.buildTarget(imageView, transcodeClass); } public Handler getMainHandler() { return mainHandler; } public Engine getEngine() { return engine; } public Registry getRegistry() { return registry; } @Override public void onTrimMemory(int level) { componentCallbacks.onTrimMemory(level); } @Override public void onConfigurationChanged(Configuration newConfig) { componentCallbacks.onConfigurationChanged(newConfig); } @Override public void onLowMemory() { componentCallbacks.onLowMemory(); } }
[ "@", "TargetApi", "(", "Build", ".", "VERSION_CODES", ".", "ICE_CREAM_SANDWICH", ")", "public", "class", "GlideContext", "extends", "ContextWrapper", "implements", "ComponentCallbacks2", "{", "private", "final", "Handler", "mainHandler", ";", "private", "final", "Registry", "registry", ";", "private", "final", "ImageViewTargetFactory", "imageViewTargetFactory", ";", "private", "final", "RequestOptions", "options", ";", "private", "final", "Engine", "engine", ";", "private", "final", "ComponentCallbacks2", "componentCallbacks", ";", "public", "GlideContext", "(", "Context", "context", ",", "Registry", "registry", ",", "ImageViewTargetFactory", "imageViewTargetFactory", ",", "RequestOptions", "options", ",", "Engine", "engine", ",", "ComponentCallbacks2", "componentCallbacks", ")", "{", "super", "(", "context", ".", "getApplicationContext", "(", ")", ")", ";", "this", ".", "registry", "=", "registry", ";", "this", ".", "imageViewTargetFactory", "=", "imageViewTargetFactory", ";", "this", ".", "options", "=", "options", ";", "this", ".", "engine", "=", "engine", ";", "this", ".", "componentCallbacks", "=", "componentCallbacks", ";", "mainHandler", "=", "new", "Handler", "(", "Looper", ".", "getMainLooper", "(", ")", ")", ";", "}", "public", "RequestOptions", "getOptions", "(", ")", "{", "return", "options", ";", "}", "public", "<", "X", ">", "Target", "<", "X", ">", "buildImageViewTarget", "(", "ImageView", "imageView", ",", "Class", "<", "X", ">", "transcodeClass", ")", "{", "return", "imageViewTargetFactory", ".", "buildTarget", "(", "imageView", ",", "transcodeClass", ")", ";", "}", "public", "Handler", "getMainHandler", "(", ")", "{", "return", "mainHandler", ";", "}", "public", "Engine", "getEngine", "(", ")", "{", "return", "engine", ";", "}", "public", "Registry", "getRegistry", "(", ")", "{", "return", "registry", ";", "}", "@", "Override", "public", "void", "onTrimMemory", "(", "int", "level", ")", "{", "componentCallbacks", ".", "onTrimMemory", "(", "level", ")", ";", "}", "@", "Override", "public", "void", "onConfigurationChanged", "(", "Configuration", "newConfig", ")", "{", "componentCallbacks", ".", "onConfigurationChanged", "(", "newConfig", ")", ";", "}", "@", "Override", "public", "void", "onLowMemory", "(", ")", "{", "componentCallbacks", ".", "onLowMemory", "(", ")", ";", "}", "}" ]
Global context for all loads in Glide containing and exposing the various registries and classes required to load resources.
[ "Global", "context", "for", "all", "loads", "in", "Glide", "containing", "and", "exposing", "the", "various", "registries", "and", "classes", "required", "to", "load", "resources", "." ]
[]
[ { "param": "ContextWrapper", "type": null }, { "param": "ComponentCallbacks2", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ContextWrapper", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "ComponentCallbacks2", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35e2f2691f7f1ea84a1b25f1a725f9d641f00318
fras2560/Tangent-L
src/utilities/CommandLineArguments.java
[ "Apache-2.0" ]
Java
CommandLineArguments
/** * A class to parse the command line arguments. * * @author Dallas Fraser * @since 2018-02-02 */
A class to parse the command line arguments. @author Dallas Fraser @since 2018-02-02
[ "A", "class", "to", "parse", "the", "command", "line", "arguments", ".", "@author", "Dallas", "Fraser", "@since", "2018", "-", "02", "-", "02" ]
public class CommandLineArguments { public static String INDEXDIRECTORY = "indexDirectory"; public static String QUERIES = "queriesFile"; public static String JUDGEMENTS = "judgements"; public static String DOCUMENTSDIRECTORY = "documentsDirectory"; public static String LOGFILE = "logFile"; public static String RESULTSFILE = "resultsFile"; public static String QUERIESOUTPUTFILE = "queriesOutputFile"; public static String SEPERATOR = ":"; private final Map<String, Path> configLookup; private Path indexPath; private Path queriesPath; private Path judgementsPath; private Path documentsPath; private Path logPath; private Path resultsPath; private Path queriesOutputPath; /** * The command Line arguments. * * @param args the string of arguments from the command line * @throws CommandLineException raised when the help is passed as a parameter * @throws IOException - issue while dealing with a file */ public CommandLineArguments(String[] args) throws CommandLineException, IOException { this(args, new ArrayList<String>()); } /** * Loads the config file. that should be located at root folder in a file called config.txt * * @return Map the lookup of the config * @throws IOException - issue while dealing with a file */ public static Map<String, Path> loadConfig() throws IOException { final Path config = Paths.get(System.getProperty("user.dir"), "config.txt"); final BufferedReader fileReader = new BufferedReader(new FileReader(config.toFile())); String line; String attribute; Path value; String[] parts; final Map<String, Path> configLookup = new HashMap<String, Path>(); while ((line = fileReader.readLine()) != null && !line.trim().equals("")) { if (!line.startsWith("#")) { parts = line.split(CommandLineArguments.SEPERATOR); if (parts.length != 2) { // not sure what the file is fileReader.close(); throw new IOException("Unrecongizable config file"); } attribute = parts[0].trim(); value = Paths.get(parts[1].trim()); configLookup.put(attribute, value); } } System.out.println(configLookup); fileReader.close(); return configLookup; } /** * Constructor. * * @param args the string of arguments from the command line * @param required a list of required arguments * @throws CommandLineException - issue command line arguemtns * @throws IOException - issue while dealing with a file */ public CommandLineArguments(String[] args, List<String> required) throws CommandLineException, IOException { // check command line for override default methods this.configLookup = CommandLineArguments.loadConfig(); this.indexPath = null; this.resultsPath = null; this.queriesOutputPath = null; this.documentsPath = null; this.logPath = null; this.queriesPath = null; this.judgementsPath = null; for (int i = 0; i < args.length; i++) { if (args[i].equals("-h") || args[i].equals("-help")) { throw new CommandLineException("Help was request at the command line"); } else if (("-" + CommandLineArguments.INDEXDIRECTORY).equals(args[i])) { this.indexPath = Paths.get(args[i + 1]); i++; } else if (("-" + CommandLineArguments.RESULTSFILE).equals(args[i])) { this.resultsPath = Paths.get(args[i + 1]); i++; } else if (("-" + CommandLineArguments.QUERIESOUTPUTFILE).equals(args[i])) { this.queriesOutputPath = Paths.get(args[i + 1]); i++; } else if (("-" + CommandLineArguments.DOCUMENTSDIRECTORY).equals(args[i])) { this.documentsPath = Paths.get(args[i + 1]); i++; } else if (("-" + CommandLineArguments.LOGFILE).equals(args[i])) { this.logPath = Paths.get(args[i + 1]); i++; } else if (("-" + CommandLineArguments.QUERIES).equals(args[i])) { this.queriesPath = Paths.get(args[i + 1]); i++; } else if (("-" + CommandLineArguments.JUDGEMENTS).equals(args[i])) { this.judgementsPath = Paths.get(args[i + 1]); i++; } } for (final String check : required) { if (check.equals(CommandLineArguments.INDEXDIRECTORY) && this.indexPath == null) { this.indexPath = this.pathOrLookup(this.indexPath, CommandLineArguments.INDEXDIRECTORY); if (this.indexPath == null) { throw new CommandLineException( "Missing Required IndexDirectory and not listed in Config"); } } else if (check.equals(CommandLineArguments.RESULTSFILE) && this.resultsPath == null) { this.resultsPath = this.pathOrLookup(this.resultsPath, CommandLineArguments.RESULTSFILE); if (this.resultsPath == null) { throw new CommandLineException( "Missing Required ResultsDirectory and not listed in Config"); } } else if (check.equals(CommandLineArguments.QUERIESOUTPUTFILE) && this.queriesOutputPath == null) { this.queriesOutputPath = this.pathOrLookup(this.queriesOutputPath, CommandLineArguments.QUERIESOUTPUTFILE); if (this.queriesOutputPath == null) { throw new CommandLineException( "Missing Required Queries Output File and not listed in Config"); } } else if (check.equals(CommandLineArguments.DOCUMENTSDIRECTORY) && this.documentsPath == null) { this.documentsPath = this.pathOrLookup(this.documentsPath, CommandLineArguments.DOCUMENTSDIRECTORY); if (this.documentsPath == null) { throw new CommandLineException( "Missing Required Documents Folder and not listed in Config"); } } else if (check.equals(CommandLineArguments.LOGFILE) && this.logPath == null) { this.logPath = this.pathOrLookup(this.logPath, CommandLineArguments.LOGFILE); if (this.logPath == null) { throw new CommandLineException("Missing Required Log File and not listed in Config"); } } else if (check.equals(CommandLineArguments.QUERIES) && this.queriesPath == null) { this.queriesPath = this.pathOrLookup(this.queriesPath, CommandLineArguments.QUERIES); if (this.queriesPath == null) { throw new CommandLineException("Missing Required Queries File and not listed in Config"); } } else if (check.equals(CommandLineArguments.JUDGEMENTS) && this.judgementsPath == null) { this.judgementsPath = this.pathOrLookup(this.judgementsPath, CommandLineArguments.JUDGEMENTS); if (this.judgementsPath == null) { throw new CommandLineException( "Missing Required Judgements File and not listed in Config"); } } } } /** * Returns a Path or Looks it up. * * @param check a possible path if null then lookup it up * @param argument the argument path * @return Path the path */ public Path pathOrLookup(Path check, String argument) { Path result = check; if (check == null) { result = this.configLookup.get(argument); } System.out.println("Lookup result" + result); return result; } /** * Get the path for some parameter. * * @param parameter the parameter to get a path for * @return Path the resulting path for the parameter * @throws CommandLineException - exception when dealing command line */ public Path getPath(String parameter) throws CommandLineException { Path p = null; if (parameter.equals(CommandLineArguments.INDEXDIRECTORY)) { p = this.indexPath; } else if (parameter.equals(CommandLineArguments.RESULTSFILE)) { p = this.resultsPath; } else if (parameter.equals(CommandLineArguments.QUERIESOUTPUTFILE)) { p = this.queriesOutputPath; } else if (parameter.equals(CommandLineArguments.DOCUMENTSDIRECTORY)) { p = this.documentsPath; } else if (parameter.equals(CommandLineArguments.LOGFILE)) { p = this.logPath; } else if (parameter.equals(CommandLineArguments.QUERIES)) { p = this.queriesPath; } else if (parameter.equals(CommandLineArguments.JUDGEMENTS)) { p = this.judgementsPath; } else { throw new CommandLineException("Unknown Command Line Parameter: " + parameter); } return p; } }
[ "public", "class", "CommandLineArguments", "{", "public", "static", "String", "INDEXDIRECTORY", "=", "\"", "indexDirectory", "\"", ";", "public", "static", "String", "QUERIES", "=", "\"", "queriesFile", "\"", ";", "public", "static", "String", "JUDGEMENTS", "=", "\"", "judgements", "\"", ";", "public", "static", "String", "DOCUMENTSDIRECTORY", "=", "\"", "documentsDirectory", "\"", ";", "public", "static", "String", "LOGFILE", "=", "\"", "logFile", "\"", ";", "public", "static", "String", "RESULTSFILE", "=", "\"", "resultsFile", "\"", ";", "public", "static", "String", "QUERIESOUTPUTFILE", "=", "\"", "queriesOutputFile", "\"", ";", "public", "static", "String", "SEPERATOR", "=", "\"", ":", "\"", ";", "private", "final", "Map", "<", "String", ",", "Path", ">", "configLookup", ";", "private", "Path", "indexPath", ";", "private", "Path", "queriesPath", ";", "private", "Path", "judgementsPath", ";", "private", "Path", "documentsPath", ";", "private", "Path", "logPath", ";", "private", "Path", "resultsPath", ";", "private", "Path", "queriesOutputPath", ";", "/**\n * The command Line arguments.\n *\n * @param args the string of arguments from the command line\n * @throws CommandLineException raised when the help is passed as a parameter\n * @throws IOException - issue while dealing with a file\n */", "public", "CommandLineArguments", "(", "String", "[", "]", "args", ")", "throws", "CommandLineException", ",", "IOException", "{", "this", "(", "args", ",", "new", "ArrayList", "<", "String", ">", "(", ")", ")", ";", "}", "/**\n * Loads the config file. that should be located at root folder in a file called config.txt\n *\n * @return Map the lookup of the config\n * @throws IOException - issue while dealing with a file\n */", "public", "static", "Map", "<", "String", ",", "Path", ">", "loadConfig", "(", ")", "throws", "IOException", "{", "final", "Path", "config", "=", "Paths", ".", "get", "(", "System", ".", "getProperty", "(", "\"", "user.dir", "\"", ")", ",", "\"", "config.txt", "\"", ")", ";", "final", "BufferedReader", "fileReader", "=", "new", "BufferedReader", "(", "new", "FileReader", "(", "config", ".", "toFile", "(", ")", ")", ")", ";", "String", "line", ";", "String", "attribute", ";", "Path", "value", ";", "String", "[", "]", "parts", ";", "final", "Map", "<", "String", ",", "Path", ">", "configLookup", "=", "new", "HashMap", "<", "String", ",", "Path", ">", "(", ")", ";", "while", "(", "(", "line", "=", "fileReader", ".", "readLine", "(", ")", ")", "!=", "null", "&&", "!", "line", ".", "trim", "(", ")", ".", "equals", "(", "\"", "\"", ")", ")", "{", "if", "(", "!", "line", ".", "startsWith", "(", "\"", "#", "\"", ")", ")", "{", "parts", "=", "line", ".", "split", "(", "CommandLineArguments", ".", "SEPERATOR", ")", ";", "if", "(", "parts", ".", "length", "!=", "2", ")", "{", "fileReader", ".", "close", "(", ")", ";", "throw", "new", "IOException", "(", "\"", "Unrecongizable config file", "\"", ")", ";", "}", "attribute", "=", "parts", "[", "0", "]", ".", "trim", "(", ")", ";", "value", "=", "Paths", ".", "get", "(", "parts", "[", "1", "]", ".", "trim", "(", ")", ")", ";", "configLookup", ".", "put", "(", "attribute", ",", "value", ")", ";", "}", "}", "System", ".", "out", ".", "println", "(", "configLookup", ")", ";", "fileReader", ".", "close", "(", ")", ";", "return", "configLookup", ";", "}", "/**\n * Constructor.\n *\n * @param args the string of arguments from the command line\n * @param required a list of required arguments\n * @throws CommandLineException - issue command line arguemtns\n * @throws IOException - issue while dealing with a file\n */", "public", "CommandLineArguments", "(", "String", "[", "]", "args", ",", "List", "<", "String", ">", "required", ")", "throws", "CommandLineException", ",", "IOException", "{", "this", ".", "configLookup", "=", "CommandLineArguments", ".", "loadConfig", "(", ")", ";", "this", ".", "indexPath", "=", "null", ";", "this", ".", "resultsPath", "=", "null", ";", "this", ".", "queriesOutputPath", "=", "null", ";", "this", ".", "documentsPath", "=", "null", ";", "this", ".", "logPath", "=", "null", ";", "this", ".", "queriesPath", "=", "null", ";", "this", ".", "judgementsPath", "=", "null", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "{", "if", "(", "args", "[", "i", "]", ".", "equals", "(", "\"", "-h", "\"", ")", "||", "args", "[", "i", "]", ".", "equals", "(", "\"", "-help", "\"", ")", ")", "{", "throw", "new", "CommandLineException", "(", "\"", "Help was request at the command line", "\"", ")", ";", "}", "else", "if", "(", "(", "\"", "-", "\"", "+", "CommandLineArguments", ".", "INDEXDIRECTORY", ")", ".", "equals", "(", "args", "[", "i", "]", ")", ")", "{", "this", ".", "indexPath", "=", "Paths", ".", "get", "(", "args", "[", "i", "+", "1", "]", ")", ";", "i", "++", ";", "}", "else", "if", "(", "(", "\"", "-", "\"", "+", "CommandLineArguments", ".", "RESULTSFILE", ")", ".", "equals", "(", "args", "[", "i", "]", ")", ")", "{", "this", ".", "resultsPath", "=", "Paths", ".", "get", "(", "args", "[", "i", "+", "1", "]", ")", ";", "i", "++", ";", "}", "else", "if", "(", "(", "\"", "-", "\"", "+", "CommandLineArguments", ".", "QUERIESOUTPUTFILE", ")", ".", "equals", "(", "args", "[", "i", "]", ")", ")", "{", "this", ".", "queriesOutputPath", "=", "Paths", ".", "get", "(", "args", "[", "i", "+", "1", "]", ")", ";", "i", "++", ";", "}", "else", "if", "(", "(", "\"", "-", "\"", "+", "CommandLineArguments", ".", "DOCUMENTSDIRECTORY", ")", ".", "equals", "(", "args", "[", "i", "]", ")", ")", "{", "this", ".", "documentsPath", "=", "Paths", ".", "get", "(", "args", "[", "i", "+", "1", "]", ")", ";", "i", "++", ";", "}", "else", "if", "(", "(", "\"", "-", "\"", "+", "CommandLineArguments", ".", "LOGFILE", ")", ".", "equals", "(", "args", "[", "i", "]", ")", ")", "{", "this", ".", "logPath", "=", "Paths", ".", "get", "(", "args", "[", "i", "+", "1", "]", ")", ";", "i", "++", ";", "}", "else", "if", "(", "(", "\"", "-", "\"", "+", "CommandLineArguments", ".", "QUERIES", ")", ".", "equals", "(", "args", "[", "i", "]", ")", ")", "{", "this", ".", "queriesPath", "=", "Paths", ".", "get", "(", "args", "[", "i", "+", "1", "]", ")", ";", "i", "++", ";", "}", "else", "if", "(", "(", "\"", "-", "\"", "+", "CommandLineArguments", ".", "JUDGEMENTS", ")", ".", "equals", "(", "args", "[", "i", "]", ")", ")", "{", "this", ".", "judgementsPath", "=", "Paths", ".", "get", "(", "args", "[", "i", "+", "1", "]", ")", ";", "i", "++", ";", "}", "}", "for", "(", "final", "String", "check", ":", "required", ")", "{", "if", "(", "check", ".", "equals", "(", "CommandLineArguments", ".", "INDEXDIRECTORY", ")", "&&", "this", ".", "indexPath", "==", "null", ")", "{", "this", ".", "indexPath", "=", "this", ".", "pathOrLookup", "(", "this", ".", "indexPath", ",", "CommandLineArguments", ".", "INDEXDIRECTORY", ")", ";", "if", "(", "this", ".", "indexPath", "==", "null", ")", "{", "throw", "new", "CommandLineException", "(", "\"", "Missing Required IndexDirectory and not listed in Config", "\"", ")", ";", "}", "}", "else", "if", "(", "check", ".", "equals", "(", "CommandLineArguments", ".", "RESULTSFILE", ")", "&&", "this", ".", "resultsPath", "==", "null", ")", "{", "this", ".", "resultsPath", "=", "this", ".", "pathOrLookup", "(", "this", ".", "resultsPath", ",", "CommandLineArguments", ".", "RESULTSFILE", ")", ";", "if", "(", "this", ".", "resultsPath", "==", "null", ")", "{", "throw", "new", "CommandLineException", "(", "\"", "Missing Required ResultsDirectory and not listed in Config", "\"", ")", ";", "}", "}", "else", "if", "(", "check", ".", "equals", "(", "CommandLineArguments", ".", "QUERIESOUTPUTFILE", ")", "&&", "this", ".", "queriesOutputPath", "==", "null", ")", "{", "this", ".", "queriesOutputPath", "=", "this", ".", "pathOrLookup", "(", "this", ".", "queriesOutputPath", ",", "CommandLineArguments", ".", "QUERIESOUTPUTFILE", ")", ";", "if", "(", "this", ".", "queriesOutputPath", "==", "null", ")", "{", "throw", "new", "CommandLineException", "(", "\"", "Missing Required Queries Output File and not listed in Config", "\"", ")", ";", "}", "}", "else", "if", "(", "check", ".", "equals", "(", "CommandLineArguments", ".", "DOCUMENTSDIRECTORY", ")", "&&", "this", ".", "documentsPath", "==", "null", ")", "{", "this", ".", "documentsPath", "=", "this", ".", "pathOrLookup", "(", "this", ".", "documentsPath", ",", "CommandLineArguments", ".", "DOCUMENTSDIRECTORY", ")", ";", "if", "(", "this", ".", "documentsPath", "==", "null", ")", "{", "throw", "new", "CommandLineException", "(", "\"", "Missing Required Documents Folder and not listed in Config", "\"", ")", ";", "}", "}", "else", "if", "(", "check", ".", "equals", "(", "CommandLineArguments", ".", "LOGFILE", ")", "&&", "this", ".", "logPath", "==", "null", ")", "{", "this", ".", "logPath", "=", "this", ".", "pathOrLookup", "(", "this", ".", "logPath", ",", "CommandLineArguments", ".", "LOGFILE", ")", ";", "if", "(", "this", ".", "logPath", "==", "null", ")", "{", "throw", "new", "CommandLineException", "(", "\"", "Missing Required Log File and not listed in Config", "\"", ")", ";", "}", "}", "else", "if", "(", "check", ".", "equals", "(", "CommandLineArguments", ".", "QUERIES", ")", "&&", "this", ".", "queriesPath", "==", "null", ")", "{", "this", ".", "queriesPath", "=", "this", ".", "pathOrLookup", "(", "this", ".", "queriesPath", ",", "CommandLineArguments", ".", "QUERIES", ")", ";", "if", "(", "this", ".", "queriesPath", "==", "null", ")", "{", "throw", "new", "CommandLineException", "(", "\"", "Missing Required Queries File and not listed in Config", "\"", ")", ";", "}", "}", "else", "if", "(", "check", ".", "equals", "(", "CommandLineArguments", ".", "JUDGEMENTS", ")", "&&", "this", ".", "judgementsPath", "==", "null", ")", "{", "this", ".", "judgementsPath", "=", "this", ".", "pathOrLookup", "(", "this", ".", "judgementsPath", ",", "CommandLineArguments", ".", "JUDGEMENTS", ")", ";", "if", "(", "this", ".", "judgementsPath", "==", "null", ")", "{", "throw", "new", "CommandLineException", "(", "\"", "Missing Required Judgements File and not listed in Config", "\"", ")", ";", "}", "}", "}", "}", "/**\n * Returns a Path or Looks it up.\n *\n * @param check a possible path if null then lookup it up\n * @param argument the argument path\n * @return Path the path\n */", "public", "Path", "pathOrLookup", "(", "Path", "check", ",", "String", "argument", ")", "{", "Path", "result", "=", "check", ";", "if", "(", "check", "==", "null", ")", "{", "result", "=", "this", ".", "configLookup", ".", "get", "(", "argument", ")", ";", "}", "System", ".", "out", ".", "println", "(", "\"", "Lookup result", "\"", "+", "result", ")", ";", "return", "result", ";", "}", "/**\n * Get the path for some parameter.\n *\n * @param parameter the parameter to get a path for\n * @return Path the resulting path for the parameter\n * @throws CommandLineException - exception when dealing command line\n */", "public", "Path", "getPath", "(", "String", "parameter", ")", "throws", "CommandLineException", "{", "Path", "p", "=", "null", ";", "if", "(", "parameter", ".", "equals", "(", "CommandLineArguments", ".", "INDEXDIRECTORY", ")", ")", "{", "p", "=", "this", ".", "indexPath", ";", "}", "else", "if", "(", "parameter", ".", "equals", "(", "CommandLineArguments", ".", "RESULTSFILE", ")", ")", "{", "p", "=", "this", ".", "resultsPath", ";", "}", "else", "if", "(", "parameter", ".", "equals", "(", "CommandLineArguments", ".", "QUERIESOUTPUTFILE", ")", ")", "{", "p", "=", "this", ".", "queriesOutputPath", ";", "}", "else", "if", "(", "parameter", ".", "equals", "(", "CommandLineArguments", ".", "DOCUMENTSDIRECTORY", ")", ")", "{", "p", "=", "this", ".", "documentsPath", ";", "}", "else", "if", "(", "parameter", ".", "equals", "(", "CommandLineArguments", ".", "LOGFILE", ")", ")", "{", "p", "=", "this", ".", "logPath", ";", "}", "else", "if", "(", "parameter", ".", "equals", "(", "CommandLineArguments", ".", "QUERIES", ")", ")", "{", "p", "=", "this", ".", "queriesPath", ";", "}", "else", "if", "(", "parameter", ".", "equals", "(", "CommandLineArguments", ".", "JUDGEMENTS", ")", ")", "{", "p", "=", "this", ".", "judgementsPath", ";", "}", "else", "{", "throw", "new", "CommandLineException", "(", "\"", "Unknown Command Line Parameter: ", "\"", "+", "parameter", ")", ";", "}", "return", "p", ";", "}", "}" ]
A class to parse the command line arguments.
[ "A", "class", "to", "parse", "the", "command", "line", "arguments", "." ]
[ "// not sure what the file is", "// check command line for override default methods" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
35e35f667d05a01a6bcf3f740d742b1c170f5d60
vietnux/CodeEditorMobile
examples/ru.iiec.cxxdroid/sources/androidx/fragment/app/d.java
[ "Apache-2.0" ]
Java
C0019d
/* renamed from: androidx.fragment.app.d$d reason: collision with other inner class name */
renamed from: androidx.fragment.app.d$d reason: collision with other inner class name
[ "renamed", "from", ":", "androidx", ".", "fragment", ".", "app", ".", "d$d", "reason", ":", "collision", "with", "other", "inner", "class", "name" ]
class C0019d implements o<i> { C0019d() { } @SuppressLint({"SyntheticAccessor"}) public void a(i iVar) { if (iVar != null && d.this.g0) { View t0 = d.this.t0(); if (t0.getParent() != null) { throw new IllegalStateException("DialogFragment can not be attached to a container view"); } else if (d.this.k0 != null) { if (n.d(3)) { Log.d("FragmentManager", "DialogFragment " + this + " setting the content view on " + d.this.k0); } d.this.k0.setContentView(t0); } } } }
[ "class", "C0019d", "implements", "o", "<", "i", ">", "{", "C0019d", "(", ")", "{", "}", "@", "SuppressLint", "(", "{", "\"", "SyntheticAccessor", "\"", "}", ")", "public", "void", "a", "(", "i", "iVar", ")", "{", "if", "(", "iVar", "!=", "null", "&&", "d", ".", "this", ".", "g0", ")", "{", "View", "t0", "=", "d", ".", "this", ".", "t0", "(", ")", ";", "if", "(", "t0", ".", "getParent", "(", ")", "!=", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "DialogFragment can not be attached to a container view", "\"", ")", ";", "}", "else", "if", "(", "d", ".", "this", ".", "k0", "!=", "null", ")", "{", "if", "(", "n", ".", "d", "(", "3", ")", ")", "{", "Log", ".", "d", "(", "\"", "FragmentManager", "\"", ",", "\"", "DialogFragment ", "\"", "+", "this", "+", "\"", " setting the content view on ", "\"", "+", "d", ".", "this", ".", "k0", ")", ";", "}", "d", ".", "this", ".", "k0", ".", "setContentView", "(", "t0", ")", ";", "}", "}", "}", "}" ]
renamed from: androidx.fragment.app.d$d reason: collision with other inner class name
[ "renamed", "from", ":", "androidx", ".", "fragment", ".", "app", ".", "d$d", "reason", ":", "collision", "with", "other", "inner", "class", "name" ]
[]
[ { "param": "o<i>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "o<i>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35e4e79f321fddbd44c3640e972a4ba1094a2985
yuri0x7c1/uxerp
uxcrm-ofbiz/generated-entity/src/main/java/org/apache/ofbiz/party/party/PartyIcsAvsOverride.java
[ "Apache-2.0" ]
Java
PartyIcsAvsOverride
/** * Party Ics Avs Override */
Party Ics Avs Override
[ "Party", "Ics", "Avs", "Override" ]
@FieldNameConstants public class PartyIcsAvsOverride implements Serializable { public static final long serialVersionUID = 1233288659383099392L; public static final String NAME = "PartyIcsAvsOverride"; /** * Party Id */ @Getter @Setter private String partyId; /** * Avs Decline String */ @Getter @Setter private String avsDeclineString; /** * Last Updated Stamp */ @Getter @Setter private Timestamp lastUpdatedStamp; /** * Last Updated Tx Stamp */ @Getter @Setter private Timestamp lastUpdatedTxStamp; /** * Created Stamp */ @Getter @Setter private Timestamp createdStamp; /** * Created Tx Stamp */ @Getter @Setter private Timestamp createdTxStamp; public PartyIcsAvsOverride(GenericValue value) { partyId = (String) value.get(FIELD_PARTY_ID); avsDeclineString = (String) value.get(FIELD_AVS_DECLINE_STRING); lastUpdatedStamp = (Timestamp) value.get(FIELD_LAST_UPDATED_STAMP); lastUpdatedTxStamp = (Timestamp) value.get(FIELD_LAST_UPDATED_TX_STAMP); createdStamp = (Timestamp) value.get(FIELD_CREATED_STAMP); createdTxStamp = (Timestamp) value.get(FIELD_CREATED_TX_STAMP); } public static PartyIcsAvsOverride fromValue( org.apache.ofbiz.entity.GenericValue value) { return new PartyIcsAvsOverride(value); } public static List<PartyIcsAvsOverride> fromValues(List<GenericValue> values) { List<PartyIcsAvsOverride> entities = new ArrayList<>(); for (GenericValue value : values) { entities.add(new PartyIcsAvsOverride(value)); } return entities; } }
[ "@", "FieldNameConstants", "public", "class", "PartyIcsAvsOverride", "implements", "Serializable", "{", "public", "static", "final", "long", "serialVersionUID", "=", "1233288659383099392L", ";", "public", "static", "final", "String", "NAME", "=", "\"", "PartyIcsAvsOverride", "\"", ";", "/**\n\t * Party Id\n\t */", "@", "Getter", "@", "Setter", "private", "String", "partyId", ";", "/**\n\t * Avs Decline String\n\t */", "@", "Getter", "@", "Setter", "private", "String", "avsDeclineString", ";", "/**\n\t * Last Updated Stamp\n\t */", "@", "Getter", "@", "Setter", "private", "Timestamp", "lastUpdatedStamp", ";", "/**\n\t * Last Updated Tx Stamp\n\t */", "@", "Getter", "@", "Setter", "private", "Timestamp", "lastUpdatedTxStamp", ";", "/**\n\t * Created Stamp\n\t */", "@", "Getter", "@", "Setter", "private", "Timestamp", "createdStamp", ";", "/**\n\t * Created Tx Stamp\n\t */", "@", "Getter", "@", "Setter", "private", "Timestamp", "createdTxStamp", ";", "public", "PartyIcsAvsOverride", "(", "GenericValue", "value", ")", "{", "partyId", "=", "(", "String", ")", "value", ".", "get", "(", "FIELD_PARTY_ID", ")", ";", "avsDeclineString", "=", "(", "String", ")", "value", ".", "get", "(", "FIELD_AVS_DECLINE_STRING", ")", ";", "lastUpdatedStamp", "=", "(", "Timestamp", ")", "value", ".", "get", "(", "FIELD_LAST_UPDATED_STAMP", ")", ";", "lastUpdatedTxStamp", "=", "(", "Timestamp", ")", "value", ".", "get", "(", "FIELD_LAST_UPDATED_TX_STAMP", ")", ";", "createdStamp", "=", "(", "Timestamp", ")", "value", ".", "get", "(", "FIELD_CREATED_STAMP", ")", ";", "createdTxStamp", "=", "(", "Timestamp", ")", "value", ".", "get", "(", "FIELD_CREATED_TX_STAMP", ")", ";", "}", "public", "static", "PartyIcsAvsOverride", "fromValue", "(", "org", ".", "apache", ".", "ofbiz", ".", "entity", ".", "GenericValue", "value", ")", "{", "return", "new", "PartyIcsAvsOverride", "(", "value", ")", ";", "}", "public", "static", "List", "<", "PartyIcsAvsOverride", ">", "fromValues", "(", "List", "<", "GenericValue", ">", "values", ")", "{", "List", "<", "PartyIcsAvsOverride", ">", "entities", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "GenericValue", "value", ":", "values", ")", "{", "entities", ".", "add", "(", "new", "PartyIcsAvsOverride", "(", "value", ")", ")", ";", "}", "return", "entities", ";", "}", "}" ]
Party Ics Avs Override
[ "Party", "Ics", "Avs", "Override" ]
[]
[ { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35e7ccd44b4fb3af496e08f0be282a8a2446ed6d
YY-ORG/yycloud
yy-common/yy-common-utils/src/main/java/com/yy/cloud/common/data/otd/assess/MarkedAssessAnswerItem.java
[ "Apache-2.0" ]
Java
MarkedAssessAnswerItem
/** * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON. <br/> * Date: 1/24/18 9:33 PM<br/> * * @author chenxj * @see * @since JDK 1.8 */
@author chenxj @see @since JDK 1.8
[ "@author", "chenxj", "@see", "@since", "JDK", "1", ".", "8" ]
@Data public class MarkedAssessAnswerItem extends SimpleAssessAnswerItem { private static final long serialVersionUID = -7659550556386376601L; private BigDecimal auxiliaryScore = BigDecimal.ZERO; private BigDecimal markedScore = BigDecimal.ZERO; private BigDecimal auditScore = BigDecimal.ZERO; private BigDecimal rMarkedScore = BigDecimal.ZERO; private BigDecimal rAuditScore = BigDecimal.ZERO; private String markedComment; private String auditComment; }
[ "@", "Data", "public", "class", "MarkedAssessAnswerItem", "extends", "SimpleAssessAnswerItem", "{", "private", "static", "final", "long", "serialVersionUID", "=", "-", "7659550556386376601L", ";", "private", "BigDecimal", "auxiliaryScore", "=", "BigDecimal", ".", "ZERO", ";", "private", "BigDecimal", "markedScore", "=", "BigDecimal", ".", "ZERO", ";", "private", "BigDecimal", "auditScore", "=", "BigDecimal", ".", "ZERO", ";", "private", "BigDecimal", "rMarkedScore", "=", "BigDecimal", ".", "ZERO", ";", "private", "BigDecimal", "rAuditScore", "=", "BigDecimal", ".", "ZERO", ";", "private", "String", "markedComment", ";", "private", "String", "auditComment", ";", "}" ]
Function: TODO ADD FUNCTION.
[ "Function", ":", "TODO", "ADD", "FUNCTION", "." ]
[]
[ { "param": "SimpleAssessAnswerItem", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "SimpleAssessAnswerItem", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35e85f48f75c44c240d76f477bc5cfbe6a7a4483
ll901001/picketlink
modules/federation/src/main/java/org/picketlink/identity/federation/web/process/SAMLHandlerChainProcessor.java
[ "Apache-2.0" ]
Java
SAMLHandlerChainProcessor
/** * Processor for the SAML2 Handler Chain * * @author Anil.Saldhana@redhat.com * @since Oct 27, 2009 */
Processor for the SAML2 Handler Chain @author Anil.Saldhana@redhat.com @since Oct 27, 2009
[ "Processor", "for", "the", "SAML2", "Handler", "Chain", "@author", "Anil", ".", "Saldhana@redhat", ".", "com", "@since", "Oct", "27", "2009" ]
public class SAMLHandlerChainProcessor { private final Set<SAML2Handler> handlers = new LinkedHashSet<SAML2Handler>(); private final PicketLinkType configuration; public SAMLHandlerChainProcessor(Set<SAML2Handler> handlers, PicketLinkType configuration) { this.handlers.addAll(handlers); this.configuration = configuration; } public void callHandlerChain(SAML2Object samlObject, SAML2HandlerRequest saml2HandlerRequest, SAML2HandlerResponse saml2HandlerResponse, HTTPContext httpContext, Lock chainLock) throws ProcessingException, IOException { try { if (this.configuration.getHandlers().isLocking()) { chainLock.lock(); } // Deal with handler chains for (SAML2Handler handler : handlers) { if (saml2HandlerResponse.isInError()) { httpContext.getResponse().sendError(saml2HandlerResponse.getErrorCode()); break; } if (samlObject instanceof RequestAbstractType) { handler.handleRequestType(saml2HandlerRequest, saml2HandlerResponse); } else { handler.handleStatusResponseType(saml2HandlerRequest, saml2HandlerResponse); } } } finally { if (this.configuration.getHandlers().isLocking()) { chainLock.unlock(); } } } }
[ "public", "class", "SAMLHandlerChainProcessor", "{", "private", "final", "Set", "<", "SAML2Handler", ">", "handlers", "=", "new", "LinkedHashSet", "<", "SAML2Handler", ">", "(", ")", ";", "private", "final", "PicketLinkType", "configuration", ";", "public", "SAMLHandlerChainProcessor", "(", "Set", "<", "SAML2Handler", ">", "handlers", ",", "PicketLinkType", "configuration", ")", "{", "this", ".", "handlers", ".", "addAll", "(", "handlers", ")", ";", "this", ".", "configuration", "=", "configuration", ";", "}", "public", "void", "callHandlerChain", "(", "SAML2Object", "samlObject", ",", "SAML2HandlerRequest", "saml2HandlerRequest", ",", "SAML2HandlerResponse", "saml2HandlerResponse", ",", "HTTPContext", "httpContext", ",", "Lock", "chainLock", ")", "throws", "ProcessingException", ",", "IOException", "{", "try", "{", "if", "(", "this", ".", "configuration", ".", "getHandlers", "(", ")", ".", "isLocking", "(", ")", ")", "{", "chainLock", ".", "lock", "(", ")", ";", "}", "for", "(", "SAML2Handler", "handler", ":", "handlers", ")", "{", "if", "(", "saml2HandlerResponse", ".", "isInError", "(", ")", ")", "{", "httpContext", ".", "getResponse", "(", ")", ".", "sendError", "(", "saml2HandlerResponse", ".", "getErrorCode", "(", ")", ")", ";", "break", ";", "}", "if", "(", "samlObject", "instanceof", "RequestAbstractType", ")", "{", "handler", ".", "handleRequestType", "(", "saml2HandlerRequest", ",", "saml2HandlerResponse", ")", ";", "}", "else", "{", "handler", ".", "handleStatusResponseType", "(", "saml2HandlerRequest", ",", "saml2HandlerResponse", ")", ";", "}", "}", "}", "finally", "{", "if", "(", "this", ".", "configuration", ".", "getHandlers", "(", ")", ".", "isLocking", "(", ")", ")", "{", "chainLock", ".", "unlock", "(", ")", ";", "}", "}", "}", "}" ]
Processor for the SAML2 Handler Chain @author Anil.Saldhana@redhat.com @since Oct 27, 2009
[ "Processor", "for", "the", "SAML2", "Handler", "Chain", "@author", "Anil", ".", "Saldhana@redhat", ".", "com", "@since", "Oct", "27", "2009" ]
[ "// Deal with handler chains" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
35ea4cc63f65dca15fc26e6c8b9065c8d68b2dc6
BenZhao-forever/Ben-leetcode-practice
src/main/java/leetcode5.java
[ "MIT" ]
Java
leetcode5
/** * Package: PACKAGE_NAME * Created by Ben Zhao on 2021/6/27 * Project: Ben-leetcode-practice */
PACKAGE_NAME Created by Ben Zhao on 2021/6/27 Project: Ben-leetcode-practice
[ "PACKAGE_NAME", "Created", "by", "Ben", "Zhao", "on", "2021", "/", "6", "/", "27", "Project", ":", "Ben", "-", "leetcode", "-", "practice" ]
public class leetcode5 { public static void main(String[] args) { } public static String longestPalindrome(String s) { String answer = ""; if (s.length() == 0) { return answer; } answer = "" + s.charAt(0); int left; int right; for (int i = 0; i < s.length() - 1; i++) { left = i; right = i; answer = answer.length() > palindrome(s, left, right).length() ? answer : palindrome(s, left, right); if (s.charAt(i) == s.charAt(i + 1)) { right++; } answer = answer.length() > palindrome(s, left, right).length() ? answer : palindrome(s, left, right); } return answer; } public static String palindrome(String s, int left, int right) { while (s.charAt(left) == s.charAt(right)) { left--; right++; if (left < 0 || right >= s.length()) { break; } } return s.substring(left + 1, right); } }
[ "public", "class", "leetcode5", "{", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "}", "public", "static", "String", "longestPalindrome", "(", "String", "s", ")", "{", "String", "answer", "=", "\"", "\"", ";", "if", "(", "s", ".", "length", "(", ")", "==", "0", ")", "{", "return", "answer", ";", "}", "answer", "=", "\"", "\"", "+", "s", ".", "charAt", "(", "0", ")", ";", "int", "left", ";", "int", "right", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "s", ".", "length", "(", ")", "-", "1", ";", "i", "++", ")", "{", "left", "=", "i", ";", "right", "=", "i", ";", "answer", "=", "answer", ".", "length", "(", ")", ">", "palindrome", "(", "s", ",", "left", ",", "right", ")", ".", "length", "(", ")", "?", "answer", ":", "palindrome", "(", "s", ",", "left", ",", "right", ")", ";", "if", "(", "s", ".", "charAt", "(", "i", ")", "==", "s", ".", "charAt", "(", "i", "+", "1", ")", ")", "{", "right", "++", ";", "}", "answer", "=", "answer", ".", "length", "(", ")", ">", "palindrome", "(", "s", ",", "left", ",", "right", ")", ".", "length", "(", ")", "?", "answer", ":", "palindrome", "(", "s", ",", "left", ",", "right", ")", ";", "}", "return", "answer", ";", "}", "public", "static", "String", "palindrome", "(", "String", "s", ",", "int", "left", ",", "int", "right", ")", "{", "while", "(", "s", ".", "charAt", "(", "left", ")", "==", "s", ".", "charAt", "(", "right", ")", ")", "{", "left", "--", ";", "right", "++", ";", "if", "(", "left", "<", "0", "||", "right", ">=", "s", ".", "length", "(", ")", ")", "{", "break", ";", "}", "}", "return", "s", ".", "substring", "(", "left", "+", "1", ",", "right", ")", ";", "}", "}" ]
Package: PACKAGE_NAME Created by Ben Zhao on 2021/6/27 Project: Ben-leetcode-practice
[ "Package", ":", "PACKAGE_NAME", "Created", "by", "Ben", "Zhao", "on", "2021", "/", "6", "/", "27", "Project", ":", "Ben", "-", "leetcode", "-", "practice" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
35ecbcf692d538d51ad347e47588bf5f1f3b5798
jongha/android-boilerplate
modules/khanjar/khanjar/src/main/java/net/mrlatte/khanjar/ui/views/EditTextKnife.java
[ "MIT" ]
Java
EditTextKnife
/** * Created by Jong-Ha Ahn on 9/28/15. */
Created by Jong-Ha Ahn on 9/28/15.
[ "Created", "by", "Jong", "-", "Ha", "Ahn", "on", "9", "/", "28", "/", "15", "." ]
public class EditTextKnife { public static void setTextAndCursorEnd(EditText editText, String text) { editText.setText(text); placeCursorAtEnd(editText); } public static void placeCursorAtEnd(EditText editText) { editText.setSelection(editText.getText().length()); } }
[ "public", "class", "EditTextKnife", "{", "public", "static", "void", "setTextAndCursorEnd", "(", "EditText", "editText", ",", "String", "text", ")", "{", "editText", ".", "setText", "(", "text", ")", ";", "placeCursorAtEnd", "(", "editText", ")", ";", "}", "public", "static", "void", "placeCursorAtEnd", "(", "EditText", "editText", ")", "{", "editText", ".", "setSelection", "(", "editText", ".", "getText", "(", ")", ".", "length", "(", ")", ")", ";", "}", "}" ]
Created by Jong-Ha Ahn on 9/28/15.
[ "Created", "by", "Jong", "-", "Ha", "Ahn", "on", "9", "/", "28", "/", "15", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
35ed18037786b2ec0a3009345c422359771c3b75
murinrad/musicMultiply
Broadcaster/src/main/java/org/murinrad/android/musicmultiply/devices/management/MockAdvertListener.java
[ "Apache-2.0" ]
Java
MockAdvertListener
/** * Created by Radovan Murin on 6.4.2015. */
Created by Radovan Murin on 6.4.2015.
[ "Created", "by", "Radovan", "Murin", "on", "6", ".", "4", ".", "2015", "." ]
public class MockAdvertListener extends IDeviceAdvertListener { public MockAdvertListener(Context ctx) { super(ctx); Thread initThread = new Thread(new Runnable() { @Override public void run() { try { IDevice device = new DeviceImpl(InetAddress.getByName("192.168.1.3"), "fakeLocal", "F-F-F"); addDevice(device); device = new DeviceImpl(InetAddress.getByName("192.168.1.44"), "fakeLocal", "F-F-G"); addDevice(device); } catch (IOException ex) { Log.e(MainActivity.APP_TAG, "Error on init of fake device", ex); } } }); initThread.start(); } @Override public void stop() { //do nothing } }
[ "public", "class", "MockAdvertListener", "extends", "IDeviceAdvertListener", "{", "public", "MockAdvertListener", "(", "Context", "ctx", ")", "{", "super", "(", "ctx", ")", ";", "Thread", "initThread", "=", "new", "Thread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "IDevice", "device", "=", "new", "DeviceImpl", "(", "InetAddress", ".", "getByName", "(", "\"", "192.168.1.3", "\"", ")", ",", "\"", "fakeLocal", "\"", ",", "\"", "F-F-F", "\"", ")", ";", "addDevice", "(", "device", ")", ";", "device", "=", "new", "DeviceImpl", "(", "InetAddress", ".", "getByName", "(", "\"", "192.168.1.44", "\"", ")", ",", "\"", "fakeLocal", "\"", ",", "\"", "F-F-G", "\"", ")", ";", "addDevice", "(", "device", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "Log", ".", "e", "(", "MainActivity", ".", "APP_TAG", ",", "\"", "Error on init of fake device", "\"", ",", "ex", ")", ";", "}", "}", "}", ")", ";", "initThread", ".", "start", "(", ")", ";", "}", "@", "Override", "public", "void", "stop", "(", ")", "{", "}", "}" ]
Created by Radovan Murin on 6.4.2015.
[ "Created", "by", "Radovan", "Murin", "on", "6", ".", "4", ".", "2015", "." ]
[ "//do nothing" ]
[ { "param": "IDeviceAdvertListener", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IDeviceAdvertListener", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f222154acd77c142c1d22f379b54774cc565ad
frostymarvelous/Fluxxan
app/src/main/java/com/umaplay/fluxxandemo/flux/middleware/LoggerMiddleware.java
[ "MIT" ]
Java
LoggerMiddleware
/** * Created by niltonvasques on 11/15/16. */
Created by niltonvasques on 11/15/16.
[ "Created", "by", "niltonvasques", "on", "11", "/", "15", "/", "16", "." ]
public class LoggerMiddleware extends BaseMiddleware<AppState> { @Override public void before(Action action, AppState appState) throws Exception { Log.d("[LoggerMiddleware]", action.Type); } }
[ "public", "class", "LoggerMiddleware", "extends", "BaseMiddleware", "<", "AppState", ">", "{", "@", "Override", "public", "void", "before", "(", "Action", "action", ",", "AppState", "appState", ")", "throws", "Exception", "{", "Log", ".", "d", "(", "\"", "[LoggerMiddleware]", "\"", ",", "action", ".", "Type", ")", ";", "}", "}" ]
Created by niltonvasques on 11/15/16.
[ "Created", "by", "niltonvasques", "on", "11", "/", "15", "/", "16", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
35f2c5f4a61aa7cdea15778488b291758dcdee55
chegini91/mVis
dependencies/DMandML-master/src/main/java/com/github/TKnudsen/DMandML/model/associations/WekaAssociator.java
[ "MIT" ]
Java
WekaAssociator
/** * <p> * Title: WekaAssociator * </p> * * <p> * Description: * </p> * * <p> * Copyright: (c) 2016-2017 Juergen Bernard, https://github.com/TKnudsen/DMandML * </p> * * @author Juergen Bernard * @version 1.01 */
Description: @author Juergen Bernard @version 1.01
[ "Description", ":", "@author", "Juergen", "Bernard", "@version", "1", ".", "01" ]
public abstract class WekaAssociator implements IAssociator { protected AbstractAssociator associator; protected Instances data; protected abstract void initializeAssociator(); public void initializeData(ComplexDataContainer dataContainer) { data = WekaConversion.getInstances(dataContainer); } public void buildAssociations() throws Exception { if (data == null) throw new IllegalArgumentException("Associator: no data instances defined."); associator.buildAssociations(data); } public AbstractAssociator getAssociator() { return associator; } public void printResult() { System.out.println(associator); } }
[ "public", "abstract", "class", "WekaAssociator", "implements", "IAssociator", "{", "protected", "AbstractAssociator", "associator", ";", "protected", "Instances", "data", ";", "protected", "abstract", "void", "initializeAssociator", "(", ")", ";", "public", "void", "initializeData", "(", "ComplexDataContainer", "dataContainer", ")", "{", "data", "=", "WekaConversion", ".", "getInstances", "(", "dataContainer", ")", ";", "}", "public", "void", "buildAssociations", "(", ")", "throws", "Exception", "{", "if", "(", "data", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "Associator: no data instances defined.", "\"", ")", ";", "associator", ".", "buildAssociations", "(", "data", ")", ";", "}", "public", "AbstractAssociator", "getAssociator", "(", ")", "{", "return", "associator", ";", "}", "public", "void", "printResult", "(", ")", "{", "System", ".", "out", ".", "println", "(", "associator", ")", ";", "}", "}" ]
<p> Title: WekaAssociator </p>
[ "<p", ">", "Title", ":", "WekaAssociator", "<", "/", "p", ">" ]
[]
[ { "param": "IAssociator", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IAssociator", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f45a7d576b4aee3ba8a2fd7dd0739594bc7f4a
twistezo/currency-converter
src/main/java/MyFrame.java
[ "MIT" ]
Java
MyFrame
/** * Class with GUI * * @author twistezo * */
Class with GUI @author twistezo
[ "Class", "with", "GUI", "@author", "twistezo" ]
@SuppressWarnings("serial") public class MyFrame extends JFrame implements KeyListener { private int borderOffset = 5; private String userInputString; JTextField userInput; JTextField resultField; JRadioButton radioButtonPLNto; JRadioButton radioButtonEURto; JRadioButton radioButtonGBPto; JRadioButton radioButtonUSDto; JRadioButton radioButtonPLN; JRadioButton radioButtonEUR; JRadioButton radioButtonGBP; JRadioButton radioButtonUSD; JButton startButton; JButton cleanButton; JLabel dateLabel; JLabel serverLabel; JLabel todayLabel; JLabel onServerLabel; /** Check server on/off-line */ boolean serverIsWorking = CurrencyConverterMainClass.getServerWorking(); public MyFrame(){ /** app should look * -------------------------------------- * | | * | amountInput result | * | chooseCurrency1 chooseCurrency2 | * | countButton | * | | * -------------------------------------- */ /** Create main frame */ JFrame mainFrame = new JFrame("Currency Converter"); /** Create panels and offsets from border*/ JPanel mainPanel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); mainPanel.setBorder(BorderFactory.createEmptyBorder (borderOffset, borderOffset, borderOffset, borderOffset)); // up, left, down, right JPanel leftRadioButtonsBoxPanel = new JPanel(); leftRadioButtonsBoxPanel.setLayout((new BoxLayout(leftRadioButtonsBoxPanel, BoxLayout.PAGE_AXIS))); TitledBorder titledLeftRadioButtons = new TitledBorder(null, "from", TitledBorder.CENTER, TitledBorder.TOP, null, Color.gray); leftRadioButtonsBoxPanel.setBorder(titledLeftRadioButtons); JPanel rightRadioButtonsBoxPanel = new JPanel(); rightRadioButtonsBoxPanel.setLayout((new BoxLayout(rightRadioButtonsBoxPanel, BoxLayout.PAGE_AXIS))); TitledBorder titledRightRadioButtons = new TitledBorder(null, "to", TitledBorder.CENTER, TitledBorder.TOP, null, Color.gray); rightRadioButtonsBoxPanel.setBorder(titledRightRadioButtons); JPanel statusServerPanel = new JPanel(); /** Create TextFields - userInput of value */ userInput = new JTextField(); userInput.setHorizontalAlignment(JTextField.RIGHT); userInput.setPreferredSize( new Dimension( 100, 24 ) ); userInput.setFocusable(true); userInput.addKeyListener(this); resultField = new JTextField(); resultField.setHorizontalAlignment(JTextField.LEFT); resultField.setPreferredSize( new Dimension( 100, 24 ) ); resultField.setEditable(false); /** Create LEFT list of currency comodities */ radioButtonPLNto = new JRadioButton("PLN"); radioButtonPLNto.setSelected(true); radioButtonEURto = new JRadioButton("EUR"); radioButtonGBPto = new JRadioButton("GBP"); radioButtonUSDto = new JRadioButton("USD"); ButtonGroup buttonGroupLeft = new ButtonGroup(); buttonGroupLeft.add(radioButtonPLNto); buttonGroupLeft.add(radioButtonEURto); buttonGroupLeft.add(radioButtonGBPto); buttonGroupLeft.add(radioButtonUSDto); /** Create RIGHT list of currency comodities */ radioButtonPLN = new JRadioButton("PLN"); radioButtonEUR = new JRadioButton("EUR"); radioButtonEUR.setSelected(true); radioButtonGBP = new JRadioButton("GBP"); radioButtonUSD = new JRadioButton("USD"); ButtonGroup buttonGroupRight = new ButtonGroup(); buttonGroupRight.add(radioButtonPLN); buttonGroupRight.add(radioButtonEUR); buttonGroupRight.add(radioButtonGBP); buttonGroupRight.add(radioButtonUSD); /** Create bottom GO and CLEAN button */ startButton = new JButton("Calculate"); startButton.addActionListener(new startButtonListener()); cleanButton = new JButton("Clear"); cleanButton.addActionListener(new cleanButtonListener()); /** Create Separator */ JSeparator separatorH = new JSeparator(JSeparator.HORIZONTAL); separatorH.setPreferredSize(new Dimension(2,2)); /** Title */ JLabel titleLabel = new JLabel("Currency Converter"); titleLabel.setFont(new Font(null, Font.PLAIN, 20)); titleLabel.setForeground(Color.GRAY); /** Label with todays currencies */ if(serverIsWorking) { TodayValues today = new TodayValues(); today.getTodayValues(); BigDecimal oneValue = today.getOneValue(); BigDecimal secondValue = today.getSecondValue(); BigDecimal thirdValue = today.getThirdValue(); todayLabel = new JLabel("1 PLN = " +oneValue.toString()+ " EUR / " +secondValue.toString()+ " GBP / " +thirdValue.toString()+ " USD"); }else { todayLabel = new JLabel("No internet connection"); } /** Create Label with actual currencies date from XML */ if(serverIsWorking) { DataFromXML.dataFromXML(); String dateXML = DataFromXML.getDateXML(); dateLabel = new JLabel("Last update: " +dateXML); dateLabel.setHorizontalAlignment(JLabel.RIGHT); dateLabel.setForeground(Color.GRAY); serverLabel = new JLabel("Data server: http://www.ecb.europa.eu/"); }else { dateLabel = new JLabel("Last update: ----"); dateLabel.setHorizontalAlignment(JLabel.RIGHT); dateLabel.setForeground(Color.GRAY); } /** serverStatusLabel */ JLabel serverStatusLabel = new JLabel("Data source: ecb.europa.eu"); serverStatusLabel.setForeground(Color.GRAY); /** Image icon ON-OFF data server */ BufferedImage onServerImage = null; if (serverIsWorking) { try { onServerImage = ImageIO.read(getClass().getResource("on.png")); Image onServerImageSmall = onServerImage.getScaledInstance(12, 12, java.awt.Image.SCALE_SMOOTH); onServerLabel = new JLabel(new ImageIcon(onServerImageSmall)); } catch (IOException e) { System.out.println("No File"); } } else { try { onServerImage = ImageIO.read(getClass().getResource("off.png")); Image onServerImageSmall = onServerImage.getScaledInstance(12, 12, java.awt.Image.SCALE_SMOOTH); onServerLabel = new JLabel(new ImageIcon(onServerImageSmall)); } catch (IOException e) { System.out.println("No File"); } } /** Add elements to panels */ c.insets = new Insets(borderOffset,0,0,borderOffset/2); c.gridx = 0; c.gridy = 0; c.gridwidth = 2; c.ipady = 15; mainPanel.add(titleLabel, c); c.gridx = 0; c.gridy = 1; c.gridwidth = 1; c.ipady = 0; mainPanel.add(userInput, c); c.gridx = 1; c.gridy = 1; mainPanel.add(resultField, c); c.gridx = 0; c.gridy = 2; leftRadioButtonsBoxPanel.add(radioButtonPLNto); leftRadioButtonsBoxPanel.add(radioButtonEURto); leftRadioButtonsBoxPanel.add(radioButtonGBPto); leftRadioButtonsBoxPanel.add(radioButtonUSDto); mainPanel.add(leftRadioButtonsBoxPanel, c); c.gridx = 1; c.gridy = 2; rightRadioButtonsBoxPanel.add(radioButtonPLN); rightRadioButtonsBoxPanel.add(radioButtonEUR); rightRadioButtonsBoxPanel.add(radioButtonGBP); rightRadioButtonsBoxPanel.add(radioButtonUSD); mainPanel.add(rightRadioButtonsBoxPanel, c); c.gridx = 0; c.gridy = 3; mainPanel.add(startButton, c); c.gridx = 1; c.gridy = 3; mainPanel.add(cleanButton, c); c.gridx = 0; c.gridy = 4; c.gridwidth = 2; c.fill = GridBagConstraints.HORIZONTAL; mainPanel.add(separatorH, c); c.gridx = 0; c.gridy = 5; c.fill = 0; // reset fill mainPanel.add(todayLabel, c); c.gridx = 0; c.gridy = 6; c.gridwidth = 2; //2 columns wide c.anchor = GridBagConstraints.LAST_LINE_END; c.insets = new Insets(6,0,0,5); mainPanel.add(dateLabel, c); c.gridx = 0; c.gridy = 7; c.gridwidth = 2; c.insets = new Insets(0,0,0,0); mainPanel.add(statusServerPanel, c); statusServerPanel.add(serverStatusLabel); statusServerPanel.add(onServerLabel); /** Activate frame and set window position */ mainFrame.add(mainPanel); mainFrame.setBounds(500, 300, 0, 0); mainFrame.setResizable(false); mainFrame.setVisible(true); mainFrame.pack(); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public class startButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent a) { /** Get user text */ userInputString = userInput.getText(); if(serverIsWorking) { if(isInteger(userInputString)) { /** Set text on result field */ resultField.setForeground(Color.black); resultField.setText(userInputString); /** Send MyFrame object to Logic class */ Logic logic = new Logic(); logic.logic(MyFrame.this, userInputString); }else if(isInteger(userInputString)==false) { resultField.setForeground(Color.gray); resultField.setText("Input digits"); } }else { resultField.setForeground(Color.gray); resultField.setText("-----"); } } } public class cleanButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent a) { /** Clear user text */ userInputString = ""; userInput.setText(""); resultField.setText(userInputString); } } /** Below method checks what user input * User can type number from 0 to 9 and '.' char * If user type above, function return true */ public static boolean isInteger(String str) { if (str == null) { return false; } int length = str.length(); if (length == 0) { return false; } int i = 0; if (str.charAt(0) == '-') { if (length == 1) { return false; } i = 1; } for (; i < length; i++) { char c = str.charAt(i); if ( (c < '0' || c > '9') && c != '.') { return false; } } return true; } @Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if(serverIsWorking) { if (key == KeyEvent.VK_ENTER) { /** Get user text */ userInputString = userInput.getText(); if(isInteger(userInputString)) { /** Set text on result field */ resultField.setForeground(Color.black); resultField.setText(userInputString); /** Send MyFrame object to Logic class */ Logic logic = new Logic(); logic.logic(MyFrame.this, userInputString); }else if(isInteger(userInputString)==false) { resultField.setForeground(Color.gray); resultField.setText("Input digits"); } } }else { resultField.setForeground(Color.gray); resultField.setText("-----"); } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } }
[ "@", "SuppressWarnings", "(", "\"", "serial", "\"", ")", "public", "class", "MyFrame", "extends", "JFrame", "implements", "KeyListener", "{", "private", "int", "borderOffset", "=", "5", ";", "private", "String", "userInputString", ";", "JTextField", "userInput", ";", "JTextField", "resultField", ";", "JRadioButton", "radioButtonPLNto", ";", "JRadioButton", "radioButtonEURto", ";", "JRadioButton", "radioButtonGBPto", ";", "JRadioButton", "radioButtonUSDto", ";", "JRadioButton", "radioButtonPLN", ";", "JRadioButton", "radioButtonEUR", ";", "JRadioButton", "radioButtonGBP", ";", "JRadioButton", "radioButtonUSD", ";", "JButton", "startButton", ";", "JButton", "cleanButton", ";", "JLabel", "dateLabel", ";", "JLabel", "serverLabel", ";", "JLabel", "todayLabel", ";", "JLabel", "onServerLabel", ";", "/** Check server on/off-line */", "boolean", "serverIsWorking", "=", "CurrencyConverterMainClass", ".", "getServerWorking", "(", ")", ";", "public", "MyFrame", "(", ")", "{", "/** app should look\n\t\t * --------------------------------------\n\t\t * |\t\t\t\t\t\t\t\t\t|\n\t\t * | amountInput\t\tresult\t\t\t|\t\n\t\t * | chooseCurrency1\tchooseCurrency2\t|\n\t\t * | countButton\t\t\t\t\t\t|\t\n\t\t * |\t\t\t\t\t\t\t\t\t|\n\t\t * --------------------------------------\n\t\t */", "/** Create main frame */", "JFrame", "mainFrame", "=", "new", "JFrame", "(", "\"", "Currency Converter", "\"", ")", ";", "/** Create panels and offsets from border*/", "JPanel", "mainPanel", "=", "new", "JPanel", "(", "new", "GridBagLayout", "(", ")", ")", ";", "GridBagConstraints", "c", "=", "new", "GridBagConstraints", "(", ")", ";", "mainPanel", ".", "setBorder", "(", "BorderFactory", ".", "createEmptyBorder", "(", "borderOffset", ",", "borderOffset", ",", "borderOffset", ",", "borderOffset", ")", ")", ";", "JPanel", "leftRadioButtonsBoxPanel", "=", "new", "JPanel", "(", ")", ";", "leftRadioButtonsBoxPanel", ".", "setLayout", "(", "(", "new", "BoxLayout", "(", "leftRadioButtonsBoxPanel", ",", "BoxLayout", ".", "PAGE_AXIS", ")", ")", ")", ";", "TitledBorder", "titledLeftRadioButtons", "=", "new", "TitledBorder", "(", "null", ",", "\"", "from", "\"", ",", "TitledBorder", ".", "CENTER", ",", "TitledBorder", ".", "TOP", ",", "null", ",", "Color", ".", "gray", ")", ";", "leftRadioButtonsBoxPanel", ".", "setBorder", "(", "titledLeftRadioButtons", ")", ";", "JPanel", "rightRadioButtonsBoxPanel", "=", "new", "JPanel", "(", ")", ";", "rightRadioButtonsBoxPanel", ".", "setLayout", "(", "(", "new", "BoxLayout", "(", "rightRadioButtonsBoxPanel", ",", "BoxLayout", ".", "PAGE_AXIS", ")", ")", ")", ";", "TitledBorder", "titledRightRadioButtons", "=", "new", "TitledBorder", "(", "null", ",", "\"", "to", "\"", ",", "TitledBorder", ".", "CENTER", ",", "TitledBorder", ".", "TOP", ",", "null", ",", "Color", ".", "gray", ")", ";", "rightRadioButtonsBoxPanel", ".", "setBorder", "(", "titledRightRadioButtons", ")", ";", "JPanel", "statusServerPanel", "=", "new", "JPanel", "(", ")", ";", "/** Create TextFields - userInput of value */", "userInput", "=", "new", "JTextField", "(", ")", ";", "userInput", ".", "setHorizontalAlignment", "(", "JTextField", ".", "RIGHT", ")", ";", "userInput", ".", "setPreferredSize", "(", "new", "Dimension", "(", "100", ",", "24", ")", ")", ";", "userInput", ".", "setFocusable", "(", "true", ")", ";", "userInput", ".", "addKeyListener", "(", "this", ")", ";", "resultField", "=", "new", "JTextField", "(", ")", ";", "resultField", ".", "setHorizontalAlignment", "(", "JTextField", ".", "LEFT", ")", ";", "resultField", ".", "setPreferredSize", "(", "new", "Dimension", "(", "100", ",", "24", ")", ")", ";", "resultField", ".", "setEditable", "(", "false", ")", ";", "/** Create LEFT list of currency comodities */", "radioButtonPLNto", "=", "new", "JRadioButton", "(", "\"", "PLN", "\"", ")", ";", "radioButtonPLNto", ".", "setSelected", "(", "true", ")", ";", "radioButtonEURto", "=", "new", "JRadioButton", "(", "\"", "EUR", "\"", ")", ";", "radioButtonGBPto", "=", "new", "JRadioButton", "(", "\"", "GBP", "\"", ")", ";", "radioButtonUSDto", "=", "new", "JRadioButton", "(", "\"", "USD", "\"", ")", ";", "ButtonGroup", "buttonGroupLeft", "=", "new", "ButtonGroup", "(", ")", ";", "buttonGroupLeft", ".", "add", "(", "radioButtonPLNto", ")", ";", "buttonGroupLeft", ".", "add", "(", "radioButtonEURto", ")", ";", "buttonGroupLeft", ".", "add", "(", "radioButtonGBPto", ")", ";", "buttonGroupLeft", ".", "add", "(", "radioButtonUSDto", ")", ";", "/** Create RIGHT list of currency comodities */", "radioButtonPLN", "=", "new", "JRadioButton", "(", "\"", "PLN", "\"", ")", ";", "radioButtonEUR", "=", "new", "JRadioButton", "(", "\"", "EUR", "\"", ")", ";", "radioButtonEUR", ".", "setSelected", "(", "true", ")", ";", "radioButtonGBP", "=", "new", "JRadioButton", "(", "\"", "GBP", "\"", ")", ";", "radioButtonUSD", "=", "new", "JRadioButton", "(", "\"", "USD", "\"", ")", ";", "ButtonGroup", "buttonGroupRight", "=", "new", "ButtonGroup", "(", ")", ";", "buttonGroupRight", ".", "add", "(", "radioButtonPLN", ")", ";", "buttonGroupRight", ".", "add", "(", "radioButtonEUR", ")", ";", "buttonGroupRight", ".", "add", "(", "radioButtonGBP", ")", ";", "buttonGroupRight", ".", "add", "(", "radioButtonUSD", ")", ";", "/** Create bottom GO and CLEAN button */", "startButton", "=", "new", "JButton", "(", "\"", "Calculate", "\"", ")", ";", "startButton", ".", "addActionListener", "(", "new", "startButtonListener", "(", ")", ")", ";", "cleanButton", "=", "new", "JButton", "(", "\"", "Clear", "\"", ")", ";", "cleanButton", ".", "addActionListener", "(", "new", "cleanButtonListener", "(", ")", ")", ";", "/** Create Separator */", "JSeparator", "separatorH", "=", "new", "JSeparator", "(", "JSeparator", ".", "HORIZONTAL", ")", ";", "separatorH", ".", "setPreferredSize", "(", "new", "Dimension", "(", "2", ",", "2", ")", ")", ";", "/** Title */", "JLabel", "titleLabel", "=", "new", "JLabel", "(", "\"", "Currency Converter", "\"", ")", ";", "titleLabel", ".", "setFont", "(", "new", "Font", "(", "null", ",", "Font", ".", "PLAIN", ",", "20", ")", ")", ";", "titleLabel", ".", "setForeground", "(", "Color", ".", "GRAY", ")", ";", "/** Label with todays currencies */", "if", "(", "serverIsWorking", ")", "{", "TodayValues", "today", "=", "new", "TodayValues", "(", ")", ";", "today", ".", "getTodayValues", "(", ")", ";", "BigDecimal", "oneValue", "=", "today", ".", "getOneValue", "(", ")", ";", "BigDecimal", "secondValue", "=", "today", ".", "getSecondValue", "(", ")", ";", "BigDecimal", "thirdValue", "=", "today", ".", "getThirdValue", "(", ")", ";", "todayLabel", "=", "new", "JLabel", "(", "\"", "1 PLN = ", "\"", "+", "oneValue", ".", "toString", "(", ")", "+", "\"", " EUR / ", "\"", "+", "secondValue", ".", "toString", "(", ")", "+", "\"", " GBP / ", "\"", "+", "thirdValue", ".", "toString", "(", ")", "+", "\"", " USD", "\"", ")", ";", "}", "else", "{", "todayLabel", "=", "new", "JLabel", "(", "\"", "No internet connection", "\"", ")", ";", "}", "/** Create Label with actual currencies date from XML */", "if", "(", "serverIsWorking", ")", "{", "DataFromXML", ".", "dataFromXML", "(", ")", ";", "String", "dateXML", "=", "DataFromXML", ".", "getDateXML", "(", ")", ";", "dateLabel", "=", "new", "JLabel", "(", "\"", "Last update: ", "\"", "+", "dateXML", ")", ";", "dateLabel", ".", "setHorizontalAlignment", "(", "JLabel", ".", "RIGHT", ")", ";", "dateLabel", ".", "setForeground", "(", "Color", ".", "GRAY", ")", ";", "serverLabel", "=", "new", "JLabel", "(", "\"", "Data server: http://www.ecb.europa.eu/", "\"", ")", ";", "}", "else", "{", "dateLabel", "=", "new", "JLabel", "(", "\"", "Last update: ----", "\"", ")", ";", "dateLabel", ".", "setHorizontalAlignment", "(", "JLabel", ".", "RIGHT", ")", ";", "dateLabel", ".", "setForeground", "(", "Color", ".", "GRAY", ")", ";", "}", "/** serverStatusLabel */", "JLabel", "serverStatusLabel", "=", "new", "JLabel", "(", "\"", "Data source: ecb.europa.eu", "\"", ")", ";", "serverStatusLabel", ".", "setForeground", "(", "Color", ".", "GRAY", ")", ";", "/** Image icon ON-OFF data server */", "BufferedImage", "onServerImage", "=", "null", ";", "if", "(", "serverIsWorking", ")", "{", "try", "{", "onServerImage", "=", "ImageIO", ".", "read", "(", "getClass", "(", ")", ".", "getResource", "(", "\"", "on.png", "\"", ")", ")", ";", "Image", "onServerImageSmall", "=", "onServerImage", ".", "getScaledInstance", "(", "12", ",", "12", ",", "java", ".", "awt", ".", "Image", ".", "SCALE_SMOOTH", ")", ";", "onServerLabel", "=", "new", "JLabel", "(", "new", "ImageIcon", "(", "onServerImageSmall", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "No File", "\"", ")", ";", "}", "}", "else", "{", "try", "{", "onServerImage", "=", "ImageIO", ".", "read", "(", "getClass", "(", ")", ".", "getResource", "(", "\"", "off.png", "\"", ")", ")", ";", "Image", "onServerImageSmall", "=", "onServerImage", ".", "getScaledInstance", "(", "12", ",", "12", ",", "java", ".", "awt", ".", "Image", ".", "SCALE_SMOOTH", ")", ";", "onServerLabel", "=", "new", "JLabel", "(", "new", "ImageIcon", "(", "onServerImageSmall", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "No File", "\"", ")", ";", "}", "}", "/** Add elements to panels */", "c", ".", "insets", "=", "new", "Insets", "(", "borderOffset", ",", "0", ",", "0", ",", "borderOffset", "/", "2", ")", ";", "c", ".", "gridx", "=", "0", ";", "c", ".", "gridy", "=", "0", ";", "c", ".", "gridwidth", "=", "2", ";", "c", ".", "ipady", "=", "15", ";", "mainPanel", ".", "add", "(", "titleLabel", ",", "c", ")", ";", "c", ".", "gridx", "=", "0", ";", "c", ".", "gridy", "=", "1", ";", "c", ".", "gridwidth", "=", "1", ";", "c", ".", "ipady", "=", "0", ";", "mainPanel", ".", "add", "(", "userInput", ",", "c", ")", ";", "c", ".", "gridx", "=", "1", ";", "c", ".", "gridy", "=", "1", ";", "mainPanel", ".", "add", "(", "resultField", ",", "c", ")", ";", "c", ".", "gridx", "=", "0", ";", "c", ".", "gridy", "=", "2", ";", "leftRadioButtonsBoxPanel", ".", "add", "(", "radioButtonPLNto", ")", ";", "leftRadioButtonsBoxPanel", ".", "add", "(", "radioButtonEURto", ")", ";", "leftRadioButtonsBoxPanel", ".", "add", "(", "radioButtonGBPto", ")", ";", "leftRadioButtonsBoxPanel", ".", "add", "(", "radioButtonUSDto", ")", ";", "mainPanel", ".", "add", "(", "leftRadioButtonsBoxPanel", ",", "c", ")", ";", "c", ".", "gridx", "=", "1", ";", "c", ".", "gridy", "=", "2", ";", "rightRadioButtonsBoxPanel", ".", "add", "(", "radioButtonPLN", ")", ";", "rightRadioButtonsBoxPanel", ".", "add", "(", "radioButtonEUR", ")", ";", "rightRadioButtonsBoxPanel", ".", "add", "(", "radioButtonGBP", ")", ";", "rightRadioButtonsBoxPanel", ".", "add", "(", "radioButtonUSD", ")", ";", "mainPanel", ".", "add", "(", "rightRadioButtonsBoxPanel", ",", "c", ")", ";", "c", ".", "gridx", "=", "0", ";", "c", ".", "gridy", "=", "3", ";", "mainPanel", ".", "add", "(", "startButton", ",", "c", ")", ";", "c", ".", "gridx", "=", "1", ";", "c", ".", "gridy", "=", "3", ";", "mainPanel", ".", "add", "(", "cleanButton", ",", "c", ")", ";", "c", ".", "gridx", "=", "0", ";", "c", ".", "gridy", "=", "4", ";", "c", ".", "gridwidth", "=", "2", ";", "c", ".", "fill", "=", "GridBagConstraints", ".", "HORIZONTAL", ";", "mainPanel", ".", "add", "(", "separatorH", ",", "c", ")", ";", "c", ".", "gridx", "=", "0", ";", "c", ".", "gridy", "=", "5", ";", "c", ".", "fill", "=", "0", ";", "mainPanel", ".", "add", "(", "todayLabel", ",", "c", ")", ";", "c", ".", "gridx", "=", "0", ";", "c", ".", "gridy", "=", "6", ";", "c", ".", "gridwidth", "=", "2", ";", "c", ".", "anchor", "=", "GridBagConstraints", ".", "LAST_LINE_END", ";", "c", ".", "insets", "=", "new", "Insets", "(", "6", ",", "0", ",", "0", ",", "5", ")", ";", "mainPanel", ".", "add", "(", "dateLabel", ",", "c", ")", ";", "c", ".", "gridx", "=", "0", ";", "c", ".", "gridy", "=", "7", ";", "c", ".", "gridwidth", "=", "2", ";", "c", ".", "insets", "=", "new", "Insets", "(", "0", ",", "0", ",", "0", ",", "0", ")", ";", "mainPanel", ".", "add", "(", "statusServerPanel", ",", "c", ")", ";", "statusServerPanel", ".", "add", "(", "serverStatusLabel", ")", ";", "statusServerPanel", ".", "add", "(", "onServerLabel", ")", ";", "/** Activate frame and set window position */", "mainFrame", ".", "add", "(", "mainPanel", ")", ";", "mainFrame", ".", "setBounds", "(", "500", ",", "300", ",", "0", ",", "0", ")", ";", "mainFrame", ".", "setResizable", "(", "false", ")", ";", "mainFrame", ".", "setVisible", "(", "true", ")", ";", "mainFrame", ".", "pack", "(", ")", ";", "mainFrame", ".", "setDefaultCloseOperation", "(", "JFrame", ".", "EXIT_ON_CLOSE", ")", ";", "}", "public", "class", "startButtonListener", "implements", "ActionListener", "{", "@", "Override", "public", "void", "actionPerformed", "(", "ActionEvent", "a", ")", "{", "/** Get user text */", "userInputString", "=", "userInput", ".", "getText", "(", ")", ";", "if", "(", "serverIsWorking", ")", "{", "if", "(", "isInteger", "(", "userInputString", ")", ")", "{", "/** Set text on result field */", "resultField", ".", "setForeground", "(", "Color", ".", "black", ")", ";", "resultField", ".", "setText", "(", "userInputString", ")", ";", "/** Send MyFrame object to Logic class */", "Logic", "logic", "=", "new", "Logic", "(", ")", ";", "logic", ".", "logic", "(", "MyFrame", ".", "this", ",", "userInputString", ")", ";", "}", "else", "if", "(", "isInteger", "(", "userInputString", ")", "==", "false", ")", "{", "resultField", ".", "setForeground", "(", "Color", ".", "gray", ")", ";", "resultField", ".", "setText", "(", "\"", "Input digits", "\"", ")", ";", "}", "}", "else", "{", "resultField", ".", "setForeground", "(", "Color", ".", "gray", ")", ";", "resultField", ".", "setText", "(", "\"", "-----", "\"", ")", ";", "}", "}", "}", "public", "class", "cleanButtonListener", "implements", "ActionListener", "{", "@", "Override", "public", "void", "actionPerformed", "(", "ActionEvent", "a", ")", "{", "/** Clear user text */", "userInputString", "=", "\"", "\"", ";", "userInput", ".", "setText", "(", "\"", "\"", ")", ";", "resultField", ".", "setText", "(", "userInputString", ")", ";", "}", "}", "/** Below method checks what user input\n\t * User can type number from 0 to 9 and '.' char\n\t * If user type above, function return true\n\t */", "public", "static", "boolean", "isInteger", "(", "String", "str", ")", "{", "if", "(", "str", "==", "null", ")", "{", "return", "false", ";", "}", "int", "length", "=", "str", ".", "length", "(", ")", ";", "if", "(", "length", "==", "0", ")", "{", "return", "false", ";", "}", "int", "i", "=", "0", ";", "if", "(", "str", ".", "charAt", "(", "0", ")", "==", "'-'", ")", "{", "if", "(", "length", "==", "1", ")", "{", "return", "false", ";", "}", "i", "=", "1", ";", "}", "for", "(", ";", "i", "<", "length", ";", "i", "++", ")", "{", "char", "c", "=", "str", ".", "charAt", "(", "i", ")", ";", "if", "(", "(", "c", "<", "'0'", "||", "c", ">", "'9'", ")", "&&", "c", "!=", "'.'", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "@", "Override", "public", "void", "keyPressed", "(", "KeyEvent", "e", ")", "{", "int", "key", "=", "e", ".", "getKeyCode", "(", ")", ";", "if", "(", "serverIsWorking", ")", "{", "if", "(", "key", "==", "KeyEvent", ".", "VK_ENTER", ")", "{", "/** Get user text */", "userInputString", "=", "userInput", ".", "getText", "(", ")", ";", "if", "(", "isInteger", "(", "userInputString", ")", ")", "{", "/** Set text on result field */", "resultField", ".", "setForeground", "(", "Color", ".", "black", ")", ";", "resultField", ".", "setText", "(", "userInputString", ")", ";", "/** Send MyFrame object to Logic class */", "Logic", "logic", "=", "new", "Logic", "(", ")", ";", "logic", ".", "logic", "(", "MyFrame", ".", "this", ",", "userInputString", ")", ";", "}", "else", "if", "(", "isInteger", "(", "userInputString", ")", "==", "false", ")", "{", "resultField", ".", "setForeground", "(", "Color", ".", "gray", ")", ";", "resultField", ".", "setText", "(", "\"", "Input digits", "\"", ")", ";", "}", "}", "}", "else", "{", "resultField", ".", "setForeground", "(", "Color", ".", "gray", ")", ";", "resultField", ".", "setText", "(", "\"", "-----", "\"", ")", ";", "}", "}", "@", "Override", "public", "void", "keyReleased", "(", "KeyEvent", "e", ")", "{", "}", "@", "Override", "public", "void", "keyTyped", "(", "KeyEvent", "e", ")", "{", "}", "}" ]
Class with GUI
[ "Class", "with", "GUI" ]
[ "// up, left, down, right", "// reset fill", "//2 columns wide" ]
[ { "param": "JFrame", "type": null }, { "param": "KeyListener", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "JFrame", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "KeyListener", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f59749bd4a92d36afa473b61c5d26c4df31829
manxisuo/java-image-scaling
src/test/java/com/mortennobel/imagescaling/Issue10.java
[ "BSD-3-Clause" ]
Java
Issue10
/** * Problem when scaling 1 channel (Grayscale) image */
Problem when scaling 1 channel (Grayscale) image
[ "Problem", "when", "scaling", "1", "channel", "(", "Grayscale", ")", "image" ]
public class Issue10 extends TestCase { /** * Test that the library can scale a grayscale image * @throws Exception should not occur */ public void testIssue10() throws Exception { BufferedImage image2D = ImageIO.read(getClass().getResourceAsStream("test_issue10.jpg")); DimensionConstrain dc = DimensionConstrain.createAbsolutionDimension(50,50); ResampleOp resampleOp = new ResampleOp (dc); BufferedImage rescaledTomato = resampleOp.filter(image2D, null); } /** * Test that the library throws an exception if a destination image is not compatible with source img * @throws Exception should not occur */ public void testIssue10Exception() throws Exception { RuntimeException re = null; try{ BufferedImage image2D = ImageIO.read(getClass().getResourceAsStream("test_issue10.jpg")); DimensionConstrain dc = DimensionConstrain.createAbsolutionDimension(50,50); BufferedImage out = new BufferedImage(50,50, BufferedImage.TYPE_INT_ARGB); ResampleOp resampleOp = new ResampleOp (dc); BufferedImage rescaledTomato = resampleOp.filter(image2D, out); } catch (RuntimeException e){ re = e; } assertNotNull("ISL should throw an exception since out image is not compatible", re); } }
[ "public", "class", "Issue10", "extends", "TestCase", "{", "/**\n\t * Test that the library can scale a grayscale image\n\t * @throws Exception should not occur\n\t */", "public", "void", "testIssue10", "(", ")", "throws", "Exception", "{", "BufferedImage", "image2D", "=", "ImageIO", ".", "read", "(", "getClass", "(", ")", ".", "getResourceAsStream", "(", "\"", "test_issue10.jpg", "\"", ")", ")", ";", "DimensionConstrain", "dc", "=", "DimensionConstrain", ".", "createAbsolutionDimension", "(", "50", ",", "50", ")", ";", "ResampleOp", "resampleOp", "=", "new", "ResampleOp", "(", "dc", ")", ";", "BufferedImage", "rescaledTomato", "=", "resampleOp", ".", "filter", "(", "image2D", ",", "null", ")", ";", "}", "/**\n\t * Test that the library throws an exception if a destination image is not compatible with source img\n\t * @throws Exception should not occur\n\t */", "public", "void", "testIssue10Exception", "(", ")", "throws", "Exception", "{", "RuntimeException", "re", "=", "null", ";", "try", "{", "BufferedImage", "image2D", "=", "ImageIO", ".", "read", "(", "getClass", "(", ")", ".", "getResourceAsStream", "(", "\"", "test_issue10.jpg", "\"", ")", ")", ";", "DimensionConstrain", "dc", "=", "DimensionConstrain", ".", "createAbsolutionDimension", "(", "50", ",", "50", ")", ";", "BufferedImage", "out", "=", "new", "BufferedImage", "(", "50", ",", "50", ",", "BufferedImage", ".", "TYPE_INT_ARGB", ")", ";", "ResampleOp", "resampleOp", "=", "new", "ResampleOp", "(", "dc", ")", ";", "BufferedImage", "rescaledTomato", "=", "resampleOp", ".", "filter", "(", "image2D", ",", "out", ")", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "re", "=", "e", ";", "}", "assertNotNull", "(", "\"", "ISL should throw an exception since out image is not compatible", "\"", ",", "re", ")", ";", "}", "}" ]
Problem when scaling 1 channel (Grayscale) image
[ "Problem", "when", "scaling", "1", "channel", "(", "Grayscale", ")", "image" ]
[]
[ { "param": "TestCase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "TestCase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f8757e36b951bdacffe9e2834137c4bd9d59fe
mlehotsky13/camunda-bpm-platform
model-api/cmmn-model/src/main/java/org/camunda/bpm/model/cmmn/impl/instance/AssociationImpl.java
[ "Apache-2.0" ]
Java
AssociationImpl
/** * @author Roman Smirnov * */
@author Roman Smirnov
[ "@author", "Roman", "Smirnov" ]
public class AssociationImpl extends ArtifactImpl implements Association { protected static AttributeReference<CmmnElement> sourceRefAttribute; protected static AttributeReference<CmmnElement> targetRefAttribute; protected static Attribute<AssociationDirection> associationDirectionAttribute; public AssociationImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public CmmnElement getSource() { return sourceRefAttribute.getReferenceTargetElement(this); } public void setSource(CmmnElement source) { sourceRefAttribute.setReferenceTargetElement(this, source); } public CmmnElement getTarget() { return targetRefAttribute.getReferenceTargetElement(this); } public void setTarget(CmmnElement target) { targetRefAttribute.setReferenceTargetElement(this, target); } public AssociationDirection getAssociationDirection() { return associationDirectionAttribute.getValue(this); } public void setAssociationDirection(AssociationDirection associationDirection) { associationDirectionAttribute.setValue(this, associationDirection); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Association.class, CMMN_ELEMENT_ASSOCIATION) .namespaceUri(CMMN11_NS) .extendsType(Artifact.class) .instanceProvider(new ModelTypeInstanceProvider<Association>() { public Association newInstance(ModelTypeInstanceContext instanceContext) { return new AssociationImpl(instanceContext); } }); sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF) .idAttributeReference(CmmnElement.class) .build(); targetRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_REF) .idAttributeReference(CmmnElement.class) .build(); associationDirectionAttribute = typeBuilder.enumAttribute(CMMN_ATTRIBUTE_ASSOCIATION_DIRECTION, AssociationDirection.class) .build(); typeBuilder.build(); } }
[ "public", "class", "AssociationImpl", "extends", "ArtifactImpl", "implements", "Association", "{", "protected", "static", "AttributeReference", "<", "CmmnElement", ">", "sourceRefAttribute", ";", "protected", "static", "AttributeReference", "<", "CmmnElement", ">", "targetRefAttribute", ";", "protected", "static", "Attribute", "<", "AssociationDirection", ">", "associationDirectionAttribute", ";", "public", "AssociationImpl", "(", "ModelTypeInstanceContext", "instanceContext", ")", "{", "super", "(", "instanceContext", ")", ";", "}", "public", "CmmnElement", "getSource", "(", ")", "{", "return", "sourceRefAttribute", ".", "getReferenceTargetElement", "(", "this", ")", ";", "}", "public", "void", "setSource", "(", "CmmnElement", "source", ")", "{", "sourceRefAttribute", ".", "setReferenceTargetElement", "(", "this", ",", "source", ")", ";", "}", "public", "CmmnElement", "getTarget", "(", ")", "{", "return", "targetRefAttribute", ".", "getReferenceTargetElement", "(", "this", ")", ";", "}", "public", "void", "setTarget", "(", "CmmnElement", "target", ")", "{", "targetRefAttribute", ".", "setReferenceTargetElement", "(", "this", ",", "target", ")", ";", "}", "public", "AssociationDirection", "getAssociationDirection", "(", ")", "{", "return", "associationDirectionAttribute", ".", "getValue", "(", "this", ")", ";", "}", "public", "void", "setAssociationDirection", "(", "AssociationDirection", "associationDirection", ")", "{", "associationDirectionAttribute", ".", "setValue", "(", "this", ",", "associationDirection", ")", ";", "}", "public", "static", "void", "registerType", "(", "ModelBuilder", "modelBuilder", ")", "{", "ModelElementTypeBuilder", "typeBuilder", "=", "modelBuilder", ".", "defineType", "(", "Association", ".", "class", ",", "CMMN_ELEMENT_ASSOCIATION", ")", ".", "namespaceUri", "(", "CMMN11_NS", ")", ".", "extendsType", "(", "Artifact", ".", "class", ")", ".", "instanceProvider", "(", "new", "ModelTypeInstanceProvider", "<", "Association", ">", "(", ")", "{", "public", "Association", "newInstance", "(", "ModelTypeInstanceContext", "instanceContext", ")", "{", "return", "new", "AssociationImpl", "(", "instanceContext", ")", ";", "}", "}", ")", ";", "sourceRefAttribute", "=", "typeBuilder", ".", "stringAttribute", "(", "CMMN_ATTRIBUTE_SOURCE_REF", ")", ".", "idAttributeReference", "(", "CmmnElement", ".", "class", ")", ".", "build", "(", ")", ";", "targetRefAttribute", "=", "typeBuilder", ".", "stringAttribute", "(", "CMMN_ATTRIBUTE_TARGET_REF", ")", ".", "idAttributeReference", "(", "CmmnElement", ".", "class", ")", ".", "build", "(", ")", ";", "associationDirectionAttribute", "=", "typeBuilder", ".", "enumAttribute", "(", "CMMN_ATTRIBUTE_ASSOCIATION_DIRECTION", ",", "AssociationDirection", ".", "class", ")", ".", "build", "(", ")", ";", "typeBuilder", ".", "build", "(", ")", ";", "}", "}" ]
@author Roman Smirnov
[ "@author", "Roman", "Smirnov" ]
[]
[ { "param": "ArtifactImpl", "type": null }, { "param": "Association", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ArtifactImpl", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "Association", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f8f49d4b5c72bc449a3bf13ccec8bf5b412142
uOOOO/mosby
sample-mvi/src/main/java/com/hannesdorfmann/mosby3/sample/mvi/view/home/PartialStateChanges.java
[ "Apache-2.0" ]
Java
FirstPageLoading
/** * Indicates that the first page is loading */
Indicates that the first page is loading
[ "Indicates", "that", "the", "first", "page", "is", "loading" ]
final class FirstPageLoading implements PartialStateChanges { @Override public String toString() { return "FirstPageLoadingState{}"; } }
[ "final", "class", "FirstPageLoading", "implements", "PartialStateChanges", "{", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "FirstPageLoadingState{}", "\"", ";", "}", "}" ]
Indicates that the first page is loading
[ "Indicates", "that", "the", "first", "page", "is", "loading" ]
[]
[ { "param": "PartialStateChanges", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PartialStateChanges", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f8f49d4b5c72bc449a3bf13ccec8bf5b412142
uOOOO/mosby
sample-mvi/src/main/java/com/hannesdorfmann/mosby3/sample/mvi/view/home/PartialStateChanges.java
[ "Apache-2.0" ]
Java
FirstPageError
/** * Indicates that an error has occurred while loading the first page */
Indicates that an error has occurred while loading the first page
[ "Indicates", "that", "an", "error", "has", "occurred", "while", "loading", "the", "first", "page" ]
final class FirstPageError implements PartialStateChanges { private final Throwable error; public FirstPageError(Throwable error) { this.error = error; } public Throwable getError() { return error; } @Override public String toString() { return "FirstPageErrorState{" + "error=" + error + '}'; } }
[ "final", "class", "FirstPageError", "implements", "PartialStateChanges", "{", "private", "final", "Throwable", "error", ";", "public", "FirstPageError", "(", "Throwable", "error", ")", "{", "this", ".", "error", "=", "error", ";", "}", "public", "Throwable", "getError", "(", ")", "{", "return", "error", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "FirstPageErrorState{", "\"", "+", "\"", "error=", "\"", "+", "error", "+", "'}'", ";", "}", "}" ]
Indicates that an error has occurred while loading the first page
[ "Indicates", "that", "an", "error", "has", "occurred", "while", "loading", "the", "first", "page" ]
[]
[ { "param": "PartialStateChanges", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PartialStateChanges", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f8f49d4b5c72bc449a3bf13ccec8bf5b412142
uOOOO/mosby
sample-mvi/src/main/java/com/hannesdorfmann/mosby3/sample/mvi/view/home/PartialStateChanges.java
[ "Apache-2.0" ]
Java
FirstPageLoaded
/** * Indicates that the first page data has been loaded successfully */
Indicates that the first page data has been loaded successfully
[ "Indicates", "that", "the", "first", "page", "data", "has", "been", "loaded", "successfully" ]
final class FirstPageLoaded implements PartialStateChanges { private final List<FeedItem> data; public FirstPageLoaded(List<FeedItem> data) { this.data = data; } public List<FeedItem> getData() { return data; } }
[ "final", "class", "FirstPageLoaded", "implements", "PartialStateChanges", "{", "private", "final", "List", "<", "FeedItem", ">", "data", ";", "public", "FirstPageLoaded", "(", "List", "<", "FeedItem", ">", "data", ")", "{", "this", ".", "data", "=", "data", ";", "}", "public", "List", "<", "FeedItem", ">", "getData", "(", ")", "{", "return", "data", ";", "}", "}" ]
Indicates that the first page data has been loaded successfully
[ "Indicates", "that", "the", "first", "page", "data", "has", "been", "loaded", "successfully" ]
[]
[ { "param": "PartialStateChanges", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PartialStateChanges", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f8f49d4b5c72bc449a3bf13ccec8bf5b412142
uOOOO/mosby
sample-mvi/src/main/java/com/hannesdorfmann/mosby3/sample/mvi/view/home/PartialStateChanges.java
[ "Apache-2.0" ]
Java
NextPageLoaded
/** * Next Page has been loaded successfully */
Next Page has been loaded successfully
[ "Next", "Page", "has", "been", "loaded", "successfully" ]
final class NextPageLoaded implements PartialStateChanges { private final List<FeedItem> data; public NextPageLoaded(List<FeedItem> data) { this.data = data; } public List<FeedItem> getData() { return data; } }
[ "final", "class", "NextPageLoaded", "implements", "PartialStateChanges", "{", "private", "final", "List", "<", "FeedItem", ">", "data", ";", "public", "NextPageLoaded", "(", "List", "<", "FeedItem", ">", "data", ")", "{", "this", ".", "data", "=", "data", ";", "}", "public", "List", "<", "FeedItem", ">", "getData", "(", ")", "{", "return", "data", ";", "}", "}" ]
Next Page has been loaded successfully
[ "Next", "Page", "has", "been", "loaded", "successfully" ]
[]
[ { "param": "PartialStateChanges", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PartialStateChanges", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f8f49d4b5c72bc449a3bf13ccec8bf5b412142
uOOOO/mosby
sample-mvi/src/main/java/com/hannesdorfmann/mosby3/sample/mvi/view/home/PartialStateChanges.java
[ "Apache-2.0" ]
Java
NexPageLoadingError
/** * Error while loading new page */
Error while loading new page
[ "Error", "while", "loading", "new", "page" ]
final class NexPageLoadingError implements PartialStateChanges { private final Throwable error; public NexPageLoadingError(Throwable error) { this.error = error; } public Throwable getError() { return error; } }
[ "final", "class", "NexPageLoadingError", "implements", "PartialStateChanges", "{", "private", "final", "Throwable", "error", ";", "public", "NexPageLoadingError", "(", "Throwable", "error", ")", "{", "this", ".", "error", "=", "error", ";", "}", "public", "Throwable", "getError", "(", ")", "{", "return", "error", ";", "}", "}" ]
Error while loading new page
[ "Error", "while", "loading", "new", "page" ]
[]
[ { "param": "PartialStateChanges", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PartialStateChanges", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f8f49d4b5c72bc449a3bf13ccec8bf5b412142
uOOOO/mosby
sample-mvi/src/main/java/com/hannesdorfmann/mosby3/sample/mvi/view/home/PartialStateChanges.java
[ "Apache-2.0" ]
Java
PullToRefeshLoadingError
/** * Indicates that an error while loading the newest items via pull to refresh has occurred */
Indicates that an error while loading the newest items via pull to refresh has occurred
[ "Indicates", "that", "an", "error", "while", "loading", "the", "newest", "items", "via", "pull", "to", "refresh", "has", "occurred" ]
final class PullToRefeshLoadingError implements PartialStateChanges { private final Throwable error; public PullToRefeshLoadingError(Throwable error) { this.error = error; } public Throwable getError() { return error; } }
[ "final", "class", "PullToRefeshLoadingError", "implements", "PartialStateChanges", "{", "private", "final", "Throwable", "error", ";", "public", "PullToRefeshLoadingError", "(", "Throwable", "error", ")", "{", "this", ".", "error", "=", "error", ";", "}", "public", "Throwable", "getError", "(", ")", "{", "return", "error", ";", "}", "}" ]
Indicates that an error while loading the newest items via pull to refresh has occurred
[ "Indicates", "that", "an", "error", "while", "loading", "the", "newest", "items", "via", "pull", "to", "refresh", "has", "occurred" ]
[]
[ { "param": "PartialStateChanges", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PartialStateChanges", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f8f49d4b5c72bc449a3bf13ccec8bf5b412142
uOOOO/mosby
sample-mvi/src/main/java/com/hannesdorfmann/mosby3/sample/mvi/view/home/PartialStateChanges.java
[ "Apache-2.0" ]
Java
PullToRefreshLoaded
/** * Indicates that data has been loaded successfully over pull-to-refresh */
Indicates that data has been loaded successfully over pull-to-refresh
[ "Indicates", "that", "data", "has", "been", "loaded", "successfully", "over", "pull", "-", "to", "-", "refresh" ]
final class PullToRefreshLoaded implements PartialStateChanges { private final List<FeedItem> data; public PullToRefreshLoaded(List<FeedItem> data) { this.data = data; } public List<FeedItem> getData() { return data; } }
[ "final", "class", "PullToRefreshLoaded", "implements", "PartialStateChanges", "{", "private", "final", "List", "<", "FeedItem", ">", "data", ";", "public", "PullToRefreshLoaded", "(", "List", "<", "FeedItem", ">", "data", ")", "{", "this", ".", "data", "=", "data", ";", "}", "public", "List", "<", "FeedItem", ">", "getData", "(", ")", "{", "return", "data", ";", "}", "}" ]
Indicates that data has been loaded successfully over pull-to-refresh
[ "Indicates", "that", "data", "has", "been", "loaded", "successfully", "over", "pull", "-", "to", "-", "refresh" ]
[]
[ { "param": "PartialStateChanges", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PartialStateChanges", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f8f49d4b5c72bc449a3bf13ccec8bf5b412142
uOOOO/mosby
sample-mvi/src/main/java/com/hannesdorfmann/mosby3/sample/mvi/view/home/PartialStateChanges.java
[ "Apache-2.0" ]
Java
ProductsOfCategoryLoading
/** * Loading all Products of a given category has been started */
Loading all Products of a given category has been started
[ "Loading", "all", "Products", "of", "a", "given", "category", "has", "been", "started" ]
final class ProductsOfCategoryLoading implements PartialStateChanges { private final String categoryName; public ProductsOfCategoryLoading(String categoryName) { this.categoryName = categoryName; } public String getCategoryName() { return categoryName; } }
[ "final", "class", "ProductsOfCategoryLoading", "implements", "PartialStateChanges", "{", "private", "final", "String", "categoryName", ";", "public", "ProductsOfCategoryLoading", "(", "String", "categoryName", ")", "{", "this", ".", "categoryName", "=", "categoryName", ";", "}", "public", "String", "getCategoryName", "(", ")", "{", "return", "categoryName", ";", "}", "}" ]
Loading all Products of a given category has been started
[ "Loading", "all", "Products", "of", "a", "given", "category", "has", "been", "started" ]
[]
[ { "param": "PartialStateChanges", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PartialStateChanges", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f8f49d4b5c72bc449a3bf13ccec8bf5b412142
uOOOO/mosby
sample-mvi/src/main/java/com/hannesdorfmann/mosby3/sample/mvi/view/home/PartialStateChanges.java
[ "Apache-2.0" ]
Java
ProductsOfCategoryLoadingError
/** * An error while loading all products has been occurred */
An error while loading all products has been occurred
[ "An", "error", "while", "loading", "all", "products", "has", "been", "occurred" ]
final class ProductsOfCategoryLoadingError implements PartialStateChanges { private final String categoryName; private final Throwable error; public ProductsOfCategoryLoadingError(String categoryName, Throwable error) { this.categoryName = categoryName; this.error = error; } public String getCategoryName() { return categoryName; } public Throwable getError() { return error; } }
[ "final", "class", "ProductsOfCategoryLoadingError", "implements", "PartialStateChanges", "{", "private", "final", "String", "categoryName", ";", "private", "final", "Throwable", "error", ";", "public", "ProductsOfCategoryLoadingError", "(", "String", "categoryName", ",", "Throwable", "error", ")", "{", "this", ".", "categoryName", "=", "categoryName", ";", "this", ".", "error", "=", "error", ";", "}", "public", "String", "getCategoryName", "(", ")", "{", "return", "categoryName", ";", "}", "public", "Throwable", "getError", "(", ")", "{", "return", "error", ";", "}", "}" ]
An error while loading all products has been occurred
[ "An", "error", "while", "loading", "all", "products", "has", "been", "occurred" ]
[]
[ { "param": "PartialStateChanges", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PartialStateChanges", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f8f49d4b5c72bc449a3bf13ccec8bf5b412142
uOOOO/mosby
sample-mvi/src/main/java/com/hannesdorfmann/mosby3/sample/mvi/view/home/PartialStateChanges.java
[ "Apache-2.0" ]
Java
ProductsOfCategoryLoaded
/** * Products of a given Category has been loaded */
Products of a given Category has been loaded
[ "Products", "of", "a", "given", "Category", "has", "been", "loaded" ]
final class ProductsOfCategoryLoaded implements PartialStateChanges { private final List<Product> data; private final String categoryName; public ProductsOfCategoryLoaded(String categoryName, List<Product> data) { this.data = data; this.categoryName = categoryName; } public String getCategoryName() { return categoryName; } public List<Product> getData() { return data; } }
[ "final", "class", "ProductsOfCategoryLoaded", "implements", "PartialStateChanges", "{", "private", "final", "List", "<", "Product", ">", "data", ";", "private", "final", "String", "categoryName", ";", "public", "ProductsOfCategoryLoaded", "(", "String", "categoryName", ",", "List", "<", "Product", ">", "data", ")", "{", "this", ".", "data", "=", "data", ";", "this", ".", "categoryName", "=", "categoryName", ";", "}", "public", "String", "getCategoryName", "(", ")", "{", "return", "categoryName", ";", "}", "public", "List", "<", "Product", ">", "getData", "(", ")", "{", "return", "data", ";", "}", "}" ]
Products of a given Category has been loaded
[ "Products", "of", "a", "given", "Category", "has", "been", "loaded" ]
[]
[ { "param": "PartialStateChanges", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PartialStateChanges", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
35f9585b37aca8422eaff095bb99e862a9ea3ae8
realDaiwei/thinking-in-code
thinking-in-bytebuddy/src/main/java/io/daiwei/bytebuddy/BeforeAdvice.java
[ "Apache-2.0" ]
Java
BeforeAdvice
/** * Created by Daiwei on 2021/3/22 */
Created by Daiwei on 2021/3/22
[ "Created", "by", "Daiwei", "on", "2021", "/", "3", "/", "22" ]
public class BeforeAdvice { @RuntimeType public Object beforeAdvice(@This Object target, @AllArguments Object[] args) { System.out.println("before advice"); System.out.println(target.getClass().getName()); System.out.println(Arrays.toString(args)); return null; } }
[ "public", "class", "BeforeAdvice", "{", "@", "RuntimeType", "public", "Object", "beforeAdvice", "(", "@", "This", "Object", "target", ",", "@", "AllArguments", "Object", "[", "]", "args", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "before advice", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "target", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "System", ".", "out", ".", "println", "(", "Arrays", ".", "toString", "(", "args", ")", ")", ";", "return", "null", ";", "}", "}" ]
Created by Daiwei on 2021/3/22
[ "Created", "by", "Daiwei", "on", "2021", "/", "3", "/", "22" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
35fb8d21a0f3175707909c262f552a620454e4ae
westbrook-jp/AndroidLib
Preference/src/main/java/jp/westbrook/android/preference/SliderPreference.java
[ "Apache-2.0" ]
Java
SliderPreference
/** * Slider preference base template class * @param <N> type */
Slider preference base template class @param type
[ "Slider", "preference", "base", "template", "class", "@param", "type" ]
public abstract class SliderPreference<N extends Number> extends Preference { protected enum LAYOUT_RESOURCE_MODE { SEEKBAR_LAYOUT_RESOURCE, LAYOUT_RESOURCE, WIDGET_LAYOUT_RESOURCE, } // static protected static final LAYOUT_RESOURCE_MODE mLayoutResourceMode = LAYOUT_RESOURCE_MODE.SEEKBAR_LAYOUT_RESOURCE; protected static int mSeekBarPreferenceResourceId = 0; // value settings protected BigDecimal mDefaultValue; protected BigDecimal mMinimum; protected BigDecimal mMaximum; protected BigDecimal mTick; protected boolean mShowValue; protected boolean mUpdatesContinuously; protected boolean mAdjustable; // controls protected SeekBar mSeekBar; protected TextView mValueTextView; // value protected BigDecimal mValue; ///////////////////////////////////////////////////////////////////////////////////////////// // constructors /** * constructor * @param context Context: The Context this is associated with, through which it can access the current theme, resources, SharedPreferences, etc. */ public SliderPreference(Context context) { super(context); initialize(context, null, 0, 0); } /** * constructor * @param context Context: The Context this is associated with, through which it can access the current theme, resources, SharedPreferences, etc. * @param attrs AttributeSet: The attributes of the XML tag that is inflating the preference */ public SliderPreference(Context context, AttributeSet attrs) { super(context, attrs); initialize(context, attrs, 0, 0); } /** * constructor * @param context Context: The Context this is associated with, through which it can access the current theme, resources, SharedPreferences, etc. * @param attrs AttributeSet: The attributes of the XML tag that is inflating the preference * @param defStyleAttr int: An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults. */ public SliderPreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initialize(context, attrs, defStyleAttr, 0); } /** * constructor * @param context Context: The Context this is associated with, through which it can access the current theme, resources, SharedPreferences, etc. * @param attrs AttributeSet: The attributes of the XML tag that is inflating the preference * @param defStyleAttr int: An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults. * @param defStyleRes int: A resource identifier of a style resource that supplies default values for the view, used only if defStyleAttr is 0 or can not be found in the theme. Can be 0 to not look for defaults. */ public SliderPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); initialize(context, attrs, defStyleAttr, defStyleRes); } ///////////////////////////////////////////////////////////////////////////////////////////// // implements protected void initialize(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { switch (mLayoutResourceMode) { case LAYOUT_RESOURCE: setLayoutResource(R.layout.slider_preference); break; case WIDGET_LAYOUT_RESOURCE: setWidgetLayoutResource(R.layout.slider_preference_widget); break; case SEEKBAR_LAYOUT_RESOURCE: if (mSeekBarPreferenceResourceId == 0) { mSeekBarPreferenceResourceId = new SeekBarPreference(context).getLayoutResource(); } setLayoutResource(mSeekBarPreferenceResourceId); break; } // initialize flags mShowValue = false; mAdjustable = true; mUpdatesContinuously = false; // initialize values valueInitialize(); // get xml value TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SliderPreference, defStyleAttr, defStyleRes); try { mMinimum = typedArrayGetValue(a, R.styleable.SliderPreference_minimum, mMinimum); mMaximum = typedArrayGetValue(a, R.styleable.SliderPreference_maximum, mMaximum); mTick = typedArrayGetValue(a, R.styleable.SliderPreference_tick, mTick); mShowValue = a.getBoolean(R.styleable.SliderPreference_showValue, mShowValue); mAdjustable = a.getBoolean(R.styleable.SliderPreference_adjustable, mAdjustable); mUpdatesContinuously = a.getBoolean(R.styleable.SliderPreference_updatesContinuously, mUpdatesContinuously); } finally { a.recycle(); } // values valueInitializeFix(); } protected abstract void valueInitialize(); protected void valueInitializeFix() {} protected abstract int getValueScale(); protected int convertToSeekBarProgress(BigDecimal value) { return value.subtract(mMinimum).divide(mTick, getValueScale(), RoundingMode.HALF_UP).intValue(); } protected BigDecimal convertFromSeekBarProgress(int value) { return BigDecimal.valueOf(value).multiply(mTick).add(mMinimum).setScale(getValueScale(), RoundingMode.HALF_UP); } protected abstract BigDecimal convertToValue(N value); protected abstract N convertFromValue(BigDecimal value); protected String typedArrayGetString(TypedArray a, int index, @Nullable String defaultValue) { String string = a.getString(index); if (string != null) { return string; } return defaultValue; } protected BigDecimal typedArrayGetValue(TypedArray a, int index, @Nullable BigDecimal defaultValue) { String string = a.getString(index); if (string != null) { try { return new BigDecimal(string); } catch(Exception e) {} } return defaultValue; } protected abstract BigDecimal getPersistedValue(@Nullable Object defaultValue); protected abstract void persistValue(BigDecimal value); protected abstract boolean callChangeListener(BigDecimal newValue); @Override protected Object onGetDefaultValue(TypedArray a, int index) { mDefaultValue = typedArrayGetValue(a, index, null); return mDefaultValue; } @Override protected void onSetInitialValue(@Nullable Object defaultValue) { mValue = getPersistedValue(defaultValue); super.onSetInitialValue(defaultValue); } @Override public void onBindViewHolder(PreferenceViewHolder view) { super.onBindViewHolder(view); // view.itemView.setOnKeyListener(mSeekBarKeyListener); mSeekBar = (SeekBar)view.findViewById(R.id.seekbar); mValueTextView = (TextView)view.findViewById(R.id.seekbar_value); if (mSeekBar == null) { return; } if (mValueTextView != null) { if (mShowValue) { mValueTextView.setVisibility(View.VISIBLE); } else { mValueTextView.setVisibility(View.GONE); mValueTextView = null; } } // mSeekBar.setOnSeekBarChangeListener(mSeekBarChangeListener); mSeekBar.setMax(convertToSeekBarProgress(mMaximum)); updateSeekBarProgress(mValue); updateValueLabel(mValue); mSeekBar.setEnabled(isEnabled()); } protected void setValueInternal(BigDecimal value, boolean notifyChanged) { if (value.compareTo(mMinimum) < 0) { value = mMinimum; } if (value.compareTo(mMaximum) > 0) { value = mMaximum; } if (value != mValue) { mValue = value; updateSeekBarProgress(mValue); persistValue(mValue); if (notifyChanged) { notifyChanged(); } } } /** * Persist the SeekBar value */ protected void syncValue() { BigDecimal seekBarValue = convertFromSeekBarProgress(mSeekBar.getProgress()); if (seekBarValue != mValue) { if (callChangeListener(seekBarValue)) { setValueInternal(seekBarValue, false); } else { updateSeekBarProgress(mValue); updateValueLabel(mValue); } } } /** * Attempts to update the TextView label that displays the current value. */ protected void updateSeekBarProgress(BigDecimal value) { if (mSeekBar != null) { mSeekBar.setProgress(convertToSeekBarProgress(value)); } } /** * Attempts to update the TextView label that displays the current value. */ protected void updateValueLabel(BigDecimal value) { if (mValueTextView != null) { mValueTextView.setText(value.toPlainString()); } } /** * seek bar lisener */ protected SeekBar.OnSeekBarChangeListener mSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() { boolean mTrackingTouch; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser && (mUpdatesContinuously || !mTrackingTouch)) { syncValue(); } else { // always update text while the seek bar is being dragged updateValueLabel(convertFromSeekBarProgress(progress)); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { mTrackingTouch = true; } @Override public void onStopTrackingTouch(SeekBar seekBar) { mTrackingTouch = false; syncValue(); } }; /** * keylisener */ /** * Listener reacting to the user pressing DPAD left/right keys if {@code * adjustable} attribute is set to true; it transfers the key presses to the SeekBar * to be handled accordingly. */ private View.OnKeyListener mSeekBarKeyListener = new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() != KeyEvent.ACTION_DOWN) { return false; } if (!mAdjustable && (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)) { // Right or left keys are pressed when in non-adjustable mode; Skip the keys. return false; } // We don't want to propagate the click keys down to the SeekBar view since it will // create the ripple effect for the thumb. if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) { return false; } if (mSeekBar == null) { return false; } return mSeekBar.onKeyDown(keyCode, event); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // public interface /** * Gets the current progress of the SeekBar. * * @return The current progress of the SeekBar */ public N getValue() { return convertFromValue(mValue); } /** * Sets the current progress of the SeekBar. * * @param value The current progress of the SeekBar */ public void setValue(N value) { setValueInternal(convertToValue(value), true); } /** * Gets the lower bound set on the SeekBar. * * @return The lower bound set */ public N getMin() { return convertFromValue(mMinimum); } /** * Sets the lower bound on the SeekBar. * * @param min The lower bound to set */ public void setMin(N min) { BigDecimal value = convertToValue(min); if (value.compareTo(mMaximum) > 0) { value = mMaximum; } if (value != mMinimum) { mMinimum = value; notifyChanged(); } } /** * Gets the upper bound set on the SeekBar. * * @return The upper bound set */ public N getMax() { return convertFromValue(mMaximum); } /** * Sets the upper bound on the SeekBar. * * @param max The upper bound to set */ public final void setMax(N max) { BigDecimal value = convertToValue(max); if (value.compareTo(mMinimum) < 0) { value = mMinimum; } if (value != mMaximum) { mMaximum = value; notifyChanged(); } } /** * Gets whether the current SeekBar value is displayed to the user. * * @return Whether the current SeekBar value is displayed to the user * @see #setShowValue(boolean) */ public boolean getShowValue() { return mShowValue; } /** * Sets whether the current SeekBar value is displayed to the user. * * @param showValue Whether the current SeekBar value is displayed to the user * @see #getShowValue() */ public void setShowValue(boolean showValue) { mShowValue = showValue; notifyChanged(); } /** * Gets whether the SeekBar should respond to the left/right keys. * * @return Whether the SeekBar should respond to the left/right keys */ public boolean isAdjustable() { return mAdjustable; } /** * Sets whether the SeekBar should respond to the left/right keys. * * @param adjustable Whether the SeekBar should respond to the left/right keys */ public void setAdjustable(boolean adjustable) { mAdjustable = adjustable; } /** * Gets whether the {@link SliderPreference} should continuously save the SeekBar value * while it is being dragged. Note that when the value is true, * {@link Preference.OnPreferenceChangeListener} will be called continuously as well. * * @return Whether the {@link SliderPreference} should continuously save the SeekBar * value while it is being dragged * @see #setUpdatesContinuously(boolean) */ public boolean getUpdatesContinuously() { return mUpdatesContinuously; } /** * Sets whether the {@link SeekBarPreference} should continuously save the SeekBar value * while it is being dragged. * * @param updatesContinuously Whether the {@link SeekBarPreference} should continuously save * the SeekBar value while it is being dragged * @see #getUpdatesContinuously() */ public void setUpdatesContinuously(boolean updatesContinuously) { mUpdatesContinuously = updatesContinuously; } }
[ "public", "abstract", "class", "SliderPreference", "<", "N", "extends", "Number", ">", "extends", "Preference", "{", "protected", "enum", "LAYOUT_RESOURCE_MODE", "{", "SEEKBAR_LAYOUT_RESOURCE", ",", "LAYOUT_RESOURCE", ",", "WIDGET_LAYOUT_RESOURCE", ",", "}", "protected", "static", "final", "LAYOUT_RESOURCE_MODE", "mLayoutResourceMode", "=", "LAYOUT_RESOURCE_MODE", ".", "SEEKBAR_LAYOUT_RESOURCE", ";", "protected", "static", "int", "mSeekBarPreferenceResourceId", "=", "0", ";", "protected", "BigDecimal", "mDefaultValue", ";", "protected", "BigDecimal", "mMinimum", ";", "protected", "BigDecimal", "mMaximum", ";", "protected", "BigDecimal", "mTick", ";", "protected", "boolean", "mShowValue", ";", "protected", "boolean", "mUpdatesContinuously", ";", "protected", "boolean", "mAdjustable", ";", "protected", "SeekBar", "mSeekBar", ";", "protected", "TextView", "mValueTextView", ";", "protected", "BigDecimal", "mValue", ";", "/**\n * constructor\n * @param context Context: The Context this is associated with, through which it can access the current theme, resources, SharedPreferences, etc.\n */", "public", "SliderPreference", "(", "Context", "context", ")", "{", "super", "(", "context", ")", ";", "initialize", "(", "context", ",", "null", ",", "0", ",", "0", ")", ";", "}", "/**\n * constructor\n * @param context Context: The Context this is associated with, through which it can access the current theme, resources, SharedPreferences, etc.\n * @param attrs AttributeSet: The attributes of the XML tag that is inflating the preference\n */", "public", "SliderPreference", "(", "Context", "context", ",", "AttributeSet", "attrs", ")", "{", "super", "(", "context", ",", "attrs", ")", ";", "initialize", "(", "context", ",", "attrs", ",", "0", ",", "0", ")", ";", "}", "/**\n * constructor\n * @param context Context: The Context this is associated with, through which it can access the current theme, resources, SharedPreferences, etc.\n * @param attrs AttributeSet: The attributes of the XML tag that is inflating the preference\n * @param defStyleAttr int: An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.\n */", "public", "SliderPreference", "(", "Context", "context", ",", "AttributeSet", "attrs", ",", "int", "defStyleAttr", ")", "{", "super", "(", "context", ",", "attrs", ",", "defStyleAttr", ")", ";", "initialize", "(", "context", ",", "attrs", ",", "defStyleAttr", ",", "0", ")", ";", "}", "/**\n * constructor\n * @param context Context: The Context this is associated with, through which it can access the current theme, resources, SharedPreferences, etc.\n * @param attrs AttributeSet: The attributes of the XML tag that is inflating the preference\n * @param defStyleAttr int: An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.\n * @param defStyleRes int: A resource identifier of a style resource that supplies default values for the view, used only if defStyleAttr is 0 or can not be found in the theme. Can be 0 to not look for defaults.\n */", "public", "SliderPreference", "(", "Context", "context", ",", "AttributeSet", "attrs", ",", "int", "defStyleAttr", ",", "int", "defStyleRes", ")", "{", "super", "(", "context", ",", "attrs", ",", "defStyleAttr", ",", "defStyleRes", ")", ";", "initialize", "(", "context", ",", "attrs", ",", "defStyleAttr", ",", "defStyleRes", ")", ";", "}", "protected", "void", "initialize", "(", "Context", "context", ",", "AttributeSet", "attrs", ",", "int", "defStyleAttr", ",", "int", "defStyleRes", ")", "{", "switch", "(", "mLayoutResourceMode", ")", "{", "case", "LAYOUT_RESOURCE", ":", "setLayoutResource", "(", "R", ".", "layout", ".", "slider_preference", ")", ";", "break", ";", "case", "WIDGET_LAYOUT_RESOURCE", ":", "setWidgetLayoutResource", "(", "R", ".", "layout", ".", "slider_preference_widget", ")", ";", "break", ";", "case", "SEEKBAR_LAYOUT_RESOURCE", ":", "if", "(", "mSeekBarPreferenceResourceId", "==", "0", ")", "{", "mSeekBarPreferenceResourceId", "=", "new", "SeekBarPreference", "(", "context", ")", ".", "getLayoutResource", "(", ")", ";", "}", "setLayoutResource", "(", "mSeekBarPreferenceResourceId", ")", ";", "break", ";", "}", "mShowValue", "=", "false", ";", "mAdjustable", "=", "true", ";", "mUpdatesContinuously", "=", "false", ";", "valueInitialize", "(", ")", ";", "TypedArray", "a", "=", "context", ".", "obtainStyledAttributes", "(", "attrs", ",", "R", ".", "styleable", ".", "SliderPreference", ",", "defStyleAttr", ",", "defStyleRes", ")", ";", "try", "{", "mMinimum", "=", "typedArrayGetValue", "(", "a", ",", "R", ".", "styleable", ".", "SliderPreference_minimum", ",", "mMinimum", ")", ";", "mMaximum", "=", "typedArrayGetValue", "(", "a", ",", "R", ".", "styleable", ".", "SliderPreference_maximum", ",", "mMaximum", ")", ";", "mTick", "=", "typedArrayGetValue", "(", "a", ",", "R", ".", "styleable", ".", "SliderPreference_tick", ",", "mTick", ")", ";", "mShowValue", "=", "a", ".", "getBoolean", "(", "R", ".", "styleable", ".", "SliderPreference_showValue", ",", "mShowValue", ")", ";", "mAdjustable", "=", "a", ".", "getBoolean", "(", "R", ".", "styleable", ".", "SliderPreference_adjustable", ",", "mAdjustable", ")", ";", "mUpdatesContinuously", "=", "a", ".", "getBoolean", "(", "R", ".", "styleable", ".", "SliderPreference_updatesContinuously", ",", "mUpdatesContinuously", ")", ";", "}", "finally", "{", "a", ".", "recycle", "(", ")", ";", "}", "valueInitializeFix", "(", ")", ";", "}", "protected", "abstract", "void", "valueInitialize", "(", ")", ";", "protected", "void", "valueInitializeFix", "(", ")", "{", "}", "protected", "abstract", "int", "getValueScale", "(", ")", ";", "protected", "int", "convertToSeekBarProgress", "(", "BigDecimal", "value", ")", "{", "return", "value", ".", "subtract", "(", "mMinimum", ")", ".", "divide", "(", "mTick", ",", "getValueScale", "(", ")", ",", "RoundingMode", ".", "HALF_UP", ")", ".", "intValue", "(", ")", ";", "}", "protected", "BigDecimal", "convertFromSeekBarProgress", "(", "int", "value", ")", "{", "return", "BigDecimal", ".", "valueOf", "(", "value", ")", ".", "multiply", "(", "mTick", ")", ".", "add", "(", "mMinimum", ")", ".", "setScale", "(", "getValueScale", "(", ")", ",", "RoundingMode", ".", "HALF_UP", ")", ";", "}", "protected", "abstract", "BigDecimal", "convertToValue", "(", "N", "value", ")", ";", "protected", "abstract", "N", "convertFromValue", "(", "BigDecimal", "value", ")", ";", "protected", "String", "typedArrayGetString", "(", "TypedArray", "a", ",", "int", "index", ",", "@", "Nullable", "String", "defaultValue", ")", "{", "String", "string", "=", "a", ".", "getString", "(", "index", ")", ";", "if", "(", "string", "!=", "null", ")", "{", "return", "string", ";", "}", "return", "defaultValue", ";", "}", "protected", "BigDecimal", "typedArrayGetValue", "(", "TypedArray", "a", ",", "int", "index", ",", "@", "Nullable", "BigDecimal", "defaultValue", ")", "{", "String", "string", "=", "a", ".", "getString", "(", "index", ")", ";", "if", "(", "string", "!=", "null", ")", "{", "try", "{", "return", "new", "BigDecimal", "(", "string", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "return", "defaultValue", ";", "}", "protected", "abstract", "BigDecimal", "getPersistedValue", "(", "@", "Nullable", "Object", "defaultValue", ")", ";", "protected", "abstract", "void", "persistValue", "(", "BigDecimal", "value", ")", ";", "protected", "abstract", "boolean", "callChangeListener", "(", "BigDecimal", "newValue", ")", ";", "@", "Override", "protected", "Object", "onGetDefaultValue", "(", "TypedArray", "a", ",", "int", "index", ")", "{", "mDefaultValue", "=", "typedArrayGetValue", "(", "a", ",", "index", ",", "null", ")", ";", "return", "mDefaultValue", ";", "}", "@", "Override", "protected", "void", "onSetInitialValue", "(", "@", "Nullable", "Object", "defaultValue", ")", "{", "mValue", "=", "getPersistedValue", "(", "defaultValue", ")", ";", "super", ".", "onSetInitialValue", "(", "defaultValue", ")", ";", "}", "@", "Override", "public", "void", "onBindViewHolder", "(", "PreferenceViewHolder", "view", ")", "{", "super", ".", "onBindViewHolder", "(", "view", ")", ";", "view", ".", "itemView", ".", "setOnKeyListener", "(", "mSeekBarKeyListener", ")", ";", "mSeekBar", "=", "(", "SeekBar", ")", "view", ".", "findViewById", "(", "R", ".", "id", ".", "seekbar", ")", ";", "mValueTextView", "=", "(", "TextView", ")", "view", ".", "findViewById", "(", "R", ".", "id", ".", "seekbar_value", ")", ";", "if", "(", "mSeekBar", "==", "null", ")", "{", "return", ";", "}", "if", "(", "mValueTextView", "!=", "null", ")", "{", "if", "(", "mShowValue", ")", "{", "mValueTextView", ".", "setVisibility", "(", "View", ".", "VISIBLE", ")", ";", "}", "else", "{", "mValueTextView", ".", "setVisibility", "(", "View", ".", "GONE", ")", ";", "mValueTextView", "=", "null", ";", "}", "}", "mSeekBar", ".", "setOnSeekBarChangeListener", "(", "mSeekBarChangeListener", ")", ";", "mSeekBar", ".", "setMax", "(", "convertToSeekBarProgress", "(", "mMaximum", ")", ")", ";", "updateSeekBarProgress", "(", "mValue", ")", ";", "updateValueLabel", "(", "mValue", ")", ";", "mSeekBar", ".", "setEnabled", "(", "isEnabled", "(", ")", ")", ";", "}", "protected", "void", "setValueInternal", "(", "BigDecimal", "value", ",", "boolean", "notifyChanged", ")", "{", "if", "(", "value", ".", "compareTo", "(", "mMinimum", ")", "<", "0", ")", "{", "value", "=", "mMinimum", ";", "}", "if", "(", "value", ".", "compareTo", "(", "mMaximum", ")", ">", "0", ")", "{", "value", "=", "mMaximum", ";", "}", "if", "(", "value", "!=", "mValue", ")", "{", "mValue", "=", "value", ";", "updateSeekBarProgress", "(", "mValue", ")", ";", "persistValue", "(", "mValue", ")", ";", "if", "(", "notifyChanged", ")", "{", "notifyChanged", "(", ")", ";", "}", "}", "}", "/**\n * Persist the SeekBar value\n */", "protected", "void", "syncValue", "(", ")", "{", "BigDecimal", "seekBarValue", "=", "convertFromSeekBarProgress", "(", "mSeekBar", ".", "getProgress", "(", ")", ")", ";", "if", "(", "seekBarValue", "!=", "mValue", ")", "{", "if", "(", "callChangeListener", "(", "seekBarValue", ")", ")", "{", "setValueInternal", "(", "seekBarValue", ",", "false", ")", ";", "}", "else", "{", "updateSeekBarProgress", "(", "mValue", ")", ";", "updateValueLabel", "(", "mValue", ")", ";", "}", "}", "}", "/**\n * Attempts to update the TextView label that displays the current value.\n */", "protected", "void", "updateSeekBarProgress", "(", "BigDecimal", "value", ")", "{", "if", "(", "mSeekBar", "!=", "null", ")", "{", "mSeekBar", ".", "setProgress", "(", "convertToSeekBarProgress", "(", "value", ")", ")", ";", "}", "}", "/**\n * Attempts to update the TextView label that displays the current value.\n */", "protected", "void", "updateValueLabel", "(", "BigDecimal", "value", ")", "{", "if", "(", "mValueTextView", "!=", "null", ")", "{", "mValueTextView", ".", "setText", "(", "value", ".", "toPlainString", "(", ")", ")", ";", "}", "}", "/**\n * seek bar lisener\n */", "protected", "SeekBar", ".", "OnSeekBarChangeListener", "mSeekBarChangeListener", "=", "new", "SeekBar", ".", "OnSeekBarChangeListener", "(", ")", "{", "boolean", "mTrackingTouch", ";", "@", "Override", "public", "void", "onProgressChanged", "(", "SeekBar", "seekBar", ",", "int", "progress", ",", "boolean", "fromUser", ")", "{", "if", "(", "fromUser", "&&", "(", "mUpdatesContinuously", "||", "!", "mTrackingTouch", ")", ")", "{", "syncValue", "(", ")", ";", "}", "else", "{", "updateValueLabel", "(", "convertFromSeekBarProgress", "(", "progress", ")", ")", ";", "}", "}", "@", "Override", "public", "void", "onStartTrackingTouch", "(", "SeekBar", "seekBar", ")", "{", "mTrackingTouch", "=", "true", ";", "}", "@", "Override", "public", "void", "onStopTrackingTouch", "(", "SeekBar", "seekBar", ")", "{", "mTrackingTouch", "=", "false", ";", "syncValue", "(", ")", ";", "}", "}", ";", "/**\n * keylisener\n */", "/**\n * Listener reacting to the user pressing DPAD left/right keys if {@code\n * adjustable} attribute is set to true; it transfers the key presses to the SeekBar\n * to be handled accordingly.\n */", "private", "View", ".", "OnKeyListener", "mSeekBarKeyListener", "=", "new", "View", ".", "OnKeyListener", "(", ")", "{", "@", "Override", "public", "boolean", "onKey", "(", "View", "v", ",", "int", "keyCode", ",", "KeyEvent", "event", ")", "{", "if", "(", "event", ".", "getAction", "(", ")", "!=", "KeyEvent", ".", "ACTION_DOWN", ")", "{", "return", "false", ";", "}", "if", "(", "!", "mAdjustable", "&&", "(", "keyCode", "==", "KeyEvent", ".", "KEYCODE_DPAD_LEFT", "||", "keyCode", "==", "KeyEvent", ".", "KEYCODE_DPAD_RIGHT", ")", ")", "{", "return", "false", ";", "}", "if", "(", "keyCode", "==", "KeyEvent", ".", "KEYCODE_DPAD_CENTER", "||", "keyCode", "==", "KeyEvent", ".", "KEYCODE_ENTER", ")", "{", "return", "false", ";", "}", "if", "(", "mSeekBar", "==", "null", ")", "{", "return", "false", ";", "}", "return", "mSeekBar", ".", "onKeyDown", "(", "keyCode", ",", "event", ")", ";", "}", "}", ";", "/**\n * Gets the current progress of the SeekBar.\n *\n * @return The current progress of the SeekBar\n */", "public", "N", "getValue", "(", ")", "{", "return", "convertFromValue", "(", "mValue", ")", ";", "}", "/**\n * Sets the current progress of the SeekBar.\n *\n * @param value The current progress of the SeekBar\n */", "public", "void", "setValue", "(", "N", "value", ")", "{", "setValueInternal", "(", "convertToValue", "(", "value", ")", ",", "true", ")", ";", "}", "/**\n * Gets the lower bound set on the SeekBar.\n *\n * @return The lower bound set\n */", "public", "N", "getMin", "(", ")", "{", "return", "convertFromValue", "(", "mMinimum", ")", ";", "}", "/**\n * Sets the lower bound on the SeekBar.\n *\n * @param min The lower bound to set\n */", "public", "void", "setMin", "(", "N", "min", ")", "{", "BigDecimal", "value", "=", "convertToValue", "(", "min", ")", ";", "if", "(", "value", ".", "compareTo", "(", "mMaximum", ")", ">", "0", ")", "{", "value", "=", "mMaximum", ";", "}", "if", "(", "value", "!=", "mMinimum", ")", "{", "mMinimum", "=", "value", ";", "notifyChanged", "(", ")", ";", "}", "}", "/**\n * Gets the upper bound set on the SeekBar.\n *\n * @return The upper bound set\n */", "public", "N", "getMax", "(", ")", "{", "return", "convertFromValue", "(", "mMaximum", ")", ";", "}", "/**\n * Sets the upper bound on the SeekBar.\n *\n * @param max The upper bound to set\n */", "public", "final", "void", "setMax", "(", "N", "max", ")", "{", "BigDecimal", "value", "=", "convertToValue", "(", "max", ")", ";", "if", "(", "value", ".", "compareTo", "(", "mMinimum", ")", "<", "0", ")", "{", "value", "=", "mMinimum", ";", "}", "if", "(", "value", "!=", "mMaximum", ")", "{", "mMaximum", "=", "value", ";", "notifyChanged", "(", ")", ";", "}", "}", "/**\n * Gets whether the current SeekBar value is displayed to the user.\n *\n * @return Whether the current SeekBar value is displayed to the user\n * @see #setShowValue(boolean)\n */", "public", "boolean", "getShowValue", "(", ")", "{", "return", "mShowValue", ";", "}", "/**\n * Sets whether the current SeekBar value is displayed to the user.\n *\n * @param showValue Whether the current SeekBar value is displayed to the user\n * @see #getShowValue()\n */", "public", "void", "setShowValue", "(", "boolean", "showValue", ")", "{", "mShowValue", "=", "showValue", ";", "notifyChanged", "(", ")", ";", "}", "/**\n * Gets whether the SeekBar should respond to the left/right keys.\n *\n * @return Whether the SeekBar should respond to the left/right keys\n */", "public", "boolean", "isAdjustable", "(", ")", "{", "return", "mAdjustable", ";", "}", "/**\n * Sets whether the SeekBar should respond to the left/right keys.\n *\n * @param adjustable Whether the SeekBar should respond to the left/right keys\n */", "public", "void", "setAdjustable", "(", "boolean", "adjustable", ")", "{", "mAdjustable", "=", "adjustable", ";", "}", "/**\n * Gets whether the {@link SliderPreference} should continuously save the SeekBar value\n * while it is being dragged. Note that when the value is true,\n * {@link Preference.OnPreferenceChangeListener} will be called continuously as well.\n *\n * @return Whether the {@link SliderPreference} should continuously save the SeekBar\n * value while it is being dragged\n * @see #setUpdatesContinuously(boolean)\n */", "public", "boolean", "getUpdatesContinuously", "(", ")", "{", "return", "mUpdatesContinuously", ";", "}", "/**\n * Sets whether the {@link SeekBarPreference} should continuously save the SeekBar value\n * while it is being dragged.\n *\n * @param updatesContinuously Whether the {@link SeekBarPreference} should continuously save\n * the SeekBar value while it is being dragged\n * @see #getUpdatesContinuously()\n */", "public", "void", "setUpdatesContinuously", "(", "boolean", "updatesContinuously", ")", "{", "mUpdatesContinuously", "=", "updatesContinuously", ";", "}", "}" ]
Slider preference base template class @param <N> type
[ "Slider", "preference", "base", "template", "class", "@param", "<N", ">", "type" ]
[ "// static", "// value settings", "// controls", "// value", "/////////////////////////////////////////////////////////////////////////////////////////////", "// constructors", "/////////////////////////////////////////////////////////////////////////////////////////////", "// implements", "// initialize flags", "// initialize values", "// get xml value", "// values", "//", "//", "// always update text while the seek bar is being dragged", "// Right or left keys are pressed when in non-adjustable mode; Skip the keys.", "// We don't want to propagate the click keys down to the SeekBar view since it will", "// create the ripple effect for the thumb.", "///////////////////////////////////////////////////////////////////////////////////////////////", "// public interface" ]
[ { "param": "Preference", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Preference", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c406fbbc98f9a84514a2f90a11a3ea910967afab
frederic89/Java_HMM
src/edu/sjtu/j_hmm/TR_OBJ.java
[ "MIT" ]
Java
TR_OBJ
/** * Created by guanyongqing on 2016/8/24. */
Created by guanyongqing on 2016/8/24.
[ "Created", "by", "guanyongqing", "on", "2016", "/", "8", "/", "24", "." ]
public class TR_OBJ { ArrayList scale; ArrayList prob; ArrayList eMat; ArrayList labels; ArrayList seq; ArrayList f; ArrayList b; String name; int len; TR_OBJ(ArrayList<String> seq,ArrayList<String> labels){ this.seq = seq; this.len = seq.size(); //length of the sequence this.labels = labels; //TODO this.f = new ArrayList<>();//the forward matrix this.b = new ArrayList<>();//the backward matrix this.eMat = new ArrayList<>(); //# the precalculate emission matrix this.scale = new ArrayList<>();//the scale factors this.prob = new ArrayList<>();//the probability of the sequence this.name = ""; //TODO } }
[ "public", "class", "TR_OBJ", "{", "ArrayList", "scale", ";", "ArrayList", "prob", ";", "ArrayList", "eMat", ";", "ArrayList", "labels", ";", "ArrayList", "seq", ";", "ArrayList", "f", ";", "ArrayList", "b", ";", "String", "name", ";", "int", "len", ";", "TR_OBJ", "(", "ArrayList", "<", "String", ">", "seq", ",", "ArrayList", "<", "String", ">", "labels", ")", "{", "this", ".", "seq", "=", "seq", ";", "this", ".", "len", "=", "seq", ".", "size", "(", ")", ";", "this", ".", "labels", "=", "labels", ";", "this", ".", "f", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "this", ".", "b", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "this", ".", "eMat", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "this", ".", "scale", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "this", ".", "prob", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "this", ".", "name", "=", "\"", "\"", ";", "}", "}" ]
Created by guanyongqing on 2016/8/24.
[ "Created", "by", "guanyongqing", "on", "2016", "/", "8", "/", "24", "." ]
[ "//length of the sequence\r", "//TODO\r", "//the forward matrix\r", "//the backward matrix\r", "//# the precalculate emission matrix\r", "//the scale factors\r", "//the probability of the sequence\r", "//TODO\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c40836d8863648607e933341bf1d1dd998779e6f
rd2281136306/pinpoint
commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/stat/join/JoinDirectBufferBo.java
[ "Apache-2.0" ]
Java
JoinDirectBufferBo
/** * @author Roy Kim */
@author Roy Kim
[ "@author", "Roy", "Kim" ]
public class JoinDirectBufferBo implements JoinStatBo { public static final JoinDirectBufferBo EMPTY_JOIN_DIRECT_BUFFER_BO = new JoinDirectBufferBo(); public static final long UNCOLLECTED_VALUE = -1; private String id = UNKNOWN_ID; private long timestamp = Long.MIN_VALUE; private long avgDirectCount = UNCOLLECTED_VALUE; private String maxDirectCountAgentId = UNKNOWN_AGENT; private long maxDirectCount = UNCOLLECTED_VALUE; private String minDirectCountAgentId = UNKNOWN_AGENT; private long minDirectCount = UNCOLLECTED_VALUE; private long avgDirectMemoryUsed = UNCOLLECTED_VALUE; private String maxDirectMemoryUsedAgentId = UNKNOWN_AGENT; private long maxDirectMemoryUsed = UNCOLLECTED_VALUE; private String minDirectMemoryUsedAgentId = UNKNOWN_AGENT; private long minDirectMemoryUsed = UNCOLLECTED_VALUE; private long avgMappedCount = UNCOLLECTED_VALUE; private String maxMappedCountAgentId = UNKNOWN_AGENT; private long maxMappedCount = UNCOLLECTED_VALUE; private String minMappedCountAgentId = UNKNOWN_AGENT; private long minMappedCount = UNCOLLECTED_VALUE; private long avgMappedMemoryUsed = UNCOLLECTED_VALUE; private String maxMappedMemoryUsedAgentId = UNKNOWN_AGENT; private long maxMappedMemoryUsed = UNCOLLECTED_VALUE; private String minMappedMemoryUsedAgentId = UNKNOWN_AGENT; private long minMappedMemoryUsed = UNCOLLECTED_VALUE; public JoinDirectBufferBo() { } public JoinDirectBufferBo(String id, long avgDirectCount, long maxDirectCount, String maxDirectCountAgentId, long minDirectCount, String minDirectCountAgentId , long avgDirectMemoryUsed, long maxDirectMemoryUsed, String maxDirectMemoryUsedAgentId, long minDirectMemoryUsed, String minDirectMemoryUsedAgentId , long avgMappedCount, long maxMappedCount, String maxMappedCountAgentId, long minMappedCount, String minMappedCountAgentId , long avgMappedMemoryUsed, long maxMappedMemoryUsed, String maxMappedMemoryUsedAgentId, long minMappedMemoryUsed, String minMappedMemoryUsedAgentId , long timestamp) { this.id = id; this.timestamp = timestamp; this.avgDirectCount = avgDirectCount; this.maxDirectCountAgentId = maxDirectCountAgentId; this.maxDirectCount = maxDirectCount; this.minDirectCountAgentId = minDirectCountAgentId; this.minDirectCount = minDirectCount; this.avgDirectMemoryUsed = avgDirectMemoryUsed; this.maxDirectMemoryUsedAgentId = maxDirectMemoryUsedAgentId; this.maxDirectMemoryUsed = maxDirectMemoryUsed; this.minDirectMemoryUsedAgentId = minDirectMemoryUsedAgentId; this.minDirectMemoryUsed = minDirectMemoryUsed; this.avgMappedCount = avgMappedCount; this.maxMappedCountAgentId = maxMappedCountAgentId; this.maxMappedCount = maxMappedCount; this.minMappedCountAgentId = minMappedCountAgentId; this.minMappedCount = minMappedCount; this.avgMappedMemoryUsed = avgMappedMemoryUsed; this.maxMappedMemoryUsedAgentId = maxMappedMemoryUsedAgentId; this.maxMappedMemoryUsed = maxMappedMemoryUsed; this.minMappedMemoryUsedAgentId = minMappedMemoryUsedAgentId; this.minMappedMemoryUsed = minMappedMemoryUsed; } public static JoinDirectBufferBo joinDirectBufferBoList(List<JoinDirectBufferBo> joinDirectBufferBoList, Long timestamp) { int boCount = joinDirectBufferBoList.size(); if (joinDirectBufferBoList.size() == 0) { return EMPTY_JOIN_DIRECT_BUFFER_BO; } JoinDirectBufferBo newJoinDirectBufferBo = new JoinDirectBufferBo(); JoinDirectBufferBo initJoinDirectBufferBo = joinDirectBufferBoList.get(0); newJoinDirectBufferBo.setId(initJoinDirectBufferBo.getId()); newJoinDirectBufferBo.setTimestamp(timestamp); long sumDirectCount = 0L; String maxDirectCountAgentId = initJoinDirectBufferBo.getMaxDirectCountAgentId(); long maxDirectCount = initJoinDirectBufferBo.getMaxDirectCount(); String minDirectCountAgentId = initJoinDirectBufferBo.getMinDirectCountAgentId(); long minDirectCount = initJoinDirectBufferBo.getMinDirectCount(); long sumDirectMemoryUsed = 0L; String maxDirectMemoryUsedAgentId = initJoinDirectBufferBo.getMaxDirectMemoryUsedAgentId(); long maxDirectMemoryUsed = initJoinDirectBufferBo.getMaxDirectMemoryUsed(); String minDirectMemoryUsedAgentId = initJoinDirectBufferBo.getMinDirectMemoryUsedAgentId(); long minDirectMemoryUsed = initJoinDirectBufferBo.getMinDirectMemoryUsed(); long sumMappedCount = 0L; String maxMappedCountAgentId = initJoinDirectBufferBo.getMaxMappedCountAgentId(); long maxMappedCount = initJoinDirectBufferBo.getMaxMappedCount(); String minMappedCountAgentId = initJoinDirectBufferBo.getMinMappedCountAgentId(); long minMappedCount = initJoinDirectBufferBo.getMinMappedCount(); long sumMappedMemoryUsed = 0L; String maxMappedMemoryUsedAgentId = initJoinDirectBufferBo.getMaxMappedMemoryUsedAgentId(); long maxMappedMemoryUsed = initJoinDirectBufferBo.getMaxMappedMemoryUsed(); String minMappedMemoryUsedAgentId = initJoinDirectBufferBo.getMinMappedMemoryUsedAgentId(); long minMappedMemoryUsed = initJoinDirectBufferBo.getMinMappedMemoryUsed(); for (JoinDirectBufferBo joinDirectBufferBo : joinDirectBufferBoList) { sumDirectCount += joinDirectBufferBo.getAvgDirectCount(); if (joinDirectBufferBo.getMaxDirectCount() > maxDirectCount) { maxDirectCount = joinDirectBufferBo.getMaxDirectCount(); maxDirectCountAgentId = joinDirectBufferBo.getMaxDirectCountAgentId(); } if (joinDirectBufferBo.getMinDirectCount() < minDirectCount) { minDirectCount = joinDirectBufferBo.getMinDirectCount(); minDirectCountAgentId = joinDirectBufferBo.getMinDirectCountAgentId(); } sumDirectMemoryUsed += joinDirectBufferBo.getAvgDirectMemoryUsed(); if (joinDirectBufferBo.getMaxDirectMemoryUsed() > maxDirectMemoryUsed) { maxDirectMemoryUsed = joinDirectBufferBo.getMaxDirectMemoryUsed(); maxDirectMemoryUsedAgentId = joinDirectBufferBo.getMaxDirectMemoryUsedAgentId(); } if (joinDirectBufferBo.getMinDirectMemoryUsed() < minDirectMemoryUsed) { minDirectMemoryUsed = joinDirectBufferBo.getMinDirectMemoryUsed(); minDirectMemoryUsedAgentId = joinDirectBufferBo.getMinDirectMemoryUsedAgentId(); } sumMappedCount += joinDirectBufferBo.getAvgMappedCount(); if (joinDirectBufferBo.getMaxMappedCount() > maxMappedCount) { maxMappedCount = joinDirectBufferBo.getMaxMappedCount(); maxMappedCountAgentId = joinDirectBufferBo.getMaxMappedCountAgentId(); } if (joinDirectBufferBo.getMinMappedCount() < minMappedCount) { minMappedCount = joinDirectBufferBo.getMinMappedCount(); minMappedCountAgentId = joinDirectBufferBo.getMinMappedCountAgentId(); } sumMappedMemoryUsed += joinDirectBufferBo.getAvgMappedMemoryUsed(); if (joinDirectBufferBo.getMaxMappedMemoryUsed() > maxMappedMemoryUsed) { maxMappedMemoryUsed = joinDirectBufferBo.getMaxMappedMemoryUsed(); maxMappedMemoryUsedAgentId = joinDirectBufferBo.getMaxMappedMemoryUsedAgentId(); } if (joinDirectBufferBo.getMinMappedMemoryUsed() < minMappedMemoryUsed) { minMappedMemoryUsed = joinDirectBufferBo.getMinMappedMemoryUsed(); minMappedMemoryUsedAgentId = joinDirectBufferBo.getMinMappedMemoryUsedAgentId(); } } newJoinDirectBufferBo.setAvgDirectCount((sumDirectCount / boCount)); newJoinDirectBufferBo.setMaxDirectCount(maxDirectCount); newJoinDirectBufferBo.setMaxDirectCountAgentId(maxDirectCountAgentId); newJoinDirectBufferBo.setMinDirectCount(minDirectCount); newJoinDirectBufferBo.setMinDirectCountAgentId(minDirectCountAgentId); newJoinDirectBufferBo.setAvgDirectMemoryUsed((sumDirectMemoryUsed / boCount)); newJoinDirectBufferBo.setMaxDirectMemoryUsed(maxDirectMemoryUsed); newJoinDirectBufferBo.setMaxDirectMemoryUsedAgentId(maxDirectMemoryUsedAgentId); newJoinDirectBufferBo.setMinDirectMemoryUsed(minDirectMemoryUsed); newJoinDirectBufferBo.setMinDirectMemoryUsedAgentId(minDirectMemoryUsedAgentId); newJoinDirectBufferBo.setAvgMappedCount((sumMappedCount / boCount)); newJoinDirectBufferBo.setMaxMappedCount(maxMappedCount); newJoinDirectBufferBo.setMaxMappedCountAgentId(maxMappedCountAgentId); newJoinDirectBufferBo.setMinMappedCount(minMappedCount); newJoinDirectBufferBo.setMinMappedCountAgentId(minMappedCountAgentId); newJoinDirectBufferBo.setAvgMappedMemoryUsed((sumMappedMemoryUsed / boCount)); newJoinDirectBufferBo.setMaxMappedMemoryUsed(maxMappedMemoryUsed); newJoinDirectBufferBo.setMaxMappedMemoryUsedAgentId(maxMappedMemoryUsedAgentId); newJoinDirectBufferBo.setMinMappedMemoryUsed(minMappedMemoryUsed); newJoinDirectBufferBo.setMinMappedMemoryUsedAgentId(minMappedMemoryUsedAgentId); return newJoinDirectBufferBo; } @Override public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public long getAvgDirectCount() { return avgDirectCount; } public void setAvgDirectCount(long avgDirectCount) { this.avgDirectCount = avgDirectCount; } public String getMaxDirectCountAgentId() { return maxDirectCountAgentId; } public void setMaxDirectCountAgentId(String maxDirectCountAgentId) { this.maxDirectCountAgentId = maxDirectCountAgentId; } public long getMaxDirectCount() { return maxDirectCount; } public void setMaxDirectCount(long maxDirectCount) { this.maxDirectCount = maxDirectCount; } public String getMinDirectCountAgentId() { return minDirectCountAgentId; } public void setMinDirectCountAgentId(String minDirectCountAgentId) { this.minDirectCountAgentId = minDirectCountAgentId; } public long getMinDirectCount() { return minDirectCount; } public void setMinDirectCount(long minDirectCount) { this.minDirectCount = minDirectCount; } public long getAvgDirectMemoryUsed() { return avgDirectMemoryUsed; } public void setAvgDirectMemoryUsed(long avgDirectMemoryUsed) { this.avgDirectMemoryUsed = avgDirectMemoryUsed; } public String getMaxDirectMemoryUsedAgentId() { return maxDirectMemoryUsedAgentId; } public void setMaxDirectMemoryUsedAgentId(String maxDirectMemoryUsedAgentId) { this.maxDirectMemoryUsedAgentId = maxDirectMemoryUsedAgentId; } public long getMaxDirectMemoryUsed() { return maxDirectMemoryUsed; } public void setMaxDirectMemoryUsed(long maxDirectMemoryUsed) { this.maxDirectMemoryUsed = maxDirectMemoryUsed; } public String getMinDirectMemoryUsedAgentId() { return minDirectMemoryUsedAgentId; } public void setMinDirectMemoryUsedAgentId(String minDirectMemoryUsedAgentId) { this.minDirectMemoryUsedAgentId = minDirectMemoryUsedAgentId; } public long getMinDirectMemoryUsed() { return minDirectMemoryUsed; } public void setMinDirectMemoryUsed(long minDirectMemoryUsed) { this.minDirectMemoryUsed = minDirectMemoryUsed; } public long getAvgMappedCount() { return avgMappedCount; } public void setAvgMappedCount(long avgMappedCount) { this.avgMappedCount = avgMappedCount; } public String getMaxMappedCountAgentId() { return maxMappedCountAgentId; } public void setMaxMappedCountAgentId(String maxMappedCountAgentId) { this.maxMappedCountAgentId = maxMappedCountAgentId; } public long getMaxMappedCount() { return maxMappedCount; } public void setMaxMappedCount(long maxMappedCount) { this.maxMappedCount = maxMappedCount; } public String getMinMappedCountAgentId() { return minMappedCountAgentId; } public void setMinMappedCountAgentId(String minMappedCountAgentId) { this.minMappedCountAgentId = minMappedCountAgentId; } public long getMinMappedCount() { return minMappedCount; } public void setMinMappedCount(long minMappedCount) { this.minMappedCount = minMappedCount; } public long getAvgMappedMemoryUsed() { return avgMappedMemoryUsed; } public void setAvgMappedMemoryUsed(long avgMappedMemoryUsed) { this.avgMappedMemoryUsed = avgMappedMemoryUsed; } public String getMaxMappedMemoryUsedAgentId() { return maxMappedMemoryUsedAgentId; } public void setMaxMappedMemoryUsedAgentId(String maxMappedMemoryUsedAgentId) { this.maxMappedMemoryUsedAgentId = maxMappedMemoryUsedAgentId; } public long getMaxMappedMemoryUsed() { return maxMappedMemoryUsed; } public void setMaxMappedMemoryUsed(long maxMappedMemoryUsed) { this.maxMappedMemoryUsed = maxMappedMemoryUsed; } public String getMinMappedMemoryUsedAgentId() { return minMappedMemoryUsedAgentId; } public void setMinMappedMemoryUsedAgentId(String minMappedMemoryUsedAgentId) { this.minMappedMemoryUsedAgentId = minMappedMemoryUsedAgentId; } public long getMinMappedMemoryUsed() { return minMappedMemoryUsed; } public void setMinMappedMemoryUsed(long minMappedMemoryUsed) { this.minMappedMemoryUsed = minMappedMemoryUsed; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; JoinDirectBufferBo that = (JoinDirectBufferBo) o; if (timestamp != that.timestamp) return false; if (avgDirectCount != that.avgDirectCount) return false; if (maxDirectCount != that.maxDirectCount) return false; if (minDirectCount != that.minDirectCount) return false; if (avgDirectMemoryUsed != that.avgDirectMemoryUsed) return false; if (maxDirectMemoryUsed != that.maxDirectMemoryUsed) return false; if (minDirectMemoryUsed != that.minDirectMemoryUsed) return false; if (avgMappedCount != that.avgMappedCount) return false; if (maxMappedCount != that.maxMappedCount) return false; if (minMappedCount != that.minMappedCount) return false; if (avgMappedMemoryUsed != that.avgMappedMemoryUsed) return false; if (maxMappedMemoryUsed != that.maxMappedMemoryUsed) return false; if (minMappedMemoryUsed != that.minMappedMemoryUsed) return false; if (!id.equals(that.id)) return false; if (!maxDirectCountAgentId.equals(that.maxDirectCountAgentId)) return false; if (!minDirectCountAgentId.equals(that.minDirectCountAgentId)) return false; if (!maxDirectMemoryUsedAgentId.equals(that.maxDirectMemoryUsedAgentId)) return false; if (!minDirectMemoryUsedAgentId.equals(that.minDirectMemoryUsedAgentId)) return false; if (!maxMappedCountAgentId.equals(that.maxMappedCountAgentId)) return false; if (!minMappedCountAgentId.equals(that.minMappedCountAgentId)) return false; if (!maxMappedMemoryUsedAgentId.equals(that.maxMappedMemoryUsedAgentId)) return false; return minMappedMemoryUsedAgentId.equals(that.minMappedMemoryUsedAgentId); } @Override public int hashCode() { int result; result = id.hashCode(); result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); result = 31 * result + (int) (avgDirectCount ^ (avgDirectCount >>> 32)); result = 31 * result + maxDirectCountAgentId.hashCode(); result = 31 * result + (int) (maxDirectCount ^ (maxDirectCount >>> 32)); result = 31 * result + minDirectCountAgentId.hashCode(); result = 31 * result + (int) (minDirectCount ^ (minDirectCount >>> 32)); result = 31 * result + (int) (avgDirectMemoryUsed ^ (avgDirectMemoryUsed >>> 32)); result = 31 * result + maxDirectMemoryUsedAgentId.hashCode(); result = 31 * result + (int) (maxDirectMemoryUsed ^ (maxDirectMemoryUsed >>> 32)); result = 31 * result + minDirectMemoryUsedAgentId.hashCode(); result = 31 * result + (int) (minDirectMemoryUsed ^ (minDirectMemoryUsed >>> 32)); result = 31 * result + (int) (avgMappedCount ^ (avgMappedCount >>> 32)); result = 31 * result + maxMappedCountAgentId.hashCode(); result = 31 * result + (int) (maxMappedCount ^ (maxMappedCount >>> 32)); result = 31 * result + minMappedCountAgentId.hashCode(); result = 31 * result + (int) (minMappedCount ^ (minMappedCount >>> 32)); result = 31 * result + (int) (avgMappedMemoryUsed ^ (avgMappedMemoryUsed >>> 32)); result = 31 * result + maxMappedMemoryUsedAgentId.hashCode(); result = 31 * result + (int) (maxMappedMemoryUsed ^ (maxMappedMemoryUsed >>> 32)); result = 31 * result + minMappedMemoryUsedAgentId.hashCode(); result = 31 * result + (int) (minMappedMemoryUsed ^ (minMappedMemoryUsed >>> 32)); return result; } @Override public String toString() { return "JoinDirectBufferBo{" + "id='" + id + '\'' + ", avgDirectCount=" + avgDirectCount + ", maxDirectCountAgentId='" + maxDirectCountAgentId + '\'' + ", maxDirectCount=" + maxDirectCount + ", minDirectCountAgentId='" + minDirectCountAgentId + '\'' + ", minDirectCount=" + minDirectCount + ", avgDirectMemoryUsed=" + avgDirectMemoryUsed + ", maxDirectMemoryUsedAgentId='" + maxDirectMemoryUsedAgentId + '\'' + ", maxDirectMemoryUsed=" + maxDirectMemoryUsed + ", minDirectMemoryUsedAgentId='" + minDirectMemoryUsedAgentId + '\'' + ", minDirectMemoryUsed=" + minDirectMemoryUsed + ", avgMappedCount=" + avgMappedCount + ", maxMappedCountAgentId='" + maxMappedCountAgentId + '\'' + ", maxMappedCount=" + maxMappedCount + ", minMappedCountAgentId='" + minMappedCountAgentId + '\'' + ", minMappedCount=" + minMappedCount + ", avgMappedMemoryUsed=" + avgMappedMemoryUsed + ", maxMappedMemoryUsedAgentId='" + maxMappedMemoryUsedAgentId + '\'' + ", maxMappedMemoryUsed=" + maxMappedMemoryUsed + ", minMappedMemoryUsedAgentId='" + minMappedMemoryUsedAgentId + '\'' + ", minMappedMemoryUsed=" + minMappedMemoryUsed + ", timestamp=" + timestamp +"(" + new Date(timestamp)+ ")" + '}'; } }
[ "public", "class", "JoinDirectBufferBo", "implements", "JoinStatBo", "{", "public", "static", "final", "JoinDirectBufferBo", "EMPTY_JOIN_DIRECT_BUFFER_BO", "=", "new", "JoinDirectBufferBo", "(", ")", ";", "public", "static", "final", "long", "UNCOLLECTED_VALUE", "=", "-", "1", ";", "private", "String", "id", "=", "UNKNOWN_ID", ";", "private", "long", "timestamp", "=", "Long", ".", "MIN_VALUE", ";", "private", "long", "avgDirectCount", "=", "UNCOLLECTED_VALUE", ";", "private", "String", "maxDirectCountAgentId", "=", "UNKNOWN_AGENT", ";", "private", "long", "maxDirectCount", "=", "UNCOLLECTED_VALUE", ";", "private", "String", "minDirectCountAgentId", "=", "UNKNOWN_AGENT", ";", "private", "long", "minDirectCount", "=", "UNCOLLECTED_VALUE", ";", "private", "long", "avgDirectMemoryUsed", "=", "UNCOLLECTED_VALUE", ";", "private", "String", "maxDirectMemoryUsedAgentId", "=", "UNKNOWN_AGENT", ";", "private", "long", "maxDirectMemoryUsed", "=", "UNCOLLECTED_VALUE", ";", "private", "String", "minDirectMemoryUsedAgentId", "=", "UNKNOWN_AGENT", ";", "private", "long", "minDirectMemoryUsed", "=", "UNCOLLECTED_VALUE", ";", "private", "long", "avgMappedCount", "=", "UNCOLLECTED_VALUE", ";", "private", "String", "maxMappedCountAgentId", "=", "UNKNOWN_AGENT", ";", "private", "long", "maxMappedCount", "=", "UNCOLLECTED_VALUE", ";", "private", "String", "minMappedCountAgentId", "=", "UNKNOWN_AGENT", ";", "private", "long", "minMappedCount", "=", "UNCOLLECTED_VALUE", ";", "private", "long", "avgMappedMemoryUsed", "=", "UNCOLLECTED_VALUE", ";", "private", "String", "maxMappedMemoryUsedAgentId", "=", "UNKNOWN_AGENT", ";", "private", "long", "maxMappedMemoryUsed", "=", "UNCOLLECTED_VALUE", ";", "private", "String", "minMappedMemoryUsedAgentId", "=", "UNKNOWN_AGENT", ";", "private", "long", "minMappedMemoryUsed", "=", "UNCOLLECTED_VALUE", ";", "public", "JoinDirectBufferBo", "(", ")", "{", "}", "public", "JoinDirectBufferBo", "(", "String", "id", ",", "long", "avgDirectCount", ",", "long", "maxDirectCount", ",", "String", "maxDirectCountAgentId", ",", "long", "minDirectCount", ",", "String", "minDirectCountAgentId", ",", "long", "avgDirectMemoryUsed", ",", "long", "maxDirectMemoryUsed", ",", "String", "maxDirectMemoryUsedAgentId", ",", "long", "minDirectMemoryUsed", ",", "String", "minDirectMemoryUsedAgentId", ",", "long", "avgMappedCount", ",", "long", "maxMappedCount", ",", "String", "maxMappedCountAgentId", ",", "long", "minMappedCount", ",", "String", "minMappedCountAgentId", ",", "long", "avgMappedMemoryUsed", ",", "long", "maxMappedMemoryUsed", ",", "String", "maxMappedMemoryUsedAgentId", ",", "long", "minMappedMemoryUsed", ",", "String", "minMappedMemoryUsedAgentId", ",", "long", "timestamp", ")", "{", "this", ".", "id", "=", "id", ";", "this", ".", "timestamp", "=", "timestamp", ";", "this", ".", "avgDirectCount", "=", "avgDirectCount", ";", "this", ".", "maxDirectCountAgentId", "=", "maxDirectCountAgentId", ";", "this", ".", "maxDirectCount", "=", "maxDirectCount", ";", "this", ".", "minDirectCountAgentId", "=", "minDirectCountAgentId", ";", "this", ".", "minDirectCount", "=", "minDirectCount", ";", "this", ".", "avgDirectMemoryUsed", "=", "avgDirectMemoryUsed", ";", "this", ".", "maxDirectMemoryUsedAgentId", "=", "maxDirectMemoryUsedAgentId", ";", "this", ".", "maxDirectMemoryUsed", "=", "maxDirectMemoryUsed", ";", "this", ".", "minDirectMemoryUsedAgentId", "=", "minDirectMemoryUsedAgentId", ";", "this", ".", "minDirectMemoryUsed", "=", "minDirectMemoryUsed", ";", "this", ".", "avgMappedCount", "=", "avgMappedCount", ";", "this", ".", "maxMappedCountAgentId", "=", "maxMappedCountAgentId", ";", "this", ".", "maxMappedCount", "=", "maxMappedCount", ";", "this", ".", "minMappedCountAgentId", "=", "minMappedCountAgentId", ";", "this", ".", "minMappedCount", "=", "minMappedCount", ";", "this", ".", "avgMappedMemoryUsed", "=", "avgMappedMemoryUsed", ";", "this", ".", "maxMappedMemoryUsedAgentId", "=", "maxMappedMemoryUsedAgentId", ";", "this", ".", "maxMappedMemoryUsed", "=", "maxMappedMemoryUsed", ";", "this", ".", "minMappedMemoryUsedAgentId", "=", "minMappedMemoryUsedAgentId", ";", "this", ".", "minMappedMemoryUsed", "=", "minMappedMemoryUsed", ";", "}", "public", "static", "JoinDirectBufferBo", "joinDirectBufferBoList", "(", "List", "<", "JoinDirectBufferBo", ">", "joinDirectBufferBoList", ",", "Long", "timestamp", ")", "{", "int", "boCount", "=", "joinDirectBufferBoList", ".", "size", "(", ")", ";", "if", "(", "joinDirectBufferBoList", ".", "size", "(", ")", "==", "0", ")", "{", "return", "EMPTY_JOIN_DIRECT_BUFFER_BO", ";", "}", "JoinDirectBufferBo", "newJoinDirectBufferBo", "=", "new", "JoinDirectBufferBo", "(", ")", ";", "JoinDirectBufferBo", "initJoinDirectBufferBo", "=", "joinDirectBufferBoList", ".", "get", "(", "0", ")", ";", "newJoinDirectBufferBo", ".", "setId", "(", "initJoinDirectBufferBo", ".", "getId", "(", ")", ")", ";", "newJoinDirectBufferBo", ".", "setTimestamp", "(", "timestamp", ")", ";", "long", "sumDirectCount", "=", "0L", ";", "String", "maxDirectCountAgentId", "=", "initJoinDirectBufferBo", ".", "getMaxDirectCountAgentId", "(", ")", ";", "long", "maxDirectCount", "=", "initJoinDirectBufferBo", ".", "getMaxDirectCount", "(", ")", ";", "String", "minDirectCountAgentId", "=", "initJoinDirectBufferBo", ".", "getMinDirectCountAgentId", "(", ")", ";", "long", "minDirectCount", "=", "initJoinDirectBufferBo", ".", "getMinDirectCount", "(", ")", ";", "long", "sumDirectMemoryUsed", "=", "0L", ";", "String", "maxDirectMemoryUsedAgentId", "=", "initJoinDirectBufferBo", ".", "getMaxDirectMemoryUsedAgentId", "(", ")", ";", "long", "maxDirectMemoryUsed", "=", "initJoinDirectBufferBo", ".", "getMaxDirectMemoryUsed", "(", ")", ";", "String", "minDirectMemoryUsedAgentId", "=", "initJoinDirectBufferBo", ".", "getMinDirectMemoryUsedAgentId", "(", ")", ";", "long", "minDirectMemoryUsed", "=", "initJoinDirectBufferBo", ".", "getMinDirectMemoryUsed", "(", ")", ";", "long", "sumMappedCount", "=", "0L", ";", "String", "maxMappedCountAgentId", "=", "initJoinDirectBufferBo", ".", "getMaxMappedCountAgentId", "(", ")", ";", "long", "maxMappedCount", "=", "initJoinDirectBufferBo", ".", "getMaxMappedCount", "(", ")", ";", "String", "minMappedCountAgentId", "=", "initJoinDirectBufferBo", ".", "getMinMappedCountAgentId", "(", ")", ";", "long", "minMappedCount", "=", "initJoinDirectBufferBo", ".", "getMinMappedCount", "(", ")", ";", "long", "sumMappedMemoryUsed", "=", "0L", ";", "String", "maxMappedMemoryUsedAgentId", "=", "initJoinDirectBufferBo", ".", "getMaxMappedMemoryUsedAgentId", "(", ")", ";", "long", "maxMappedMemoryUsed", "=", "initJoinDirectBufferBo", ".", "getMaxMappedMemoryUsed", "(", ")", ";", "String", "minMappedMemoryUsedAgentId", "=", "initJoinDirectBufferBo", ".", "getMinMappedMemoryUsedAgentId", "(", ")", ";", "long", "minMappedMemoryUsed", "=", "initJoinDirectBufferBo", ".", "getMinMappedMemoryUsed", "(", ")", ";", "for", "(", "JoinDirectBufferBo", "joinDirectBufferBo", ":", "joinDirectBufferBoList", ")", "{", "sumDirectCount", "+=", "joinDirectBufferBo", ".", "getAvgDirectCount", "(", ")", ";", "if", "(", "joinDirectBufferBo", ".", "getMaxDirectCount", "(", ")", ">", "maxDirectCount", ")", "{", "maxDirectCount", "=", "joinDirectBufferBo", ".", "getMaxDirectCount", "(", ")", ";", "maxDirectCountAgentId", "=", "joinDirectBufferBo", ".", "getMaxDirectCountAgentId", "(", ")", ";", "}", "if", "(", "joinDirectBufferBo", ".", "getMinDirectCount", "(", ")", "<", "minDirectCount", ")", "{", "minDirectCount", "=", "joinDirectBufferBo", ".", "getMinDirectCount", "(", ")", ";", "minDirectCountAgentId", "=", "joinDirectBufferBo", ".", "getMinDirectCountAgentId", "(", ")", ";", "}", "sumDirectMemoryUsed", "+=", "joinDirectBufferBo", ".", "getAvgDirectMemoryUsed", "(", ")", ";", "if", "(", "joinDirectBufferBo", ".", "getMaxDirectMemoryUsed", "(", ")", ">", "maxDirectMemoryUsed", ")", "{", "maxDirectMemoryUsed", "=", "joinDirectBufferBo", ".", "getMaxDirectMemoryUsed", "(", ")", ";", "maxDirectMemoryUsedAgentId", "=", "joinDirectBufferBo", ".", "getMaxDirectMemoryUsedAgentId", "(", ")", ";", "}", "if", "(", "joinDirectBufferBo", ".", "getMinDirectMemoryUsed", "(", ")", "<", "minDirectMemoryUsed", ")", "{", "minDirectMemoryUsed", "=", "joinDirectBufferBo", ".", "getMinDirectMemoryUsed", "(", ")", ";", "minDirectMemoryUsedAgentId", "=", "joinDirectBufferBo", ".", "getMinDirectMemoryUsedAgentId", "(", ")", ";", "}", "sumMappedCount", "+=", "joinDirectBufferBo", ".", "getAvgMappedCount", "(", ")", ";", "if", "(", "joinDirectBufferBo", ".", "getMaxMappedCount", "(", ")", ">", "maxMappedCount", ")", "{", "maxMappedCount", "=", "joinDirectBufferBo", ".", "getMaxMappedCount", "(", ")", ";", "maxMappedCountAgentId", "=", "joinDirectBufferBo", ".", "getMaxMappedCountAgentId", "(", ")", ";", "}", "if", "(", "joinDirectBufferBo", ".", "getMinMappedCount", "(", ")", "<", "minMappedCount", ")", "{", "minMappedCount", "=", "joinDirectBufferBo", ".", "getMinMappedCount", "(", ")", ";", "minMappedCountAgentId", "=", "joinDirectBufferBo", ".", "getMinMappedCountAgentId", "(", ")", ";", "}", "sumMappedMemoryUsed", "+=", "joinDirectBufferBo", ".", "getAvgMappedMemoryUsed", "(", ")", ";", "if", "(", "joinDirectBufferBo", ".", "getMaxMappedMemoryUsed", "(", ")", ">", "maxMappedMemoryUsed", ")", "{", "maxMappedMemoryUsed", "=", "joinDirectBufferBo", ".", "getMaxMappedMemoryUsed", "(", ")", ";", "maxMappedMemoryUsedAgentId", "=", "joinDirectBufferBo", ".", "getMaxMappedMemoryUsedAgentId", "(", ")", ";", "}", "if", "(", "joinDirectBufferBo", ".", "getMinMappedMemoryUsed", "(", ")", "<", "minMappedMemoryUsed", ")", "{", "minMappedMemoryUsed", "=", "joinDirectBufferBo", ".", "getMinMappedMemoryUsed", "(", ")", ";", "minMappedMemoryUsedAgentId", "=", "joinDirectBufferBo", ".", "getMinMappedMemoryUsedAgentId", "(", ")", ";", "}", "}", "newJoinDirectBufferBo", ".", "setAvgDirectCount", "(", "(", "sumDirectCount", "/", "boCount", ")", ")", ";", "newJoinDirectBufferBo", ".", "setMaxDirectCount", "(", "maxDirectCount", ")", ";", "newJoinDirectBufferBo", ".", "setMaxDirectCountAgentId", "(", "maxDirectCountAgentId", ")", ";", "newJoinDirectBufferBo", ".", "setMinDirectCount", "(", "minDirectCount", ")", ";", "newJoinDirectBufferBo", ".", "setMinDirectCountAgentId", "(", "minDirectCountAgentId", ")", ";", "newJoinDirectBufferBo", ".", "setAvgDirectMemoryUsed", "(", "(", "sumDirectMemoryUsed", "/", "boCount", ")", ")", ";", "newJoinDirectBufferBo", ".", "setMaxDirectMemoryUsed", "(", "maxDirectMemoryUsed", ")", ";", "newJoinDirectBufferBo", ".", "setMaxDirectMemoryUsedAgentId", "(", "maxDirectMemoryUsedAgentId", ")", ";", "newJoinDirectBufferBo", ".", "setMinDirectMemoryUsed", "(", "minDirectMemoryUsed", ")", ";", "newJoinDirectBufferBo", ".", "setMinDirectMemoryUsedAgentId", "(", "minDirectMemoryUsedAgentId", ")", ";", "newJoinDirectBufferBo", ".", "setAvgMappedCount", "(", "(", "sumMappedCount", "/", "boCount", ")", ")", ";", "newJoinDirectBufferBo", ".", "setMaxMappedCount", "(", "maxMappedCount", ")", ";", "newJoinDirectBufferBo", ".", "setMaxMappedCountAgentId", "(", "maxMappedCountAgentId", ")", ";", "newJoinDirectBufferBo", ".", "setMinMappedCount", "(", "minMappedCount", ")", ";", "newJoinDirectBufferBo", ".", "setMinMappedCountAgentId", "(", "minMappedCountAgentId", ")", ";", "newJoinDirectBufferBo", ".", "setAvgMappedMemoryUsed", "(", "(", "sumMappedMemoryUsed", "/", "boCount", ")", ")", ";", "newJoinDirectBufferBo", ".", "setMaxMappedMemoryUsed", "(", "maxMappedMemoryUsed", ")", ";", "newJoinDirectBufferBo", ".", "setMaxMappedMemoryUsedAgentId", "(", "maxMappedMemoryUsedAgentId", ")", ";", "newJoinDirectBufferBo", ".", "setMinMappedMemoryUsed", "(", "minMappedMemoryUsed", ")", ";", "newJoinDirectBufferBo", ".", "setMinMappedMemoryUsedAgentId", "(", "minMappedMemoryUsedAgentId", ")", ";", "return", "newJoinDirectBufferBo", ";", "}", "@", "Override", "public", "String", "getId", "(", ")", "{", "return", "id", ";", "}", "public", "void", "setId", "(", "String", "id", ")", "{", "this", ".", "id", "=", "id", ";", "}", "@", "Override", "public", "long", "getTimestamp", "(", ")", "{", "return", "timestamp", ";", "}", "public", "void", "setTimestamp", "(", "long", "timestamp", ")", "{", "this", ".", "timestamp", "=", "timestamp", ";", "}", "public", "long", "getAvgDirectCount", "(", ")", "{", "return", "avgDirectCount", ";", "}", "public", "void", "setAvgDirectCount", "(", "long", "avgDirectCount", ")", "{", "this", ".", "avgDirectCount", "=", "avgDirectCount", ";", "}", "public", "String", "getMaxDirectCountAgentId", "(", ")", "{", "return", "maxDirectCountAgentId", ";", "}", "public", "void", "setMaxDirectCountAgentId", "(", "String", "maxDirectCountAgentId", ")", "{", "this", ".", "maxDirectCountAgentId", "=", "maxDirectCountAgentId", ";", "}", "public", "long", "getMaxDirectCount", "(", ")", "{", "return", "maxDirectCount", ";", "}", "public", "void", "setMaxDirectCount", "(", "long", "maxDirectCount", ")", "{", "this", ".", "maxDirectCount", "=", "maxDirectCount", ";", "}", "public", "String", "getMinDirectCountAgentId", "(", ")", "{", "return", "minDirectCountAgentId", ";", "}", "public", "void", "setMinDirectCountAgentId", "(", "String", "minDirectCountAgentId", ")", "{", "this", ".", "minDirectCountAgentId", "=", "minDirectCountAgentId", ";", "}", "public", "long", "getMinDirectCount", "(", ")", "{", "return", "minDirectCount", ";", "}", "public", "void", "setMinDirectCount", "(", "long", "minDirectCount", ")", "{", "this", ".", "minDirectCount", "=", "minDirectCount", ";", "}", "public", "long", "getAvgDirectMemoryUsed", "(", ")", "{", "return", "avgDirectMemoryUsed", ";", "}", "public", "void", "setAvgDirectMemoryUsed", "(", "long", "avgDirectMemoryUsed", ")", "{", "this", ".", "avgDirectMemoryUsed", "=", "avgDirectMemoryUsed", ";", "}", "public", "String", "getMaxDirectMemoryUsedAgentId", "(", ")", "{", "return", "maxDirectMemoryUsedAgentId", ";", "}", "public", "void", "setMaxDirectMemoryUsedAgentId", "(", "String", "maxDirectMemoryUsedAgentId", ")", "{", "this", ".", "maxDirectMemoryUsedAgentId", "=", "maxDirectMemoryUsedAgentId", ";", "}", "public", "long", "getMaxDirectMemoryUsed", "(", ")", "{", "return", "maxDirectMemoryUsed", ";", "}", "public", "void", "setMaxDirectMemoryUsed", "(", "long", "maxDirectMemoryUsed", ")", "{", "this", ".", "maxDirectMemoryUsed", "=", "maxDirectMemoryUsed", ";", "}", "public", "String", "getMinDirectMemoryUsedAgentId", "(", ")", "{", "return", "minDirectMemoryUsedAgentId", ";", "}", "public", "void", "setMinDirectMemoryUsedAgentId", "(", "String", "minDirectMemoryUsedAgentId", ")", "{", "this", ".", "minDirectMemoryUsedAgentId", "=", "minDirectMemoryUsedAgentId", ";", "}", "public", "long", "getMinDirectMemoryUsed", "(", ")", "{", "return", "minDirectMemoryUsed", ";", "}", "public", "void", "setMinDirectMemoryUsed", "(", "long", "minDirectMemoryUsed", ")", "{", "this", ".", "minDirectMemoryUsed", "=", "minDirectMemoryUsed", ";", "}", "public", "long", "getAvgMappedCount", "(", ")", "{", "return", "avgMappedCount", ";", "}", "public", "void", "setAvgMappedCount", "(", "long", "avgMappedCount", ")", "{", "this", ".", "avgMappedCount", "=", "avgMappedCount", ";", "}", "public", "String", "getMaxMappedCountAgentId", "(", ")", "{", "return", "maxMappedCountAgentId", ";", "}", "public", "void", "setMaxMappedCountAgentId", "(", "String", "maxMappedCountAgentId", ")", "{", "this", ".", "maxMappedCountAgentId", "=", "maxMappedCountAgentId", ";", "}", "public", "long", "getMaxMappedCount", "(", ")", "{", "return", "maxMappedCount", ";", "}", "public", "void", "setMaxMappedCount", "(", "long", "maxMappedCount", ")", "{", "this", ".", "maxMappedCount", "=", "maxMappedCount", ";", "}", "public", "String", "getMinMappedCountAgentId", "(", ")", "{", "return", "minMappedCountAgentId", ";", "}", "public", "void", "setMinMappedCountAgentId", "(", "String", "minMappedCountAgentId", ")", "{", "this", ".", "minMappedCountAgentId", "=", "minMappedCountAgentId", ";", "}", "public", "long", "getMinMappedCount", "(", ")", "{", "return", "minMappedCount", ";", "}", "public", "void", "setMinMappedCount", "(", "long", "minMappedCount", ")", "{", "this", ".", "minMappedCount", "=", "minMappedCount", ";", "}", "public", "long", "getAvgMappedMemoryUsed", "(", ")", "{", "return", "avgMappedMemoryUsed", ";", "}", "public", "void", "setAvgMappedMemoryUsed", "(", "long", "avgMappedMemoryUsed", ")", "{", "this", ".", "avgMappedMemoryUsed", "=", "avgMappedMemoryUsed", ";", "}", "public", "String", "getMaxMappedMemoryUsedAgentId", "(", ")", "{", "return", "maxMappedMemoryUsedAgentId", ";", "}", "public", "void", "setMaxMappedMemoryUsedAgentId", "(", "String", "maxMappedMemoryUsedAgentId", ")", "{", "this", ".", "maxMappedMemoryUsedAgentId", "=", "maxMappedMemoryUsedAgentId", ";", "}", "public", "long", "getMaxMappedMemoryUsed", "(", ")", "{", "return", "maxMappedMemoryUsed", ";", "}", "public", "void", "setMaxMappedMemoryUsed", "(", "long", "maxMappedMemoryUsed", ")", "{", "this", ".", "maxMappedMemoryUsed", "=", "maxMappedMemoryUsed", ";", "}", "public", "String", "getMinMappedMemoryUsedAgentId", "(", ")", "{", "return", "minMappedMemoryUsedAgentId", ";", "}", "public", "void", "setMinMappedMemoryUsedAgentId", "(", "String", "minMappedMemoryUsedAgentId", ")", "{", "this", ".", "minMappedMemoryUsedAgentId", "=", "minMappedMemoryUsedAgentId", ";", "}", "public", "long", "getMinMappedMemoryUsed", "(", ")", "{", "return", "minMappedMemoryUsed", ";", "}", "public", "void", "setMinMappedMemoryUsed", "(", "long", "minMappedMemoryUsed", ")", "{", "this", ".", "minMappedMemoryUsed", "=", "minMappedMemoryUsed", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "o", ")", "{", "if", "(", "this", "==", "o", ")", "return", "true", ";", "if", "(", "o", "==", "null", "||", "getClass", "(", ")", "!=", "o", ".", "getClass", "(", ")", ")", "return", "false", ";", "JoinDirectBufferBo", "that", "=", "(", "JoinDirectBufferBo", ")", "o", ";", "if", "(", "timestamp", "!=", "that", ".", "timestamp", ")", "return", "false", ";", "if", "(", "avgDirectCount", "!=", "that", ".", "avgDirectCount", ")", "return", "false", ";", "if", "(", "maxDirectCount", "!=", "that", ".", "maxDirectCount", ")", "return", "false", ";", "if", "(", "minDirectCount", "!=", "that", ".", "minDirectCount", ")", "return", "false", ";", "if", "(", "avgDirectMemoryUsed", "!=", "that", ".", "avgDirectMemoryUsed", ")", "return", "false", ";", "if", "(", "maxDirectMemoryUsed", "!=", "that", ".", "maxDirectMemoryUsed", ")", "return", "false", ";", "if", "(", "minDirectMemoryUsed", "!=", "that", ".", "minDirectMemoryUsed", ")", "return", "false", ";", "if", "(", "avgMappedCount", "!=", "that", ".", "avgMappedCount", ")", "return", "false", ";", "if", "(", "maxMappedCount", "!=", "that", ".", "maxMappedCount", ")", "return", "false", ";", "if", "(", "minMappedCount", "!=", "that", ".", "minMappedCount", ")", "return", "false", ";", "if", "(", "avgMappedMemoryUsed", "!=", "that", ".", "avgMappedMemoryUsed", ")", "return", "false", ";", "if", "(", "maxMappedMemoryUsed", "!=", "that", ".", "maxMappedMemoryUsed", ")", "return", "false", ";", "if", "(", "minMappedMemoryUsed", "!=", "that", ".", "minMappedMemoryUsed", ")", "return", "false", ";", "if", "(", "!", "id", ".", "equals", "(", "that", ".", "id", ")", ")", "return", "false", ";", "if", "(", "!", "maxDirectCountAgentId", ".", "equals", "(", "that", ".", "maxDirectCountAgentId", ")", ")", "return", "false", ";", "if", "(", "!", "minDirectCountAgentId", ".", "equals", "(", "that", ".", "minDirectCountAgentId", ")", ")", "return", "false", ";", "if", "(", "!", "maxDirectMemoryUsedAgentId", ".", "equals", "(", "that", ".", "maxDirectMemoryUsedAgentId", ")", ")", "return", "false", ";", "if", "(", "!", "minDirectMemoryUsedAgentId", ".", "equals", "(", "that", ".", "minDirectMemoryUsedAgentId", ")", ")", "return", "false", ";", "if", "(", "!", "maxMappedCountAgentId", ".", "equals", "(", "that", ".", "maxMappedCountAgentId", ")", ")", "return", "false", ";", "if", "(", "!", "minMappedCountAgentId", ".", "equals", "(", "that", ".", "minMappedCountAgentId", ")", ")", "return", "false", ";", "if", "(", "!", "maxMappedMemoryUsedAgentId", ".", "equals", "(", "that", ".", "maxMappedMemoryUsedAgentId", ")", ")", "return", "false", ";", "return", "minMappedMemoryUsedAgentId", ".", "equals", "(", "that", ".", "minMappedMemoryUsedAgentId", ")", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "int", "result", ";", "result", "=", "id", ".", "hashCode", "(", ")", ";", "result", "=", "31", "*", "result", "+", "(", "int", ")", "(", "timestamp", "^", "(", "timestamp", ">>>", "32", ")", ")", ";", "result", "=", "31", "*", "result", "+", "(", "int", ")", "(", "avgDirectCount", "^", "(", "avgDirectCount", ">>>", "32", ")", ")", ";", "result", "=", "31", "*", "result", "+", "maxDirectCountAgentId", ".", "hashCode", "(", ")", ";", "result", "=", "31", "*", "result", "+", "(", "int", ")", "(", "maxDirectCount", "^", "(", "maxDirectCount", ">>>", "32", ")", ")", ";", "result", "=", "31", "*", "result", "+", "minDirectCountAgentId", ".", "hashCode", "(", ")", ";", "result", "=", "31", "*", "result", "+", "(", "int", ")", "(", "minDirectCount", "^", "(", "minDirectCount", ">>>", "32", ")", ")", ";", "result", "=", "31", "*", "result", "+", "(", "int", ")", "(", "avgDirectMemoryUsed", "^", "(", "avgDirectMemoryUsed", ">>>", "32", ")", ")", ";", "result", "=", "31", "*", "result", "+", "maxDirectMemoryUsedAgentId", ".", "hashCode", "(", ")", ";", "result", "=", "31", "*", "result", "+", "(", "int", ")", "(", "maxDirectMemoryUsed", "^", "(", "maxDirectMemoryUsed", ">>>", "32", ")", ")", ";", "result", "=", "31", "*", "result", "+", "minDirectMemoryUsedAgentId", ".", "hashCode", "(", ")", ";", "result", "=", "31", "*", "result", "+", "(", "int", ")", "(", "minDirectMemoryUsed", "^", "(", "minDirectMemoryUsed", ">>>", "32", ")", ")", ";", "result", "=", "31", "*", "result", "+", "(", "int", ")", "(", "avgMappedCount", "^", "(", "avgMappedCount", ">>>", "32", ")", ")", ";", "result", "=", "31", "*", "result", "+", "maxMappedCountAgentId", ".", "hashCode", "(", ")", ";", "result", "=", "31", "*", "result", "+", "(", "int", ")", "(", "maxMappedCount", "^", "(", "maxMappedCount", ">>>", "32", ")", ")", ";", "result", "=", "31", "*", "result", "+", "minMappedCountAgentId", ".", "hashCode", "(", ")", ";", "result", "=", "31", "*", "result", "+", "(", "int", ")", "(", "minMappedCount", "^", "(", "minMappedCount", ">>>", "32", ")", ")", ";", "result", "=", "31", "*", "result", "+", "(", "int", ")", "(", "avgMappedMemoryUsed", "^", "(", "avgMappedMemoryUsed", ">>>", "32", ")", ")", ";", "result", "=", "31", "*", "result", "+", "maxMappedMemoryUsedAgentId", ".", "hashCode", "(", ")", ";", "result", "=", "31", "*", "result", "+", "(", "int", ")", "(", "maxMappedMemoryUsed", "^", "(", "maxMappedMemoryUsed", ">>>", "32", ")", ")", ";", "result", "=", "31", "*", "result", "+", "minMappedMemoryUsedAgentId", ".", "hashCode", "(", ")", ";", "result", "=", "31", "*", "result", "+", "(", "int", ")", "(", "minMappedMemoryUsed", "^", "(", "minMappedMemoryUsed", ">>>", "32", ")", ")", ";", "return", "result", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "JoinDirectBufferBo{", "\"", "+", "\"", "id='", "\"", "+", "id", "+", "'\\''", "+", "\"", ", avgDirectCount=", "\"", "+", "avgDirectCount", "+", "\"", ", maxDirectCountAgentId='", "\"", "+", "maxDirectCountAgentId", "+", "'\\''", "+", "\"", ", maxDirectCount=", "\"", "+", "maxDirectCount", "+", "\"", ", minDirectCountAgentId='", "\"", "+", "minDirectCountAgentId", "+", "'\\''", "+", "\"", ", minDirectCount=", "\"", "+", "minDirectCount", "+", "\"", ", avgDirectMemoryUsed=", "\"", "+", "avgDirectMemoryUsed", "+", "\"", ", maxDirectMemoryUsedAgentId='", "\"", "+", "maxDirectMemoryUsedAgentId", "+", "'\\''", "+", "\"", ", maxDirectMemoryUsed=", "\"", "+", "maxDirectMemoryUsed", "+", "\"", ", minDirectMemoryUsedAgentId='", "\"", "+", "minDirectMemoryUsedAgentId", "+", "'\\''", "+", "\"", ", minDirectMemoryUsed=", "\"", "+", "minDirectMemoryUsed", "+", "\"", ", avgMappedCount=", "\"", "+", "avgMappedCount", "+", "\"", ", maxMappedCountAgentId='", "\"", "+", "maxMappedCountAgentId", "+", "'\\''", "+", "\"", ", maxMappedCount=", "\"", "+", "maxMappedCount", "+", "\"", ", minMappedCountAgentId='", "\"", "+", "minMappedCountAgentId", "+", "'\\''", "+", "\"", ", minMappedCount=", "\"", "+", "minMappedCount", "+", "\"", ", avgMappedMemoryUsed=", "\"", "+", "avgMappedMemoryUsed", "+", "\"", ", maxMappedMemoryUsedAgentId='", "\"", "+", "maxMappedMemoryUsedAgentId", "+", "'\\''", "+", "\"", ", maxMappedMemoryUsed=", "\"", "+", "maxMappedMemoryUsed", "+", "\"", ", minMappedMemoryUsedAgentId='", "\"", "+", "minMappedMemoryUsedAgentId", "+", "'\\''", "+", "\"", ", minMappedMemoryUsed=", "\"", "+", "minMappedMemoryUsed", "+", "\"", ", timestamp=", "\"", "+", "timestamp", "+", "\"", "(", "\"", "+", "new", "Date", "(", "timestamp", ")", "+", "\"", ")", "\"", "+", "'}'", ";", "}", "}" ]
@author Roy Kim
[ "@author", "Roy", "Kim" ]
[]
[ { "param": "JoinStatBo", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "JoinStatBo", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c408510c02c8344b8b1fdd9fc31d2519fdbf2171
wwjiang007/falcon
common/src/main/java/org/apache/falcon/persistence/ProcessInstanceInfoBean.java
[ "Apache-2.0" ]
Java
ProcessInstanceInfoBean
/** * Class to store info regarding process history. */
Class to store info regarding process history.
[ "Class", "to", "store", "info", "regarding", "process", "history", "." ]
@Entity @NamedQueries({ @NamedQuery(name= PersistenceConstants.GET_ALL_PROCESS_INFO_INSTANCES , query = "select OBJECT(a) from ProcessInstanceInfoBean a ") }) @Table(name = "ProcessInstanceInfo") //RESUME CHECKSTYLE CHECK LineLengthCheck public class ProcessInstanceInfoBean { @NotNull @GeneratedValue(strategy = GenerationType.AUTO) @Id private String id; @NotNull @Column(name = "process_name") private String processName; @NotNull @Column(name = "colo") private String colo; public String getPipeline() { return pipeline; } public void setPipeline(String pipeline) { this.pipeline = pipeline; } @NotNull @Column(name = "pipeline") private String pipeline; @NotNull @Column(name = "status") private String status; @NotNull @Column(name = "nominal_time") private Date nominalTime; @NotNull @Column(name = "start_delay") private long startDelay; @NotNull @Column(name = "processing_time") private long processingTime; public Date getNominalTime() { return nominalTime; } public void setNominalTime(Date nominalTime) { this.nominalTime = nominalTime; } public String getProcessName() { return processName; } public void setProcessName(String processName) { this.processName = processName; } public String getColo() { return colo; } public void setColo(String colo) { this.colo = colo; } public long getStartDelay() { return startDelay; } public void setStartDelay(long startDelay) { this.startDelay = startDelay; } public long getProcessingTime() { return processingTime; } public void setProcessingTime(long processingTime) { this.processingTime = processingTime; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
[ "@", "Entity", "@", "NamedQueries", "(", "{", "@", "NamedQuery", "(", "name", "=", "PersistenceConstants", ".", "GET_ALL_PROCESS_INFO_INSTANCES", ",", "query", "=", "\"", "select OBJECT(a) from ProcessInstanceInfoBean a ", "\"", ")", "}", ")", "@", "Table", "(", "name", "=", "\"", "ProcessInstanceInfo", "\"", ")", "public", "class", "ProcessInstanceInfoBean", "{", "@", "NotNull", "@", "GeneratedValue", "(", "strategy", "=", "GenerationType", ".", "AUTO", ")", "@", "Id", "private", "String", "id", ";", "@", "NotNull", "@", "Column", "(", "name", "=", "\"", "process_name", "\"", ")", "private", "String", "processName", ";", "@", "NotNull", "@", "Column", "(", "name", "=", "\"", "colo", "\"", ")", "private", "String", "colo", ";", "public", "String", "getPipeline", "(", ")", "{", "return", "pipeline", ";", "}", "public", "void", "setPipeline", "(", "String", "pipeline", ")", "{", "this", ".", "pipeline", "=", "pipeline", ";", "}", "@", "NotNull", "@", "Column", "(", "name", "=", "\"", "pipeline", "\"", ")", "private", "String", "pipeline", ";", "@", "NotNull", "@", "Column", "(", "name", "=", "\"", "status", "\"", ")", "private", "String", "status", ";", "@", "NotNull", "@", "Column", "(", "name", "=", "\"", "nominal_time", "\"", ")", "private", "Date", "nominalTime", ";", "@", "NotNull", "@", "Column", "(", "name", "=", "\"", "start_delay", "\"", ")", "private", "long", "startDelay", ";", "@", "NotNull", "@", "Column", "(", "name", "=", "\"", "processing_time", "\"", ")", "private", "long", "processingTime", ";", "public", "Date", "getNominalTime", "(", ")", "{", "return", "nominalTime", ";", "}", "public", "void", "setNominalTime", "(", "Date", "nominalTime", ")", "{", "this", ".", "nominalTime", "=", "nominalTime", ";", "}", "public", "String", "getProcessName", "(", ")", "{", "return", "processName", ";", "}", "public", "void", "setProcessName", "(", "String", "processName", ")", "{", "this", ".", "processName", "=", "processName", ";", "}", "public", "String", "getColo", "(", ")", "{", "return", "colo", ";", "}", "public", "void", "setColo", "(", "String", "colo", ")", "{", "this", ".", "colo", "=", "colo", ";", "}", "public", "long", "getStartDelay", "(", ")", "{", "return", "startDelay", ";", "}", "public", "void", "setStartDelay", "(", "long", "startDelay", ")", "{", "this", ".", "startDelay", "=", "startDelay", ";", "}", "public", "long", "getProcessingTime", "(", ")", "{", "return", "processingTime", ";", "}", "public", "void", "setProcessingTime", "(", "long", "processingTime", ")", "{", "this", ".", "processingTime", "=", "processingTime", ";", "}", "public", "String", "getStatus", "(", ")", "{", "return", "status", ";", "}", "public", "void", "setStatus", "(", "String", "status", ")", "{", "this", ".", "status", "=", "status", ";", "}", "}" ]
Class to store info regarding process history.
[ "Class", "to", "store", "info", "regarding", "process", "history", "." ]
[ "//RESUME CHECKSTYLE CHECK LineLengthCheck" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c409726b25443e67264c1c0ea208cdccc6f49bc6
daniilsorokin/language-identifier
src/main/java/de/nlptools/languageid/classifiers/EvaluationResult.java
[ "MIT" ]
Java
EvaluationResult
/** * The class is used to store results of a classifier evaluation. * * @author Daniil Sorokin <daniil.sorokin@uni-tuebingen.de> */
The class is used to store results of a classifier evaluation. @author Daniil Sorokin
[ "The", "class", "is", "used", "to", "store", "results", "of", "a", "classifier", "evaluation", ".", "@author", "Daniil", "Sorokin" ]
public class EvaluationResult { private double accuracy; public EvaluationResult(double accuracy) { this.accuracy = accuracy; } public double getAccuracy() { return accuracy; } }
[ "public", "class", "EvaluationResult", "{", "private", "double", "accuracy", ";", "public", "EvaluationResult", "(", "double", "accuracy", ")", "{", "this", ".", "accuracy", "=", "accuracy", ";", "}", "public", "double", "getAccuracy", "(", ")", "{", "return", "accuracy", ";", "}", "}" ]
The class is used to store results of a classifier evaluation.
[ "The", "class", "is", "used", "to", "store", "results", "of", "a", "classifier", "evaluation", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c40eb82970b03c107f441239f297cbe26c8ce5e6
vcellmike/Biosimulators_VCell
vcell-core/src/main/java/cbit/vcell/math/FastInvariant.java
[ "MIT" ]
Java
FastInvariant
/** * This class was generated by a SmartGuide. * */
This class was generated by a SmartGuide.
[ "This", "class", "was", "generated", "by", "a", "SmartGuide", "." ]
public class FastInvariant extends BoundFunction{ /** * FastInvariant constructor comment. * @param mathDesc cbit.vcell.math.MathDescription * @param function cbit.vcell.parser.Expression */ public FastInvariant(Expression function) { super(function); } public boolean compareEqual(Matchable obj) { if (!(obj instanceof FastInvariant)) return false; return compareEqual0(obj); } }
[ "public", "class", "FastInvariant", "extends", "BoundFunction", "{", "/**\r\n * FastInvariant constructor comment.\r\n * @param mathDesc cbit.vcell.math.MathDescription\r\n * @param function cbit.vcell.parser.Expression\r\n */", "public", "FastInvariant", "(", "Expression", "function", ")", "{", "super", "(", "function", ")", ";", "}", "public", "boolean", "compareEqual", "(", "Matchable", "obj", ")", "{", "if", "(", "!", "(", "obj", "instanceof", "FastInvariant", ")", ")", "return", "false", ";", "return", "compareEqual0", "(", "obj", ")", ";", "}", "}" ]
This class was generated by a SmartGuide.
[ "This", "class", "was", "generated", "by", "a", "SmartGuide", "." ]
[]
[ { "param": "BoundFunction", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BoundFunction", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c40f06816791cad26dfbd8b486bc71cc2ee827a2
steinwurf/score-android
source/src/main/java/com/steinwurf/score/source/AutoSource.java
[ "BSD-Source-Code" ]
Java
AutoSource
/** * <h1>Handle to a native Manual Score Source</h1> * AutoSource wraps a native source object and gives access to its data members. */
Handle to a native Manual Score Source AutoSource wraps a native source object and gives access to its data members.
[ "Handle", "to", "a", "native", "Manual", "Score", "Source", "AutoSource", "wraps", "a", "native", "source", "object", "and", "gives", "access", "to", "its", "data", "members", "." ]
@SuppressWarnings("JniMissingFunction") public class AutoSource extends Source { static { // Load the native source library System.loadLibrary("auto_source_jni"); } /** * A long representing a pointer to the underlying native object. */ private final long pointer; /** * Construct AutoSource object. */ public AutoSource() { pointer = init(); } /** * Construct a native Score source and returns a long value which represents * the pointer of the created object. */ private static native long init(); @Override public native void readMessage(byte[] buffer, int offset, int size); @Override public native void flush(); @Override public native boolean hasDataPacket(); @Override public native byte[] nativeGetDataPacket(); @Override public native void readSnackPacket(byte[] buffer, int offset, int size) throws InvalidSnackPacketException; @Override public native int generationWindowSize(); @Override public native float dataRedundancy(); @Override public native float feedbackProbability(); @Override public native int symbolSize(); @Override public native int generationSize(); /** * Set the maximum data redundancy that can be used * @param data_redundancy new value for max redundancy, must be greater than or equal to 0 */ public void setMaxDataRedundancy(float data_redundancy) { if (data_redundancy < 0) throw new IllegalArgumentException(data_redundancy + " < 0"); nativeSetMaxDataRedundancy(data_redundancy); } private native void nativeSetMaxDataRedundancy(float data_redundancy); /** * The maximum data redundancy that can be used * @return the maximum data redundancy that can be used */ public native float maxDataRedundancy(); /** * Set the gain used to automatically adjust the data redundancy, a * higher value will track changes faster but also result in a less * steady redundancy level * @param gain float in the range ]0,1]. */ public void setDataRedundancyEstimationGain(float gain) { if (gain < 0) throw new IllegalArgumentException(gain + " < 0"); nativeSetDataRedundancyEstimationGain(gain); } private native void nativeSetDataRedundancyEstimationGain(float gain); /** * The gain used to automatically adjust the data redundancy * @return the gain used to automatically adjust the data redundancy */ public native float dataRedundancyEstimationGain(); /** * Set the target number of snacks the source would like to read * per generation * @param snacks the number of target snacks per generation */ public void setTargetSnacksPerGeneration(int snacks) { if (snacks < 0) throw new IllegalArgumentException(snacks + " < 0"); nativeSetTargetSnacksPerGeneration(snacks); } private native void nativeSetTargetSnacksPerGeneration(int snacks); /** * The number of snacks the source would like to read per generation * @return Desired number of snacks per generation */ public native int targetSnacksPerGeneration(); /** * Set the minimum feedback probability that can be used * @param probability the min feedback probability */ public void setMinFeedbackProbability(float probability) { if (probability < 0) throw new IllegalArgumentException(probability + " < 0"); nativeSetMinFeedbackProbability(probability); } private native void nativeSetMinFeedbackProbability(float probability); /** * The minimum feedback probability that can be used * @return Minimum feedback probability */ public native float minFeedbackProbability(); /** * Set the maximum feedback probability that can be used * @param probability the max feedback probability */ public void setMaxFeedbackProbability(float probability) { if (probability < 0) throw new IllegalArgumentException(probability + " < 0"); nativeSetMaxFeedbackProbability(probability); } private native void nativeSetMaxFeedbackProbability(float probability); /** * The maximum feedback probability that can be used * @return Maximum feedback probability */ public native float maxFeedbackProbability(); /** * Set the gain used to automatically adjust the data redundancy, a * higher value will track changes faster but also result in a less * steady redundancy level * @param gain float in the range ]0,1], default 0.2 */ public void setFeedbackProbabilityGain(float gain) { if (gain < 0) throw new IllegalArgumentException(gain + " < 0"); nativeSetFeedbackProbabilityGain(gain); } private native void nativeSetFeedbackProbabilityGain(float gain); /** * The gain used to automatically adjust the feedback probability * @return Feedback probability gain */ public native float feedbackProbabilityGain(); /** * Set the target repair delay in milliseconds * @param milliseconds_delay the target repair delay in milliseconds */ public void setTargetRepairDelay(int milliseconds_delay) { if (milliseconds_delay < 0) throw new IllegalArgumentException(milliseconds_delay + " < 0"); nativeSetTargetRepairDelay(milliseconds_delay); } private native void nativeSetTargetRepairDelay(int milliseconds_delay); /** * The target repair delay in milliseconds * @return Target repair delay in milliseconds */ public native int targetRepairDelay(); /** * Set the symbol size. * Has no effect on current active encoders. * @param size the symbols size in bytes */ public void setSymbolSize(int size) { // The symbol size must be bigger than the serialization header if (size < 4) throw new IllegalArgumentException(size + " < 4"); nativeSetSymbolSize(size); } private native void nativeSetSymbolSize(int size); /** * Set the generation size. * Has no effect on current active encoders * @param symbols the number of symbols in the next created generation */ public void setGenerationSize(int symbols) { if (symbols < 0) throw new IllegalArgumentException(symbols + " < 0"); nativeSetGenerationSize(symbols); } private native void nativeSetGenerationSize(int symbols); /** * Finalizes the object and it's underlying native part. */ @Override protected void finalize() throws Throwable { finalize(pointer); super.finalize(); } /** * Finalizes the underlying native part. * @param pointer A long representing a pointer to the underlying native object. */ private native void finalize(long pointer); }
[ "@", "SuppressWarnings", "(", "\"", "JniMissingFunction", "\"", ")", "public", "class", "AutoSource", "extends", "Source", "{", "static", "{", "System", ".", "loadLibrary", "(", "\"", "auto_source_jni", "\"", ")", ";", "}", "/**\n * A long representing a pointer to the underlying native object.\n */", "private", "final", "long", "pointer", ";", "/**\n * Construct AutoSource object.\n */", "public", "AutoSource", "(", ")", "{", "pointer", "=", "init", "(", ")", ";", "}", "/**\n * Construct a native Score source and returns a long value which represents\n * the pointer of the created object.\n */", "private", "static", "native", "long", "init", "(", ")", ";", "@", "Override", "public", "native", "void", "readMessage", "(", "byte", "[", "]", "buffer", ",", "int", "offset", ",", "int", "size", ")", ";", "@", "Override", "public", "native", "void", "flush", "(", ")", ";", "@", "Override", "public", "native", "boolean", "hasDataPacket", "(", ")", ";", "@", "Override", "public", "native", "byte", "[", "]", "nativeGetDataPacket", "(", ")", ";", "@", "Override", "public", "native", "void", "readSnackPacket", "(", "byte", "[", "]", "buffer", ",", "int", "offset", ",", "int", "size", ")", "throws", "InvalidSnackPacketException", ";", "@", "Override", "public", "native", "int", "generationWindowSize", "(", ")", ";", "@", "Override", "public", "native", "float", "dataRedundancy", "(", ")", ";", "@", "Override", "public", "native", "float", "feedbackProbability", "(", ")", ";", "@", "Override", "public", "native", "int", "symbolSize", "(", ")", ";", "@", "Override", "public", "native", "int", "generationSize", "(", ")", ";", "/**\n * Set the maximum data redundancy that can be used\n * @param data_redundancy new value for max redundancy, must be greater than or equal to 0\n */", "public", "void", "setMaxDataRedundancy", "(", "float", "data_redundancy", ")", "{", "if", "(", "data_redundancy", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "data_redundancy", "+", "\"", " < 0", "\"", ")", ";", "nativeSetMaxDataRedundancy", "(", "data_redundancy", ")", ";", "}", "private", "native", "void", "nativeSetMaxDataRedundancy", "(", "float", "data_redundancy", ")", ";", "/**\n * The maximum data redundancy that can be used\n * @return the maximum data redundancy that can be used\n */", "public", "native", "float", "maxDataRedundancy", "(", ")", ";", "/**\n * Set the gain used to automatically adjust the data redundancy, a\n * higher value will track changes faster but also result in a less\n * steady redundancy level\n * @param gain float in the range ]0,1].\n */", "public", "void", "setDataRedundancyEstimationGain", "(", "float", "gain", ")", "{", "if", "(", "gain", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "gain", "+", "\"", " < 0", "\"", ")", ";", "nativeSetDataRedundancyEstimationGain", "(", "gain", ")", ";", "}", "private", "native", "void", "nativeSetDataRedundancyEstimationGain", "(", "float", "gain", ")", ";", "/**\n * The gain used to automatically adjust the data redundancy\n * @return the gain used to automatically adjust the data redundancy\n */", "public", "native", "float", "dataRedundancyEstimationGain", "(", ")", ";", "/**\n * Set the target number of snacks the source would like to read\n * per generation\n * @param snacks the number of target snacks per generation\n */", "public", "void", "setTargetSnacksPerGeneration", "(", "int", "snacks", ")", "{", "if", "(", "snacks", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "snacks", "+", "\"", " < 0", "\"", ")", ";", "nativeSetTargetSnacksPerGeneration", "(", "snacks", ")", ";", "}", "private", "native", "void", "nativeSetTargetSnacksPerGeneration", "(", "int", "snacks", ")", ";", "/**\n * The number of snacks the source would like to read per generation\n * @return Desired number of snacks per generation\n */", "public", "native", "int", "targetSnacksPerGeneration", "(", ")", ";", "/**\n * Set the minimum feedback probability that can be used\n * @param probability the min feedback probability\n */", "public", "void", "setMinFeedbackProbability", "(", "float", "probability", ")", "{", "if", "(", "probability", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "probability", "+", "\"", " < 0", "\"", ")", ";", "nativeSetMinFeedbackProbability", "(", "probability", ")", ";", "}", "private", "native", "void", "nativeSetMinFeedbackProbability", "(", "float", "probability", ")", ";", "/**\n * The minimum feedback probability that can be used\n * @return Minimum feedback probability\n */", "public", "native", "float", "minFeedbackProbability", "(", ")", ";", "/**\n * Set the maximum feedback probability that can be used\n * @param probability the max feedback probability\n */", "public", "void", "setMaxFeedbackProbability", "(", "float", "probability", ")", "{", "if", "(", "probability", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "probability", "+", "\"", " < 0", "\"", ")", ";", "nativeSetMaxFeedbackProbability", "(", "probability", ")", ";", "}", "private", "native", "void", "nativeSetMaxFeedbackProbability", "(", "float", "probability", ")", ";", "/**\n * The maximum feedback probability that can be used\n * @return Maximum feedback probability\n */", "public", "native", "float", "maxFeedbackProbability", "(", ")", ";", "/**\n * Set the gain used to automatically adjust the data redundancy, a\n * higher value will track changes faster but also result in a less\n * steady redundancy level\n * @param gain float in the range ]0,1], default 0.2\n */", "public", "void", "setFeedbackProbabilityGain", "(", "float", "gain", ")", "{", "if", "(", "gain", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "gain", "+", "\"", " < 0", "\"", ")", ";", "nativeSetFeedbackProbabilityGain", "(", "gain", ")", ";", "}", "private", "native", "void", "nativeSetFeedbackProbabilityGain", "(", "float", "gain", ")", ";", "/**\n * The gain used to automatically adjust the feedback probability\n * @return Feedback probability gain\n */", "public", "native", "float", "feedbackProbabilityGain", "(", ")", ";", "/**\n * Set the target repair delay in milliseconds\n * @param milliseconds_delay the target repair delay in milliseconds\n */", "public", "void", "setTargetRepairDelay", "(", "int", "milliseconds_delay", ")", "{", "if", "(", "milliseconds_delay", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "milliseconds_delay", "+", "\"", " < 0", "\"", ")", ";", "nativeSetTargetRepairDelay", "(", "milliseconds_delay", ")", ";", "}", "private", "native", "void", "nativeSetTargetRepairDelay", "(", "int", "milliseconds_delay", ")", ";", "/**\n * The target repair delay in milliseconds\n * @return Target repair delay in milliseconds\n */", "public", "native", "int", "targetRepairDelay", "(", ")", ";", "/**\n * Set the symbol size.\n * Has no effect on current active encoders.\n * @param size the symbols size in bytes\n */", "public", "void", "setSymbolSize", "(", "int", "size", ")", "{", "if", "(", "size", "<", "4", ")", "throw", "new", "IllegalArgumentException", "(", "size", "+", "\"", " < 4", "\"", ")", ";", "nativeSetSymbolSize", "(", "size", ")", ";", "}", "private", "native", "void", "nativeSetSymbolSize", "(", "int", "size", ")", ";", "/**\n * Set the generation size.\n * Has no effect on current active encoders\n * @param symbols the number of symbols in the next created generation\n */", "public", "void", "setGenerationSize", "(", "int", "symbols", ")", "{", "if", "(", "symbols", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "symbols", "+", "\"", " < 0", "\"", ")", ";", "nativeSetGenerationSize", "(", "symbols", ")", ";", "}", "private", "native", "void", "nativeSetGenerationSize", "(", "int", "symbols", ")", ";", "/**\n * Finalizes the object and it's underlying native part.\n */", "@", "Override", "protected", "void", "finalize", "(", ")", "throws", "Throwable", "{", "finalize", "(", "pointer", ")", ";", "super", ".", "finalize", "(", ")", ";", "}", "/**\n * Finalizes the underlying native part.\n * @param pointer A long representing a pointer to the underlying native object.\n */", "private", "native", "void", "finalize", "(", "long", "pointer", ")", ";", "}" ]
<h1>Handle to a native Manual Score Source</h1> AutoSource wraps a native source object and gives access to its data members.
[ "<h1", ">", "Handle", "to", "a", "native", "Manual", "Score", "Source<", "/", "h1", ">", "AutoSource", "wraps", "a", "native", "source", "object", "and", "gives", "access", "to", "its", "data", "members", "." ]
[ "// Load the native source library", "// The symbol size must be bigger than the serialization header" ]
[ { "param": "Source", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Source", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c41b48341c99c602dcd5f6edee8ffb192d18b179
sriThariduSangeeth/kore-chatbot-modernization-mobile
BotsSDK/korebotsdklib/src/main/java/kore/botssdk/websocket/SocketWrapper.java
[ "MIT" ]
Java
SocketWrapper
/** * Created by Ramachandra Pradeep on 6/1/2016. * Copyright (c) 2014 Kore Inc. All rights reserved. */
Created by Ramachandra Pradeep on 6/1/2016. Copyright (c) 2014 Kore Inc. All rights reserved.
[ "Created", "by", "Ramachandra", "Pradeep", "on", "6", "/", "1", "/", "2016", ".", "Copyright", "(", "c", ")", "2014", "Kore", "Inc", ".", "All", "rights", "reserved", "." ]
public final class SocketWrapper{ private final String LOG_TAG = "SocketWrapper";// public static SocketWrapper pKorePresenceInstance; private SocketConnectionListener socketConnectionListener = null; // private final WebSocketConnection mConnection = new WebSocketConnection(); private final IWebSocket mConnection = new WebSocketConnection(); private static Timer timer = new Timer(); public boolean ismIsReconnectionAttemptNeeded() { return mIsReconnectionAttemptNeeded; } public void shouldAttemptToReconnect(boolean mIsReconnectionAttemptNeeded) { this.mIsReconnectionAttemptNeeded = mIsReconnectionAttemptNeeded; } private boolean mIsReconnectionAttemptNeeded = true; private boolean isConnecting = false; // private String url; // private URI uri; // private boolean mTLSEnabled = false; private HashMap<String, Object> optParameterBotInfo; private String accessToken; private String userAccessToken = null; private String anonymousUserAccessToken = null; private String JWTToken; private String auth; private String botUserId; public BotInfoModel getBotInfoModel() { return botInfoModel; } public void setBotInfoModel(BotInfoModel botInfoModel) { this.botInfoModel = botInfoModel; } private BotInfoModel botInfoModel; private BotSocketOptions options; private Context mContext; /** * initial reconnection delay 1 Sec */ private int mReconnectDelay = 1000; /** * initial reconnection count */ private int mReconnectionCount = 0; /** * Restricting outside object creation */ private SocketWrapper(Context mContext) { // start(mContext); this.mContext = mContext; // KoreEventCenter.register(this); } public String getAccessToken(){ return auth; } /** * The global default SocketWrapper instance */ public static SocketWrapper getInstance(Context mContext) { if (pKorePresenceInstance == null) { // synchronized (SocketWrapper.class) { // if(pKorePresenceInstance == null) { pKorePresenceInstance = new SocketWrapper(mContext); // } // } } return pKorePresenceInstance; } /** * To prevent cloning * * @return * @throws CloneNotSupportedException */ @Override protected Object clone() throws CloneNotSupportedException { return new CloneNotSupportedException("Clone not supported"); } // final RestAPI restAPI = BotRestBuilder.getBotRestService(); private Observable<RestResponse.RTMUrl> getRtmUrl(String accessToken,final BotInfoModel botInfoModel){ return Observable.create(new ObservableOnSubscribe<RestResponse.RTMUrl>() { @Override public void subscribe(ObservableEmitter<RestResponse.RTMUrl> observableEmitter) throws Exception { try { Call<RestResponse.JWTTokenResponse> jwtTokenResponseCall = BotRestBuilder.getBotRestService().getJWTToken("bearer " + accessToken); Response<RestResponse.JWTTokenResponse> jwtTokenResponseResponse = jwtTokenResponseCall.execute(); HashMap<String, Object> hsh = new HashMap<>(); hsh.put(Constants.KEY_ASSERTION, jwtTokenResponseResponse.body().getJwt()); hsh.put(Constants.BOT_INFO, botInfoModel); Call<RestResponse.BotAuthorization> botAuthorizationCall = BotRestBuilder.getBotRestService().jwtGrant(hsh); Response<RestResponse.BotAuthorization> botAuthorizationResponse = botAuthorizationCall.execute(); auth = botAuthorizationResponse.body().getAuthorization().getAccessToken(); botUserId = botAuthorizationResponse.body().getUserInfo().getUserId(); Call<RestResponse.RTMUrl> rtmUrlCall = BotRestBuilder.getBotRestService().getRtmUrl("bearer " + botAuthorizationResponse.body().getAuthorization().getAccessToken(), optParameterBotInfo); Response<RestResponse.RTMUrl> rtmUrlResponse = rtmUrlCall.execute(); observableEmitter.onNext(rtmUrlResponse.body()); observableEmitter.onComplete(); } catch (Exception e) { observableEmitter.onError(e); } } }); /*return BotRestBuilder.getBotRestService().getJWTToken("bearer " + accessToken).flatMap(new Function<RestResponse.JWTTokenResponse, ObservableSource<RestResponse.BotAuthorization>>() { @Override public ObservableSource<RestResponse.BotAuthorization> apply(RestResponse.JWTTokenResponse jwtTokenResponse) throws Exception { HashMap<String, Object> hsh = new HashMap<>(); hsh.put(Constants.KEY_ASSERTION, jwtTokenResponse.getJwt()); hsh.put(Constants.BOT_INFO, botInfoModel); return BotRestBuilder.getBotRestService().jwtGrant(hsh); } }).flatMap(new Function<RestResponse.BotAuthorization, ObservableSource<RestResponse.RTMUrl>>() { @Override public ObservableSource<RestResponse.RTMUrl> apply(RestResponse.BotAuthorization botAuthorization) throws Exception { auth = botAuthorization.getAuthorization().getAccessToken(); botUserId = botAuthorization.getUserInfo().getUserId(); return BotRestBuilder.getBotRestService().getRtmUrl("bearer " + botAuthorization.getAuthorization().getAccessToken(), optParameterBotInfo); } });*/ } //TODO For speed connection private Observable<RestResponse.RTMUrl> getRtmUrlForConnectAnonymous(final String sJwtGrant, final BotInfoModel botInfoModel){ return Observable.create(new ObservableOnSubscribe<RestResponse.RTMUrl>() { @Override public void subscribe(ObservableEmitter<RestResponse.RTMUrl> observableEmitter) throws Exception { try { HashMap<String, Object> hsh = new HashMap<>(); hsh.put(Constants.KEY_ASSERTION, sJwtGrant); hsh.put(Constants.BOT_INFO, botInfoModel); Call<RestResponse.BotAuthorization> botAuthorizationCall = BotRestBuilder.getBotRestService().jwtGrant(hsh); Response<RestResponse.BotAuthorization> botAuthorizationResponse = botAuthorizationCall.execute(); HashMap<String, Object> hsh1 = new HashMap<>(); hsh1.put(Constants.BOT_INFO, botInfoModel); botUserId = botAuthorizationResponse.body().getUserInfo().getUserId(); auth = botAuthorizationResponse.body().getAuthorization().getAccessToken(); Call<RestResponse.RTMUrl> rtmUrlCall = BotRestBuilder.getBotRestService().getRtmUrl("bearer " + botAuthorizationResponse.body().getAuthorization().getAccessToken(), hsh1); Response<RestResponse.RTMUrl> rtmUrlResponse = rtmUrlCall.execute(); observableEmitter.onNext(rtmUrlResponse.body()); observableEmitter.onComplete(); } catch (Exception e) { observableEmitter.onError(e); } } }); /*return BotRestBuilder.getBotRestService().jwtGrant(hsh).flatMap(new Function<RestResponse.BotAuthorization, ObservableSource<RestResponse.RTMUrl>>() { @Override public ObservableSource<RestResponse.RTMUrl> apply(RestResponse.BotAuthorization botAuthorization) throws Exception { HashMap<String, Object> hsh1 = new HashMap<>(); hsh1.put(Constants.BOT_INFO, botInfoModel); botUserId = botAuthorization.getUserInfo().getUserId(); auth = botAuthorization.getAuthorization().getAccessToken(); return BotRestBuilder.getBotRestService().getRtmUrl("bearer " + botAuthorization.getAuthorization().getAccessToken(), hsh1); } });*/ } /** * Method to invoke connection for authenticated user * * @param accessToken : AccessToken of the loged user. */ public void connect(String accessToken,final BotInfoModel botInfoModel,SocketConnectionListener socketConnectionListener) { this.botInfoModel = botInfoModel; this.socketConnectionListener = socketConnectionListener; this.accessToken = accessToken; optParameterBotInfo = new HashMap<>(); optParameterBotInfo.put(Constants.BOT_INFO, botInfoModel); //If spiceManager is not started then start it /*if (!isConnected()) { start(mContext); }*/ getRtmUrl(accessToken,botInfoModel).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<RestResponse.RTMUrl>() { @Override public void onSubscribe(Disposable disposable) {} @Override public void onNext(RestResponse.RTMUrl rtmUrl) {try { connectToSocket(rtmUrl.getUrl(), false); } catch (URISyntaxException e) { e.printStackTrace(); } } @Override public void onError(Throwable throwable) {} @Override public void onComplete() {} }); } public void ConnectAnonymousForKora(final String userAccessToken, final String sJwtGrant, BotInfoModel botInfoModel, SocketConnectionListener socketConnectionListener, final String url, String botUserId, String auth){ this.userAccessToken = userAccessToken; this.botInfoModel = botInfoModel; this.socketConnectionListener = socketConnectionListener; this.accessToken = null; this.JWTToken = sJwtGrant; this.botInfoModel = botInfoModel; this.botUserId = botUserId; this.auth = auth; // Log.d("IKIDO","Hey Initiating Socket"); try { connectToSocket(url,false); } catch (URISyntaxException e) { e.printStackTrace(); } } /** * Method to invoke connection for anonymous * * These keys are generated from bot admin console */ public void connectAnonymous(final String sJwtGrant, final BotInfoModel botInfoModel, final SocketConnectionListener socketConnectionListener, BotSocketOptions options) { this.socketConnectionListener = socketConnectionListener; this.accessToken = null; this.JWTToken = sJwtGrant; this.botInfoModel = botInfoModel; this.options = options; //If spiceManager is not started then start it /*if (!isConnected()) { start(mContext); }*/ getRtmUrlForConnectAnonymous(sJwtGrant,botInfoModel).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<RestResponse.RTMUrl>() { @Override public void onSubscribe(Disposable disposable) { Log.d("HI","on Subscribe"); } @Override public void onNext(RestResponse.RTMUrl rtmUrl) { try { connectToSocket(rtmUrl.getUrl(),false); } catch (URISyntaxException e) { e.printStackTrace(); } } @Override public void onError(Throwable throwable) { Log.d("HI","on error"); mIsReconnectionAttemptNeeded = true; reconnectAttempt(); } @Override public void onComplete() { // Log.d("IKIDO","on complete called man"); } }); } /** * To connect through socket * * @param url : to connect the socket to * @throws URISyntaxException */ private void connectToSocket(String url, final boolean isReconnectionAttaempt) throws URISyntaxException { if((isConnecting || isConnected())) return; isConnecting = true; if (url != null) { if(options != null){ url = options.replaceOptions(url,options); } // this.url = url; // this.uri = new URI(url); WebSocketOptions connectOptions = new WebSocketOptions(); connectOptions.setReconnectInterval(0); try { mConnection.connect(url, new WebSocketConnectionHandler() { @Override public void onOpen() { // Log.d(LOG_TAG, "Connection Open."); if (socketConnectionListener != null) { socketConnectionListener.onOpen(isReconnectionAttaempt); }else{ Log.d("IKIDO","Hey listener is null"); } isConnecting = false; startSendingPong(); mReconnectionCount = 1; mReconnectDelay = 1000; KoreEventCenter.post(new RTMConnectionEvent(true)); } @Override public void onClose(int code, String reason) { Log.d(LOG_TAG, "Connection Lost."); if (socketConnectionListener != null) { socketConnectionListener.onClose(code, reason); }else{ Log.d("IKIDO","Hey listener is null"); } if(timer != null){ timer.cancel(); timer = null; } isConnecting = false; /*if (isConnected()) { stop(); }*/ // if(Utils.isNetworkAvailable(mContext)) reconnectAttempt(); } @Override public void onMessage(String payload) { // Log.d(LOG_TAG, "onTextMessage payload :" + payload); if (socketConnectionListener != null) { socketConnectionListener.onTextMessage(payload); }else{ Log.d("IKIDO","Hey listener is null"); } } /*@Override public void onRawTextMessage(byte[] payload) { // Log.d(LOG_TAG, "onRawTextMessage payload:" + payload); if (socketConnectionListener != null) { socketConnectionListener.onRawTextMessage(payload); } } @Override public void onBinaryMessage(byte[] payload) { // Log.d(LOG_TAG, "onBinaryMessage payload: " + payload); if (socketConnectionListener != null) { socketConnectionListener.onBinaryMessage(payload); } }*/ }); } catch (WebSocketException e) { isConnecting = false; if(e.getMessage() != null && e.getMessage().equals("already connected")){ if (socketConnectionListener != null) { socketConnectionListener.onOpen(isReconnectionAttaempt); } startSendingPong(); mReconnectionCount = 1; mReconnectDelay = 1000; } e.printStackTrace(); } } } private void startSendingPong(){ TimerTask tTask = new TimerTask() { @Override public void run() { try { if ( mConnection.isConnected()) { mConnection.sendPing("pong from the client".getBytes()); } }catch (Exception e){ e.printStackTrace(); } } }; try { if(timer == null)timer = new Timer(); timer.scheduleAtFixedRate(tTask, 1000L, 30000L); }catch(Exception e){ e.printStackTrace(); } } /** * Reconnect to socket */ private void reconnect() { if (accessToken != null) { //Reconnection for valid credential reconnectForAuthenticUser(); } else { //Reconnection for anonymous reconnectForAnonymousUser(); } } private Observable<RestResponse.RTMUrl> getRtmUrlReconnectForAuthenticUser(String accessToken){ return Observable.create(new ObservableOnSubscribe<RestResponse.RTMUrl>() { @Override public void subscribe(ObservableEmitter<RestResponse.RTMUrl> observableEmitter) throws Exception { try { Call<RestResponse.JWTTokenResponse> jwtTokenResponseCall = BotRestBuilder.getBotRestService().getJWTToken("bearer " + accessToken); Response<RestResponse.JWTTokenResponse> jwtTokenResponseResponse = jwtTokenResponseCall.execute(); HashMap<String, Object> hsh = new HashMap<>(1); hsh.put(Constants.KEY_ASSERTION, jwtTokenResponseResponse.body().getJwt()); Call<RestResponse.BotAuthorization> botAuthorizationCall = BotRestBuilder.getBotRestService().jwtGrant(hsh); Response<RestResponse.BotAuthorization> botAuthorizationResponse = botAuthorizationCall.execute(); Call<RestResponse.RTMUrl> rtmUrlCall = BotRestBuilder.getBotRestService().getRtmUrl("bearer " + botAuthorizationResponse.body().getAuthorization().getAccessToken(), optParameterBotInfo,true); Response<RestResponse.RTMUrl> rtmUrlResponse = rtmUrlCall.execute(); /*Call<RestResponse.BotAuthorization> botAuthorizationCall = BotRestBuilder.getBotRestService().jwtGrant(hsh); Response<RestResponse.BotAuthorization> botAuthorizationResponse = botAuthorizationCall.execute(); HashMap<String, Object> hsh1 = new HashMap<>(); hsh1.put(Constants.BOT_INFO, botInfoModel); auth = botAuthorizationResponse.body().getAuthorization().getAccessToken(); botUserId = botAuthorizationResponse.body().getUserInfo().getUserId(); Call<RestResponse.RTMUrl> rtmUrlCall = BotRestBuilder.getBotRestService().getRtmUrl("bearer " + botAuthorizationResponse.body().getAuthorization().getAccessToken(), hsh1,true); Response<RestResponse.RTMUrl> rtmUrlResponse = rtmUrlCall.execute();*/ observableEmitter.onNext(rtmUrlResponse.body()); observableEmitter.onComplete(); } catch (Exception e) { observableEmitter.onError(e); } } }); /*return BotRestBuilder.getBotRestService().getJWTToken("bearer " + accessToken).flatMap(new Function<RestResponse.JWTTokenResponse, ObservableSource<RestResponse.BotAuthorization>>() { @Override public ObservableSource<RestResponse.BotAuthorization> apply(RestResponse.JWTTokenResponse jwtTokenResponse) throws Exception { HashMap<String, Object> hsh = new HashMap<>(1); hsh.put(Constants.KEY_ASSERTION, jwtTokenResponse.getJwt()); return BotRestBuilder.getBotRestService().jwtGrant(hsh); } }).flatMap(new Function<RestResponse.BotAuthorization, ObservableSource<RestResponse.RTMUrl>>() { @Override public ObservableSource<RestResponse.RTMUrl> apply(RestResponse.BotAuthorization botAuthorization) throws Exception { return BotRestBuilder.getBotRestService().getRtmUrl("bearer " + botAuthorization.getAuthorization().getAccessToken(), optParameterBotInfo,true); } });*/ } /** * Reconnection for authentic user */ private void reconnectForAuthenticUser() { Log.i(LOG_TAG, "Connection lost. Reconnecting...."); getRtmUrlReconnectForAuthenticUser(accessToken).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<RestResponse.RTMUrl>() { @Override public void onSubscribe(Disposable disposable) { } @Override public void onNext(RestResponse.RTMUrl rtmUrl) { try { connectToSocket(rtmUrl.getUrl().concat("&isReconnect=true"), true); } catch (URISyntaxException e) { e.printStackTrace(); } } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { } }); } private Observable<RestResponse.RTMUrl> getRtmUrlReconnectForAnonymousUser(){ return Observable.create(new ObservableOnSubscribe<RestResponse.RTMUrl>() { @Override public void subscribe(ObservableEmitter<RestResponse.RTMUrl> observableEmitter) throws Exception { try { HashMap<String, Object> hsh = new HashMap<>(); hsh.put(Constants.KEY_ASSERTION, JWTToken); hsh.put(Constants.BOT_INFO, botInfoModel); Call<RestResponse.BotAuthorization> botAuthorizationCall = BotRestBuilder.getBotRestService().jwtGrant(hsh); Response<RestResponse.BotAuthorization> botAuthorizationResponse = botAuthorizationCall.execute(); HashMap<String, Object> hsh1 = new HashMap<>(); hsh1.put(Constants.BOT_INFO, botInfoModel); auth = botAuthorizationResponse.body().getAuthorization().getAccessToken(); botUserId = botAuthorizationResponse.body().getUserInfo().getUserId(); Call<RestResponse.RTMUrl> rtmUrlCall = BotRestBuilder.getBotRestService().getRtmUrl("bearer " + botAuthorizationResponse.body().getAuthorization().getAccessToken(), hsh1,true); Response<RestResponse.RTMUrl> rtmUrlResponse = rtmUrlCall.execute(); /*Call<JWTTokenResponse> jwtTokenResponseCall = KaRestBuilder.getKaRestAPI().getJWTToken(Utils.ah(accessToken),new HashMap<String, Object>()); Response<JWTTokenResponse> jwtTokenResponse = jwtTokenResponseCall.execute(); SDKConfiguration.Server.setKoreBotServerUrl(jwtTokenResponse.body().getBotsUrl()); KoraSocketConnectionManager.this.jwtKeyResponse = jwtTokenResponse.body(); botName = jwtKeyResponse.getBotName(); streamId = jwtKeyResponse.getStreamId(); HashMap<String, Object> hsh = new HashMap<>(); botInfoModel = new BotInfoModel(jwtTokenResponse.body().getBotName(),jwtTokenResponse.body().getStreamId(),botClient.getCustomData()); hsh.put(Constants.KEY_ASSERTION, jwtTokenResponse.body().getJwt()); hsh.put(Constants.BOT_INFO, botInfoModel); Call<RestResponse.BotAuthorization> botAuthorizationCall = BotRestBuilder.getBotRestService().jwtGrant(hsh); Response<RestResponse.BotAuthorization> botAuthorizationResponse = botAuthorizationCall.execute(); HashMap<String, Object> optParameterBotInfo = new HashMap<>(); optParameterBotInfo.put(Constants.BOT_INFO, botInfoModel); botUserId = botAuthorizationResponse.body().getUserInfo().getUserId(); botAccessToken = botAuthorizationResponse.body().getAuthorization().getAccessToken(); Call<RestResponse.RTMUrl> rtmUrlCall = BotRestBuilder.getBotRestService().getRtmUrl("bearer " + botAuthorizationResponse.body().getAuthorization().getAccessToken(), optParameterBotInfo); Response<RestResponse.RTMUrl> rtmUrlResponse = rtmUrlCall.execute();*/ observableEmitter.onNext(rtmUrlResponse.body()); observableEmitter.onComplete(); } catch (Exception e) { observableEmitter.onError(e); } } }); /*return BotRestBuilder.getBotRestService().jwtGrant(hsh).flatMap(new Function<RestResponse.BotAuthorization, ObservableSource<RestResponse.RTMUrl>>() { @Override public ObservableSource<RestResponse.RTMUrl> apply(RestResponse.BotAuthorization botAuthorization) throws Exception { HashMap<String, Object> hsh1 = new HashMap<>(); hsh1.put(Constants.BOT_INFO, botInfoModel); auth = botAuthorization.getAuthorization().getAccessToken(); botUserId = botAuthorization.getUserInfo().getUserId(); return BotRestBuilder.getBotRestService().getRtmUrl("bearer " + botAuthorization.getAuthorization().getAccessToken(), hsh1,true); } });*/ } /** * Reconnection for anonymous user */ private void reconnectForAnonymousUser() { Log.i(LOG_TAG, "Connection lost. Reconnecting...."); getRtmUrlReconnectForAnonymousUser().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<RestResponse.RTMUrl>() { @Override public void onSubscribe(Disposable disposable) { } @Override public void onNext(RestResponse.RTMUrl rtmUrl) { try { connectToSocket(rtmUrl.getUrl().concat("&isReconnect=true"),true); } catch (URISyntaxException e) { e.printStackTrace(); } } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { } }); } public void onTokenRefresh(String token){ JWTToken = token; reconnect(); } /** * @param msg : The message object * @return Was it able to successfully send the message. */ public boolean sendMessage(String msg) { if (mConnection != null && mConnection.isConnected()) { mConnection.sendMessage(msg); return true; } else { if(userAccessToken != null && socketConnectionListener != null){ socketConnectionListener.refreshJwtToken(); }else { reconnect(); } Log.e(LOG_TAG, "Connection is not present. Reconnecting..."); return false; } } /* * Method to Reconnection attempt based on incremental delay * * @reurn */ private void reconnectAttempt() { // mIsImmediateFetchActionNeeded = true; mReconnectDelay = getReconnectDelay(); try { final Handler _handler = new Handler(); Runnable r = new Runnable() { @Override public void run() { Log.d(LOG_TAG, "Entered into reconnection post delayed " + mReconnectDelay); if (mIsReconnectionAttemptNeeded && !isConnected()) { reconnect(); // Toast.makeText(mContext,"SocketDisConnected",Toast.LENGTH_SHORT).show(); mReconnectDelay = getReconnectDelay(); _handler.postDelayed(this, mReconnectDelay); Log.d(LOG_TAG, "#### trying to reconnect"); } } }; _handler.postDelayed(r, mReconnectDelay); } catch (Exception e) { Log.d(LOG_TAG, ":: The Exception is " + e.toString()); } } /** * The reconnection attempt delay(incremental delay) * * @return */ private int getReconnectDelay() { mReconnectionCount++; Log.d(LOG_TAG, "Reconnection count " + mReconnectionCount); if (mReconnectionCount > 6) mReconnectionCount = 1; Random rint = new Random(); return (rint.nextInt(5) + 1) * mReconnectionCount * 1000; } /** * For disconnecting user's presence * Call this method when the user logged out */ public void disConnect() { mIsReconnectionAttemptNeeded = false; if (mConnection != null && mConnection.isConnected()) { try { mConnection.sendClose(); } catch (Exception e) { Log.d(LOG_TAG, "Exception while disconnection"); } Log.d(LOG_TAG, "DisConnected successfully"); } else { Log.d(LOG_TAG, "Cannot disconnect.._client is null"); } //The bot URL may change BotRestBuilder.clearInstance(); auth = null; botUserId = null; /*if (isConnected()) { stop(); }*/ } /** * Determine the TLS enability of the url. * @param url url to connect to (is generally either ws:// or wss://) */ /* private void determineTLSEnability(String url) { mTLSEnabled = url.startsWith(Constants.SECURE_WEBSOCKET_PREFIX); }*/ /** * To determine wither socket is connected or not * @return boolean indicating the connection presence. */ public boolean isConnected() { if (mConnection != null && mConnection.isConnected()) { return true; } else { return false; } } public String getBotUserId() { return botUserId; } public void setBotUserId(String botUserId) { this.botUserId = botUserId; } }
[ "public", "final", "class", "SocketWrapper", "{", "private", "final", "String", "LOG_TAG", "=", "\"", "SocketWrapper", "\"", ";", "public", "static", "SocketWrapper", "pKorePresenceInstance", ";", "private", "SocketConnectionListener", "socketConnectionListener", "=", "null", ";", "private", "final", "IWebSocket", "mConnection", "=", "new", "WebSocketConnection", "(", ")", ";", "private", "static", "Timer", "timer", "=", "new", "Timer", "(", ")", ";", "public", "boolean", "ismIsReconnectionAttemptNeeded", "(", ")", "{", "return", "mIsReconnectionAttemptNeeded", ";", "}", "public", "void", "shouldAttemptToReconnect", "(", "boolean", "mIsReconnectionAttemptNeeded", ")", "{", "this", ".", "mIsReconnectionAttemptNeeded", "=", "mIsReconnectionAttemptNeeded", ";", "}", "private", "boolean", "mIsReconnectionAttemptNeeded", "=", "true", ";", "private", "boolean", "isConnecting", "=", "false", ";", "private", "HashMap", "<", "String", ",", "Object", ">", "optParameterBotInfo", ";", "private", "String", "accessToken", ";", "private", "String", "userAccessToken", "=", "null", ";", "private", "String", "anonymousUserAccessToken", "=", "null", ";", "private", "String", "JWTToken", ";", "private", "String", "auth", ";", "private", "String", "botUserId", ";", "public", "BotInfoModel", "getBotInfoModel", "(", ")", "{", "return", "botInfoModel", ";", "}", "public", "void", "setBotInfoModel", "(", "BotInfoModel", "botInfoModel", ")", "{", "this", ".", "botInfoModel", "=", "botInfoModel", ";", "}", "private", "BotInfoModel", "botInfoModel", ";", "private", "BotSocketOptions", "options", ";", "private", "Context", "mContext", ";", "/**\n * initial reconnection delay 1 Sec\n */", "private", "int", "mReconnectDelay", "=", "1000", ";", "/**\n * initial reconnection count\n */", "private", "int", "mReconnectionCount", "=", "0", ";", "/**\n * Restricting outside object creation\n */", "private", "SocketWrapper", "(", "Context", "mContext", ")", "{", "this", ".", "mContext", "=", "mContext", ";", "}", "public", "String", "getAccessToken", "(", ")", "{", "return", "auth", ";", "}", "/**\n * The global default SocketWrapper instance\n */", "public", "static", "SocketWrapper", "getInstance", "(", "Context", "mContext", ")", "{", "if", "(", "pKorePresenceInstance", "==", "null", ")", "{", "pKorePresenceInstance", "=", "new", "SocketWrapper", "(", "mContext", ")", ";", "}", "return", "pKorePresenceInstance", ";", "}", "/**\n * To prevent cloning\n *\n * @return\n * @throws CloneNotSupportedException\n */", "@", "Override", "protected", "Object", "clone", "(", ")", "throws", "CloneNotSupportedException", "{", "return", "new", "CloneNotSupportedException", "(", "\"", "Clone not supported", "\"", ")", ";", "}", "private", "Observable", "<", "RestResponse", ".", "RTMUrl", ">", "getRtmUrl", "(", "String", "accessToken", ",", "final", "BotInfoModel", "botInfoModel", ")", "{", "return", "Observable", ".", "create", "(", "new", "ObservableOnSubscribe", "<", "RestResponse", ".", "RTMUrl", ">", "(", ")", "{", "@", "Override", "public", "void", "subscribe", "(", "ObservableEmitter", "<", "RestResponse", ".", "RTMUrl", ">", "observableEmitter", ")", "throws", "Exception", "{", "try", "{", "Call", "<", "RestResponse", ".", "JWTTokenResponse", ">", "jwtTokenResponseCall", "=", "BotRestBuilder", ".", "getBotRestService", "(", ")", ".", "getJWTToken", "(", "\"", "bearer ", "\"", "+", "accessToken", ")", ";", "Response", "<", "RestResponse", ".", "JWTTokenResponse", ">", "jwtTokenResponseResponse", "=", "jwtTokenResponseCall", ".", "execute", "(", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "hsh", "=", "new", "HashMap", "<", ">", "(", ")", ";", "hsh", ".", "put", "(", "Constants", ".", "KEY_ASSERTION", ",", "jwtTokenResponseResponse", ".", "body", "(", ")", ".", "getJwt", "(", ")", ")", ";", "hsh", ".", "put", "(", "Constants", ".", "BOT_INFO", ",", "botInfoModel", ")", ";", "Call", "<", "RestResponse", ".", "BotAuthorization", ">", "botAuthorizationCall", "=", "BotRestBuilder", ".", "getBotRestService", "(", ")", ".", "jwtGrant", "(", "hsh", ")", ";", "Response", "<", "RestResponse", ".", "BotAuthorization", ">", "botAuthorizationResponse", "=", "botAuthorizationCall", ".", "execute", "(", ")", ";", "auth", "=", "botAuthorizationResponse", ".", "body", "(", ")", ".", "getAuthorization", "(", ")", ".", "getAccessToken", "(", ")", ";", "botUserId", "=", "botAuthorizationResponse", ".", "body", "(", ")", ".", "getUserInfo", "(", ")", ".", "getUserId", "(", ")", ";", "Call", "<", "RestResponse", ".", "RTMUrl", ">", "rtmUrlCall", "=", "BotRestBuilder", ".", "getBotRestService", "(", ")", ".", "getRtmUrl", "(", "\"", "bearer ", "\"", "+", "botAuthorizationResponse", ".", "body", "(", ")", ".", "getAuthorization", "(", ")", ".", "getAccessToken", "(", ")", ",", "optParameterBotInfo", ")", ";", "Response", "<", "RestResponse", ".", "RTMUrl", ">", "rtmUrlResponse", "=", "rtmUrlCall", ".", "execute", "(", ")", ";", "observableEmitter", ".", "onNext", "(", "rtmUrlResponse", ".", "body", "(", ")", ")", ";", "observableEmitter", ".", "onComplete", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "observableEmitter", ".", "onError", "(", "e", ")", ";", "}", "}", "}", ")", ";", "/*return BotRestBuilder.getBotRestService().getJWTToken(\"bearer \" + accessToken).flatMap(new Function<RestResponse.JWTTokenResponse,\n ObservableSource<RestResponse.BotAuthorization>>() {\n @Override\n public ObservableSource<RestResponse.BotAuthorization> apply(RestResponse.JWTTokenResponse jwtTokenResponse) throws Exception {\n HashMap<String, Object> hsh = new HashMap<>();\n hsh.put(Constants.KEY_ASSERTION, jwtTokenResponse.getJwt());\n hsh.put(Constants.BOT_INFO, botInfoModel);\n return BotRestBuilder.getBotRestService().jwtGrant(hsh);\n }\n }).flatMap(new Function<RestResponse.BotAuthorization, ObservableSource<RestResponse.RTMUrl>>() {\n @Override\n public ObservableSource<RestResponse.RTMUrl> apply(RestResponse.BotAuthorization botAuthorization) throws Exception {\n auth = botAuthorization.getAuthorization().getAccessToken();\n botUserId = botAuthorization.getUserInfo().getUserId();\n return BotRestBuilder.getBotRestService().getRtmUrl(\"bearer \" + botAuthorization.getAuthorization().getAccessToken(), optParameterBotInfo);\n }\n });*/", "}", "private", "Observable", "<", "RestResponse", ".", "RTMUrl", ">", "getRtmUrlForConnectAnonymous", "(", "final", "String", "sJwtGrant", ",", "final", "BotInfoModel", "botInfoModel", ")", "{", "return", "Observable", ".", "create", "(", "new", "ObservableOnSubscribe", "<", "RestResponse", ".", "RTMUrl", ">", "(", ")", "{", "@", "Override", "public", "void", "subscribe", "(", "ObservableEmitter", "<", "RestResponse", ".", "RTMUrl", ">", "observableEmitter", ")", "throws", "Exception", "{", "try", "{", "HashMap", "<", "String", ",", "Object", ">", "hsh", "=", "new", "HashMap", "<", ">", "(", ")", ";", "hsh", ".", "put", "(", "Constants", ".", "KEY_ASSERTION", ",", "sJwtGrant", ")", ";", "hsh", ".", "put", "(", "Constants", ".", "BOT_INFO", ",", "botInfoModel", ")", ";", "Call", "<", "RestResponse", ".", "BotAuthorization", ">", "botAuthorizationCall", "=", "BotRestBuilder", ".", "getBotRestService", "(", ")", ".", "jwtGrant", "(", "hsh", ")", ";", "Response", "<", "RestResponse", ".", "BotAuthorization", ">", "botAuthorizationResponse", "=", "botAuthorizationCall", ".", "execute", "(", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "hsh1", "=", "new", "HashMap", "<", ">", "(", ")", ";", "hsh1", ".", "put", "(", "Constants", ".", "BOT_INFO", ",", "botInfoModel", ")", ";", "botUserId", "=", "botAuthorizationResponse", ".", "body", "(", ")", ".", "getUserInfo", "(", ")", ".", "getUserId", "(", ")", ";", "auth", "=", "botAuthorizationResponse", ".", "body", "(", ")", ".", "getAuthorization", "(", ")", ".", "getAccessToken", "(", ")", ";", "Call", "<", "RestResponse", ".", "RTMUrl", ">", "rtmUrlCall", "=", "BotRestBuilder", ".", "getBotRestService", "(", ")", ".", "getRtmUrl", "(", "\"", "bearer ", "\"", "+", "botAuthorizationResponse", ".", "body", "(", ")", ".", "getAuthorization", "(", ")", ".", "getAccessToken", "(", ")", ",", "hsh1", ")", ";", "Response", "<", "RestResponse", ".", "RTMUrl", ">", "rtmUrlResponse", "=", "rtmUrlCall", ".", "execute", "(", ")", ";", "observableEmitter", ".", "onNext", "(", "rtmUrlResponse", ".", "body", "(", ")", ")", ";", "observableEmitter", ".", "onComplete", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "observableEmitter", ".", "onError", "(", "e", ")", ";", "}", "}", "}", ")", ";", "/*return BotRestBuilder.getBotRestService().jwtGrant(hsh).flatMap(new Function<RestResponse.BotAuthorization, ObservableSource<RestResponse.RTMUrl>>() {\n @Override\n public ObservableSource<RestResponse.RTMUrl> apply(RestResponse.BotAuthorization botAuthorization) throws Exception {\n HashMap<String, Object> hsh1 = new HashMap<>();\n hsh1.put(Constants.BOT_INFO, botInfoModel);\n\n botUserId = botAuthorization.getUserInfo().getUserId();\n auth = botAuthorization.getAuthorization().getAccessToken();\n return BotRestBuilder.getBotRestService().getRtmUrl(\"bearer \" + botAuthorization.getAuthorization().getAccessToken(), hsh1);\n }\n });*/", "}", "/**\n * Method to invoke connection for authenticated user\n *\n * @param accessToken : AccessToken of the loged user.\n */", "public", "void", "connect", "(", "String", "accessToken", ",", "final", "BotInfoModel", "botInfoModel", ",", "SocketConnectionListener", "socketConnectionListener", ")", "{", "this", ".", "botInfoModel", "=", "botInfoModel", ";", "this", ".", "socketConnectionListener", "=", "socketConnectionListener", ";", "this", ".", "accessToken", "=", "accessToken", ";", "optParameterBotInfo", "=", "new", "HashMap", "<", ">", "(", ")", ";", "optParameterBotInfo", ".", "put", "(", "Constants", ".", "BOT_INFO", ",", "botInfoModel", ")", ";", "/*if (!isConnected()) {\n start(mContext);\n }*/", "getRtmUrl", "(", "accessToken", ",", "botInfoModel", ")", ".", "subscribeOn", "(", "Schedulers", ".", "io", "(", ")", ")", ".", "observeOn", "(", "AndroidSchedulers", ".", "mainThread", "(", ")", ")", ".", "subscribe", "(", "new", "Observer", "<", "RestResponse", ".", "RTMUrl", ">", "(", ")", "{", "@", "Override", "public", "void", "onSubscribe", "(", "Disposable", "disposable", ")", "{", "}", "@", "Override", "public", "void", "onNext", "(", "RestResponse", ".", "RTMUrl", "rtmUrl", ")", "{", "try", "{", "connectToSocket", "(", "rtmUrl", ".", "getUrl", "(", ")", ",", "false", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "@", "Override", "public", "void", "onError", "(", "Throwable", "throwable", ")", "{", "}", "@", "Override", "public", "void", "onComplete", "(", ")", "{", "}", "}", ")", ";", "}", "public", "void", "ConnectAnonymousForKora", "(", "final", "String", "userAccessToken", ",", "final", "String", "sJwtGrant", ",", "BotInfoModel", "botInfoModel", ",", "SocketConnectionListener", "socketConnectionListener", ",", "final", "String", "url", ",", "String", "botUserId", ",", "String", "auth", ")", "{", "this", ".", "userAccessToken", "=", "userAccessToken", ";", "this", ".", "botInfoModel", "=", "botInfoModel", ";", "this", ".", "socketConnectionListener", "=", "socketConnectionListener", ";", "this", ".", "accessToken", "=", "null", ";", "this", ".", "JWTToken", "=", "sJwtGrant", ";", "this", ".", "botInfoModel", "=", "botInfoModel", ";", "this", ".", "botUserId", "=", "botUserId", ";", "this", ".", "auth", "=", "auth", ";", "try", "{", "connectToSocket", "(", "url", ",", "false", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "/**\n * Method to invoke connection for anonymous\n *\n * These keys are generated from bot admin console\n */", "public", "void", "connectAnonymous", "(", "final", "String", "sJwtGrant", ",", "final", "BotInfoModel", "botInfoModel", ",", "final", "SocketConnectionListener", "socketConnectionListener", ",", "BotSocketOptions", "options", ")", "{", "this", ".", "socketConnectionListener", "=", "socketConnectionListener", ";", "this", ".", "accessToken", "=", "null", ";", "this", ".", "JWTToken", "=", "sJwtGrant", ";", "this", ".", "botInfoModel", "=", "botInfoModel", ";", "this", ".", "options", "=", "options", ";", "/*if (!isConnected()) {\n start(mContext);\n }*/", "getRtmUrlForConnectAnonymous", "(", "sJwtGrant", ",", "botInfoModel", ")", ".", "subscribeOn", "(", "Schedulers", ".", "io", "(", ")", ")", ".", "observeOn", "(", "AndroidSchedulers", ".", "mainThread", "(", ")", ")", ".", "subscribe", "(", "new", "Observer", "<", "RestResponse", ".", "RTMUrl", ">", "(", ")", "{", "@", "Override", "public", "void", "onSubscribe", "(", "Disposable", "disposable", ")", "{", "Log", ".", "d", "(", "\"", "HI", "\"", ",", "\"", "on Subscribe", "\"", ")", ";", "}", "@", "Override", "public", "void", "onNext", "(", "RestResponse", ".", "RTMUrl", "rtmUrl", ")", "{", "try", "{", "connectToSocket", "(", "rtmUrl", ".", "getUrl", "(", ")", ",", "false", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "@", "Override", "public", "void", "onError", "(", "Throwable", "throwable", ")", "{", "Log", ".", "d", "(", "\"", "HI", "\"", ",", "\"", "on error", "\"", ")", ";", "mIsReconnectionAttemptNeeded", "=", "true", ";", "reconnectAttempt", "(", ")", ";", "}", "@", "Override", "public", "void", "onComplete", "(", ")", "{", "}", "}", ")", ";", "}", "/**\n * To connect through socket\n *\n * @param url : to connect the socket to\n * @throws URISyntaxException\n */", "private", "void", "connectToSocket", "(", "String", "url", ",", "final", "boolean", "isReconnectionAttaempt", ")", "throws", "URISyntaxException", "{", "if", "(", "(", "isConnecting", "||", "isConnected", "(", ")", ")", ")", "return", ";", "isConnecting", "=", "true", ";", "if", "(", "url", "!=", "null", ")", "{", "if", "(", "options", "!=", "null", ")", "{", "url", "=", "options", ".", "replaceOptions", "(", "url", ",", "options", ")", ";", "}", "WebSocketOptions", "connectOptions", "=", "new", "WebSocketOptions", "(", ")", ";", "connectOptions", ".", "setReconnectInterval", "(", "0", ")", ";", "try", "{", "mConnection", ".", "connect", "(", "url", ",", "new", "WebSocketConnectionHandler", "(", ")", "{", "@", "Override", "public", "void", "onOpen", "(", ")", "{", "if", "(", "socketConnectionListener", "!=", "null", ")", "{", "socketConnectionListener", ".", "onOpen", "(", "isReconnectionAttaempt", ")", ";", "}", "else", "{", "Log", ".", "d", "(", "\"", "IKIDO", "\"", ",", "\"", "Hey listener is null", "\"", ")", ";", "}", "isConnecting", "=", "false", ";", "startSendingPong", "(", ")", ";", "mReconnectionCount", "=", "1", ";", "mReconnectDelay", "=", "1000", ";", "KoreEventCenter", ".", "post", "(", "new", "RTMConnectionEvent", "(", "true", ")", ")", ";", "}", "@", "Override", "public", "void", "onClose", "(", "int", "code", ",", "String", "reason", ")", "{", "Log", ".", "d", "(", "LOG_TAG", ",", "\"", "Connection Lost.", "\"", ")", ";", "if", "(", "socketConnectionListener", "!=", "null", ")", "{", "socketConnectionListener", ".", "onClose", "(", "code", ",", "reason", ")", ";", "}", "else", "{", "Log", ".", "d", "(", "\"", "IKIDO", "\"", ",", "\"", "Hey listener is null", "\"", ")", ";", "}", "if", "(", "timer", "!=", "null", ")", "{", "timer", ".", "cancel", "(", ")", ";", "timer", "=", "null", ";", "}", "isConnecting", "=", "false", ";", "/*if (isConnected()) {\n stop();\n }*/", "reconnectAttempt", "(", ")", ";", "}", "@", "Override", "public", "void", "onMessage", "(", "String", "payload", ")", "{", "if", "(", "socketConnectionListener", "!=", "null", ")", "{", "socketConnectionListener", ".", "onTextMessage", "(", "payload", ")", ";", "}", "else", "{", "Log", ".", "d", "(", "\"", "IKIDO", "\"", ",", "\"", "Hey listener is null", "\"", ")", ";", "}", "}", "/*@Override\n public void onRawTextMessage(byte[] payload) {\n// Log.d(LOG_TAG, \"onRawTextMessage payload:\" + payload);\n if (socketConnectionListener != null) {\n socketConnectionListener.onRawTextMessage(payload);\n }\n }\n\n @Override\n public void onBinaryMessage(byte[] payload) {\n// Log.d(LOG_TAG, \"onBinaryMessage payload: \" + payload);\n if (socketConnectionListener != null) {\n socketConnectionListener.onBinaryMessage(payload);\n }\n }*/", "}", ")", ";", "}", "catch", "(", "WebSocketException", "e", ")", "{", "isConnecting", "=", "false", ";", "if", "(", "e", ".", "getMessage", "(", ")", "!=", "null", "&&", "e", ".", "getMessage", "(", ")", ".", "equals", "(", "\"", "already connected", "\"", ")", ")", "{", "if", "(", "socketConnectionListener", "!=", "null", ")", "{", "socketConnectionListener", ".", "onOpen", "(", "isReconnectionAttaempt", ")", ";", "}", "startSendingPong", "(", ")", ";", "mReconnectionCount", "=", "1", ";", "mReconnectDelay", "=", "1000", ";", "}", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}", "private", "void", "startSendingPong", "(", ")", "{", "TimerTask", "tTask", "=", "new", "TimerTask", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "if", "(", "mConnection", ".", "isConnected", "(", ")", ")", "{", "mConnection", ".", "sendPing", "(", "\"", "pong from the client", "\"", ".", "getBytes", "(", ")", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}", ";", "try", "{", "if", "(", "timer", "==", "null", ")", "timer", "=", "new", "Timer", "(", ")", ";", "timer", ".", "scheduleAtFixedRate", "(", "tTask", ",", "1000L", ",", "30000L", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "/**\n * Reconnect to socket\n */", "private", "void", "reconnect", "(", ")", "{", "if", "(", "accessToken", "!=", "null", ")", "{", "reconnectForAuthenticUser", "(", ")", ";", "}", "else", "{", "reconnectForAnonymousUser", "(", ")", ";", "}", "}", "private", "Observable", "<", "RestResponse", ".", "RTMUrl", ">", "getRtmUrlReconnectForAuthenticUser", "(", "String", "accessToken", ")", "{", "return", "Observable", ".", "create", "(", "new", "ObservableOnSubscribe", "<", "RestResponse", ".", "RTMUrl", ">", "(", ")", "{", "@", "Override", "public", "void", "subscribe", "(", "ObservableEmitter", "<", "RestResponse", ".", "RTMUrl", ">", "observableEmitter", ")", "throws", "Exception", "{", "try", "{", "Call", "<", "RestResponse", ".", "JWTTokenResponse", ">", "jwtTokenResponseCall", "=", "BotRestBuilder", ".", "getBotRestService", "(", ")", ".", "getJWTToken", "(", "\"", "bearer ", "\"", "+", "accessToken", ")", ";", "Response", "<", "RestResponse", ".", "JWTTokenResponse", ">", "jwtTokenResponseResponse", "=", "jwtTokenResponseCall", ".", "execute", "(", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "hsh", "=", "new", "HashMap", "<", ">", "(", "1", ")", ";", "hsh", ".", "put", "(", "Constants", ".", "KEY_ASSERTION", ",", "jwtTokenResponseResponse", ".", "body", "(", ")", ".", "getJwt", "(", ")", ")", ";", "Call", "<", "RestResponse", ".", "BotAuthorization", ">", "botAuthorizationCall", "=", "BotRestBuilder", ".", "getBotRestService", "(", ")", ".", "jwtGrant", "(", "hsh", ")", ";", "Response", "<", "RestResponse", ".", "BotAuthorization", ">", "botAuthorizationResponse", "=", "botAuthorizationCall", ".", "execute", "(", ")", ";", "Call", "<", "RestResponse", ".", "RTMUrl", ">", "rtmUrlCall", "=", "BotRestBuilder", ".", "getBotRestService", "(", ")", ".", "getRtmUrl", "(", "\"", "bearer ", "\"", "+", "botAuthorizationResponse", ".", "body", "(", ")", ".", "getAuthorization", "(", ")", ".", "getAccessToken", "(", ")", ",", "optParameterBotInfo", ",", "true", ")", ";", "Response", "<", "RestResponse", ".", "RTMUrl", ">", "rtmUrlResponse", "=", "rtmUrlCall", ".", "execute", "(", ")", ";", "/*Call<RestResponse.BotAuthorization> botAuthorizationCall = BotRestBuilder.getBotRestService().jwtGrant(hsh);\n Response<RestResponse.BotAuthorization> botAuthorizationResponse = botAuthorizationCall.execute();\n HashMap<String, Object> hsh1 = new HashMap<>();\n hsh1.put(Constants.BOT_INFO, botInfoModel);\n\n auth = botAuthorizationResponse.body().getAuthorization().getAccessToken();\n botUserId = botAuthorizationResponse.body().getUserInfo().getUserId();\n\n Call<RestResponse.RTMUrl> rtmUrlCall = BotRestBuilder.getBotRestService().getRtmUrl(\"bearer \" + botAuthorizationResponse.body().getAuthorization().getAccessToken(), hsh1,true);\n Response<RestResponse.RTMUrl> rtmUrlResponse = rtmUrlCall.execute();*/", "observableEmitter", ".", "onNext", "(", "rtmUrlResponse", ".", "body", "(", ")", ")", ";", "observableEmitter", ".", "onComplete", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "observableEmitter", ".", "onError", "(", "e", ")", ";", "}", "}", "}", ")", ";", "/*return BotRestBuilder.getBotRestService().getJWTToken(\"bearer \" + accessToken).flatMap(new Function<RestResponse.JWTTokenResponse, ObservableSource<RestResponse.BotAuthorization>>() {\n @Override\n public ObservableSource<RestResponse.BotAuthorization> apply(RestResponse.JWTTokenResponse jwtTokenResponse) throws Exception {\n HashMap<String, Object> hsh = new HashMap<>(1);\n hsh.put(Constants.KEY_ASSERTION, jwtTokenResponse.getJwt());\n return BotRestBuilder.getBotRestService().jwtGrant(hsh);\n }\n }).flatMap(new Function<RestResponse.BotAuthorization, ObservableSource<RestResponse.RTMUrl>>() {\n @Override\n public ObservableSource<RestResponse.RTMUrl> apply(RestResponse.BotAuthorization botAuthorization) throws Exception {\n return BotRestBuilder.getBotRestService().getRtmUrl(\"bearer \" + botAuthorization.getAuthorization().getAccessToken(), optParameterBotInfo,true);\n }\n });*/", "}", "/**\n * Reconnection for authentic user\n */", "private", "void", "reconnectForAuthenticUser", "(", ")", "{", "Log", ".", "i", "(", "LOG_TAG", ",", "\"", "Connection lost. Reconnecting....", "\"", ")", ";", "getRtmUrlReconnectForAuthenticUser", "(", "accessToken", ")", ".", "subscribeOn", "(", "Schedulers", ".", "io", "(", ")", ")", ".", "observeOn", "(", "AndroidSchedulers", ".", "mainThread", "(", ")", ")", ".", "subscribe", "(", "new", "Observer", "<", "RestResponse", ".", "RTMUrl", ">", "(", ")", "{", "@", "Override", "public", "void", "onSubscribe", "(", "Disposable", "disposable", ")", "{", "}", "@", "Override", "public", "void", "onNext", "(", "RestResponse", ".", "RTMUrl", "rtmUrl", ")", "{", "try", "{", "connectToSocket", "(", "rtmUrl", ".", "getUrl", "(", ")", ".", "concat", "(", "\"", "&isReconnect=true", "\"", ")", ",", "true", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "@", "Override", "public", "void", "onError", "(", "Throwable", "throwable", ")", "{", "}", "@", "Override", "public", "void", "onComplete", "(", ")", "{", "}", "}", ")", ";", "}", "private", "Observable", "<", "RestResponse", ".", "RTMUrl", ">", "getRtmUrlReconnectForAnonymousUser", "(", ")", "{", "return", "Observable", ".", "create", "(", "new", "ObservableOnSubscribe", "<", "RestResponse", ".", "RTMUrl", ">", "(", ")", "{", "@", "Override", "public", "void", "subscribe", "(", "ObservableEmitter", "<", "RestResponse", ".", "RTMUrl", ">", "observableEmitter", ")", "throws", "Exception", "{", "try", "{", "HashMap", "<", "String", ",", "Object", ">", "hsh", "=", "new", "HashMap", "<", ">", "(", ")", ";", "hsh", ".", "put", "(", "Constants", ".", "KEY_ASSERTION", ",", "JWTToken", ")", ";", "hsh", ".", "put", "(", "Constants", ".", "BOT_INFO", ",", "botInfoModel", ")", ";", "Call", "<", "RestResponse", ".", "BotAuthorization", ">", "botAuthorizationCall", "=", "BotRestBuilder", ".", "getBotRestService", "(", ")", ".", "jwtGrant", "(", "hsh", ")", ";", "Response", "<", "RestResponse", ".", "BotAuthorization", ">", "botAuthorizationResponse", "=", "botAuthorizationCall", ".", "execute", "(", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "hsh1", "=", "new", "HashMap", "<", ">", "(", ")", ";", "hsh1", ".", "put", "(", "Constants", ".", "BOT_INFO", ",", "botInfoModel", ")", ";", "auth", "=", "botAuthorizationResponse", ".", "body", "(", ")", ".", "getAuthorization", "(", ")", ".", "getAccessToken", "(", ")", ";", "botUserId", "=", "botAuthorizationResponse", ".", "body", "(", ")", ".", "getUserInfo", "(", ")", ".", "getUserId", "(", ")", ";", "Call", "<", "RestResponse", ".", "RTMUrl", ">", "rtmUrlCall", "=", "BotRestBuilder", ".", "getBotRestService", "(", ")", ".", "getRtmUrl", "(", "\"", "bearer ", "\"", "+", "botAuthorizationResponse", ".", "body", "(", ")", ".", "getAuthorization", "(", ")", ".", "getAccessToken", "(", ")", ",", "hsh1", ",", "true", ")", ";", "Response", "<", "RestResponse", ".", "RTMUrl", ">", "rtmUrlResponse", "=", "rtmUrlCall", ".", "execute", "(", ")", ";", "/*Call<JWTTokenResponse> jwtTokenResponseCall = KaRestBuilder.getKaRestAPI().getJWTToken(Utils.ah(accessToken),new HashMap<String, Object>());\n Response<JWTTokenResponse> jwtTokenResponse = jwtTokenResponseCall.execute();\n\n SDKConfiguration.Server.setKoreBotServerUrl(jwtTokenResponse.body().getBotsUrl());\n KoraSocketConnectionManager.this.jwtKeyResponse = jwtTokenResponse.body();\n botName = jwtKeyResponse.getBotName();\n streamId = jwtKeyResponse.getStreamId();\n\n\n HashMap<String, Object> hsh = new HashMap<>();\n botInfoModel = new BotInfoModel(jwtTokenResponse.body().getBotName(),jwtTokenResponse.body().getStreamId(),botClient.getCustomData());\n hsh.put(Constants.KEY_ASSERTION, jwtTokenResponse.body().getJwt());\n hsh.put(Constants.BOT_INFO, botInfoModel);\n\n Call<RestResponse.BotAuthorization> botAuthorizationCall = BotRestBuilder.getBotRestService().jwtGrant(hsh);\n Response<RestResponse.BotAuthorization> botAuthorizationResponse = botAuthorizationCall.execute();\n\n HashMap<String, Object> optParameterBotInfo = new HashMap<>();\n optParameterBotInfo.put(Constants.BOT_INFO, botInfoModel);\n botUserId = botAuthorizationResponse.body().getUserInfo().getUserId();\n botAccessToken = botAuthorizationResponse.body().getAuthorization().getAccessToken();\n\n Call<RestResponse.RTMUrl> rtmUrlCall = BotRestBuilder.getBotRestService().getRtmUrl(\"bearer \" + botAuthorizationResponse.body().getAuthorization().getAccessToken(), optParameterBotInfo);\n Response<RestResponse.RTMUrl> rtmUrlResponse = rtmUrlCall.execute();*/", "observableEmitter", ".", "onNext", "(", "rtmUrlResponse", ".", "body", "(", ")", ")", ";", "observableEmitter", ".", "onComplete", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "observableEmitter", ".", "onError", "(", "e", ")", ";", "}", "}", "}", ")", ";", "/*return BotRestBuilder.getBotRestService().jwtGrant(hsh).flatMap(new Function<RestResponse.BotAuthorization, ObservableSource<RestResponse.RTMUrl>>() {\n @Override\n public ObservableSource<RestResponse.RTMUrl> apply(RestResponse.BotAuthorization botAuthorization) throws Exception {\n HashMap<String, Object> hsh1 = new HashMap<>();\n hsh1.put(Constants.BOT_INFO, botInfoModel);\n\n auth = botAuthorization.getAuthorization().getAccessToken();\n botUserId = botAuthorization.getUserInfo().getUserId();\n\n return BotRestBuilder.getBotRestService().getRtmUrl(\"bearer \" + botAuthorization.getAuthorization().getAccessToken(), hsh1,true);\n }\n });*/", "}", "/**\n * Reconnection for anonymous user\n */", "private", "void", "reconnectForAnonymousUser", "(", ")", "{", "Log", ".", "i", "(", "LOG_TAG", ",", "\"", "Connection lost. Reconnecting....", "\"", ")", ";", "getRtmUrlReconnectForAnonymousUser", "(", ")", ".", "subscribeOn", "(", "Schedulers", ".", "io", "(", ")", ")", ".", "observeOn", "(", "AndroidSchedulers", ".", "mainThread", "(", ")", ")", ".", "subscribe", "(", "new", "Observer", "<", "RestResponse", ".", "RTMUrl", ">", "(", ")", "{", "@", "Override", "public", "void", "onSubscribe", "(", "Disposable", "disposable", ")", "{", "}", "@", "Override", "public", "void", "onNext", "(", "RestResponse", ".", "RTMUrl", "rtmUrl", ")", "{", "try", "{", "connectToSocket", "(", "rtmUrl", ".", "getUrl", "(", ")", ".", "concat", "(", "\"", "&isReconnect=true", "\"", ")", ",", "true", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "@", "Override", "public", "void", "onError", "(", "Throwable", "throwable", ")", "{", "}", "@", "Override", "public", "void", "onComplete", "(", ")", "{", "}", "}", ")", ";", "}", "public", "void", "onTokenRefresh", "(", "String", "token", ")", "{", "JWTToken", "=", "token", ";", "reconnect", "(", ")", ";", "}", "/**\n * @param msg : The message object\n * @return Was it able to successfully send the message.\n */", "public", "boolean", "sendMessage", "(", "String", "msg", ")", "{", "if", "(", "mConnection", "!=", "null", "&&", "mConnection", ".", "isConnected", "(", ")", ")", "{", "mConnection", ".", "sendMessage", "(", "msg", ")", ";", "return", "true", ";", "}", "else", "{", "if", "(", "userAccessToken", "!=", "null", "&&", "socketConnectionListener", "!=", "null", ")", "{", "socketConnectionListener", ".", "refreshJwtToken", "(", ")", ";", "}", "else", "{", "reconnect", "(", ")", ";", "}", "Log", ".", "e", "(", "LOG_TAG", ",", "\"", "Connection is not present. Reconnecting...", "\"", ")", ";", "return", "false", ";", "}", "}", "/*\n * Method to Reconnection attempt based on incremental delay\n *\n * @reurn\n */", "private", "void", "reconnectAttempt", "(", ")", "{", "mReconnectDelay", "=", "getReconnectDelay", "(", ")", ";", "try", "{", "final", "Handler", "_handler", "=", "new", "Handler", "(", ")", ";", "Runnable", "r", "=", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "Log", ".", "d", "(", "LOG_TAG", ",", "\"", "Entered into reconnection post delayed ", "\"", "+", "mReconnectDelay", ")", ";", "if", "(", "mIsReconnectionAttemptNeeded", "&&", "!", "isConnected", "(", ")", ")", "{", "reconnect", "(", ")", ";", "mReconnectDelay", "=", "getReconnectDelay", "(", ")", ";", "_handler", ".", "postDelayed", "(", "this", ",", "mReconnectDelay", ")", ";", "Log", ".", "d", "(", "LOG_TAG", ",", "\"", "#### trying to reconnect", "\"", ")", ";", "}", "}", "}", ";", "_handler", ".", "postDelayed", "(", "r", ",", "mReconnectDelay", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "d", "(", "LOG_TAG", ",", "\"", ":: The Exception is ", "\"", "+", "e", ".", "toString", "(", ")", ")", ";", "}", "}", "/**\n * The reconnection attempt delay(incremental delay)\n *\n * @return\n */", "private", "int", "getReconnectDelay", "(", ")", "{", "mReconnectionCount", "++", ";", "Log", ".", "d", "(", "LOG_TAG", ",", "\"", "Reconnection count ", "\"", "+", "mReconnectionCount", ")", ";", "if", "(", "mReconnectionCount", ">", "6", ")", "mReconnectionCount", "=", "1", ";", "Random", "rint", "=", "new", "Random", "(", ")", ";", "return", "(", "rint", ".", "nextInt", "(", "5", ")", "+", "1", ")", "*", "mReconnectionCount", "*", "1000", ";", "}", "/**\n * For disconnecting user's presence\n * Call this method when the user logged out\n */", "public", "void", "disConnect", "(", ")", "{", "mIsReconnectionAttemptNeeded", "=", "false", ";", "if", "(", "mConnection", "!=", "null", "&&", "mConnection", ".", "isConnected", "(", ")", ")", "{", "try", "{", "mConnection", ".", "sendClose", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "d", "(", "LOG_TAG", ",", "\"", "Exception while disconnection", "\"", ")", ";", "}", "Log", ".", "d", "(", "LOG_TAG", ",", "\"", "DisConnected successfully", "\"", ")", ";", "}", "else", "{", "Log", ".", "d", "(", "LOG_TAG", ",", "\"", "Cannot disconnect.._client is null", "\"", ")", ";", "}", "BotRestBuilder", ".", "clearInstance", "(", ")", ";", "auth", "=", "null", ";", "botUserId", "=", "null", ";", "/*if (isConnected()) {\n stop();\n }*/", "}", "/**\n * Determine the TLS enability of the url.\n * @param url url to connect to (is generally either ws:// or wss://)\n */", "/* private void determineTLSEnability(String url) {\n mTLSEnabled = url.startsWith(Constants.SECURE_WEBSOCKET_PREFIX);\n }*/", "/**\n * To determine wither socket is connected or not\n * @return boolean indicating the connection presence.\n */", "public", "boolean", "isConnected", "(", ")", "{", "if", "(", "mConnection", "!=", "null", "&&", "mConnection", ".", "isConnected", "(", ")", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "public", "String", "getBotUserId", "(", ")", "{", "return", "botUserId", ";", "}", "public", "void", "setBotUserId", "(", "String", "botUserId", ")", "{", "this", ".", "botUserId", "=", "botUserId", ";", "}", "}" ]
Created by Ramachandra Pradeep on 6/1/2016.
[ "Created", "by", "Ramachandra", "Pradeep", "on", "6", "/", "1", "/", "2016", "." ]
[ "//", "// private final WebSocketConnection mConnection = new WebSocketConnection();", "// private String url;", "// private URI uri;", "// private boolean mTLSEnabled = false;", "// start(mContext);", "// KoreEventCenter.register(this);", "// synchronized (SocketWrapper.class) {", "// if(pKorePresenceInstance == null) {", "// }", "// }", "// final RestAPI restAPI = BotRestBuilder.getBotRestService();", "//TODO For speed connection", "//If spiceManager is not started then start it", "// Log.d(\"IKIDO\",\"Hey Initiating Socket\");", "//If spiceManager is not started then start it", "// Log.d(\"IKIDO\",\"on complete called man\");", "// this.url = url;", "// this.uri = new URI(url);", "// Log.d(LOG_TAG, \"Connection Open.\");", "// if(Utils.isNetworkAvailable(mContext))", "// Log.d(LOG_TAG, \"onTextMessage payload :\" + payload);", "//Reconnection for valid credential", "//Reconnection for anonymous", "// mIsImmediateFetchActionNeeded = true;", "// Toast.makeText(mContext,\"SocketDisConnected\",Toast.LENGTH_SHORT).show();", "//The bot URL may change" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c41cdbbebea95fe9dbb0872c9de8e2516f07b9fb
sola-da/TSFinder
src/tsfinder/Utils.java
[ "MIT" ]
Java
Utils
/** * @author Andrew Habib * */
@author Andrew Habib
[ "@author", "Andrew", "Habib" ]
public class Utils { public static List<String> ReadListFromFile(String path) { List<String> lines = null; try { lines = Files.readAllLines(Paths.get(path)); } catch (IOException e) { e.printStackTrace(); } if (lines == null) System.out.println("Warning: File at " + path + "is empty."); return lines; } public static String[] GetSootArgs() { String args = ""; // args += "-w "; // args += "-allow-phantom-refs "; args += "-p cg "; args += "library:any-subtype,all-reachable:true "; args += "include-all "; args += "-w "; args += "-full-resolver "; args += "-allow-phantom-refs "; args += "-f n "; args += "-cp " + Config.SOOT_CP + " "; args += "-process-dir "; args += Config.DIR_TO_ANALYZE; System.out.println(args); return args.split(" "); } public static boolean hasSyncBlock(SootMethod m) { // RuntimeException thrown here is meant to // prevent the analysis from crashing when // m.retrieveActiveBody() throws an exception // when it can't get a method body. if (m.isConcrete()) { JimpleBody jbody = (JimpleBody) m.retrieveActiveBody(); Iterator<Unit> it = jbody.getUnits().iterator(); while (it.hasNext()) { if (it.next() instanceof MonitorStmt) { return true; } } } return false; } /** * Careful when using this as it may return null if the local does not * correspond to any class field. * * @param l * @param body * @return SootField or null */ public static SootField getFieldFromLocal(Local l, Body body) { SootClass cl = body.getMethod().getDeclaringClass(); List<SootField> hierarchyFields = new ArrayList<>(); while (cl.getName() != "java.lang.Object" && !cl.isPhantom() && cl != null) { hierarchyFields.addAll(cl.getFields()); cl = cl.getSuperclass(); } DefinitionStmt defStmt; for (Unit u : body.getUnits()) { if (u instanceof DefinitionStmt) { defStmt = (DefinitionStmt) u; Value lhsOp = defStmt.getLeftOp(); if (lhsOp == l) { Value rhsOp = defStmt.getRightOp(); if (rhsOp instanceof FieldRef) { SootField f = ((FieldRef) rhsOp).getField(); if (hierarchyFields.contains(f)) return f; } else if (rhsOp instanceof ArrayRef) return getFieldFromLocal((Local) ((ArrayRef) rhsOp).getBase(), body); } } } return null; } }
[ "public", "class", "Utils", "{", "public", "static", "List", "<", "String", ">", "ReadListFromFile", "(", "String", "path", ")", "{", "List", "<", "String", ">", "lines", "=", "null", ";", "try", "{", "lines", "=", "Files", ".", "readAllLines", "(", "Paths", ".", "get", "(", "path", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "if", "(", "lines", "==", "null", ")", "System", ".", "out", ".", "println", "(", "\"", "Warning: File at ", "\"", "+", "path", "+", "\"", "is empty.", "\"", ")", ";", "return", "lines", ";", "}", "public", "static", "String", "[", "]", "GetSootArgs", "(", ")", "{", "String", "args", "=", "\"", "\"", ";", "args", "+=", "\"", "-p cg ", "\"", ";", "args", "+=", "\"", "library:any-subtype,all-reachable:true ", "\"", ";", "args", "+=", "\"", "include-all ", "\"", ";", "args", "+=", "\"", "-w ", "\"", ";", "args", "+=", "\"", "-full-resolver ", "\"", ";", "args", "+=", "\"", "-allow-phantom-refs ", "\"", ";", "args", "+=", "\"", "-f n ", "\"", ";", "args", "+=", "\"", "-cp ", "\"", "+", "Config", ".", "SOOT_CP", "+", "\"", " ", "\"", ";", "args", "+=", "\"", "-process-dir ", "\"", ";", "args", "+=", "Config", ".", "DIR_TO_ANALYZE", ";", "System", ".", "out", ".", "println", "(", "args", ")", ";", "return", "args", ".", "split", "(", "\"", " ", "\"", ")", ";", "}", "public", "static", "boolean", "hasSyncBlock", "(", "SootMethod", "m", ")", "{", "if", "(", "m", ".", "isConcrete", "(", ")", ")", "{", "JimpleBody", "jbody", "=", "(", "JimpleBody", ")", "m", ".", "retrieveActiveBody", "(", ")", ";", "Iterator", "<", "Unit", ">", "it", "=", "jbody", ".", "getUnits", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "if", "(", "it", ".", "next", "(", ")", "instanceof", "MonitorStmt", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}", "/**\n\t * Careful when using this as it may return null if the local does not\n\t * correspond to any class field.\n\t * \n\t * @param l\n\t * @param body\n\t * @return SootField or null\n\t */", "public", "static", "SootField", "getFieldFromLocal", "(", "Local", "l", ",", "Body", "body", ")", "{", "SootClass", "cl", "=", "body", ".", "getMethod", "(", ")", ".", "getDeclaringClass", "(", ")", ";", "List", "<", "SootField", ">", "hierarchyFields", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "while", "(", "cl", ".", "getName", "(", ")", "!=", "\"", "java.lang.Object", "\"", "&&", "!", "cl", ".", "isPhantom", "(", ")", "&&", "cl", "!=", "null", ")", "{", "hierarchyFields", ".", "addAll", "(", "cl", ".", "getFields", "(", ")", ")", ";", "cl", "=", "cl", ".", "getSuperclass", "(", ")", ";", "}", "DefinitionStmt", "defStmt", ";", "for", "(", "Unit", "u", ":", "body", ".", "getUnits", "(", ")", ")", "{", "if", "(", "u", "instanceof", "DefinitionStmt", ")", "{", "defStmt", "=", "(", "DefinitionStmt", ")", "u", ";", "Value", "lhsOp", "=", "defStmt", ".", "getLeftOp", "(", ")", ";", "if", "(", "lhsOp", "==", "l", ")", "{", "Value", "rhsOp", "=", "defStmt", ".", "getRightOp", "(", ")", ";", "if", "(", "rhsOp", "instanceof", "FieldRef", ")", "{", "SootField", "f", "=", "(", "(", "FieldRef", ")", "rhsOp", ")", ".", "getField", "(", ")", ";", "if", "(", "hierarchyFields", ".", "contains", "(", "f", ")", ")", "return", "f", ";", "}", "else", "if", "(", "rhsOp", "instanceof", "ArrayRef", ")", "return", "getFieldFromLocal", "(", "(", "Local", ")", "(", "(", "ArrayRef", ")", "rhsOp", ")", ".", "getBase", "(", ")", ",", "body", ")", ";", "}", "}", "}", "return", "null", ";", "}", "}" ]
@author Andrew Habib
[ "@author", "Andrew", "Habib" ]
[ "//\t\targs += \"-w \";", "//\t\targs += \"-allow-phantom-refs \";", "// RuntimeException thrown here is meant to", "// prevent the analysis from crashing when", "// m.retrieveActiveBody() throws an exception", "// when it can't get a method body." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c4201bbb1f974a94dc15adc7d380a995005530c1
opensim-org/opensim-gui
Gui/opensim/modeling/src/org/opensim/modeling/VectorBaseDouble.java
[ "Apache-2.0" ]
Java
VectorBaseDouble
/** * This is a dataless rehash of the MatrixBase class to specialize it for Vectors.<br> * This mostly entails overriding a few of the methods. Note that all the MatrixBase<br> * operations remain available if you static_cast&lt;&gt; this up to a MatrixBase. */
This is a dataless rehash of the MatrixBase class to specialize it for Vectors. This mostly entails overriding a few of the methods. Note that all the MatrixBase operations remain available if you static_cast<> this up to a MatrixBase.
[ "This", "is", "a", "dataless", "rehash", "of", "the", "MatrixBase", "class", "to", "specialize", "it", "for", "Vectors", ".", "This", "mostly", "entails", "overriding", "a", "few", "of", "the", "methods", ".", "Note", "that", "all", "the", "MatrixBase", "operations", "remain", "available", "if", "you", "static_cast<", ">", "this", "up", "to", "a", "MatrixBase", "." ]
public class VectorBaseDouble extends MatrixBaseDouble { private transient long swigCPtr; public VectorBaseDouble(long cPtr, boolean cMemoryOwn) { super(opensimSimbodyJNI.VectorBaseDouble_SWIGUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } public static long getCPtr(VectorBaseDouble obj) { return (obj == null) ? 0 : obj.swigCPtr; } @SuppressWarnings("deprecation") protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; opensimSimbodyJNI.delete_VectorBaseDouble(swigCPtr); } swigCPtr = 0; } super.delete(); } public double[][] getAsMat() { double[][] ret = new double[size()][1]; for (int i = 0; i < size(); ++i) { ret[i][0] = get(i); } return ret; } /** * These constructors create new VectorBase objects which own their<br> * own data and are (at least by default) resizable. The resulting matrices<br> * are m X 1 with the number of columns locked at 1. If there is any data<br> * allocated but not explicitly initialized, that data will be uninitialized<br> * garbage in Release builds but will be initialized to NaN (at a performance<br> * cost) in Debug builds.<br> * <br> * Default constructor makes a 0x1 matrix locked at 1 column; you can<br> * provide an initial allocation if you want. */ public VectorBaseDouble(int m) { this(opensimSimbodyJNI.new_VectorBaseDouble__SWIG_0(m), true); } /** * These constructors create new VectorBase objects which own their<br> * own data and are (at least by default) resizable. The resulting matrices<br> * are m X 1 with the number of columns locked at 1. If there is any data<br> * allocated but not explicitly initialized, that data will be uninitialized<br> * garbage in Release builds but will be initialized to NaN (at a performance<br> * cost) in Debug builds.<br> * <br> * Default constructor makes a 0x1 matrix locked at 1 column; you can<br> * provide an initial allocation if you want. */ public VectorBaseDouble() { this(opensimSimbodyJNI.new_VectorBaseDouble__SWIG_1(), true); } /** * Copy constructor is a deep copy (not appropriate for views!). That<br> * means it creates a new, densely packed vector whose elements are<br> * initialized from the source object. */ public VectorBaseDouble(VectorBaseDouble source) { this(opensimSimbodyJNI.new_VectorBaseDouble__SWIG_2(VectorBaseDouble.getCPtr(source), source), true); } public int size() { return opensimSimbodyJNI.VectorBaseDouble_size(swigCPtr, this); } public int nrow() { return opensimSimbodyJNI.VectorBaseDouble_nrow(swigCPtr, this); } public int ncol() { return opensimSimbodyJNI.VectorBaseDouble_ncol(swigCPtr, this); } public VectorBaseDouble resize(int m) { return new VectorBaseDouble(opensimSimbodyJNI.VectorBaseDouble_resize(swigCPtr, this, m), false); } public VectorBaseDouble resizeKeep(int m) { return new VectorBaseDouble(opensimSimbodyJNI.VectorBaseDouble_resizeKeep(swigCPtr, this, m), false); } public void clear() { opensimSimbodyJNI.VectorBaseDouble_clear(swigCPtr, this); } public double sum() { return opensimSimbodyJNI.VectorBaseDouble_sum(swigCPtr, this); } public double get(int i) { return opensimSimbodyJNI.VectorBaseDouble_get(swigCPtr, this, i); } public void set(int i, double value) { opensimSimbodyJNI.VectorBaseDouble_set(swigCPtr, this, i, value); } public double __getitem__(int i) { return opensimSimbodyJNI.VectorBaseDouble___getitem__(swigCPtr, this, i); } public void __setitem__(int i, double value) { opensimSimbodyJNI.VectorBaseDouble___setitem__(swigCPtr, this, i, value); } }
[ "public", "class", "VectorBaseDouble", "extends", "MatrixBaseDouble", "{", "private", "transient", "long", "swigCPtr", ";", "public", "VectorBaseDouble", "(", "long", "cPtr", ",", "boolean", "cMemoryOwn", ")", "{", "super", "(", "opensimSimbodyJNI", ".", "VectorBaseDouble_SWIGUpcast", "(", "cPtr", ")", ",", "cMemoryOwn", ")", ";", "swigCPtr", "=", "cPtr", ";", "}", "public", "static", "long", "getCPtr", "(", "VectorBaseDouble", "obj", ")", "{", "return", "(", "obj", "==", "null", ")", "?", "0", ":", "obj", ".", "swigCPtr", ";", "}", "@", "SuppressWarnings", "(", "\"", "deprecation", "\"", ")", "protected", "void", "finalize", "(", ")", "{", "delete", "(", ")", ";", "}", "public", "synchronized", "void", "delete", "(", ")", "{", "if", "(", "swigCPtr", "!=", "0", ")", "{", "if", "(", "swigCMemOwn", ")", "{", "swigCMemOwn", "=", "false", ";", "opensimSimbodyJNI", ".", "delete_VectorBaseDouble", "(", "swigCPtr", ")", ";", "}", "swigCPtr", "=", "0", ";", "}", "super", ".", "delete", "(", ")", ";", "}", "public", "double", "[", "]", "[", "]", "getAsMat", "(", ")", "{", "double", "[", "]", "[", "]", "ret", "=", "new", "double", "[", "size", "(", ")", "]", "[", "1", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", "(", ")", ";", "++", "i", ")", "{", "ret", "[", "i", "]", "[", "0", "]", "=", "get", "(", "i", ")", ";", "}", "return", "ret", ";", "}", "/**\n * These constructors create new VectorBase objects which own their<br>\n * own data and are (at least by default) resizable. The resulting matrices<br>\n * are m X 1 with the number of columns locked at 1. If there is any data<br>\n * allocated but not explicitly initialized, that data will be uninitialized<br>\n * garbage in Release builds but will be initialized to NaN (at a performance<br>\n * cost) in Debug builds.<br>\n * <br>\n * Default constructor makes a 0x1 matrix locked at 1 column; you can<br>\n * provide an initial allocation if you want.\n */", "public", "VectorBaseDouble", "(", "int", "m", ")", "{", "this", "(", "opensimSimbodyJNI", ".", "new_VectorBaseDouble__SWIG_0", "(", "m", ")", ",", "true", ")", ";", "}", "/**\n * These constructors create new VectorBase objects which own their<br>\n * own data and are (at least by default) resizable. The resulting matrices<br>\n * are m X 1 with the number of columns locked at 1. If there is any data<br>\n * allocated but not explicitly initialized, that data will be uninitialized<br>\n * garbage in Release builds but will be initialized to NaN (at a performance<br>\n * cost) in Debug builds.<br>\n * <br>\n * Default constructor makes a 0x1 matrix locked at 1 column; you can<br>\n * provide an initial allocation if you want.\n */", "public", "VectorBaseDouble", "(", ")", "{", "this", "(", "opensimSimbodyJNI", ".", "new_VectorBaseDouble__SWIG_1", "(", ")", ",", "true", ")", ";", "}", "/**\n * Copy constructor is a deep copy (not appropriate for views!). That<br>\n * means it creates a new, densely packed vector whose elements are<br>\n * initialized from the source object.\n */", "public", "VectorBaseDouble", "(", "VectorBaseDouble", "source", ")", "{", "this", "(", "opensimSimbodyJNI", ".", "new_VectorBaseDouble__SWIG_2", "(", "VectorBaseDouble", ".", "getCPtr", "(", "source", ")", ",", "source", ")", ",", "true", ")", ";", "}", "public", "int", "size", "(", ")", "{", "return", "opensimSimbodyJNI", ".", "VectorBaseDouble_size", "(", "swigCPtr", ",", "this", ")", ";", "}", "public", "int", "nrow", "(", ")", "{", "return", "opensimSimbodyJNI", ".", "VectorBaseDouble_nrow", "(", "swigCPtr", ",", "this", ")", ";", "}", "public", "int", "ncol", "(", ")", "{", "return", "opensimSimbodyJNI", ".", "VectorBaseDouble_ncol", "(", "swigCPtr", ",", "this", ")", ";", "}", "public", "VectorBaseDouble", "resize", "(", "int", "m", ")", "{", "return", "new", "VectorBaseDouble", "(", "opensimSimbodyJNI", ".", "VectorBaseDouble_resize", "(", "swigCPtr", ",", "this", ",", "m", ")", ",", "false", ")", ";", "}", "public", "VectorBaseDouble", "resizeKeep", "(", "int", "m", ")", "{", "return", "new", "VectorBaseDouble", "(", "opensimSimbodyJNI", ".", "VectorBaseDouble_resizeKeep", "(", "swigCPtr", ",", "this", ",", "m", ")", ",", "false", ")", ";", "}", "public", "void", "clear", "(", ")", "{", "opensimSimbodyJNI", ".", "VectorBaseDouble_clear", "(", "swigCPtr", ",", "this", ")", ";", "}", "public", "double", "sum", "(", ")", "{", "return", "opensimSimbodyJNI", ".", "VectorBaseDouble_sum", "(", "swigCPtr", ",", "this", ")", ";", "}", "public", "double", "get", "(", "int", "i", ")", "{", "return", "opensimSimbodyJNI", ".", "VectorBaseDouble_get", "(", "swigCPtr", ",", "this", ",", "i", ")", ";", "}", "public", "void", "set", "(", "int", "i", ",", "double", "value", ")", "{", "opensimSimbodyJNI", ".", "VectorBaseDouble_set", "(", "swigCPtr", ",", "this", ",", "i", ",", "value", ")", ";", "}", "public", "double", "__getitem__", "(", "int", "i", ")", "{", "return", "opensimSimbodyJNI", ".", "VectorBaseDouble___getitem__", "(", "swigCPtr", ",", "this", ",", "i", ")", ";", "}", "public", "void", "__setitem__", "(", "int", "i", ",", "double", "value", ")", "{", "opensimSimbodyJNI", ".", "VectorBaseDouble___setitem__", "(", "swigCPtr", ",", "this", ",", "i", ",", "value", ")", ";", "}", "}" ]
This is a dataless rehash of the MatrixBase class to specialize it for Vectors.<br> This mostly entails overriding a few of the methods.
[ "This", "is", "a", "dataless", "rehash", "of", "the", "MatrixBase", "class", "to", "specialize", "it", "for", "Vectors", ".", "<br", ">", "This", "mostly", "entails", "overriding", "a", "few", "of", "the", "methods", "." ]
[]
[ { "param": "MatrixBaseDouble", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MatrixBaseDouble", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c4203522f2f82ad9f4c1487a492b86d63a23c91e
victorlvg678/SSPEDD2-Hotel
controllers/RegistroCRUD.java
[ "CC0-1.0" ]
Java
RegistroCRUD
// Clase principal de Archivo
Clase principal de Archivo
[ "Clase", "principal", "de", "Archivo" ]
public class RegistroCRUD { // Atributos privados private String RegistroTemp; private String URLTemp; // |------------------------Métodos públicos-------------------------------| // Constructor de clase public RegistroCRUD() { RegistroTemp = System.getenv("USERPROFILE") + "\\AppData\\Local\\Temp\\RegistroTempHotel.data"; URLTemp = "https://raw.githubusercontent.com/victorlvg678/SSPEDD2-Hotel/master/RegistroTempHotel.data"; } // Constructor copia de clase public RegistroCRUD(RegistroCRUD RegistroCRUDOriginal) { RegistroTemp = RegistroCRUDOriginal.RegistroTemp; URLTemp = RegistroCRUDOriginal.URLTemp; } // |---------------------------Setters-------------------------------------| // Setter para atributo RegistroTemp public void setRegistroTemp(String RegistroTempAAsignar) { RegistroTemp = RegistroTempAAsignar; } // Setter para atributo URL public void setURL(String URLAAsignar) { URLTemp = URLAAsignar; } // |---------------------------Getters-------------------------------------| // Getter para atributo RegistroTemp public String getRegistroTemp() { return RegistroTemp; } // Getter para atributo URL public String getURL() { return URLTemp; } // |--------------------------Guardar---------------------------------------| // Método para añadir usuario a archivo temporal public void Guardar(Registro RegistroAGuardar) { // Intenta el siguiente bloque de instrucciones try{ // Para recorrer registros int x; File ArchivoTemporal = new File(RegistroTemp); if(ArchivoTemporal.exists()) { if(ArchivoTemporal.delete()) { System.out.println("Se ha eliminado " + ArchivoTemporal.getName()); } else { System.out.println("Ocurrió un problema al intentar eliminar " + ArchivoTemporal.getName()); } if(ArchivoTemporal.createNewFile()) { System.out.println("Se ha creado " + ArchivoTemporal.getName()); } else { System.out.println("Ocurrió un problema al intenetar crear " + ArchivoTemporal.getName()); } } else { if(ArchivoTemporal.createNewFile()) { System.out.println("Se ha creado " + ArchivoTemporal.getName()); } else { System.out.println("Ocurrió un problema al intenetar crear " + ArchivoTemporal.getName()); } } // Creamos un outputstream para el archivo FileOutputStream FOS = new FileOutputStream(RegistroTemp, true); // Creamos un escritor para el outputstream en UTF-8 OutputStreamWriter OSW = new OutputStreamWriter(FOS, StandardCharsets.UTF_8); // Creamos un buffer para el escritor BufferedWriter Writer = new BufferedWriter(OSW); Writer.append(Serializacion.Serializar(RegistroAGuardar)); // Cerrar todo Writer.close(); OSW.close(); FOS.close(); } catch(IOException ex) { // Define e Logger.getLogger(RegistroCRUD.class.getName()).log(Level.SEVERE, null, ex); } } // |-----------------------Cargar------------------------------------------| public Registro Cargar() { // Instanciar Registro Registro RegistroCargado = new Registro(); String RegistroB64; RegistroB64 = ""; try { File ArchivoTemporal = new File(RegistroTemp); if(!ArchivoTemporal.exists()) { if(ArchivoTemporal.createNewFile()) { System.out.println("Se ha creado " + ArchivoTemporal.getName()); } else { System.out.println("Ocurrió un problema al intenetar crear " + ArchivoTemporal.getName()); } } else { // Creamos un inputstream para el archivo FileInputStream FIS = new FileInputStream(RegistroTemp); // Creamos un lector de dicho inputstream en UTF-8 InputStreamReader ISR = new InputStreamReader(FIS, StandardCharsets.UTF_8); // Y creamos un buffer para el lector BufferedReader Reader = new BufferedReader(ISR); String StrTemp; StrTemp = Reader.readLine(); while(StrTemp != null) { RegistroB64 += StrTemp; StrTemp = Reader.readLine(); } // Cerrar todo Reader.close(); ISR.close(); FIS.close(); } } catch(IOException ex) { // Define e Logger.getLogger(RegistroCRUD.class.getName()).log(Level.SEVERE, null, ex); } RegistroCargado = Serializacion.Deserializar(RegistroB64); return RegistroCargado; } }
[ "public", "class", "RegistroCRUD", "{", "private", "String", "RegistroTemp", ";", "private", "String", "URLTemp", ";", "public", "RegistroCRUD", "(", ")", "{", "RegistroTemp", "=", "System", ".", "getenv", "(", "\"", "USERPROFILE", "\"", ")", "+", "\"", "\\\\", "AppData", "\\\\", "Local", "\\\\", "Temp", "\\\\", "RegistroTempHotel.data", "\"", ";", "URLTemp", "=", "\"", "https://raw.githubusercontent.com/victorlvg678/SSPEDD2-Hotel/master/RegistroTempHotel.data", "\"", ";", "}", "public", "RegistroCRUD", "(", "RegistroCRUD", "RegistroCRUDOriginal", ")", "{", "RegistroTemp", "=", "RegistroCRUDOriginal", ".", "RegistroTemp", ";", "URLTemp", "=", "RegistroCRUDOriginal", ".", "URLTemp", ";", "}", "public", "void", "setRegistroTemp", "(", "String", "RegistroTempAAsignar", ")", "{", "RegistroTemp", "=", "RegistroTempAAsignar", ";", "}", "public", "void", "setURL", "(", "String", "URLAAsignar", ")", "{", "URLTemp", "=", "URLAAsignar", ";", "}", "public", "String", "getRegistroTemp", "(", ")", "{", "return", "RegistroTemp", ";", "}", "public", "String", "getURL", "(", ")", "{", "return", "URLTemp", ";", "}", "public", "void", "Guardar", "(", "Registro", "RegistroAGuardar", ")", "{", "try", "{", "int", "x", ";", "File", "ArchivoTemporal", "=", "new", "File", "(", "RegistroTemp", ")", ";", "if", "(", "ArchivoTemporal", ".", "exists", "(", ")", ")", "{", "if", "(", "ArchivoTemporal", ".", "delete", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Se ha eliminado ", "\"", "+", "ArchivoTemporal", ".", "getName", "(", ")", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "Ocurrió un problema al intentar eliminar \"", " ", " ", "ArchivoTemporal", ".", "getName", "(", ")", ")", ";", "}", "if", "(", "ArchivoTemporal", ".", "createNewFile", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Se ha creado ", "\"", "+", "ArchivoTemporal", ".", "getName", "(", ")", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "Ocurrió un problema al intenetar crear \"", " ", " ", "ArchivoTemporal", ".", "getName", "(", ")", ")", ";", "}", "}", "else", "{", "if", "(", "ArchivoTemporal", ".", "createNewFile", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Se ha creado ", "\"", "+", "ArchivoTemporal", ".", "getName", "(", ")", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "Ocurrió un problema al intenetar crear \"", " ", " ", "ArchivoTemporal", ".", "getName", "(", ")", ")", ";", "}", "}", "FileOutputStream", "FOS", "=", "new", "FileOutputStream", "(", "RegistroTemp", ",", "true", ")", ";", "OutputStreamWriter", "OSW", "=", "new", "OutputStreamWriter", "(", "FOS", ",", "StandardCharsets", ".", "UTF_8", ")", ";", "BufferedWriter", "Writer", "=", "new", "BufferedWriter", "(", "OSW", ")", ";", "Writer", ".", "append", "(", "Serializacion", ".", "Serializar", "(", "RegistroAGuardar", ")", ")", ";", "Writer", ".", "close", "(", ")", ";", "OSW", ".", "close", "(", ")", ";", "FOS", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "Logger", ".", "getLogger", "(", "RegistroCRUD", ".", "class", ".", "getName", "(", ")", ")", ".", "log", "(", "Level", ".", "SEVERE", ",", "null", ",", "ex", ")", ";", "}", "}", "public", "Registro", "Cargar", "(", ")", "{", "Registro", "RegistroCargado", "=", "new", "Registro", "(", ")", ";", "String", "RegistroB64", ";", "RegistroB64", "=", "\"", "\"", ";", "try", "{", "File", "ArchivoTemporal", "=", "new", "File", "(", "RegistroTemp", ")", ";", "if", "(", "!", "ArchivoTemporal", ".", "exists", "(", ")", ")", "{", "if", "(", "ArchivoTemporal", ".", "createNewFile", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Se ha creado ", "\"", "+", "ArchivoTemporal", ".", "getName", "(", ")", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "Ocurrió un problema al intenetar crear \"", " ", " ", "ArchivoTemporal", ".", "getName", "(", ")", ")", ";", "}", "}", "else", "{", "FileInputStream", "FIS", "=", "new", "FileInputStream", "(", "RegistroTemp", ")", ";", "InputStreamReader", "ISR", "=", "new", "InputStreamReader", "(", "FIS", ",", "StandardCharsets", ".", "UTF_8", ")", ";", "BufferedReader", "Reader", "=", "new", "BufferedReader", "(", "ISR", ")", ";", "String", "StrTemp", ";", "StrTemp", "=", "Reader", ".", "readLine", "(", ")", ";", "while", "(", "StrTemp", "!=", "null", ")", "{", "RegistroB64", "+=", "StrTemp", ";", "StrTemp", "=", "Reader", ".", "readLine", "(", ")", ";", "}", "Reader", ".", "close", "(", ")", ";", "ISR", ".", "close", "(", ")", ";", "FIS", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "IOException", "ex", ")", "{", "Logger", ".", "getLogger", "(", "RegistroCRUD", ".", "class", ".", "getName", "(", ")", ")", ".", "log", "(", "Level", ".", "SEVERE", ",", "null", ",", "ex", ")", ";", "}", "RegistroCargado", "=", "Serializacion", ".", "Deserializar", "(", "RegistroB64", ")", ";", "return", "RegistroCargado", ";", "}", "}" ]
Clase principal de Archivo
[ "Clase", "principal", "de", "Archivo" ]
[ "// Atributos privados", "// |------------------------Métodos públicos-------------------------------|", "// Constructor de clase", "// Constructor copia de clase", "// |---------------------------Setters-------------------------------------|", "// Setter para atributo RegistroTemp", "// Setter para atributo URL", "// |---------------------------Getters-------------------------------------|", "// Getter para atributo RegistroTemp", "// Getter para atributo URL", "// |--------------------------Guardar---------------------------------------|", "// Método para añadir usuario a archivo temporal", "// Intenta el siguiente bloque de instrucciones", "// Para recorrer registros", "// Creamos un outputstream para el archivo", "// Creamos un escritor para el outputstream en UTF-8", "// Creamos un buffer para el escritor", "// Cerrar todo", "// Define e", "// |-----------------------Cargar------------------------------------------|", "// Instanciar Registro", "// Creamos un inputstream para el archivo", "// Creamos un lector de dicho inputstream en UTF-8", "// Y creamos un buffer para el lector", "// Cerrar todo", "// Define e" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c42238e5c684791c456ad853de4f6df5923200ee
zsfenggy/Androrm
androrm/src/main/java/com/orm/androrm/OrderBy.java
[ "Apache-2.0" ]
Java
OrderBy
/** * @author Philipp Giese */
@author Philipp Giese
[ "@author", "Philipp", "Giese" ]
public class OrderBy { private String mOrderBy; /** * Add an ORDER BY statement. For convenience ASC and DESC can * be toggled by adding a preceding a <code>+</code> or <code>-</code> * to the table column. In order to sort the table column in numerical * order add the prefix #. * <br /><br /> * For example <code>-foo</code> will result in <code>foo DESC</code>. * <br /><br /> * If no preceding <code>+</code> or <code>-</code> is given * <code>ASC</code> is assumed. * * @param columns Names of the table column. */ public OrderBy(String... columns) { boolean first = true; for(int i = 0, length = columns.length; i < length; i++) { String col = columns[i]; if(!first) { mOrderBy += ", "; } else { mOrderBy = " "; } if(col.startsWith("#")) { if(col.startsWith("-")) { mOrderBy += "CAST(" +col.substring(2) + " AS INTEGER) DESC"; } else if(col.startsWith("+")) { mOrderBy += "CAST(" +col.substring(2) + " AS INTEGER) ASC"; } else { mOrderBy += "CAST(" +col.substring(1) + " AS INTEGER) ASC"; } }else{ if(col.startsWith("-")) { mOrderBy += "UPPER(" + col.substring(1) + ") DESC"; } else if(col.startsWith("+")) { mOrderBy += "UPPER(" + col.substring(1) + ") ASC"; } else { mOrderBy += "UPPER(" + col + ") ASC"; } } if(first) { first = false; } } } @Override public String toString() { return " ORDER BY" + mOrderBy; } }
[ "public", "class", "OrderBy", "{", "private", "String", "mOrderBy", ";", "/**\n\t * Add an ORDER BY statement. For convenience ASC and DESC can\n\t * be toggled by adding a preceding a <code>+</code> or <code>-</code>\n\t * to the table column. In order to sort the table column in numerical\n\t * order add the prefix #.\n\t * <br /><br />\n\t * For example <code>-foo</code> will result in <code>foo DESC</code>.\n\t * <br /><br />\n\t * If no preceding <code>+</code> or <code>-</code> is given \n\t * <code>ASC</code> is assumed.\n\t * \n\t * @param columns Names of the table column.\n\t */", "public", "OrderBy", "(", "String", "...", "columns", ")", "{", "boolean", "first", "=", "true", ";", "for", "(", "int", "i", "=", "0", ",", "length", "=", "columns", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "String", "col", "=", "columns", "[", "i", "]", ";", "if", "(", "!", "first", ")", "{", "mOrderBy", "+=", "\"", ", ", "\"", ";", "}", "else", "{", "mOrderBy", "=", "\"", " ", "\"", ";", "}", "if", "(", "col", ".", "startsWith", "(", "\"", "#", "\"", ")", ")", "{", "if", "(", "col", ".", "startsWith", "(", "\"", "-", "\"", ")", ")", "{", "mOrderBy", "+=", "\"", "CAST(", "\"", "+", "col", ".", "substring", "(", "2", ")", "+", "\"", " AS INTEGER) DESC", "\"", ";", "}", "else", "if", "(", "col", ".", "startsWith", "(", "\"", "+", "\"", ")", ")", "{", "mOrderBy", "+=", "\"", "CAST(", "\"", "+", "col", ".", "substring", "(", "2", ")", "+", "\"", " AS INTEGER) ASC", "\"", ";", "}", "else", "{", "mOrderBy", "+=", "\"", "CAST(", "\"", "+", "col", ".", "substring", "(", "1", ")", "+", "\"", " AS INTEGER) ASC", "\"", ";", "}", "}", "else", "{", "if", "(", "col", ".", "startsWith", "(", "\"", "-", "\"", ")", ")", "{", "mOrderBy", "+=", "\"", "UPPER(", "\"", "+", "col", ".", "substring", "(", "1", ")", "+", "\"", ") DESC", "\"", ";", "}", "else", "if", "(", "col", ".", "startsWith", "(", "\"", "+", "\"", ")", ")", "{", "mOrderBy", "+=", "\"", "UPPER(", "\"", "+", "col", ".", "substring", "(", "1", ")", "+", "\"", ") ASC", "\"", ";", "}", "else", "{", "mOrderBy", "+=", "\"", "UPPER(", "\"", "+", "col", "+", "\"", ") ASC", "\"", ";", "}", "}", "if", "(", "first", ")", "{", "first", "=", "false", ";", "}", "}", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", " ORDER BY", "\"", "+", "mOrderBy", ";", "}", "}" ]
@author Philipp Giese
[ "@author", "Philipp", "Giese" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c427be14622abcf4982655b28a4a7c0619432a7c
benedictkhoomw/tp
src/main/java/seedu/address/commons/core/Messages.java
[ "MIT" ]
Java
Messages
/** * Container for user visible messages. */
Container for user visible messages.
[ "Container", "for", "user", "visible", "messages", "." ]
public class Messages { public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command"; public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s"; public static final String MESSAGE_INVALID_INDEX_PREAMBLE = "The provided INDEX is invalid. "; public static final String MESSAGE_INVALID_RESIDENT_DISPLAYED_INDEX = MESSAGE_INVALID_INDEX_PREAMBLE + "The Resident INDEX must be between 1 and %s (inclusive)"; public static final String MESSAGE_NO_RESIDENTS = "There are no Residents in your current view or no Residents in SunRez yet"; public static final String MESSAGE_RESIDENTS_LISTED_OVERVIEW = "%1$d residents listed!"; public static final String MESSAGE_INVALID_ROOM_DISPLAYED_INDEX = MESSAGE_INVALID_INDEX_PREAMBLE + "The Room INDEX must be between 1 and %s (inclusive)"; public static final String MESSAGE_NO_ROOMS = "There are no Rooms in your current view or no Rooms in SunRez yet"; public static final String MESSAGE_ROOMS_LISTED_OVERVIEW = "%1$d rooms listed!"; public static final String MESSAGE_INVALID_ISSUE_DISPLAYED_INDEX = MESSAGE_INVALID_INDEX_PREAMBLE + "The Issue INDEX must be between 1 and %s (inclusive)"; public static final String MESSAGE_NO_ISSUES = "There are no Issues in your current view or no Issues in SunRez yet"; public static final String MESSAGE_ISSUES_LISTED_OVERVIEW = "%1$d issues listed!"; }
[ "public", "class", "Messages", "{", "public", "static", "final", "String", "MESSAGE_UNKNOWN_COMMAND", "=", "\"", "Unknown command", "\"", ";", "public", "static", "final", "String", "MESSAGE_INVALID_COMMAND_FORMAT", "=", "\"", "Invalid command format! ", "\\n", "%1$s", "\"", ";", "public", "static", "final", "String", "MESSAGE_INVALID_INDEX_PREAMBLE", "=", "\"", "The provided INDEX is invalid. ", "\"", ";", "public", "static", "final", "String", "MESSAGE_INVALID_RESIDENT_DISPLAYED_INDEX", "=", "MESSAGE_INVALID_INDEX_PREAMBLE", "+", "\"", "The Resident INDEX must be between 1 and %s (inclusive)", "\"", ";", "public", "static", "final", "String", "MESSAGE_NO_RESIDENTS", "=", "\"", "There are no Residents in your current view or no Residents in SunRez yet", "\"", ";", "public", "static", "final", "String", "MESSAGE_RESIDENTS_LISTED_OVERVIEW", "=", "\"", "%1$d residents listed!", "\"", ";", "public", "static", "final", "String", "MESSAGE_INVALID_ROOM_DISPLAYED_INDEX", "=", "MESSAGE_INVALID_INDEX_PREAMBLE", "+", "\"", "The Room INDEX must be between 1 and %s (inclusive)", "\"", ";", "public", "static", "final", "String", "MESSAGE_NO_ROOMS", "=", "\"", "There are no Rooms in your current view or no Rooms in SunRez yet", "\"", ";", "public", "static", "final", "String", "MESSAGE_ROOMS_LISTED_OVERVIEW", "=", "\"", "%1$d rooms listed!", "\"", ";", "public", "static", "final", "String", "MESSAGE_INVALID_ISSUE_DISPLAYED_INDEX", "=", "MESSAGE_INVALID_INDEX_PREAMBLE", "+", "\"", "The Issue INDEX must be between 1 and %s (inclusive)", "\"", ";", "public", "static", "final", "String", "MESSAGE_NO_ISSUES", "=", "\"", "There are no Issues in your current view or no Issues in SunRez yet", "\"", ";", "public", "static", "final", "String", "MESSAGE_ISSUES_LISTED_OVERVIEW", "=", "\"", "%1$d issues listed!", "\"", ";", "}" ]
Container for user visible messages.
[ "Container", "for", "user", "visible", "messages", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c42db16b90bbe422ef160329e520929a72f4b9ff
davidpete9/guacamole-client
extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/base/EntityModel.java
[ "Apache-2.0" ]
Java
EntityModel
/** * Base representation of a Guacamole object that can be granted permissions * (an "entity"), such as a user or user group, as represented in the database. * Each entity has three base properties: * * 1. The "entityID", which points to the common entry in the * guacamole_entity table and is common to any type of entity. * * 2. The "objectID", which points to the type-specific entry for the object * in question (ie: an entry in guacamole_user or guacamole_user_group). * * 3. The "identifier", which contains the unique "name" value defined for * the entity within the guacamole_entity table. */
Base representation of a Guacamole object that can be granted permissions (an "entity"), such as a user or user group, as represented in the database. Each entity has three base properties. 1. The "entityID", which points to the common entry in the guacamole_entity table and is common to any type of entity. 2. The "objectID", which points to the type-specific entry for the object in question . 3. The "identifier", which contains the unique "name" value defined for the entity within the guacamole_entity table.
[ "Base", "representation", "of", "a", "Guacamole", "object", "that", "can", "be", "granted", "permissions", "(", "an", "\"", "entity", "\"", ")", "such", "as", "a", "user", "or", "user", "group", "as", "represented", "in", "the", "database", ".", "Each", "entity", "has", "three", "base", "properties", ".", "1", ".", "The", "\"", "entityID", "\"", "which", "points", "to", "the", "common", "entry", "in", "the", "guacamole_entity", "table", "and", "is", "common", "to", "any", "type", "of", "entity", ".", "2", ".", "The", "\"", "objectID", "\"", "which", "points", "to", "the", "type", "-", "specific", "entry", "for", "the", "object", "in", "question", ".", "3", ".", "The", "\"", "identifier", "\"", "which", "contains", "the", "unique", "\"", "name", "\"", "value", "defined", "for", "the", "entity", "within", "the", "guacamole_entity", "table", "." ]
public abstract class EntityModel extends ObjectModel { /** * The ID of the entity entry which corresponds to this object in the * database, if any. Note that this is distinct from the objectID, * inherited from ObjectModel, which is specific to the actual type of * object represented by the entity. */ private Integer entityID; /** * The type of object represented by the entity (user or user group). */ private EntityType type; /** * Creates a new, empty entity. */ public EntityModel() { } /** * Creates a new entity of the given type which is otherwise empty. * * @param type * The type to assign to the new entity. */ public EntityModel(EntityType type) { this.type = type; } /** * Returns the ID of the entity entry which corresponds to this object in * the database, if it exists. Note that this is distinct from the objectID, * inherited from ObjectModel, which is specific to the actual type of * object represented by the entity. * * @return * The ID of this entity in the database, or null if this entity was * not retrieved from the database. */ public Integer getEntityID() { return entityID; } /** * Sets the ID of this entity to the given value. * * @param entityID * The ID to assign to this entity. */ public void setEntityID(Integer entityID) { this.entityID = entityID; } /** * Returns the type of object represented by the entity. Each entity may be * either a user or a user group. * * @return * The type of object represented by the entity. */ public EntityType getEntityType() { return type; } /** * Sets the type of object represented by the entity. Each entity may be * either a user or a user group. * * @param type * The type of object represented by the entity. */ public void setEntityType(EntityType type) { this.type = type; } }
[ "public", "abstract", "class", "EntityModel", "extends", "ObjectModel", "{", "/**\n * The ID of the entity entry which corresponds to this object in the\n * database, if any. Note that this is distinct from the objectID,\n * inherited from ObjectModel, which is specific to the actual type of\n * object represented by the entity.\n */", "private", "Integer", "entityID", ";", "/**\n * The type of object represented by the entity (user or user group).\n */", "private", "EntityType", "type", ";", "/**\n * Creates a new, empty entity.\n */", "public", "EntityModel", "(", ")", "{", "}", "/**\n * Creates a new entity of the given type which is otherwise empty.\n *\n * @param type\n * The type to assign to the new entity.\n */", "public", "EntityModel", "(", "EntityType", "type", ")", "{", "this", ".", "type", "=", "type", ";", "}", "/**\n * Returns the ID of the entity entry which corresponds to this object in\n * the database, if it exists. Note that this is distinct from the objectID,\n * inherited from ObjectModel, which is specific to the actual type of\n * object represented by the entity.\n *\n * @return\n * The ID of this entity in the database, or null if this entity was\n * not retrieved from the database.\n */", "public", "Integer", "getEntityID", "(", ")", "{", "return", "entityID", ";", "}", "/**\n * Sets the ID of this entity to the given value.\n *\n * @param entityID\n * The ID to assign to this entity.\n */", "public", "void", "setEntityID", "(", "Integer", "entityID", ")", "{", "this", ".", "entityID", "=", "entityID", ";", "}", "/**\n * Returns the type of object represented by the entity. Each entity may be\n * either a user or a user group.\n *\n * @return\n * The type of object represented by the entity.\n */", "public", "EntityType", "getEntityType", "(", ")", "{", "return", "type", ";", "}", "/**\n * Sets the type of object represented by the entity. Each entity may be\n * either a user or a user group.\n *\n * @param type\n * The type of object represented by the entity.\n */", "public", "void", "setEntityType", "(", "EntityType", "type", ")", "{", "this", ".", "type", "=", "type", ";", "}", "}" ]
Base representation of a Guacamole object that can be granted permissions (an "entity"), such as a user or user group, as represented in the database.
[ "Base", "representation", "of", "a", "Guacamole", "object", "that", "can", "be", "granted", "permissions", "(", "an", "\"", "entity", "\"", ")", "such", "as", "a", "user", "or", "user", "group", "as", "represented", "in", "the", "database", "." ]
[]
[ { "param": "ObjectModel", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ObjectModel", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c42dbf8f745f5503c910150bd2ed08cafb4e60de
SubDisc/subdisc
src/main/java/nl/liacs/subdisc/Validation.java
[ "Apache-2.0" ]
Java
Validation
/** * Functionality related to the statistical validation of subgroups. */
Functionality related to the statistical validation of subgroups.
[ "Functionality", "related", "to", "the", "statistical", "validation", "of", "subgroups", "." ]
public class Validation { private SearchParameters itsSearchParameters; private TargetConcept itsTargetConcept; private QualityMeasure itsQualityMeasure; private Table itsTable; private BitSet itsSelection; /** * NOTE theQualityMeasure is only used for 'Random Subsets' and * 'Random Descriptions', and then only for the {@link TargetType} * {@link TargetType#SINGLE_NOMINAL} and {@link TargetType#MULTI_LABEL}. * * @param theSearchParameters * @param theTable * @param theQualityMeasure */ public Validation(SearchParameters theSearchParameters, Table theTable, BitSet theSelection, QualityMeasure theQualityMeasure) { itsSearchParameters = theSearchParameters; itsTargetConcept = theSearchParameters.getTargetConcept(); itsTable = theTable; itsSelection = theSelection; itsQualityMeasure = theQualityMeasure; } // FIXME MM - this method should not be separate from the constructor // the data can be changed in between, causing bugs // also, the whole class should consist of just static methods // of split constructor (not all TargetTypes use QualityMeasure) public double[] getQualities(String[] theSetup) { if (!RandomQualitiesWindow.isValidRandomQualitiesSetup(theSetup)) return null; String aMethod = theSetup[0]; int aNrRepetitions = Integer.parseInt(theSetup[1]); if (RandomQualitiesWindow.RANDOM_SUBSETS.equals(aMethod)) return getRandomQualities(true, aNrRepetitions); else if (RandomQualitiesWindow.RANDOM_DESCRIPTIONS.equals(aMethod)) return getRandomQualities(false, aNrRepetitions); else if (RandomQualitiesWindow.SWAP_RANDOMIZATION.equals(aMethod)) return swapRandomization(aNrRepetitions); return null; } // add TargetTypes implemented in getRandomQualitites() to this list public static boolean isValidRandomQualitiesTargetType(TargetType theTargetType) { return theTargetType == TargetType.SINGLE_NOMINAL || theTargetType == TargetType.SINGLE_NUMERIC || theTargetType == TargetType.DOUBLE_REGRESSION || theTargetType == TargetType.DOUBLE_CORRELATION || theTargetType == TargetType.DOUBLE_BINARY || theTargetType == TargetType.MULTI_LABEL || theTargetType == TargetType.LABEL_RANKING; } public double[] getRandomQualities(boolean forSubgroups, int theNrRepetitions) { final int aMinimumCoverage = itsSearchParameters.getMinimumCoverage(); //final Random aRandom = new Random(System.currentTimeMillis()); final Random aRandom = new Random(10); final int aDepth = itsSearchParameters.getSearchDepth(); final TargetType aTargetType = itsTargetConcept.getTargetType(); switch (aTargetType) { case SINGLE_NOMINAL : { return getSingleNominalQualities(forSubgroups, theNrRepetitions, aMinimumCoverage, aRandom, aDepth); } case SINGLE_NUMERIC : { return getSingleNumericQualities(forSubgroups, theNrRepetitions, aMinimumCoverage, aRandom, aDepth); } case SINGLE_ORDINAL: { throw new AssertionError(aTargetType); } case DOUBLE_REGRESSION : { return getDoubleRegressionQualities(forSubgroups, theNrRepetitions, aMinimumCoverage, aRandom, aDepth); } case DOUBLE_CORRELATION : { return getDoubleCorrelationQualities(forSubgroups, theNrRepetitions, aMinimumCoverage, aRandom, aDepth); } case DOUBLE_BINARY : { return getDoubleBinaryQualities(forSubgroups, theNrRepetitions, aMinimumCoverage, aRandom, aDepth); } case MULTI_LABEL : { return getMultiLabelQualities(forSubgroups, theNrRepetitions, aMinimumCoverage, aRandom, aDepth); } case LABEL_RANKING : { return getLabelRankingQualities(forSubgroups, theNrRepetitions, aMinimumCoverage, aRandom, aDepth); } case MULTI_BINARY_CLASSIFICATION : { throw new AssertionError(aTargetType); } default : { throw new AssertionError(aTargetType); } } } // if forSubgroups is true, create Subgroups, else create Conditions // if forSubgroups is true, theDepth is ignored private double[] getSingleNominalQualities(boolean forSubgroups, int theNrRepetitions, int theMinimumCoverage, Random theRandom, int theDepth) { //////////////////////////////////////////////////////////////////////////////// ///// FIXME - WHY IS THIS HERE, itsBinaryTarget IS AVAILABLE ALREADY ///// ///// TECHNICALLY, IT IS ALSO WRONG -> BUG ///// ///// WHEN DATA IS CHANGED AFTER THE ResultWindow IS CREATED, THE ///// ///// THE ORIGINAL Condition MIGHT NOT BE ABLE TO RECREATE THE ///// ///// SAME BitSet AS itsBinaryTarget, BUT THIS IS A WIDER PROBLEM ///// //////////////////////////////////////////////////////////////////////////////// // create a binary target Column aTarget = itsTargetConcept.getPrimaryTarget(); ConditionBase aConditionBase = new ConditionBase(aTarget, Operator.EQUALS); String aValue = itsTargetConcept.getTargetValue(); Condition aCondition; switch (aTarget.getType()) { case NOMINAL : aCondition = new Condition(aConditionBase, aValue); break; case BINARY : if (!AttributeType.isValidBinaryValue(aValue)) throw new IllegalArgumentException(aValue + " is not a valid BINARY value"); aCondition = new Condition(aConditionBase, AttributeType.isValidBinaryTrueValue(aValue)); break; default : throw new AssertionError(aTarget.getType()); } BitSet b = new BitSet(itsTable.getNrRows()); b.set(0, itsTable.getNrRows()); b = aTarget.evaluate(b, aCondition); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// final double[] aQualities = new double[theNrRepetitions]; for (int i = 0; i < theNrRepetitions; ++i) { Subgroup aSubgroup; // essential switch between Subgroups/ Conditions if (forSubgroups) aSubgroup = getValidSubgroup(theMinimumCoverage, theRandom); else aSubgroup = getValidSubgroup(theDepth, theMinimumCoverage, theRandom); BitSet aMembers = aSubgroup.getMembers(); // aMembers is a clone so this is safe aMembers.and(b); int aCountHeadBody = aMembers.cardinality(); aQualities[i] = itsQualityMeasure.calculate(aCountHeadBody, aSubgroup.getCoverage()); } return aQualities; } // if forSubgroups is true, create Subgroups, else create Conditions // if forSubgroups is true, theDepth is ignored private double[] getSingleNumericQualities(boolean forSubgroups, int theNrRepetitions, int theMinimumCoverage, Random theRandom, int theDepth) { final double[] aQualities = new double[theNrRepetitions]; final Column aTarget = itsTargetConcept.getPrimaryTarget(); for (int i = 0; i < theNrRepetitions; ++i) { Subgroup aSubgroup; // essential switch between Subgroups/ Conditions if (forSubgroups) aSubgroup = getValidSubgroup(theMinimumCoverage, theRandom); else aSubgroup = getValidSubgroup(theDepth, theMinimumCoverage, theRandom); BitSet aMembers = aSubgroup.getMembers(); QM aQM = itsSearchParameters.getQualityMeasure(); Statistics aStatistics = aTarget.getStatistics(null, aMembers, aQM == QM.MMAD, QM.requiredStats(aQM).contains(Stat.COMPL)); //TODO check for theSelection ProbabilityDensityFunction aPDF = null; // DEBUG if (!ProbabilityDensityFunction.USE_ProbabilityDensityFunction2) aPDF = new ProbabilityDensityFunction(itsQualityMeasure.getProbabilityDensityFunction(), aMembers); else aPDF = new ProbabilityDensityFunction2(itsQualityMeasure.getProbabilityDensityFunction(), aMembers); aPDF.smooth(); aQualities[i] = itsQualityMeasure.calculate(aStatistics, aPDF); } return aQualities; } // if forSubgroups is true, create Subgroups, else create Conditions // if forSubgroups is true, theDepth is ignored private double[] getDoubleRegressionQualities(boolean forSubgroups, int theNrRepetitions, int theMinimumCoverage, Random theRandom, int theDepth) { final double[] aQualities = new double[theNrRepetitions]; Column aPrimaryColumn = itsTargetConcept.getPrimaryTarget(); Column aSecondaryColumn = itsTargetConcept.getSecondaryTarget(); RegressionMeasure itsBaseRM = new RegressionMeasure(itsSearchParameters.getQualityMeasure(), aPrimaryColumn, aSecondaryColumn); for (int i = 0; i < theNrRepetitions; ++i) { Subgroup aSubgroup; // essential switch between Subgroups/ Conditions if (forSubgroups) aSubgroup = getValidSubgroup(theMinimumCoverage, theRandom); else aSubgroup = getValidSubgroup(theDepth, theMinimumCoverage, theRandom); BitSet aMembers = aSubgroup.getMembers(); RegressionMeasure aRM = new RegressionMeasure(itsBaseRM, aMembers); aQualities[i] = aRM.getEvaluationMeasureValue(); } return aQualities; } // if forSubgroups is true, create Subgroups, else create Conditions // if forSubgroups is true, theDepth is ignored private double[] getDoubleCorrelationQualities(boolean forSubgroups, int theNrRepetitions, int theMinimumCoverage, Random theRandom, int theDepth) { final double[] aQualities = new double[theNrRepetitions]; Column aPrimaryColumn = itsTargetConcept.getPrimaryTarget(); Column aSecondaryColumn = itsTargetConcept.getSecondaryTarget(); CorrelationMeasure itsBaseCM = new CorrelationMeasure(itsSearchParameters.getQualityMeasure(), aPrimaryColumn, aSecondaryColumn); for (int i = 0; i < theNrRepetitions; ++i) { Subgroup aSubgroup; // essential switch between Subgroups/ Conditions if (forSubgroups) aSubgroup = getValidSubgroup(theMinimumCoverage, theRandom); else aSubgroup = getValidSubgroup(theDepth, theMinimumCoverage, theRandom); BitSet aMembers = aSubgroup.getMembers(); CorrelationMeasure aCM = new CorrelationMeasure(itsBaseCM); for (int k = aMembers.nextSetBit(0); k >= 0; k = aMembers.nextSetBit(k)) aCM.addObservation(aPrimaryColumn.getFloat(k), aSecondaryColumn.getFloat(k)); aQualities[i] = aCM.getEvaluationMeasureValue(); } return aQualities; } // if forSubgroups is true, create Subgroups, else create Conditions // if forSubgroups is true, theDepth is ignored private double[] getDoubleBinaryQualities(boolean forSubgroups, int theNrRepetitions, int theMinimumCoverage, Random theRandom, int theDepth) { final double[] aQualities = new double[theNrRepetitions]; Column aPrimaryColumn = itsTargetConcept.getPrimaryTarget(); Column aSecondaryColumn = itsTargetConcept.getSecondaryTarget(); CorrelationMeasure itsBaseCM = new CorrelationMeasure(itsSearchParameters.getQualityMeasure(), aPrimaryColumn, aSecondaryColumn); for (int i = 0; i < theNrRepetitions; ++i) { Subgroup aSubgroup; // essential switch between Subgroups/ Conditions if (forSubgroups) aSubgroup = getValidSubgroup(theMinimumCoverage, theRandom); else aSubgroup = getValidSubgroup(theDepth, theMinimumCoverage, theRandom); BitSet aMembers = aSubgroup.getMembers(); CorrelationMeasure aCM = new CorrelationMeasure(itsBaseCM); for (int k = aMembers.nextSetBit(0); k >= 0; k = aMembers.nextSetBit(k)) aCM.addObservation(aPrimaryColumn.getFloat(k), aSecondaryColumn.getFloat(k)); aQualities[i] = aCM.getEvaluationMeasureValue(); } return aQualities; } // if forSubgroups is true, create Subgroups, else create Conditions // if forSubgroups is true, theDepth is ignored private double[] getMultiLabelQualities(boolean forSubgroups, int theNrRepetitions, int theMinimumCoverage, Random theRandom, int theDepth) { final double[] aQualities = new double[theNrRepetitions]; // base model BinaryTable aBaseTable = new BinaryTable(itsTable, itsTargetConcept.getMultiTargets()); Bayesian aBayesian = new Bayesian(aBaseTable); aBayesian.climb(); for (int i = 0, j = aQualities.length; i < j; ++i) { Subgroup aSubgroup; // essential switch between Subgroups/ Conditions if (forSubgroups) aSubgroup = getValidSubgroup(theMinimumCoverage, theRandom); else aSubgroup = getValidSubgroup(theDepth, theMinimumCoverage, theRandom); // build model BinaryTable aBinaryTable = aBaseTable.selectRows(aSubgroup.getMembers()); aBayesian = new Bayesian(aBinaryTable); aBayesian.climb(); aSubgroup.setDAG(aBayesian.getDAG()); // store DAG with subgroup for later use aQualities[i] = itsQualityMeasure.calculate(aSubgroup); // XXX original code only did this for Condition if (!forSubgroups) Log.logCommandLine((i + 1) + "," + aSubgroup.getCoverage() + "," + aQualities[i]); } return aQualities; } //TODO: fix implementation // if forSubgroups is true, create Subgroups, else create Conditions // if forSubgroups is true, theDepth is ignored private double[] getLabelRankingQualities(boolean forSubgroups, int theNrRepetitions, int theMinimumCoverage, Random theRandom, int theDepth) { final double[] aQualities = new double[theNrRepetitions]; Column aTarget = itsTargetConcept.getPrimaryTarget(); LabelRanking aLR = aTarget.getAverageRanking(null); //average ranking over entire dataset LabelRankingMatrix aLRM = aTarget.getAverageRankingMatrix(null); QualityMeasure aQualityMeasure = new QualityMeasure(itsSearchParameters.getQualityMeasure(), itsTable.getNrRows(), aLR, aLRM); //temp<-- BufferedWriter br = null; try { final File f = new File("output.txt"); br = new BufferedWriter(new FileWriter(f)); //temp--> for (int i = 0; i < theNrRepetitions; ++i) { Subgroup aSubgroup; // essential switch between Subgroups/ Conditions if (forSubgroups) aSubgroup = getValidSubgroup(theMinimumCoverage, theRandom); else aSubgroup = getValidSubgroup(theDepth, theMinimumCoverage, theRandom); LabelRankingMatrix aSubgroupLRM = aTarget.getAverageRankingMatrix(aSubgroup); aQualities[i] = aQualityMeasure.computeLabelRankingDistance(aSubgroup.getCoverage(), aSubgroupLRM); Log.logCommandLine("qual: " + aQualities[i]); //temp<-- br.write(aQualities[i] + "\r"); //temp--> } } //temp<-- catch (IOException e) {} finally { if (br != null) { try { br.close(); } catch (IOException e) {} } } //temp--> return aQualities; } // for RANDOM_SUBSETS/Subgroups, always uses an updated Random value private Subgroup getValidSubgroup(int theMinimumCoverage, Random theRandom) { final int aNrRows = itsTable.getNrRows(); int aSubgroupSize; do aSubgroupSize = (int) (theRandom.nextDouble() * aNrRows); while (aSubgroupSize < theMinimumCoverage || aSubgroupSize == aNrRows); return new Subgroup(itsTable.getRandomBitSet(aSubgroupSize)); } // for RANDOM_DESCRIPTIONS/Conditions, always uses the same Random value private Subgroup getValidSubgroup(int theDepth, int theMinimumCoverage, Random theRandom) { final int aNrRows = itsTable.getNrRows(); int aSubgroupSize; //ConditionList aCL; ConditionListA aCL; BitSet aMembers; do { aCL = getRandomConditionList(theDepth, theRandom); aMembers = itsTable.evaluate(aCL); aSubgroupSize = aMembers.cardinality(); } while (aSubgroupSize < theMinimumCoverage || aSubgroupSize == aNrRows); Log.logCommandLine(aCL.toString()); return new Subgroup(aMembers); } /** * Swap randomizes the original {@link Table} and restores it to the * original state afterwards. * * @param theNrRepetitions the number of times to perform a permutation * of the {@link TargetConcept}. * * @return an array holding the qualities of the best scoring * {@link Subgroup} of each permutation. */ private double[] swapRandomization(int theNrRepetitions) { // Memorize COMMANDLINELOG setting boolean aCOMMANDLINELOGmem = Log.COMMANDLINELOG; double[] aQualities = new double[theNrRepetitions]; // Always back up and restore columns that will be swap randomized. final TargetType aTargetType = itsTargetConcept.getTargetType(); switch (aTargetType) { case SINGLE_NOMINAL : { // back up column that will be swap randomized Column aPrimaryCopy = itsTargetConcept.getPrimaryTarget().copy(); int aPositiveCount = itsTargetConcept.getPrimaryTarget().countValues(itsTargetConcept.getTargetValue(), itsSelection); // generate swap randomized random results for (int i = 0, j = theNrRepetitions; i < j; ++i) { itsTable.swapRandomizeTarget(itsTargetConcept); i = runSRSD(new SubgroupDiscovery(itsSearchParameters, itsTable, itsSelection, aPositiveCount, null), aQualities, i); } // restore column that was swap randomized itsTargetConcept.setPrimaryTarget(aPrimaryCopy); itsTable.getColumns().set(aPrimaryCopy.getIndex(), aPrimaryCopy); break; } case SINGLE_NUMERIC : { // back up column that will be swap randomized Column aPrimaryCopy = itsTargetConcept.getPrimaryTarget().copy(); float aTargetAverage = itsTargetConcept.getPrimaryTarget().getAverage(itsSelection); // generate swap randomized random results for (int i = 0, j = theNrRepetitions; i < j; ++i) { itsTable.swapRandomizeTarget(itsTargetConcept); SubgroupDiscovery anSD = new SubgroupDiscovery(itsSearchParameters, itsTable, itsSelection, aTargetAverage, null); i = runSRSD(anSD, aQualities, i); } // restore column that was swap randomized itsTargetConcept.setPrimaryTarget(aPrimaryCopy); itsTable.getColumns().set(aPrimaryCopy.getIndex(), aPrimaryCopy); break; } case DOUBLE_REGRESSION : { // back up columns that will be swap randomized Column aPrimaryCopy = itsTargetConcept.getPrimaryTarget().copy(); Column aSecondaryCopy = itsTargetConcept.getSecondaryTarget().copy(); // generate swap randomized random results for (int i = 0, j = theNrRepetitions; i < j; ++i) { itsTable.swapRandomizeTarget(itsTargetConcept); i = runSRSD(new SubgroupDiscovery(itsSearchParameters, itsTable, itsSelection, true, null), aQualities, i); } // restore columns that were swap randomized itsTargetConcept.setPrimaryTarget(aPrimaryCopy); itsTable.getColumns().set(aPrimaryCopy.getIndex(), aPrimaryCopy); itsTargetConcept.setSecondaryTarget(aSecondaryCopy); itsTable.getColumns().set(aSecondaryCopy.getIndex(), aSecondaryCopy); break; } case DOUBLE_CORRELATION : { // back up columns that will be swap randomized Column aPrimaryCopy = itsTargetConcept.getPrimaryTarget().copy(); Column aSecondaryCopy = itsTargetConcept.getSecondaryTarget().copy(); // generate swap randomized random results for (int i = 0, j = theNrRepetitions; i < j; ++i) { itsTable.swapRandomizeTarget(itsTargetConcept); i = runSRSD(new SubgroupDiscovery(itsSearchParameters, itsTable, itsSelection, false, null), aQualities, i); } // restore columns that were swap randomized itsTargetConcept.setPrimaryTarget(aPrimaryCopy); itsTable.getColumns().set(aPrimaryCopy.getIndex(), aPrimaryCopy); itsTargetConcept.setSecondaryTarget(aSecondaryCopy); itsTable.getColumns().set(aSecondaryCopy.getIndex(), aSecondaryCopy); break; } case DOUBLE_BINARY : { // back up columns that will be swap randomized Column aPrimaryCopy = itsTargetConcept.getPrimaryTarget().copy(); Column aSecondaryCopy = itsTargetConcept.getSecondaryTarget().copy(); // generate swap randomized random results for (int i = 0, j = theNrRepetitions; i < j; ++i) { itsTable.swapRandomizeTarget(itsTargetConcept); i = runSRSD(new SubgroupDiscovery(itsSearchParameters, itsTable, itsSelection, false, null), aQualities, i); } // restore columns that were swap randomized itsTargetConcept.setPrimaryTarget(aPrimaryCopy); itsTable.getColumns().set(aPrimaryCopy.getIndex(), aPrimaryCopy); itsTargetConcept.setSecondaryTarget(aSecondaryCopy); itsTable.getColumns().set(aSecondaryCopy.getIndex(), aSecondaryCopy); break; } case MULTI_LABEL : { // back up columns that will be swap randomized List<Column> aMultiCopy = new ArrayList<Column>(itsTargetConcept.getMultiTargets().size()); for (Column c : itsTargetConcept.getMultiTargets()) aMultiCopy.add(c.copy()); // generate swap randomized random results for (int i = 0, j = theNrRepetitions; i < j; ++i) { // swapRandomization should be performed before creating new SubgroupDiscovery itsTable.swapRandomizeTarget(itsTargetConcept); i = runSRSD(new SubgroupDiscovery(itsSearchParameters, itsTable, itsSelection, null), aQualities, i); } // restore columns that were swap randomized itsTargetConcept.setMultiTargets(aMultiCopy); for (Column c : aMultiCopy) itsTable.getColumns().set(c.getIndex(), c); break; } case MULTI_BINARY_CLASSIFICATION : { throw new AssertionError(aTargetType); } case LABEL_RANKING: { // back up column that will be swap randomized Column aPrimaryCopy = itsTargetConcept.getPrimaryTarget().copy(); // generate swap randomized random results for (int i = 0, j = theNrRepetitions; i < j; ++i) { itsTable.swapRandomizeTarget(itsTargetConcept); i = runSRSD(new SubgroupDiscovery(itsSearchParameters, null, itsTable, itsSelection), aQualities, i); } // restore column that was swap randomized itsTargetConcept.setPrimaryTarget(aPrimaryCopy); itsTable.getColumns().set(aPrimaryCopy.getIndex(), aPrimaryCopy); break; } default : { throw new AssertionError(aTargetType); } } Log.COMMANDLINELOG = aCOMMANDLINELOGmem; return aQualities; } //returns the 5% significance of swap randomisation. public float getSignWithSwapRand(int theNrRepetitions) { double[] aQualities = swapRandomization(theNrRepetitions); NormalDistribution aDistro = new NormalDistribution(aQualities); return aDistro.getFivePercentSignificance(); } /* * NOTE for the first result (i = 0) to be not equal to the original * mining result the calling function should run: * itsTable.swapRandomizeTarget(itsTargetConcept); * before creating the new theSubgroupDiscovery, and calling this * method. */ private int runSRSD(SubgroupDiscovery theSubgroupDiscovery, double[] theQualities, int theRepetition) { //quality minimum should not be taken into account when computing distribution of random qualities theSubgroupDiscovery.ignoreQualityMinimum(); Log.COMMANDLINELOG = false; theSubgroupDiscovery.mine(System.currentTimeMillis(), itsSearchParameters.getNrThreads()); Log.COMMANDLINELOG = true; SubgroupSet aSubgroupSet = theSubgroupDiscovery.getResult(); if (aSubgroupSet.size() == 0) --theRepetition; // if no subgroups are found, try again else { theQualities[theRepetition] = aSubgroupSet.getBestScore(); Log.logCommandLine((theRepetition + 1) + ", " + theQualities[theRepetition]); } return theRepetition; } //private ConditionList getRandomConditionList(int theDepth, Random theRandom) private ConditionListA getRandomConditionList(int theDepth, Random theRandom) { int aDepth = 1+theRandom.nextInt(theDepth); //random nr between 1 and theDepth (incl) //ConditionList aCL = new ConditionList(aDepth); ConditionListA aCL = ConditionListBuilder.emptyList(); int aNrColumns = itsTable.getNrColumns(); for (int j = 0; j < aDepth; j++) // j conditions { Column aColumn; do aColumn = itsTable.getColumn(theRandom.nextInt(aNrColumns)); while (itsTargetConcept.isTargetAttribute(aColumn) || !aColumn.getIsEnabled()); ConditionBase aConditionBase; Condition aCondition; switch (aColumn.getType()) { case NOMINAL : { // select a random value from the domain TreeSet<String> aDomain = aColumn.getDomain(); int aNrDistinct = aDomain.size(); int aRandomIndex = (int) (theRandom.nextDouble() * aNrDistinct); Iterator<String> anIterator = aDomain.iterator(); String aValue = anIterator.next(); for (int i=0; i<aRandomIndex; i++) aValue = anIterator.next(); aConditionBase = new ConditionBase(aColumn, Operator.EQUALS); aCondition = new Condition(aConditionBase, aValue); break; } case NUMERIC : { Operator anOperator = theRandom.nextBoolean() ? Operator.LESS_THAN_OR_EQUAL : Operator.GREATER_THAN_OR_EQUAL; float aMin = aColumn.getMin(); float aMax = aColumn.getMax(); float aRange = aMax - aMin; // fairly crude way of producing random thresholds, but will do for now float aValue = (aMin + 0.1f*aRange + 0.8f*aRange*theRandom.nextFloat()); aConditionBase = new ConditionBase(aColumn, anOperator); // value may not occur in Column, so can not set sort index aCondition = new Condition(aConditionBase, aValue, Condition.UNINITIALISED_SORT_INDEX); break; } case BINARY : { aConditionBase = new ConditionBase(aColumn, Operator.EQUALS); aCondition = new Condition(aConditionBase, theRandom.nextBoolean()); break; } default : throw new AssertionError(aColumn.getType()); } //aCL.addCondition(aCondition); aCL = ConditionListBuilder.createList(aCL, aCondition); } return aCL; } public static final double[] performRegressionTest(double[] theQualities, SubgroupSet theSubgroupSet) { double aOne = performRegressionTest(theQualities, 1, theSubgroupSet); double aTen = Math.PI; if (theSubgroupSet.size()>=10) aTen = performRegressionTest(theQualities, 10, theSubgroupSet); double[] aResult = {aOne, aTen}; return aResult; } private static final double performRegressionTest(double[] theQualities, int theK, SubgroupSet theSubgroupSet) { //extract average quality double aTopKQuality = 0.0; for (Subgroup aSubgroup : theSubgroupSet) aTopKQuality += aSubgroup.getMeasureValue(); aTopKQuality /= theK; // make deep copy of double array //public static double[] copyOf(double[] original, int newLength) int theNrRandomSubgroups = theQualities.length; double[] aCopy = Arrays.copyOf(theQualities, theQualities.length); // rescale all qualities between 0 and 1 // also compute some necessary statistics Arrays.sort(aCopy); double aMin = Math.min(aCopy[0], aTopKQuality); double aMax = Math.max(aCopy[theNrRandomSubgroups-1], aTopKQuality); double xBar = 0.5; // given our scaling this always holds double yBar = 0.0; // initial value for (int i=0; i<theNrRandomSubgroups; i++) { aCopy[i] = (aCopy[i]-aMin)/(aMax-aMin); yBar += aCopy[i]; } aTopKQuality = (aTopKQuality-aMin)/(aMax-aMin); yBar = (yBar+aTopKQuality)/((double) theNrRandomSubgroups + 1); // perform least squares linear regression on equidistant x-values and computed y-values double xxBar = 0.25; // initial value: this equals the square of (the x-value of our subgroup minus xbar) double xyBar = 0.5 * (aTopKQuality - yBar); double[] anXs = new double[theNrRandomSubgroups]; for (int i=0; i<theNrRandomSubgroups; i++) { anXs[i] = ((double)i) / ((double)theNrRandomSubgroups); Log.logCommandLine("" + anXs[i] + "\t" + aCopy[i]); } for (int i=0; i<theNrRandomSubgroups; i++) { xxBar += (anXs[i] - xBar) * (anXs[i] - xBar); xyBar += (anXs[i] - xBar) * (aCopy[i] - yBar); } double beta1 = xyBar / xxBar; double beta0 = yBar - beta1 * xBar; // this gives us the regression line y = beta1 * x + beta0 Log.logCommandLine("Fitted regression line: y = " + beta1 + " * x + " + beta0); double aScore = aTopKQuality - beta1 - beta0; // the regression test score now equals the average quality of the top-k subgroups, minus the regression value at x=1. Log.logCommandLine("Regression test score: " + aScore); return aScore; } public static final double computeEmpiricalPValue(double[] theQualities, SubgroupSet theSubgroupSet) { //hardcoded int aK = 1; // extract average quality of top-k subgroups Iterator<Subgroup> anIterator = theSubgroupSet.iterator(); double aTopKQuality = 0.0; for (int i=0; i<aK; i++) { Subgroup aSubgroup = anIterator.next(); aTopKQuality += aSubgroup.getMeasureValue(); } aTopKQuality /= aK; int aCount = 0; for (double aQuality : theQualities) if (aQuality > aTopKQuality) aCount++; Arrays.sort(theQualities); Log.logCommandLine("Empirical p-value: " + aCount/(double)theQualities.length); // Log.logCommandLine("score at alpha = 1%: " + theQualities[theQualities.length-theQualities.length/100]); // Log.logCommandLine("score at alpha = 5%: " + theQualities[theQualities.length-theQualities.length/20]); // Log.logCommandLine("score at alpha = 10%: " + theQualities[theQualities.length-theQualities.length/10]); return aCount / ((double) theQualities.length); } }
[ "public", "class", "Validation", "{", "private", "SearchParameters", "itsSearchParameters", ";", "private", "TargetConcept", "itsTargetConcept", ";", "private", "QualityMeasure", "itsQualityMeasure", ";", "private", "Table", "itsTable", ";", "private", "BitSet", "itsSelection", ";", "/**\n\t * NOTE theQualityMeasure is only used for 'Random Subsets' and\n\t * 'Random Descriptions', and then only for the {@link TargetType}\n\t * {@link TargetType#SINGLE_NOMINAL} and {@link TargetType#MULTI_LABEL}.\n\t *\n\t * @param theSearchParameters\n\t * @param theTable\n\t * @param theQualityMeasure\n\t */", "public", "Validation", "(", "SearchParameters", "theSearchParameters", ",", "Table", "theTable", ",", "BitSet", "theSelection", ",", "QualityMeasure", "theQualityMeasure", ")", "{", "itsSearchParameters", "=", "theSearchParameters", ";", "itsTargetConcept", "=", "theSearchParameters", ".", "getTargetConcept", "(", ")", ";", "itsTable", "=", "theTable", ";", "itsSelection", "=", "theSelection", ";", "itsQualityMeasure", "=", "theQualityMeasure", ";", "}", "public", "double", "[", "]", "getQualities", "(", "String", "[", "]", "theSetup", ")", "{", "if", "(", "!", "RandomQualitiesWindow", ".", "isValidRandomQualitiesSetup", "(", "theSetup", ")", ")", "return", "null", ";", "String", "aMethod", "=", "theSetup", "[", "0", "]", ";", "int", "aNrRepetitions", "=", "Integer", ".", "parseInt", "(", "theSetup", "[", "1", "]", ")", ";", "if", "(", "RandomQualitiesWindow", ".", "RANDOM_SUBSETS", ".", "equals", "(", "aMethod", ")", ")", "return", "getRandomQualities", "(", "true", ",", "aNrRepetitions", ")", ";", "else", "if", "(", "RandomQualitiesWindow", ".", "RANDOM_DESCRIPTIONS", ".", "equals", "(", "aMethod", ")", ")", "return", "getRandomQualities", "(", "false", ",", "aNrRepetitions", ")", ";", "else", "if", "(", "RandomQualitiesWindow", ".", "SWAP_RANDOMIZATION", ".", "equals", "(", "aMethod", ")", ")", "return", "swapRandomization", "(", "aNrRepetitions", ")", ";", "return", "null", ";", "}", "public", "static", "boolean", "isValidRandomQualitiesTargetType", "(", "TargetType", "theTargetType", ")", "{", "return", "theTargetType", "==", "TargetType", ".", "SINGLE_NOMINAL", "||", "theTargetType", "==", "TargetType", ".", "SINGLE_NUMERIC", "||", "theTargetType", "==", "TargetType", ".", "DOUBLE_REGRESSION", "||", "theTargetType", "==", "TargetType", ".", "DOUBLE_CORRELATION", "||", "theTargetType", "==", "TargetType", ".", "DOUBLE_BINARY", "||", "theTargetType", "==", "TargetType", ".", "MULTI_LABEL", "||", "theTargetType", "==", "TargetType", ".", "LABEL_RANKING", ";", "}", "public", "double", "[", "]", "getRandomQualities", "(", "boolean", "forSubgroups", ",", "int", "theNrRepetitions", ")", "{", "final", "int", "aMinimumCoverage", "=", "itsSearchParameters", ".", "getMinimumCoverage", "(", ")", ";", "final", "Random", "aRandom", "=", "new", "Random", "(", "10", ")", ";", "final", "int", "aDepth", "=", "itsSearchParameters", ".", "getSearchDepth", "(", ")", ";", "final", "TargetType", "aTargetType", "=", "itsTargetConcept", ".", "getTargetType", "(", ")", ";", "switch", "(", "aTargetType", ")", "{", "case", "SINGLE_NOMINAL", ":", "{", "return", "getSingleNominalQualities", "(", "forSubgroups", ",", "theNrRepetitions", ",", "aMinimumCoverage", ",", "aRandom", ",", "aDepth", ")", ";", "}", "case", "SINGLE_NUMERIC", ":", "{", "return", "getSingleNumericQualities", "(", "forSubgroups", ",", "theNrRepetitions", ",", "aMinimumCoverage", ",", "aRandom", ",", "aDepth", ")", ";", "}", "case", "SINGLE_ORDINAL", ":", "{", "throw", "new", "AssertionError", "(", "aTargetType", ")", ";", "}", "case", "DOUBLE_REGRESSION", ":", "{", "return", "getDoubleRegressionQualities", "(", "forSubgroups", ",", "theNrRepetitions", ",", "aMinimumCoverage", ",", "aRandom", ",", "aDepth", ")", ";", "}", "case", "DOUBLE_CORRELATION", ":", "{", "return", "getDoubleCorrelationQualities", "(", "forSubgroups", ",", "theNrRepetitions", ",", "aMinimumCoverage", ",", "aRandom", ",", "aDepth", ")", ";", "}", "case", "DOUBLE_BINARY", ":", "{", "return", "getDoubleBinaryQualities", "(", "forSubgroups", ",", "theNrRepetitions", ",", "aMinimumCoverage", ",", "aRandom", ",", "aDepth", ")", ";", "}", "case", "MULTI_LABEL", ":", "{", "return", "getMultiLabelQualities", "(", "forSubgroups", ",", "theNrRepetitions", ",", "aMinimumCoverage", ",", "aRandom", ",", "aDepth", ")", ";", "}", "case", "LABEL_RANKING", ":", "{", "return", "getLabelRankingQualities", "(", "forSubgroups", ",", "theNrRepetitions", ",", "aMinimumCoverage", ",", "aRandom", ",", "aDepth", ")", ";", "}", "case", "MULTI_BINARY_CLASSIFICATION", ":", "{", "throw", "new", "AssertionError", "(", "aTargetType", ")", ";", "}", "default", ":", "{", "throw", "new", "AssertionError", "(", "aTargetType", ")", ";", "}", "}", "}", "private", "double", "[", "]", "getSingleNominalQualities", "(", "boolean", "forSubgroups", ",", "int", "theNrRepetitions", ",", "int", "theMinimumCoverage", ",", "Random", "theRandom", ",", "int", "theDepth", ")", "{", "Column", "aTarget", "=", "itsTargetConcept", ".", "getPrimaryTarget", "(", ")", ";", "ConditionBase", "aConditionBase", "=", "new", "ConditionBase", "(", "aTarget", ",", "Operator", ".", "EQUALS", ")", ";", "String", "aValue", "=", "itsTargetConcept", ".", "getTargetValue", "(", ")", ";", "Condition", "aCondition", ";", "switch", "(", "aTarget", ".", "getType", "(", ")", ")", "{", "case", "NOMINAL", ":", "aCondition", "=", "new", "Condition", "(", "aConditionBase", ",", "aValue", ")", ";", "break", ";", "case", "BINARY", ":", "if", "(", "!", "AttributeType", ".", "isValidBinaryValue", "(", "aValue", ")", ")", "throw", "new", "IllegalArgumentException", "(", "aValue", "+", "\"", " is not a valid BINARY value", "\"", ")", ";", "aCondition", "=", "new", "Condition", "(", "aConditionBase", ",", "AttributeType", ".", "isValidBinaryTrueValue", "(", "aValue", ")", ")", ";", "break", ";", "default", ":", "throw", "new", "AssertionError", "(", "aTarget", ".", "getType", "(", ")", ")", ";", "}", "BitSet", "b", "=", "new", "BitSet", "(", "itsTable", ".", "getNrRows", "(", ")", ")", ";", "b", ".", "set", "(", "0", ",", "itsTable", ".", "getNrRows", "(", ")", ")", ";", "b", "=", "aTarget", ".", "evaluate", "(", "b", ",", "aCondition", ")", ";", "final", "double", "[", "]", "aQualities", "=", "new", "double", "[", "theNrRepetitions", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "theNrRepetitions", ";", "++", "i", ")", "{", "Subgroup", "aSubgroup", ";", "if", "(", "forSubgroups", ")", "aSubgroup", "=", "getValidSubgroup", "(", "theMinimumCoverage", ",", "theRandom", ")", ";", "else", "aSubgroup", "=", "getValidSubgroup", "(", "theDepth", ",", "theMinimumCoverage", ",", "theRandom", ")", ";", "BitSet", "aMembers", "=", "aSubgroup", ".", "getMembers", "(", ")", ";", "aMembers", ".", "and", "(", "b", ")", ";", "int", "aCountHeadBody", "=", "aMembers", ".", "cardinality", "(", ")", ";", "aQualities", "[", "i", "]", "=", "itsQualityMeasure", ".", "calculate", "(", "aCountHeadBody", ",", "aSubgroup", ".", "getCoverage", "(", ")", ")", ";", "}", "return", "aQualities", ";", "}", "private", "double", "[", "]", "getSingleNumericQualities", "(", "boolean", "forSubgroups", ",", "int", "theNrRepetitions", ",", "int", "theMinimumCoverage", ",", "Random", "theRandom", ",", "int", "theDepth", ")", "{", "final", "double", "[", "]", "aQualities", "=", "new", "double", "[", "theNrRepetitions", "]", ";", "final", "Column", "aTarget", "=", "itsTargetConcept", ".", "getPrimaryTarget", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "theNrRepetitions", ";", "++", "i", ")", "{", "Subgroup", "aSubgroup", ";", "if", "(", "forSubgroups", ")", "aSubgroup", "=", "getValidSubgroup", "(", "theMinimumCoverage", ",", "theRandom", ")", ";", "else", "aSubgroup", "=", "getValidSubgroup", "(", "theDepth", ",", "theMinimumCoverage", ",", "theRandom", ")", ";", "BitSet", "aMembers", "=", "aSubgroup", ".", "getMembers", "(", ")", ";", "QM", "aQM", "=", "itsSearchParameters", ".", "getQualityMeasure", "(", ")", ";", "Statistics", "aStatistics", "=", "aTarget", ".", "getStatistics", "(", "null", ",", "aMembers", ",", "aQM", "==", "QM", ".", "MMAD", ",", "QM", ".", "requiredStats", "(", "aQM", ")", ".", "contains", "(", "Stat", ".", "COMPL", ")", ")", ";", "ProbabilityDensityFunction", "aPDF", "=", "null", ";", "if", "(", "!", "ProbabilityDensityFunction", ".", "USE_ProbabilityDensityFunction2", ")", "aPDF", "=", "new", "ProbabilityDensityFunction", "(", "itsQualityMeasure", ".", "getProbabilityDensityFunction", "(", ")", ",", "aMembers", ")", ";", "else", "aPDF", "=", "new", "ProbabilityDensityFunction2", "(", "itsQualityMeasure", ".", "getProbabilityDensityFunction", "(", ")", ",", "aMembers", ")", ";", "aPDF", ".", "smooth", "(", ")", ";", "aQualities", "[", "i", "]", "=", "itsQualityMeasure", ".", "calculate", "(", "aStatistics", ",", "aPDF", ")", ";", "}", "return", "aQualities", ";", "}", "private", "double", "[", "]", "getDoubleRegressionQualities", "(", "boolean", "forSubgroups", ",", "int", "theNrRepetitions", ",", "int", "theMinimumCoverage", ",", "Random", "theRandom", ",", "int", "theDepth", ")", "{", "final", "double", "[", "]", "aQualities", "=", "new", "double", "[", "theNrRepetitions", "]", ";", "Column", "aPrimaryColumn", "=", "itsTargetConcept", ".", "getPrimaryTarget", "(", ")", ";", "Column", "aSecondaryColumn", "=", "itsTargetConcept", ".", "getSecondaryTarget", "(", ")", ";", "RegressionMeasure", "itsBaseRM", "=", "new", "RegressionMeasure", "(", "itsSearchParameters", ".", "getQualityMeasure", "(", ")", ",", "aPrimaryColumn", ",", "aSecondaryColumn", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "theNrRepetitions", ";", "++", "i", ")", "{", "Subgroup", "aSubgroup", ";", "if", "(", "forSubgroups", ")", "aSubgroup", "=", "getValidSubgroup", "(", "theMinimumCoverage", ",", "theRandom", ")", ";", "else", "aSubgroup", "=", "getValidSubgroup", "(", "theDepth", ",", "theMinimumCoverage", ",", "theRandom", ")", ";", "BitSet", "aMembers", "=", "aSubgroup", ".", "getMembers", "(", ")", ";", "RegressionMeasure", "aRM", "=", "new", "RegressionMeasure", "(", "itsBaseRM", ",", "aMembers", ")", ";", "aQualities", "[", "i", "]", "=", "aRM", ".", "getEvaluationMeasureValue", "(", ")", ";", "}", "return", "aQualities", ";", "}", "private", "double", "[", "]", "getDoubleCorrelationQualities", "(", "boolean", "forSubgroups", ",", "int", "theNrRepetitions", ",", "int", "theMinimumCoverage", ",", "Random", "theRandom", ",", "int", "theDepth", ")", "{", "final", "double", "[", "]", "aQualities", "=", "new", "double", "[", "theNrRepetitions", "]", ";", "Column", "aPrimaryColumn", "=", "itsTargetConcept", ".", "getPrimaryTarget", "(", ")", ";", "Column", "aSecondaryColumn", "=", "itsTargetConcept", ".", "getSecondaryTarget", "(", ")", ";", "CorrelationMeasure", "itsBaseCM", "=", "new", "CorrelationMeasure", "(", "itsSearchParameters", ".", "getQualityMeasure", "(", ")", ",", "aPrimaryColumn", ",", "aSecondaryColumn", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "theNrRepetitions", ";", "++", "i", ")", "{", "Subgroup", "aSubgroup", ";", "if", "(", "forSubgroups", ")", "aSubgroup", "=", "getValidSubgroup", "(", "theMinimumCoverage", ",", "theRandom", ")", ";", "else", "aSubgroup", "=", "getValidSubgroup", "(", "theDepth", ",", "theMinimumCoverage", ",", "theRandom", ")", ";", "BitSet", "aMembers", "=", "aSubgroup", ".", "getMembers", "(", ")", ";", "CorrelationMeasure", "aCM", "=", "new", "CorrelationMeasure", "(", "itsBaseCM", ")", ";", "for", "(", "int", "k", "=", "aMembers", ".", "nextSetBit", "(", "0", ")", ";", "k", ">=", "0", ";", "k", "=", "aMembers", ".", "nextSetBit", "(", "k", ")", ")", "aCM", ".", "addObservation", "(", "aPrimaryColumn", ".", "getFloat", "(", "k", ")", ",", "aSecondaryColumn", ".", "getFloat", "(", "k", ")", ")", ";", "aQualities", "[", "i", "]", "=", "aCM", ".", "getEvaluationMeasureValue", "(", ")", ";", "}", "return", "aQualities", ";", "}", "private", "double", "[", "]", "getDoubleBinaryQualities", "(", "boolean", "forSubgroups", ",", "int", "theNrRepetitions", ",", "int", "theMinimumCoverage", ",", "Random", "theRandom", ",", "int", "theDepth", ")", "{", "final", "double", "[", "]", "aQualities", "=", "new", "double", "[", "theNrRepetitions", "]", ";", "Column", "aPrimaryColumn", "=", "itsTargetConcept", ".", "getPrimaryTarget", "(", ")", ";", "Column", "aSecondaryColumn", "=", "itsTargetConcept", ".", "getSecondaryTarget", "(", ")", ";", "CorrelationMeasure", "itsBaseCM", "=", "new", "CorrelationMeasure", "(", "itsSearchParameters", ".", "getQualityMeasure", "(", ")", ",", "aPrimaryColumn", ",", "aSecondaryColumn", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "theNrRepetitions", ";", "++", "i", ")", "{", "Subgroup", "aSubgroup", ";", "if", "(", "forSubgroups", ")", "aSubgroup", "=", "getValidSubgroup", "(", "theMinimumCoverage", ",", "theRandom", ")", ";", "else", "aSubgroup", "=", "getValidSubgroup", "(", "theDepth", ",", "theMinimumCoverage", ",", "theRandom", ")", ";", "BitSet", "aMembers", "=", "aSubgroup", ".", "getMembers", "(", ")", ";", "CorrelationMeasure", "aCM", "=", "new", "CorrelationMeasure", "(", "itsBaseCM", ")", ";", "for", "(", "int", "k", "=", "aMembers", ".", "nextSetBit", "(", "0", ")", ";", "k", ">=", "0", ";", "k", "=", "aMembers", ".", "nextSetBit", "(", "k", ")", ")", "aCM", ".", "addObservation", "(", "aPrimaryColumn", ".", "getFloat", "(", "k", ")", ",", "aSecondaryColumn", ".", "getFloat", "(", "k", ")", ")", ";", "aQualities", "[", "i", "]", "=", "aCM", ".", "getEvaluationMeasureValue", "(", ")", ";", "}", "return", "aQualities", ";", "}", "private", "double", "[", "]", "getMultiLabelQualities", "(", "boolean", "forSubgroups", ",", "int", "theNrRepetitions", ",", "int", "theMinimumCoverage", ",", "Random", "theRandom", ",", "int", "theDepth", ")", "{", "final", "double", "[", "]", "aQualities", "=", "new", "double", "[", "theNrRepetitions", "]", ";", "BinaryTable", "aBaseTable", "=", "new", "BinaryTable", "(", "itsTable", ",", "itsTargetConcept", ".", "getMultiTargets", "(", ")", ")", ";", "Bayesian", "aBayesian", "=", "new", "Bayesian", "(", "aBaseTable", ")", ";", "aBayesian", ".", "climb", "(", ")", ";", "for", "(", "int", "i", "=", "0", ",", "j", "=", "aQualities", ".", "length", ";", "i", "<", "j", ";", "++", "i", ")", "{", "Subgroup", "aSubgroup", ";", "if", "(", "forSubgroups", ")", "aSubgroup", "=", "getValidSubgroup", "(", "theMinimumCoverage", ",", "theRandom", ")", ";", "else", "aSubgroup", "=", "getValidSubgroup", "(", "theDepth", ",", "theMinimumCoverage", ",", "theRandom", ")", ";", "BinaryTable", "aBinaryTable", "=", "aBaseTable", ".", "selectRows", "(", "aSubgroup", ".", "getMembers", "(", ")", ")", ";", "aBayesian", "=", "new", "Bayesian", "(", "aBinaryTable", ")", ";", "aBayesian", ".", "climb", "(", ")", ";", "aSubgroup", ".", "setDAG", "(", "aBayesian", ".", "getDAG", "(", ")", ")", ";", "aQualities", "[", "i", "]", "=", "itsQualityMeasure", ".", "calculate", "(", "aSubgroup", ")", ";", "if", "(", "!", "forSubgroups", ")", "Log", ".", "logCommandLine", "(", "(", "i", "+", "1", ")", "+", "\"", ",", "\"", "+", "aSubgroup", ".", "getCoverage", "(", ")", "+", "\"", ",", "\"", "+", "aQualities", "[", "i", "]", ")", ";", "}", "return", "aQualities", ";", "}", "private", "double", "[", "]", "getLabelRankingQualities", "(", "boolean", "forSubgroups", ",", "int", "theNrRepetitions", ",", "int", "theMinimumCoverage", ",", "Random", "theRandom", ",", "int", "theDepth", ")", "{", "final", "double", "[", "]", "aQualities", "=", "new", "double", "[", "theNrRepetitions", "]", ";", "Column", "aTarget", "=", "itsTargetConcept", ".", "getPrimaryTarget", "(", ")", ";", "LabelRanking", "aLR", "=", "aTarget", ".", "getAverageRanking", "(", "null", ")", ";", "LabelRankingMatrix", "aLRM", "=", "aTarget", ".", "getAverageRankingMatrix", "(", "null", ")", ";", "QualityMeasure", "aQualityMeasure", "=", "new", "QualityMeasure", "(", "itsSearchParameters", ".", "getQualityMeasure", "(", ")", ",", "itsTable", ".", "getNrRows", "(", ")", ",", "aLR", ",", "aLRM", ")", ";", "BufferedWriter", "br", "=", "null", ";", "try", "{", "final", "File", "f", "=", "new", "File", "(", "\"", "output.txt", "\"", ")", ";", "br", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "f", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "theNrRepetitions", ";", "++", "i", ")", "{", "Subgroup", "aSubgroup", ";", "if", "(", "forSubgroups", ")", "aSubgroup", "=", "getValidSubgroup", "(", "theMinimumCoverage", ",", "theRandom", ")", ";", "else", "aSubgroup", "=", "getValidSubgroup", "(", "theDepth", ",", "theMinimumCoverage", ",", "theRandom", ")", ";", "LabelRankingMatrix", "aSubgroupLRM", "=", "aTarget", ".", "getAverageRankingMatrix", "(", "aSubgroup", ")", ";", "aQualities", "[", "i", "]", "=", "aQualityMeasure", ".", "computeLabelRankingDistance", "(", "aSubgroup", ".", "getCoverage", "(", ")", ",", "aSubgroupLRM", ")", ";", "Log", ".", "logCommandLine", "(", "\"", "qual: ", "\"", "+", "aQualities", "[", "i", "]", ")", ";", "br", ".", "write", "(", "aQualities", "[", "i", "]", "+", "\"", "\\r", "\"", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "}", "finally", "{", "if", "(", "br", "!=", "null", ")", "{", "try", "{", "br", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "}", "}", "}", "return", "aQualities", ";", "}", "private", "Subgroup", "getValidSubgroup", "(", "int", "theMinimumCoverage", ",", "Random", "theRandom", ")", "{", "final", "int", "aNrRows", "=", "itsTable", ".", "getNrRows", "(", ")", ";", "int", "aSubgroupSize", ";", "do", "aSubgroupSize", "=", "(", "int", ")", "(", "theRandom", ".", "nextDouble", "(", ")", "*", "aNrRows", ")", ";", "while", "(", "aSubgroupSize", "<", "theMinimumCoverage", "||", "aSubgroupSize", "==", "aNrRows", ")", ";", "return", "new", "Subgroup", "(", "itsTable", ".", "getRandomBitSet", "(", "aSubgroupSize", ")", ")", ";", "}", "private", "Subgroup", "getValidSubgroup", "(", "int", "theDepth", ",", "int", "theMinimumCoverage", ",", "Random", "theRandom", ")", "{", "final", "int", "aNrRows", "=", "itsTable", ".", "getNrRows", "(", ")", ";", "int", "aSubgroupSize", ";", "ConditionListA", "aCL", ";", "BitSet", "aMembers", ";", "do", "{", "aCL", "=", "getRandomConditionList", "(", "theDepth", ",", "theRandom", ")", ";", "aMembers", "=", "itsTable", ".", "evaluate", "(", "aCL", ")", ";", "aSubgroupSize", "=", "aMembers", ".", "cardinality", "(", ")", ";", "}", "while", "(", "aSubgroupSize", "<", "theMinimumCoverage", "||", "aSubgroupSize", "==", "aNrRows", ")", ";", "Log", ".", "logCommandLine", "(", "aCL", ".", "toString", "(", ")", ")", ";", "return", "new", "Subgroup", "(", "aMembers", ")", ";", "}", "/**\n\t * Swap randomizes the original {@link Table} and restores it to the\n\t * original state afterwards.\n\t *\n\t * @param theNrRepetitions the number of times to perform a permutation\n\t * of the {@link TargetConcept}.\n\t *\n\t * @return an array holding the qualities of the best scoring\n\t * {@link Subgroup} of each permutation.\n\t */", "private", "double", "[", "]", "swapRandomization", "(", "int", "theNrRepetitions", ")", "{", "boolean", "aCOMMANDLINELOGmem", "=", "Log", ".", "COMMANDLINELOG", ";", "double", "[", "]", "aQualities", "=", "new", "double", "[", "theNrRepetitions", "]", ";", "final", "TargetType", "aTargetType", "=", "itsTargetConcept", ".", "getTargetType", "(", ")", ";", "switch", "(", "aTargetType", ")", "{", "case", "SINGLE_NOMINAL", ":", "{", "Column", "aPrimaryCopy", "=", "itsTargetConcept", ".", "getPrimaryTarget", "(", ")", ".", "copy", "(", ")", ";", "int", "aPositiveCount", "=", "itsTargetConcept", ".", "getPrimaryTarget", "(", ")", ".", "countValues", "(", "itsTargetConcept", ".", "getTargetValue", "(", ")", ",", "itsSelection", ")", ";", "for", "(", "int", "i", "=", "0", ",", "j", "=", "theNrRepetitions", ";", "i", "<", "j", ";", "++", "i", ")", "{", "itsTable", ".", "swapRandomizeTarget", "(", "itsTargetConcept", ")", ";", "i", "=", "runSRSD", "(", "new", "SubgroupDiscovery", "(", "itsSearchParameters", ",", "itsTable", ",", "itsSelection", ",", "aPositiveCount", ",", "null", ")", ",", "aQualities", ",", "i", ")", ";", "}", "itsTargetConcept", ".", "setPrimaryTarget", "(", "aPrimaryCopy", ")", ";", "itsTable", ".", "getColumns", "(", ")", ".", "set", "(", "aPrimaryCopy", ".", "getIndex", "(", ")", ",", "aPrimaryCopy", ")", ";", "break", ";", "}", "case", "SINGLE_NUMERIC", ":", "{", "Column", "aPrimaryCopy", "=", "itsTargetConcept", ".", "getPrimaryTarget", "(", ")", ".", "copy", "(", ")", ";", "float", "aTargetAverage", "=", "itsTargetConcept", ".", "getPrimaryTarget", "(", ")", ".", "getAverage", "(", "itsSelection", ")", ";", "for", "(", "int", "i", "=", "0", ",", "j", "=", "theNrRepetitions", ";", "i", "<", "j", ";", "++", "i", ")", "{", "itsTable", ".", "swapRandomizeTarget", "(", "itsTargetConcept", ")", ";", "SubgroupDiscovery", "anSD", "=", "new", "SubgroupDiscovery", "(", "itsSearchParameters", ",", "itsTable", ",", "itsSelection", ",", "aTargetAverage", ",", "null", ")", ";", "i", "=", "runSRSD", "(", "anSD", ",", "aQualities", ",", "i", ")", ";", "}", "itsTargetConcept", ".", "setPrimaryTarget", "(", "aPrimaryCopy", ")", ";", "itsTable", ".", "getColumns", "(", ")", ".", "set", "(", "aPrimaryCopy", ".", "getIndex", "(", ")", ",", "aPrimaryCopy", ")", ";", "break", ";", "}", "case", "DOUBLE_REGRESSION", ":", "{", "Column", "aPrimaryCopy", "=", "itsTargetConcept", ".", "getPrimaryTarget", "(", ")", ".", "copy", "(", ")", ";", "Column", "aSecondaryCopy", "=", "itsTargetConcept", ".", "getSecondaryTarget", "(", ")", ".", "copy", "(", ")", ";", "for", "(", "int", "i", "=", "0", ",", "j", "=", "theNrRepetitions", ";", "i", "<", "j", ";", "++", "i", ")", "{", "itsTable", ".", "swapRandomizeTarget", "(", "itsTargetConcept", ")", ";", "i", "=", "runSRSD", "(", "new", "SubgroupDiscovery", "(", "itsSearchParameters", ",", "itsTable", ",", "itsSelection", ",", "true", ",", "null", ")", ",", "aQualities", ",", "i", ")", ";", "}", "itsTargetConcept", ".", "setPrimaryTarget", "(", "aPrimaryCopy", ")", ";", "itsTable", ".", "getColumns", "(", ")", ".", "set", "(", "aPrimaryCopy", ".", "getIndex", "(", ")", ",", "aPrimaryCopy", ")", ";", "itsTargetConcept", ".", "setSecondaryTarget", "(", "aSecondaryCopy", ")", ";", "itsTable", ".", "getColumns", "(", ")", ".", "set", "(", "aSecondaryCopy", ".", "getIndex", "(", ")", ",", "aSecondaryCopy", ")", ";", "break", ";", "}", "case", "DOUBLE_CORRELATION", ":", "{", "Column", "aPrimaryCopy", "=", "itsTargetConcept", ".", "getPrimaryTarget", "(", ")", ".", "copy", "(", ")", ";", "Column", "aSecondaryCopy", "=", "itsTargetConcept", ".", "getSecondaryTarget", "(", ")", ".", "copy", "(", ")", ";", "for", "(", "int", "i", "=", "0", ",", "j", "=", "theNrRepetitions", ";", "i", "<", "j", ";", "++", "i", ")", "{", "itsTable", ".", "swapRandomizeTarget", "(", "itsTargetConcept", ")", ";", "i", "=", "runSRSD", "(", "new", "SubgroupDiscovery", "(", "itsSearchParameters", ",", "itsTable", ",", "itsSelection", ",", "false", ",", "null", ")", ",", "aQualities", ",", "i", ")", ";", "}", "itsTargetConcept", ".", "setPrimaryTarget", "(", "aPrimaryCopy", ")", ";", "itsTable", ".", "getColumns", "(", ")", ".", "set", "(", "aPrimaryCopy", ".", "getIndex", "(", ")", ",", "aPrimaryCopy", ")", ";", "itsTargetConcept", ".", "setSecondaryTarget", "(", "aSecondaryCopy", ")", ";", "itsTable", ".", "getColumns", "(", ")", ".", "set", "(", "aSecondaryCopy", ".", "getIndex", "(", ")", ",", "aSecondaryCopy", ")", ";", "break", ";", "}", "case", "DOUBLE_BINARY", ":", "{", "Column", "aPrimaryCopy", "=", "itsTargetConcept", ".", "getPrimaryTarget", "(", ")", ".", "copy", "(", ")", ";", "Column", "aSecondaryCopy", "=", "itsTargetConcept", ".", "getSecondaryTarget", "(", ")", ".", "copy", "(", ")", ";", "for", "(", "int", "i", "=", "0", ",", "j", "=", "theNrRepetitions", ";", "i", "<", "j", ";", "++", "i", ")", "{", "itsTable", ".", "swapRandomizeTarget", "(", "itsTargetConcept", ")", ";", "i", "=", "runSRSD", "(", "new", "SubgroupDiscovery", "(", "itsSearchParameters", ",", "itsTable", ",", "itsSelection", ",", "false", ",", "null", ")", ",", "aQualities", ",", "i", ")", ";", "}", "itsTargetConcept", ".", "setPrimaryTarget", "(", "aPrimaryCopy", ")", ";", "itsTable", ".", "getColumns", "(", ")", ".", "set", "(", "aPrimaryCopy", ".", "getIndex", "(", ")", ",", "aPrimaryCopy", ")", ";", "itsTargetConcept", ".", "setSecondaryTarget", "(", "aSecondaryCopy", ")", ";", "itsTable", ".", "getColumns", "(", ")", ".", "set", "(", "aSecondaryCopy", ".", "getIndex", "(", ")", ",", "aSecondaryCopy", ")", ";", "break", ";", "}", "case", "MULTI_LABEL", ":", "{", "List", "<", "Column", ">", "aMultiCopy", "=", "new", "ArrayList", "<", "Column", ">", "(", "itsTargetConcept", ".", "getMultiTargets", "(", ")", ".", "size", "(", ")", ")", ";", "for", "(", "Column", "c", ":", "itsTargetConcept", ".", "getMultiTargets", "(", ")", ")", "aMultiCopy", ".", "add", "(", "c", ".", "copy", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ",", "j", "=", "theNrRepetitions", ";", "i", "<", "j", ";", "++", "i", ")", "{", "itsTable", ".", "swapRandomizeTarget", "(", "itsTargetConcept", ")", ";", "i", "=", "runSRSD", "(", "new", "SubgroupDiscovery", "(", "itsSearchParameters", ",", "itsTable", ",", "itsSelection", ",", "null", ")", ",", "aQualities", ",", "i", ")", ";", "}", "itsTargetConcept", ".", "setMultiTargets", "(", "aMultiCopy", ")", ";", "for", "(", "Column", "c", ":", "aMultiCopy", ")", "itsTable", ".", "getColumns", "(", ")", ".", "set", "(", "c", ".", "getIndex", "(", ")", ",", "c", ")", ";", "break", ";", "}", "case", "MULTI_BINARY_CLASSIFICATION", ":", "{", "throw", "new", "AssertionError", "(", "aTargetType", ")", ";", "}", "case", "LABEL_RANKING", ":", "{", "Column", "aPrimaryCopy", "=", "itsTargetConcept", ".", "getPrimaryTarget", "(", ")", ".", "copy", "(", ")", ";", "for", "(", "int", "i", "=", "0", ",", "j", "=", "theNrRepetitions", ";", "i", "<", "j", ";", "++", "i", ")", "{", "itsTable", ".", "swapRandomizeTarget", "(", "itsTargetConcept", ")", ";", "i", "=", "runSRSD", "(", "new", "SubgroupDiscovery", "(", "itsSearchParameters", ",", "null", ",", "itsTable", ",", "itsSelection", ")", ",", "aQualities", ",", "i", ")", ";", "}", "itsTargetConcept", ".", "setPrimaryTarget", "(", "aPrimaryCopy", ")", ";", "itsTable", ".", "getColumns", "(", ")", ".", "set", "(", "aPrimaryCopy", ".", "getIndex", "(", ")", ",", "aPrimaryCopy", ")", ";", "break", ";", "}", "default", ":", "{", "throw", "new", "AssertionError", "(", "aTargetType", ")", ";", "}", "}", "Log", ".", "COMMANDLINELOG", "=", "aCOMMANDLINELOGmem", ";", "return", "aQualities", ";", "}", "public", "float", "getSignWithSwapRand", "(", "int", "theNrRepetitions", ")", "{", "double", "[", "]", "aQualities", "=", "swapRandomization", "(", "theNrRepetitions", ")", ";", "NormalDistribution", "aDistro", "=", "new", "NormalDistribution", "(", "aQualities", ")", ";", "return", "aDistro", ".", "getFivePercentSignificance", "(", ")", ";", "}", "/*\n\t * NOTE for the first result (i = 0) to be not equal to the original\n\t * mining result the calling function should run:\n\t * itsTable.swapRandomizeTarget(itsTargetConcept);\n\t * before creating the new theSubgroupDiscovery, and calling this\n\t * method.\n\t */", "private", "int", "runSRSD", "(", "SubgroupDiscovery", "theSubgroupDiscovery", ",", "double", "[", "]", "theQualities", ",", "int", "theRepetition", ")", "{", "theSubgroupDiscovery", ".", "ignoreQualityMinimum", "(", ")", ";", "Log", ".", "COMMANDLINELOG", "=", "false", ";", "theSubgroupDiscovery", ".", "mine", "(", "System", ".", "currentTimeMillis", "(", ")", ",", "itsSearchParameters", ".", "getNrThreads", "(", ")", ")", ";", "Log", ".", "COMMANDLINELOG", "=", "true", ";", "SubgroupSet", "aSubgroupSet", "=", "theSubgroupDiscovery", ".", "getResult", "(", ")", ";", "if", "(", "aSubgroupSet", ".", "size", "(", ")", "==", "0", ")", "--", "theRepetition", ";", "else", "{", "theQualities", "[", "theRepetition", "]", "=", "aSubgroupSet", ".", "getBestScore", "(", ")", ";", "Log", ".", "logCommandLine", "(", "(", "theRepetition", "+", "1", ")", "+", "\"", ", ", "\"", "+", "theQualities", "[", "theRepetition", "]", ")", ";", "}", "return", "theRepetition", ";", "}", "private", "ConditionListA", "getRandomConditionList", "(", "int", "theDepth", ",", "Random", "theRandom", ")", "{", "int", "aDepth", "=", "1", "+", "theRandom", ".", "nextInt", "(", "theDepth", ")", ";", "ConditionListA", "aCL", "=", "ConditionListBuilder", ".", "emptyList", "(", ")", ";", "int", "aNrColumns", "=", "itsTable", ".", "getNrColumns", "(", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "aDepth", ";", "j", "++", ")", "{", "Column", "aColumn", ";", "do", "aColumn", "=", "itsTable", ".", "getColumn", "(", "theRandom", ".", "nextInt", "(", "aNrColumns", ")", ")", ";", "while", "(", "itsTargetConcept", ".", "isTargetAttribute", "(", "aColumn", ")", "||", "!", "aColumn", ".", "getIsEnabled", "(", ")", ")", ";", "ConditionBase", "aConditionBase", ";", "Condition", "aCondition", ";", "switch", "(", "aColumn", ".", "getType", "(", ")", ")", "{", "case", "NOMINAL", ":", "{", "TreeSet", "<", "String", ">", "aDomain", "=", "aColumn", ".", "getDomain", "(", ")", ";", "int", "aNrDistinct", "=", "aDomain", ".", "size", "(", ")", ";", "int", "aRandomIndex", "=", "(", "int", ")", "(", "theRandom", ".", "nextDouble", "(", ")", "*", "aNrDistinct", ")", ";", "Iterator", "<", "String", ">", "anIterator", "=", "aDomain", ".", "iterator", "(", ")", ";", "String", "aValue", "=", "anIterator", ".", "next", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "aRandomIndex", ";", "i", "++", ")", "aValue", "=", "anIterator", ".", "next", "(", ")", ";", "aConditionBase", "=", "new", "ConditionBase", "(", "aColumn", ",", "Operator", ".", "EQUALS", ")", ";", "aCondition", "=", "new", "Condition", "(", "aConditionBase", ",", "aValue", ")", ";", "break", ";", "}", "case", "NUMERIC", ":", "{", "Operator", "anOperator", "=", "theRandom", ".", "nextBoolean", "(", ")", "?", "Operator", ".", "LESS_THAN_OR_EQUAL", ":", "Operator", ".", "GREATER_THAN_OR_EQUAL", ";", "float", "aMin", "=", "aColumn", ".", "getMin", "(", ")", ";", "float", "aMax", "=", "aColumn", ".", "getMax", "(", ")", ";", "float", "aRange", "=", "aMax", "-", "aMin", ";", "float", "aValue", "=", "(", "aMin", "+", "0.1f", "*", "aRange", "+", "0.8f", "*", "aRange", "*", "theRandom", ".", "nextFloat", "(", ")", ")", ";", "aConditionBase", "=", "new", "ConditionBase", "(", "aColumn", ",", "anOperator", ")", ";", "aCondition", "=", "new", "Condition", "(", "aConditionBase", ",", "aValue", ",", "Condition", ".", "UNINITIALISED_SORT_INDEX", ")", ";", "break", ";", "}", "case", "BINARY", ":", "{", "aConditionBase", "=", "new", "ConditionBase", "(", "aColumn", ",", "Operator", ".", "EQUALS", ")", ";", "aCondition", "=", "new", "Condition", "(", "aConditionBase", ",", "theRandom", ".", "nextBoolean", "(", ")", ")", ";", "break", ";", "}", "default", ":", "throw", "new", "AssertionError", "(", "aColumn", ".", "getType", "(", ")", ")", ";", "}", "aCL", "=", "ConditionListBuilder", ".", "createList", "(", "aCL", ",", "aCondition", ")", ";", "}", "return", "aCL", ";", "}", "public", "static", "final", "double", "[", "]", "performRegressionTest", "(", "double", "[", "]", "theQualities", ",", "SubgroupSet", "theSubgroupSet", ")", "{", "double", "aOne", "=", "performRegressionTest", "(", "theQualities", ",", "1", ",", "theSubgroupSet", ")", ";", "double", "aTen", "=", "Math", ".", "PI", ";", "if", "(", "theSubgroupSet", ".", "size", "(", ")", ">=", "10", ")", "aTen", "=", "performRegressionTest", "(", "theQualities", ",", "10", ",", "theSubgroupSet", ")", ";", "double", "[", "]", "aResult", "=", "{", "aOne", ",", "aTen", "}", ";", "return", "aResult", ";", "}", "private", "static", "final", "double", "performRegressionTest", "(", "double", "[", "]", "theQualities", ",", "int", "theK", ",", "SubgroupSet", "theSubgroupSet", ")", "{", "double", "aTopKQuality", "=", "0.0", ";", "for", "(", "Subgroup", "aSubgroup", ":", "theSubgroupSet", ")", "aTopKQuality", "+=", "aSubgroup", ".", "getMeasureValue", "(", ")", ";", "aTopKQuality", "/=", "theK", ";", "int", "theNrRandomSubgroups", "=", "theQualities", ".", "length", ";", "double", "[", "]", "aCopy", "=", "Arrays", ".", "copyOf", "(", "theQualities", ",", "theQualities", ".", "length", ")", ";", "Arrays", ".", "sort", "(", "aCopy", ")", ";", "double", "aMin", "=", "Math", ".", "min", "(", "aCopy", "[", "0", "]", ",", "aTopKQuality", ")", ";", "double", "aMax", "=", "Math", ".", "max", "(", "aCopy", "[", "theNrRandomSubgroups", "-", "1", "]", ",", "aTopKQuality", ")", ";", "double", "xBar", "=", "0.5", ";", "double", "yBar", "=", "0.0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "theNrRandomSubgroups", ";", "i", "++", ")", "{", "aCopy", "[", "i", "]", "=", "(", "aCopy", "[", "i", "]", "-", "aMin", ")", "/", "(", "aMax", "-", "aMin", ")", ";", "yBar", "+=", "aCopy", "[", "i", "]", ";", "}", "aTopKQuality", "=", "(", "aTopKQuality", "-", "aMin", ")", "/", "(", "aMax", "-", "aMin", ")", ";", "yBar", "=", "(", "yBar", "+", "aTopKQuality", ")", "/", "(", "(", "double", ")", "theNrRandomSubgroups", "+", "1", ")", ";", "double", "xxBar", "=", "0.25", ";", "double", "xyBar", "=", "0.5", "*", "(", "aTopKQuality", "-", "yBar", ")", ";", "double", "[", "]", "anXs", "=", "new", "double", "[", "theNrRandomSubgroups", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "theNrRandomSubgroups", ";", "i", "++", ")", "{", "anXs", "[", "i", "]", "=", "(", "(", "double", ")", "i", ")", "/", "(", "(", "double", ")", "theNrRandomSubgroups", ")", ";", "Log", ".", "logCommandLine", "(", "\"", "\"", "+", "anXs", "[", "i", "]", "+", "\"", "\\t", "\"", "+", "aCopy", "[", "i", "]", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "theNrRandomSubgroups", ";", "i", "++", ")", "{", "xxBar", "+=", "(", "anXs", "[", "i", "]", "-", "xBar", ")", "*", "(", "anXs", "[", "i", "]", "-", "xBar", ")", ";", "xyBar", "+=", "(", "anXs", "[", "i", "]", "-", "xBar", ")", "*", "(", "aCopy", "[", "i", "]", "-", "yBar", ")", ";", "}", "double", "beta1", "=", "xyBar", "/", "xxBar", ";", "double", "beta0", "=", "yBar", "-", "beta1", "*", "xBar", ";", "Log", ".", "logCommandLine", "(", "\"", "Fitted regression line: y = ", "\"", "+", "beta1", "+", "\"", " * x + ", "\"", "+", "beta0", ")", ";", "double", "aScore", "=", "aTopKQuality", "-", "beta1", "-", "beta0", ";", "Log", ".", "logCommandLine", "(", "\"", "Regression test score: ", "\"", "+", "aScore", ")", ";", "return", "aScore", ";", "}", "public", "static", "final", "double", "computeEmpiricalPValue", "(", "double", "[", "]", "theQualities", ",", "SubgroupSet", "theSubgroupSet", ")", "{", "int", "aK", "=", "1", ";", "Iterator", "<", "Subgroup", ">", "anIterator", "=", "theSubgroupSet", ".", "iterator", "(", ")", ";", "double", "aTopKQuality", "=", "0.0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "aK", ";", "i", "++", ")", "{", "Subgroup", "aSubgroup", "=", "anIterator", ".", "next", "(", ")", ";", "aTopKQuality", "+=", "aSubgroup", ".", "getMeasureValue", "(", ")", ";", "}", "aTopKQuality", "/=", "aK", ";", "int", "aCount", "=", "0", ";", "for", "(", "double", "aQuality", ":", "theQualities", ")", "if", "(", "aQuality", ">", "aTopKQuality", ")", "aCount", "++", ";", "Arrays", ".", "sort", "(", "theQualities", ")", ";", "Log", ".", "logCommandLine", "(", "\"", "Empirical p-value: ", "\"", "+", "aCount", "/", "(", "double", ")", "theQualities", ".", "length", ")", ";", "return", "aCount", "/", "(", "(", "double", ")", "theQualities", ".", "length", ")", ";", "}", "}" ]
Functionality related to the statistical validation of subgroups.
[ "Functionality", "related", "to", "the", "statistical", "validation", "of", "subgroups", "." ]
[ "// FIXME MM - this method should not be separate from the constructor", "// the data can be changed in between, causing bugs", "// also, the whole class should consist of just static methods", "// of split constructor (not all TargetTypes use QualityMeasure)", "// add TargetTypes implemented in getRandomQualitites() to this list", "//final Random aRandom = new Random(System.currentTimeMillis());", "// if forSubgroups is true, create Subgroups, else create Conditions", "// if forSubgroups is true, theDepth is ignored", "////////////////////////////////////////////////////////////////////////////////", "///// FIXME - WHY IS THIS HERE, itsBinaryTarget IS AVAILABLE ALREADY /////", "///// TECHNICALLY, IT IS ALSO WRONG -> BUG /////", "///// WHEN DATA IS CHANGED AFTER THE ResultWindow IS CREATED, THE /////", "///// THE ORIGINAL Condition MIGHT NOT BE ABLE TO RECREATE THE /////", "///// SAME BitSet AS itsBinaryTarget, BUT THIS IS A WIDER PROBLEM /////", "////////////////////////////////////////////////////////////////////////////////", "// create a binary target", "////////////////////////////////////////////////////////////////////////////////", "////////////////////////////////////////////////////////////////////////////////", "////////////////////////////////////////////////////////////////////////////////", "// essential switch between Subgroups/ Conditions", "// aMembers is a clone so this is safe", "// if forSubgroups is true, create Subgroups, else create Conditions", "// if forSubgroups is true, theDepth is ignored", "// essential switch between Subgroups/ Conditions", "//TODO check for theSelection", "// DEBUG", "// if forSubgroups is true, create Subgroups, else create Conditions", "// if forSubgroups is true, theDepth is ignored", "// essential switch between Subgroups/ Conditions", "// if forSubgroups is true, create Subgroups, else create Conditions", "// if forSubgroups is true, theDepth is ignored", "// essential switch between Subgroups/ Conditions", "// if forSubgroups is true, create Subgroups, else create Conditions", "// if forSubgroups is true, theDepth is ignored", "// essential switch between Subgroups/ Conditions", "// if forSubgroups is true, create Subgroups, else create Conditions", "// if forSubgroups is true, theDepth is ignored", "// base model", "// essential switch between Subgroups/ Conditions", "// build model", "// store DAG with subgroup for later use", "// XXX original code only did this for Condition", "//TODO: fix implementation", "// if forSubgroups is true, create Subgroups, else create Conditions", "// if forSubgroups is true, theDepth is ignored", "//average ranking over entire dataset", "//temp<--", "//temp-->", "// essential switch between Subgroups/ Conditions", "//temp<--", "//temp-->", "//temp<--", "//temp-->", "// for RANDOM_SUBSETS/Subgroups, always uses an updated Random value", "// for RANDOM_DESCRIPTIONS/Conditions, always uses the same Random value", "//ConditionList aCL;", "// Memorize COMMANDLINELOG setting", "// Always back up and restore columns that will be swap randomized.", "// back up column that will be swap randomized", "// generate swap randomized random results", "// restore column that was swap randomized", "// back up column that will be swap randomized", "// generate swap randomized random results", "// restore column that was swap randomized", "// back up columns that will be swap randomized", "// generate swap randomized random results", "// restore columns that were swap randomized", "// back up columns that will be swap randomized", "// generate swap randomized random results", "// restore columns that were swap randomized", "// back up columns that will be swap randomized", "// generate swap randomized random results", "// restore columns that were swap randomized", "// back up columns that will be swap randomized", "// generate swap randomized random results", "// swapRandomization should be performed before creating new SubgroupDiscovery", "// restore columns that were swap randomized", "// back up column that will be swap randomized", "// generate swap randomized random results", "// restore column that was swap randomized", "//returns the 5% significance of swap randomisation.", "//quality minimum should not be taken into account when computing distribution of random qualities", "// if no subgroups are found, try again", "//private ConditionList getRandomConditionList(int theDepth, Random theRandom)", "//random nr between 1 and theDepth (incl)", "//ConditionList aCL = new ConditionList(aDepth);", "// j conditions", "// select a random value from the domain", "// fairly crude way of producing random thresholds, but will do for now", "// value may not occur in Column, so can not set sort index", "//aCL.addCondition(aCondition);", "//extract average quality", "// make deep copy of double array", "//public static double[] copyOf(double[] original, int newLength)", "// rescale all qualities between 0 and 1", "// also compute some necessary statistics", "// given our scaling this always holds", "// initial value", "// perform least squares linear regression on equidistant x-values and computed y-values", "// initial value: this equals the square of (the x-value of our subgroup minus xbar)", "// this gives us the regression line y = beta1 * x + beta0", "// the regression test score now equals the average quality of the top-k subgroups, minus the regression value at x=1.", "//hardcoded", "// extract average quality of top-k subgroups", "//\t\tLog.logCommandLine(\"score at alpha = 1%: \" + theQualities[theQualities.length-theQualities.length/100]);", "//\t\tLog.logCommandLine(\"score at alpha = 5%: \" + theQualities[theQualities.length-theQualities.length/20]);", "//\t\tLog.logCommandLine(\"score at alpha = 10%: \" + theQualities[theQualities.length-theQualities.length/10]);" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c42f15b877f953b3678b76e65e010c35b6affed7
giosil/wfhir
src/main/java/org/dew/fhir/model/BodyStructure.java
[ "Apache-2.0" ]
Java
BodyStructure
/** * * Record details about an anatomical structure. * This resource may be used when a coded concept does not provide the necessary detail needed for the use case. * * @see <a href="https://www.hl7.org/fhir/bodystructure.html">BodyStructure</a> */
Record details about an anatomical structure. This resource may be used when a coded concept does not provide the necessary detail needed for the use case.
[ "Record", "details", "about", "an", "anatomical", "structure", ".", "This", "resource", "may", "be", "used", "when", "a", "coded", "concept", "does", "not", "provide", "the", "necessary", "detail", "needed", "for", "the", "use", "case", "." ]
public class BodyStructure extends DomainResource implements Serializable { private static final long serialVersionUID = 231224956059441942L; protected Identifier[] identifier; protected Boolean active; protected CodeableConcept morphology; protected CodeableConcept location; protected CodeableConcept[] locationQualifier; protected String description; protected Attachment[] image; protected Reference<Patient> patient; public BodyStructure() { } public Identifier[] getIdentifier() { return identifier; } public Boolean getActive() { return active; } public CodeableConcept getMorphology() { return morphology; } public CodeableConcept getLocation() { return location; } public CodeableConcept[] getLocationQualifier() { return locationQualifier; } public String getDescription() { return description; } public Attachment[] getImage() { return image; } public Reference<Patient> getPatient() { return patient; } public void setIdentifier(Identifier[] identifier) { this.identifier = identifier; } public void setActive(Boolean active) { this.active = active; } public void setMorphology(CodeableConcept morphology) { this.morphology = morphology; } public void setLocation(CodeableConcept location) { this.location = location; } public void setLocationQualifier(CodeableConcept[] locationQualifier) { this.locationQualifier = locationQualifier; } public void setDescription(String description) { this.description = description; } public void setImage(Attachment[] image) { this.image = image; } public void setPatient(Reference<Patient> patient) { this.patient = patient; } @Override public boolean equals(Object object) { if(object instanceof BodyStructure) { return this.hashCode() == object.hashCode(); } return false; } @Override public int hashCode() { if(id == null) return 0; return id.hashCode(); } @Override public String toString() { return "BodyStructure(" + id + ")"; } }
[ "public", "class", "BodyStructure", "extends", "DomainResource", "implements", "Serializable", "{", "private", "static", "final", "long", "serialVersionUID", "=", "231224956059441942L", ";", "protected", "Identifier", "[", "]", "identifier", ";", "protected", "Boolean", "active", ";", "protected", "CodeableConcept", "morphology", ";", "protected", "CodeableConcept", "location", ";", "protected", "CodeableConcept", "[", "]", "locationQualifier", ";", "protected", "String", "description", ";", "protected", "Attachment", "[", "]", "image", ";", "protected", "Reference", "<", "Patient", ">", "patient", ";", "public", "BodyStructure", "(", ")", "{", "}", "public", "Identifier", "[", "]", "getIdentifier", "(", ")", "{", "return", "identifier", ";", "}", "public", "Boolean", "getActive", "(", ")", "{", "return", "active", ";", "}", "public", "CodeableConcept", "getMorphology", "(", ")", "{", "return", "morphology", ";", "}", "public", "CodeableConcept", "getLocation", "(", ")", "{", "return", "location", ";", "}", "public", "CodeableConcept", "[", "]", "getLocationQualifier", "(", ")", "{", "return", "locationQualifier", ";", "}", "public", "String", "getDescription", "(", ")", "{", "return", "description", ";", "}", "public", "Attachment", "[", "]", "getImage", "(", ")", "{", "return", "image", ";", "}", "public", "Reference", "<", "Patient", ">", "getPatient", "(", ")", "{", "return", "patient", ";", "}", "public", "void", "setIdentifier", "(", "Identifier", "[", "]", "identifier", ")", "{", "this", ".", "identifier", "=", "identifier", ";", "}", "public", "void", "setActive", "(", "Boolean", "active", ")", "{", "this", ".", "active", "=", "active", ";", "}", "public", "void", "setMorphology", "(", "CodeableConcept", "morphology", ")", "{", "this", ".", "morphology", "=", "morphology", ";", "}", "public", "void", "setLocation", "(", "CodeableConcept", "location", ")", "{", "this", ".", "location", "=", "location", ";", "}", "public", "void", "setLocationQualifier", "(", "CodeableConcept", "[", "]", "locationQualifier", ")", "{", "this", ".", "locationQualifier", "=", "locationQualifier", ";", "}", "public", "void", "setDescription", "(", "String", "description", ")", "{", "this", ".", "description", "=", "description", ";", "}", "public", "void", "setImage", "(", "Attachment", "[", "]", "image", ")", "{", "this", ".", "image", "=", "image", ";", "}", "public", "void", "setPatient", "(", "Reference", "<", "Patient", ">", "patient", ")", "{", "this", ".", "patient", "=", "patient", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "object", ")", "{", "if", "(", "object", "instanceof", "BodyStructure", ")", "{", "return", "this", ".", "hashCode", "(", ")", "==", "object", ".", "hashCode", "(", ")", ";", "}", "return", "false", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "if", "(", "id", "==", "null", ")", "return", "0", ";", "return", "id", ".", "hashCode", "(", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "BodyStructure(", "\"", "+", "id", "+", "\"", ")", "\"", ";", "}", "}" ]
Record details about an anatomical structure.
[ "Record", "details", "about", "an", "anatomical", "structure", "." ]
[]
[ { "param": "DomainResource", "type": null }, { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "DomainResource", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c4300c10a80d10762eb47f422e43a1823607596a
Energyxxer/MC-Tech
src/com/energyxxer/commodore/CommandUtils.java
[ "MIT" ]
Java
CommandUtils
/** * Class containing a series of utility methods and constants for common use in commands. * */
Class containing a series of utility methods and constants for common use in commands.
[ "Class", "containing", "a", "series", "of", "utility", "methods", "and", "constants", "for", "common", "use", "in", "commands", "." ]
public final class CommandUtils { /** * String describing all the characters allowed in a string without the need of quotation marks used * in places such as objective names, nbt tag keys, entity tags, team names, etc. * */ public static final String IDENTIFIER_ALLOWED = "[A-Za-z0-9_.\\-+]*"; private static final HashMap<Character, String> ESCAPED = new HashMap<>(); static { ESCAPED.put('\b', "b"); ESCAPED.put('\n', "n"); ESCAPED.put('\f', "f"); ESCAPED.put('\r', "r"); ESCAPED.put('\t', "t"); } /** * Escapes the given string's quotes and backslashes. * * @param str The string to be escaped. * * @return The escaped string. * */ @NotNull public static String escape(@NotNull String str) { return escape(str, true); } /** * Escapes the given string's quotes and backslashes. * * @param str The string to be escaped. * * @return The escaped string. * */ @NotNull public static String escape(@NotNull String str, boolean escapeUnicode) { str = str.replace("\\", "\\\\").replace("\"", "\\\""); StringBuilder sb = new StringBuilder(); for(char c : str.toCharArray()) { if(((int) c) > 127 && escapeUnicode) { sb.append("\\u"); sb.append(padLeft(Integer.toString((int)c, 16).toUpperCase(Locale.ENGLISH), 4, '0')); } else if(ESCAPED.containsKey(c)) { sb.append("\\"); sb.append(ESCAPED.get(c)); } else { sb.append(c); } } return sb.toString(); } public static String padLeft(@NotNull String str, int minChars, char padChar) { int newChars = minChars - str.length(); if(newChars <= 0) return str; StringBuilder sb = new StringBuilder(); for(int i = 0; i < newChars; i++) { sb.append(padChar); } sb.append(str); return sb.toString(); } /** * Escapes and wraps the given string in quotes if not all its characters are allowed by commands in an * unquoted string. If all characters are allowed, nothing is changed. * * @param str The string to check and, if needed, quote. * * @return The given string, quoted, only if it contains a character not allowed in an unquoted string. Otherwise, * the returned string is the same as the original. * */ @NotNull public static String quoteIfNecessary(@NotNull String str) { return (needsQuoting(str)) ? "\"" + escape(str) + "\"" : str; } /** * Escapes and wraps the given string in quotes if not all its characters are allowed by commands in an * unquoted string. If all characters are allowed, nothing is changed. * * @param str The string to check and, if needed, quote. * * @return The given string, quoted, only if it contains a character not allowed in an unquoted string. Otherwise, * the returned string is the same as the original. * */ @NotNull public static String quoteIfNecessary(@NotNull String str, boolean escapeUnicode) { return (needsQuoting(str)) ? "\"" + escape(str, escapeUnicode) + "\"" : str; } /** * Escapes and wraps the given string in quotes if not all its characters are allowed by commands in an * unquoted string. If all characters are allowed, nothing is changed. * * @param str The string to check and, if needed, quote. * @param featureKey The feature key from which to retrieve the regex. * @param defaultRegex The default regex to use, in case the featureKey is not found in the active feature map. * * @return The given string, quoted, only if it contains a character not allowed in an unquoted string. Otherwise, * the returned string is the same as the original. * */ @NotNull public static String quoteIfNecessary(@NotNull String str, @NotNull String featureKey, String defaultRegex) { return (needsQuoting(str, featureKey, defaultRegex)) ? "\"" + escape(str) + "\"" : str; } /** * Escapes and wraps the given string in quotes if not all its characters are allowed by commands in an * unquoted string. If all characters are allowed, nothing is changed. * * @param str The string to check and, if needed, quote. * @param featureKey0 The feature key from which to retrieve the regex. * @param featureKey1 The backup feature key from which to retrieve the regex, if featureKey1 was not found. * @param defaultRegex The default regex to use, in case neither featureKey0 nor featureKey1 is not found in the active feature map. * * @return The given string, quoted, only if it contains a character not allowed in an unquoted string. Otherwise, * the returned string is the same as the original. * */ @NotNull public static String quoteIfNecessary(@NotNull String str, @NotNull String featureKey0, @NotNull String featureKey1, String defaultRegex) { return (needsQuoting(str, featureKey0, featureKey1, defaultRegex)) ? "\"" + escape(str) + "\"" : str; } /** * Returns whether this character contains any characters disallowed in unquoted strings. * * @param str The string whose need for quotation is to be tested. * * @return <code>true</code> if this character contains any characters, disallowed in unquoted strings, * <code>false</code> if all characters are allowed in unquoted strings. * */ public static boolean needsQuoting(@NotNull String str) { return needsQuoting(str, "identifiers.regex", CommandUtils.IDENTIFIER_ALLOWED); } /** * Returns whether this character contains any characters disallowed in unquoted strings. * * @param str The string whose need for quotation is to be tested. * @param featureKey The feature key from which to retrieve the regex. * @param defaultRegex The default regex to use, in case the featureKey is not found in the active feature map. * * @return <code>true</code> if this character contains any characters, disallowed in unquoted strings, * <code>false</code> if all characters are allowed in unquoted strings. * */ public static boolean needsQuoting(@NotNull String str, @NotNull String featureKey, String defaultRegex) { return !str.matches(VersionFeatureManager.getString(featureKey, defaultRegex)); } /** * Returns whether this character contains any characters disallowed in unquoted strings. * * @param str The string whose need for quotation is to be tested. * @param featureKey0 The feature key from which to retrieve the regex. * @param featureKey1 The backup feature key from which to retrieve the regex, if featureKey1 was not found. * @param defaultRegex The default regex to use, in case neither featureKey0 nor featureKey1 is not found in the active feature map. * * @return <code>true</code> if this character contains any characters, disallowed in unquoted strings, * <code>false</code> if all characters are allowed in unquoted strings. * */ public static boolean needsQuoting(@NotNull String str, @NotNull String featureKey0, @NotNull String featureKey1, String defaultRegex) { return !str.matches(VersionFeatureManager.getString(featureKey0, VersionFeatureManager.getString(featureKey1, defaultRegex))); } /** * Converts the given number into its plain string representation. This method differs from * {@link Double#toString()} on two aspects: * * <ol> * <li>Whole numbers will be displayed without the decimal places.</li> * <li>Scientific notation will not be used for big nor small numbers.</li> * </ol> * * @param num The number to turn into a plain number string. * * @return The number, as a plain number string. * */ @NotNull public static String numberToPlainString(double num) { DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); df.setMaximumFractionDigits(340); return df.format(num); } /** * Converts the given number into its plain string representation. This method differs from * {@link Double#toString()} on two aspects: * * <ol> * <li>Whole numbers will be displayed without the decimal places.</li> * <li>Scientific notation will not be used for big nor small numbers.</li> * </ol> * * @param num The number to turn into a plain number string. * * @return The number, as a plain number string. * */ @NotNull public static String numberToPlainString(Number num) { DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); df.setMaximumFractionDigits(340); return df.format(num); } /** * Converts the given number into its plain string representation. This method differs from * {@link Double#toString()} in that scientific notation will not be used. * * @param num The number to turn into a non-scientific number string. * * @return The number, as a non-scientific number string. * */ @NotNull public static String numberToStringNoScientific(double num) { DecimalFormat df = new DecimalFormat("0.0", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); df.setMaximumFractionDigits(340); return df.format(num); } @NotNull public static JsonElement constructRange(@Nullable Integer min, @Nullable Integer max) { if(min != null && min.equals(max)) return new JsonPrimitive(min); else { JsonObject range = new JsonObject(); if(min != null) range.addProperty("min", min); if(max != null) range.addProperty("max", max); return range; } } @NotNull public static JsonElement constructRange(@Nullable Double min, @Nullable Double max) { if(min != null && min.equals(max)) return new JsonPrimitive(min); else { JsonObject range = new JsonObject(); if(min != null) range.addProperty("min", min); if(max != null) range.addProperty("max", max); return range; } } @NotNull public static String parseQuotedString(@NotNull String text) { int index = 0; char delimiter = text.charAt(index); if (delimiter != '"' && delimiter != '\'') throw new CommodoreException(CommodoreException.Source.FORMAT_ERROR, "Expected string at index " + index, text); index++; StringBuilder sb = new StringBuilder(); boolean escaped = false; boolean terminated = false; for (; index < text.length(); index++) { char c = text.charAt(index); if (!escaped) { if (c == '\\') { escaped = true; continue; } else if (c == delimiter) { terminated = true; break; } } else { escaped = false; boolean unicodeSequence = false; switch (c) { case '0': c = '\0'; break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case '\\': break; case '\'': break; case '\"': break; case 'u': unicodeSequence = true; break; default: throw new CommodoreException(CommodoreException.Source.FORMAT_ERROR, "Illegal escape sequence", text); } if (unicodeSequence) { int sequenceLength = 4; if (index + sequenceLength + 1 > text.length()) throw new CommodoreException(CommodoreException.Source.FORMAT_ERROR, "Unexpected end of unicode escape sequence", text); String sequence = text.substring(index + 1, index + 1 + sequenceLength); int code; try { code = Integer.parseInt(sequence, 16); } catch(NumberFormatException x) { throw new CommodoreException(CommodoreException.Source.FORMAT_ERROR, "Illegal unicode escape sequence", text); } String unicode = new String(Character.toChars(code)); sb.append(unicode); index += sequenceLength; continue; } } sb.append(c); } if (!terminated) throw new CommodoreException(CommodoreException.Source.FORMAT_ERROR, "Unexpected end of input", text); return sb.toString(); } /** * CommandUtils should not be instantiated. * */ private CommandUtils() { } public static String quote(String str) { return quote(str, true); } public static String quote(String str, boolean escapeUnicode) { return "\"" + escape(str, escapeUnicode) + "\""; } }
[ "public", "final", "class", "CommandUtils", "{", "/**\n * String describing all the characters allowed in a string without the need of quotation marks used\n * in places such as objective names, nbt tag keys, entity tags, team names, etc.\n * */", "public", "static", "final", "String", "IDENTIFIER_ALLOWED", "=", "\"", "[A-Za-z0-9_.", "\\\\", "-+]*", "\"", ";", "private", "static", "final", "HashMap", "<", "Character", ",", "String", ">", "ESCAPED", "=", "new", "HashMap", "<", ">", "(", ")", ";", "static", "{", "ESCAPED", ".", "put", "(", "'\\b'", ",", "\"", "b", "\"", ")", ";", "ESCAPED", ".", "put", "(", "'\\n'", ",", "\"", "n", "\"", ")", ";", "ESCAPED", ".", "put", "(", "'\\f'", ",", "\"", "f", "\"", ")", ";", "ESCAPED", ".", "put", "(", "'\\r'", ",", "\"", "r", "\"", ")", ";", "ESCAPED", ".", "put", "(", "'\\t'", ",", "\"", "t", "\"", ")", ";", "}", "/**\n * Escapes the given string's quotes and backslashes.\n *\n * @param str The string to be escaped.\n *\n * @return The escaped string.\n * */", "@", "NotNull", "public", "static", "String", "escape", "(", "@", "NotNull", "String", "str", ")", "{", "return", "escape", "(", "str", ",", "true", ")", ";", "}", "/**\n * Escapes the given string's quotes and backslashes.\n *\n * @param str The string to be escaped.\n *\n * @return The escaped string.\n * */", "@", "NotNull", "public", "static", "String", "escape", "(", "@", "NotNull", "String", "str", ",", "boolean", "escapeUnicode", ")", "{", "str", "=", "str", ".", "replace", "(", "\"", "\\\\", "\"", ",", "\"", "\\\\", "\\\\", "\"", ")", ".", "replace", "(", "\"", "\\\"", "\"", ",", "\"", "\\\\", "\\\"", "\"", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "char", "c", ":", "str", ".", "toCharArray", "(", ")", ")", "{", "if", "(", "(", "(", "int", ")", "c", ")", ">", "127", "&&", "escapeUnicode", ")", "{", "sb", ".", "append", "(", "\"", "\\\\", "u", "\"", ")", ";", "sb", ".", "append", "(", "padLeft", "(", "Integer", ".", "toString", "(", "(", "int", ")", "c", ",", "16", ")", ".", "toUpperCase", "(", "Locale", ".", "ENGLISH", ")", ",", "4", ",", "'0'", ")", ")", ";", "}", "else", "if", "(", "ESCAPED", ".", "containsKey", "(", "c", ")", ")", "{", "sb", ".", "append", "(", "\"", "\\\\", "\"", ")", ";", "sb", ".", "append", "(", "ESCAPED", ".", "get", "(", "c", ")", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "c", ")", ";", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}", "public", "static", "String", "padLeft", "(", "@", "NotNull", "String", "str", ",", "int", "minChars", ",", "char", "padChar", ")", "{", "int", "newChars", "=", "minChars", "-", "str", ".", "length", "(", ")", ";", "if", "(", "newChars", "<=", "0", ")", "return", "str", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "newChars", ";", "i", "++", ")", "{", "sb", ".", "append", "(", "padChar", ")", ";", "}", "sb", ".", "append", "(", "str", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "/**\n * Escapes and wraps the given string in quotes if not all its characters are allowed by commands in an\n * unquoted string. If all characters are allowed, nothing is changed.\n *\n * @param str The string to check and, if needed, quote.\n *\n * @return The given string, quoted, only if it contains a character not allowed in an unquoted string. Otherwise,\n * the returned string is the same as the original.\n * */", "@", "NotNull", "public", "static", "String", "quoteIfNecessary", "(", "@", "NotNull", "String", "str", ")", "{", "return", "(", "needsQuoting", "(", "str", ")", ")", "?", "\"", "\\\"", "\"", "+", "escape", "(", "str", ")", "+", "\"", "\\\"", "\"", ":", "str", ";", "}", "/**\n * Escapes and wraps the given string in quotes if not all its characters are allowed by commands in an\n * unquoted string. If all characters are allowed, nothing is changed.\n *\n * @param str The string to check and, if needed, quote.\n *\n * @return The given string, quoted, only if it contains a character not allowed in an unquoted string. Otherwise,\n * the returned string is the same as the original.\n * */", "@", "NotNull", "public", "static", "String", "quoteIfNecessary", "(", "@", "NotNull", "String", "str", ",", "boolean", "escapeUnicode", ")", "{", "return", "(", "needsQuoting", "(", "str", ")", ")", "?", "\"", "\\\"", "\"", "+", "escape", "(", "str", ",", "escapeUnicode", ")", "+", "\"", "\\\"", "\"", ":", "str", ";", "}", "/**\n * Escapes and wraps the given string in quotes if not all its characters are allowed by commands in an\n * unquoted string. If all characters are allowed, nothing is changed.\n *\n * @param str The string to check and, if needed, quote.\n * @param featureKey The feature key from which to retrieve the regex.\n * @param defaultRegex The default regex to use, in case the featureKey is not found in the active feature map.\n *\n * @return The given string, quoted, only if it contains a character not allowed in an unquoted string. Otherwise,\n * the returned string is the same as the original.\n * */", "@", "NotNull", "public", "static", "String", "quoteIfNecessary", "(", "@", "NotNull", "String", "str", ",", "@", "NotNull", "String", "featureKey", ",", "String", "defaultRegex", ")", "{", "return", "(", "needsQuoting", "(", "str", ",", "featureKey", ",", "defaultRegex", ")", ")", "?", "\"", "\\\"", "\"", "+", "escape", "(", "str", ")", "+", "\"", "\\\"", "\"", ":", "str", ";", "}", "/**\n * Escapes and wraps the given string in quotes if not all its characters are allowed by commands in an\n * unquoted string. If all characters are allowed, nothing is changed.\n *\n * @param str The string to check and, if needed, quote.\n * @param featureKey0 The feature key from which to retrieve the regex.\n * @param featureKey1 The backup feature key from which to retrieve the regex, if featureKey1 was not found.\n * @param defaultRegex The default regex to use, in case neither featureKey0 nor featureKey1 is not found in the active feature map.\n *\n * @return The given string, quoted, only if it contains a character not allowed in an unquoted string. Otherwise,\n * the returned string is the same as the original.\n * */", "@", "NotNull", "public", "static", "String", "quoteIfNecessary", "(", "@", "NotNull", "String", "str", ",", "@", "NotNull", "String", "featureKey0", ",", "@", "NotNull", "String", "featureKey1", ",", "String", "defaultRegex", ")", "{", "return", "(", "needsQuoting", "(", "str", ",", "featureKey0", ",", "featureKey1", ",", "defaultRegex", ")", ")", "?", "\"", "\\\"", "\"", "+", "escape", "(", "str", ")", "+", "\"", "\\\"", "\"", ":", "str", ";", "}", "/**\n * Returns whether this character contains any characters disallowed in unquoted strings.\n *\n * @param str The string whose need for quotation is to be tested.\n *\n * @return <code>true</code> if this character contains any characters, disallowed in unquoted strings,\n * <code>false</code> if all characters are allowed in unquoted strings.\n * */", "public", "static", "boolean", "needsQuoting", "(", "@", "NotNull", "String", "str", ")", "{", "return", "needsQuoting", "(", "str", ",", "\"", "identifiers.regex", "\"", ",", "CommandUtils", ".", "IDENTIFIER_ALLOWED", ")", ";", "}", "/**\n * Returns whether this character contains any characters disallowed in unquoted strings.\n *\n * @param str The string whose need for quotation is to be tested.\n * @param featureKey The feature key from which to retrieve the regex.\n * @param defaultRegex The default regex to use, in case the featureKey is not found in the active feature map.\n *\n * @return <code>true</code> if this character contains any characters, disallowed in unquoted strings,\n * <code>false</code> if all characters are allowed in unquoted strings.\n * */", "public", "static", "boolean", "needsQuoting", "(", "@", "NotNull", "String", "str", ",", "@", "NotNull", "String", "featureKey", ",", "String", "defaultRegex", ")", "{", "return", "!", "str", ".", "matches", "(", "VersionFeatureManager", ".", "getString", "(", "featureKey", ",", "defaultRegex", ")", ")", ";", "}", "/**\n * Returns whether this character contains any characters disallowed in unquoted strings.\n *\n * @param str The string whose need for quotation is to be tested.\n * @param featureKey0 The feature key from which to retrieve the regex.\n * @param featureKey1 The backup feature key from which to retrieve the regex, if featureKey1 was not found.\n * @param defaultRegex The default regex to use, in case neither featureKey0 nor featureKey1 is not found in the active feature map.\n *\n * @return <code>true</code> if this character contains any characters, disallowed in unquoted strings,\n * <code>false</code> if all characters are allowed in unquoted strings.\n * */", "public", "static", "boolean", "needsQuoting", "(", "@", "NotNull", "String", "str", ",", "@", "NotNull", "String", "featureKey0", ",", "@", "NotNull", "String", "featureKey1", ",", "String", "defaultRegex", ")", "{", "return", "!", "str", ".", "matches", "(", "VersionFeatureManager", ".", "getString", "(", "featureKey0", ",", "VersionFeatureManager", ".", "getString", "(", "featureKey1", ",", "defaultRegex", ")", ")", ")", ";", "}", "/**\n * Converts the given number into its plain string representation. This method differs from\n * {@link Double#toString()} on two aspects:\n *\n * <ol>\n * <li>Whole numbers will be displayed without the decimal places.</li>\n * <li>Scientific notation will not be used for big nor small numbers.</li>\n * </ol>\n *\n * @param num The number to turn into a plain number string.\n *\n * @return The number, as a plain number string.\n * */", "@", "NotNull", "public", "static", "String", "numberToPlainString", "(", "double", "num", ")", "{", "DecimalFormat", "df", "=", "new", "DecimalFormat", "(", "\"", "0", "\"", ",", "DecimalFormatSymbols", ".", "getInstance", "(", "Locale", ".", "ENGLISH", ")", ")", ";", "df", ".", "setMaximumFractionDigits", "(", "340", ")", ";", "return", "df", ".", "format", "(", "num", ")", ";", "}", "/**\n * Converts the given number into its plain string representation. This method differs from\n * {@link Double#toString()} on two aspects:\n *\n * <ol>\n * <li>Whole numbers will be displayed without the decimal places.</li>\n * <li>Scientific notation will not be used for big nor small numbers.</li>\n * </ol>\n *\n * @param num The number to turn into a plain number string.\n *\n * @return The number, as a plain number string.\n * */", "@", "NotNull", "public", "static", "String", "numberToPlainString", "(", "Number", "num", ")", "{", "DecimalFormat", "df", "=", "new", "DecimalFormat", "(", "\"", "0", "\"", ",", "DecimalFormatSymbols", ".", "getInstance", "(", "Locale", ".", "ENGLISH", ")", ")", ";", "df", ".", "setMaximumFractionDigits", "(", "340", ")", ";", "return", "df", ".", "format", "(", "num", ")", ";", "}", "/**\n * Converts the given number into its plain string representation. This method differs from\n * {@link Double#toString()} in that scientific notation will not be used.\n *\n * @param num The number to turn into a non-scientific number string.\n *\n * @return The number, as a non-scientific number string.\n * */", "@", "NotNull", "public", "static", "String", "numberToStringNoScientific", "(", "double", "num", ")", "{", "DecimalFormat", "df", "=", "new", "DecimalFormat", "(", "\"", "0.0", "\"", ",", "DecimalFormatSymbols", ".", "getInstance", "(", "Locale", ".", "ENGLISH", ")", ")", ";", "df", ".", "setMaximumFractionDigits", "(", "340", ")", ";", "return", "df", ".", "format", "(", "num", ")", ";", "}", "@", "NotNull", "public", "static", "JsonElement", "constructRange", "(", "@", "Nullable", "Integer", "min", ",", "@", "Nullable", "Integer", "max", ")", "{", "if", "(", "min", "!=", "null", "&&", "min", ".", "equals", "(", "max", ")", ")", "return", "new", "JsonPrimitive", "(", "min", ")", ";", "else", "{", "JsonObject", "range", "=", "new", "JsonObject", "(", ")", ";", "if", "(", "min", "!=", "null", ")", "range", ".", "addProperty", "(", "\"", "min", "\"", ",", "min", ")", ";", "if", "(", "max", "!=", "null", ")", "range", ".", "addProperty", "(", "\"", "max", "\"", ",", "max", ")", ";", "return", "range", ";", "}", "}", "@", "NotNull", "public", "static", "JsonElement", "constructRange", "(", "@", "Nullable", "Double", "min", ",", "@", "Nullable", "Double", "max", ")", "{", "if", "(", "min", "!=", "null", "&&", "min", ".", "equals", "(", "max", ")", ")", "return", "new", "JsonPrimitive", "(", "min", ")", ";", "else", "{", "JsonObject", "range", "=", "new", "JsonObject", "(", ")", ";", "if", "(", "min", "!=", "null", ")", "range", ".", "addProperty", "(", "\"", "min", "\"", ",", "min", ")", ";", "if", "(", "max", "!=", "null", ")", "range", ".", "addProperty", "(", "\"", "max", "\"", ",", "max", ")", ";", "return", "range", ";", "}", "}", "@", "NotNull", "public", "static", "String", "parseQuotedString", "(", "@", "NotNull", "String", "text", ")", "{", "int", "index", "=", "0", ";", "char", "delimiter", "=", "text", ".", "charAt", "(", "index", ")", ";", "if", "(", "delimiter", "!=", "'\"'", "&&", "delimiter", "!=", "'\\''", ")", "throw", "new", "CommodoreException", "(", "CommodoreException", ".", "Source", ".", "FORMAT_ERROR", ",", "\"", "Expected string at index ", "\"", "+", "index", ",", "text", ")", ";", "index", "++", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "boolean", "escaped", "=", "false", ";", "boolean", "terminated", "=", "false", ";", "for", "(", ";", "index", "<", "text", ".", "length", "(", ")", ";", "index", "++", ")", "{", "char", "c", "=", "text", ".", "charAt", "(", "index", ")", ";", "if", "(", "!", "escaped", ")", "{", "if", "(", "c", "==", "'\\\\'", ")", "{", "escaped", "=", "true", ";", "continue", ";", "}", "else", "if", "(", "c", "==", "delimiter", ")", "{", "terminated", "=", "true", ";", "break", ";", "}", "}", "else", "{", "escaped", "=", "false", ";", "boolean", "unicodeSequence", "=", "false", ";", "switch", "(", "c", ")", "{", "case", "'0'", ":", "c", "=", "'\\0'", ";", "break", ";", "case", "'b'", ":", "c", "=", "'\\b'", ";", "break", ";", "case", "'f'", ":", "c", "=", "'\\f'", ";", "break", ";", "case", "'n'", ":", "c", "=", "'\\n'", ";", "break", ";", "case", "'r'", ":", "c", "=", "'\\r'", ";", "break", ";", "case", "'t'", ":", "c", "=", "'\\t'", ";", "break", ";", "case", "'\\\\'", ":", "break", ";", "case", "'\\''", ":", "break", ";", "case", "'\\\"'", ":", "break", ";", "case", "'u'", ":", "unicodeSequence", "=", "true", ";", "break", ";", "default", ":", "throw", "new", "CommodoreException", "(", "CommodoreException", ".", "Source", ".", "FORMAT_ERROR", ",", "\"", "Illegal escape sequence", "\"", ",", "text", ")", ";", "}", "if", "(", "unicodeSequence", ")", "{", "int", "sequenceLength", "=", "4", ";", "if", "(", "index", "+", "sequenceLength", "+", "1", ">", "text", ".", "length", "(", ")", ")", "throw", "new", "CommodoreException", "(", "CommodoreException", ".", "Source", ".", "FORMAT_ERROR", ",", "\"", "Unexpected end of unicode escape sequence", "\"", ",", "text", ")", ";", "String", "sequence", "=", "text", ".", "substring", "(", "index", "+", "1", ",", "index", "+", "1", "+", "sequenceLength", ")", ";", "int", "code", ";", "try", "{", "code", "=", "Integer", ".", "parseInt", "(", "sequence", ",", "16", ")", ";", "}", "catch", "(", "NumberFormatException", "x", ")", "{", "throw", "new", "CommodoreException", "(", "CommodoreException", ".", "Source", ".", "FORMAT_ERROR", ",", "\"", "Illegal unicode escape sequence", "\"", ",", "text", ")", ";", "}", "String", "unicode", "=", "new", "String", "(", "Character", ".", "toChars", "(", "code", ")", ")", ";", "sb", ".", "append", "(", "unicode", ")", ";", "index", "+=", "sequenceLength", ";", "continue", ";", "}", "}", "sb", ".", "append", "(", "c", ")", ";", "}", "if", "(", "!", "terminated", ")", "throw", "new", "CommodoreException", "(", "CommodoreException", ".", "Source", ".", "FORMAT_ERROR", ",", "\"", "Unexpected end of input", "\"", ",", "text", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "/**\n * CommandUtils should not be instantiated.\n * */", "private", "CommandUtils", "(", ")", "{", "}", "public", "static", "String", "quote", "(", "String", "str", ")", "{", "return", "quote", "(", "str", ",", "true", ")", ";", "}", "public", "static", "String", "quote", "(", "String", "str", ",", "boolean", "escapeUnicode", ")", "{", "return", "\"", "\\\"", "\"", "+", "escape", "(", "str", ",", "escapeUnicode", ")", "+", "\"", "\\\"", "\"", ";", "}", "}" ]
Class containing a series of utility methods and constants for common use in commands.
[ "Class", "containing", "a", "series", "of", "utility", "methods", "and", "constants", "for", "common", "use", "in", "commands", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c4304b477f05f41e0dbe0c9eaa5253e2dfa12972
Mahmoud-Khaled-Nasr/CrawlerMan
src/main/java/util/PathGenerator.java
[ "Apache-2.0" ]
Java
PathGenerator
/** * A class that manage paths, names, etc. of the used files in the filesystem. */
A class that manage paths, names, etc. of the used files in the filesystem.
[ "A", "class", "that", "manage", "paths", "names", "etc", ".", "of", "the", "used", "files", "in", "the", "filesystem", "." ]
public class PathGenerator { private static final String OUTPUT_DIR = "output_data"; /** * Generates a path representing a valid path to the file indicated. * @param fileName The name of the file needed, preceded with parent directories if needed * @return A valid path to the file * @throws IOException If an IO error occurred */ public static Path generate (String... fileName) throws IOException { Path path = Paths.get(OUTPUT_DIR, fileName); Files.createDirectories(path.getParent()); return path; } }
[ "public", "class", "PathGenerator", "{", "private", "static", "final", "String", "OUTPUT_DIR", "=", "\"", "output_data", "\"", ";", "/**\n * Generates a path representing a valid path to the file indicated.\n * @param fileName The name of the file needed, preceded with parent directories if needed\n * @return A valid path to the file\n * @throws IOException If an IO error occurred\n */", "public", "static", "Path", "generate", "(", "String", "...", "fileName", ")", "throws", "IOException", "{", "Path", "path", "=", "Paths", ".", "get", "(", "OUTPUT_DIR", ",", "fileName", ")", ";", "Files", ".", "createDirectories", "(", "path", ".", "getParent", "(", ")", ")", ";", "return", "path", ";", "}", "}" ]
A class that manage paths, names, etc.
[ "A", "class", "that", "manage", "paths", "names", "etc", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c43362bbba8042773f4da2fa4887742145eae1ca
madrob/solr
solr/core/src/java/org/apache/solr/servlet/RequestRateLimiter.java
[ "Apache-2.0" ]
Java
RequestRateLimiter
/** * Handles rate limiting for a specific request type. * * The control flow is as follows: * Handle request -- Check if slot is available -- If available, acquire slot and proceed -- * else reject the same. */
Handles rate limiting for a specific request type. The control flow is as follows: Handle request -- Check if slot is available -- If available, acquire slot and proceed else reject the same.
[ "Handles", "rate", "limiting", "for", "a", "specific", "request", "type", ".", "The", "control", "flow", "is", "as", "follows", ":", "Handle", "request", "--", "Check", "if", "slot", "is", "available", "--", "If", "available", "acquire", "slot", "and", "proceed", "else", "reject", "the", "same", "." ]
@SolrThreadSafe public class RequestRateLimiter { // Slots that are guaranteed for this request rate limiter. private final Semaphore guaranteedSlotsPool; // Competitive slots pool that are available for this rate limiter as well as borrowing by other request rate limiters. // By competitive, the meaning is that there is no prioritization for the acquisition of these slots -- First Come First Serve, // irrespective of whether the request is of this request rate limiter or other. private final Semaphore borrowableSlotsPool; private final RateLimiterConfig rateLimiterConfig; private final SlotMetadata guaranteedSlotMetadata; private final SlotMetadata borrowedSlotMetadata; private static final SlotMetadata nullSlotMetadata = new SlotMetadata(null); public RequestRateLimiter(RateLimiterConfig rateLimiterConfig) { this.rateLimiterConfig = rateLimiterConfig; this.guaranteedSlotsPool = new Semaphore(rateLimiterConfig.guaranteedSlotsThreshold); this.borrowableSlotsPool = new Semaphore(rateLimiterConfig.allowedRequests - rateLimiterConfig.guaranteedSlotsThreshold); this.guaranteedSlotMetadata = new SlotMetadata(guaranteedSlotsPool); this.borrowedSlotMetadata = new SlotMetadata(borrowableSlotsPool); } /** * Handles an incoming request. returns a metadata object representing the metadata for the acquired slot, if acquired. * If a slot is not acquired, returns a null metadata object. * */ public SlotMetadata handleRequest() throws InterruptedException { if (!rateLimiterConfig.isEnabled) { return nullSlotMetadata; } if (guaranteedSlotsPool.tryAcquire(rateLimiterConfig.waitForSlotAcquisition, TimeUnit.MILLISECONDS)) { return guaranteedSlotMetadata; } if (borrowableSlotsPool.tryAcquire(rateLimiterConfig.waitForSlotAcquisition, TimeUnit.MILLISECONDS)) { return borrowedSlotMetadata; } return null; } /** * Whether to allow another request type to borrow a slot from this request rate limiter. Typically works fine * if there is a relatively lesser load on this request rate limiter's type compared to the others (think of skew). * @return returns a metadata object for the acquired slot, if acquired. If the * slot was not acquired, returns a metadata object with a null pool. * * @lucene.experimental -- Can cause slots to be blocked if a request borrows a slot and is itself long lived. */ public SlotMetadata allowSlotBorrowing() throws InterruptedException { if (borrowableSlotsPool.tryAcquire(rateLimiterConfig.waitForSlotAcquisition, TimeUnit.MILLISECONDS)) { return borrowedSlotMetadata; } return nullSlotMetadata; } public RateLimiterConfig getRateLimiterConfig() { return rateLimiterConfig; } // Represents the metadata for a slot static class SlotMetadata { private final Semaphore usedPool; public SlotMetadata(Semaphore usedPool) { this.usedPool = usedPool; } public void decrementRequest() { if (usedPool != null) { usedPool.release(); } } public boolean isReleasable() { return usedPool != null; } } }
[ "@", "SolrThreadSafe", "public", "class", "RequestRateLimiter", "{", "private", "final", "Semaphore", "guaranteedSlotsPool", ";", "private", "final", "Semaphore", "borrowableSlotsPool", ";", "private", "final", "RateLimiterConfig", "rateLimiterConfig", ";", "private", "final", "SlotMetadata", "guaranteedSlotMetadata", ";", "private", "final", "SlotMetadata", "borrowedSlotMetadata", ";", "private", "static", "final", "SlotMetadata", "nullSlotMetadata", "=", "new", "SlotMetadata", "(", "null", ")", ";", "public", "RequestRateLimiter", "(", "RateLimiterConfig", "rateLimiterConfig", ")", "{", "this", ".", "rateLimiterConfig", "=", "rateLimiterConfig", ";", "this", ".", "guaranteedSlotsPool", "=", "new", "Semaphore", "(", "rateLimiterConfig", ".", "guaranteedSlotsThreshold", ")", ";", "this", ".", "borrowableSlotsPool", "=", "new", "Semaphore", "(", "rateLimiterConfig", ".", "allowedRequests", "-", "rateLimiterConfig", ".", "guaranteedSlotsThreshold", ")", ";", "this", ".", "guaranteedSlotMetadata", "=", "new", "SlotMetadata", "(", "guaranteedSlotsPool", ")", ";", "this", ".", "borrowedSlotMetadata", "=", "new", "SlotMetadata", "(", "borrowableSlotsPool", ")", ";", "}", "/**\n * Handles an incoming request. returns a metadata object representing the metadata for the acquired slot, if acquired.\n * If a slot is not acquired, returns a null metadata object.\n * */", "public", "SlotMetadata", "handleRequest", "(", ")", "throws", "InterruptedException", "{", "if", "(", "!", "rateLimiterConfig", ".", "isEnabled", ")", "{", "return", "nullSlotMetadata", ";", "}", "if", "(", "guaranteedSlotsPool", ".", "tryAcquire", "(", "rateLimiterConfig", ".", "waitForSlotAcquisition", ",", "TimeUnit", ".", "MILLISECONDS", ")", ")", "{", "return", "guaranteedSlotMetadata", ";", "}", "if", "(", "borrowableSlotsPool", ".", "tryAcquire", "(", "rateLimiterConfig", ".", "waitForSlotAcquisition", ",", "TimeUnit", ".", "MILLISECONDS", ")", ")", "{", "return", "borrowedSlotMetadata", ";", "}", "return", "null", ";", "}", "/**\n * Whether to allow another request type to borrow a slot from this request rate limiter. Typically works fine\n * if there is a relatively lesser load on this request rate limiter's type compared to the others (think of skew).\n * @return returns a metadata object for the acquired slot, if acquired. If the\n * slot was not acquired, returns a metadata object with a null pool.\n *\n * @lucene.experimental -- Can cause slots to be blocked if a request borrows a slot and is itself long lived.\n */", "public", "SlotMetadata", "allowSlotBorrowing", "(", ")", "throws", "InterruptedException", "{", "if", "(", "borrowableSlotsPool", ".", "tryAcquire", "(", "rateLimiterConfig", ".", "waitForSlotAcquisition", ",", "TimeUnit", ".", "MILLISECONDS", ")", ")", "{", "return", "borrowedSlotMetadata", ";", "}", "return", "nullSlotMetadata", ";", "}", "public", "RateLimiterConfig", "getRateLimiterConfig", "(", ")", "{", "return", "rateLimiterConfig", ";", "}", "static", "class", "SlotMetadata", "{", "private", "final", "Semaphore", "usedPool", ";", "public", "SlotMetadata", "(", "Semaphore", "usedPool", ")", "{", "this", ".", "usedPool", "=", "usedPool", ";", "}", "public", "void", "decrementRequest", "(", ")", "{", "if", "(", "usedPool", "!=", "null", ")", "{", "usedPool", ".", "release", "(", ")", ";", "}", "}", "public", "boolean", "isReleasable", "(", ")", "{", "return", "usedPool", "!=", "null", ";", "}", "}", "}" ]
Handles rate limiting for a specific request type.
[ "Handles", "rate", "limiting", "for", "a", "specific", "request", "type", "." ]
[ "// Slots that are guaranteed for this request rate limiter.", "// Competitive slots pool that are available for this rate limiter as well as borrowing by other request rate limiters.", "// By competitive, the meaning is that there is no prioritization for the acquisition of these slots -- First Come First Serve,", "// irrespective of whether the request is of this request rate limiter or other.", "// Represents the metadata for a slot" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c43362bbba8042773f4da2fa4887742145eae1ca
madrob/solr
solr/core/src/java/org/apache/solr/servlet/RequestRateLimiter.java
[ "Apache-2.0" ]
Java
SlotMetadata
// Represents the metadata for a slot
Represents the metadata for a slot
[ "Represents", "the", "metadata", "for", "a", "slot" ]
static class SlotMetadata { private final Semaphore usedPool; public SlotMetadata(Semaphore usedPool) { this.usedPool = usedPool; } public void decrementRequest() { if (usedPool != null) { usedPool.release(); } } public boolean isReleasable() { return usedPool != null; } }
[ "static", "class", "SlotMetadata", "{", "private", "final", "Semaphore", "usedPool", ";", "public", "SlotMetadata", "(", "Semaphore", "usedPool", ")", "{", "this", ".", "usedPool", "=", "usedPool", ";", "}", "public", "void", "decrementRequest", "(", ")", "{", "if", "(", "usedPool", "!=", "null", ")", "{", "usedPool", ".", "release", "(", ")", ";", "}", "}", "public", "boolean", "isReleasable", "(", ")", "{", "return", "usedPool", "!=", "null", ";", "}", "}" ]
Represents the metadata for a slot
[ "Represents", "the", "metadata", "for", "a", "slot" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c438bceb495d315f7df20faec51c4bd6d0950129
atianxia/cas-study
support/cas-server-support-oauth-core/src/main/java/org/apereo/cas/ticket/refreshtoken/RefreshTokenImpl.java
[ "Apache-2.0" ]
Java
RefreshTokenImpl
/** * An OAuth refresh token implementation. * * @author Jerome Leleu * @since 5.0.0 */
An OAuth refresh token implementation. @author Jerome Leleu @since 5.0.0
[ "An", "OAuth", "refresh", "token", "implementation", ".", "@author", "Jerome", "Leleu", "@since", "5", ".", "0", ".", "0" ]
@Entity @DiscriminatorValue(RefreshToken.PREFIX) public class RefreshTokenImpl extends OAuthCodeImpl implements RefreshToken { private static final long serialVersionUID = -3544459978950667758L; /** * Instantiates a new OAuth refresh token. */ public RefreshTokenImpl() { // exists for JPA purposes } /** * Constructs a new refresh token with unique id for a service and authentication. * * @param id the unique identifier for the ticket. * @param service the service this ticket is for. * @param authentication the authentication. * @param expirationPolicy the expiration policy. * @throws IllegalArgumentException if the service or authentication are null. */ public RefreshTokenImpl(final String id, final Service service, final Authentication authentication, final ExpirationPolicy expirationPolicy) { super(id, service, authentication, expirationPolicy); } }
[ "@", "Entity", "@", "DiscriminatorValue", "(", "RefreshToken", ".", "PREFIX", ")", "public", "class", "RefreshTokenImpl", "extends", "OAuthCodeImpl", "implements", "RefreshToken", "{", "private", "static", "final", "long", "serialVersionUID", "=", "-", "3544459978950667758L", ";", "/**\n * Instantiates a new OAuth refresh token.\n */", "public", "RefreshTokenImpl", "(", ")", "{", "}", "/**\n * Constructs a new refresh token with unique id for a service and authentication.\n *\n * @param id the unique identifier for the ticket.\n * @param service the service this ticket is for.\n * @param authentication the authentication.\n * @param expirationPolicy the expiration policy.\n * @throws IllegalArgumentException if the service or authentication are null.\n */", "public", "RefreshTokenImpl", "(", "final", "String", "id", ",", "final", "Service", "service", ",", "final", "Authentication", "authentication", ",", "final", "ExpirationPolicy", "expirationPolicy", ")", "{", "super", "(", "id", ",", "service", ",", "authentication", ",", "expirationPolicy", ")", ";", "}", "}" ]
An OAuth refresh token implementation.
[ "An", "OAuth", "refresh", "token", "implementation", "." ]
[ "// exists for JPA purposes" ]
[ { "param": "OAuthCodeImpl", "type": null }, { "param": "RefreshToken", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "OAuthCodeImpl", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "RefreshToken", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c43a07be426fb1bcb82f64bfd8c8e08e5debe9e8
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslvserver_sslcertkey_binding.java
[ "Apache-2.0" ]
Java
sslvserver_sslcertkey_binding
/** * Binding class showing the sslcertkey that can be bound to sslvserver. */
Binding class showing the sslcertkey that can be bound to sslvserver.
[ "Binding", "class", "showing", "the", "sslcertkey", "that", "can", "be", "bound", "to", "sslvserver", "." ]
public class sslvserver_sslcertkey_binding extends base_resource { private String certkeyname; private String crlcheck; private String ocspcheck; private Integer cleartextport; private Boolean ca; private Boolean snicert; private Boolean skipcaname; private String vservername; private Long __count; /** * <pre> * The name of the certificate key pair binding. * </pre> */ public void set_certkeyname(String certkeyname) throws Exception{ this.certkeyname = certkeyname; } /** * <pre> * The name of the certificate key pair binding. * </pre> */ public String get_certkeyname() throws Exception { return this.certkeyname; } /** * <pre> * The flag is used to indicate whether this particular CA certificate's CA_Name needs to be sent to the SSL client while requesting for client certificate in a SSL handshake. * </pre> */ public void set_skipcaname(boolean skipcaname) throws Exception { this.skipcaname = new Boolean(skipcaname); } /** * <pre> * The flag is used to indicate whether this particular CA certificate's CA_Name needs to be sent to the SSL client while requesting for client certificate in a SSL handshake. * </pre> */ public void set_skipcaname(Boolean skipcaname) throws Exception{ this.skipcaname = skipcaname; } /** * <pre> * The flag is used to indicate whether this particular CA certificate's CA_Name needs to be sent to the SSL client while requesting for client certificate in a SSL handshake. * </pre> */ public Boolean get_skipcaname() throws Exception { return this.skipcaname; } /** * <pre> * The name of the CertKey. Use this option to bind Certkey(s) which will be used in SNI processing. * </pre> */ public void set_snicert(boolean snicert) throws Exception { this.snicert = new Boolean(snicert); } /** * <pre> * The name of the CertKey. Use this option to bind Certkey(s) which will be used in SNI processing. * </pre> */ public void set_snicert(Boolean snicert) throws Exception{ this.snicert = snicert; } /** * <pre> * The name of the CertKey. Use this option to bind Certkey(s) which will be used in SNI processing. * </pre> */ public Boolean get_snicert() throws Exception { return this.snicert; } /** * <pre> * The state of the OCSP check parameter. (Mandatory/Optional).<br> Possible values = Mandatory, Optional * </pre> */ public void set_ocspcheck(String ocspcheck) throws Exception{ this.ocspcheck = ocspcheck; } /** * <pre> * The state of the OCSP check parameter. (Mandatory/Optional).<br> Possible values = Mandatory, Optional * </pre> */ public String get_ocspcheck() throws Exception { return this.ocspcheck; } /** * <pre> * CA certificate. * </pre> */ public void set_ca(boolean ca) throws Exception { this.ca = new Boolean(ca); } /** * <pre> * CA certificate. * </pre> */ public void set_ca(Boolean ca) throws Exception{ this.ca = ca; } /** * <pre> * CA certificate. * </pre> */ public Boolean get_ca() throws Exception { return this.ca; } /** * <pre> * The state of the CRL check parameter. (Mandatory/Optional).<br> Possible values = Mandatory, Optional * </pre> */ public void set_crlcheck(String crlcheck) throws Exception{ this.crlcheck = crlcheck; } /** * <pre> * The state of the CRL check parameter. (Mandatory/Optional).<br> Possible values = Mandatory, Optional * </pre> */ public String get_crlcheck() throws Exception { return this.crlcheck; } /** * <pre> * Name of the SSL virtual server.<br> Minimum length = 1 * </pre> */ public void set_vservername(String vservername) throws Exception{ this.vservername = vservername; } /** * <pre> * Name of the SSL virtual server.<br> Minimum length = 1 * </pre> */ public String get_vservername() throws Exception { return this.vservername; } /** * <pre> * Port on which clear-text data is sent by the appliance to the server. Do not specify this parameter for SSL offloading with end-to-end encryption. * </pre> */ public Integer get_cleartextport() throws Exception { return this.cleartextport; } /** * <pre> * converts nitro response into object and returns the object array in case of get request. * </pre> */ protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception{ sslvserver_sslcertkey_binding_response result = (sslvserver_sslcertkey_binding_response) service.get_payload_formatter().string_to_resource(sslvserver_sslcertkey_binding_response.class, response); if(result.errorcode != 0) { if (result.errorcode == 444) { service.clear_session(); } if(result.severity != null) { if (result.severity.equals("ERROR")) throw new nitro_exception(result.message,result.errorcode); } else { throw new nitro_exception(result.message,result.errorcode); } } return result.sslvserver_sslcertkey_binding; } /** * <pre> * Returns the value of object identifier argument * </pre> */ protected String get_object_name() { return this.vservername; } public static base_response add(nitro_service client, sslvserver_sslcertkey_binding resource) throws Exception { sslvserver_sslcertkey_binding updateresource = new sslvserver_sslcertkey_binding(); updateresource.vservername = resource.vservername; updateresource.certkeyname = resource.certkeyname; updateresource.ca = resource.ca; updateresource.crlcheck = resource.crlcheck; updateresource.skipcaname = resource.skipcaname; updateresource.snicert = resource.snicert; updateresource.ocspcheck = resource.ocspcheck; return updateresource.update_resource(client); } public static base_responses add(nitro_service client, sslvserver_sslcertkey_binding resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { sslvserver_sslcertkey_binding updateresources[] = new sslvserver_sslcertkey_binding[resources.length]; for (int i=0;i<resources.length;i++){ updateresources[i] = new sslvserver_sslcertkey_binding(); updateresources[i].vservername = resources[i].vservername; updateresources[i].certkeyname = resources[i].certkeyname; updateresources[i].ca = resources[i].ca; updateresources[i].crlcheck = resources[i].crlcheck; updateresources[i].skipcaname = resources[i].skipcaname; updateresources[i].snicert = resources[i].snicert; updateresources[i].ocspcheck = resources[i].ocspcheck; } result = update_bulk_request(client, updateresources); } return result; } public static base_response delete(nitro_service client, sslvserver_sslcertkey_binding resource) throws Exception { sslvserver_sslcertkey_binding deleteresource = new sslvserver_sslcertkey_binding(); deleteresource.vservername = resource.vservername; deleteresource.certkeyname = resource.certkeyname; deleteresource.ca = resource.ca; deleteresource.crlcheck = resource.crlcheck; deleteresource.snicert = resource.snicert; deleteresource.ocspcheck = resource.ocspcheck; return deleteresource.delete_resource(client); } public static base_responses delete(nitro_service client, sslvserver_sslcertkey_binding resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { sslvserver_sslcertkey_binding deleteresources[] = new sslvserver_sslcertkey_binding[resources.length]; for (int i=0;i<resources.length;i++){ deleteresources[i] = new sslvserver_sslcertkey_binding(); deleteresources[i].vservername = resources[i].vservername; deleteresources[i].certkeyname = resources[i].certkeyname; deleteresources[i].ca = resources[i].ca; deleteresources[i].crlcheck = resources[i].crlcheck; deleteresources[i].snicert = resources[i].snicert; deleteresources[i].ocspcheck = resources[i].ocspcheck; } result = delete_bulk_request(client, deleteresources); } return result; } /** * Use this API to fetch sslvserver_sslcertkey_binding resources of given name . */ public static sslvserver_sslcertkey_binding[] get(nitro_service service, String vservername) throws Exception{ sslvserver_sslcertkey_binding obj = new sslvserver_sslcertkey_binding(); obj.set_vservername(vservername); sslvserver_sslcertkey_binding response[] = (sslvserver_sslcertkey_binding[]) obj.get_resources(service); return response; } /** * Use this API to fetch filtered set of sslvserver_sslcertkey_binding resources. * filter string should be in JSON format.eg: "port:80,servicetype:HTTP". */ public static sslvserver_sslcertkey_binding[] get_filtered(nitro_service service, String vservername, String filter) throws Exception{ sslvserver_sslcertkey_binding obj = new sslvserver_sslcertkey_binding(); obj.set_vservername(vservername); options option = new options(); option.set_filter(filter); sslvserver_sslcertkey_binding[] response = (sslvserver_sslcertkey_binding[]) obj.getfiltered(service, option); return response; } /** * Use this API to fetch filtered set of sslvserver_sslcertkey_binding resources. * set the filter parameter values in filtervalue object. */ public static sslvserver_sslcertkey_binding[] get_filtered(nitro_service service, String vservername, filtervalue[] filter) throws Exception{ sslvserver_sslcertkey_binding obj = new sslvserver_sslcertkey_binding(); obj.set_vservername(vservername); options option = new options(); option.set_filter(filter); sslvserver_sslcertkey_binding[] response = (sslvserver_sslcertkey_binding[]) obj.getfiltered(service, option); return response; } /** * Use this API to count sslvserver_sslcertkey_binding resources configued on NetScaler. */ public static long count(nitro_service service, String vservername) throws Exception{ sslvserver_sslcertkey_binding obj = new sslvserver_sslcertkey_binding(); obj.set_vservername(vservername); options option = new options(); option.set_count(true); sslvserver_sslcertkey_binding response[] = (sslvserver_sslcertkey_binding[]) obj.get_resources(service,option); if (response != null) { return response[0].__count; } return 0; } /** * Use this API to count the filtered set of sslvserver_sslcertkey_binding resources. * filter string should be in JSON format.eg: "port:80,servicetype:HTTP". */ public static long count_filtered(nitro_service service, String vservername, String filter) throws Exception{ sslvserver_sslcertkey_binding obj = new sslvserver_sslcertkey_binding(); obj.set_vservername(vservername); options option = new options(); option.set_count(true); option.set_filter(filter); sslvserver_sslcertkey_binding[] response = (sslvserver_sslcertkey_binding[]) obj.getfiltered(service, option); if (response != null) { return response[0].__count; } return 0; } /** * Use this API to count the filtered set of sslvserver_sslcertkey_binding resources. * set the filter parameter values in filtervalue object. */ public static long count_filtered(nitro_service service, String vservername, filtervalue[] filter) throws Exception{ sslvserver_sslcertkey_binding obj = new sslvserver_sslcertkey_binding(); obj.set_vservername(vservername); options option = new options(); option.set_count(true); option.set_filter(filter); sslvserver_sslcertkey_binding[] response = (sslvserver_sslcertkey_binding[]) obj.getfiltered(service, option); if (response != null) { return response[0].__count; } return 0; } public static class ocspcheckEnum { public static final String Mandatory = "Mandatory"; public static final String Optional = "Optional"; } public static class crlcheckEnum { public static final String Mandatory = "Mandatory"; public static final String Optional = "Optional"; } public static class labeltypeEnum { public static final String vserver = "vserver"; public static final String service = "service"; public static final String policylabel = "policylabel"; } }
[ "public", "class", "sslvserver_sslcertkey_binding", "extends", "base_resource", "{", "private", "String", "certkeyname", ";", "private", "String", "crlcheck", ";", "private", "String", "ocspcheck", ";", "private", "Integer", "cleartextport", ";", "private", "Boolean", "ca", ";", "private", "Boolean", "snicert", ";", "private", "Boolean", "skipcaname", ";", "private", "String", "vservername", ";", "private", "Long", "__count", ";", "/**\n\t* <pre>\n\t* The name of the certificate key pair binding.\n\t* </pre>\n\t*/", "public", "void", "set_certkeyname", "(", "String", "certkeyname", ")", "throws", "Exception", "{", "this", ".", "certkeyname", "=", "certkeyname", ";", "}", "/**\n\t* <pre>\n\t* The name of the certificate key pair binding.\n\t* </pre>\n\t*/", "public", "String", "get_certkeyname", "(", ")", "throws", "Exception", "{", "return", "this", ".", "certkeyname", ";", "}", "/**\n\t* <pre>\n\t* The flag is used to indicate whether this particular CA certificate's CA_Name needs to be sent to the SSL client while requesting for client certificate in a SSL handshake.\n\t* </pre>\n\t*/", "public", "void", "set_skipcaname", "(", "boolean", "skipcaname", ")", "throws", "Exception", "{", "this", ".", "skipcaname", "=", "new", "Boolean", "(", "skipcaname", ")", ";", "}", "/**\n\t* <pre>\n\t* The flag is used to indicate whether this particular CA certificate's CA_Name needs to be sent to the SSL client while requesting for client certificate in a SSL handshake.\n\t* </pre>\n\t*/", "public", "void", "set_skipcaname", "(", "Boolean", "skipcaname", ")", "throws", "Exception", "{", "this", ".", "skipcaname", "=", "skipcaname", ";", "}", "/**\n\t* <pre>\n\t* The flag is used to indicate whether this particular CA certificate's CA_Name needs to be sent to the SSL client while requesting for client certificate in a SSL handshake.\n\t* </pre>\n\t*/", "public", "Boolean", "get_skipcaname", "(", ")", "throws", "Exception", "{", "return", "this", ".", "skipcaname", ";", "}", "/**\n\t* <pre>\n\t* The name of the CertKey. Use this option to bind Certkey(s) which will be used in SNI processing.\n\t* </pre>\n\t*/", "public", "void", "set_snicert", "(", "boolean", "snicert", ")", "throws", "Exception", "{", "this", ".", "snicert", "=", "new", "Boolean", "(", "snicert", ")", ";", "}", "/**\n\t* <pre>\n\t* The name of the CertKey. Use this option to bind Certkey(s) which will be used in SNI processing.\n\t* </pre>\n\t*/", "public", "void", "set_snicert", "(", "Boolean", "snicert", ")", "throws", "Exception", "{", "this", ".", "snicert", "=", "snicert", ";", "}", "/**\n\t* <pre>\n\t* The name of the CertKey. Use this option to bind Certkey(s) which will be used in SNI processing.\n\t* </pre>\n\t*/", "public", "Boolean", "get_snicert", "(", ")", "throws", "Exception", "{", "return", "this", ".", "snicert", ";", "}", "/**\n\t* <pre>\n\t* The state of the OCSP check parameter. (Mandatory/Optional).<br> Possible values = Mandatory, Optional\n\t* </pre>\n\t*/", "public", "void", "set_ocspcheck", "(", "String", "ocspcheck", ")", "throws", "Exception", "{", "this", ".", "ocspcheck", "=", "ocspcheck", ";", "}", "/**\n\t* <pre>\n\t* The state of the OCSP check parameter. (Mandatory/Optional).<br> Possible values = Mandatory, Optional\n\t* </pre>\n\t*/", "public", "String", "get_ocspcheck", "(", ")", "throws", "Exception", "{", "return", "this", ".", "ocspcheck", ";", "}", "/**\n\t* <pre>\n\t* CA certificate.\n\t* </pre>\n\t*/", "public", "void", "set_ca", "(", "boolean", "ca", ")", "throws", "Exception", "{", "this", ".", "ca", "=", "new", "Boolean", "(", "ca", ")", ";", "}", "/**\n\t* <pre>\n\t* CA certificate.\n\t* </pre>\n\t*/", "public", "void", "set_ca", "(", "Boolean", "ca", ")", "throws", "Exception", "{", "this", ".", "ca", "=", "ca", ";", "}", "/**\n\t* <pre>\n\t* CA certificate.\n\t* </pre>\n\t*/", "public", "Boolean", "get_ca", "(", ")", "throws", "Exception", "{", "return", "this", ".", "ca", ";", "}", "/**\n\t* <pre>\n\t* The state of the CRL check parameter. (Mandatory/Optional).<br> Possible values = Mandatory, Optional\n\t* </pre>\n\t*/", "public", "void", "set_crlcheck", "(", "String", "crlcheck", ")", "throws", "Exception", "{", "this", ".", "crlcheck", "=", "crlcheck", ";", "}", "/**\n\t* <pre>\n\t* The state of the CRL check parameter. (Mandatory/Optional).<br> Possible values = Mandatory, Optional\n\t* </pre>\n\t*/", "public", "String", "get_crlcheck", "(", ")", "throws", "Exception", "{", "return", "this", ".", "crlcheck", ";", "}", "/**\n\t* <pre>\n\t* Name of the SSL virtual server.<br> Minimum length = 1\n\t* </pre>\n\t*/", "public", "void", "set_vservername", "(", "String", "vservername", ")", "throws", "Exception", "{", "this", ".", "vservername", "=", "vservername", ";", "}", "/**\n\t* <pre>\n\t* Name of the SSL virtual server.<br> Minimum length = 1\n\t* </pre>\n\t*/", "public", "String", "get_vservername", "(", ")", "throws", "Exception", "{", "return", "this", ".", "vservername", ";", "}", "/**\n\t* <pre>\n\t* Port on which clear-text data is sent by the appliance to the server. Do not specify this parameter for SSL offloading with end-to-end encryption.\n\t* </pre>\n\t*/", "public", "Integer", "get_cleartextport", "(", ")", "throws", "Exception", "{", "return", "this", ".", "cleartextport", ";", "}", "/**\n\t* <pre>\n\t* converts nitro response into object and returns the object array in case of get request.\n\t* </pre>\n\t*/", "protected", "base_resource", "[", "]", "get_nitro_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "sslvserver_sslcertkey_binding_response", "result", "=", "(", "sslvserver_sslcertkey_binding_response", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "sslvserver_sslcertkey_binding_response", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "444", ")", "{", "service", ".", "clear_session", "(", ")", ";", "}", "if", "(", "result", ".", "severity", "!=", "null", ")", "{", "if", "(", "result", ".", "severity", ".", "equals", "(", "\"", "ERROR", "\"", ")", ")", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ")", ";", "}", "else", "{", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ")", ";", "}", "}", "return", "result", ".", "sslvserver_sslcertkey_binding", ";", "}", "/**\n\t* <pre>\n\t* Returns the value of object identifier argument\n\t* </pre>\n\t*/", "protected", "String", "get_object_name", "(", ")", "{", "return", "this", ".", "vservername", ";", "}", "public", "static", "base_response", "add", "(", "nitro_service", "client", ",", "sslvserver_sslcertkey_binding", "resource", ")", "throws", "Exception", "{", "sslvserver_sslcertkey_binding", "updateresource", "=", "new", "sslvserver_sslcertkey_binding", "(", ")", ";", "updateresource", ".", "vservername", "=", "resource", ".", "vservername", ";", "updateresource", ".", "certkeyname", "=", "resource", ".", "certkeyname", ";", "updateresource", ".", "ca", "=", "resource", ".", "ca", ";", "updateresource", ".", "crlcheck", "=", "resource", ".", "crlcheck", ";", "updateresource", ".", "skipcaname", "=", "resource", ".", "skipcaname", ";", "updateresource", ".", "snicert", "=", "resource", ".", "snicert", ";", "updateresource", ".", "ocspcheck", "=", "resource", ".", "ocspcheck", ";", "return", "updateresource", ".", "update_resource", "(", "client", ")", ";", "}", "public", "static", "base_responses", "add", "(", "nitro_service", "client", ",", "sslvserver_sslcertkey_binding", "resources", "[", "]", ")", "throws", "Exception", "{", "base_responses", "result", "=", "null", ";", "if", "(", "resources", "!=", "null", "&&", "resources", ".", "length", ">", "0", ")", "{", "sslvserver_sslcertkey_binding", "updateresources", "[", "]", "=", "new", "sslvserver_sslcertkey_binding", "[", "resources", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "resources", ".", "length", ";", "i", "++", ")", "{", "updateresources", "[", "i", "]", "=", "new", "sslvserver_sslcertkey_binding", "(", ")", ";", "updateresources", "[", "i", "]", ".", "vservername", "=", "resources", "[", "i", "]", ".", "vservername", ";", "updateresources", "[", "i", "]", ".", "certkeyname", "=", "resources", "[", "i", "]", ".", "certkeyname", ";", "updateresources", "[", "i", "]", ".", "ca", "=", "resources", "[", "i", "]", ".", "ca", ";", "updateresources", "[", "i", "]", ".", "crlcheck", "=", "resources", "[", "i", "]", ".", "crlcheck", ";", "updateresources", "[", "i", "]", ".", "skipcaname", "=", "resources", "[", "i", "]", ".", "skipcaname", ";", "updateresources", "[", "i", "]", ".", "snicert", "=", "resources", "[", "i", "]", ".", "snicert", ";", "updateresources", "[", "i", "]", ".", "ocspcheck", "=", "resources", "[", "i", "]", ".", "ocspcheck", ";", "}", "result", "=", "update_bulk_request", "(", "client", ",", "updateresources", ")", ";", "}", "return", "result", ";", "}", "public", "static", "base_response", "delete", "(", "nitro_service", "client", ",", "sslvserver_sslcertkey_binding", "resource", ")", "throws", "Exception", "{", "sslvserver_sslcertkey_binding", "deleteresource", "=", "new", "sslvserver_sslcertkey_binding", "(", ")", ";", "deleteresource", ".", "vservername", "=", "resource", ".", "vservername", ";", "deleteresource", ".", "certkeyname", "=", "resource", ".", "certkeyname", ";", "deleteresource", ".", "ca", "=", "resource", ".", "ca", ";", "deleteresource", ".", "crlcheck", "=", "resource", ".", "crlcheck", ";", "deleteresource", ".", "snicert", "=", "resource", ".", "snicert", ";", "deleteresource", ".", "ocspcheck", "=", "resource", ".", "ocspcheck", ";", "return", "deleteresource", ".", "delete_resource", "(", "client", ")", ";", "}", "public", "static", "base_responses", "delete", "(", "nitro_service", "client", ",", "sslvserver_sslcertkey_binding", "resources", "[", "]", ")", "throws", "Exception", "{", "base_responses", "result", "=", "null", ";", "if", "(", "resources", "!=", "null", "&&", "resources", ".", "length", ">", "0", ")", "{", "sslvserver_sslcertkey_binding", "deleteresources", "[", "]", "=", "new", "sslvserver_sslcertkey_binding", "[", "resources", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "resources", ".", "length", ";", "i", "++", ")", "{", "deleteresources", "[", "i", "]", "=", "new", "sslvserver_sslcertkey_binding", "(", ")", ";", "deleteresources", "[", "i", "]", ".", "vservername", "=", "resources", "[", "i", "]", ".", "vservername", ";", "deleteresources", "[", "i", "]", ".", "certkeyname", "=", "resources", "[", "i", "]", ".", "certkeyname", ";", "deleteresources", "[", "i", "]", ".", "ca", "=", "resources", "[", "i", "]", ".", "ca", ";", "deleteresources", "[", "i", "]", ".", "crlcheck", "=", "resources", "[", "i", "]", ".", "crlcheck", ";", "deleteresources", "[", "i", "]", ".", "snicert", "=", "resources", "[", "i", "]", ".", "snicert", ";", "deleteresources", "[", "i", "]", ".", "ocspcheck", "=", "resources", "[", "i", "]", ".", "ocspcheck", ";", "}", "result", "=", "delete_bulk_request", "(", "client", ",", "deleteresources", ")", ";", "}", "return", "result", ";", "}", "/**\n\t* Use this API to fetch sslvserver_sslcertkey_binding resources of given name .\n\t*/", "public", "static", "sslvserver_sslcertkey_binding", "[", "]", "get", "(", "nitro_service", "service", ",", "String", "vservername", ")", "throws", "Exception", "{", "sslvserver_sslcertkey_binding", "obj", "=", "new", "sslvserver_sslcertkey_binding", "(", ")", ";", "obj", ".", "set_vservername", "(", "vservername", ")", ";", "sslvserver_sslcertkey_binding", "response", "[", "]", "=", "(", "sslvserver_sslcertkey_binding", "[", "]", ")", "obj", ".", "get_resources", "(", "service", ")", ";", "return", "response", ";", "}", "/**\n\t* Use this API to fetch filtered set of sslvserver_sslcertkey_binding resources.\n\t* filter string should be in JSON format.eg: \"port:80,servicetype:HTTP\".\n\t*/", "public", "static", "sslvserver_sslcertkey_binding", "[", "]", "get_filtered", "(", "nitro_service", "service", ",", "String", "vservername", ",", "String", "filter", ")", "throws", "Exception", "{", "sslvserver_sslcertkey_binding", "obj", "=", "new", "sslvserver_sslcertkey_binding", "(", ")", ";", "obj", ".", "set_vservername", "(", "vservername", ")", ";", "options", "option", "=", "new", "options", "(", ")", ";", "option", ".", "set_filter", "(", "filter", ")", ";", "sslvserver_sslcertkey_binding", "[", "]", "response", "=", "(", "sslvserver_sslcertkey_binding", "[", "]", ")", "obj", ".", "getfiltered", "(", "service", ",", "option", ")", ";", "return", "response", ";", "}", "/**\n\t* Use this API to fetch filtered set of sslvserver_sslcertkey_binding resources.\n\t* set the filter parameter values in filtervalue object.\n\t*/", "public", "static", "sslvserver_sslcertkey_binding", "[", "]", "get_filtered", "(", "nitro_service", "service", ",", "String", "vservername", ",", "filtervalue", "[", "]", "filter", ")", "throws", "Exception", "{", "sslvserver_sslcertkey_binding", "obj", "=", "new", "sslvserver_sslcertkey_binding", "(", ")", ";", "obj", ".", "set_vservername", "(", "vservername", ")", ";", "options", "option", "=", "new", "options", "(", ")", ";", "option", ".", "set_filter", "(", "filter", ")", ";", "sslvserver_sslcertkey_binding", "[", "]", "response", "=", "(", "sslvserver_sslcertkey_binding", "[", "]", ")", "obj", ".", "getfiltered", "(", "service", ",", "option", ")", ";", "return", "response", ";", "}", "/**\n\t* Use this API to count sslvserver_sslcertkey_binding resources configued on NetScaler.\n\t*/", "public", "static", "long", "count", "(", "nitro_service", "service", ",", "String", "vservername", ")", "throws", "Exception", "{", "sslvserver_sslcertkey_binding", "obj", "=", "new", "sslvserver_sslcertkey_binding", "(", ")", ";", "obj", ".", "set_vservername", "(", "vservername", ")", ";", "options", "option", "=", "new", "options", "(", ")", ";", "option", ".", "set_count", "(", "true", ")", ";", "sslvserver_sslcertkey_binding", "response", "[", "]", "=", "(", "sslvserver_sslcertkey_binding", "[", "]", ")", "obj", ".", "get_resources", "(", "service", ",", "option", ")", ";", "if", "(", "response", "!=", "null", ")", "{", "return", "response", "[", "0", "]", ".", "__count", ";", "}", "return", "0", ";", "}", "/**\n\t* Use this API to count the filtered set of sslvserver_sslcertkey_binding resources.\n\t* filter string should be in JSON format.eg: \"port:80,servicetype:HTTP\".\n\t*/", "public", "static", "long", "count_filtered", "(", "nitro_service", "service", ",", "String", "vservername", ",", "String", "filter", ")", "throws", "Exception", "{", "sslvserver_sslcertkey_binding", "obj", "=", "new", "sslvserver_sslcertkey_binding", "(", ")", ";", "obj", ".", "set_vservername", "(", "vservername", ")", ";", "options", "option", "=", "new", "options", "(", ")", ";", "option", ".", "set_count", "(", "true", ")", ";", "option", ".", "set_filter", "(", "filter", ")", ";", "sslvserver_sslcertkey_binding", "[", "]", "response", "=", "(", "sslvserver_sslcertkey_binding", "[", "]", ")", "obj", ".", "getfiltered", "(", "service", ",", "option", ")", ";", "if", "(", "response", "!=", "null", ")", "{", "return", "response", "[", "0", "]", ".", "__count", ";", "}", "return", "0", ";", "}", "/**\n\t* Use this API to count the filtered set of sslvserver_sslcertkey_binding resources.\n\t* set the filter parameter values in filtervalue object.\n\t*/", "public", "static", "long", "count_filtered", "(", "nitro_service", "service", ",", "String", "vservername", ",", "filtervalue", "[", "]", "filter", ")", "throws", "Exception", "{", "sslvserver_sslcertkey_binding", "obj", "=", "new", "sslvserver_sslcertkey_binding", "(", ")", ";", "obj", ".", "set_vservername", "(", "vservername", ")", ";", "options", "option", "=", "new", "options", "(", ")", ";", "option", ".", "set_count", "(", "true", ")", ";", "option", ".", "set_filter", "(", "filter", ")", ";", "sslvserver_sslcertkey_binding", "[", "]", "response", "=", "(", "sslvserver_sslcertkey_binding", "[", "]", ")", "obj", ".", "getfiltered", "(", "service", ",", "option", ")", ";", "if", "(", "response", "!=", "null", ")", "{", "return", "response", "[", "0", "]", ".", "__count", ";", "}", "return", "0", ";", "}", "public", "static", "class", "ocspcheckEnum", "{", "public", "static", "final", "String", "Mandatory", "=", "\"", "Mandatory", "\"", ";", "public", "static", "final", "String", "Optional", "=", "\"", "Optional", "\"", ";", "}", "public", "static", "class", "crlcheckEnum", "{", "public", "static", "final", "String", "Mandatory", "=", "\"", "Mandatory", "\"", ";", "public", "static", "final", "String", "Optional", "=", "\"", "Optional", "\"", ";", "}", "public", "static", "class", "labeltypeEnum", "{", "public", "static", "final", "String", "vserver", "=", "\"", "vserver", "\"", ";", "public", "static", "final", "String", "service", "=", "\"", "service", "\"", ";", "public", "static", "final", "String", "policylabel", "=", "\"", "policylabel", "\"", ";", "}", "}" ]
Binding class showing the sslcertkey that can be bound to sslvserver.
[ "Binding", "class", "showing", "the", "sslcertkey", "that", "can", "be", "bound", "to", "sslvserver", "." ]
[]
[ { "param": "base_resource", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "base_resource", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c43c3d2f559d424bd3881bf73668b6c4c2f4224e
jianghaolu/azure-storage-java
src/main/java/com/microsoft/azure/storage/blob/PageBlobAccessConditions.java
[ "Apache-2.0" ]
Java
PageBlobAccessConditions
/** * This class contains values that restrict the successful completion of PageBlob operations to certain conditions. * It may be set to null if no access conditions are desired. * * Please refer to the request header section * <a href=https://docs.microsoft.com/en-us/rest/api/storageservices/put-page>here</a> for more conceptual information. */
This class contains values that restrict the successful completion of PageBlob operations to certain conditions. It may be set to null if no access conditions are desired. Please refer to the request header section here for more conceptual information.
[ "This", "class", "contains", "values", "that", "restrict", "the", "successful", "completion", "of", "PageBlob", "operations", "to", "certain", "conditions", ".", "It", "may", "be", "set", "to", "null", "if", "no", "access", "conditions", "are", "desired", ".", "Please", "refer", "to", "the", "request", "header", "section", "here", "for", "more", "conceptual", "information", "." ]
public final class PageBlobAccessConditions { /** * An object representing no access conditions. */ public static final PageBlobAccessConditions NONE = new PageBlobAccessConditions(); private SequenceNumberAccessConditions sequenceNumberAccessConditions; private ModifiedAccessConditions modifiedAccessConditions; private LeaseAccessConditions leaseAccessConditions; /** * {@link SequenceNumberAccessConditions} */ public SequenceNumberAccessConditions sequenceNumberAccessConditions() { return sequenceNumberAccessConditions; } /** * {@link SequenceNumberAccessConditions} */ public PageBlobAccessConditions withSequenceNumberAccessConditions(SequenceNumberAccessConditions sequenceNumberAccessConditions) { this.sequenceNumberAccessConditions = sequenceNumberAccessConditions; return this; } /** * {@link ModifiedAccessConditions} */ public ModifiedAccessConditions modifiedAccessConditions() { return modifiedAccessConditions; } /** * {@link ModifiedAccessConditions} */ public PageBlobAccessConditions withModifiedAccessConditions(ModifiedAccessConditions modifiedAccessConditions) { this.modifiedAccessConditions = modifiedAccessConditions; return this; } /** * {@link LeaseAccessConditions} */ public LeaseAccessConditions leaseAccessConditions() { return leaseAccessConditions; } /** * {@link LeaseAccessConditions} */ public PageBlobAccessConditions withLeaseAccessConditions(LeaseAccessConditions leaseAccessConditions) { this.leaseAccessConditions = leaseAccessConditions; return this; } public PageBlobAccessConditions() { this.sequenceNumberAccessConditions = new SequenceNumberAccessConditions(); this.modifiedAccessConditions = new ModifiedAccessConditions(); this.leaseAccessConditions = new LeaseAccessConditions(); } }
[ "public", "final", "class", "PageBlobAccessConditions", "{", "/**\n * An object representing no access conditions.\n */", "public", "static", "final", "PageBlobAccessConditions", "NONE", "=", "new", "PageBlobAccessConditions", "(", ")", ";", "private", "SequenceNumberAccessConditions", "sequenceNumberAccessConditions", ";", "private", "ModifiedAccessConditions", "modifiedAccessConditions", ";", "private", "LeaseAccessConditions", "leaseAccessConditions", ";", "/**\n * {@link SequenceNumberAccessConditions}\n */", "public", "SequenceNumberAccessConditions", "sequenceNumberAccessConditions", "(", ")", "{", "return", "sequenceNumberAccessConditions", ";", "}", "/**\n * {@link SequenceNumberAccessConditions}\n */", "public", "PageBlobAccessConditions", "withSequenceNumberAccessConditions", "(", "SequenceNumberAccessConditions", "sequenceNumberAccessConditions", ")", "{", "this", ".", "sequenceNumberAccessConditions", "=", "sequenceNumberAccessConditions", ";", "return", "this", ";", "}", "/**\n * {@link ModifiedAccessConditions}\n */", "public", "ModifiedAccessConditions", "modifiedAccessConditions", "(", ")", "{", "return", "modifiedAccessConditions", ";", "}", "/**\n * {@link ModifiedAccessConditions}\n */", "public", "PageBlobAccessConditions", "withModifiedAccessConditions", "(", "ModifiedAccessConditions", "modifiedAccessConditions", ")", "{", "this", ".", "modifiedAccessConditions", "=", "modifiedAccessConditions", ";", "return", "this", ";", "}", "/**\n * {@link LeaseAccessConditions}\n */", "public", "LeaseAccessConditions", "leaseAccessConditions", "(", ")", "{", "return", "leaseAccessConditions", ";", "}", "/**\n * {@link LeaseAccessConditions}\n */", "public", "PageBlobAccessConditions", "withLeaseAccessConditions", "(", "LeaseAccessConditions", "leaseAccessConditions", ")", "{", "this", ".", "leaseAccessConditions", "=", "leaseAccessConditions", ";", "return", "this", ";", "}", "public", "PageBlobAccessConditions", "(", ")", "{", "this", ".", "sequenceNumberAccessConditions", "=", "new", "SequenceNumberAccessConditions", "(", ")", ";", "this", ".", "modifiedAccessConditions", "=", "new", "ModifiedAccessConditions", "(", ")", ";", "this", ".", "leaseAccessConditions", "=", "new", "LeaseAccessConditions", "(", ")", ";", "}", "}" ]
This class contains values that restrict the successful completion of PageBlob operations to certain conditions.
[ "This", "class", "contains", "values", "that", "restrict", "the", "successful", "completion", "of", "PageBlob", "operations", "to", "certain", "conditions", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c43c8ff58a396366753cd347090558b91c447026
state303/spring-batch
spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkRequest.java
[ "Apache-2.0" ]
Java
ChunkRequest
/** * Encapsulation of a chunk of items to be processed remotely as part of a step * execution. * * @author Dave Syer * * @param <T> the type of the items to process */
Encapsulation of a chunk of items to be processed remotely as part of a step execution. @author Dave Syer @param the type of the items to process
[ "Encapsulation", "of", "a", "chunk", "of", "items", "to", "be", "processed", "remotely", "as", "part", "of", "a", "step", "execution", ".", "@author", "Dave", "Syer", "@param", "the", "type", "of", "the", "items", "to", "process" ]
public class ChunkRequest<T> implements Serializable { private static final long serialVersionUID = 1L; private final long jobId; private final Collection<? extends T> items; private final StepContribution stepContribution; private final int sequence; public ChunkRequest(int sequence, Collection<? extends T> items, long jobId, StepContribution stepContribution) { this.sequence = sequence; this.items = items; this.jobId = jobId; this.stepContribution = stepContribution; } public long getJobId() { return jobId; } public Collection<? extends T> getItems() { return items; } public int getSequence() { return sequence; } /** * @return the {@link StepContribution} for this chunk */ public StepContribution getStepContribution() { return stepContribution; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return getClass().getSimpleName() + ": jobId=" + jobId + ", sequence=" + sequence + ", contribution=" + stepContribution + ", item count=" + items.size(); } }
[ "public", "class", "ChunkRequest", "<", "T", ">", "implements", "Serializable", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "private", "final", "long", "jobId", ";", "private", "final", "Collection", "<", "?", "extends", "T", ">", "items", ";", "private", "final", "StepContribution", "stepContribution", ";", "private", "final", "int", "sequence", ";", "public", "ChunkRequest", "(", "int", "sequence", ",", "Collection", "<", "?", "extends", "T", ">", "items", ",", "long", "jobId", ",", "StepContribution", "stepContribution", ")", "{", "this", ".", "sequence", "=", "sequence", ";", "this", ".", "items", "=", "items", ";", "this", ".", "jobId", "=", "jobId", ";", "this", ".", "stepContribution", "=", "stepContribution", ";", "}", "public", "long", "getJobId", "(", ")", "{", "return", "jobId", ";", "}", "public", "Collection", "<", "?", "extends", "T", ">", "getItems", "(", ")", "{", "return", "items", ";", "}", "public", "int", "getSequence", "(", ")", "{", "return", "sequence", ";", "}", "/**\n\t * @return the {@link StepContribution} for this chunk\n\t */", "public", "StepContribution", "getStepContribution", "(", ")", "{", "return", "stepContribution", ";", "}", "/**\n\t * @see java.lang.Object#toString()\n\t */", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "getClass", "(", ")", ".", "getSimpleName", "(", ")", "+", "\"", ": jobId=", "\"", "+", "jobId", "+", "\"", ", sequence=", "\"", "+", "sequence", "+", "\"", ", contribution=", "\"", "+", "stepContribution", "+", "\"", ", item count=", "\"", "+", "items", ".", "size", "(", ")", ";", "}", "}" ]
Encapsulation of a chunk of items to be processed remotely as part of a step execution.
[ "Encapsulation", "of", "a", "chunk", "of", "items", "to", "be", "processed", "remotely", "as", "part", "of", "a", "step", "execution", "." ]
[]
[ { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c43d3b06bd0fc5e1d586212ec93ca87813514b21
Ermax81/demo-springboot-openpdf
src/test/java/com/example/demospringbootopenpdf/GeneratePdfWithFormFieldsExample.java
[ "MIT" ]
Java
GeneratePdfWithFormFieldsExample
// WORK IN PROGRESS...
WORK IN PROGRESS
[ "WORK", "IN", "PROGRESS" ]
public class GeneratePdfWithFormFieldsExample { @Test void test() throws IOException { Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("src/test/resources/example.pdf")); document.open(); PdfAcroForm acroForm = writer.getAcroForm(); document.add(new Paragraph("Hello World")); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); String coffeeImagePath = classLoader.getResource("coffee-icon.png").getPath(); String reindeerImagePath = classLoader.getResource("reindeer-deer-icon.png").getPath(); Image reindeerImage = Image.getInstance(reindeerImagePath); reindeerImage.scalePercent(50); float height = reindeerImage.getScaledHeight(); float width = reindeerImage.getScaledWidth(); Rectangle box = new Rectangle(height, width); Rectangle rect = new Rectangle(243, 153); rect.setBackgroundColor(new Color(0xFF, 0xFF, 0xCC)); PdfPTable table = new PdfPTable(2); PdfPCell cell = new PdfPCell(); cell.setFixedHeight(height); Paragraph paragraph = new Paragraph("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt" + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco" + " laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in " + " ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco" + " laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in " + "voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat" + " non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."); cell.addElement(paragraph); table.addCell(cell); // new Rectangle(40,120) //PushbuttonField imageField = new PushbuttonField(writer, box, "image"); //imageField.setImage(reindeerImage); ////imageField.setText("Exemple..."); //PdfFormField ff = imageField.getField(); //cell.setCellEvent(new ImageFormField(ff)); //PdfPCell cell = table.getDefaultCell(); //cell.setFixedHeight(height); //defaultCell.get //new Rectangle(100, 100, 200, 200) PushbuttonField bt = new PushbuttonField(writer, new Rectangle(200, 200), "Button1"); //bt.setText("My Caption"); //bt.setFontSize(0); bt.setImage(reindeerImage); //bt.setLayout(PushbuttonField.LAYOUT_ICON_TOP_LABEL_BOTTOM); bt.setLayout(PushbuttonField.LAYOUT_ICON_ONLY); //bt.setScaleIcon(PushbuttonField.SCALE_ICON_IS_TOO_BIG); //bt.setProportionalIcon(true); bt.setBackgroundColor(Color.cyan); bt.setBorderStyle(PdfBorderDictionary.STYLE_SOLID); bt.setBorderColor(Color.red); bt.setBorderWidth(3); PdfFormField ff = bt.getField(); cell = new PdfPCell(); cell.setFixedHeight(height); cell.setCellEvent(new FormField(ff)); table.addCell(cell); cell = new PdfPCell(); cell.setColspan(2); TextField text = new TextField(writer, new Rectangle(0, 0), "name"); text.setText("NameByDefaut"); text.setOptions(TextField.MULTILINE); text.setFontSize(8); PdfFormField name = text.getTextField(); cell.setCellEvent(new FormField(name)); cell.setFixedHeight(60); table.addCell(cell); document.add(table); writer.addAnnotation(ff); writer.addAnnotation(name); document.close(); writer.close(); String pdfInPath = classLoader.getResource("example.pdf").getPath(); PdfReader reader = new PdfReader(pdfInPath); PdfStamper pdfStamper = new PdfStamper(reader, new FileOutputStream("src/test/resources/modified-example.pdf")); AcroFields form1 = pdfStamper.getAcroFields(); PushbuttonField button = form1.getNewPushbuttonFromField("Button1"); Image coffeeImage = Image.getInstance(coffeeImagePath); button.setImage(coffeeImage); button.setText("Modified text"); PdfFormField buttonFormField = button.getField(); form1.replacePushbuttonField("Button1", buttonFormField); form1.setField("name", "Modified Name"); pdfStamper.close(); } }
[ "public", "class", "GeneratePdfWithFormFieldsExample", "{", "@", "Test", "void", "test", "(", ")", "throws", "IOException", "{", "Document", "document", "=", "new", "Document", "(", "PageSize", ".", "A4", ")", ";", "PdfWriter", "writer", "=", "PdfWriter", ".", "getInstance", "(", "document", ",", "new", "FileOutputStream", "(", "\"", "src/test/resources/example.pdf", "\"", ")", ")", ";", "document", ".", "open", "(", ")", ";", "PdfAcroForm", "acroForm", "=", "writer", ".", "getAcroForm", "(", ")", ";", "document", ".", "add", "(", "new", "Paragraph", "(", "\"", "Hello World", "\"", ")", ")", ";", "ClassLoader", "classLoader", "=", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ";", "String", "coffeeImagePath", "=", "classLoader", ".", "getResource", "(", "\"", "coffee-icon.png", "\"", ")", ".", "getPath", "(", ")", ";", "String", "reindeerImagePath", "=", "classLoader", ".", "getResource", "(", "\"", "reindeer-deer-icon.png", "\"", ")", ".", "getPath", "(", ")", ";", "Image", "reindeerImage", "=", "Image", ".", "getInstance", "(", "reindeerImagePath", ")", ";", "reindeerImage", ".", "scalePercent", "(", "50", ")", ";", "float", "height", "=", "reindeerImage", ".", "getScaledHeight", "(", ")", ";", "float", "width", "=", "reindeerImage", ".", "getScaledWidth", "(", ")", ";", "Rectangle", "box", "=", "new", "Rectangle", "(", "height", ",", "width", ")", ";", "Rectangle", "rect", "=", "new", "Rectangle", "(", "243", ",", "153", ")", ";", "rect", ".", "setBackgroundColor", "(", "new", "Color", "(", "0xFF", ",", "0xFF", ",", "0xCC", ")", ")", ";", "PdfPTable", "table", "=", "new", "PdfPTable", "(", "2", ")", ";", "PdfPCell", "cell", "=", "new", "PdfPCell", "(", ")", ";", "cell", ".", "setFixedHeight", "(", "height", ")", ";", "Paragraph", "paragraph", "=", "new", "Paragraph", "(", "\"", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt", "\"", "+", "\"", " ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco", "\"", "+", "\"", " laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in ", "\"", "+", "\"", " ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco", "\"", "+", "\"", " laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in ", "\"", "+", "\"", "voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat", "\"", "+", "\"", " non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "\"", ")", ";", "cell", ".", "addElement", "(", "paragraph", ")", ";", "table", ".", "addCell", "(", "cell", ")", ";", "PushbuttonField", "bt", "=", "new", "PushbuttonField", "(", "writer", ",", "new", "Rectangle", "(", "200", ",", "200", ")", ",", "\"", "Button1", "\"", ")", ";", "bt", ".", "setImage", "(", "reindeerImage", ")", ";", "bt", ".", "setLayout", "(", "PushbuttonField", ".", "LAYOUT_ICON_ONLY", ")", ";", "bt", ".", "setBackgroundColor", "(", "Color", ".", "cyan", ")", ";", "bt", ".", "setBorderStyle", "(", "PdfBorderDictionary", ".", "STYLE_SOLID", ")", ";", "bt", ".", "setBorderColor", "(", "Color", ".", "red", ")", ";", "bt", ".", "setBorderWidth", "(", "3", ")", ";", "PdfFormField", "ff", "=", "bt", ".", "getField", "(", ")", ";", "cell", "=", "new", "PdfPCell", "(", ")", ";", "cell", ".", "setFixedHeight", "(", "height", ")", ";", "cell", ".", "setCellEvent", "(", "new", "FormField", "(", "ff", ")", ")", ";", "table", ".", "addCell", "(", "cell", ")", ";", "cell", "=", "new", "PdfPCell", "(", ")", ";", "cell", ".", "setColspan", "(", "2", ")", ";", "TextField", "text", "=", "new", "TextField", "(", "writer", ",", "new", "Rectangle", "(", "0", ",", "0", ")", ",", "\"", "name", "\"", ")", ";", "text", ".", "setText", "(", "\"", "NameByDefaut", "\"", ")", ";", "text", ".", "setOptions", "(", "TextField", ".", "MULTILINE", ")", ";", "text", ".", "setFontSize", "(", "8", ")", ";", "PdfFormField", "name", "=", "text", ".", "getTextField", "(", ")", ";", "cell", ".", "setCellEvent", "(", "new", "FormField", "(", "name", ")", ")", ";", "cell", ".", "setFixedHeight", "(", "60", ")", ";", "table", ".", "addCell", "(", "cell", ")", ";", "document", ".", "add", "(", "table", ")", ";", "writer", ".", "addAnnotation", "(", "ff", ")", ";", "writer", ".", "addAnnotation", "(", "name", ")", ";", "document", ".", "close", "(", ")", ";", "writer", ".", "close", "(", ")", ";", "String", "pdfInPath", "=", "classLoader", ".", "getResource", "(", "\"", "example.pdf", "\"", ")", ".", "getPath", "(", ")", ";", "PdfReader", "reader", "=", "new", "PdfReader", "(", "pdfInPath", ")", ";", "PdfStamper", "pdfStamper", "=", "new", "PdfStamper", "(", "reader", ",", "new", "FileOutputStream", "(", "\"", "src/test/resources/modified-example.pdf", "\"", ")", ")", ";", "AcroFields", "form1", "=", "pdfStamper", ".", "getAcroFields", "(", ")", ";", "PushbuttonField", "button", "=", "form1", ".", "getNewPushbuttonFromField", "(", "\"", "Button1", "\"", ")", ";", "Image", "coffeeImage", "=", "Image", ".", "getInstance", "(", "coffeeImagePath", ")", ";", "button", ".", "setImage", "(", "coffeeImage", ")", ";", "button", ".", "setText", "(", "\"", "Modified text", "\"", ")", ";", "PdfFormField", "buttonFormField", "=", "button", ".", "getField", "(", ")", ";", "form1", ".", "replacePushbuttonField", "(", "\"", "Button1", "\"", ",", "buttonFormField", ")", ";", "form1", ".", "setField", "(", "\"", "name", "\"", ",", "\"", "Modified Name", "\"", ")", ";", "pdfStamper", ".", "close", "(", ")", ";", "}", "}" ]
WORK IN PROGRESS...
[ "WORK", "IN", "PROGRESS", "..." ]
[ "// new Rectangle(40,120)", "//PushbuttonField imageField = new PushbuttonField(writer, box, \"image\");", "//imageField.setImage(reindeerImage);", "////imageField.setText(\"Exemple...\");", "//PdfFormField ff = imageField.getField();", "//cell.setCellEvent(new ImageFormField(ff));", "//PdfPCell cell = table.getDefaultCell();", "//cell.setFixedHeight(height);", "//defaultCell.get", "//new Rectangle(100, 100, 200, 200)", "//bt.setText(\"My Caption\");", "//bt.setFontSize(0);", "//bt.setLayout(PushbuttonField.LAYOUT_ICON_TOP_LABEL_BOTTOM);", "//bt.setScaleIcon(PushbuttonField.SCALE_ICON_IS_TOO_BIG);", "//bt.setProportionalIcon(true);" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c43d6e44c3a59f5b5cf3da950c3c67d6e16d3547
fdamken/mybatis-mapper-parser
src/main/java/com/dmken/oss/mybatis/mapper/parser/tree/SelfClosingXmlTag.java
[ "Apache-2.0" ]
Java
SelfClosingXmlTag
/** * Represents a self-closing XML tag with no children (e.g. * <code>&lt;help /&gt;</code>). * * @see XmlTag */
Represents a self-closing XML tag with no children .
[ "Represents", "a", "self", "-", "closing", "XML", "tag", "with", "no", "children", "." ]
public class SelfClosingXmlTag extends AbstractXmlTag { /** * Constructor of SelfClosingXmlTag. * * @param name * See {@link AbstractXmlTag}. * @param parameters * See {@link AbstractXmlTag}. */ public SelfClosingXmlTag(final String name, final Map<String, String> parameters) { super(name, parameters); } /** * {@inheritDoc} * * @see com.dmken.oss.mybatis.mapper.parser.tree.AbstractXmlTag#toString() */ @Override public String toString() { return this.getName() + "/>" + this.getParameters().toString(); } }
[ "public", "class", "SelfClosingXmlTag", "extends", "AbstractXmlTag", "{", "/**\n * Constructor of SelfClosingXmlTag.\n *\n * @param name\n * See {@link AbstractXmlTag}.\n * @param parameters\n * See {@link AbstractXmlTag}.\n */", "public", "SelfClosingXmlTag", "(", "final", "String", "name", ",", "final", "Map", "<", "String", ",", "String", ">", "parameters", ")", "{", "super", "(", "name", ",", "parameters", ")", ";", "}", "/**\n * {@inheritDoc}\n *\n * @see com.dmken.oss.mybatis.mapper.parser.tree.AbstractXmlTag#toString()\n */", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "this", ".", "getName", "(", ")", "+", "\"", "/>", "\"", "+", "this", ".", "getParameters", "(", ")", ".", "toString", "(", ")", ";", "}", "}" ]
Represents a self-closing XML tag with no children (e.g.
[ "Represents", "a", "self", "-", "closing", "XML", "tag", "with", "no", "children", "(", "e", ".", "g", "." ]
[]
[ { "param": "AbstractXmlTag", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractXmlTag", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c43e6e2cfa148bc5a2e7dddc7061018b9f151fc0
teco-kit/ModelDrivenGateways
src/edu.teco.automata.gmf/src/Automata/util/AutomataAdapterFactory.java
[ "MIT" ]
Java
AutomataAdapterFactory
/** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see Automata.AutomataPackage * @generated */
The Adapter Factory for the model. It provides an adapter createXXX method for each class of the model.
[ "The", "Adapter", "Factory", "for", "the", "model", ".", "It", "provides", "an", "adapter", "createXXX", "method", "for", "each", "class", "of", "the", "model", "." ]
public class AutomataAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static AutomataPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public AutomataAdapterFactory() { if (modelPackage == null) { modelPackage = AutomataPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject)object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected AutomataSwitch<Adapter> modelSwitch = new AutomataSwitch<Adapter>() { @Override public Adapter caseStateMachine(StateMachine object) { return createStateMachineAdapter(); } @Override public Adapter caseState(State object) { return createStateAdapter(); } @Override public Adapter caseSimpleState(SimpleState object) { return createSimpleStateAdapter(); } @Override public Adapter caseStartState(StartState object) { return createStartStateAdapter(); } @Override public Adapter caseStopState(StopState object) { return createStopStateAdapter(); } @Override public Adapter caseDataType(DataType object) { return createDataTypeAdapter(); } @Override public Adapter casecomplexType(complexType object) { return createcomplexTypeAdapter(); } @Override public Adapter caseTByte(TByte object) { return createTByteAdapter(); } @Override public Adapter caseTChar(TChar object) { return createTCharAdapter(); } @Override public Adapter caseTShort(TShort object) { return createTShortAdapter(); } @Override public Adapter caseTInt(TInt object) { return createTIntAdapter(); } @Override public Adapter caseTLong(TLong object) { return createTLongAdapter(); } @Override public Adapter caseTFloat(TFloat object) { return createTFloatAdapter(); } @Override public Adapter caseTDouble(TDouble object) { return createTDoubleAdapter(); } @Override public Adapter caseTString(TString object) { return createTStringAdapter(); } @Override public Adapter defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { return modelSwitch.doSwitch((EObject)target); } /** * Creates a new adapter for an object of class '{@link Automata.StateMachine <em>State Machine</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.StateMachine * @generated */ public Adapter createStateMachineAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Automata.State <em>State</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.State * @generated */ public Adapter createStateAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Automata.SimpleState <em>Simple State</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.SimpleState * @generated */ public Adapter createSimpleStateAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Automata.StartState <em>Start State</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.StartState * @generated */ public Adapter createStartStateAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Automata.StopState <em>Stop State</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.StopState * @generated */ public Adapter createStopStateAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Automata.DataType <em>Data Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.DataType * @generated */ public Adapter createDataTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Automata.complexType <em>complex Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.complexType * @generated */ public Adapter createcomplexTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Automata.TByte <em>TByte</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.TByte * @generated */ public Adapter createTByteAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Automata.TChar <em>TChar</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.TChar * @generated */ public Adapter createTCharAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Automata.TShort <em>TShort</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.TShort * @generated */ public Adapter createTShortAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Automata.TInt <em>TInt</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.TInt * @generated */ public Adapter createTIntAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Automata.TLong <em>TLong</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.TLong * @generated */ public Adapter createTLongAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Automata.TFloat <em>TFloat</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.TFloat * @generated */ public Adapter createTFloatAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Automata.TDouble <em>TDouble</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.TDouble * @generated */ public Adapter createTDoubleAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Automata.TString <em>TString</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Automata.TString * @generated */ public Adapter createTStringAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } }
[ "public", "class", "AutomataAdapterFactory", "extends", "AdapterFactoryImpl", "{", "/**\n\t * The cached model package.\n\t * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n\t * @generated\n\t */", "protected", "static", "AutomataPackage", "modelPackage", ";", "/**\n\t * Creates an instance of the adapter factory.\n\t * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n\t * @generated\n\t */", "public", "AutomataAdapterFactory", "(", ")", "{", "if", "(", "modelPackage", "==", "null", ")", "{", "modelPackage", "=", "AutomataPackage", ".", "eINSTANCE", ";", "}", "}", "/**\n\t * Returns whether this factory is applicable for the type of the object.\n\t * <!-- begin-user-doc -->\n * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model.\n * <!-- end-user-doc -->\n\t * @return whether this factory is applicable for the type of the object.\n\t * @generated\n\t */", "@", "Override", "public", "boolean", "isFactoryForType", "(", "Object", "object", ")", "{", "if", "(", "object", "==", "modelPackage", ")", "{", "return", "true", ";", "}", "if", "(", "object", "instanceof", "EObject", ")", "{", "return", "(", "(", "EObject", ")", "object", ")", ".", "eClass", "(", ")", ".", "getEPackage", "(", ")", "==", "modelPackage", ";", "}", "return", "false", ";", "}", "/**\n\t * The switch that delegates to the <code>createXXX</code> methods.\n\t * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n\t * @generated\n\t */", "protected", "AutomataSwitch", "<", "Adapter", ">", "modelSwitch", "=", "new", "AutomataSwitch", "<", "Adapter", ">", "(", ")", "{", "@", "Override", "public", "Adapter", "caseStateMachine", "(", "StateMachine", "object", ")", "{", "return", "createStateMachineAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseState", "(", "State", "object", ")", "{", "return", "createStateAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseSimpleState", "(", "SimpleState", "object", ")", "{", "return", "createSimpleStateAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseStartState", "(", "StartState", "object", ")", "{", "return", "createStartStateAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseStopState", "(", "StopState", "object", ")", "{", "return", "createStopStateAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseDataType", "(", "DataType", "object", ")", "{", "return", "createDataTypeAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "casecomplexType", "(", "complexType", "object", ")", "{", "return", "createcomplexTypeAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseTByte", "(", "TByte", "object", ")", "{", "return", "createTByteAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseTChar", "(", "TChar", "object", ")", "{", "return", "createTCharAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseTShort", "(", "TShort", "object", ")", "{", "return", "createTShortAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseTInt", "(", "TInt", "object", ")", "{", "return", "createTIntAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseTLong", "(", "TLong", "object", ")", "{", "return", "createTLongAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseTFloat", "(", "TFloat", "object", ")", "{", "return", "createTFloatAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseTDouble", "(", "TDouble", "object", ")", "{", "return", "createTDoubleAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseTString", "(", "TString", "object", ")", "{", "return", "createTStringAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "defaultCase", "(", "EObject", "object", ")", "{", "return", "createEObjectAdapter", "(", ")", ";", "}", "}", ";", "/**\n\t * Creates an adapter for the <code>target</code>.\n\t * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n\t * @param target the object to adapt.\n\t * @return the adapter for the <code>target</code>.\n\t * @generated\n\t */", "@", "Override", "public", "Adapter", "createAdapter", "(", "Notifier", "target", ")", "{", "return", "modelSwitch", ".", "doSwitch", "(", "(", "EObject", ")", "target", ")", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.StateMachine <em>State Machine</em>}'.\n\t * <!-- begin-user-doc -->\n * This default implementation returns null so that we can easily ignore cases;\n * it's useful to ignore a case when inheritance will catch all the cases anyway.\n * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.StateMachine\n\t * @generated\n\t */", "public", "Adapter", "createStateMachineAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.State <em>State</em>}'.\n\t * <!-- begin-user-doc -->\n * This default implementation returns null so that we can easily ignore cases;\n * it's useful to ignore a case when inheritance will catch all the cases anyway.\n * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.State\n\t * @generated\n\t */", "public", "Adapter", "createStateAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.SimpleState <em>Simple State</em>}'.\n\t * <!-- begin-user-doc -->\n * This default implementation returns null so that we can easily ignore cases;\n * it's useful to ignore a case when inheritance will catch all the cases anyway.\n * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.SimpleState\n\t * @generated\n\t */", "public", "Adapter", "createSimpleStateAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.StartState <em>Start State</em>}'.\n\t * <!-- begin-user-doc -->\n * This default implementation returns null so that we can easily ignore cases;\n * it's useful to ignore a case when inheritance will catch all the cases anyway.\n * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.StartState\n\t * @generated\n\t */", "public", "Adapter", "createStartStateAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.StopState <em>Stop State</em>}'.\n\t * <!-- begin-user-doc -->\n * This default implementation returns null so that we can easily ignore cases;\n * it's useful to ignore a case when inheritance will catch all the cases anyway.\n * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.StopState\n\t * @generated\n\t */", "public", "Adapter", "createStopStateAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.DataType <em>Data Type</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.DataType\n\t * @generated\n\t */", "public", "Adapter", "createDataTypeAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.complexType <em>complex Type</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.complexType\n\t * @generated\n\t */", "public", "Adapter", "createcomplexTypeAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.TByte <em>TByte</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.TByte\n\t * @generated\n\t */", "public", "Adapter", "createTByteAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.TChar <em>TChar</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.TChar\n\t * @generated\n\t */", "public", "Adapter", "createTCharAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.TShort <em>TShort</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.TShort\n\t * @generated\n\t */", "public", "Adapter", "createTShortAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.TInt <em>TInt</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.TInt\n\t * @generated\n\t */", "public", "Adapter", "createTIntAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.TLong <em>TLong</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.TLong\n\t * @generated\n\t */", "public", "Adapter", "createTLongAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.TFloat <em>TFloat</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.TFloat\n\t * @generated\n\t */", "public", "Adapter", "createTFloatAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.TDouble <em>TDouble</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.TDouble\n\t * @generated\n\t */", "public", "Adapter", "createTDoubleAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Automata.TString <em>TString</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Automata.TString\n\t * @generated\n\t */", "public", "Adapter", "createTStringAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for the default case.\n\t * <!-- begin-user-doc -->\n * This default implementation returns null.\n * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @generated\n\t */", "public", "Adapter", "createEObjectAdapter", "(", ")", "{", "return", "null", ";", "}", "}" ]
<!-- begin-user-doc --> The <b>Adapter Factory</b> for the model.
[ "<!", "--", "begin", "-", "user", "-", "doc", "--", ">", "The", "<b", ">", "Adapter", "Factory<", "/", "b", ">", "for", "the", "model", "." ]
[]
[ { "param": "AdapterFactoryImpl", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AdapterFactoryImpl", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c43ffece6ab4e4be267a82bcf33f2a20eae44185
rtshkmr/tp
src/main/java/seedu/address/model/note/Note.java
[ "MIT" ]
Java
Note
/** * Generic Note class for country and client notes. */
Generic Note class for country and client notes.
[ "Generic", "Note", "class", "for", "country", "and", "client", "notes", "." ]
public class Note { public static final String MESSAGE_CONSTRAINTS = "Notes should not be blank"; private static final Logger logger = LogsCenter.getLogger(Note.class); private final String noteContent; private final Set<Tag> tags = new HashSet<>(); /** * Constructs a Note object with some content in it. * * @param content to be added */ public Note(String content) { requireNonNull(content); noteContent = content; logger.info(String.format("--------------[New Note created with contents: %s]", noteContent)); } /** * Sets the tags of this {@code Note} to the {@code tags} passed in. * * @param tags The set of {@code Tag} objects to be associated with this {@code Note}. */ public void setTags(Set<Tag> tags) { requireAllNonNull(tags); this.tags.clear(); this.tags.addAll(tags); } /** * Gets the content of the note. * * @return The content of the note. */ public String getNoteContent() { return noteContent; } /** * Returns whether this note is a client note. * * @return True if this note is a client note, false otherwise. */ public boolean isClientNote() { return true; } /** * Gets the set of tags that is related to this Note. * * @return The set of tags that is related to this Note. */ public Set<Tag> getTags() { return Collections.unmodifiableSet(tags); } /** * Returns true if a given string is a valid note. */ public static boolean isValidNote(String test) { return !test.trim().isEmpty(); } @Override public boolean equals(Object obj) { // short circuit if same object if (obj == this) { return true; } // instanceof handles nulls if (!(obj instanceof Note)) { return false; } // state check Note c = (Note) obj; boolean hasSameTags = this.tags.equals(c.tags); return this.noteContent.equals(c.noteContent) && hasSameTags; } @Override public String toString() { return noteContent; } @Override public int hashCode() { return Objects.hash(noteContent, tags); } }
[ "public", "class", "Note", "{", "public", "static", "final", "String", "MESSAGE_CONSTRAINTS", "=", "\"", "Notes should not be blank", "\"", ";", "private", "static", "final", "Logger", "logger", "=", "LogsCenter", ".", "getLogger", "(", "Note", ".", "class", ")", ";", "private", "final", "String", "noteContent", ";", "private", "final", "Set", "<", "Tag", ">", "tags", "=", "new", "HashSet", "<", ">", "(", ")", ";", "/**\n * Constructs a Note object with some content in it.\n *\n * @param content to be added\n */", "public", "Note", "(", "String", "content", ")", "{", "requireNonNull", "(", "content", ")", ";", "noteContent", "=", "content", ";", "logger", ".", "info", "(", "String", ".", "format", "(", "\"", "--------------[New Note created with contents: %s]", "\"", ",", "noteContent", ")", ")", ";", "}", "/**\n * Sets the tags of this {@code Note} to the {@code tags} passed in.\n *\n * @param tags The set of {@code Tag} objects to be associated with this {@code Note}.\n */", "public", "void", "setTags", "(", "Set", "<", "Tag", ">", "tags", ")", "{", "requireAllNonNull", "(", "tags", ")", ";", "this", ".", "tags", ".", "clear", "(", ")", ";", "this", ".", "tags", ".", "addAll", "(", "tags", ")", ";", "}", "/**\n * Gets the content of the note.\n *\n * @return The content of the note.\n */", "public", "String", "getNoteContent", "(", ")", "{", "return", "noteContent", ";", "}", "/**\n * Returns whether this note is a client note.\n *\n * @return True if this note is a client note, false otherwise.\n */", "public", "boolean", "isClientNote", "(", ")", "{", "return", "true", ";", "}", "/**\n * Gets the set of tags that is related to this Note.\n *\n * @return The set of tags that is related to this Note.\n */", "public", "Set", "<", "Tag", ">", "getTags", "(", ")", "{", "return", "Collections", ".", "unmodifiableSet", "(", "tags", ")", ";", "}", "/**\n * Returns true if a given string is a valid note.\n */", "public", "static", "boolean", "isValidNote", "(", "String", "test", ")", "{", "return", "!", "test", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "obj", "==", "this", ")", "{", "return", "true", ";", "}", "if", "(", "!", "(", "obj", "instanceof", "Note", ")", ")", "{", "return", "false", ";", "}", "Note", "c", "=", "(", "Note", ")", "obj", ";", "boolean", "hasSameTags", "=", "this", ".", "tags", ".", "equals", "(", "c", ".", "tags", ")", ";", "return", "this", ".", "noteContent", ".", "equals", "(", "c", ".", "noteContent", ")", "&&", "hasSameTags", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "noteContent", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "return", "Objects", ".", "hash", "(", "noteContent", ",", "tags", ")", ";", "}", "}" ]
Generic Note class for country and client notes.
[ "Generic", "Note", "class", "for", "country", "and", "client", "notes", "." ]
[ "// short circuit if same object", "// instanceof handles nulls", "// state check" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c44006c144cf1d9d44d41f7df242d4d3fc2ef14d
dawud-tan/penawaran
app/src/main/java/org/spongycastle/util/io/Streams.java
[ "MIT" ]
Java
Streams
/** * Utility methods to assist with stream processing. */
Utility methods to assist with stream processing.
[ "Utility", "methods", "to", "assist", "with", "stream", "processing", "." ]
public final class Streams { private static int BUFFER_SIZE = 4096; /** * Read stream fully, returning contents in a byte array. * * @param inStr stream to be read. * @return a byte array representing the contents of inStr. * @throws IOException in case of underlying IOException. */ public static byte[] readAll(InputStream inStr) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); pipeAll(inStr, buf); return buf.toByteArray(); } /** * Fully read in buf's length in data, or up to EOF, whichever occurs first, * * @param inStr the stream to be read. * @param buf the buffer to be read into. * @return the number of bytes read into the buffer. * @throws IOException in case of underlying IOException. */ public static int readFully(InputStream inStr, byte[] buf) throws IOException { return readFully(inStr, buf, 0, buf.length); } /** * Fully read in len's bytes of data into buf, or up to EOF, whichever occurs first, * * @param inStr the stream to be read. * @param buf the buffer to be read into. * @param off offset into buf to start putting bytes into. * @param len the number of bytes to be read. * @return the number of bytes read into the buffer. * @throws IOException in case of underlying IOException. */ public static int readFully(InputStream inStr, byte[] buf, int off, int len) throws IOException { int totalRead = 0; while (totalRead < len) { int numRead = inStr.read(buf, off + totalRead, len - totalRead); if (numRead < 0) { break; } totalRead += numRead; } return totalRead; } /** * Write the full contents of inStr to the destination stream outStr. * * @param inStr source input stream. * @param outStr destination output stream. * @throws IOException in case of underlying IOException. */ public static void pipeAll(InputStream inStr, OutputStream outStr) throws IOException { byte[] bs = new byte[BUFFER_SIZE]; int numRead; while ((numRead = inStr.read(bs, 0, bs.length)) >= 0) { outStr.write(bs, 0, numRead); } } }
[ "public", "final", "class", "Streams", "{", "private", "static", "int", "BUFFER_SIZE", "=", "4096", ";", "/**\n * Read stream fully, returning contents in a byte array.\n *\n * @param inStr stream to be read.\n * @return a byte array representing the contents of inStr.\n * @throws IOException in case of underlying IOException.\n */", "public", "static", "byte", "[", "]", "readAll", "(", "InputStream", "inStr", ")", "throws", "IOException", "{", "ByteArrayOutputStream", "buf", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "pipeAll", "(", "inStr", ",", "buf", ")", ";", "return", "buf", ".", "toByteArray", "(", ")", ";", "}", "/**\n * Fully read in buf's length in data, or up to EOF, whichever occurs first,\n *\n * @param inStr the stream to be read.\n * @param buf the buffer to be read into.\n * @return the number of bytes read into the buffer.\n * @throws IOException in case of underlying IOException.\n */", "public", "static", "int", "readFully", "(", "InputStream", "inStr", ",", "byte", "[", "]", "buf", ")", "throws", "IOException", "{", "return", "readFully", "(", "inStr", ",", "buf", ",", "0", ",", "buf", ".", "length", ")", ";", "}", "/**\n * Fully read in len's bytes of data into buf, or up to EOF, whichever occurs first,\n *\n * @param inStr the stream to be read.\n * @param buf the buffer to be read into.\n * @param off offset into buf to start putting bytes into.\n * @param len the number of bytes to be read.\n * @return the number of bytes read into the buffer.\n * @throws IOException in case of underlying IOException.\n */", "public", "static", "int", "readFully", "(", "InputStream", "inStr", ",", "byte", "[", "]", "buf", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "int", "totalRead", "=", "0", ";", "while", "(", "totalRead", "<", "len", ")", "{", "int", "numRead", "=", "inStr", ".", "read", "(", "buf", ",", "off", "+", "totalRead", ",", "len", "-", "totalRead", ")", ";", "if", "(", "numRead", "<", "0", ")", "{", "break", ";", "}", "totalRead", "+=", "numRead", ";", "}", "return", "totalRead", ";", "}", "/**\n * Write the full contents of inStr to the destination stream outStr.\n *\n * @param inStr source input stream.\n * @param outStr destination output stream.\n * @throws IOException in case of underlying IOException.\n */", "public", "static", "void", "pipeAll", "(", "InputStream", "inStr", ",", "OutputStream", "outStr", ")", "throws", "IOException", "{", "byte", "[", "]", "bs", "=", "new", "byte", "[", "BUFFER_SIZE", "]", ";", "int", "numRead", ";", "while", "(", "(", "numRead", "=", "inStr", ".", "read", "(", "bs", ",", "0", ",", "bs", ".", "length", ")", ")", ">=", "0", ")", "{", "outStr", ".", "write", "(", "bs", ",", "0", ",", "numRead", ")", ";", "}", "}", "}" ]
Utility methods to assist with stream processing.
[ "Utility", "methods", "to", "assist", "with", "stream", "processing", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c440cb9f138b426d676f6363412f99802954f120
licaon-kter/atalk-android
aTalk/src/main/java/org/jivesoftware/smackx/bob/provider/BoBProvider.java
[ "Apache-2.0" ]
Java
BoBProvider
/** * The <tt>BoBProvider</tt> is an extension element provider that is meant to be used for * thumbnail & captcha requests and responses. Implementing XEP-0231: Bits of Binary * * @author Eng Chong Meng */
The BoBProvider is an extension element provider that is meant to be used for thumbnail & captcha requests and responses. Implementing XEP-0231: Bits of Binary @author Eng Chong Meng
[ "The", "BoBProvider", "is", "an", "extension", "element", "provider", "that", "is", "meant", "to", "be", "used", "for", "thumbnail", "&", "captcha", "requests", "and", "responses", ".", "Implementing", "XEP", "-", "0231", ":", "Bits", "of", "Binary", "@author", "Eng", "Chong", "Meng" ]
public class BoBProvider extends ExtensionElementProvider<BoB> { /** * Parses the given <tt>XmlPullParser</tt> into a BoB packet and returns it. * Note: parse first XmlPullParser.OPEN_TAG is already consumed on first entry. * XEP-0231: Bits of Binary * * <data xmlns='urn:xmpp:tmp:bob' * cid='sha1+8f35fef110ffc5df08d579a50083ff9308fb6242@bob.xmpp.org'/> * max-age='86400' * type='image/png'> * iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP * ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0 * vr4MkhoXe0rZigAAAABJRU5ErkJggg== * </data> * * @see ExtensionElementProvider#parse(XmlPullParser, int) */ @Override public BoB parse(XmlPullParser parser, int initialDepth) throws Exception { long maxAge = 0; String data = ""; String cid = parser.getAttributeValue("", BoB.ATTR_CID); String age = parser.getAttributeValue("", BoB.ATTR_MAX_AGE); if (!StringUtils.isNullOrEmpty(age)) maxAge = Integer.parseInt(age); String mimeType = parser.getAttributeValue("", "type"); // outerloop: while (true) { // int eventType = parser.next(); // switch (eventType) { // case XmlPullParser.TEXT: // data = parser.getText(); // break; // case XmlPullParser.END_TAG: // if (parser.getDepth() == initialDepth) { // break outerloop; // } // break; // } // } boolean done = false; while (!done) { int eventType = parser.next(); if (eventType == XmlPullParser.TEXT) { data = parser.getText(); } else if (eventType == XmlPullParser.END_TAG) { if (BoB.ELEMENT.equals(parser.getName())) { done = true; } } } return new BoB(cid, maxAge, mimeType, data); } }
[ "public", "class", "BoBProvider", "extends", "ExtensionElementProvider", "<", "BoB", ">", "{", "/**\n * Parses the given <tt>XmlPullParser</tt> into a BoB packet and returns it.\n * Note: parse first XmlPullParser.OPEN_TAG is already consumed on first entry.\n * XEP-0231: Bits of Binary\n *\n * <data xmlns='urn:xmpp:tmp:bob'\n * cid='sha1+8f35fef110ffc5df08d579a50083ff9308fb6242@bob.xmpp.org'/>\n * max-age='86400'\n * type='image/png'>\n * iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP\n * ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0\n * vr4MkhoXe0rZigAAAABJRU5ErkJggg==\n * </data>\n *\n * @see ExtensionElementProvider#parse(XmlPullParser, int)\n */", "@", "Override", "public", "BoB", "parse", "(", "XmlPullParser", "parser", ",", "int", "initialDepth", ")", "throws", "Exception", "{", "long", "maxAge", "=", "0", ";", "String", "data", "=", "\"", "\"", ";", "String", "cid", "=", "parser", ".", "getAttributeValue", "(", "\"", "\"", ",", "BoB", ".", "ATTR_CID", ")", ";", "String", "age", "=", "parser", ".", "getAttributeValue", "(", "\"", "\"", ",", "BoB", ".", "ATTR_MAX_AGE", ")", ";", "if", "(", "!", "StringUtils", ".", "isNullOrEmpty", "(", "age", ")", ")", "maxAge", "=", "Integer", ".", "parseInt", "(", "age", ")", ";", "String", "mimeType", "=", "parser", ".", "getAttributeValue", "(", "\"", "\"", ",", "\"", "type", "\"", ")", ";", "boolean", "done", "=", "false", ";", "while", "(", "!", "done", ")", "{", "int", "eventType", "=", "parser", ".", "next", "(", ")", ";", "if", "(", "eventType", "==", "XmlPullParser", ".", "TEXT", ")", "{", "data", "=", "parser", ".", "getText", "(", ")", ";", "}", "else", "if", "(", "eventType", "==", "XmlPullParser", ".", "END_TAG", ")", "{", "if", "(", "BoB", ".", "ELEMENT", ".", "equals", "(", "parser", ".", "getName", "(", ")", ")", ")", "{", "done", "=", "true", ";", "}", "}", "}", "return", "new", "BoB", "(", "cid", ",", "maxAge", ",", "mimeType", ",", "data", ")", ";", "}", "}" ]
The <tt>BoBProvider</tt> is an extension element provider that is meant to be used for thumbnail & captcha requests and responses.
[ "The", "<tt", ">", "BoBProvider<", "/", "tt", ">", "is", "an", "extension", "element", "provider", "that", "is", "meant", "to", "be", "used", "for", "thumbnail", "&", "captcha", "requests", "and", "responses", "." ]
[ "// outerloop: while (true) {", "// int eventType = parser.next();", "// switch (eventType) {", "// case XmlPullParser.TEXT:", "// data = parser.getText();", "// break;", "// case XmlPullParser.END_TAG:", "// if (parser.getDepth() == initialDepth) {", "// break outerloop;", "// }", "// break;", "// }", "// }" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c442cb70dcde2afd24a936f80868ee08eaa85a5a
qingye5x/disunity
src/info/ata4/unity/cli/cmd/BundleListCmd.java
[ "Unlicense" ]
Java
BundleListCmd
/** * * @author Nico Bergemann <barracuda415 at yahoo.de> */
@author Nico Bergemann
[ "@author", "Nico", "Bergemann" ]
@Parameters( commandNames = "bundle-list", commandDescription = "List files contained in asset bundles." ) public class BundleListCmd extends AssetCommand { private final PrintStream ps; public BundleListCmd(PrintStream ps) { this.ps = ps; setProcessAssets(false); setProcessBundledAssets(false); } @Override public void processAssetBundle(AssetBundle bundle) throws IOException { int p1 = 64; int p2 = 10; ps.print(StringUtils.rightPad("Path", p1)); ps.print(" | "); ps.print(StringUtils.leftPad("Size", p2)); ps.println(); ps.print(StringUtils.repeat("-", p1)); ps.print(" | "); ps.print(StringUtils.repeat("-", p2)); ps.println(); for (Map.Entry<String, ByteBuffer> entry : bundle.getEntries().entrySet()) { ps.print(StringUtils.rightPad(entry.getKey(), p1)); ps.print(" | "); ps.print(StringUtils.leftPad(String.valueOf(entry.getValue().limit()), p2)); ps.println(); } } }
[ "@", "Parameters", "(", "commandNames", "=", "\"", "bundle-list", "\"", ",", "commandDescription", "=", "\"", "List files contained in asset bundles.", "\"", ")", "public", "class", "BundleListCmd", "extends", "AssetCommand", "{", "private", "final", "PrintStream", "ps", ";", "public", "BundleListCmd", "(", "PrintStream", "ps", ")", "{", "this", ".", "ps", "=", "ps", ";", "setProcessAssets", "(", "false", ")", ";", "setProcessBundledAssets", "(", "false", ")", ";", "}", "@", "Override", "public", "void", "processAssetBundle", "(", "AssetBundle", "bundle", ")", "throws", "IOException", "{", "int", "p1", "=", "64", ";", "int", "p2", "=", "10", ";", "ps", ".", "print", "(", "StringUtils", ".", "rightPad", "(", "\"", "Path", "\"", ",", "p1", ")", ")", ";", "ps", ".", "print", "(", "\"", " | ", "\"", ")", ";", "ps", ".", "print", "(", "StringUtils", ".", "leftPad", "(", "\"", "Size", "\"", ",", "p2", ")", ")", ";", "ps", ".", "println", "(", ")", ";", "ps", ".", "print", "(", "StringUtils", ".", "repeat", "(", "\"", "-", "\"", ",", "p1", ")", ")", ";", "ps", ".", "print", "(", "\"", " | ", "\"", ")", ";", "ps", ".", "print", "(", "StringUtils", ".", "repeat", "(", "\"", "-", "\"", ",", "p2", ")", ")", ";", "ps", ".", "println", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "ByteBuffer", ">", "entry", ":", "bundle", ".", "getEntries", "(", ")", ".", "entrySet", "(", ")", ")", "{", "ps", ".", "print", "(", "StringUtils", ".", "rightPad", "(", "entry", ".", "getKey", "(", ")", ",", "p1", ")", ")", ";", "ps", ".", "print", "(", "\"", " | ", "\"", ")", ";", "ps", ".", "print", "(", "StringUtils", ".", "leftPad", "(", "String", ".", "valueOf", "(", "entry", ".", "getValue", "(", ")", ".", "limit", "(", ")", ")", ",", "p2", ")", ")", ";", "ps", ".", "println", "(", ")", ";", "}", "}", "}" ]
@author Nico Bergemann <barracuda415 at yahoo.de>
[ "@author", "Nico", "Bergemann", "<barracuda415", "at", "yahoo", ".", "de", ">" ]
[]
[ { "param": "AssetCommand", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AssetCommand", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c448a7fadb6da13833f32319ced8d69d102f3dca
ponfee/commons-core
src/main/java/code/ponfee/commons/exception/UnimplementedException.java
[ "MIT" ]
Java
UnimplementedException
/** * Unimplemented exception definition * * @author Ponfee */
Unimplemented exception definition @author Ponfee
[ "Unimplemented", "exception", "definition", "@author", "Ponfee" ]
public class UnimplementedException extends BaseException { private static final long serialVersionUID = -5983398403463732650L; private static final int CODE = ResultCode.SERVER_UNSUPPORT.getCode(); public UnimplementedException() { super(CODE); } public UnimplementedException(String message) { super(CODE, message); } public UnimplementedException(Throwable cause) { super(CODE, cause); } public UnimplementedException(String message, Throwable cause) { super(CODE, message, cause); } public UnimplementedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(CODE, message, cause, enableSuppression, writableStackTrace); } }
[ "public", "class", "UnimplementedException", "extends", "BaseException", "{", "private", "static", "final", "long", "serialVersionUID", "=", "-", "5983398403463732650L", ";", "private", "static", "final", "int", "CODE", "=", "ResultCode", ".", "SERVER_UNSUPPORT", ".", "getCode", "(", ")", ";", "public", "UnimplementedException", "(", ")", "{", "super", "(", "CODE", ")", ";", "}", "public", "UnimplementedException", "(", "String", "message", ")", "{", "super", "(", "CODE", ",", "message", ")", ";", "}", "public", "UnimplementedException", "(", "Throwable", "cause", ")", "{", "super", "(", "CODE", ",", "cause", ")", ";", "}", "public", "UnimplementedException", "(", "String", "message", ",", "Throwable", "cause", ")", "{", "super", "(", "CODE", ",", "message", ",", "cause", ")", ";", "}", "public", "UnimplementedException", "(", "String", "message", ",", "Throwable", "cause", ",", "boolean", "enableSuppression", ",", "boolean", "writableStackTrace", ")", "{", "super", "(", "CODE", ",", "message", ",", "cause", ",", "enableSuppression", ",", "writableStackTrace", ")", ";", "}", "}" ]
Unimplemented exception definition
[ "Unimplemented", "exception", "definition" ]
[]
[ { "param": "BaseException", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseException", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c44e6699ad9ef42ce1ecb7f71cf19399fb7d4de3
liveqmock/ares-studio
core/com.hundsun.ares.studio.emfadapter/src/com/hundsun/ares/studio/model/util/ModelAdapterFactory.java
[ "MIT" ]
Java
ModelAdapterFactory
/** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see com.hundsun.ares.studio.model.ModelPackage * @generated */
The Adapter Factory for the model. It provides an adapter createXXX method for each class of the model.
[ "The", "Adapter", "Factory", "for", "the", "model", ".", "It", "provides", "an", "adapter", "createXXX", "method", "for", "each", "class", "of", "the", "model", "." ]
public class ModelAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static ModelPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ModelAdapterFactory() { if (modelPackage == null) { modelPackage = ModelPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject)object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ModelSwitch<Adapter> modelSwitch = new ModelSwitch<Adapter>() { @Override public Adapter caseEmfExtendAble(EmfExtendAble object) { return createEmfExtendAbleAdapter(); } @Override public Adapter caseIExtendAbleModel(IExtendAbleModel object) { return createIExtendAbleModelAdapter(); } @Override public Adapter caseStringMapEntry(Map.Entry<String, String> object) { return createStringMapEntryAdapter(); } @Override public Adapter caseEMapImprove(EMapImprove object) { return createEMapImproveAdapter(); } @Override public Adapter caseIExtendFieldModel(IExtendFieldModel object) { return createIExtendFieldModelAdapter(); } @Override public Adapter caseMap(Map object) { return createMapAdapter(); } @Override public Adapter caseExtendFieldModel(ExtendFieldModel object) { return createExtendFieldModelAdapter(); } @Override public Adapter defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { return modelSwitch.doSwitch((EObject)target); } /** * Creates a new adapter for an object of class '{@link com.hundsun.ares.studio.model.EmfExtendAble <em>Emf Extend Able</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see com.hundsun.ares.studio.model.EmfExtendAble * @generated */ public Adapter createEmfExtendAbleAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link IExtendAbleModel <em>IExtend Able Model</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see IExtendAbleModel * @generated */ public Adapter createIExtendAbleModelAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link java.util.Map.Entry <em>String Map Entry</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see java.util.Map.Entry * @generated */ public Adapter createStringMapEntryAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link com.hundsun.ares.studio.model.EMapImprove <em>EMap Improve</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see com.hundsun.ares.studio.model.EMapImprove * @generated */ public Adapter createEMapImproveAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link IExtendFieldModel <em>IExtend Field Model</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see IExtendFieldModel * @generated */ public Adapter createIExtendFieldModelAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link Map <em>Map</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see Map * @generated */ public Adapter createMapAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link com.hundsun.ares.studio.model.ExtendFieldModel <em>Extend Field Model</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see com.hundsun.ares.studio.model.ExtendFieldModel * @generated */ public Adapter createExtendFieldModelAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } }
[ "public", "class", "ModelAdapterFactory", "extends", "AdapterFactoryImpl", "{", "/**\n\t * The cached model package.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "protected", "static", "ModelPackage", "modelPackage", ";", "/**\n\t * Creates an instance of the adapter factory.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "public", "ModelAdapterFactory", "(", ")", "{", "if", "(", "modelPackage", "==", "null", ")", "{", "modelPackage", "=", "ModelPackage", ".", "eINSTANCE", ";", "}", "}", "/**\n\t * Returns whether this factory is applicable for the type of the object.\n\t * <!-- begin-user-doc -->\n\t * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model.\n\t * <!-- end-user-doc -->\n\t * @return whether this factory is applicable for the type of the object.\n\t * @generated\n\t */", "@", "Override", "public", "boolean", "isFactoryForType", "(", "Object", "object", ")", "{", "if", "(", "object", "==", "modelPackage", ")", "{", "return", "true", ";", "}", "if", "(", "object", "instanceof", "EObject", ")", "{", "return", "(", "(", "EObject", ")", "object", ")", ".", "eClass", "(", ")", ".", "getEPackage", "(", ")", "==", "modelPackage", ";", "}", "return", "false", ";", "}", "/**\n\t * The switch that delegates to the <code>createXXX</code> methods.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "protected", "ModelSwitch", "<", "Adapter", ">", "modelSwitch", "=", "new", "ModelSwitch", "<", "Adapter", ">", "(", ")", "{", "@", "Override", "public", "Adapter", "caseEmfExtendAble", "(", "EmfExtendAble", "object", ")", "{", "return", "createEmfExtendAbleAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseIExtendAbleModel", "(", "IExtendAbleModel", "object", ")", "{", "return", "createIExtendAbleModelAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseStringMapEntry", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "object", ")", "{", "return", "createStringMapEntryAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseEMapImprove", "(", "EMapImprove", "object", ")", "{", "return", "createEMapImproveAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseIExtendFieldModel", "(", "IExtendFieldModel", "object", ")", "{", "return", "createIExtendFieldModelAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseMap", "(", "Map", "object", ")", "{", "return", "createMapAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "caseExtendFieldModel", "(", "ExtendFieldModel", "object", ")", "{", "return", "createExtendFieldModelAdapter", "(", ")", ";", "}", "@", "Override", "public", "Adapter", "defaultCase", "(", "EObject", "object", ")", "{", "return", "createEObjectAdapter", "(", ")", ";", "}", "}", ";", "/**\n\t * Creates an adapter for the <code>target</code>.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param target the object to adapt.\n\t * @return the adapter for the <code>target</code>.\n\t * @generated\n\t */", "@", "Override", "public", "Adapter", "createAdapter", "(", "Notifier", "target", ")", "{", "return", "modelSwitch", ".", "doSwitch", "(", "(", "EObject", ")", "target", ")", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link com.hundsun.ares.studio.model.EmfExtendAble <em>Emf Extend Able</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see com.hundsun.ares.studio.model.EmfExtendAble\n\t * @generated\n\t */", "public", "Adapter", "createEmfExtendAbleAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link IExtendAbleModel <em>IExtend Able Model</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see IExtendAbleModel\n\t * @generated\n\t */", "public", "Adapter", "createIExtendAbleModelAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link java.util.Map.Entry <em>String Map Entry</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see java.util.Map.Entry\n\t * @generated\n\t */", "public", "Adapter", "createStringMapEntryAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link com.hundsun.ares.studio.model.EMapImprove <em>EMap Improve</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see com.hundsun.ares.studio.model.EMapImprove\n\t * @generated\n\t */", "public", "Adapter", "createEMapImproveAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link IExtendFieldModel <em>IExtend Field Model</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see IExtendFieldModel\n\t * @generated\n\t */", "public", "Adapter", "createIExtendFieldModelAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link Map <em>Map</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see Map\n\t * @generated\n\t */", "public", "Adapter", "createMapAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for an object of class '{@link com.hundsun.ares.studio.model.ExtendFieldModel <em>Extend Field Model</em>}'.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null so that we can easily ignore cases;\n\t * it's useful to ignore a case when inheritance will catch all the cases anyway.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @see com.hundsun.ares.studio.model.ExtendFieldModel\n\t * @generated\n\t */", "public", "Adapter", "createExtendFieldModelAdapter", "(", ")", "{", "return", "null", ";", "}", "/**\n\t * Creates a new adapter for the default case.\n\t * <!-- begin-user-doc -->\n\t * This default implementation returns null.\n\t * <!-- end-user-doc -->\n\t * @return the new adapter.\n\t * @generated\n\t */", "public", "Adapter", "createEObjectAdapter", "(", ")", "{", "return", "null", ";", "}", "}" ]
<!-- begin-user-doc --> The <b>Adapter Factory</b> for the model.
[ "<!", "--", "begin", "-", "user", "-", "doc", "--", ">", "The", "<b", ">", "Adapter", "Factory<", "/", "b", ">", "for", "the", "model", "." ]
[]
[ { "param": "AdapterFactoryImpl", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AdapterFactoryImpl", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c4524eb4d4a3780259cf85bd0e01573dbd2ee9fa
JoshTDN03/scalecube-config
config-vault/src/main/java/io/scalecube/config/vault/VaultConfigSource.java
[ "Apache-2.0" ]
Java
VaultConfigSource
/** * This class is an implementation of {@link ConfigSource} for Vault. * * @see <a href="https://www.vaultproject.io/">Vault Project</a> */
This class is an implementation of ConfigSource for Vault. @see Vault Project
[ "This", "class", "is", "an", "implementation", "of", "ConfigSource", "for", "Vault", ".", "@see", "Vault", "Project" ]
public class VaultConfigSource implements ConfigSource { private static final Logger LOGGER = LoggerFactory.getLogger(VaultConfigSource.class); private static final EnvironmentLoader ENVIRONMENT_LOADER = new EnvironmentLoader(); private static final String PATHS_SEPARATOR = ":"; private final VaultInvoker vault; private final Collection<String> secretsPaths; private VaultConfigSource(VaultInvoker vault, Collection<String> secretsPaths) { this.vault = vault; this.secretsPaths = new ArrayList<>(secretsPaths); } @Override public Map<String, ConfigProperty> loadConfig() { Map<String, ConfigProperty> result = new HashMap<>(); for (String path : secretsPaths) { try { LogicalResponse response = vault.invoke(vault -> vault.logical().read(path)); final Map<String, LoadedConfigProperty> pathProps = response.getData().entrySet().stream() .map(LoadedConfigProperty::withNameAndValue) .map(LoadedConfigProperty.Builder::build) .collect(Collectors.toMap(LoadedConfigProperty::name, Function.identity())); result.putAll(pathProps); } catch (VaultException ex) { if (ex.getHttpStatusCode() == 404) { LOGGER.warn("Unable to load config properties from: {}", path); } else { throw new ConfigSourceNotAvailableException(ex); } } catch (Exception ex) { LOGGER.error("Unable to load config properties from: {}, cause:", path, ex); throw new ConfigSourceNotAvailableException(ex); } } return result; } public static Builder builder() { return new Builder(); } public static final class Builder { private Function<VaultInvoker.Builder, VaultInvoker.Builder> builderFunction = Function.identity(); private VaultInvoker invoker; private Set<String> secretsPaths = Optional.ofNullable( Optional.ofNullable(ENVIRONMENT_LOADER.loadVariable("VAULT_SECRETS_PATH")) .orElse(ENVIRONMENT_LOADER.loadVariable("VAULT_SECRETS_PATHS"))) .map(s -> s.split(PATHS_SEPARATOR)) .map(Arrays::asList) .map(HashSet::new) .orElseGet(HashSet::new); private Builder() {} /** * Appends {@code secretsPath} to {@code secretsPaths}. * * @param secretsPath secretsPath (may contain value with paths separated by {@code :}) * @return this builder * @deprecated will be removed in future releases without notice, use {@link * #addSecretsPath(String...)} or {@link #secretsPaths(Collection)}. */ @Deprecated public Builder secretsPath(String secretsPath) { this.secretsPaths.addAll(toSecretsPaths(Collections.singletonList(secretsPath))); return this; } /** * Appends one or several secretsPath\es to {@code secretsPaths}. * * @param secretsPath one or several secretsPath\es (each value may contain paths separated by * {@code :}) * @return this builder */ public Builder addSecretsPath(String... secretsPath) { this.secretsPaths.addAll(toSecretsPaths(Arrays.asList(secretsPath))); return this; } /** * Setter for {@code secretsPaths}. * * @param secretsPaths collection of secretsPath\es (each value may contain paths separated by * colon) * @return this builder */ public Builder secretsPaths(Collection<String> secretsPaths) { this.secretsPaths = toSecretsPaths(secretsPaths); return this; } private static Set<String> toSecretsPaths(Collection<String> secretsPaths) { return secretsPaths.stream() .flatMap(s -> Arrays.stream(s.split(PATHS_SEPARATOR))) .collect(Collectors.toSet()); } public Builder invoker(VaultInvoker invoker) { this.invoker = invoker; return this; } public Builder vault(UnaryOperator<VaultInvoker.Builder> opts) { this.builderFunction = this.builderFunction.andThen(opts); return this; } public Builder config(UnaryOperator<VaultConfig> vaultConfig) { this.builderFunction = this.builderFunction.andThen(b -> b.options(vaultConfig)); return this; } public Builder tokenSupplier(VaultTokenSupplier supplier) { this.builderFunction = this.builderFunction.andThen(b -> b.tokenSupplier(supplier)); return this; } /** * Builds vault config source. * * @return instance of {@link VaultConfigSource} */ public VaultConfigSource build() { return new VaultConfigSource( invoker != null ? invoker : builderFunction.apply(new VaultInvoker.Builder()).build(), secretsPaths); } } }
[ "public", "class", "VaultConfigSource", "implements", "ConfigSource", "{", "private", "static", "final", "Logger", "LOGGER", "=", "LoggerFactory", ".", "getLogger", "(", "VaultConfigSource", ".", "class", ")", ";", "private", "static", "final", "EnvironmentLoader", "ENVIRONMENT_LOADER", "=", "new", "EnvironmentLoader", "(", ")", ";", "private", "static", "final", "String", "PATHS_SEPARATOR", "=", "\"", ":", "\"", ";", "private", "final", "VaultInvoker", "vault", ";", "private", "final", "Collection", "<", "String", ">", "secretsPaths", ";", "private", "VaultConfigSource", "(", "VaultInvoker", "vault", ",", "Collection", "<", "String", ">", "secretsPaths", ")", "{", "this", ".", "vault", "=", "vault", ";", "this", ".", "secretsPaths", "=", "new", "ArrayList", "<", ">", "(", "secretsPaths", ")", ";", "}", "@", "Override", "public", "Map", "<", "String", ",", "ConfigProperty", ">", "loadConfig", "(", ")", "{", "Map", "<", "String", ",", "ConfigProperty", ">", "result", "=", "new", "HashMap", "<", ">", "(", ")", ";", "for", "(", "String", "path", ":", "secretsPaths", ")", "{", "try", "{", "LogicalResponse", "response", "=", "vault", ".", "invoke", "(", "vault", "->", "vault", ".", "logical", "(", ")", ".", "read", "(", "path", ")", ")", ";", "final", "Map", "<", "String", ",", "LoadedConfigProperty", ">", "pathProps", "=", "response", ".", "getData", "(", ")", ".", "entrySet", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "LoadedConfigProperty", "::", "withNameAndValue", ")", ".", "map", "(", "LoadedConfigProperty", ".", "Builder", "::", "build", ")", ".", "collect", "(", "Collectors", ".", "toMap", "(", "LoadedConfigProperty", "::", "name", ",", "Function", ".", "identity", "(", ")", ")", ")", ";", "result", ".", "putAll", "(", "pathProps", ")", ";", "}", "catch", "(", "VaultException", "ex", ")", "{", "if", "(", "ex", ".", "getHttpStatusCode", "(", ")", "==", "404", ")", "{", "LOGGER", ".", "warn", "(", "\"", "Unable to load config properties from: {}", "\"", ",", "path", ")", ";", "}", "else", "{", "throw", "new", "ConfigSourceNotAvailableException", "(", "ex", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "LOGGER", ".", "error", "(", "\"", "Unable to load config properties from: {}, cause:", "\"", ",", "path", ",", "ex", ")", ";", "throw", "new", "ConfigSourceNotAvailableException", "(", "ex", ")", ";", "}", "}", "return", "result", ";", "}", "public", "static", "Builder", "builder", "(", ")", "{", "return", "new", "Builder", "(", ")", ";", "}", "public", "static", "final", "class", "Builder", "{", "private", "Function", "<", "VaultInvoker", ".", "Builder", ",", "VaultInvoker", ".", "Builder", ">", "builderFunction", "=", "Function", ".", "identity", "(", ")", ";", "private", "VaultInvoker", "invoker", ";", "private", "Set", "<", "String", ">", "secretsPaths", "=", "Optional", ".", "ofNullable", "(", "Optional", ".", "ofNullable", "(", "ENVIRONMENT_LOADER", ".", "loadVariable", "(", "\"", "VAULT_SECRETS_PATH", "\"", ")", ")", ".", "orElse", "(", "ENVIRONMENT_LOADER", ".", "loadVariable", "(", "\"", "VAULT_SECRETS_PATHS", "\"", ")", ")", ")", ".", "map", "(", "s", "->", "s", ".", "split", "(", "PATHS_SEPARATOR", ")", ")", ".", "map", "(", "Arrays", "::", "asList", ")", ".", "map", "(", "HashSet", "::", "new", ")", ".", "orElseGet", "(", "HashSet", "::", "new", ")", ";", "private", "Builder", "(", ")", "{", "}", "/**\n * Appends {@code secretsPath} to {@code secretsPaths}.\n *\n * @param secretsPath secretsPath (may contain value with paths separated by {@code :})\n * @return this builder\n * @deprecated will be removed in future releases without notice, use {@link\n * #addSecretsPath(String...)} or {@link #secretsPaths(Collection)}.\n */", "@", "Deprecated", "public", "Builder", "secretsPath", "(", "String", "secretsPath", ")", "{", "this", ".", "secretsPaths", ".", "addAll", "(", "toSecretsPaths", "(", "Collections", ".", "singletonList", "(", "secretsPath", ")", ")", ")", ";", "return", "this", ";", "}", "/**\n * Appends one or several secretsPath\\es to {@code secretsPaths}.\n *\n * @param secretsPath one or several secretsPath\\es (each value may contain paths separated by\n * {@code :})\n * @return this builder\n */", "public", "Builder", "addSecretsPath", "(", "String", "...", "secretsPath", ")", "{", "this", ".", "secretsPaths", ".", "addAll", "(", "toSecretsPaths", "(", "Arrays", ".", "asList", "(", "secretsPath", ")", ")", ")", ";", "return", "this", ";", "}", "/**\n * Setter for {@code secretsPaths}.\n *\n * @param secretsPaths collection of secretsPath\\es (each value may contain paths separated by\n * colon)\n * @return this builder\n */", "public", "Builder", "secretsPaths", "(", "Collection", "<", "String", ">", "secretsPaths", ")", "{", "this", ".", "secretsPaths", "=", "toSecretsPaths", "(", "secretsPaths", ")", ";", "return", "this", ";", "}", "private", "static", "Set", "<", "String", ">", "toSecretsPaths", "(", "Collection", "<", "String", ">", "secretsPaths", ")", "{", "return", "secretsPaths", ".", "stream", "(", ")", ".", "flatMap", "(", "s", "->", "Arrays", ".", "stream", "(", "s", ".", "split", "(", "PATHS_SEPARATOR", ")", ")", ")", ".", "collect", "(", "Collectors", ".", "toSet", "(", ")", ")", ";", "}", "public", "Builder", "invoker", "(", "VaultInvoker", "invoker", ")", "{", "this", ".", "invoker", "=", "invoker", ";", "return", "this", ";", "}", "public", "Builder", "vault", "(", "UnaryOperator", "<", "VaultInvoker", ".", "Builder", ">", "opts", ")", "{", "this", ".", "builderFunction", "=", "this", ".", "builderFunction", ".", "andThen", "(", "opts", ")", ";", "return", "this", ";", "}", "public", "Builder", "config", "(", "UnaryOperator", "<", "VaultConfig", ">", "vaultConfig", ")", "{", "this", ".", "builderFunction", "=", "this", ".", "builderFunction", ".", "andThen", "(", "b", "->", "b", ".", "options", "(", "vaultConfig", ")", ")", ";", "return", "this", ";", "}", "public", "Builder", "tokenSupplier", "(", "VaultTokenSupplier", "supplier", ")", "{", "this", ".", "builderFunction", "=", "this", ".", "builderFunction", ".", "andThen", "(", "b", "->", "b", ".", "tokenSupplier", "(", "supplier", ")", ")", ";", "return", "this", ";", "}", "/**\n * Builds vault config source.\n *\n * @return instance of {@link VaultConfigSource}\n */", "public", "VaultConfigSource", "build", "(", ")", "{", "return", "new", "VaultConfigSource", "(", "invoker", "!=", "null", "?", "invoker", ":", "builderFunction", ".", "apply", "(", "new", "VaultInvoker", ".", "Builder", "(", ")", ")", ".", "build", "(", ")", ",", "secretsPaths", ")", ";", "}", "}", "}" ]
This class is an implementation of {@link ConfigSource} for Vault.
[ "This", "class", "is", "an", "implementation", "of", "{", "@link", "ConfigSource", "}", "for", "Vault", "." ]
[]
[ { "param": "ConfigSource", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ConfigSource", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c452e29b49389ed83be379f2d189c37a8c7c48f7
rondinelisaad/lockss-daemon
src/org/lockss/protocol/psm/PsmResponse.java
[ "BSD-3-Clause" ]
Java
PsmResponse
/** * PsmResponse maps an event to a response, which is either an action or a * the name of new state to which to transition. Responses match all * events that are subsumed by the response's event, so the order in which * they appear in a state's response array is important. */
PsmResponse maps an event to a response, which is either an action or a the name of new state to which to transition. Responses match all events that are subsumed by the response's event, so the order in which they appear in a state's response array is important.
[ "PsmResponse", "maps", "an", "event", "to", "a", "response", "which", "is", "either", "an", "action", "or", "a", "the", "name", "of", "new", "state", "to", "which", "to", "transition", ".", "Responses", "match", "all", "events", "that", "are", "subsumed", "by", "the", "response", "'", "s", "event", "so", "the", "order", "in", "which", "they", "appear", "in", "a", "state", "'", "s", "response", "array", "is", "important", "." ]
public class PsmResponse { private PsmEvent event; private String newState; private PsmAction action; /** Create a response that maps the event to the named new state. * @param event the pattern event against which incoming events are matched * @param newState name of state to transition to if matching event is * signalled. */ public PsmResponse(PsmEvent event, String newState) { if (event == null) { throw new PsmException.IllegalStateMachine("event is null"); } if (StringUtil.isNullString(newState)) { throw new PsmException.IllegalStateMachine("newState is null string"); } this.event = event; this.newState = newState; } /** Create a response that maps the event to the specified action. * @param event the pattern event against which incoming events are matched * @param action the action to perform if matching event is signalled. */ public PsmResponse(PsmEvent event, PsmAction action) { if (event == null) throw new PsmException.IllegalStateMachine("event is null"); if (action == null) throw new PsmException.IllegalStateMachine("action is null"); this.event = event; this.action = action; } /** Return the event against which incoming events are matched */ public PsmEvent getEvent() { return event; } /** Return true if the reponse to the event is to transition to a new * state */ public boolean isTransition() { return newState != null; } /** Return true if the reponse to the event is to perform an action */ public boolean isAction() { return action != null; } /** Return the new state, iff a transition response */ public String getNewState() { return newState; } /** Return the action, iff an action response */ public PsmAction getAction() { return action; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[Resp: "); sb.append(event); sb.append(" -> "); if (isAction()) { sb.append(action); } else if (isTransition()) { sb.append(newState); } else { sb.append("[???]"); } sb.append("]"); return sb.toString(); } }
[ "public", "class", "PsmResponse", "{", "private", "PsmEvent", "event", ";", "private", "String", "newState", ";", "private", "PsmAction", "action", ";", "/** Create a response that maps the event to the named new state.\n * @param event the pattern event against which incoming events are matched\n * @param newState name of state to transition to if matching event is\n * signalled.\n */", "public", "PsmResponse", "(", "PsmEvent", "event", ",", "String", "newState", ")", "{", "if", "(", "event", "==", "null", ")", "{", "throw", "new", "PsmException", ".", "IllegalStateMachine", "(", "\"", "event is null", "\"", ")", ";", "}", "if", "(", "StringUtil", ".", "isNullString", "(", "newState", ")", ")", "{", "throw", "new", "PsmException", ".", "IllegalStateMachine", "(", "\"", "newState is null string", "\"", ")", ";", "}", "this", ".", "event", "=", "event", ";", "this", ".", "newState", "=", "newState", ";", "}", "/** Create a response that maps the event to the specified action.\n * @param event the pattern event against which incoming events are matched\n * @param action the action to perform if matching event is signalled.\n */", "public", "PsmResponse", "(", "PsmEvent", "event", ",", "PsmAction", "action", ")", "{", "if", "(", "event", "==", "null", ")", "throw", "new", "PsmException", ".", "IllegalStateMachine", "(", "\"", "event is null", "\"", ")", ";", "if", "(", "action", "==", "null", ")", "throw", "new", "PsmException", ".", "IllegalStateMachine", "(", "\"", "action is null", "\"", ")", ";", "this", ".", "event", "=", "event", ";", "this", ".", "action", "=", "action", ";", "}", "/** Return the event against which incoming events are matched */", "public", "PsmEvent", "getEvent", "(", ")", "{", "return", "event", ";", "}", "/** Return true if the reponse to the event is to transition to a new\n * state */", "public", "boolean", "isTransition", "(", ")", "{", "return", "newState", "!=", "null", ";", "}", "/** Return true if the reponse to the event is to perform an action */", "public", "boolean", "isAction", "(", ")", "{", "return", "action", "!=", "null", ";", "}", "/** Return the new state, iff a transition response */", "public", "String", "getNewState", "(", ")", "{", "return", "newState", ";", "}", "/** Return the action, iff an action response */", "public", "PsmAction", "getAction", "(", ")", "{", "return", "action", ";", "}", "public", "String", "toString", "(", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", ")", ";", "sb", ".", "append", "(", "\"", "[Resp: ", "\"", ")", ";", "sb", ".", "append", "(", "event", ")", ";", "sb", ".", "append", "(", "\"", " -> ", "\"", ")", ";", "if", "(", "isAction", "(", ")", ")", "{", "sb", ".", "append", "(", "action", ")", ";", "}", "else", "if", "(", "isTransition", "(", ")", ")", "{", "sb", ".", "append", "(", "newState", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"", "[???]", "\"", ")", ";", "}", "sb", ".", "append", "(", "\"", "]", "\"", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "}" ]
PsmResponse maps an event to a response, which is either an action or a the name of new state to which to transition.
[ "PsmResponse", "maps", "an", "event", "to", "a", "response", "which", "is", "either", "an", "action", "or", "a", "the", "name", "of", "new", "state", "to", "which", "to", "transition", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c45522f90277a123bc9fe131268b489fbb9a76b4
Manny27nyc/azure-sdk-for-java
sdk/servicefabric/azure-resourcemanager-servicefabric/src/main/java/com/azure/resourcemanager/servicefabric/models/RollingUpgradeMode.java
[ "MIT" ]
Java
RollingUpgradeMode
/** Defines values for RollingUpgradeMode. */
Defines values for RollingUpgradeMode.
[ "Defines", "values", "for", "RollingUpgradeMode", "." ]
public final class RollingUpgradeMode extends ExpandableStringEnum<RollingUpgradeMode> { /** Static value Invalid for RollingUpgradeMode. */ public static final RollingUpgradeMode INVALID = fromString("Invalid"); /** Static value UnmonitoredAuto for RollingUpgradeMode. */ public static final RollingUpgradeMode UNMONITORED_AUTO = fromString("UnmonitoredAuto"); /** Static value UnmonitoredManual for RollingUpgradeMode. */ public static final RollingUpgradeMode UNMONITORED_MANUAL = fromString("UnmonitoredManual"); /** Static value Monitored for RollingUpgradeMode. */ public static final RollingUpgradeMode MONITORED = fromString("Monitored"); /** * Creates or finds a RollingUpgradeMode from its string representation. * * @param name a name to look for. * @return the corresponding RollingUpgradeMode. */ @JsonCreator public static RollingUpgradeMode fromString(String name) { return fromString(name, RollingUpgradeMode.class); } /** @return known RollingUpgradeMode values. */ public static Collection<RollingUpgradeMode> values() { return values(RollingUpgradeMode.class); } }
[ "public", "final", "class", "RollingUpgradeMode", "extends", "ExpandableStringEnum", "<", "RollingUpgradeMode", ">", "{", "/** Static value Invalid for RollingUpgradeMode. */", "public", "static", "final", "RollingUpgradeMode", "INVALID", "=", "fromString", "(", "\"", "Invalid", "\"", ")", ";", "/** Static value UnmonitoredAuto for RollingUpgradeMode. */", "public", "static", "final", "RollingUpgradeMode", "UNMONITORED_AUTO", "=", "fromString", "(", "\"", "UnmonitoredAuto", "\"", ")", ";", "/** Static value UnmonitoredManual for RollingUpgradeMode. */", "public", "static", "final", "RollingUpgradeMode", "UNMONITORED_MANUAL", "=", "fromString", "(", "\"", "UnmonitoredManual", "\"", ")", ";", "/** Static value Monitored for RollingUpgradeMode. */", "public", "static", "final", "RollingUpgradeMode", "MONITORED", "=", "fromString", "(", "\"", "Monitored", "\"", ")", ";", "/**\n * Creates or finds a RollingUpgradeMode from its string representation.\n *\n * @param name a name to look for.\n * @return the corresponding RollingUpgradeMode.\n */", "@", "JsonCreator", "public", "static", "RollingUpgradeMode", "fromString", "(", "String", "name", ")", "{", "return", "fromString", "(", "name", ",", "RollingUpgradeMode", ".", "class", ")", ";", "}", "/** @return known RollingUpgradeMode values. */", "public", "static", "Collection", "<", "RollingUpgradeMode", ">", "values", "(", ")", "{", "return", "values", "(", "RollingUpgradeMode", ".", "class", ")", ";", "}", "}" ]
Defines values for RollingUpgradeMode.
[ "Defines", "values", "for", "RollingUpgradeMode", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c45f04a6803977fbf3d0c9fea472e95167976f37
adaptris/interlok-elastic
interlok-elastic-common/src/main/java/com/adaptris/core/elastic/CSVDocumentBuilder.java
[ "Apache-2.0" ]
Java
CSVDocumentBuilder
/** * Builds a simple document for elastic search. * * <p> * The document that is created contains the following characteristics * <ul> * <li>The first record of the CSV is usually assumed to be a header row, and is used as the fieldName for each entry. If * {@code use-header-record} is marked as false, then fields will be generated according to their position.</li> * <li>The "unique-id" for the document is derived from the specified column, duplicates may have unexpected results depending on * your configuration.</li> * </ul> * </p> * * @config elastic-csv-document-builder * */
Builds a simple document for elastic search. The document that is created contains the following characteristics The first record of the CSV is usually assumed to be a header row, and is used as the fieldName for each entry. If use-header-record is marked as false, then fields will be generated according to their position. The "unique-id" for the document is derived from the specified column, duplicates may have unexpected results depending on your configuration. @config elastic-csv-document-builder
[ "Builds", "a", "simple", "document", "for", "elastic", "search", ".", "The", "document", "that", "is", "created", "contains", "the", "following", "characteristics", "The", "first", "record", "of", "the", "CSV", "is", "usually", "assumed", "to", "be", "a", "header", "row", "and", "is", "used", "as", "the", "fieldName", "for", "each", "entry", ".", "If", "use", "-", "header", "-", "record", "is", "marked", "as", "false", "then", "fields", "will", "be", "generated", "according", "to", "their", "position", ".", "The", "\"", "unique", "-", "id", "\"", "for", "the", "document", "is", "derived", "from", "the", "specified", "column", "duplicates", "may", "have", "unexpected", "results", "depending", "on", "your", "configuration", ".", "@config", "elastic", "-", "csv", "-", "document", "-", "builder" ]
@XStreamAlias("elastic-csv-document-builder") @ComponentProfile(summary = "Build documents for elasticsearch from a CSV document", since = "3.9.1") public class CSVDocumentBuilder extends CSVDocumentBuilderImpl { /** * Whether or not the document contains a header row. * * <p>This defaults to true unless otherwise specified</p> */ @AdvancedConfig @InputFieldDefault(value = "true") @Getter @Setter private Boolean useHeaderRecord; public CSVDocumentBuilder() { super(); } @Deprecated public CSVDocumentBuilder(FormatBuilder f) { super(); setFormat(f); } public CSVDocumentBuilder(PreferenceBuilder p) { super(); setPreference(p); } public CSVDocumentBuilder withUseHeaderRecord(Boolean b) { setUseHeaderRecord(b); return this; } private boolean useHeaderRecord() { return BooleanUtils.toBooleanDefaultIfNull(getUseHeaderRecord(), true); } @Override @Deprecated protected CSVDocumentWrapper buildWrapper(CSVParser parser, AdaptrisMessage msg) { return new ApacheWrapper(parser); } @Override protected CSVDocumentWrapper buildWrapper(CsvListReader reader, AdaptrisMessage message) { return new SuperWrapper(reader); } private class SuperWrapper extends CSVDocumentWrapper { private String[] headers = new String[0]; private List<String> next; public SuperWrapper(CsvListReader r) { super(r); if (useHeaderRecord()) { headers = buildHeaders(r); } } @Override public DocumentWrapper next() { DocumentWrapper result = null; try { List<String> row = next; next = null; if (row != null) { int idField = 0; if (uniqueIdField() <= row.size()) { idField = uniqueIdField(); } else { throw new Exception("unique-id field > number of fields in record"); } String uniqueId = row.get(idField); XContentBuilder builder = jsonBuilder(); builder.startObject(); addTimestamp(builder); for (int i = 0; i < row.size(); i++) { String fieldName = getFieldNameMapper().map(headers.length > 0 ? headers[i] : "field_" + i); String data = row.get(i); builder.field(fieldName, new Text(data != null ? data : "")); } builder.endObject(); result = new DocumentWrapper(uniqueId, builder); } } catch (Exception e) { throw new RuntimeException(e); } return result; } @Override public boolean hasNext() { try { next = reader.read(); return next != null; } catch (IOException e) { return false; } } } @Deprecated private class ApacheWrapper extends CSVDocumentWrapper { private List<String> headers = new ArrayList<>(); public ApacheWrapper(CSVParser p) { super(p); if (useHeaderRecord()) { headers = buildHeaders(csvIterator.next()); } } @Override public DocumentWrapper next() { DocumentWrapper result = null; try { CSVRecord record = csvIterator.next(); int idField = 0; if (uniqueIdField() <= record.size()) { idField = uniqueIdField(); } else { throw new Exception("unique-id field > number of fields in record"); } String uniqueId = record.get(idField); XContentBuilder builder = jsonBuilder(); builder.startObject(); addTimestamp(builder); for (int i = 0; i < record.size(); i++) { String fieldName = getFieldNameMapper().map(headers.size() > 0 ? headers.get(i) : "field_" + i); String data = record.get(i); builder.field(fieldName, new Text(data)); } builder.endObject(); result = new DocumentWrapper(uniqueId, builder); } catch (Exception e) { throw new RuntimeException(e); } return result; } } }
[ "@", "XStreamAlias", "(", "\"", "elastic-csv-document-builder", "\"", ")", "@", "ComponentProfile", "(", "summary", "=", "\"", "Build documents for elasticsearch from a CSV document", "\"", ",", "since", "=", "\"", "3.9.1", "\"", ")", "public", "class", "CSVDocumentBuilder", "extends", "CSVDocumentBuilderImpl", "{", "/**\n * Whether or not the document contains a header row.\n *\n * <p>This defaults to true unless otherwise specified</p>\n */", "@", "AdvancedConfig", "@", "InputFieldDefault", "(", "value", "=", "\"", "true", "\"", ")", "@", "Getter", "@", "Setter", "private", "Boolean", "useHeaderRecord", ";", "public", "CSVDocumentBuilder", "(", ")", "{", "super", "(", ")", ";", "}", "@", "Deprecated", "public", "CSVDocumentBuilder", "(", "FormatBuilder", "f", ")", "{", "super", "(", ")", ";", "setFormat", "(", "f", ")", ";", "}", "public", "CSVDocumentBuilder", "(", "PreferenceBuilder", "p", ")", "{", "super", "(", ")", ";", "setPreference", "(", "p", ")", ";", "}", "public", "CSVDocumentBuilder", "withUseHeaderRecord", "(", "Boolean", "b", ")", "{", "setUseHeaderRecord", "(", "b", ")", ";", "return", "this", ";", "}", "private", "boolean", "useHeaderRecord", "(", ")", "{", "return", "BooleanUtils", ".", "toBooleanDefaultIfNull", "(", "getUseHeaderRecord", "(", ")", ",", "true", ")", ";", "}", "@", "Override", "@", "Deprecated", "protected", "CSVDocumentWrapper", "buildWrapper", "(", "CSVParser", "parser", ",", "AdaptrisMessage", "msg", ")", "{", "return", "new", "ApacheWrapper", "(", "parser", ")", ";", "}", "@", "Override", "protected", "CSVDocumentWrapper", "buildWrapper", "(", "CsvListReader", "reader", ",", "AdaptrisMessage", "message", ")", "{", "return", "new", "SuperWrapper", "(", "reader", ")", ";", "}", "private", "class", "SuperWrapper", "extends", "CSVDocumentWrapper", "{", "private", "String", "[", "]", "headers", "=", "new", "String", "[", "0", "]", ";", "private", "List", "<", "String", ">", "next", ";", "public", "SuperWrapper", "(", "CsvListReader", "r", ")", "{", "super", "(", "r", ")", ";", "if", "(", "useHeaderRecord", "(", ")", ")", "{", "headers", "=", "buildHeaders", "(", "r", ")", ";", "}", "}", "@", "Override", "public", "DocumentWrapper", "next", "(", ")", "{", "DocumentWrapper", "result", "=", "null", ";", "try", "{", "List", "<", "String", ">", "row", "=", "next", ";", "next", "=", "null", ";", "if", "(", "row", "!=", "null", ")", "{", "int", "idField", "=", "0", ";", "if", "(", "uniqueIdField", "(", ")", "<=", "row", ".", "size", "(", ")", ")", "{", "idField", "=", "uniqueIdField", "(", ")", ";", "}", "else", "{", "throw", "new", "Exception", "(", "\"", "unique-id field > number of fields in record", "\"", ")", ";", "}", "String", "uniqueId", "=", "row", ".", "get", "(", "idField", ")", ";", "XContentBuilder", "builder", "=", "jsonBuilder", "(", ")", ";", "builder", ".", "startObject", "(", ")", ";", "addTimestamp", "(", "builder", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "row", ".", "size", "(", ")", ";", "i", "++", ")", "{", "String", "fieldName", "=", "getFieldNameMapper", "(", ")", ".", "map", "(", "headers", ".", "length", ">", "0", "?", "headers", "[", "i", "]", ":", "\"", "field_", "\"", "+", "i", ")", ";", "String", "data", "=", "row", ".", "get", "(", "i", ")", ";", "builder", ".", "field", "(", "fieldName", ",", "new", "Text", "(", "data", "!=", "null", "?", "data", ":", "\"", "\"", ")", ")", ";", "}", "builder", ".", "endObject", "(", ")", ";", "result", "=", "new", "DocumentWrapper", "(", "uniqueId", ",", "builder", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "return", "result", ";", "}", "@", "Override", "public", "boolean", "hasNext", "(", ")", "{", "try", "{", "next", "=", "reader", ".", "read", "(", ")", ";", "return", "next", "!=", "null", ";", "}", "catch", "(", "IOException", "e", ")", "{", "return", "false", ";", "}", "}", "}", "@", "Deprecated", "private", "class", "ApacheWrapper", "extends", "CSVDocumentWrapper", "{", "private", "List", "<", "String", ">", "headers", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "public", "ApacheWrapper", "(", "CSVParser", "p", ")", "{", "super", "(", "p", ")", ";", "if", "(", "useHeaderRecord", "(", ")", ")", "{", "headers", "=", "buildHeaders", "(", "csvIterator", ".", "next", "(", ")", ")", ";", "}", "}", "@", "Override", "public", "DocumentWrapper", "next", "(", ")", "{", "DocumentWrapper", "result", "=", "null", ";", "try", "{", "CSVRecord", "record", "=", "csvIterator", ".", "next", "(", ")", ";", "int", "idField", "=", "0", ";", "if", "(", "uniqueIdField", "(", ")", "<=", "record", ".", "size", "(", ")", ")", "{", "idField", "=", "uniqueIdField", "(", ")", ";", "}", "else", "{", "throw", "new", "Exception", "(", "\"", "unique-id field > number of fields in record", "\"", ")", ";", "}", "String", "uniqueId", "=", "record", ".", "get", "(", "idField", ")", ";", "XContentBuilder", "builder", "=", "jsonBuilder", "(", ")", ";", "builder", ".", "startObject", "(", ")", ";", "addTimestamp", "(", "builder", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "record", ".", "size", "(", ")", ";", "i", "++", ")", "{", "String", "fieldName", "=", "getFieldNameMapper", "(", ")", ".", "map", "(", "headers", ".", "size", "(", ")", ">", "0", "?", "headers", ".", "get", "(", "i", ")", ":", "\"", "field_", "\"", "+", "i", ")", ";", "String", "data", "=", "record", ".", "get", "(", "i", ")", ";", "builder", ".", "field", "(", "fieldName", ",", "new", "Text", "(", "data", ")", ")", ";", "}", "builder", ".", "endObject", "(", ")", ";", "result", "=", "new", "DocumentWrapper", "(", "uniqueId", ",", "builder", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "return", "result", ";", "}", "}", "}" ]
Builds a simple document for elastic search.
[ "Builds", "a", "simple", "document", "for", "elastic", "search", "." ]
[]
[ { "param": "CSVDocumentBuilderImpl", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "CSVDocumentBuilderImpl", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c45fe4e3aa5f8b0cca1e0eda150e0f2b720cd856
aliyun/tauris
tauris-config/src/main/java/com/aliyun/tauris/config/parser/Plugin.java
[ "Apache-2.0" ]
Java
Plugin
/** * Created by jdziworski on 30.03.16. */
Created by jdziworski on 30.03.16.
[ "Created", "by", "jdziworski", "on", "30", ".", "03", ".", "16", "." ]
public class Plugin { private String name; private Assignments assignments; public Plugin(String name, Assignments assignments) { this.name = name; this.assignments = assignments; } public String getName() { return name; } public <T extends TPlugin> TPlugin build(Class<T> type) { TPluginResolver resolver = TPluginResolver.defaultResolver; TPlugin plugin = resolver.resolvePlugin(type, name); return this.build(plugin); } public TPlugin build(TPluginFactory factory) { TPlugin plugin = factory.newInstance(name); return build(plugin); } public TPlugin build(TPlugin plugin) { Helper.m.message(name).expand("{").next(); this.assignments.assignTo(plugin); String pid = name + "_" + RandomStringUtils.randomNumeric(8).toLowerCase(); if (plugin.id() == null) { plugin.setId(pid); Helper.m.collapse("} //id: " + pid).next(); } else { Helper.m.collapse("}").next(); } init(plugin, name); return plugin; } private void init(Object o, String name) { try { Method initMethod = o.getClass().getMethod("init"); initMethod.invoke(o); } catch (IllegalArgumentException e) { throw new TConfigException("init component " + name + " failed, cause by " + e.getMessage(), e); } catch (NoSuchMethodException e) { // ignore } catch (IllegalAccessException e) { System.err.println("warning: cannot access init method of " + o.getClass()); } catch (InvocationTargetException e) { // throw Throwable source = e.getTargetException(); throw new TConfigException("init component " + name + " failed, cause by " + source.getMessage(), source); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Plugin component = (Plugin) o; if (name != null ? !name.equals(component.name) : component.name != null) return false; return assignments != null ? assignments.equals(component.assignments) : component.assignments == null; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (assignments != null ? assignments.hashCode() : 0); return result; } @Override public String toString() { return "Method{" + "\nname='" + name + '\'' + "\nassignments=" + assignments + '}'; } }
[ "public", "class", "Plugin", "{", "private", "String", "name", ";", "private", "Assignments", "assignments", ";", "public", "Plugin", "(", "String", "name", ",", "Assignments", "assignments", ")", "{", "this", ".", "name", "=", "name", ";", "this", ".", "assignments", "=", "assignments", ";", "}", "public", "String", "getName", "(", ")", "{", "return", "name", ";", "}", "public", "<", "T", "extends", "TPlugin", ">", "TPlugin", "build", "(", "Class", "<", "T", ">", "type", ")", "{", "TPluginResolver", "resolver", "=", "TPluginResolver", ".", "defaultResolver", ";", "TPlugin", "plugin", "=", "resolver", ".", "resolvePlugin", "(", "type", ",", "name", ")", ";", "return", "this", ".", "build", "(", "plugin", ")", ";", "}", "public", "TPlugin", "build", "(", "TPluginFactory", "factory", ")", "{", "TPlugin", "plugin", "=", "factory", ".", "newInstance", "(", "name", ")", ";", "return", "build", "(", "plugin", ")", ";", "}", "public", "TPlugin", "build", "(", "TPlugin", "plugin", ")", "{", "Helper", ".", "m", ".", "message", "(", "name", ")", ".", "expand", "(", "\"", "{", "\"", ")", ".", "next", "(", ")", ";", "this", ".", "assignments", ".", "assignTo", "(", "plugin", ")", ";", "String", "pid", "=", "name", "+", "\"", "_", "\"", "+", "RandomStringUtils", ".", "randomNumeric", "(", "8", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "plugin", ".", "id", "(", ")", "==", "null", ")", "{", "plugin", ".", "setId", "(", "pid", ")", ";", "Helper", ".", "m", ".", "collapse", "(", "\"", "} //id: ", "\"", "+", "pid", ")", ".", "next", "(", ")", ";", "}", "else", "{", "Helper", ".", "m", ".", "collapse", "(", "\"", "}", "\"", ")", ".", "next", "(", ")", ";", "}", "init", "(", "plugin", ",", "name", ")", ";", "return", "plugin", ";", "}", "private", "void", "init", "(", "Object", "o", ",", "String", "name", ")", "{", "try", "{", "Method", "initMethod", "=", "o", ".", "getClass", "(", ")", ".", "getMethod", "(", "\"", "init", "\"", ")", ";", "initMethod", ".", "invoke", "(", "o", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "TConfigException", "(", "\"", "init component ", "\"", "+", "name", "+", "\"", " failed, cause by ", "\"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "catch", "(", "NoSuchMethodException", "e", ")", "{", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "System", ".", "err", ".", "println", "(", "\"", "warning: cannot access init method of ", "\"", "+", "o", ".", "getClass", "(", ")", ")", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "Throwable", "source", "=", "e", ".", "getTargetException", "(", ")", ";", "throw", "new", "TConfigException", "(", "\"", "init component ", "\"", "+", "name", "+", "\"", " failed, cause by ", "\"", "+", "source", ".", "getMessage", "(", ")", ",", "source", ")", ";", "}", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "o", ")", "{", "if", "(", "this", "==", "o", ")", "return", "true", ";", "if", "(", "o", "==", "null", "||", "getClass", "(", ")", "!=", "o", ".", "getClass", "(", ")", ")", "return", "false", ";", "Plugin", "component", "=", "(", "Plugin", ")", "o", ";", "if", "(", "name", "!=", "null", "?", "!", "name", ".", "equals", "(", "component", ".", "name", ")", ":", "component", ".", "name", "!=", "null", ")", "return", "false", ";", "return", "assignments", "!=", "null", "?", "assignments", ".", "equals", "(", "component", ".", "assignments", ")", ":", "component", ".", "assignments", "==", "null", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "int", "result", "=", "name", "!=", "null", "?", "name", ".", "hashCode", "(", ")", ":", "0", ";", "result", "=", "31", "*", "result", "+", "(", "assignments", "!=", "null", "?", "assignments", ".", "hashCode", "(", ")", ":", "0", ")", ";", "return", "result", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "Method{", "\"", "+", "\"", "\\n", "name='", "\"", "+", "name", "+", "'\\''", "+", "\"", "\\n", "assignments=", "\"", "+", "assignments", "+", "'}'", ";", "}", "}" ]
Created by jdziworski on 30.03.16.
[ "Created", "by", "jdziworski", "on", "30", ".", "03", ".", "16", "." ]
[ "// ignore", "// throw" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c463da423044ecfc8dc3b5e296ed5eaaa4a763bc
tijkijiki/backend
server/src/main/java/io/fnx/backend/util/thyme/ThymeEngineFactory.java
[ "MIT" ]
Java
ThymeEngineFactory
/** * @author Tomas Zverina <zverina@m-atelier.cz> */
@author Tomas Zverina
[ "@author", "Tomas", "Zverina" ]
public class ThymeEngineFactory { public static TemplateEngine initializeTemplateEngine(final String thymeFolder) { TemplateResolver templateResolver = new TemplateResolver(); // XHTML is the default mode, but we set it anyway for better understanding of code templateResolver.setTemplateMode("LEGACYHTML5"); templateResolver.setCacheable(true); templateResolver.setCharacterEncoding("UTF-8"); // Template cache TTL=1h. If not set, entries would be cached until expelled by LRU templateResolver.setCacheTTLMs(3600000L); templateResolver.setResourceResolver(new FnxResourceResolver(thymeFolder)); TemplateEngine templateEngine = new TemplateEngine(); templateEngine.addDialect(new LayoutDialect()); templateEngine.addDialect(new MaThymeDialect()); templateEngine.addDialect(new JodaDateThymeDialect()); templateEngine.setTemplateResolver(templateResolver); return templateEngine; } private static class FnxResourceResolver implements IResourceResolver { private final String thymeFolder; public FnxResourceResolver(String thymeFolder) { this.thymeFolder = thymeFolder; } @Override public String getName() { return "ThymeEngineFactory"; } @Override public InputStream getResourceAsStream(TemplateProcessingParameters templateProcessingParameters, String resourceName) { return ThymeEngineFactory.class.getResourceAsStream("/"+ thymeFolder +"/"+resourceName+".html"); } } }
[ "public", "class", "ThymeEngineFactory", "{", "public", "static", "TemplateEngine", "initializeTemplateEngine", "(", "final", "String", "thymeFolder", ")", "{", "TemplateResolver", "templateResolver", "=", "new", "TemplateResolver", "(", ")", ";", "templateResolver", ".", "setTemplateMode", "(", "\"", "LEGACYHTML5", "\"", ")", ";", "templateResolver", ".", "setCacheable", "(", "true", ")", ";", "templateResolver", ".", "setCharacterEncoding", "(", "\"", "UTF-8", "\"", ")", ";", "templateResolver", ".", "setCacheTTLMs", "(", "3600000L", ")", ";", "templateResolver", ".", "setResourceResolver", "(", "new", "FnxResourceResolver", "(", "thymeFolder", ")", ")", ";", "TemplateEngine", "templateEngine", "=", "new", "TemplateEngine", "(", ")", ";", "templateEngine", ".", "addDialect", "(", "new", "LayoutDialect", "(", ")", ")", ";", "templateEngine", ".", "addDialect", "(", "new", "MaThymeDialect", "(", ")", ")", ";", "templateEngine", ".", "addDialect", "(", "new", "JodaDateThymeDialect", "(", ")", ")", ";", "templateEngine", ".", "setTemplateResolver", "(", "templateResolver", ")", ";", "return", "templateEngine", ";", "}", "private", "static", "class", "FnxResourceResolver", "implements", "IResourceResolver", "{", "private", "final", "String", "thymeFolder", ";", "public", "FnxResourceResolver", "(", "String", "thymeFolder", ")", "{", "this", ".", "thymeFolder", "=", "thymeFolder", ";", "}", "@", "Override", "public", "String", "getName", "(", ")", "{", "return", "\"", "ThymeEngineFactory", "\"", ";", "}", "@", "Override", "public", "InputStream", "getResourceAsStream", "(", "TemplateProcessingParameters", "templateProcessingParameters", ",", "String", "resourceName", ")", "{", "return", "ThymeEngineFactory", ".", "class", ".", "getResourceAsStream", "(", "\"", "/", "\"", "+", "thymeFolder", "+", "\"", "/", "\"", "+", "resourceName", "+", "\"", ".html", "\"", ")", ";", "}", "}", "}" ]
@author Tomas Zverina <zverina@m-atelier.cz>
[ "@author", "Tomas", "Zverina", "<zverina@m", "-", "atelier", ".", "cz", ">" ]
[ "// XHTML is the default mode, but we set it anyway for better understanding of code", "// Template cache TTL=1h. If not set, entries would be cached until expelled by LRU" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c464921a54521a1fbd91c38ec1bf15cca123d9ec
ETeissonniere/redbear_backup
apps/android/DuoApp/controller/src/main/java/net/redbear/board/controller/view/customView/PinView.java
[ "Unlicense" ]
Java
PinView
/** * Created by dong on 3/21/16. */
Created by dong on 3/21/16.
[ "Created", "by", "dong", "on", "3", "/", "21", "/", "16", "." ]
public class PinView extends RelativeLayout implements View.OnClickListener,PinAble{ private boolean isLeft = true; private Context context; private float height; private TextView pinButton; private RelativeLayout controlLayout; private TextView stateText; private TextView controlTextView; private SwitchButton controlSwitch; private TextView switchTextView; private int pinNum; private int pinViewNum; private int pinMode = Common.PIN_MODE_IDE; private PinViewCallback callback; public PinView(Context context, boolean isLeft,int pinViewNum) { super(context); this.isLeft = isLeft; this.pinViewNum = pinViewNum; init(context); } public PinView(Context context ,int pinViewNum) { super(context); this.pinViewNum = pinViewNum; init(context); } public PinView(Context context) { super(context); init(context); } public PinView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public PinView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(final Context context){ this.context = context; setWillNotDraw(false); pinButton = new TextView(context); pinButton.setTag(1); stateText = new TextView(context); controlLayout = new RelativeLayout(context); controlSwitch = new SwitchButton(context,90); controlSwitch.setClickable(false); switchTextView = new TextView(context); controlTextView = new TextView(context); post(new Runnable() { @Override public void run() { height = getMeasuredHeight(); //pin button pinButton.setGravity(Gravity.CENTER); pinButton.setId(R.id.pinViewButtonLeftView); pinButton.setTextSize(17); pinButton.setOnClickListener(PinView.this); LayoutParams layoutParams = new LayoutParams((int)(height*0.7),(int)(height*0.7)); layoutParams.setMarginStart(10); if (isLeft){ layoutParams.addRule(ALIGN_PARENT_START); }else { layoutParams.addRule(ALIGN_PARENT_END); } layoutParams.addRule(CENTER_HORIZONTAL); pinButton.setLayoutParams(layoutParams); addView(pinButton); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setTag(2); linearLayout.setOnClickListener(PinView.this); linearLayout.setOrientation(LinearLayout.VERTICAL); LayoutParams layoutParams2 = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT); if (isLeft){ layoutParams2.addRule(END_OF, R.id.pinViewButtonLeftView); }else { layoutParams2.addRule(START_OF,R.id.pinViewButtonLeftView); } linearLayout.setLayoutParams(layoutParams2); LayoutParams layoutParams3 = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,(int)(height*0.5)); controlLayout.setLayoutParams(layoutParams3); controlLayout.setGravity(Gravity.CENTER); linearLayout.addView(controlLayout,0); stateText.setGravity(Gravity.CENTER); stateText.setTextColor(context.getResources().getColor(R.color.colorPrimary)); stateText.setLayoutParams(layoutParams3); linearLayout.addView(stateText,1); controlTextView.setText(getWidth()+""); LayoutParams layoutParams5 = new LayoutParams((int)(getWidth()*0.4f), ViewGroup.LayoutParams.MATCH_PARENT); controlTextView.setGravity(Gravity.CENTER); controlTextView.setTextColor(context.getResources().getColor(R.color.colorPrimary)); controlTextView.setBackground(context.getResources().getDrawable(R.drawable.stroke_rect_red_solid_null)); controlTextView.setLayoutParams(layoutParams5); controlSwitch.setId(R.id.controlViewSwitch); LayoutParams layoutParams4 = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams4.addRule(CENTER_VERTICAL); controlSwitch.setLayoutParams(layoutParams4); switchTextView.setText("HHH"); switchTextView.setTextColor(context.getResources().getColor(R.color.colorPrimary)); switchTextView.setGravity(Gravity.CENTER_VERTICAL); LayoutParams layoutParams1 = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT); layoutParams1.addRule(END_OF,R.id.controlViewSwitch); switchTextView.setLayoutParams(layoutParams1); controlLayout.addView(controlSwitch); controlLayout.addView(switchTextView); controlLayout.addView(controlTextView); addView(linearLayout); } }); } public void notifyState(int pinMode){ this.pinMode = pinMode; if(pinMode == PIN_MODE_DISABLE){ pinButton.setAlpha(0.3f); pinButton.setEnabled(false); }else { pinButton.setAlpha(1f); pinButton.setEnabled(true); } if (pinMode != PIN_MODE_DISABLE && pinMode != PIN_MODE_IDE){ pinButton.setBackground(context.getResources().getDrawable(R.drawable.stroke_round_red)); pinButton.setTextColor(context.getResources().getColor(R.color.colorPrimary)); controlLayout.setVisibility(VISIBLE); controlLayout.setEnabled(true); }else { clearControl(); pinButton.setBackground(context.getResources().getDrawable(R.drawable.stroke_round_gray)); pinButton.setTextColor(Color.GRAY); } switch (pinMode){ case PIN_MODE_DIGITAL_READ: stateText.setText("Digital Read"); notifyControlView(0); break; case PIN_MODE_DIGITAL_WRITE: stateText.setText("Digital Write"); notifyControlView(1); break; case PIN_MODE_PWM: stateText.setText("PWM"); notifyControlView(0); break; case PIN_MODE_ANALOG_READ: stateText.setText("Analog Read"); notifyControlView(0); break; case PIN_MODE_SERVO: stateText.setText("Servo"); notifyControlView(0); break; } } private void notifyControlView(int state){ if (state == 0){ switchTextView.setVisibility(GONE); controlSwitch.setVisibility(GONE); controlTextView.setVisibility(VISIBLE); }else { switchTextView.setVisibility(VISIBLE); controlSwitch.setVisibility(VISIBLE); controlTextView.setVisibility(GONE); } } private void clearControl(){ controlLayout.setVisibility(GONE); stateText.setText(""); } public int getPinMode() { return pinMode; } @Override public void onClick(View v) { if (callback == null) return; int i = (Integer) v.getTag(); if (i == 1) { callback.onPinClick(pinNum,pinViewNum); }else if(i == 2) { callback.onControlClick(pinNum,pinViewNum,pinMode); } } @Override public void setPinName(String name) { pinButton.setText(name); if (name.length() > 2){ pinButton.post(new Runnable() { @Override public void run() { pinButton.setTextSize(10); } }); }else{ pinButton.post(new Runnable() { @Override public void run() { pinButton.setTextSize(17); } }); } } @Override public void setValue(int value) { controlTextView.setText(""+value); controlSwitch.setValue(value != 0 ?true:false); switchTextView.setText(value != 0 ?"HIGHT":"LOW"); } @Override public void setPinNum(int pinNum) { this.pinNum = pinNum; } public void setCallback(PinViewCallback callback) { this.callback = callback; } }
[ "public", "class", "PinView", "extends", "RelativeLayout", "implements", "View", ".", "OnClickListener", ",", "PinAble", "{", "private", "boolean", "isLeft", "=", "true", ";", "private", "Context", "context", ";", "private", "float", "height", ";", "private", "TextView", "pinButton", ";", "private", "RelativeLayout", "controlLayout", ";", "private", "TextView", "stateText", ";", "private", "TextView", "controlTextView", ";", "private", "SwitchButton", "controlSwitch", ";", "private", "TextView", "switchTextView", ";", "private", "int", "pinNum", ";", "private", "int", "pinViewNum", ";", "private", "int", "pinMode", "=", "Common", ".", "PIN_MODE_IDE", ";", "private", "PinViewCallback", "callback", ";", "public", "PinView", "(", "Context", "context", ",", "boolean", "isLeft", ",", "int", "pinViewNum", ")", "{", "super", "(", "context", ")", ";", "this", ".", "isLeft", "=", "isLeft", ";", "this", ".", "pinViewNum", "=", "pinViewNum", ";", "init", "(", "context", ")", ";", "}", "public", "PinView", "(", "Context", "context", ",", "int", "pinViewNum", ")", "{", "super", "(", "context", ")", ";", "this", ".", "pinViewNum", "=", "pinViewNum", ";", "init", "(", "context", ")", ";", "}", "public", "PinView", "(", "Context", "context", ")", "{", "super", "(", "context", ")", ";", "init", "(", "context", ")", ";", "}", "public", "PinView", "(", "Context", "context", ",", "AttributeSet", "attrs", ")", "{", "super", "(", "context", ",", "attrs", ")", ";", "init", "(", "context", ")", ";", "}", "public", "PinView", "(", "Context", "context", ",", "AttributeSet", "attrs", ",", "int", "defStyleAttr", ")", "{", "super", "(", "context", ",", "attrs", ",", "defStyleAttr", ")", ";", "init", "(", "context", ")", ";", "}", "private", "void", "init", "(", "final", "Context", "context", ")", "{", "this", ".", "context", "=", "context", ";", "setWillNotDraw", "(", "false", ")", ";", "pinButton", "=", "new", "TextView", "(", "context", ")", ";", "pinButton", ".", "setTag", "(", "1", ")", ";", "stateText", "=", "new", "TextView", "(", "context", ")", ";", "controlLayout", "=", "new", "RelativeLayout", "(", "context", ")", ";", "controlSwitch", "=", "new", "SwitchButton", "(", "context", ",", "90", ")", ";", "controlSwitch", ".", "setClickable", "(", "false", ")", ";", "switchTextView", "=", "new", "TextView", "(", "context", ")", ";", "controlTextView", "=", "new", "TextView", "(", "context", ")", ";", "post", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "height", "=", "getMeasuredHeight", "(", ")", ";", "pinButton", ".", "setGravity", "(", "Gravity", ".", "CENTER", ")", ";", "pinButton", ".", "setId", "(", "R", ".", "id", ".", "pinViewButtonLeftView", ")", ";", "pinButton", ".", "setTextSize", "(", "17", ")", ";", "pinButton", ".", "setOnClickListener", "(", "PinView", ".", "this", ")", ";", "LayoutParams", "layoutParams", "=", "new", "LayoutParams", "(", "(", "int", ")", "(", "height", "*", "0.7", ")", ",", "(", "int", ")", "(", "height", "*", "0.7", ")", ")", ";", "layoutParams", ".", "setMarginStart", "(", "10", ")", ";", "if", "(", "isLeft", ")", "{", "layoutParams", ".", "addRule", "(", "ALIGN_PARENT_START", ")", ";", "}", "else", "{", "layoutParams", ".", "addRule", "(", "ALIGN_PARENT_END", ")", ";", "}", "layoutParams", ".", "addRule", "(", "CENTER_HORIZONTAL", ")", ";", "pinButton", ".", "setLayoutParams", "(", "layoutParams", ")", ";", "addView", "(", "pinButton", ")", ";", "LinearLayout", "linearLayout", "=", "new", "LinearLayout", "(", "context", ")", ";", "linearLayout", ".", "setTag", "(", "2", ")", ";", "linearLayout", ".", "setOnClickListener", "(", "PinView", ".", "this", ")", ";", "linearLayout", ".", "setOrientation", "(", "LinearLayout", ".", "VERTICAL", ")", ";", "LayoutParams", "layoutParams2", "=", "new", "LayoutParams", "(", "ViewGroup", ".", "LayoutParams", ".", "MATCH_PARENT", ",", "ViewGroup", ".", "LayoutParams", ".", "MATCH_PARENT", ")", ";", "if", "(", "isLeft", ")", "{", "layoutParams2", ".", "addRule", "(", "END_OF", ",", "R", ".", "id", ".", "pinViewButtonLeftView", ")", ";", "}", "else", "{", "layoutParams2", ".", "addRule", "(", "START_OF", ",", "R", ".", "id", ".", "pinViewButtonLeftView", ")", ";", "}", "linearLayout", ".", "setLayoutParams", "(", "layoutParams2", ")", ";", "LayoutParams", "layoutParams3", "=", "new", "LayoutParams", "(", "ViewGroup", ".", "LayoutParams", ".", "MATCH_PARENT", ",", "(", "int", ")", "(", "height", "*", "0.5", ")", ")", ";", "controlLayout", ".", "setLayoutParams", "(", "layoutParams3", ")", ";", "controlLayout", ".", "setGravity", "(", "Gravity", ".", "CENTER", ")", ";", "linearLayout", ".", "addView", "(", "controlLayout", ",", "0", ")", ";", "stateText", ".", "setGravity", "(", "Gravity", ".", "CENTER", ")", ";", "stateText", ".", "setTextColor", "(", "context", ".", "getResources", "(", ")", ".", "getColor", "(", "R", ".", "color", ".", "colorPrimary", ")", ")", ";", "stateText", ".", "setLayoutParams", "(", "layoutParams3", ")", ";", "linearLayout", ".", "addView", "(", "stateText", ",", "1", ")", ";", "controlTextView", ".", "setText", "(", "getWidth", "(", ")", "+", "\"", "\"", ")", ";", "LayoutParams", "layoutParams5", "=", "new", "LayoutParams", "(", "(", "int", ")", "(", "getWidth", "(", ")", "*", "0.4f", ")", ",", "ViewGroup", ".", "LayoutParams", ".", "MATCH_PARENT", ")", ";", "controlTextView", ".", "setGravity", "(", "Gravity", ".", "CENTER", ")", ";", "controlTextView", ".", "setTextColor", "(", "context", ".", "getResources", "(", ")", ".", "getColor", "(", "R", ".", "color", ".", "colorPrimary", ")", ")", ";", "controlTextView", ".", "setBackground", "(", "context", ".", "getResources", "(", ")", ".", "getDrawable", "(", "R", ".", "drawable", ".", "stroke_rect_red_solid_null", ")", ")", ";", "controlTextView", ".", "setLayoutParams", "(", "layoutParams5", ")", ";", "controlSwitch", ".", "setId", "(", "R", ".", "id", ".", "controlViewSwitch", ")", ";", "LayoutParams", "layoutParams4", "=", "new", "LayoutParams", "(", "ViewGroup", ".", "LayoutParams", ".", "WRAP_CONTENT", ",", "ViewGroup", ".", "LayoutParams", ".", "WRAP_CONTENT", ")", ";", "layoutParams4", ".", "addRule", "(", "CENTER_VERTICAL", ")", ";", "controlSwitch", ".", "setLayoutParams", "(", "layoutParams4", ")", ";", "switchTextView", ".", "setText", "(", "\"", "HHH", "\"", ")", ";", "switchTextView", ".", "setTextColor", "(", "context", ".", "getResources", "(", ")", ".", "getColor", "(", "R", ".", "color", ".", "colorPrimary", ")", ")", ";", "switchTextView", ".", "setGravity", "(", "Gravity", ".", "CENTER_VERTICAL", ")", ";", "LayoutParams", "layoutParams1", "=", "new", "LayoutParams", "(", "ViewGroup", ".", "LayoutParams", ".", "WRAP_CONTENT", ",", "ViewGroup", ".", "LayoutParams", ".", "MATCH_PARENT", ")", ";", "layoutParams1", ".", "addRule", "(", "END_OF", ",", "R", ".", "id", ".", "controlViewSwitch", ")", ";", "switchTextView", ".", "setLayoutParams", "(", "layoutParams1", ")", ";", "controlLayout", ".", "addView", "(", "controlSwitch", ")", ";", "controlLayout", ".", "addView", "(", "switchTextView", ")", ";", "controlLayout", ".", "addView", "(", "controlTextView", ")", ";", "addView", "(", "linearLayout", ")", ";", "}", "}", ")", ";", "}", "public", "void", "notifyState", "(", "int", "pinMode", ")", "{", "this", ".", "pinMode", "=", "pinMode", ";", "if", "(", "pinMode", "==", "PIN_MODE_DISABLE", ")", "{", "pinButton", ".", "setAlpha", "(", "0.3f", ")", ";", "pinButton", ".", "setEnabled", "(", "false", ")", ";", "}", "else", "{", "pinButton", ".", "setAlpha", "(", "1f", ")", ";", "pinButton", ".", "setEnabled", "(", "true", ")", ";", "}", "if", "(", "pinMode", "!=", "PIN_MODE_DISABLE", "&&", "pinMode", "!=", "PIN_MODE_IDE", ")", "{", "pinButton", ".", "setBackground", "(", "context", ".", "getResources", "(", ")", ".", "getDrawable", "(", "R", ".", "drawable", ".", "stroke_round_red", ")", ")", ";", "pinButton", ".", "setTextColor", "(", "context", ".", "getResources", "(", ")", ".", "getColor", "(", "R", ".", "color", ".", "colorPrimary", ")", ")", ";", "controlLayout", ".", "setVisibility", "(", "VISIBLE", ")", ";", "controlLayout", ".", "setEnabled", "(", "true", ")", ";", "}", "else", "{", "clearControl", "(", ")", ";", "pinButton", ".", "setBackground", "(", "context", ".", "getResources", "(", ")", ".", "getDrawable", "(", "R", ".", "drawable", ".", "stroke_round_gray", ")", ")", ";", "pinButton", ".", "setTextColor", "(", "Color", ".", "GRAY", ")", ";", "}", "switch", "(", "pinMode", ")", "{", "case", "PIN_MODE_DIGITAL_READ", ":", "stateText", ".", "setText", "(", "\"", "Digital Read", "\"", ")", ";", "notifyControlView", "(", "0", ")", ";", "break", ";", "case", "PIN_MODE_DIGITAL_WRITE", ":", "stateText", ".", "setText", "(", "\"", "Digital Write", "\"", ")", ";", "notifyControlView", "(", "1", ")", ";", "break", ";", "case", "PIN_MODE_PWM", ":", "stateText", ".", "setText", "(", "\"", "PWM", "\"", ")", ";", "notifyControlView", "(", "0", ")", ";", "break", ";", "case", "PIN_MODE_ANALOG_READ", ":", "stateText", ".", "setText", "(", "\"", "Analog Read", "\"", ")", ";", "notifyControlView", "(", "0", ")", ";", "break", ";", "case", "PIN_MODE_SERVO", ":", "stateText", ".", "setText", "(", "\"", "Servo", "\"", ")", ";", "notifyControlView", "(", "0", ")", ";", "break", ";", "}", "}", "private", "void", "notifyControlView", "(", "int", "state", ")", "{", "if", "(", "state", "==", "0", ")", "{", "switchTextView", ".", "setVisibility", "(", "GONE", ")", ";", "controlSwitch", ".", "setVisibility", "(", "GONE", ")", ";", "controlTextView", ".", "setVisibility", "(", "VISIBLE", ")", ";", "}", "else", "{", "switchTextView", ".", "setVisibility", "(", "VISIBLE", ")", ";", "controlSwitch", ".", "setVisibility", "(", "VISIBLE", ")", ";", "controlTextView", ".", "setVisibility", "(", "GONE", ")", ";", "}", "}", "private", "void", "clearControl", "(", ")", "{", "controlLayout", ".", "setVisibility", "(", "GONE", ")", ";", "stateText", ".", "setText", "(", "\"", "\"", ")", ";", "}", "public", "int", "getPinMode", "(", ")", "{", "return", "pinMode", ";", "}", "@", "Override", "public", "void", "onClick", "(", "View", "v", ")", "{", "if", "(", "callback", "==", "null", ")", "return", ";", "int", "i", "=", "(", "Integer", ")", "v", ".", "getTag", "(", ")", ";", "if", "(", "i", "==", "1", ")", "{", "callback", ".", "onPinClick", "(", "pinNum", ",", "pinViewNum", ")", ";", "}", "else", "if", "(", "i", "==", "2", ")", "{", "callback", ".", "onControlClick", "(", "pinNum", ",", "pinViewNum", ",", "pinMode", ")", ";", "}", "}", "@", "Override", "public", "void", "setPinName", "(", "String", "name", ")", "{", "pinButton", ".", "setText", "(", "name", ")", ";", "if", "(", "name", ".", "length", "(", ")", ">", "2", ")", "{", "pinButton", ".", "post", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "pinButton", ".", "setTextSize", "(", "10", ")", ";", "}", "}", ")", ";", "}", "else", "{", "pinButton", ".", "post", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "pinButton", ".", "setTextSize", "(", "17", ")", ";", "}", "}", ")", ";", "}", "}", "@", "Override", "public", "void", "setValue", "(", "int", "value", ")", "{", "controlTextView", ".", "setText", "(", "\"", "\"", "+", "value", ")", ";", "controlSwitch", ".", "setValue", "(", "value", "!=", "0", "?", "true", ":", "false", ")", ";", "switchTextView", ".", "setText", "(", "value", "!=", "0", "?", "\"", "HIGHT", "\"", ":", "\"", "LOW", "\"", ")", ";", "}", "@", "Override", "public", "void", "setPinNum", "(", "int", "pinNum", ")", "{", "this", ".", "pinNum", "=", "pinNum", ";", "}", "public", "void", "setCallback", "(", "PinViewCallback", "callback", ")", "{", "this", ".", "callback", "=", "callback", ";", "}", "}" ]
Created by dong on 3/21/16.
[ "Created", "by", "dong", "on", "3", "/", "21", "/", "16", "." ]
[ "//pin button" ]
[ { "param": "RelativeLayout", "type": null }, { "param": "View.OnClickListener,PinAble", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "RelativeLayout", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "View.OnClickListener,PinAble", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }