text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public <T> T generate(Class<T> spec, DBObject dbObject) {
if(dbObject == null) return null;
Constructor constructor = getDefaultConstructor(spec);
Object entity = invoke(constructor);
for (Field field : spec.getDeclaredFields()) {
if (!dbObject.containsField(field.getName())) {
continue;
}
Object fieldValue = null;
if (field.getAnnotation(SubDocument.class) != null) {
fieldValue = generate(field.getType(), (BasicDBObject) dbObject.get(field.getName()));
}
else if(Collection.class.isAssignableFrom(field.getType())) {
Class targetClazz = field.getType();
CollectionSpec collectionSpec = field.getAnnotation(CollectionSpec.class);
if(collectionSpec != null)
targetClazz = collectionSpec.type();
Object o = dbObject.get(field.getName());
List<Object> list = CollectionFactory.newList();
if(o != null && BasicDBList.class.isAssignableFrom(o.getClass())) {
BasicDBList values = (BasicDBList) o;
for (Object object : values) {
list.add(fieldValueDecoder.decode(targetClazz, object));
}
}
fieldValue = list;
}
else {
fieldValue = fieldValueDecoder.decode(field.getType(), dbObject.get(field.getName()));
}
setFieldValue(entity, field, fieldValue);
}
return (T) entity;
} | 9 |
public static void main(String[] args) {
User user = new User();
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(new File("D:\\Java SE\\src\\json\\object\\user.json"), user);
User user2 = objectMapper.readValue(new File("D:\\Java SE\\src\\json\\object\\user.json"), User.class);
System.out.println(user2);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | 3 |
@Test(timeout = 200)
public void testReceiveTimeout_MessageArrivesAfterTime() {
try {
consumer = new AbstractMessageConsumer(mockTopic) {
};
} catch (DestinationClosedException e) {
fail("Unexpected exception on constructor");
}
assertNotNull(mockTopic.getTopicSubscriber());
try {
Message msg = new MockMessage("TestMessage");
FutureTask<Message> future = getMessageFuture(consumer, 100);
Thread.sleep(110);
mockTopic.getTopicSubscriber().onMessage(msg);
Message received = future.get(5, TimeUnit.MILLISECONDS);
assertNull("Received message,after timeout, is not null ", received);
received = consumer.receive();
assertNotNull("Received message is null ", received);
assertEquals("Message values dont match.", msg.getMessage(),
received.getMessage());
} catch (InterruptedException e) {
fail("Timeout did not happen on receive method");
} catch (Exception e) {
logger.error("Error while calling receiving message", e);
fail("Error while calling onMessage:" + e.getMessage());
}
} | 3 |
public void rewindNbits(int N)
{
totbit -= N;
buf_byte_idx -= N;
if (buf_byte_idx<0)
buf_byte_idx += BUFSIZE;
} | 1 |
public void iTunes(String[] args) {
if(args.length < 2) {
bot.errorMessage(channel, sender, "incorrect parameters. !help for details");
return;
}
args = argsPrepare(args);
args[1] = platformAlias(args[1]);
String response;
// return both 32 and 64 bit urls for windows
if(args[1].toLowerCase().equals("win") && args[3].toLowerCase().equals("url"))
response = "32 bit: " + makeURLRequest(APIBASE + "/iTunes/" + args[1] + "/" + args[2] + "/" + "url")
+ " 64 bit: " + makeURLRequest(APIBASE + "/iTunes/" + args[1] + "/" + args[2] + "/" + "64biturl");
else
response = makeURLRequest(APIBASE + "/iTunes/" + args[1] + "/" + args[2] + "/" + args[3]);
if(args.length > 2 && (args[3].equals("releasedate") || args[3].equals("uploaddate"))) {
// format the response in something slightly nicer than RFC3339
response = parseRFC3339(response);
}
sendMessage((response != null
? "the " + args[3] + " for " + args[1] + " (" + args[2] + ") is " + response
: "this request combo is unknown."));
} // iTunes | 7 |
@Override
public Boolean visitIf(IfTree node, Context p) {
IfTree currentTree = node;
StatementTree endingTree;
int count = 0;
while (true) {
if (currentTree.getElseStatement() == null) {
count++;
StatementTree thenTree = currentTree.getThenStatement();
if (thenTree instanceof IfTree) {
currentTree = (IfTree) thenTree;
} else if (thenTree instanceof BlockTree) {
BlockTree blockTree = (BlockTree) thenTree;
if (blockTree.getStatements().size() == 1
&& blockTree.getStatements().get(0) instanceof IfTree) {
currentTree = (IfTree) blockTree.getStatements().get(0);
} else {
endingTree = thenTree;
break;
}
} else {
endingTree = thenTree;
break;
}
} else {
endingTree = currentTree;
break;
}
}
if (count >= MIN_IFS) {
RefactoringSuggestion rs = new CCEAndRefactoringSuggestion(p, node,
currentTree);
suggestions.add(rs);
}
if (endingTree instanceof IfTree) {
currentTree.getThenStatement().accept(this, p);
currentTree.getElseStatement().accept(this, p);
} else {
endingTree.accept(this, p);
}
return true;
} | 8 |
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int cases = 1;
while (true) {
// input
m = input.nextInt();
n = input.nextInt();
if (m + n == 0) return;
x1 = input.nextInt();
y1 = input.nextInt();
x2 = input.nextInt();
y2 = input.nextInt();
x3 = input.nextInt();
y3 = input.nextInt();
// get the stops
int size = n * m;
s1 = size / 4;
s2 = size / 2;
s3 = 3 * size / 4;
s4 = size;
steps = 0;
// solve it
grid = new int[m][n]; // 1 is default, 2 for curr, 3 for visited, - for station
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
grid[i][j] = 1;
// set the stations
grid[x1][y1] = -1;
grid[x2][y2] = -1;
grid[x3][y3] = -1;
grid[0][1] = -1;
// make the first move
int routes = solve(0, 0, 1);
// output
System.out.printf("Case %d: %d\n", cases, routes);
++cases;
}
} | 4 |
public void register(final Region region) {
this.regions.add(region);
this.references.put(region, 0L);
if (!region.active) return;
// load region into applicable loaded chunk index entries
for (final ChunkCoordinates coords : region.chunks())
if (this.world.isChunkLoaded(coords.x, coords.z))
this.cache(coords.getHash(), region);
} | 3 |
public Serializable decode(File file, Map parameters) {
Serializable object = null;
try {
ObjectInputStream stream = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(file)));
object = (Serializable) stream.readObject();
stream.close();
} catch (IOException e) {
throw new ParseException("Could not open file to read!");
} catch (ClassCastException e) {
throw new ParseException("Bad Class Read!");
} catch (ClassNotFoundException e) {
throw new ParseException("Unrecognized Class Read!");
}
return object;
} | 3 |
int insertKeyRehash(int val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
} | 9 |
public static void dump_grammar() throws internal_error
{
System.err.println("===== Terminals =====");
for (int tidx=0, cnt=0; tidx < terminal.number(); tidx++, cnt++)
{
System.err.print("["+tidx+"]"+terminal.find(tidx).name()+" ");
if ((cnt+1) % 5 == 0) System.err.println();
}
System.err.println();
System.err.println();
System.err.println("===== Non terminals =====");
for (int nidx=0, cnt=0; nidx < non_terminal.number(); nidx++, cnt++)
{
System.err.print("["+nidx+"]"+non_terminal.find(nidx).name()+" ");
if ((cnt+1) % 5 == 0) System.err.println();
}
System.err.println();
System.err.println();
System.err.println("===== Productions =====");
for (int pidx=0; pidx < production.number(); pidx++)
{
production prod = production.find(pidx);
System.err.print("["+pidx+"] "+prod.lhs().the_symbol().name() + " ::= ");
for (int i=0; i<prod.rhs_length(); i++)
if (prod.rhs(i).is_action())
System.err.print("{action} ");
else
System.err.print(
((symbol_part)prod.rhs(i)).the_symbol().name() + " ");
System.err.println();
}
System.err.println();
} | 7 |
public void setItemId(int itemId) {
this.itemId = itemId;
} | 0 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final Physical target = mob.location();
if(target.fetchEffect(this.ID())!=null)
{
mob.tell(mob,null,null,L("An Ice Sheet is already here!"));
return false;
}
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
String msgStr=L("the ground becomes covered in ice!");
if(CMLib.flags().isWateryRoom(mob.location()))
msgStr=L("the water freezes over!");
if(auto)
msgStr=Character.toUpperCase(msgStr.charAt(0))+msgStr.substring(1);
final CMMsg msg = CMClass.getMsg(mob, target, this, somanticCastCode(mob,target,auto),L(auto?"":"^S<S-NAME> speak(s) and gesture(s) and ")+msgStr+"^?");
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
Spell_IceSheet sheet=(Spell_IceSheet)beneficialAffect(mob,mob.location(),asLevel,0);
if(sheet != null)
{
sheet.theSheet = CMClass.getBasicItem("StdItem");
sheet.theSheet.setName("an ice sheet");
sheet.theSheet.setDisplayText("an enormous ice sheet covers the ground here");
CMLib.flags().setGettable(sheet.theSheet, false);
mob.location().addItem(sheet.theSheet);
}
}
}
else
return beneficialVisualFizzle(mob,null,L("<S-NAME> speak(s) about the cold, but the spell fizzles."));
// return whether it worked
return success;
} | 8 |
@Override
public void draw() {
if (hidden) {
return;
}
super.draw();
for (GUIComponent component : subComponents) {
component.draw();
}
} | 2 |
public Map<String, ArrayList<RowData>> getObjectsFromTable(
String tableName, String columnFamily, String startRange,
String endRange, String... retrieveColumns) throws IOException {
// Validate the tableName
if (!validateStringIfNullOrEmpty(tableName)) {
throw new IllegalArgumentException(
"Invalid tableName input to HBaseConnectionUtil.getObjectsFromTable");
}
// Scan object to loop through the Table to find the objects
Scan scan = new Scan();
byte[] columnFamilyBytes = Bytes.toBytes(columnFamily);
scan.addFamily(columnFamilyBytes);
// Add the filter for columns to be retrieved
if (retrieveColumns != null && retrieveColumns.length > 0) {
for (String columnName : retrieveColumns)
scan.addColumn(columnFamilyBytes, Bytes.toBytes(columnName));
}
// Get the table object refered by the tableName
HTableInterface table = getHTable(tableName);
// Check if the startRange and endRange are given
// If yes, set the start and end range for the scan object created above
if (validateStringIfNullOrEmpty(startRange, endRange)) {
scan.setStartRow(Bytes.toBytes(startRange));
scan.setStopRow(Bytes.toBytes(endRange));
}
// Create a Data Structure to store the data from the table
// Key for the Map is a String i.e. the rowID for the given table
// Value is an ArrayList of RowData. RowData is going to be used to save
// the
// Key-Value pairs inside the column family
Map<String, ArrayList<RowData>> resultSet = new HashMap<String, ArrayList<RowData>>();
// Initiate the Scanning of the Table
ResultScanner scanner = table.getScanner(scan);
RowData rowData = null;
String rowId = null;
ArrayList<RowData> mapValue;
// Looping through the Scanned Result
for (Result result : scanner) {
// Extracting the KeyValue pair for each row inside the column
// family
for (KeyValue keyValue : result.raw()) {
rowData = new RowData();
rowData.setKey(Bytes.toString(keyValue.getQualifier()));
rowData.setValue(Bytes.toString(keyValue.getValue()));
rowId = Bytes.toString(result.getRow());
// Check if the Map contains the rowID
// if yes, re-use the corresponding ArrayList to store the new
// RowData object
// or else create a new one
if (resultSet.containsKey(rowId)) {
mapValue = resultSet.get(rowId);
} else {
mapValue = new ArrayList<RowData>();
}
// Storing the new RowData object inside the ArrayList
mapValue.add(rowData);
// Saving it inside the Map
resultSet.put(rowId, mapValue);
}
}
return resultSet;
} | 8 |
public double simulateHandWithSharedCards(ArrayList<Card> holeCards, ArrayList<Card> sharedCards, int players) throws Exception {
if (sharedCards.size() < 3) {
throw new Exception("Less then 3 shared cards");
}
Deck deck = new Deck();
deck.removeCards(holeCards);
deck.removeCards(sharedCards);
ArrayList<Card> sharedAndHoleCards = new ArrayList<Card>();
sharedAndHoleCards.addAll(holeCards);
sharedAndHoleCards.addAll(sharedCards);
CardPower power = new PowerRanking().calcCardPower(sharedAndHoleCards);
ArrayList<ArrayList<Card>> holeCardsCombinations = deck.holeCardsCombinations();
int wins = 0;
int ties = 0;
int losses = 0;
for (ArrayList<Card> opponentHoleCards: holeCardsCombinations) {
ArrayList<Card> opponentSharedAndHoleCards = new ArrayList<Card>();
opponentSharedAndHoleCards.addAll(opponentHoleCards);
opponentSharedAndHoleCards.addAll(sharedCards);
CardPower opponentPower = new PowerRanking().calcCardPower(opponentSharedAndHoleCards);
if (opponentPower.compareTo(power) == 0) { // tie
ties++;
} else if(opponentPower.compareTo(power) > 0) { // loss
losses++;
} else { // win
wins++;
}
}
return Math.pow((wins + 0.5 * ties) / ( wins + ties + losses), players);
} | 4 |
private boolean testLocation(XYLocation location) {
if (location.getXCoOrdinate()<0 || location.getXCoOrdinate()>rowBoard-1)
return false;
if (location.getYCoOrdinate()<0 || location.getYCoOrdinate()>colBoard-1)
return false;
return true;
} | 4 |
public static PGM difference(PGM img1, PGM img2){
try{
if (img1.getHauteur() != img2.getHauteur() || img1.getLargeur() != img2.getLargeur()){
throw (new DifferentSizeException());
}
} catch (Exception e){
System.out.println("Les deux images doivent être de la même taille.");
}
ArrayList<Integer> list = new ArrayList<>();
for(int i =0; i< img1.getNiveauxGris().size(); i++){
list.add(Math.abs(img1.getNiveauxGris().get(i) - img2.getNiveauxGris().get(i)));
}
return new PGM(img1.getMaxNiveauGris(),img1.getHauteur(),img1.getLargeur(),list);
} | 4 |
private void drawString(Graphics2D g2d, String text, int startAngle, int angle){
double percent = (double) Math.round((double) angle/360*100*1000)/1000;
if(percent > 5 || text.equalsIgnoreCase("Other")){
g2d.setColor(Color.BLACK);
g2d.setFont(getFont().deriveFont(9.0f));
g2d.drawString(text, (float) Math.cos(Math.toRadians(-(angle/2 + startAngle) - 90))*80 + 140 - text.length()*2, (float) Math.sin(Math.toRadians(-(angle/2 + startAngle) - 90))*80 + 140);
} else {
g2d.setColor(Color.BLACK);
g2d.setFont(getFont().deriveFont(9.0f));
g2d.drawString(String.valueOf(n), (float) Math.cos(Math.toRadians(-(angle/2 + startAngle) - 90))*90 + 140, (float) Math.sin(Math.toRadians(-(angle/2 + startAngle) - 90))*90 + 140);
n++;
}
} | 2 |
public void createPath() {
if (dir.exists()) {
return;
}
if (!dir.mkdir()) {
throw new DataBaseException("Cannot create directory!");
}
} | 2 |
private static String solve(char[][] x, int N) {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
if (x[i][j] == '#') {
if (!remove(x, N, i, j)) return "NO";
if (!remove(x, N, i+1, j-1)) return "NO";
if (!remove(x, N, i+1, j)) return "NO";
if (!remove(x, N, i+1, j+1)) return "NO";
if (!remove(x, N, i+2, j)) return "NO";
}
return "YES";
} | 8 |
public void formatStringOne(char[] str, int length) {
boolean isWord = false;
int start = 0, end = 0, wordCount = 0;
for (int i = 0; i < length; i++) {
if (str[i] != ' ' && isWord == false) {
isWord = true;
start = i;
} else if (str[i] == ' ' && isWord == true) {
isWord = false;
end = i - 1;
if (wordCount > 0) {
System.out.print(' ');
}
for (int j = start; j <= end; j++) {
System.out.print(str[j]);
}
wordCount++;
}
}
} | 7 |
@Override
public void Handle(byte[] message, Server server, IOClient p) {
Player player;
if (p instanceof Player) {
player = (Player)p;
}
else
return;
ByteBuffer bb = ByteBuffer.allocate(9);
bb.put(message);
//byte ID = bb.get(0);
short X = bb.getShort(1);
short Y = bb.getShort(3);
short Z = bb.getShort(5);
player.yaw = bb.get(7);
player.pitch = bb.get(8);
player.setX(X);
player.setY(Y);
player.setZ(Z);
PlayerMoveEvent event = new PlayerMoveEvent(player, X, Y, Z);
server.getEventSystem().callEvent(event);
if (event.isCancelled()) {
player.setPos(player.oldX, player.oldY, player.oldZ, player.oldyaw, player.oldpitch);
return;
}
try {
player.UpdatePos();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 3 |
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
} | 0 |
public Product() {
} | 0 |
private void requestUpdatesPath() {
boolean valid = false;
File f;
while (!valid) {
String path = requestInput("SQL Updates Folder");
Path p = Paths.get(path);
f = p.toFile();
if (f.canRead() && f.isDirectory()) {
// path found
updatesfolder = p;
return;
} else {
console.printf("Please enter a proper path and make sure it`s readable!\n");
}
}
} | 3 |
public static void normalizeNotProposition(Proposition self) {
{ Stella_Object argument = (self.arguments.theArray)[0];
Proposition proposition = null;
if (Logic.variableP(argument)) {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
{ Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get();
try {
Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true);
stream000.nativeStream.println("ERROR: Can't yet handle propositional variables within negations.");
Logic.helpSignalPropositionError(stream000, Logic.KWD_ERROR);
} finally {
Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000);
}
}
throw ((PropositionError)(PropositionError.newPropositionError(stream000.theStringReader()).fillInStackTrace()));
}
}
proposition = ((Proposition)(argument));
if (proposition.kind == Logic.KWD_EQUIVALENT) {
Proposition.normalizeProposition(proposition);
}
{ Keyword testValue000 = proposition.kind;
if ((testValue000 == Logic.KWD_ISA) ||
((testValue000 == Logic.KWD_PREDICATE) ||
(testValue000 == Logic.KWD_FUNCTION))) {
if (BooleanWrapper.coerceWrappedBooleanToBoolean(proposition.variableTypeP())) {
Proposition.overlayWithConstantProposition(self, Logic.FALSE_PROPOSITION);
}
else {
Proposition.normalizeProposition(proposition);
}
}
else if (testValue000 == Logic.KWD_CONSTANT) {
{ GeneralizedSymbol testValue001 = proposition.operator;
if (testValue001 == Logic.SGT_STELLA_TRUE) {
Proposition.overlayWithConstantProposition(self, Logic.FALSE_PROPOSITION);
}
else if (testValue001 == Logic.SGT_STELLA_FALSE) {
Proposition.overlayWithConstantProposition(self, Logic.TRUE_PROPOSITION);
}
else {
}
}
}
else {
Proposition.invertProposition(proposition);
Proposition.overlayProposition(self, proposition);
}
}
}
} | 9 |
public String getString(String key) {
Object value = get(key);
return value != null ? value.toString() : ""; //$NON-NLS-1$
} | 1 |
private void generateLabelPositions() {
boolean addedCandidate = false;
// Start off with label that is in the middle of the line
LineTextParameter candidate = new LineTextParameter(use, 50);
try {
candidate.getGeometry();
addCandidate(candidate);
addedCandidate=true;
} catch (FalloffException e){
System.err.println("Invalid offset "+50);
} catch (TightBendException e){
System.err.println("Bend too much");
}
// Add other positions along line
for(int percentage=10; percentage<100; percentage=percentage+10){
if(percentage==50){
continue;
}
candidate = new LineTextParameter(use, percentage);
try {
candidate.getGeometry();
addCandidate(candidate);
addedCandidate=true;
} catch (FalloffException e){
System.err.println("Invalid offset "+percentage);
break;
} catch (TightBendException e){
System.err.println("Bend too much");
}
}
if(addedCandidate==false){
System.err.println("No valid candidate for: "+use.getTextContent());
// Clear label if it does not fit anywhere
use.setTextContent("");
}
} | 7 |
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
handler.beforeStart();
if (method.getAnnotation(Sql.class) != null) {
return sql(method, args, method.getAnnotation(Sql.class));
}
return null;
} | 1 |
public void fileReader() {
try {
File fileComplete = getFile();
Scanner lineRead = new Scanner(fileComplete);
while (lineRead.hasNextLine() == true) {
String lineTemp = lineRead.nextLine();
// "Items:" = storeLine, "~" = itemLine, "=" = fusionLine
if (lineTemp.contains(" Items:")) {
handleStoreLine(lineTemp);
}
else if (lineTemp.contains("~")) {
handleItemLine(lineTemp);
}
else if (lineTemp.contains("=")) {
handleFusionLine(lineTemp);
}
}
} catch (FileNotFoundException fnfe) {
System.out.println("File could not be found");
}
} | 5 |
@Override
public Command planNextMove(Info info) {
// you can NONE, MOVE_FORWARD, MOVE_BACK, TURN_LEFT, TURN_RIGHT, SHOOT
InfoDetail myInfo = new InfoDetail(info.getX(), info.getY(), info.getDirection());
if(info.getEnemies().isEmpty() && info.getGrenades().isEmpty()){
return new Command(CommandType.NONE, CommandType.NONE, 0, CommandType.NONE);
}
if(info.getGrenades().isEmpty()){
return new Command(CommandType.NONE, CommandType.TURN_RIGHT, aimRight(firstEnemy(info.getEnemies(), myInfo), myInfo), CommandType.SHOOT);
}
InfoDetail granat=firstGranateForMe(myInfo, info.getGrenades());
if(granat!=null){
return new Command(CommandType.MOVE_FORWARD, CommandType.TURN_RIGHT, 90+granat.getDirection()-myInfo.getDirection(), CommandType.NONE);
}
if(!info.getEnemies().isEmpty()){
return new Command(CommandType.NONE, CommandType.TURN_RIGHT, aimRight(firstEnemy(info.getEnemies(), myInfo), myInfo), CommandType.SHOOT);
}
return new Command(CommandType.NONE, CommandType.NONE, 0, CommandType.NONE);
} | 5 |
public static void main(String[] args) throws IOException {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Title frame = new Title();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} | 1 |
private void createJFinalConfig(String configClass) {
if (configClass == null) {
throw new RuntimeException("please set configClass in the web.xml");
}
try {
Object o = Class.forName(configClass).newInstance();
if (o instanceof JFinalConfig) {
jfinalConfig = (JFinalConfig) o;
}
else {
throw new RuntimeException("Can not new instance by configClass : "+configClass);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} | 5 |
public Boolean loginUser(String login, String password){
PreparedStatement pStmt = null;
ResultSet rs = null;
Boolean returnLogin = false;
try {
pStmt = conn.prepareStatement("SELECT * FROM USER WHERE login = ? AND password = ?;");
pStmt.setString(1, login);
pStmt.setString(2, getMD5Hash(password));
rs = pStmt.executeQuery();
if(rs.next()) returnLogin = true;
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeResource(pStmt);
closeResource(rs);
}
return returnLogin;
} | 2 |
public void load(){
synchronized(options){
try {
options.load(new FileInputStream("timers.conf"));
synchronized (timers){
timers.clear();
for(Object key : options.keySet()){
String str = key.toString();
if(str.indexOf("Name")>0){
continue;
}
String tmp[] = options.getProperty(str).split(",");
try{
int start = Integer.parseInt(tmp[0]);
int time = Integer.parseInt(tmp[1]);
String name = options.getProperty(str+"Name");
new Timer(start, time, name);
} catch(Exception e){}
}
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
} | 5 |
static private final int jjMoveStringLiteralDfa3_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(1, old0);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(2, active0);
return 3;
}
switch(curChar)
{
case 78:
return jjMoveStringLiteralDfa4_0(active0, 0x20L);
case 95:
return jjMoveStringLiteralDfa4_0(active0, 0x40L);
case 107:
return jjMoveStringLiteralDfa4_0(active0, 0x2000L);
case 110:
return jjMoveStringLiteralDfa4_0(active0, 0x80L);
case 112:
return jjMoveStringLiteralDfa4_0(active0, 0xa00L);
case 115:
return jjMoveStringLiteralDfa4_0(active0, 0x1100L);
case 117:
return jjMoveStringLiteralDfa4_0(active0, 0x400L);
default :
break;
}
return jjStartNfa_0(2, active0);
} | 9 |
private String signup(String[] msg) {
String ans =null;
user.User user = forumSystem.signup(msg[1], msg[2], msg[3],msg[4], msg[5]);
if (user!=null) {
this.user=user;
ans="SUCC_SIGNUP";
}
else ans="ERR_SIGNUP";
return ans;
} | 1 |
public void centerViewOnPoint(int index)
{
//MapGetter.getMapImage(MapGetter.createUrl(markerRect.getLongtitude(index), markerRect.getLatitude(index)));
//repaint();
} | 0 |
public static void main(String[] args) {
int i;
for ( i = 0; i < 10; i++)
switch(i) {
case 0:
System.out.println("i is zero");
break;
case 1:
System.out.println("i is one");
break;
case 2:
System.out.println("i is two");
break;
case 3:
System.out.println("i is three");
break;
case 4:
System.out.println("i is four");
break;
default:
System.out.println(" i is five or more");
}
} | 6 |
public void initializeKeySet()
{
int i1;
int j1;
int k1;
int l1;
int i2;
int j2;
int k2;
int l = i1 = j1 = k1 = l1 = i2 = j2 = k2 = 0x9e3779b9;
for(int i = 0; i < 4; i++)
{
l ^= i1 << 11;
k1 += l;
i1 += j1;
i1 ^= j1 >>> 2;
l1 += i1;
j1 += k1;
j1 ^= k1 << 8;
i2 += j1;
k1 += l1;
k1 ^= l1 >>> 16;
j2 += k1;
l1 += i2;
l1 ^= i2 << 10;
k2 += l1;
i2 += j2;
i2 ^= j2 >>> 4;
l += i2;
j2 += k2;
j2 ^= k2 << 8;
i1 += j2;
k2 += l;
k2 ^= l >>> 9;
j1 += k2;
l += i1;
}
for(int j = 0; j < 256; j += 8)
{
l += keySetArray[j];
i1 += keySetArray[j + 1];
j1 += keySetArray[j + 2];
k1 += keySetArray[j + 3];
l1 += keySetArray[j + 4];
i2 += keySetArray[j + 5];
j2 += keySetArray[j + 6];
k2 += keySetArray[j + 7];
l ^= i1 << 11;
k1 += l;
i1 += j1;
i1 ^= j1 >>> 2;
l1 += i1;
j1 += k1;
j1 ^= k1 << 8;
i2 += j1;
k1 += l1;
k1 ^= l1 >>> 16;
j2 += k1;
l1 += i2;
l1 ^= i2 << 10;
k2 += l1;
i2 += j2;
i2 ^= j2 >>> 4;
l += i2;
j2 += k2;
j2 ^= k2 << 8;
i1 += j2;
k2 += l;
k2 ^= l >>> 9;
j1 += k2;
l += i1;
cryptArray[j] = l;
cryptArray[j + 1] = i1;
cryptArray[j + 2] = j1;
cryptArray[j + 3] = k1;
cryptArray[j + 4] = l1;
cryptArray[j + 5] = i2;
cryptArray[j + 6] = j2;
cryptArray[j + 7] = k2;
}
for(int k = 0; k < 256; k += 8)
{
l += cryptArray[k];
i1 += cryptArray[k + 1];
j1 += cryptArray[k + 2];
k1 += cryptArray[k + 3];
l1 += cryptArray[k + 4];
i2 += cryptArray[k + 5];
j2 += cryptArray[k + 6];
k2 += cryptArray[k + 7];
l ^= i1 << 11;
k1 += l;
i1 += j1;
i1 ^= j1 >>> 2;
l1 += i1;
j1 += k1;
j1 ^= k1 << 8;
i2 += j1;
k1 += l1;
k1 ^= l1 >>> 16;
j2 += k1;
l1 += i2;
l1 ^= i2 << 10;
k2 += l1;
i2 += j2;
i2 ^= j2 >>> 4;
l += i2;
j2 += k2;
j2 ^= k2 << 8;
i1 += j2;
k2 += l;
k2 ^= l >>> 9;
j1 += k2;
l += i1;
cryptArray[k] = l;
cryptArray[k + 1] = i1;
cryptArray[k + 2] = j1;
cryptArray[k + 3] = k1;
cryptArray[k + 4] = l1;
cryptArray[k + 5] = i2;
cryptArray[k + 6] = j2;
cryptArray[k + 7] = k2;
}
generateNextKeySet();
keyArrayIdx = 256;
} | 3 |
public void run() {
try {
WebServer webServer = new WebServer(port);
XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer();
PropertyHandlerMapping phm = new PropertyHandlerMapping();
phm.addHandler( "StockProcedure", MyWebServer.class);
xmlRpcServer.setHandlerMapping(phm);
XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig();
serverConfig.setEnabledForExtensions(true);
serverConfig.setContentLengthOptional(false);
webServer.start();
System.out.println("The Web Server has been started..." );
} catch (Exception exception) {
System.err.println("JavaServer: " + exception);
}
} | 1 |
private static final int method2894
(int i, int i_16_, byte[] is, int[] is_17_, int i_18_, int i_19_,
int i_20_, int i_21_, int i_22_, int i_23_, int i_24_,
Class348_Sub16_Sub5 class348_sub16_sub5, int i_25_, int i_26_) {
if (i_25_ == 0
|| (i_22_ = i_19_ + (i_24_ + 256 - i_18_ + i_25_) / i_25_) > i_23_)
i_22_ = i_23_;
i_19_ <<= 1;
i_22_ <<= 1;
while (i_19_ < i_22_) {
i_16_ = i_18_ >> 8;
i = is[i_16_ - 1];
i = (i << 8) + (is[i_16_] - i) * (i_18_ & 0xff);
is_17_[i_19_++] += i * i_20_ >> 6;
is_17_[i_19_++] += i * i_21_ >> 6;
i_18_ += i_25_;
}
if (i_25_ == 0
|| ((i_22_ = (i_19_ >> 1) + (i_24_ - i_18_ + i_25_) / i_25_)
> i_23_))
i_22_ = i_23_;
i_22_ <<= 1;
i_16_ = i_26_;
while (i_19_ < i_22_) {
i = (i_16_ << 8) + (is[i_18_ >> 8] - i_16_) * (i_18_ & 0xff);
is_17_[i_19_++] += i * i_20_ >> 6;
is_17_[i_19_++] += i * i_21_ >> 6;
i_18_ += i_25_;
}
class348_sub16_sub5.anInt8983 = i_18_;
return i_19_ >> 1;
} | 6 |
public static void main(String[] args)
{
// Load GUI by default
boolean headless = false;
// Folder to log stuff to
String logFolderPath = System.getProperty("user.dir") + File.separator;
/*
* Parse arguments
*/
String arguments = "";
for(String string : args)
{
arguments += " " + string;
}
Scanner scanner = new Scanner(arguments);
while(scanner.hasNext())
{
String next = scanner.next();
if(next.equals("--headless"))
{
headless = true;
}
else if(next.equals("--folder"))
{
if(scanner.hasNext())
{
logFolderPath = scanner.next();
}
}
}
/*
* Set up the proxy
*/
//Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("130.209.6.40", 8080));
Proxy proxy = Proxy.NO_PROXY;
/*
* Create logger
*/
File logFolder = new File(logFolderPath);
//final AbstractLogger logger = new Logger();
final AbstractLogger logger = new FrequencyLogger();
/*
* Start (graphical) user interface
*/
if(headless)
{
CLI cli = new CLI(proxy, logger, logFolder, 120000);
cli.start();
}
else
{
GUI gui = new GUI(proxy, logger, logFolder, 120000);
gui.start();
}
} | 6 |
protected void layoutChildren(Rectangle[] bounds) {
for (int i = 0; i < bounds.length; i++) {
mChildren.get(i).layout(bounds[i]);
}
} | 1 |
static String readFieldId(RandomAccessFile raf, int length, VorbisCommentBlock block) throws IOException {
StringBuilder fieldId = new StringBuilder();
char c;
while( (c=(char)MediaFileUtil.read_sure(raf))!= '=' ) {
fieldId.append(c);
}
return new String(fieldId);
} | 1 |
@Test
public void reTest7() {
userInput.add("hi");
userInput.add("my name is meng meng");
userInput.add("can you bring me something");
userInput.add("knife");
userInput.add("errorhandling");
userInput.add("errorhandling");
userInput.add("errorhandling");
userInput.add("errorhandling");
userInput.add("handle the error");
userInput.add("handle the error somehow");
userInput.add("handle this error");
userInput.add("bring me a knife");
this.runMainActivityWithTestInput(userInput);
assertTrue((nlgResults.get(4).contains("again") || nlgResults.get(4).contains("repeat"))
&& (nlgResults.get(6).contains("again") || nlgResults.get(6).contains("repeat"))
&& nlgResults.get(7).contains("rephrase")
&& nlgResults.get(9).contains("rephrase")
&& nlgResults.get(10).contains("tools")
&& nlgResults.get(11).contains("silverware drawer"));
} | 7 |
public void readDB(String path, String styleYear){
// check to see if the style guide is in the DB already
dbPath = path;
styleFileName = "styleguide" + styleYear + ".xml";
File styleFile = new File(path, styleFileName);
if(styleFile != null && !styleFile.exists()){
Frame window = new Frame();
// style file doesn't exist!
new Dialog(window, "Can not open style guide: "+path+"/"+styleFileName+"\n Please check your install!");
//try reverting to the base styleguide
styleFileName = "styleguide.xml";
styleFile = new File(path, styleFileName);
}
try {
styleDB.clear();
stockFermDB.clear();
fermDB.clear();
stockHopsDB.clear();
hopsDB.clear();
yeastDB.clear();
waterDB.clear();
readFermentables(dbPath);
readPrimeSugar(dbPath);
readHops(dbPath);
readYeast(dbPath);
readMisc(dbPath);
importStyles(dbPath, styleYear);
readWater(dbPath);
// sort
Debug.print(styleDB.size());
Collections.sort(styleDB);
Collections.sort(fermDB);
Collections.sort(hopsDB);
Collections.sort(yeastDB);
Collections.sort(waterDB);
} catch (NullPointerException e) {
e.printStackTrace();
}
} | 3 |
public static void main(String[] args) throws IOException {
Socket sock = parseArgs(args);
if (sock == null)
return;
AI solver = new SimpleAI();
Game game = new Game(NAME, sock);
int gameResult = game.solve(solver);
if(gameResult == game.getID())
System.out.println("Congratz");
else if(gameResult >= 1)
System.out.format("gg to player %d\n", gameResult);
} | 3 |
public boolean isAvailable(Date start, Date end) {
if(!start.before(end))
throw new IllegalArgumentException("Illegal given period");
for(Reservation reservation : reservations) {
if(reservation.getEndDate().before(start) || reservation.getStartDate().after(end))
continue;
return false;
}
return true;
} | 4 |
public void update(){
for(Map.Entry<Memorable,JLabel> entry:labels.entrySet()){
Memorable memorable = entry.getKey();
float hp = memorable.hasHistory();
Color color=new Color(hp,hp,hp);
if(hp==1){
boolean wasBetter=false;
float er=memorable.errorRate();
if(best.containsKey(memorable)){
wasBetter=er> best.get(memorable);
er=Math.min(er, best.get(memorable));
}
best.put(memorable,er);
if(wasBetter){
if(er<0.3){
color = new Color(0,128,0);
}else if(er>0.7){
color = new Color(128,0, 0);
}else{
color = new Color(128,128,0);
}
}else{
if(er<0.3){
color = Color.GREEN;
}else if(er>0.7){
color = Color.RED;
}else{
color=Color.YELLOW;
}
}
}
entry.getValue().setForeground(color);
}
root.repaint();
} | 8 |
public void method357() {
if (imageWidth == libWidth && imageHeight == anInt1457)
return;
byte abyte0[] = new byte[libWidth * anInt1457];
int i = 0;
for (int j = 0; j < imageHeight; j++) {
for (int k = 0; k < imageWidth; k++)
abyte0[k + drawOffsetX + (j + drawOffsetY) * libWidth] = imagePixels[i++];
}
imagePixels = abyte0;
imageWidth = libWidth;
imageHeight = anInt1457;
drawOffsetX = 0;
drawOffsetY = 0;
} | 4 |
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getHeader("Proxy-Client-IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getHeader("WL-Proxy-Client-IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getRemoteAddr();
return ip;
} | 9 |
public Funcion(String nombre){
ArrayList<String> expresion;
ArrayList<Arbol> operandos;
puntos = new ArrayList<Punto>();
expresion = new ArrayList<String>();
operandos = new ArrayList<Arbol>();
LeerArchivo archivoIn = new LeerArchivo(nombre);
String [] linea;
try{
linea=archivoIn.readLine().split(" ");
for(int i=0; i<linea.length; i++){
expresion.add(linea[i]);
}
}
catch(Exception e){
e.printStackTrace();
}
for(int i=0; i<expresion.size(); i++){
if(Expresion.esOperador(expresion.get(i))){
if(Expresion.esOperadorBinario(expresion.get(i))){
Arbol arbolParcial = new Arbol();
arbolParcial.unir(expresion.get(i), operandos.get(operandos.size()-2), operandos.get(operandos.size()-1));
operandos.remove(operandos.size()-1);
operandos.remove(operandos.size()-1);
operandos.add(arbolParcial);
}
if(Expresion.esOperadorUnario(expresion.get(i))){
Arbol arbolParcial = new Arbol();
arbolParcial.unir(expresion.get(i), operandos.get(operandos.size()-1));
operandos.remove(operandos.size()-1);
operandos.add(arbolParcial);
}
}
if(Expresion.esOperando(expresion.get(i))){
operandos.add(new Arbol(expresion.get(i)));
}
}
arbol = operandos.get(operandos.size()-1);
} | 7 |
boolean isPalindorme(String s, int start, int end) {
for (int i = start, j = end; i < j; i++, j--)
if (s.charAt(i) != s.charAt(j))
return false;
return true;
} | 2 |
public void initialDeal(ArrayList<Player> players, Dealer dealer, int numPlayers){
for (int i=0;i<numPlayers;i++)
{//This loop goes through an array and deals initial cards to each player in the array
for (int j=0;j<2;j++)//this interior loop makes sure that 2 cards are dealt since this is initial hand
players.get(i).addCardtoHand(dealer.DealCard());
}
for (int i=0;i<2;i++)
dealer.addCardtoHand(dealer.DealCard());//loops through twice to give the dealer 2 cards
} | 3 |
public Fruit(Player[] players, int bowlsize, int[] dist)
{
this.players = players;
this.bowlsize = bowlsize;
this.nfruits = bowlsize * players.length;
this.fruitDist = dist;
// generate the preference for each player
preference = new int[players.length][];
for (int i = 0; i != players.length; ++i) {
preference[i] = genPref();
players[i].init(players.length, preference[i].clone());
}
// compute expectation
expectation = new int[players.length];
for (int p = 0; p != players.length; ++p) {
expectation[p] = computeExpectation(preference[p], dist, nfruits, bowlsize);
}
// bowl of player of both rounds
bowlOfPlayer = new int[2][players.length][];
timeout = new boolean[players.length];
printConfig();
} | 2 |
public void test(String script)
throws EugeneException {
try {
// first, we need to parse the script
this.parse(script);
} catch(Exception e) {
throw new EugeneException(e.getMessage());
}
Map<String, List<CompositePredicate>> predicates =
this.parser.getPredicateRepository().getPredicates();
List<Component[]> solutions = new ArrayList<Component[]>();
for(String name : predicates.keySet()) {
// System.out.println("All composite predicates named " + name + ": ");
List<CompositePredicate> lst = predicates.get(name);
for(CompositePredicate cp : lst) {
// System.out.println(cp.toString());
// TEST IT
solutions.addAll(
new PredicateTester().test(cp, this.parser.getN()));
}
}
visualize(solutions);
} | 3 |
private Thread searchThreadsInGroup(final String threadName, final ThreadGroup group, final int level) {
Thread thread = null;
Thread[] threads = new Thread[group.activeCount() * 2];
int numThreads = group.enumerate(threads, false);
for (int i = 0; i < numThreads; i++) {
if (threads[i].getName().equals(threadName)) {
thread = threads[i];
}
}
if (thread == null) {
thread = searchThreadsInSubGroup(threadName, group, level);
}
return thread;
} | 3 |
private void checkType(Class<?> actual, Class<?> expected) {
if(expected==actual || expected.isAssignableFrom(actual))
return; // no problem
if( expected==JCodeModel.boxToPrimitive.get(actual) )
return; // no problem
throw new IllegalArgumentException("Expected "+expected+" but found "+actual);
} | 5 |
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length < 2) {
sender.sendMessage(new TextComponent(ChatColor.RED + "Usage: /mode <channel> <mode ...>"));
return;
}
if (!IRC.sock.isConnected()) {
sender.sendMessage(new TextComponent(ChatColor.RED + "The proxy is not connected to IRC."));
return;
}
ArrayList<String> list = new ArrayList<String>(Arrays.asList(args));
list.remove(0);
StringBuilder msg = new StringBuilder();
for (String a : list) msg.append(a).append(" ");
if (!Util.giveChannelModes(args[0], msg.toString())) {
sender.sendMessage(new TextComponent(ChatColor.RED + "One or more of the modes were not recognised."));
return;
}
sender.sendMessage(new TextComponent(ChatColor.GRAY + "Modes set."));
} | 4 |
protected void sendResponses() {
if(responses != null) {
Object obj;
for(int i=0; i < responses.length; i++) {
if(delay > 0)
Util.sleep(delay);
obj=responses[i];
if(obj == null) {
System.err.println("object was null");
continue;
}
if(obj instanceof Message) {
Message msg=(Message)obj;
Address sender=msg.getSrc();
Object retval=null;
try {
retval=Util.objectFromByteBuffer(msg.getBuffer());
}
catch(Exception e) {
e.printStackTrace();
}
request.receiveResponse(retval, sender, false);
}
else if(obj instanceof View)
request.viewChange((View)obj);
}
}
} | 7 |
private void persistResources(IArticle article) throws IOException {
for (IResource resource : article.getResources()) {
em.persist(resource);
}
} | 1 |
private boolean PlayerHidden(int posX, int poY)
{
for (Polygon p : ps)
{
if (p.contains(posX, poY))
return true;
}
return false;
} | 2 |
public static String reverseWords1(String s) {
if (s == null || s.length() == 0) {
return "";
}
String[] arrayStr = s.split(" ");
int length = arrayStr.length;
StringBuffer newStr = new StringBuffer();
for (int i = length - 1; i >= 0; i--) {
if (!arrayStr[i].trim().equals("")) {
newStr.append(arrayStr[i].trim()).append(" ");
}
}
// the last " "(space) needs to be deleted
return newStr.length() == 0 ? "": newStr.substring(0, newStr.length() - 1);
} | 5 |
public static String getFilenameExtension(String path) {
if (path == null) {
return null;
}
int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
if (extIndex == -1) {
return null;
}
int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);
if (folderIndex > extIndex) {
return null;
}
return path.substring(extIndex + 1);
} | 3 |
public static BufferedImage getTexture(String texture) {
switch(texture) {
case "grass":
return grass;
case "grassLeft":
return grassLeft;
case "grassRight":
return grassRight;
case "dirt":
return dirt;
case "log":
return log;
case "tree":
return tree;
case "bigTree":
return bigTree;
case "player_mask":
return playerMask;
case "grassSingle":
return grassSingle;
default:
return null;
}
} | 9 |
public boolean isEmpty() {
boolean retVal = false;
if (topPtr == CAPACITY) {
retVal = true;
}
return retVal;
} | 1 |
private void pivot(int p, int q) {
// everything but row p and column q
for (int i = 0; i <= M; i++)
for (int j = 0; j <= M + N; j++)
if (i != p && j != q) a[i][j] -= a[p][j] * a[i][q] / a[p][q];
// zero out column q
for (int i = 0; i <= M; i++)
if (i != p) a[i][q] = 0.0;
// scale row p
for (int j = 0; j <= M + N; j++)
if (j != q) a[p][j] /= a[p][q];
a[p][q] = 1.0;
} | 8 |
void receive() throws IOException {
if (this.closed) throw new SocketClosedException();
class Container {
public IOException exception = null;
public boolean isClosed = false;
}
final Container container = new Container();
this.listener.onData(new IBufferReadable() {
@Override
public int read(ByteBuffer buffer) {
int readed;
try {
readed = TCPSocket.this.channel.read(buffer);
} catch (IOException ex) {
container.exception = ex;
return 0;
}
if (readed != -1) {
return readed;
} else {
container.isClosed = true;
return 0;
}
}
});
if (container.exception != null) {
throw container.exception;
}
if (container.isClosed) {
throw new SocketClosedException();
}
} | 5 |
public CardStack(String file, String name) throws StorageReaderException {
stack = new ArrayList<Card>();
top = 0;
Random random = new Random();
int index;
ArrayList<Card> temp = new CardCreator(file, name).cardArray();
while(!temp.isEmpty()) {
index = random.nextInt(temp.size());
index = index - (index == 0 ? 0 : 1);
stack.add(temp.get(index));
temp.remove(index);
}
for(int i = 0; i < stack.size(); i++) {
stack.get(i).setIndex(i);
}
} | 3 |
public void setTree(JoeTree tree) {this.tree = tree;} | 0 |
@Override
public boolean update() {
finishButton.update();
fundsTextbox.update();
boolean blockFinish = false;
for(PartySelectButton selector : partySelectors) {
selector.update();
if(selector.blockFinish) {
blockFinish = true;
}
}
if(!finishButton.isImpossible && (blockFinish || (numSelectedMembers < reqNumPartyMembers))) {
setFinishButtonEnabled(false);
}
else if(finishButton.isImpossible && !blockFinish && (numSelectedMembers >= reqNumPartyMembers)) {
setFinishButtonEnabled(true);
}
return finished;
} | 8 |
public void calculerVoisinage(Node current){
ArrayList<Node> voisins = findVoisin(current);
for(Node voisin : voisins){
if(voisin.getState() != BLOCK && !closedList.contains(voisin)){
voisin.setColor(Color.gray);
int newG = current.getG_movementCost() + COUT;
if(!openList.contains(voisin) || newG < voisin.getG_movementCost()){
voisin.setParent(current);
voisin.setG_movementCost(current.getG_movementCost()+ COUT );
voisin.setH_heuristique(calculHeuristique(voisin.getXpos(), voisin.getYpos()));
// current.setG_movementCost(newG);
//current.setParent(voisin);
if(!openList.contains(voisin)){
openList.add(voisin);
}
}
}/*else{
if(newG < voisin.getG_movementCost()){
// voisin.setG_movementCost(newG);
// voisin.setParent(current);
current.setParent(voisin);
current.setG_movementCost(newG);
}
}*/
}
} | 6 |
public Object clone() {
try {
VariableSet other = (VariableSet) super.clone();
if (count > 0) {
other.locals = new LocalInfo[count];
System.arraycopy(locals, 0, other.locals, 0, count);
}
return other;
} catch (CloneNotSupportedException ex) {
throw new jode.AssertError("Clone?");
}
} | 2 |
public void render(Screen screen) {
// Where the player is found on the spritesheet
int xTile = 0;
int yTile = 28;
int walkingSpeed = 3;
// Number between 0 and 1
// top part of the body
int flipTop = (numSteps >> walkingSpeed) & 1;
// bottom part of the body
int flipBottom = (numSteps >> walkingSpeed) & 1;
if (movingDir == 1) {
xTile += 2;
} else if (movingDir > 1) {
// Third player tile start
xTile += 4 + ((numSteps >> walkingSpeed) & 1) * 2;
flipTop = (movingDir - 1) % 2;
}
// Size of the player (8x8)
int modifier = 8 * scale;
int xOffset = x - modifier / 2;
int yOffset = y - modifier / 2 - 4;
if (isSwimming) {
int waterColour = 0;
yOffset += 4;
// 1/4 of this
if (tickCount % 60 < 15) {
waterColour = Colours.get(-1, -1, 225, -1);
} else if (15 <= tickCount % 60 && tickCount % 60 < 30) {
yOffset -= 1;
waterColour = Colours.get(-1, 225, 115, -1);
} else if (30 <= tickCount % 60 && tickCount % 60 < 45) {
waterColour = Colours.get(-1, 115, -1, 225);
} else {
yOffset -= 1;
waterColour = Colours.get(-1, 225, 115, -1);
}
int tile = 0 + 27 * 32;
screen.render(xOffset,
yOffset + 3,
tile,
waterColour,
Screen.BIT_MIRROR_NONE,
Screen.NORMAL_SCALE);
// Flip the image displayed above on the x axis
screen.render(xOffset + 8,
yOffset + 3,
tile,
waterColour,
Screen.BIT_MIRROR_X,
Screen.NORMAL_SCALE);
}
// Render the first top left part of the player image (and others)
// This is for future modification (e.g. swimming etc...)
screen.render(xOffset + (modifier * flipTop), yOffset, xTile + yTile
* 32, // to get the tile number
COLOUR, flipTop, scale);
screen.render(xOffset + modifier - (modifier * flipTop), yOffset,
(xTile + 1) + yTile * 32, COLOUR, flipTop, scale);
if (!isSwimming) {
screen.render(xOffset + (modifier * flipBottom),
yOffset + modifier, xTile + (yTile + 1) * 32, COLOUR,
flipBottom, scale);
screen.render(xOffset + modifier - (modifier * flipBottom), yOffset
+ modifier, (xTile + 1) + (yTile + 1) * 32, COLOUR,
flipBottom, scale);
}
} | 9 |
private void printResults() {
for (int i = 0;i<VALUE_ITERATIONS_NUMBER;i++) {
System.out.println(results[i]);
}
} | 1 |
private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
// TODO add your handling code here:
if (saveMenuItemIsUsed == false)
{ int n = JOptionPane.showConfirmDialog(null,"Are you sure that you want to exit without saving\nAll unsaved work will be lost", "Warning!", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if(n == JOptionPane.YES_OPTION)
System.exit(0);
else
saveMenuItemIsUsed = false;
}
else
System.exit(0);
}//GEN-LAST:event_exitMenuItemActionPerformed | 2 |
private void paintScreen()
// use active rendering to put the buffered image on-screen
{
Graphics g;
try {
g = this.getGraphics();
if ((g != null) && (dbImage != null))
g.drawImage(dbImage, 0, 0, null);
// Sync the display on some systems.
// (on Linux, this fixes event queue problems)
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
catch (Exception e)
{ System.out.println("Graphics context error: " + e); }
} // end of paintScreen() | 3 |
protected void buildClassifierWithWeights(Instances data)
throws Exception {
Instances trainData, training;
double epsilon, reweight;
Evaluation evaluation;
int numInstances = data.numInstances();
Random randomInstance = new Random(m_Seed);
// Initialize data
m_Betas = new double [m_Classifiers.length];
m_NumIterationsPerformed = 0;
// Create a copy of the data so that when the weights are diddled
// with it doesn't mess up the weights for anyone else
training = new Instances(data, 0, numInstances);
// Do boostrap iterations
for (m_NumIterationsPerformed = 0; m_NumIterationsPerformed < m_Classifiers.length;
m_NumIterationsPerformed++) {
if (m_Debug) {
System.err.println("Training classifier " + (m_NumIterationsPerformed + 1));
}
// Select instances to train the classifier on
if (m_WeightThreshold < 100) {
trainData = selectWeightQuantile(training,
(double)m_WeightThreshold / 100);
} else {
trainData = new Instances(training, 0, numInstances);
}
// Build the classifier
if (m_Classifiers[m_NumIterationsPerformed] instanceof Randomizable)
((Randomizable) m_Classifiers[m_NumIterationsPerformed]).setSeed(randomInstance.nextInt());
m_Classifiers[m_NumIterationsPerformed].buildClassifier(trainData);
// Evaluate the classifier
evaluation = new Evaluation(data);
evaluation.evaluateModel(m_Classifiers[m_NumIterationsPerformed], training);
epsilon = evaluation.errorRate();
// Stop if error too small or error too big and ignore this model
if (Utils.grOrEq(epsilon, 0.5) || Utils.eq(epsilon, 0)) {
if (m_NumIterationsPerformed == 0) {
m_NumIterationsPerformed = 1; // If we're the first we have to to use it
}
break;
}
// Determine the weight to assign to this model
m_Betas[m_NumIterationsPerformed] = Math.log((1 - epsilon) / epsilon);
reweight = (1 - epsilon) / epsilon;
if (m_Debug) {
System.err.println("\terror rate = " + epsilon
+" beta = " + m_Betas[m_NumIterationsPerformed]);
}
// Update instance weights
setWeights(training, reweight);
}
} | 8 |
public boolean getStudentIdByBookId(IssueBookVO issueBookVO)
throws LibraryManagementException {
boolean returnValue = true;
ConnectionFactory connectionFactory = new ConnectionFactory();
Connection connection;
try {
connection = connectionFactory.getConnection();
} catch (LibraryManagementException e) {
throw e;
}
PreparedStatement preparedStatement = null;
ResultSet resultSet;
try {
preparedStatement = connection
.prepareStatement("select STUDENT_ID from ISSUE_BOOK where BOOK_ID = ?"
+ " and RECEIVE_DATE is null");
preparedStatement.setString(1, issueBookVO.getBookID());
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
String studentIdDB = resultSet.getString("STUDENT_ID");
if (!studentIdDB.equals(issueBookVO.getStudentID())) {
returnValue = false;
throw new LibraryManagementException(
ExceptionCategory.BOOK_IS_ISSUED_TO_OTHER_STUDENT);
}
}
} catch (SQLException e) {
throw new LibraryManagementException(ExceptionCategory.SYSTEM);
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
throw new LibraryManagementException(
ExceptionCategory.SYSTEM);
}
}
connectionFactory.closeConnection(connection);
}
return returnValue;
} | 6 |
public void setShutdownFontsize(int fontsize) {
if (fontsize <= 0) {
this.shutdownFontSize = UIFontInits.SHDBTN.getSize();
} else {
this.shutdownFontSize = fontsize;
}
somethingChanged();
} | 1 |
public AtomVerbs getVerbs(Movable player)
{
AtomVerbs rval = new AtomVerbs();
rval.atomUID = this.UID;
rval.verbs = new ArrayList<VerbSignature>();
// Check all the class' methods
for(Method m : this.getClass().getMethods())
{
// TODO: Check if this verb is accessible by the the player atom
// Check if it's a verb
if(m.getAnnotation(Verb.class) != null)
{
// Create a new verb to add to our list
VerbSignature sig = new VerbSignature();
sig.verbName = m.getName();
sig.parameters = new ArrayList<VerbParameter>();
// Go through the parameters and add their type one by one.
// Note that later for lists, we'll need to check the method's annotations,
// e.g. "@param(position = 1, type = "List")
for(Class type : m.getParameterTypes())
{
// TODO: add list support
VerbParameter param = new VerbParameter();
if(type == String.class)
{
param.type = VerbParameter.Type.STRING;
}
else if(type == Integer.class)
{
param.type = VerbParameter.Type.INTEGER;
}
else
{
throw new RuntimeException("Verb "+this.getClass().getCanonicalName()+":"+
m.getName()+" has parameter of invalid type.");
}
sig.parameters.add(param);
}
rval.verbs.add(sig);
}
}
return rval;
} | 5 |
private boolean isDrawRound() {
if(drawRound) {
return true;
}
if(getColor().equals(Color.YELLOW)) {
return true;
}
return false;
} | 2 |
public void saveXml() {
if (!vermilionCascadeNotebook.getModified()) {
return;
}
File file = new File(VCNConstants.WORK_FILE_PATH);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
Document xml = builder.newDocument();
vermilionCascadeNotebook.flushEditor();
constructXml(xml);
System.out.println("Write data.xml..");
Transformer t = TransformerFactory.newInstance().newTransformer();
// t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "");
// t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty(OutputKeys.METHOD, "xml");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
FileOutputStream fos = new FileOutputStream(file);
StreamResult sr = new StreamResult(fos);
t.transform(new DOMSource(xml), sr);
fos.flush();
fos.close();
System.out.println("Write data.xml.");
} catch (Exception ex) {
VermilionCascadeNotebook.getInstance().setInModified();
UI.messageDialog(VermilionCascadeNotebook.getInstance().getShell(), "Error writing user data '" + ex +
"'\r\nRecent modifictions were not saved\r\n",
"Writing user data process has caused an error: " + ex +"\r\nError stack: \r\n\r\n" + GeneralUtils.getStackTrace(ex));
ex.printStackTrace();
}
VermilionCascadeNotebook.getInstance().setInModified();
} | 2 |
@Override
public String toString() {
StringBuffer s = new StringBuffer("Graph mit " + vertexIndex.size() + " Knoten\n");
int i = 0;
for (V v : vertices) {
if (v != null) {
s.append(v + ": ");
for (E e : adjList.get(i)) {
s.append(e.getVertexB() + " ");
}
s.append("\n");
}
i++;
}
return new String(s);
} | 3 |
public void pauseDownload(final int gid) {
switch (downloads.get(gid).getStatus()) {
case ACTIVE:
case WAITING:
taskManager.pause(gid);
break;
default:
break;
}
} | 2 |
public float getTotalPrice() {
return totalPrice;
} | 0 |
public static Constants.ResponseType update(Client client, UpdateDataRequestMessage updateDataRequestMessage) {
boolean update = false;
Constants.ResponseType responseType = Constants.ResponseType.failed;
EntityManager entityManager = PersistenceManager.getInstance().getEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
Player player = entityManager.find(Player.class, client.getPlayerModel().getName());
if (player != null) {
String oldPassword = updateDataRequestMessage.getOldPassword();
String password = updateDataRequestMessage.getPassword();
String mail = updateDataRequestMessage.getEmail();
if ((oldPassword != null) && (oldPassword.length() > 0) && (password != null) && (password.length() > 0)) {
if (player.getPassword().equals(oldPassword)) {
player.setPassword(password);
update = true;
}
}
if ((mail != null) && (mail.length() > 0)) {
player.setEmail(mail);
update = true;
} else {
logger.error("Password not changed because old password was wrong");
}
if (update) {
entityManager.merge(player);
entityManager.flush();
responseType = Constants.ResponseType.ok;
logger.info("Registartion data for client " + client + " changed.");
}
} else {
logger.error("player with client " + client + " was not found.");
}
entityTransaction.commit();
return responseType;
} | 9 |
public MetricSet<E> search(E e, Metric<? super E> m) {
int leastDistance = Integer.MAX_VALUE;
for (E elem : this) {
leastDistance = Math.min(leastDistance, m.distance(elem, e));
}
MetricSet<E> newSet = new MetricSet<E>();
for (E elem : this) {
if (m.distance(elem, e) == leastDistance)
newSet.add(elem);
}
return newSet;
} | 4 |
public static void main(String args[]) {
int size = 4;
int[][][] cube = new int[size][size][size];
TicTacToe tictactoe = new TicTacToe(cube);
boolean gameOver = false;
int PLAYER=1;
List<Long> runTime = new LinkedList<Long>();
while (!gameOver) {
System.out
.println("Instruction:Layer1(bot)->Layer4(top), 1 means player and 2 means computer");
for (int i = 0; i < size; i++) {
System.out.println("Layer" + (i+1) + ":");
for (int j = 0; j < size; j++) {
for (int q = 0; q < size; q++) {
System.out.print(cube[i][j][q] + " ");
}
System.out.println();
}
}
System.out.println("Please input the layer first:");
Scanner scan = new Scanner(new BufferedInputStream(System.in));
int layer = scan.nextInt();
System.out.println("Please input the row:");
int row = scan.nextInt();
System.out.println("Please input the column:");
int column = scan.nextInt();
System.out.println("---------------------------------------------");
tictactoe.placeXorO(layer-1, row-1, column-1, PLAYER, true);
if(tictactoe.judgeWinOrLose()==1){
System.out.println("Player wins!");
break;
}else{
if(tictactoe.judgeWinOrLose()==-1){
System.out.println("Computer wins!");
break;
}
}
long startTime = System.nanoTime();
tictactoe.judgeNextStep();
long endTime = System.nanoTime();
runTime.add(endTime - startTime);
if(tictactoe.judgeWinOrLose()==1){
System.out.println("Player wins!");
break;
}else{
if(tictactoe.judgeWinOrLose()==-1){
System.out.println("Computer wins!");
break;
}
}
}
for(int i=0;i<runTime.size();i++){
System.out.println(runTime.get(i));
}
} | 9 |
@Override
public void configure(JobConf conf) {
try {
FileSystem hdfs = FileSystem.get(conf);
FileUtil.copyMerge(hdfs, new Path(IOInfo.TEMP_MOVIE_OUTPUT), hdfs, new Path(IOInfo.TEMP_MOVIE_MERGE)
, false, conf, null);
FileUtil.copyMerge(hdfs, new Path(IOInfo.TEMP_USER_OUTPUT), hdfs, new Path(IOInfo.TEMP_USER_MERGE)
, false, conf, null);
String movieCacheName = new Path(IOInfo.TEMP_MOVIE_MERGE).getName();
String userCacheName = new Path(IOInfo.TEMP_USER_MERGE).getName();
Path [] cacheFiles = DistributedCache.getLocalCacheFiles(conf);
int count = 0;
if (null != cacheFiles && cacheFiles.length > 0) {
for (Path cachePath : cacheFiles) {
if(cachePath.getName().equals(userCacheName)) {
loadUserStat(cachePath);
count++;
} else if (cachePath.getName().equals(movieCacheName)) {
loadMovieStat(cachePath);
count++;
}
if(count>2) break;
}
}
} catch (IOException ioe) {
System.err.println("IOException reading from distributed cache");
System.err.println(ioe.toString());
}
} | 7 |
@Override
public final void setModelStatus(ModelStatus modelStatus) {
CheckUtils.isNotNull(modelStatus);
if (!this.checkBeforeSet(this.getModelStatus(), modelStatus))
return;
if (this.modelStatus != null
&& this.modelStatus.equals(ModelStatus.DELETED)) {
throw new IllegalStateException(
"You cannot update the status of a deleted model");
}
ModelStatus oldModelStatus = this.modelStatus;
this.modelStatus = modelStatus;
this.propertyChangeSupport.firePropertyChange(
PROP_MODEL_STATUS,
oldModelStatus,
modelStatus);
if (modelStatus.equals(ModelStatus.TO_UPDATE)
|| modelStatus.equals(ModelStatus.TO_DELETE)
|| modelStatus.equals(ModelStatus.DELETED))
this.setModelUpdateDate(Calendar.getInstance());
} | 6 |
@SuppressWarnings("resource")
public Connection getConn() {
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
String databaseUrl = "jdbc:sqlite:mydatabase.db";
conn = DriverManager.getConnection(databaseUrl);
String sqlQuery = new Scanner(new File(CREATETABLES_SQL_PATH)).useDelimiter("\\A").next();
stmt = conn.createStatement();
stmt.executeUpdate(sqlQuery);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return conn;
} | 5 |
public static List<Message> parseMessages(String resultString){
List<Message> messages = new ArrayList<Message>();
JSONObject base;
try {
base = new JSONObject(resultString);
int retcode = base.optInt("retcode",-1);
if (retcode == 0) {
JSONArray messageArray = base.optJSONArray("result");
for (int i = 0; i < messageArray.length(); i++) {
Message message = Message.newEntity(messageArray.optJSONObject(i));
if (message!=null) {
messages.add(message);
}
}
}else if (retcode == 100) {
//TODO
}else if (retcode == 120){
//TODO
}else if (retcode == 121){
//TODO
}else if (retcode == 116){
Bot.getInstance().setPtwebqq(base.optString("p"));
}
} catch (JSONException e) {
e.printStackTrace();
}
return messages;
} | 8 |
public void setTable() {
// Centering the first two column's cell content
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
questionTable.getColumnModel().getColumn(0).setCellRenderer( centerRenderer );
questionTable.getColumnModel().getColumn(1).setCellRenderer( centerRenderer );
// Set the columns width
TableColumn column = null;
for (int i = 0; i < 3; i++) {
column = questionTable.getColumnModel().getColumn(i);
if (i == 0) {
column.setPreferredWidth(10); //sport column is bigger
} else if (i == 1) {
column.setPreferredWidth(30);
} else {
column.setPreferredWidth(780);
}
}
} | 3 |
public void setCrs(Crs crs)
{
this.crs = crs;
} | 0 |
@Override
public void setIdleTimeout(long idleTimeout) {
this.idleTimeout = idleTimeout;
} | 0 |
public void neighborLightPropagationChanged(EnumSkyBlock var1, int var2, int var3, int var4, int var5) {
if (!this.worldProvider.hasNoSky || var1 != EnumSkyBlock.Sky) {
if (this.blockExists(var2, var3, var4)) {
if (var1 == EnumSkyBlock.Sky) {
if (this.canExistingBlockSeeTheSky(var2, var3, var4)) {
var5 = 15;
}
} else if (var1 == EnumSkyBlock.Block) {
int var6 = this.getBlockId(var2, var3, var4);
if (Block.lightValue[var6] > var5) {
var5 = Block.lightValue[var6];
}
}
if (this.getSavedLightValue(var1, var2, var3, var4) != var5) {
this.scheduleLightingUpdate(var1, var2, var3, var4, var2, var3, var4);
}
}
}
} | 8 |
public Iterator<Land> iterator() {
return laenderList.iterator();
} | 0 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.