text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
short getNumber()
{
return number;
} | 0 |
public Land getSecondLand() {
return second_land;
} | 0 |
Item newInteger(final int value) {
key.set(value);
Item result = get(key);
if (result == null) {
pool.putByte(INT).putInt(value);
result = new Item(index++, key);
put(result);
}
return result;
} | 1 |
public Point transformFromAutomatonToView(Point point) {
return (Point) transform.transform(point, new Point());
} | 0 |
public static void question7() {
/*
QUESTION PANEL SETUP
*/
questionLabel.setText("What is your favourite drink?");
questionNumberLabel.setText("7");
/*
ANSWERS PANEL SETUP
*/
//resetting
radioButton1.setSelected(false);
radioButton2.setSelected(false);
radioButton3.setSelected(false);
radioButton4.setSelected(false);
radioButton5.setSelected(false);
radioButton6.setSelected(false);
radioButton7.setSelected(false);
radioButton8.setSelected(false);
radioButton9.setSelected(false);
radioButton10.setSelected(false);
radioButton11.setSelected(false);
radioButton12.setSelected(false);;
radioButton13.setSelected(false);
radioButton14.setSelected(false);
//enability
radioButton1.setEnabled(true);
radioButton2.setEnabled(true);
radioButton3.setEnabled(true);
radioButton4.setEnabled(true);
radioButton5.setEnabled(true);
radioButton6.setEnabled(true);
radioButton7.setEnabled(false);
radioButton8.setEnabled(false);
radioButton9.setEnabled(false);
radioButton10.setEnabled(false);
radioButton11.setEnabled(false);
radioButton12.setEnabled(false);
radioButton13.setEnabled(false);
radioButton14.setEnabled(false);
//setting the text
radioButton1.setText("Alcohol.");
radioButton2.setText("Tea.");
radioButton3.setText("Coffee.");
radioButton4.setText("Juice.");
radioButton5.setText("All of the above.");
radioButton6.setText("I don't care.");
radioButton7.setText("No used");
radioButton8.setText("No used");
radioButton9.setText("No used");
radioButton10.setText("No used");
radioButton11.setText("No used");
radioButton12.setText("No used");
radioButton13.setText("No used");
radioButton14.setText("No used");
// Calculating the best guesses and showing them.
Knowledge.calculateAndColorTheEvents();
} | 0 |
private MazeRoomEnterBehavior getBehavior(RoomType roomType){
MazeRoomEnterBehavior enterBehavior;
switch(roomType){
case DOOR:
enterBehavior = new DoorRoomEnterBehavior();
break;
case EXIT:
enterBehavior = new ExitRoomEnterBehavior();
break;
case PATH:
if(rand.nextDouble() >= .5)
enterBehavior = new QuestionRoomEnterBehavior();
else
enterBehavior = new TrueRoomEnterBehavior();
break;
case START:
enterBehavior = new StartRoomEnterBehavior();
break;
case WALL:
enterBehavior = new WallRoomEnterBehavior();
break;
default:
enterBehavior = new WallRoomEnterBehavior();
}
return enterBehavior;
} | 6 |
public void setAge(String age) {
this.age = age;
} | 0 |
private static BufferedImage[][][] createImagesFiende()
{
BufferedImage[][][] bilder = null;
BufferedImage[] imgs0 = Bilder.naziN;
BufferedImage[] imgs1 = Bilder.naziE;
BufferedImage[] imgs2 = Bilder.naziS;
BufferedImage[] imgs3 = Bilder.naziW;
BufferedImage[] imgs4 = Bilder.naziNW;
BufferedImage[] imgs5 = Bilder.naziNE;
BufferedImage[] imgs6 = Bilder.naziSE;
BufferedImage[] imgs7 = Bilder.naziSW;
BufferedImage[][] imgses = new BufferedImage[][]{imgs0,imgs1,imgs2,imgs3,imgs4,imgs5,imgs6,imgs7};
imgs0 = null;
imgs1 = null;
imgs2 = null;
imgs3 = null;
imgs4 = null;
imgs5 = null;
imgs6 = null;
imgs7 = null;
int[] dead = {7,8,9,10,11,12,13,14};
int[] hurt = {5,6};
int[] attacking = {4};
int[] jumping = {0};
int[] airborne = {0};
int[] walking = {2,1,3,1};
int[] standby = {0};
int[][] ordning = {dead,hurt,attacking,jumping,airborne,walking,standby};
int[][][] revisor = new int[8][][];
for(int i = 0;i < 8;i++)
{
revisor[i] = ordning;
}
bilder = new BufferedImage[revisor.length][][];
for(int i = 0;i < 8;i++)
{
bilder[i] = new BufferedImage[revisor[0].length][];
for(int j = 0;j < revisor[0].length;j++)
{
bilder[i][j] = new BufferedImage[revisor[0][j].length];
}
}
for(int i = 0;i < revisor.length;i++)
{
for(int j = 0;j < revisor[0].length;j++)
{
for(int k = 0;k < revisor[0][j].length;k++)
{
bilder[i][j][k] = imgses[i][revisor[0][j][k]];
}
}
}
return bilder;
} | 6 |
private static void findPatternInFile( File src, String pattern,
Vector<Match> matches, MVD mvd ) throws Exception
{
short vId = mvd.getVersionByLongName( src.getName() );
if ( vId != -1 )
{
int length = (int)src.length();
FileInputStream fis = new FileInputStream( src );
byte[] data = new byte[length];
fis.read( data );
fis.close();
int offset = 0;
int index = -1;
byte[] bPattern = pattern.getBytes("UTF-8");
do
{
index = KMPSearch.search( data, offset, bPattern );
if ( index != -1 )
{
Match m = new Match( index, bPattern.length, vId,
mvd.getVersionShortName(vId) );
matches.add( m );
offset += index + pattern.length();
}
}
while ( index != -1 );
}
} | 3 |
public static void spawnHellhound (Location loc, int amount) {
int i = 0;
while (i < amount) {
Wolf hound = (Wolf) loc.getWorld().spawnEntity(loc, EntityType.WOLF);
hound.getEquipment().setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE, 1, (short) - 98789));
hound.getEquipment().setChestplateDropChance(0.0F);
hound.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 2147483647, 1));
hound.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 2147483647, 1));
hound.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 2147483647, 1));
hound.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 2147483647, 10));
hound.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 2147483647, 1));
hound.setBreed(false);
hound.setFireTicks(2147483647);
hound.setAngry(true);
i++;
}
} | 1 |
void addRecipe(ItemStack var1, Object ... var2) {
String var3 = "";
int var4 = 0;
int var5 = 0;
int var6 = 0;
if(var2[var4] instanceof String[]) {
String[] var7 = (String[])((String[])var2[var4++]);
for(int var8 = 0; var8 < var7.length; ++var8) {
String var9 = var7[var8];
++var6;
var5 = var9.length();
var3 = var3 + var9;
}
} else {
while(var2[var4] instanceof String) {
String var11 = (String)var2[var4++];
++var6;
var5 = var11.length();
var3 = var3 + var11;
}
}
HashMap var12;
for(var12 = new HashMap(); var4 < var2.length; var4 += 2) {
Character var13 = (Character)var2[var4];
ItemStack var15 = null;
if(var2[var4 + 1] instanceof Item) {
var15 = new ItemStack((Item)var2[var4 + 1]);
} else if(var2[var4 + 1] instanceof Block) {
var15 = new ItemStack((Block)var2[var4 + 1], 1, -1);
} else if(var2[var4 + 1] instanceof ItemStack) {
var15 = (ItemStack)var2[var4 + 1];
}
var12.put(var13, var15);
}
ItemStack[] var14 = new ItemStack[var5 * var6];
for(int var16 = 0; var16 < var5 * var6; ++var16) {
char var10 = var3.charAt(var16);
if(var12.containsKey(Character.valueOf(var10))) {
var14[var16] = ((ItemStack)var12.get(Character.valueOf(var10))).copy();
} else {
var14[var16] = null;
}
}
this.recipes.add(new ShapedRecipes(var5, var6, var14, var1));
} | 9 |
private void destroyBonds() {
if (bonds != null && !bonds.isEmpty()) {
synchronized (bonds.getSynchronizationLock()) {
for (Iterator it = bonds.iterator(); it.hasNext();) {
((RadialBond) it.next()).destroy();
}
}
}
bonds.clear();
if (bends != null && !bends.isEmpty()) {
synchronized (bends.getSynchronizationLock()) {
for (Iterator it = bends.iterator(); it.hasNext();) {
((AngularBond) it.next()).destroy();
}
}
}
bends.clear();
if (molecules != null && !molecules.isEmpty()) {
synchronized (molecules.getSynchronizationLock()) {
for (Iterator it = molecules.iterator(); it.hasNext();) {
((Molecule) it.next()).destroy();
}
}
}
molecules.clear();
} | 9 |
public void zoneEventOccurred(String eventZone, int eventType){
// If within the bounds of the text, go to the link
if(eventType==ZoneEvents.ENTER && eventZone.equals("polygon")){
Gui.changeCursor(Cursor.HAND_CURSOR);
}
else if (eventType==ZoneEvents.CLICK && eventZone.equals("polygon")){
// Added by Mike S
if(onclick > 0)
Engine.gotoSlide(onclick);
else if(onclick == 0);
BrowserLoader.openURL(onclickurl);
}
} | 6 |
private void pop(char c) throws JSONException {
if (this.top <= 0) {
throw new JSONException("Nesting error.");
}
char m = this.stack[this.top - 1] == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.top -= 1;
this.mode = this.top == 0
? 'd'
: this.stack[this.top - 1] == null
? 'a'
: 'k';
} | 5 |
public static boolean containsFeet(Point f1){
for (int i = 0; i < PlatformManager.floors.size(); i++){
if (PlatformManager.floors.get(i).contains(f1) && PlatformManager.floorLevel.get(i) == GameManager.level){
return true;
}
}
return false;
} | 3 |
private static void eliminarCliente()
{
boolean salir;
Integer idCliente;
char caracter;
do
{
try
{
System.out.print( "Introduce el Id del cliente: ");
idCliente = Integer.parseInt( scanner.nextLine());
System.out.print( "Deseas eliminar todas las cuentas en tiendas del cliente que tengan saldo positivo? (s/n): ");
caracter = Character.toLowerCase(scanner.nextLine().charAt(0));
Cliente.eliminar( idCliente, caracter == 's');
System.out.println( (caracter == 's') ? "- Cliente id " + idCliente + " eliminado completamente del registro -"
: "- Cuentas vacas del cliente en tiendas eliminadas. -");
salir = true;
}
catch (Exception e)
{
System.out.println( e.getMessage());
salir = !GestionTiendas.preguntaReintentar( "Deseas intentarlo de nuevo?");
}
} while (!salir);
} | 3 |
public static void main(String[] args) {
try {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File(ClassLoader.getSystemResource(runXMLAUTHORITY).getFile());
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null);
for (String warning : warnings) {
System.out.println("Warning:" + warning);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMLParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 6 |
private HubNode getBusOf (Device dev)
throws IOException
{
Bus bus = dev.getBus ();
for (int i = 0; i < busses.length; i++) {
if (bus == busses [i])
return hubs [i];
}
System.err.println ("what bus ??");
return null;
} | 2 |
public String getText()
{
StringBuffer sb = new StringBuffer();
try (BufferedInputStream in = new BufferedInputStream(
new FileInputStream(new File(path))))
{
int c;
while ((c = in.read()) != -1)
{
sb.append((char) c);
}
}
catch (IOException e)
{
e.printStackTrace();
}
return sb.toString();
} | 2 |
public void activateEmbeddedMovie(boolean b) {
if (b) {
if (job != null && !job.contains(movieUpdater))
job.add(movieUpdater);
int m = movieUpdater.getInterval();
modelTimeQueue.setInterval(m);
kine.setInterval(m);
pote.setInterval(m);
tote.setInterval(m);
int n = movie.getCapacity();
setQueueLength(n);
for (int i = 0; i < iAtom; i++) {
if (i == 0 || atom[i].isMovable())
atom[i].initMovieQ(n);
}
} else {
if (job != null && job.contains(movieUpdater))
job.remove(movieUpdater);
setQueueLength(-1);
for (int i = 0; i < iAtom; i++) {
atom[i].initMovieQ(-1);
}
}
movie.setCurrentFrameIndex(0);
setRecorderDisabled(!b);
} | 9 |
private int nextChunk()
throws IOException
{
int available = super.available();
// must always try to read 1 byte!
// some buggy InputStreams return < 0!
if (available <= 0)
{
available = 1;
}
if (available > inBuf.length)
{
available = super.read(inBuf, 0, inBuf.length);
}
else
{
available = super.read(inBuf, 0, available);
}
if (available < 0)
{
if (finalized)
{
return -1;
}
try
{
buf = c.doFinal();
}
catch (Exception e)
{
throw new IOException("error processing stream: " + e.toString());
}
bufOff = 0;
if (buf != null)
{
maxBuf = buf.length;
}
else
{
maxBuf = 0;
}
finalized = true;
if (bufOff == maxBuf)
{
return -1;
}
}
else
{
bufOff = 0;
try
{
maxBuf = c.update(inBuf, 0, available, buf, 0);
}
catch (Exception e)
{
throw new IOException("error processing stream: " + e.toString());
}
if (maxBuf == 0) // not enough bytes read for first block...
{
return nextChunk();
}
}
return maxBuf;
} | 9 |
private static void addCollection(Collection<ATask> task){
Session session = HibernateUtil.getSessionFactory().openSession();
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
for(ATask o : task)
session.save(o);
session.getTransaction().commit();
System.out.println("saved!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка при работе с базой данных", JOptionPane.OK_OPTION);
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
} | 4 |
public void csv(){
Grid g1 = hierarchyGrids.getGrid(1);
GridNode[] n = g1.nodes;
Map<Integer, Integer> ClustersFine = new HashMap<Integer, Integer>();
System.out.println();
System.out.println("F-POINTS:");
for(GridNode f : n){
if(f.type == NodeType.F){
System.out.print(f.id+1 + " ");
}
}
System.out.println();
System.out.println("C-POINTS:");
for(GridNode c : n){
if(c.type == NodeType.C){
// System.out.print((c.id+1)+" ");
System.out.println("[ID:" + (c.id+1) + " , ORDER:" + (c.order+1) + "] ");
}
}
System.out.println();
System.out.println();
//Map between
for(GridNode f : n){
if(f.type == NodeType.F){
double max = 0;
int R = -1;
for(GridNode c : f.Ci.values()){
if(f.Dependence.get(c.id) > max){
R = c.id;
max = f.Dependence.get(c.id);
}
}
if(R+1 != 0) {
System.out.println((f.id+1) + "," + (R+1));//+ "," + 2
ClustersFine.put(f.id+1, R);
} else {
System.err.println();
System.err.println("ERROR: Node ID: " + f.id+1 + ", not have nodes in his Ci");
}
}
}
// Map<Integer, String> ClustersCoarse = new HashMap<Integer, String>();
// for(GridNode c : n){
// if(c.type == NodeType.C){
// if(c.S.values().size() == 0){
// ClustersCoarse.put(c.id, "R" + (c.id+1));
// ClustersFine.put(c.id+1, c.id);
// } else {
// boolean isExist = false;
// for(GridNode cn : c.S.values()){
// if(cn.type == NodeType.C){
// if(ClustersCoarse.get(cn.id) != null){
// ClustersCoarse.put(c.id, ClustersCoarse.get(cn.id));
// ClustersFine.put(c.id+1, cn.id);
// isExist = true;
// }
//
// }
// }
// if(!isExist){
// ClustersCoarse.put(c.id, "R"+(c.id+1));
// ClustersFine.put(c.id+1, c.id);
// }
// }
// }
// }
// // System.out.println();
// // System.out.println("Final Clustering: ");
// Map<Integer, String> FinalClustering = new HashMap<Integer, String>();
// for (Map.Entry<Integer, Integer> entry : ClustersFine.entrySet())
// {
// FinalClustering.put(entry.getKey()-1, ClustersCoarse.get(entry.getValue()));
// //System.out.println(entry.getKey() + ":" + ClustersCoarse.get(entry.getValue()));
// }
//
//
//
// return print(FinalClustering, n);
} | 9 |
@Override
public void save(ObjectOutput out) throws IOException {
out.writeShort(ints.length);
for(int i:ints){
out.writeInt(i);
}
out.writeShort(longs.length);
for(long l:longs){
out.writeLong(l);
}
out.writeShort(floats.length);
for(float f:floats){
out.writeFloat(f);
}
out.writeShort(doubles.length);
for(double d:doubles){
out.writeDouble(d);
}
out.writeShort(strings.length);
for(String s:strings){
out.writeUTF(s);
}
out.writeShort(bytes.length);
for(byte[] bytes2:bytes){
out.writeShort(bytes2.length);
out.write(bytes2);
}
} | 6 |
protected Object getParentElement(Object element) {
boolean oldBusy = isBusy();
setBusy(true);
try {
if (contentProviderIsLazy && !contentProviderIsTreeBased && !(element instanceof TreePath)) {
ILazyTreeContentProvider lazyTreeContentProvider = (ILazyTreeContentProvider) getContentProvider();
return lazyTreeContentProvider.getParent(element);
}
if (contentProviderIsLazy && contentProviderIsTreeBased && !(element instanceof TreePath)) {
ILazyTreePathContentProvider lazyTreePathContentProvider = (ILazyTreePathContentProvider) getContentProvider();
TreePath[] parents = lazyTreePathContentProvider
.getParents(element);
if (parents != null && parents.length > 0) {
return parents[0];
}
}
return super.getParentElement(element);
} finally {
setBusy(oldBusy);
}
} | 8 |
public CachedRowSetImpl executeQuery() throws SQLException {
String sql = "";
CachedRowSetImpl crs = new CachedRowSetImpl();
if (isGetAll()) {
sql = SELECT + getQueryBuilder().getSelectValue() + FROM + getQueryBuilder().getTableName() + ";";
try {
getConnection(false);
sqlStatement = getConn().prepareStatement(sql);
crs.populate(sqlStatement.executeQuery());
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
sqlStatement.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} else {
sql = SELECT + getQueryBuilder().getSelectValue() +
FROM + getQueryBuilder().getTableName() +
WHERE + getWhere().getWhereKey() + " " + getWhere().getWhereOperator() + " ?;";
try {
getConnection(false);
sqlStatement = getConn().prepareStatement(sql);
sqlStatement.setString(1, getWhere().getWhereValue());
crs.populate(sqlStatement.executeQuery());
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
sqlStatement.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return crs;
} | 5 |
public String toString() {
return this.mode == 'd' ? this.writer.toString() : null;
} | 1 |
public ContactEntity getContact() {
return contact;
} | 0 |
public javax.swing.JTable getTabla(){
return this.tabla;
} | 0 |
public final EsperParser.ifthenelse_return ifthenelse() throws RecognitionException {
EsperParser.ifthenelse_return retval = new EsperParser.ifthenelse_return();
retval.start = input.LT(1);
Object root_0 = null;
Token ENDIF30=null;
EsperParser.if__return if_27 =null;
EsperParser.elseif_return elseif28 =null;
EsperParser.else__return else_29 =null;
Object ENDIF30_tree=null;
try {
// C:\\Users\\Alex\\Dropbox\\EclipseWorkspace\\esper-compiler\\src\\compiler\\Esper.g:46:12: ( if_ ( elseif )* ( else_ )* ENDIF )
// C:\\Users\\Alex\\Dropbox\\EclipseWorkspace\\esper-compiler\\src\\compiler\\Esper.g:46:14: if_ ( elseif )* ( else_ )* ENDIF
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_if__in_ifthenelse378);
if_27=if_();
state._fsp--;
adaptor.addChild(root_0, if_27.getTree());
// C:\\Users\\Alex\\Dropbox\\EclipseWorkspace\\esper-compiler\\src\\compiler\\Esper.g:46:18: ( elseif )*
loop5:
do {
int alt5=2;
int LA5_0 = input.LA(1);
if ( (LA5_0==ELSEIF) ) {
alt5=1;
}
switch (alt5) {
case 1 :
// C:\\Users\\Alex\\Dropbox\\EclipseWorkspace\\esper-compiler\\src\\compiler\\Esper.g:46:18: elseif
{
pushFollow(FOLLOW_elseif_in_ifthenelse380);
elseif28=elseif();
state._fsp--;
adaptor.addChild(root_0, elseif28.getTree());
}
break;
default :
break loop5;
}
} while (true);
// C:\\Users\\Alex\\Dropbox\\EclipseWorkspace\\esper-compiler\\src\\compiler\\Esper.g:46:26: ( else_ )*
loop6:
do {
int alt6=2;
int LA6_0 = input.LA(1);
if ( (LA6_0==ELSE) ) {
alt6=1;
}
switch (alt6) {
case 1 :
// C:\\Users\\Alex\\Dropbox\\EclipseWorkspace\\esper-compiler\\src\\compiler\\Esper.g:46:26: else_
{
pushFollow(FOLLOW_else__in_ifthenelse383);
else_29=else_();
state._fsp--;
adaptor.addChild(root_0, else_29.getTree());
}
break;
default :
break loop6;
}
} while (true);
ENDIF30=(Token)match(input,ENDIF,FOLLOW_ENDIF_in_ifthenelse386);
ENDIF30_tree =
(Object)adaptor.create(ENDIF30)
;
adaptor.addChild(root_0, ENDIF30_tree);
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
} | 7 |
public void showGroupMembers (String group, CommandSender sender) {
ArrayList <String> players = new ArrayList <String> ();
Player [] player = Bukkit.getServer().getOnlinePlayers();
for (int i = 0; i < player.length; i++) {
if (config.getConfig().getString("Player."+player[i].getName()+".CR").equalsIgnoreCase(group)) {
if (config.getConfig().getString("Player."+player[i].getName()+".NM").equalsIgnoreCase(player[i].getName()))
players.add(player[i].getName());
else players.add(player[i].getName()+" ("+config.getConfig().getString("Player."+player[i].getName()+".NM")+")");
}
}//close for
sender.sendMessage(ChatColor.GRAY+"Current chatroom members: ");
String subbed = (players.toString()).substring(1, players.toString().length()-1);
sender.sendMessage(subbed);
} | 3 |
public MainController() {
} | 0 |
@Override
protected void process(Entity e) {
Position pos = rectplayermap.get(e);
int height = container.getHeight();
int width = container.getWidth();
Input input = container.getInput();
// AXE VERTICAL
{
if (input.isKeyDown(Input.KEY_UP)) {
if (pos.getY() - VELOCITE >= 0) {
pos.setY(pos.getY() - VELOCITE);
}
} else if (input.isKeyDown(Input.KEY_DOWN)) {
if (pos.getY() + VELOCITE + 50 < height) { //50
pos.setY(pos.getY() + VELOCITE);
}
}
}
// AXE HORIZONTAL
{
if (input.isKeyDown(Input.KEY_LEFT)) {
if (pos.getX() - VELOCITE >= 0) {
pos.setX(pos.getX() - VELOCITE);
}
} else if (input.isKeyDown(Input.KEY_RIGHT)) {
if (pos.getX() + VELOCITE + 50 < width) { // 50
pos.setX(pos.getX() + VELOCITE);
}
}
}
{
if (input.isKeyDown(Input.KEY_S)) {
//FIRE
System.out.println("Fire");
}
}
} | 9 |
public Move getLastMove() {
return this.moveList.size() > 0 ? this.moveList.get(this.moveList.size() - 1) : null;
} | 1 |
public static void main(String[] args)
{
// read class name from command line args or user input
String name;
if (args.length > 0) name = args[0];
else
{
Scanner in = new Scanner(System.in);
System.out.println("Enter class name (e.g. java.util.Collections): ");
name = in.next();
}
try
{
// print generic info for class and public methods
Class<?> cl = Class.forName(name);
printClass(cl);
for (Method m : cl.getDeclaredMethods())
printMethod(m);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
} | 4 |
public static boolean checkKing()
{
if(player=="black")
for(int y=0;y<7;y++)
if(pieces[0][y]==-1)
return true;
else if(player=="white")
for(int a=0; a<7; a++)
if(pieces[7][a]==1)
return true;
return false;
} | 6 |
public LocalDate getEventLocalDate(int meetingsAway) {
LocalDate thisMeeting = (weekOfMonth != LAST) ?
now.with(TemporalAdjusters.dayOfWeekInMonth(weekOfMonth,dayOfWeek)) :
now.with(TemporalAdjusters.lastInMonth(dayOfWeek));
// Has the meeting already happened this month?
if (thisMeeting.isBefore(now)) {
// start from next month
meetingsAway++;
}
if (meetingsAway > 0) {
thisMeeting = thisMeeting.plusMonths(meetingsAway).with(TemporalAdjusters.dayOfWeekInMonth(weekOfMonth,dayOfWeek));
}
return thisMeeting;
} | 3 |
public int[] getPos()
{
if(protons == 1)
return new int[] {0, 0};
int thisRow = 0, thisCol = 0;
boolean breakOut = false;
for(int row = 0; row < periodicTable.length; row++)
{
for(int col = 0; col < periodicTable[0].length; col++)
{
if(periodicTable[row][col] == protons)
{
thisRow = row;
thisCol = col;
breakOut = true;
break;
}
}
if(breakOut)
break;
}
return new int[] {thisRow, thisCol};
} | 5 |
public void mainMenu()
{
int valg = -1;
while(valg < 0 || valg > 5)
{
System.out.println("=========Logged in as " + user.getName() + "=========");
startUpInvitations();
System.out.println("0: Log out");
System.out.println("1: Appointment manager");
System.out.println("2: Group management");
System.out.println("3: Invitation manager");
System.out.println("4: Show alarms");
System.out.println("5: Show notifications");
valg = readInt();
switch (valg)
{
case 0:
user = null;
return;
case 1:
appointmentManager();
break;
case 2:
groupManagement();
break;
case 3:
invitationManager();
break;
case 4:
showAlarms();
break;
case 5:
showNotifications();
break;
}
valg = -1;
}
} | 8 |
public OptionsPanel(Frame parent)
{
super(parent);
setModal(true);
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Настройки", 0);
label.setBorder(new EmptyBorder(0, 0, 16, 0));
label.setFont(new Font("Default", 1, 16));
panel.add(label, "North");
JPanel optionsPanel = new JPanel(new BorderLayout());
JPanel labelPanel = new JPanel(new GridLayout(0, 1));
JPanel fieldPanel = new JPanel(new GridLayout(0, 1));
optionsPanel.add(labelPanel, "West");
optionsPanel.add(fieldPanel, "Center");
final TransparentCheckbox dlFl = new TransparentCheckbox ("Обновить клиент!");
dlFl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
boolean forceUpdateInfo;
forceUpdateInfo = dlFl.isSelected();
if (forceUpdateInfo == true)
GameUpdater.forceUpdate = true;
else
GameUpdater.forceUpdate = false;
}
});
final JButton forceButton = new JButton("Обновить клиент!");
forceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
GameUpdater.forceUpdate = true;
forceButton.setText("Клиент будет обновлен!");
forceButton.setEnabled(false);
}
});
fieldPanel.add(dlFl);
labelPanel.add(new JLabel("Принудительно обновить клиент: ", 4));
fieldPanel.add(forceButton);
labelPanel.add(new JLabel("Расположение клиента на компьютере: ", 4));
labelPanel.add(new JLabel("Сколько памяти выделять игре (в мегабайтах): ", 4));
TransparentLabel dirLink = new TransparentLabel(Util.getWorkingDirectory().toString()) {
private static final long serialVersionUID = 0L;
public void paint(Graphics g) { super.paint(g);
int x = 0;
int y = 0;
FontMetrics fm = g.getFontMetrics();
int width = fm.stringWidth(getText());
int height = fm.getHeight();
if (getAlignmentX() == 2.0F) x = 0;
else if (getAlignmentX() == 0.0F) x = getBounds().width / 2 - width / 2;
else if (getAlignmentX() == 4.0F) x = getBounds().width - width;
y = getBounds().height / 2 + height / 2 - 1;
g.drawLine(x + 2, y, x + width - 2, y); }
public void update(Graphics g)
{
paint(g);
}
};
dirLink.setCursor(Cursor.getPredefinedCursor(12));
dirLink.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent arg0) {
try {
Util.openLink(new URL("file://" + Util.getWorkingDirectory().getAbsolutePath()).toURI());
} catch (Exception e) {
e.printStackTrace();
}
}
});
dirLink.setForeground(new Color(2105599));
fieldPanel.add(dirLink);
panel.add(optionsPanel, "Center");
memory = Util.getMemorySelection();
if (memory == 1)
memory = 1024;
String memos = Integer.toString(memory);
memoryfield.setText(memos);
fieldPanel.add(memoryfield,"mb");
JPanel buttonsPanel = new JPanel(new BorderLayout());
buttonsPanel.add(new JPanel(), "Center");
JButton doneButton = new JButton("Done");
doneButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
memorys = memoryfield.getText();
int memory = Integer.parseInt(memorys);
if (memory != Util.getMemorySelection()) {
Util.setMemorySelection(memory);
String[] args = null;
try {
MinecraftLauncher.main(args);
} catch (Exception e) {
e.printStackTrace();
}
}
setVisible(false);
}
});
buttonsPanel.add(doneButton, "East");
buttonsPanel.setBorder(new EmptyBorder(16, 0, 0, 0));
panel.add(buttonsPanel, "South");
add(panel);
panel.setBorder(new EmptyBorder(16, 24, 24, 24));
pack();
setLocationRelativeTo(parent);
} | 8 |
private void checkBurntState() { //used to make talking heads burn
if (isOnFire() == false && !burned)
{
return;
}
if (burnedFeet == true)
{
burnedDontMove = true;
return;
}
if (isOnFire() == true)
{
if (!cooked)
{
cookTimer = cookTimer + 1; //this is all used to trigger the burn01 and then burn sprite
if (cookTimer > COOKLIMIT)
{
cooked = true;
}
}
setHappiness(Happiness.SAD);
// panicType = panicType.BURN;
// if (isCurrentlyWet())
// {
// onFire = false;
// whiteSteamEffect();
// return;
// }
burnTimer = burnTimer + 1;
if (burnTimer == BURNLIMIT[getBodyAgeState().ordinal()] || burnTimer > BURNLIMIT[getBodyAgeState().ordinal()])
{
setMessage(MessagePool.getMessage(this, MessagePool.Action.CantMove));
burnedFeet = true;
burnedDontMove = true;
onFire = false;
}
return;
}
else
return;
} | 8 |
private static void playerInventory() {
System.out.println("Player Inventory");
for (int i = 0; i < playerInventory.length; ++i) {
if (playerInventory[i] != null) {
System.out.println(i + ":" + playerInventory[i]);
}
}
} | 2 |
private static void test_strdtoi(TestCase t) {
// Print the name of the function to the log
pw.printf("\nTesting %s:\n", t.name);
// Run each test for this test case
int score = 0;
for (int i = 0; i < t.tests.length; i += 2) {
int exp = (Integer) t.tests[i];
String arg1 = (String) t.tests[i + 1];
int res = HW2Bases.strdtoi(arg1);
boolean cor = exp == res;
if (cor) {
++score;
}
pw.printf("%s(%10s): Expected: %8X Result: %8X Correct: %5b\n",
t.name, arg1, exp, res, cor);
pw.flush();
}
// Set the score for this test case
t.score = (double) score / (t.tests.length / 2);
} | 2 |
private void moveP() {
Player player = Main.getGamestate().getPlayer();
if (getY() < player.getY()) {
move(0, 1);
} else if (getY() > player.getY()) {
move(0, -1);
} else if (getX() < player.getX()) {
move(1, 0);
} else if (getX() > player.getX()) {
move(-1, 0);
}
if (getX() == player.getX() && getY() == player.getY()) {
Game.getInstance().toast.setData("Game Over!", 128, 0, 64);
Game.getInstance().toast.show();
}
} | 6 |
@Override
protected void loadNBT(NBTTagCompound data) {
super.loadNBT(data);
NBTTagList tagList = new NBTTagList();
for (Map.Entry<WorldCoordinate, SignalAspect> entry : aspects.entrySet()) {
NBTTagCompound nbt = new NBTTagCompound();
if (entry.getKey() != null && entry.getValue() != null) {
entry.getKey().writeToNBT(nbt, "coord");
entry.getValue().writeToNBT(nbt, "aspect");
tagList.appendTag(nbt);
}
}
data.setTag("aspects", tagList);
} | 3 |
private boolean addOwnable(ChunkyObject o) {
if (o == null)
throw new IllegalArgumentException();
// If owner is a owned by the child, remove owner from tree first.
// ex. town.setOwner(Peasant) Peasant is removed from parent (Town).
if (this.isOwnedBy(o) && this.owner != null) {
this.getOwner().removeOwnableAndTakeChildren(this);
}
if (ownables.containsKey(o.getType())) {
Boolean exists = ownables.get(o.getType()).add(o);
if (exists) DatabaseManager.getDatabase().addOwnership(this, o);
return exists;
} else {
HashSet<ChunkyObject> ownables = new HashSet<ChunkyObject>();
ownables.add(o);
this.ownables.put(o.getType(), ownables);
DatabaseManager.getDatabase().addOwnership(this, o);
return true;
}
} | 5 |
public Boolean ifExistAuditeur(Auditeur a) {
for (int i =0; i<liste.size();i++){
Auditeur ai = liste.get(i);
if (ai.getNom().equalsIgnoreCase(a.getNom()) &&
ai.getPrenom().equalsIgnoreCase(a.getPrenom())&&
ai.getDateNaissance().equals(a.getDateNaissance())){
return true;
}
}
return false;
} | 4 |
public static void checkRank(Player player) {
int kills = player.getKillCount();
for (int i = 0; i < ranks.length; i++) {
PkRank rank = ranks[i];
if (rank == null)
break;
if (rank.username.equalsIgnoreCase(player.getUsername())) {
ranks[i] = new PkRank(player);
sort();
return;
}
}
for (int i = 0; i < ranks.length; i++) {
PkRank rank = ranks[i];
if (rank == null) {
ranks[i] = new PkRank(player);
sort();
return;
}
}
for (int i = 0; i < ranks.length; i++) {
if (ranks[i].kills < kills) {
ranks[i] = new PkRank(player);
sort();
return;
}
}
} | 7 |
private void redraw(Graphics g) {
g.translate((int) dx, (int) dy);
if (toBeDrawn == null) {
if (action != null && action.equals("inventory"))
GraphicsRenderer.drawInventory(g, Class_Examples.getChest());
else if (action != null && action.equals("drawRoom"))
room.draw(g);
} else
g.drawImage(toBeDrawn, 0, 0, null);
} | 5 |
public void flujoEntrada(){
String entra="";
String nickname_input="";
Integer tipo;
DES objetoDES = new DES(this.clave);
try {
while(conectado){
//Leemos el Nickname
//entra=(String) entrada.readObject();
//this.ventana.setPanelText(entra, Color.cyan);
//leemos el tipo de mensaje
/*
* 1 = mensaje
* 2 = Conexion
* 3 = desconexion
*/
tipo=Integer.parseInt(entrada.readUTF());
//Leemos el nickname
nickname_input=(String) entrada.readUTF();
System.out.println("El nickname obtenido es: "+nickname_input);
//Leemos el mensaje
//entra=(String) entrada.readUTF();
entra=objetoDES.desencriptar((String) entrada.readUTF());
System.out.println(entra);
System.out.println("El mensaje obtenido es: "+entra);
switch (tipo){
case 1:
this.ventana.setPanelText(nickname_input, Color.magenta);
this.ventana.setPanelText(entra+"\n", Color.black);
break;
case 2:
this.ventana.setPanelText(nickname_input, Color.green);
this.ventana.setPanelText(entra+"\n", Color.black);
System.out.println("Esto es lo que llega al actualziar uSER: "+entra);
entra=entra.substring(0,entra.lastIndexOf(" desde"));
System.out.println("Esto despues de la operacion:__"+entra+"___");
if (!this.usuarios.contains(entra)){
this.usuarios.add(entra);
}
this.ventana.setUsuarios(usuarios);
break;
case 3:
this.ventana.setPanelText(nickname_input, Color.red);
this.ventana.setPanelText(entra+"\n", Color.black);
//Descomponemos la palabra.
entra=entra.substring(0,entra.lastIndexOf(" desde"));
this.usuarios.remove(entra);
this.ventana.setUsuarios(usuarios);
break;
case 4:
this.ventana.setPanelText(nickname_input, Color.red);
this.ventana.setPanelText(" Subió el archivo "+entra+"\n", Color.black);
int acepto=JOptionPane.showConfirmDialog(ventana, "El usuario "+nickname_input+" ha subido el archivo "+entra+", ¿desea descargarlo?.","Nuevo mensaje",JOptionPane.YES_NO_OPTION);
if(acepto==JOptionPane.YES_OPTION){
JFileChooser fileChooser = new JFileChooser();
fileChooser.setSelectedFile(new File(entra));
if (fileChooser.showSaveDialog(ventana) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
ConexionFTP con=new ConexionFTP("1","1",host);
System.out.println("El file que sale de Cliente 4 "+file.getAbsolutePath());
con.downFile(entra,file);
System.out.println("Se descargo el archivo satisfactoriamente");
}
}
break;
}
}
entrada.close();
conexion.close();
} catch (IOException ex) {
// Logger.getLogger(VentanaCliente.class.getName()).log(Level.SEVERE, null, ex);
this.ventana.setPanelText("La conexion se Cerro :(\n", Color.red);
this.usuarios.clear();
this.ventana.setUsuarios(usuarios);
}
} | 9 |
public FuseArgumentParser(String[] args) {
boolean seenOption = false;
for (String arg : args) {
if (seenOption == true) {
remaining.add(arg);
seenOption = false;
} else if ("-o".equals(arg)) {
remaining.add(arg);
seenOption = true;
} else if ("-f".equals(arg)) {
foreground = true;
} else if (mountPoint == null) {
mountPoint = arg;
} else if (source == null) {
source = arg;
} else {
remaining.add(arg);
}
}
} | 6 |
*/
public void nextActiveUnit(Tile tile) {
if (!requireOurTurn()) return;
// Always flush outstanding messages first.
nextModelMessage();
//if (canvas.isShowingSubPanel()) {
// canvas.getShowingSubPanel().requestFocus();
// return;
//}
// Flush any outstanding orders once the mode is raised.
if (moveMode >= MODE_EXECUTE_GOTO_ORDERS
&& !doExecuteGotoOrders()) {
return;
}
// Look for active units.
Player player = freeColClient.getMyPlayer();
Unit unit = gui.getActiveUnit();
if (unit != null
&& unit.couldMove()) return; // Current active unit has more to do.
if (player.hasNextActiveUnit()) {
gui.setActiveUnit(player.getNextActiveUnit());
return; // Successfully found a unit to display
}
// No active units left. Do the goto orders.
if (!doExecuteGotoOrders()) return;
// If not already ending the turn, use the fallback tile if
// supplied, then check for automatic end of turn, otherwise
// just select nothing and wait.
gui.setActiveUnit(null);
ClientOptions options = freeColClient.getClientOptions();
if (tile != null) {
gui.setSelectedTile(tile, false);
} else if (options.getBoolean(ClientOptions.AUTO_END_TURN)) {
endTurn();
}
} | 9 |
public UnconditionalFlowInfo unconditionalFieldLessCopy() {
// TODO (maxime) may consider leveraging null contribution verification as it is done in copy
UnconditionalFlowInfo copy = new UnconditionalFlowInfo();
copy.tagBits = this.tagBits;
copy.maxFieldCount = this.maxFieldCount;
int limit = this.maxFieldCount;
if (limit < BitCacheSize) {
long mask;
copy.definiteInits = this.definiteInits & (mask = ~((1L << limit)-1));
copy.potentialInits = this.potentialInits & mask;
copy.nullBit1 = this.nullBit1 & mask;
copy.nullBit2 = this.nullBit2 & mask;
copy.nullBit3 = this.nullBit3 & mask;
copy.nullBit4 = this.nullBit4 & mask;
}
// use extra vector
if (this.extra == null) {
return copy; // if vector not yet allocated, then not initialized
}
int vectorIndex, length, copyStart;
if ((vectorIndex = (limit / BitCacheSize) - 1) >=
(length = this.extra[0].length)) {
return copy; // not enough room yet
}
long mask;
copy.extra = new long[extraLength][];
if ((copyStart = vectorIndex + 1) < length) {
int copyLength = length - copyStart;
for (int j = 0; j < extraLength; j++) {
System.arraycopy(this.extra[j], copyStart,
(copy.extra[j] = new long[length]), copyStart,
copyLength);
}
}
else if (vectorIndex >= 0) {
for (int j = 0; j < extraLength; j++) {
copy.extra[j] = new long[length];
}
}
if (vectorIndex >= 0) {
mask = ~((1L << (limit % BitCacheSize))-1);
for (int j = 0; j < extraLength; j++) {
copy.extra[j][vectorIndex] =
this.extra[j][vectorIndex] & mask;
}
}
return copy;
} | 9 |
public void update(int id, TravelTrip travelTrip){
TravelTrip travelTripTemp = findById(id);
travelTripTemp.setCountry(travelTrip.getCountry());
travelTripTemp.setCity(travelTrip.getCity());
travelTripTemp.setFromDate(travelTrip.getFromDate());
travelTripTemp.setToDate(travelTrip.getToDate());
travelTripTemp.setBusiness(travelTrip.isBusiness());
em.persist(travelTripTemp);
} | 0 |
private void incrementTurn() {
index++;
for (int i = index;; i++) {
index = i % numPlayers;
if (players[index].isLiving())
break;
}
if (index == firstPlayerIndex) {
updateRound();
round++;
log("Beginning Round " + round);
}
playerPnlHash.get(activePlayer).setActive(false);
activePlayer = players[index];
if (saveFile != null)
saveGame();
if (!activePlayer.isAI())
handleTurn();
} | 5 |
private static int method516(char ac[], int j) {
for (int k = j; k < ac.length && k >= 0; k++)
if (ac[k] < '0' || ac[k] > '9')
return k;
return ac.length;
} | 4 |
public void setFunConsumoUltimoMes(Integer funConsumoUltimoMes) {
this.funConsumoUltimoMes = funConsumoUltimoMes;
} | 0 |
public void DBUpdateRoomItem(String roomID, Item item)
{
if((roomID==null)||(!item.isSavable())||(item.amDestroyed()))
return;
synchronized(roomID.toUpperCase().intern())
{
DBDeleteRoomItem(roomID,item);
if(Log.debugChannelOn()&&(CMSecurity.isDebugging(CMSecurity.DbgFlag.CMROIT)||CMSecurity.isDebugging(CMSecurity.DbgFlag.DBROOMS)))
Log.debugOut("RoomLoader","Continue updating item "+item.name()+" in room "+roomID);
DBCreateThisItem(roomID,item);
if(Log.debugChannelOn()&&(CMSecurity.isDebugging(CMSecurity.DbgFlag.CMROIT)||CMSecurity.isDebugging(CMSecurity.DbgFlag.DBROOMS)))
Log.debugOut("RoomLoader","Done updating item "+item.name()+" in room "+roomID);
}
} | 9 |
private void pop(char c) throws JSONException {
if (this.top <= 0) {
throw new JSONException("Nesting error.");
}
char m = this.stack[this.top - 1] == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.top -= 1;
this.mode = this.top == 0
? 'd'
: this.stack[this.top - 1] == null
? 'a'
: 'k';
} | 5 |
void run(){
Scanner sc = new Scanner(System.in);
for(;;){
h = sc.nextInt(); w = sc.nextInt();
if((h|w)==0)break;
m = new int[h][w];
dist = new int[h][w];
dir = new int[100];
for(int i=0;i<h;i++)for(int j=0;j<w;j++){
m[i][j] = sc.nextInt();
if(m[i][j]==0)c++;
if(m[i][j]==2){
ai = i; aj = j;
}
if(m[i][j]==3){
bi = i; bj = j;
}
}
res = INF;
need = bfs();
if(need!=INF){
need--;
m[ai][aj] = -1;
dfs(ai, aj, c, 0);
}
System.out.println(res==INF?0:res);
}
} | 9 |
public void Solve() {
int[] initialArray = new int[10];
for (int i = 0; i < 10; i++) {
initialArray[i] = i;
}
List<int[]> pandigitalNumbers = Enumerate(initialArray, 0);
long sum = 0;
int[] divisors = new int[]{2, 3, 5, 7, 11, 13, 17};
for (Iterator<int[]> it = pandigitalNumbers.iterator(); it.hasNext();) {
int[] numberArray = it.next();
boolean isOk = true;
for (int i = 0; i < divisors.length; i++) {
int divisor = divisors[i];
int numberToDivide = numberArray[i + 1] * 100 + numberArray[i + 2] * 10 + numberArray[i + 3];
if (numberToDivide % divisor != 0) {
isOk = false;
break;
}
}
if (isOk) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < numberArray.length; i++) {
stringBuilder.append(numberArray[i]);
}
System.out.println(stringBuilder.toString());
sum += Long.parseLong(stringBuilder.toString());
}
}
System.out.println("Result=" + sum);
} | 6 |
public void visitIntInsn(final int opcode, final int operand) {
buf.setLength(0);
buf.append(tab2)
.append(OPCODES[opcode])
.append(' ')
.append(opcode == Opcodes.NEWARRAY ? TYPES[operand] : Integer
.toString(operand)).append('\n');
text.add(buf.toString());
if (mv != null) {
mv.visitIntInsn(opcode, operand);
}
} | 2 |
@SuppressWarnings({ "rawtypes", "unchecked" })
private <K> BeanEvent<K> updateBeanEvents(Class<?> beanClass,
Class<K> listener) {
BeanEvent result = null;
try {
for (EventSetDescriptor ed : Introspector.getBeanInfo(beanClass)
.getEventSetDescriptors()) {
BeanEvent be = new BeanEvent(ed);
eventMap.put(getEventTypeyKey(beanClass, ed.getListenerType()),
be);
if (ed.getListenerType().equals(listener)) {
result = be;
}
}
} catch (IntrospectionException ex) {
throw new RuntimeException(ex);
}
if (result == null) {
result = new BeanEvent(null);
eventMap.put(getEventTypeyKey(beanClass, listener), result);
}
return result;
} | 5 |
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
// TODO add your handling code here:
String str2;
DefaultListModel md = new DefaultListModel();
str2 = this.jTextField9.getText().toUpperCase();
if(Biblio.containsKey(str2)){
j = (Juego) Biblio.get(str2);
this.jTextField4.setText(j.getNombre());
this.jTextField5.setText(j.getEmpresa());
str2 = str2.valueOf(j.getAño());
this.jTextField6.setText(str2);
this.jTextField7.setText(j.getClasificacion());
this.jTextField8.setText(j.getGenero());
for(int q=0;q<j.getPlataformas().size();q++){
md.addElement(j.getPlataformas().get(q));
}
this.jList2.setModel(md);
}else{
JOptionPane.showMessageDialog(null, "El Rut No Esta En La Base De Datos");
return;
}
}//GEN-LAST:event_jButton7ActionPerformed | 2 |
@Override
public boolean liiku(Ruutu kohde) {
Ruutu ohestalyotava = null;
if (this.ruutu.getSijainti().xMuutos(kohde.getSijainti()) != 0 && kohde.getNappula() == null) {
ohestalyotava = lauta.getRuutu(kohde.getSijainti().getX(), this.ruutu.getSijainti().getY());
}
int vuoro = -1;
if (kohde.getSijainti().yMuutos(this.ruutu.getSijainti()) == 2) {
vuoro = lauta.getVuoro() + 1;
}
boolean liikkui = super.liiku(kohde);
if (liikkui) {
if ((this.ruutu.getSijainti().getY() == 0 && this.getVari() == Vari.VALKOINEN) || (this.ruutu.getSijainti().getY() == 7 && this.getVari() == Vari.MUSTA)) {
Nappula ylennys = new Kuningatar(lauta, ruutu, this.getVari());
ylennys.setRuutu(this.ruutu);
this.ruutu.setNappula(ylennys);
}
if (ohestalyotava != null) {
ohestalyotava.poistaNappula();
}
ohestalyotavaVuorolla = vuoro;
}
return liikkui;
} | 9 |
@Override
protected EncryptionKey send(final String sessionId, final String orderId, final PaymentForm form,
final CommodityDetail[] commodityDetail) throws NoSuchAlgorithmException {
log.info("POST送信開始");
try {
// AIRWEBはクライアント証明書を配布しない
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(final String host, final SSLSession ses) {
return true;
}
});
// URLクラスのインスタンスを生成
MerchantConf info = MerchantConf.getInfo();
URL accessURL = new URL(info.getAirWebRegistUrl());
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, null, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// 接続します
URLConnection con = accessURL.openConnection();
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + Constants.AW_ENCODE);
con.setRequestProperty("Accept-Language", "ja");
con.setRequestProperty("Connection", "close");
con.setDoOutput(true);
// 出力ストリームを取得
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(con.getOutputStream(), Constants.AW_ENCODE));
Map<String, Object> map = createParameterMap(sessionId, orderId, form, commodityDetail);
String postData = getPostData(map);
log.info("送信データ:" + postData);
bw.write(postData);
bw.flush();
bw.close();
// 入力ストリームを取得
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), Constants.AW_ENCODE));
// 一行ずつ読み込みます
EncryptionKey ret = new EncryptionKey();
String line;
try {
while ((line = in.readLine()) != null) {
// 表示します
log.info("返信内容:" + line);
if (line.startsWith("MERCHANT_ENCRYPTION_KEY")) {
String tmp = line.substring(24);
registKey(orderId, tmp, sessionId);
ret.setMerchantEncryptionKey(tmp);
} else if (line.startsWith("BROWSER_ENCRYPTION_KEY")) {
String tmp = line.substring(23);
ret.setBrowserEncryptionKey(tmp);
} else if (line.startsWith("ERROR_MESSAGE")) {
String tmp = URLDecoder.decode(line.substring(14), Constants.AW_ENCODE);
ret.setErrorMessage(tmp);
}
}
} catch (Throwable th) {
log.error("受信結果解析エラーです", th);
return null;
}
// 入力ストリームを閉じます
in.close();
log.info("POST通信完了");
return ret;
} catch (MalformedURLException e) {
log.error("接続エラーです。", e);
return null;
} catch (IOException e) {
log.error("接続エラーです。", e);
return null;
} catch (NoSuchAlgorithmException e) {
log.error("接続エラーです。", e);
return null;
} catch (KeyManagementException e) {
log.error("接続エラーです。", e);
return null;
}
} | 9 |
private boolean jj_3R_41() {
if (jj_scan_token(WHILE)) return true;
if (jj_3R_50()) return true;
if (jj_scan_token(DO)) return true;
return false;
} | 3 |
public Site getAdjByTag(Site site, SiteTag tag) {
int x = site.x;
int y = site.y;
switch (tag) {
case NORTH: y--; break;
case EAST: x++; break;
case SOUTH: y++; break;
case WEST: x--; break;
}
if (this instanceof TorusSpace) {
x = x % width;
y = y % height;
return getSite(x, y);
} else {
if ((x < 0) || (x >= width) || (y < 0) || (y >= height))
return null;
else
return getSite(x, y);
}
} | 9 |
public boolean checkLoan(Loan l, final Inventory i) {
Borrower bwer = l.getBorrower();
Period period = l.getPeriod();
Equipment stuff = i.findAvailableEquipment(l.getModel());
final int LOAN_DURATION_LIMIT;
final int LOAN_RESERVATION_LIMIT;
// Checks if the loan is valid
if (stuff == null)
return false;
// if(bwer.getType().equals("teacher")) => ne reconnait pas que c'est un
// Teacher
if (bwer instanceof Teacher) {
LOAN_DURATION_LIMIT = TEACHER_LOAN_DURATION_LIMIT;
LOAN_RESERVATION_LIMIT = TEACHER_LOAN_RESERVATION_LIMIT;
} else {
LOAN_DURATION_LIMIT = STUDENT_LOAN_DURATION_LIMIT;
LOAN_RESERVATION_LIMIT = STUDENT_LOAN_RESERVATION_LIMIT;
}
if (period.getDuration() > LOAN_DURATION_LIMIT
|| period.daysFromNow() > LOAN_RESERVATION_LIMIT)
return false;
// Updates the stuff, the loan and the borrower
stuff.getUnavailabalityPeriods().add(period);
l.setEquipmentID(stuff.getId());
bwer.getLoanList().add(l);
return true;
} | 4 |
@XmlElementDecl(namespace = "http://www.w3.org/2001/04/xmlenc#", name = "RecipientKeyInfo", scope = AgreementMethodType.class)
public JAXBElement<KeyInfoType> createAgreementMethodTypeRecipientKeyInfo(KeyInfoType value) {
return new JAXBElement<KeyInfoType>(_AgreementMethodTypeRecipientKeyInfo_QNAME, KeyInfoType.class, AgreementMethodType.class, value);
} | 0 |
final void method3643(Canvas canvas, int i, int i_195_) {
do {
try {
anInt7955++;
if (canvas == ((NativeToolkit) this).aCanvas7925)
throw new RuntimeException();
if (aHashtable8014.containsKey(canvas))
break;
if (!canvas.isShowing())
throw new RuntimeException();
try {
Class var_class = Class.forName("java.awt.Canvas");
Method method
= var_class.getMethod("setIgnoreRepaint",
new Class[] { Boolean.TYPE });
method.invoke(canvas, new Object[] { Boolean.TRUE });
} catch (Exception exception) {
/* empty */
}
Object object = method3876(-1, canvas);
if (object == null)
throw new RuntimeException();
aHashtable8014.put(canvas, object);
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("wga.VF("
+ (canvas != null ? "{...}"
: "null")
+ ',' + i + ',' + i_195_
+ ')'));
}
break;
} while (false);
} | 8 |
public void registerMany(Kim kim) {
int length = kim.length;
int limit = this.capacity - this.length;
if (limit > JSONzip.substringLimit) {
limit = JSONzip.substringLimit;
}
int until = length - (JSONzip.minSubstringLength - 1);
for (int from = 0; from < until; from += 1) {
int len = length - from;
if (len > JSONzip.maxSubstringLength) {
len = JSONzip.maxSubstringLength;
}
len += from;
Node node = this.root;
for (int at = from; at < len; at += 1) {
Node next = node.vet(kim.get(at));
if (next.integer == none
&& at - from >= (JSONzip.minSubstringLength - 1)) {
next.integer = this.length;
this.uses[this.length] = 1;
this.kims[this.length] = kim;
this.froms[this.length] = from;
this.thrus[this.length] = at + 1;
if (JSONzip.probe) {
try {
JSONzip.log("<<" + this.length + " "
+ new Kim(kim, from, at + 1) + ">> ");
} catch (Throwable ignore) {
}
}
this.length += 1;
limit -= 1;
if (limit <= 0) {
return;
}
}
node = next;
}
}
} | 9 |
public synchronized void gridletPause(int gridletId, int userId, boolean ack)
{
boolean status = false;
// find this Gridlet in the execution list
int found = gridletInExecList_.indexOf(gridletId, userId);
if (found >= 0)
{
// update Gridlets in execution list up to this point in time
updateGridletProcessing();
// get a Gridlet from execution list
ResGridlet rgl = (ResGridlet) gridletInExecList_.remove(found);
// if a Gridlet is finished upon pausing, then set it to success
// instead.
if (rgl.getRemainingGridletLength() == 0.0)
{
System.out.println(super.resName_
+ ".TimeShared.gridletPause(): Cannot pause"
+ " Gridlet #" + gridletId + " for User #" + userId
+ " since it is FINISHED.");
gridletFinish(rgl, Gridlet.SUCCESS);
}
else
{
status = true;
rgl.setGridletStatus(Gridlet.PAUSED);
// add the Gridlet into the paused list
gridletPausedList_.add(rgl);
System.out.println(super.resName_ +
".TimeShared.gridletPause(): Gridlet #" + gridletId +
" with User #" + userId + " has been sucessfully PAUSED.");
}
// forecast all Gridlets in the execution list
forecastGridlet();
}
else // if not found in the execution list
{
System.out.println(super.resName_ +
".TimeShared.gridletPause(): Cannot find " +
"Gridlet #" + gridletId + " for User #" + userId);
}
// sends back an ack
if (ack)
{
super.sendAck(GridSimTags.GRIDLET_PAUSE_ACK, status,
gridletId, userId);
}
} | 3 |
private boolean AvoidGrenade(Info info){
for(int i=0;i<info.getEnemies().size();i++){
double angle = 0;
int e_x = info.getX();
int e_y = info.getY();
int my_x = info.getEnemies().get(i).getX();
int my_y = info.getEnemies().get(i).getY();
//-----------VYPOCET UHLU
if(my_y > e_y && my_x < e_x || my_y < e_y && my_x > e_x){
angle += (Math.atan(Math.abs(((double)(my_x-e_x))/((double)(my_y-e_y)))))*(180.00 / Math.PI);
}else{
angle += 90.00 - (Math.atan(Math.abs(((double)(my_x-e_x))/((double)(my_y-e_y)))))*(180.00 / Math.PI);
}
angle = (int)angle;
System.out.println(angle);
if(angle == info.getEnemies().get(i).getDirection()){
System.out.println("DANGER");
step++;
return true;
}
}
return false;
} | 6 |
@Override
public void initialize(String filePath){
patternEncoderUtil = new PatternEncoderUtil();
try {
setUtil(patternEncoderUtil);
analyzePattern(new FileReader(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
patternEncoderUtil.construct2DMatrix(new FileReader(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
initializeEncoderComponents();
} | 2 |
private int sendClearCommand() throws Exception
{
int c;
ArrayList<Integer> answer = new ArrayList();
this.output.flush();
Thread.sleep(this.MAX_INTERVAL * 10);
this.output.write((char)Sign.REQUEST);
this.output.flush();
Thread.sleep(this.MAX_INTERVAL * 3);
//this.input.reset();
System.out.println();
while ((c = input.read()) != -1)
answer.add(c);
if (answer.get(0) == Status.ERROR)
return 1;
if (answer.get(0) == Status.OK)
{
if (answer.get(1) != Sign.MESSAGE_BEGIN)
throw new Exception("Второй байт ответа не является STX!");
this.output.write((char)Status.OK);
Thread.sleep(this.MAX_INTERVAL * 2);
return 2;
}
else
throw new Exception("Первый байт ответа не является ACK млм NAK!");
} | 4 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TNode<T> tNode = (TNode<T>) o;
if (center != tNode.center) return false;
if (character != tNode.character) return false;
if (left != tNode.left) return false;
if (right != tNode.right) return false;
if (value != tNode.value) return false;
return true;
} | 8 |
public static void main(String args[]) throws Exception
{
try
{
//int depth=Integer.parseInt(args[2]);
int depth=3;
FileReader in = new FileReader(args[0]);
BufferedReader br = new BufferedReader(in);
String test=br.readLine();
FileWriter out = new FileWriter(args[1]);
BufferedWriter write = new BufferedWriter(out);
//String test="WWWxxxxxxxxxxxxxxxxxBB";
char[] board=new char[22];
board=test.toCharArray();
// NEW ROUTINE TO CHANGE TO WHITE TO BLACK and REVERSE
char[] board2=new char[22];
for(int j=0;j<22;j++)
{
if(board[j]=='W') board2[j]='B';
if(board[j]=='B') board2[j]='W';
if(board[j]=='x') board2[j]='x';
}
int Min=MinMax(board2,depth);
// convert it back !!
char[] best=bestmove.toCharArray();
char[] bestmove_update=new char[22];
for(int j=0;j<22;j++)
{
if(best[j]=='W') bestmove_update[j]='B';
if(best[j]=='B') bestmove_update[j]='W';
if(best[j]=='x') bestmove_update[j]='x';
}
String bestmove2=new String(bestmove_update);
System.out.println(bestmove2);
System.out.println("MinMax Estimate="+Min);
System.out.println("Positions Evaluated:"+count_min);
out.write(bestmove2);
out.close();
//System.out.println(Alphabeta(board,depth,-10000,10000,'W'));
}catch(Exception e){}
} | 9 |
private void verificarSeleccionParametricasTransformador() {
if (puntoLuz.getTransformador().getTipoTransformador().getId() == null) {
puntoLuz.getTransformador().setTipoTransformador(null);
}
if (puntoLuz.getTransformador().getFabricante().getId() == 0) {
puntoLuz.getTransformador().setFabricante(null);
}
if (puntoLuz.getTransformador().getFrecuencia().getId() == null) {
puntoLuz.getTransformador().setFrecuencia(null);
}
if (puntoLuz.getTransformador().getFase().getId() == null) {
puntoLuz.getTransformador().setFase(null);
}
if (puntoLuz.getTransformador().getTipoConexionTransformador().getId() == null) {
puntoLuz.getTransformador().setTipoConexionTransformador(null);
}
if (puntoLuz.getTransformador().getVoltajeAlta().getId() == null) {
puntoLuz.getTransformador().setVoltajeAlta(null);
}
if (puntoLuz.getTransformador().getVoltajeBaja().getId() == null) {
puntoLuz.getTransformador().setVoltajeBaja(null);
}
if (puntoLuz.getTransformador().getPotencia().getId() == null) {
puntoLuz.getTransformador().setPotencia(null);
}
} | 8 |
@Override
public void buildFinished(SRunningBuild build) {
super.buildFinished(build);
if( !build.isPersonal() && build.getBuildStatus().isSuccessful() && slackConfig.postSuccessful() )
{
processSuccessfulBuild(build);
}
else if ( !build.isPersonal() && build.getBuildStatus().isFailed() && slackConfig.postFailed() )
{
postFailureBuild(build);
}
else
{
//TODO - modify in future if we care about other states
}
} | 6 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(VtnEventosSociales.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VtnEventosSociales.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VtnEventosSociales.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VtnEventosSociales.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new VtnEventosSociales().setVisible(true);
}
});
} | 6 |
public List<List<LngLatAlt>> getInteriorRings()
{
assertExteriorRing();
return coordinates.subList(1, coordinates.size());
} | 0 |
protected void processClauseGraphFragments(List<GraphFragment> matchPhraseList) throws InformationProblem {
int matchPhraseCount = 0;
for (GraphFragment matchPhrase : matchPhraseList) {
if (matchPhraseCount > 0) {
_strBuf.append(", ");
}
List<List<GraphComponent>> matchPhraseGraphComponentList = (new DepthFirstVisitor(matchPhrase)).findGraphPaths();
if (matchPhraseGraphComponentList.size() > 0) {
int matchPhraseGraphComponentCount = 0;
for (List<GraphComponent> individualPathGraphComponentList : matchPhraseGraphComponentList) {
if (matchPhraseGraphComponentCount > 0) {
_strBuf.append(", ");
}
// append the cypher string encoding of each graph component in the list
if (individualPathGraphComponentList != null) {
for (GraphComponent graphComponent : individualPathGraphComponentList) {
_strBuf.append(convertGraphComponentToCypher(graphComponent));
}
}
matchPhraseGraphComponentCount++;
} // end individual path graph component list for loop
} // end non zero length matchPhraseGraphComponentList
matchPhraseCount++;
}
} | 7 |
byte[] getPngData(Image img) {
int imageType = artwork.hasAlpha() ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
// FIXME: Wouldn't it be better to use a BufferedImage and avoid this anyway?
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), imageType);
Graphics bg = bi.getGraphics();
bg.drawImage(img, 0, 0, null);
bg.dispose();
ByteArrayOutputStream pngFileStream = new ByteArrayOutputStream(1024);
try {
ImageIO.write(bi, "png", pngFileStream);
} catch (IOException e) {
}
byte[] pngData = pngFileStream.toByteArray();
return pngData;
} | 2 |
public int getX() {
if(this == RIGHT) return 1;
if(this == LEFT) return -1;
return 0;
} | 2 |
public int getCount(int number){
if(number > 3){
for(int i=3 ; i < number ; i++){
for(int j=2 ; j < i ; j++){
count ++;
if(i%j == 0){
break;
}
count--;
}
}
number -= (count+2);
System.out.println(number);
return number;
}else if(number == 3){
return 1;
}
return 0;
} | 5 |
public boolean chequearQuery(String sql) {
boolean resultado = false;
int indice = sql.indexOf(' ');
String tipo = sql.substring(0, indice).toLowerCase();
if (tipo.equals("select") || tipo.equals("insert")
|| tipo.equals("update") || tipo.equals("delete"))
resultado = true;
return resultado;
} | 4 |
private ResolvedGenericType resolveSuper(Type genericSuperType) {
if (genericSuperType instanceof Class) {
return new ResolvedGenericType((Class<?>)genericSuperType, new Class<?>[0]);
} else if (genericSuperType instanceof ParameterizedType) {
TypeVariable<?>[] typeParameters = getRawType().getTypeParameters();
Type[] superTypeArguments = ((ParameterizedType) genericSuperType).getActualTypeArguments();
for (int i=0; i<superTypeArguments.length; i++) {
for (int j=0; j<typeParameters.length; j++) {
if (superTypeArguments[i]==typeParameters[j]) {
superTypeArguments[i]=this.actualParameters[j];
}
}
}
return new ResolvedGenericType((Class<?>) ((ParameterizedType) genericSuperType).getRawType(), superTypeArguments);
}
throw new IllegalArgumentException("Unable to handle type "+this);
} | 9 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Employee)) {
return false;
}
Employee other = (Employee) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} | 5 |
@Override
public <T extends Event> void event(final T event) {
for (Class<? extends Event> cls : core.getClasses()) {
if (cls.isInstance(event)) {
for (@SuppressWarnings("rawtypes")
final ControllerListener listener : core.getListeners(cls)) {
Runnable r = new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
try {
listener.event(event);
} catch (RuntimeException e) {
e.printStackTrace();
}
}
};
executorService.execute(r);
}
}
}
} | 5 |
@SuppressWarnings("unchecked")
void readRegulationTrack(String regTrack) {
//---
// Read file
//---
if (verbose) Timer.showStdErr("Reading regulation track '" + regTrack + "'");
String regFile = config.getDirDataVersion() + "/regulation_" + regTrack + ".bin";
ArrayList<Regulation> regulation = (ArrayList<Regulation>) Gpr.readFileSerializedGz(regFile);
//---
// Are all chromosomes available?
//---
Genome genome = config.getGenome();
HashMap<String, Integer> chrs = new HashMap<String, Integer>();
for (Regulation r : regulation) {
String chr = r.getChromosomeName();
int max = chrs.containsKey(chr) ? chrs.get(chr) : 0;
max = Math.max(max, r.getEnd());
chrs.put(chr, max);
}
// Add all chromos
for (String chr : chrs.keySet())
if (genome.getChromosome(chr) == null) genome.add(new Chromosome(genome, 0, chrs.get(chr), 1, chr));
//---
// Add all markers to predictor
//---
SnpEffectPredictor snpEffectPredictor = config.getSnpEffectPredictor();
for (Regulation r : regulation)
snpEffectPredictor.add(r);
} | 6 |
@Test
public void testInfixToPostfix2() throws DAIllegalArgumentException,
DAIndexOutOfBoundsException, ShouldNotBeHereException,
BadNextValueException, UnmatchingParenthesisException {
try {
infix.addLast("*");
infix.addLast("5");
QueueInterface<String> postFix = calc.infixToPostfix(infix);
String result = "245*+";
assertEquals(result, calc.stringTrans(postFix));
} catch (DAIllegalArgumentException e) {
throw new DAIllegalArgumentException();
} catch (DAIndexOutOfBoundsException e) {
throw new DAIndexOutOfBoundsException();
} catch (ShouldNotBeHereException e) {
throw new ShouldNotBeHereException();
} catch (BadNextValueException e) {
throw new BadNextValueException();
} catch (UnmatchingParenthesisException e) {
throw new UnmatchingParenthesisException();
}
} | 5 |
public Vector<LogicalJoinNode> orderJoins(
HashMap<String, TableStats> stats,
HashMap<String, Double> filterSelectivities, boolean explain)
throws ParsingException {
// See the project writeup for some hints as to how this function
// should work.
// some code goes here
//Replace the following
//return joins;
if (joins == null || joins.size() == 0) {
return new Vector<LogicalJoinNode>();
}
PlanCache pc = new PlanCache();
for (int i = 1; i <= joins.size(); i++) {
Set<Set<LogicalJoinNode>> subset_i = enumerateSubsets(joins, i);
for(Set<LogicalJoinNode> s: subset_i) {
CostCard c = new CostCard();
c.cost = Double.MAX_VALUE; // bestPlan = {}
c.card = Integer.MAX_VALUE;
c.plan = new Vector<LogicalJoinNode> ();
for (LogicalJoinNode joinToRemove : s) {
CostCard c_new = computeCostAndCardOfSubplan(stats,
filterSelectivities,
joinToRemove,
s,
c.cost,
pc);
if (c_new != null) { // if cost(plan) < cost(bestPlan)
if (c.cost > c_new.cost) {
c = c_new; // bestPlan = plan
}
}
}
pc.addPlan(s, c.cost, c.card, c.plan); //optjoin(s) = bestPlan
}
}
Vector<LogicalJoinNode> js = pc.getOrder(new HashSet<LogicalJoinNode>(joins));
if (explain) {
printJoins(js, pc, stats, filterSelectivities);
}
return js;
} | 8 |
@Override
public void initializeNorm()
{
checkingNorms();
for ( Action action : getAllActions().values() )
{
if ( action.getNormType() != null ) // Only action linked with deontic concept will goona be setted
{
if ( action.getNormType() == NormType.OBLIGATION )
{
if ( getPlayer().containAction( action.getName() ) )
getPlayer().getAction( action.getName() ).setNormType( NormType.OBLIGATION );
}
else if ( action.getNormType() == NormType.PROHIBITION )
{
if ( getPlayer().containAction( action.getName() ) )
getPlayer().getAction( action.getName() ).setNormType( NormType.PROHIBITION );
}
else
{
if ( getPlayer().containAction( action.getName() ) )
getPlayer().getAction( action.getName() ).setNormType( NormType.PERMISSION );
}
}
}
for( Belief belief : getAllBeliefs().values() )
{
if( belief.getNormType() != null ) // Only belief linked with deontic concept will goona be added
{
getPlayer().addBelief( belief.getName(), belief );
}
}
} | 9 |
public boolean canAttack(Unit enemy) {
return enemy != null && enemy.getHP() > 0 && team != enemy.getTEAM() && inRange(enemy) && attacking;
} | 4 |
public static int findSmallestDiff(int[] a)
{
if (a.length < 2)
return -1;
int diff = (int)Math.abs(a[0] - a[1]);
for (int i = 0; i < a.length; i++)
for (int j = i + 1; j < a.length; j++) {
int tmp_diff = Math.abs(a[i] - a[j]);
if (tmp_diff < diff)
diff = tmp_diff;
}
return diff;
} | 4 |
@EventHandler
public void SkeletonRegeneration(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Skeleton.Regeneration.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof Arrow) {
Arrow a = (Arrow) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getSkeletonConfig().getBoolean("Skeleton.Regeneration.Enabled", true) && shooter instanceof Skeleton && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, plugin.getSkeletonConfig().getInt("Skeleton.Regeneration.Time"), plugin.getSkeletonConfig().getInt("Skeleton.Regeneration.Power")));
}
}
} | 7 |
public void update(Game game)
{
actions.clear();
//passive moment.
super.updatePassive();
//Get the closest targets
closestTargets(game);
Direction act = Types.DNONE;
if(targets.size() > 0)
{
//If there's a target, get the path to it and take the first action.
VGDLSprite target = targets.get(0);
ArrayList<Node> path = game.getPath(this.getPosition(), target.getPosition());
if(path!=null && path.size()>0)
{
Vector2d v = path.get(0).comingFrom;
act = new Direction(v.x, v.y);
}
this.counter = this.cons; //Reset the counter of consecutive moves.
}else
{
//No target, just move random.
act = getRandomMove(game);
}
//Apply the action to move.
this.physics.activeMovement(this, act, this.speed);
} | 3 |
@Override
protected void mutate(Individual i) {
Expression e = (Expression) i;
Random r = new Random();
if (e.isLeaf()) {
((Leaf) e).rebuild();
return;
}// else
int d = r.nextInt(e.depth());
int current = 0;
int choosen = 0;
Expression[] exps = null;
while (current < d && !e.isLeaf()) {
exps = ((Operator) e).expressions;
choosen = r.nextInt(exps.length);
e = exps[choosen];
}
if(exps==null)
((Operator) e).rebuildBest(4);
else{
exps[choosen] = Expression.generateRandomTree(Expression.maxDepth-e.depth());
e.recalcule();
}
} | 4 |
private <T extends Fetcher> void doFetcher(Collection<T> fs,
Map<String, Integer> ignored, Map<String, Integer> offered)
throws InterruptedException {
for (Fetcher fetcher : fs) {
String fetcherKey = fetcher.getClass().getName();
if (fetcher.isIgnore()) {
this.getLogger().debug(
"ignore fetch " + fetcher.getRequestWrapper().getUrl());
if (ignored.containsKey(fetcherKey)) {
ignored.put(fetcherKey, ignored.get(fetcherKey) + 1);
} else {
ignored.put(fetcherKey, 1);
}
continue;
}
boolean offeredFlag = false;
do {
offeredFlag = IautosResource.fetchQueue.offer(fetcher, 500,
TimeUnit.MILLISECONDS);
getLogger().debug(
"offer " + fetcher.getRequestWrapper().getUrl());
} while (!offeredFlag);
if (offered.containsKey(fetcherKey)) {
offered.put(fetcherKey, offered.get(fetcherKey) + 1);
} else {
offered.put(fetcherKey, 1);
}
}
} | 5 |