text stringlengths 14 410k | label int32 0 9 |
|---|---|
protected void loadInputProperties() {
if (VERBOSE)
System.out.println("Loading '" + getInputFilename() + "'...");
m_InputProperties = new Properties();
try {
File f = new File(getInputFilename());
if (getExplicitPropsFile() && f.exists())
m_InputProperties.load(new FileInputStream(getInputFilename()));
else
m_InputProperties = Utils.readProperties(getInputFilename());
// excludes
m_Excludes.clear();
Properties p = Utils.readProperties(EXCLUDE_FILE);
Enumeration enm = p.propertyNames();
while (enm.hasMoreElements()) {
String name = enm.nextElement().toString();
// new Hashtable for key
Hashtable t = new Hashtable();
m_Excludes.put(name, t);
t.put(EXCLUDE_INTERFACE, new Vector());
t.put(EXCLUDE_CLASS, new Vector());
t.put(EXCLUDE_SUPERCLASS, new Vector());
// process entries
StringTokenizer tok = new StringTokenizer(p.getProperty(name), ",");
while (tok.hasMoreTokens()) {
String item = tok.nextToken();
// get list
Vector list = new Vector();
if (item.startsWith(EXCLUDE_INTERFACE + ":"))
list = (Vector) t.get(EXCLUDE_INTERFACE);
else if (item.startsWith(EXCLUDE_CLASS + ":"))
list = (Vector) t.get(EXCLUDE_CLASS);
else if (item.startsWith(EXCLUDE_SUPERCLASS))
list = (Vector) t.get(EXCLUDE_SUPERCLASS);
// add to list
list.add(item.substring(item.indexOf(":") + 1));
}
}
}
catch (Exception e) {
e.printStackTrace();
}
} | 9 |
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
request.setCharacterEncoding("UTF-8");
User loggedIn = (User) session.getAttribute("loggedIn");
String gameidString = request.getParameter("gameid");
int gameid = Integer.parseInt(gameidString);
int points = 0;
String notes = "";
String rolenotes = "";
if (!isLoggedIn(session)) {
showJSP("index.jsp", request, response);
return;
}
String idParam = request.getParameter("id");
Player player = null;
int id = 1;
try {
id = Integer.parseInt(idParam);
} catch (Exception e) {
}
try {
player = Player.getPlayer(id);
if (Game.getGame(Player.getPlayer(id).getGameid()).getUserID() != loggedIn.getID()) {
setError("Stop trying to hack the database!", request);
showJSP("index.jsp", request, response);
return;
}
} catch (SQLException ex) {
Logger.getLogger(GameServlet.class.getName()).log(Level.SEVERE, null, ex);
}
if (player != null) {
request.setAttribute("player", player);
request.setAttribute("gameid", gameid);
showJSP("player.jsp", request, response);
} else {
request.setAttribute("game", null);
setError("The player was not found!", request);
List<Player> players = null;
try {
players = Player.getPlayers(loggedIn.getID());
} catch (SQLException ex) {
Logger.getLogger(GameServlet.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("players", players);
showJSP("Game?id=" + gameid, request, response);
}
} | 6 |
public void RenderAll(Graphics g) {
for (int i = 0; i < tiles.length; i++) { // cols
for (int j = 0; j < tiles[0].length; j++) { // rows
int xt;
int yt;
if (tiles[i][j].getTileID() != 0) {
xt = tiles[i][j].getTileID() % 16 - 1;
yt = (int) Math.floor(tiles[i][j].getTileID() / 16);
spriteSheet.getSubImages()[yt][xt].draw(j * 64, i * 64);
}
}
}
} | 3 |
public static String generateKey(String lockString){
int i = 0;
byte[] lock = null;
byte[] key = null;
lockString = lockString.substring(0,lockString.indexOf(' '));
lockString.trim();
lock = lockString.getBytes();
key = new byte[lock.length];
for(i=1;i<lock.length;i++){
key[i] = (byte)((lock[i] ^ lock[i-1]) & 0xFF);
}
key[0] = (byte)((((lock[0] ^ lock[lock.length-1]) ^ lock[lock.length-2]) ^ 5) & 0xFF);
for(i=0;i<key.length;i++){
key[i] = (byte)((((key[i]<<4) & 0xF0) | ((key[i]>>4) & 0x0F)) & 0xFF);
}
return(dcnEncode(new String(key)));
} | 2 |
public void printMiddle(Node root) {
if (root == null) {
return;
}
System.out.println("Linked list is ");
print(root);
Node hare = null;
Node tortoise = null;
boolean temp = false;
if (size(root) % 2 == 0)
temp = true;
if (temp) {
hare = root.getLink();
tortoise = root;
} else {
hare = root;
tortoise = root;
}
while (hare != null && hare.getLink() != null) {
hare = hare.getLink().getLink();
tortoise = tortoise.getLink();
}
if (temp) {
System.out.println("Middle elements :" + tortoise.getData()
+ " and " + tortoise.getLink().getData());
} else {
System.out.println("Middle element is :" + tortoise.getData());
}
} | 6 |
static final void method2811(boolean bool) {
anInt6777++;
if ((InterfaceScript.anInt6992 ^ 0xffffffff) > -1) {
InterfaceScript.anInt6992 = 0;
TextureLoader.anInt4609 = -1;
Class48.anInt859 = -1;
}
if (InterfaceScript.anInt6992 > Class75.anInt1259) {
InterfaceScript.anInt6992 = Class75.anInt1259;
Class48.anInt859 = -1;
TextureLoader.anInt4609 = -1;
}
if ((Class245.anInt3170 ^ 0xffffffff) > -1) {
Class48.anInt859 = -1;
Class245.anInt3170 = 0;
TextureLoader.anInt4609 = -1;
}
if ((Class245.anInt3170 ^ 0xffffffff)
< (Class75.anInt1267 ^ 0xffffffff)) {
Class245.anInt3170 = Class75.anInt1267;
TextureLoader.anInt4609 = -1;
Class48.anInt859 = -1;
}
if (bool != false)
aDouble6774 = 1.5874482848681375;
} | 5 |
public void train(StringWrapperIterator i)
{
Set seenTokens = new HashSet();
while (i.hasNext()) {
BagOfTokens bag = asBagOfTokens(i.nextStringWrapper());
seenTokens.clear();
for (Iterator j=bag.tokenIterator(); j.hasNext(); ) {
totalTokenCount++;
Token tokj = (Token)j.next();
if (!seenTokens.contains(tokj)) {
seenTokens.add(tokj);
// increment documentFrequency counts
Integer df = (Integer)documentFrequency.get(tokj);
if (df==null) documentFrequency.put(tokj,ONE);
else if (df==ONE) documentFrequency.put(tokj,TWO);
else if (df==TWO) documentFrequency.put(tokj,THREE);
else documentFrequency.put(tokj, new Integer(df.intValue()+1));
}
}
collectionSize++;
}
} | 6 |
public int getLength() {
return this.length;
} | 0 |
public Unit getOccupyingUnit() {
Unit unit = getFirstUnit();
Player owner = null;
if (getOwningSettlement() != null) {
owner = getOwningSettlement().getOwner();
}
if (owner != null && unit != null && unit.getOwner() != owner
&& owner.getStance(unit.getOwner()) != Stance.ALLIANCE) {
for(Unit enemyUnit : getUnitList()) {
if (enemyUnit.isOffensiveUnit()
&& enemyUnit.getState() == Unit.UnitState.FORTIFIED) {
return enemyUnit;
}
}
}
return null;
} | 8 |
public void inject(T csvBean, Map<Field, String> values) throws CsvReadException {
if (csvBean == null || values == null || values.isEmpty())
return;
for (Map.Entry<Field, String> entry : values.entrySet()) {
Field field = entry.getKey();
String content = entry.getValue();
Object value = null;
try {
value = convert(content, field);
} catch (Exception e) {
String caption = ReflectUtil.getFieldCaption(field);
csvBean.setResult(ProcessResult.failed);
csvBean.addMessage(caption + e.getMessage());
}
if (value != null)
injectField(csvBean, field, value);
}
} | 6 |
public BoardPiece getPlayerKing(String playerColor) throws Exception{
for (int i=0; i<boardSquares.length; i++){
for (int j=0; j<boardSquares[i].length; j++){
BoardPiece boardPiece = boardSquares[i][j].getBoardPiece();
if (boardPiece != null){
if (boardPiece.pieceColor.equals(playerColor) && boardPiece.pieceType.equals(BoardPiece.TYPE_KING)){
return boardPiece;
}
}
}
}
throw new Exception();
} | 5 |
public void loadAttributes(BufferedReader reader) {
try {
String line;
while((line = reader.readLine()) != null && !line.matches("<END>")) {
this.attributes += line + "\n";
}
if(attributes.endsWith("\n"))
attributes = attributes.substring(0, attributes.length() - 1);
} catch (IOException e) {
e.printStackTrace();
}
} | 4 |
private void closeConnection() {
// remove from the selector.
_skey.cancel();
try {
_sChannel.close();
} catch (IOException ignored) {
ignored = null;
}
} | 1 |
public static boolean isMyPlant(Item I, MOB mob)
{
if((I!=null)
&&(I.rawSecretIdentity().equals(mob.Name()))
&&(I.owner()!=null)
&&(I.owner() instanceof Room))
{
for(final Enumeration<Ability> a=I.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)
&&((A.invoker()==mob)||(A.text().equals(mob.Name())))
&&(A instanceof Chant_SummonPlants))
return true;
}
}
return false;
} | 9 |
public boolean equals(PERangeList other) {
if(this == other) {
return true;
} else if(getNumPE() != other.getNumPE()) {
return false;
}
PERangeList list = intersection(other);
if(list.getNumPE() == getNumPE() && list.getNumPE() == other.getNumPE()) {
return true;
}
return true;
} | 4 |
public void paint(GC gc, int width, int height) {
if (!example.checkAdvancedGraphics()) return;
Device device = gc.getDevice();
if (alphaImg1 == null) {
alphaImg1 = GraphicsExample.loadImage(device, GraphicsExample.class, "alpha_img1.png");
alphaImg2 = GraphicsExample.loadImage(device, GraphicsExample.class, "alpha_img2.png");
}
Rectangle rect = alphaImg1.getBounds();
gc.setAlpha(alphaValue);
gc.drawImage(alphaImg1, rect.x, rect.y, rect.width, rect.height,
width/2, height/2, width/4, height/4);
gc.drawImage(alphaImg1, rect.x, rect.y, rect.width, rect.height,
0, 0, width/4, height/4);
gc.setAlpha(255-alphaValue);
gc.drawImage(alphaImg2, rect.x, rect.y, rect.width, rect.height,
width/2, 0, width/4, height/4);
gc.drawImage(alphaImg2, rect.x, rect.y, rect.width, rect.height,
0, 3*height/4, width/4, height/4);
// pentagon
gc.setBackground(device.getSystemColor(SWT.COLOR_DARK_MAGENTA));
gc.fillPolygon(new int [] {width/10, height/2, 3*width/10, height/2-width/6, 5*width/10, height/2,
4*width/10, height/2+width/6, 2*width/10, height/2+width/6});
gc.setBackground(device.getSystemColor(SWT.COLOR_RED));
// square
gc.setAlpha(alphaValue);
gc.fillRectangle(width/2, height-75, 75, 75);
// triangle
gc.setAlpha(alphaValue + 15);
gc.fillPolygon(new int[]{width/2+75, height-(2*75), width/2+75, height-75, width/2+(2*75), height-75});
// triangle
gc.setAlpha(alphaValue + 30);
gc.fillPolygon(new int[]{width/2+80, height-(2*75), width/2+(2*75), height-(2*75), width/2+(2*75), height-80});
// triangle
gc.setAlpha(alphaValue + 45);
gc.fillPolygon(new int[]{width/2+(2*75), height-(2*75), width/2+(3*75), height-(2*75), width/2+(3*75), height-(3*75)});
// triangle
gc.setAlpha(alphaValue + 60);
gc.fillPolygon(new int[]{width/2+(2*75), height-((2*75)+5), width/2+(2*75), height-(3*75), width/2+((3*75)-5), height-(3*75)});
// square
gc.setAlpha(alphaValue + 75);
gc.fillRectangle(width/2+(3*75), height-(4*75), 75, 75);
gc.setBackground(device.getSystemColor(SWT.COLOR_GREEN));
// circle in top right corner
gc.setAlpha(alphaValue2);
gc.fillOval(width-100, 0, 100, 100);
// triangle
gc.setAlpha(alphaValue + 90);
gc.fillPolygon(new int[]{width-300, 10, width-100, 10, width-275, 50});
// triangle
gc.setAlpha(alphaValue + 105);
gc.fillPolygon(new int[]{width-10, 100, width-10, 300, width-50, 275});
// quadrilateral shape
gc.setAlpha(alphaValue + 120);
gc.fillPolygon(new int[]{width-100, 100, width-200, 150, width-200, 200, width-150, 200});
// blue circles
gc.setBackground(device.getSystemColor(SWT.COLOR_BLUE));
int size = 50;
int alpha = 20;
for (int i = 0; i < 10; i++) {
gc.setAlpha(alphaValue + alpha);
if (i % 2 > 0) {
gc.fillOval(width-((i+1)*size), height-size, size, size);
} else {
gc.fillOval(width-((i+1)*size), height-(3*size/2), size, size);
}
alpha = alpha + 20;
}
// SWT string appearing randomly
gc.setAlpha(alphaValue2);
String text = GraphicsExample.getResourceString("SWT");
Font font = createFont(device, 100, SWT.NONE);
gc.setFont(font);
Point textSize = gc.stringExtent(text);
int textWidth = textSize.x;
int textHeight = textSize.y;
if (alphaValue2 == 0){
randX = (int)(width*Math.random());
randY = (int)(height*Math.random());
randX = (randX > textWidth) ? randX - textWidth : randX;
randY = (randY > textHeight) ? randY - textHeight : randY;
}
gc.drawString(text, randX, randY, true);
font.dispose();
// gray donut
gc.setAlpha(100);
Path path = new Path(device);
path.addArc((width-diameter)/2, (height-diameter)/2, diameter, diameter, 0, 360);
path.close();
path.addArc((width-diameter+25)/2, (height-diameter+25)/2, diameter-25, diameter-25, 0, 360);
path.close();
gc.setBackground(device.getSystemColor(SWT.COLOR_GRAY));
gc.fillPath(path);
gc.drawPath(path);
path.dispose();
} | 7 |
public static int min3(int a, int b, int c) {
if( a > b )
return (( c > b) ? b : c);
else
return (( c > a) ? a : c);
} | 3 |
private void btnGuardarClaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarClaveActionPerformed
String p = JOptionPane.showInputDialog("Introduce la clave a guardar");
if (Obj.principal.claves.get(p) != null) {
int g = JOptionPane.showConfirmDialog(null,
"La clave (" + p + ") ya existe"
+ " ¿Quieres sobreescribirla?");
if (g == 0) {
selectorClave.removeItem(p);
guardarClave(p);
}
} else {
guardarClave(p);
}
}//GEN-LAST:event_btnGuardarClaveActionPerformed | 2 |
public void init ()
{
if (initted)
return;
try {
getContentPane ().add ("Center",
new DisplayPanel ());
initted = true;
} catch (IOException e) {
e.printStackTrace ();
throw new RuntimeException (e.getMessage ());
}
} | 2 |
public static void applyGear(Background v, Actor actor) {
int BQ = v.standing ;
for (Service gear : v.gear) {
if (gear instanceof DeviceType) {
actor.gear.equipDevice(Item.withQuality(gear, BQ + Rand.index(3))) ;
}
else if (gear instanceof OutfitType) {
actor.gear.equipOutfit(Item.withQuality(gear, BQ + Rand.index(3))) ;
}
else actor.gear.addItem(Item.withAmount(gear, 1 + Rand.index(3))) ;
}
if (actor.gear.credits() == 0) {
actor.gear.incCredits((50 + Rand.index(100)) * BQ / 2f) ;
}
actor.gear.boostShields(actor.gear.maxShields() / 2f, true) ;
} | 4 |
public int[] getLongestCommonSequence(int[] x, int[] y) {
int[][] c = new int[x.length + 1][y.length + 1];
// start from c[1][1], since row 0 and column 0 should all be 0
// if either one string is 0, then LCS is also 0
for (int i = 1; i <= x.length; i++) {
for (int j = 1; j <= y.length; j++) {
// three possibilities
if (x[i - 1] == y[j - 1])// current charAt comparison
{
c[i][j] = c[i - 1][j - 1] + 1;
} else if (c[i - 1][j] >= c[i][j - 1]) {
c[i][j] = c[i - 1][j];
} else {
c[i][j] = c[i][j - 1];
}
}
}
print(c);
return DisplayLCS(c, x, y);
} | 4 |
boolean checkValidCode(String code, int maxDigit){
try {
for (char c : code.toCharArray()){
check(c >= '0');
check(c <= '0'+maxDigit);
};
} catch (Exception e) {
return false;
}
return true;
} | 2 |
public static int getCount() {
return addresses.size();
} | 0 |
public static String formatOutput(String str)
{
//处理边界的分隔符
int index = str.length()-1;
int start = str.charAt(0) == split_char ? 1 : 0;
int length = str.charAt(index) == split_char ? index : index + 1;
if(start == 0 || length == index)
{
str = str.substring(start, length);
}
//格式化输出
if(str.length()>0)
{
return "\""+str.replace(",", "\",\"")+"\"";
}
return null;
} | 5 |
public FileItemList(String workingDirectory) {
super(workingDirectory);
directory = new File(workingDirectory);
if (directory.exists() && directory.isDirectory()) {
items.addAll(Arrays.asList(directory.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return (name.endsWith(".jpg") || name.endsWith(".jpeg"));
}
})));
}
} | 3 |
public String toString() {
return super.toString();
} | 0 |
public StringDataType createStringDataType() {
return new StringDataType();
} | 0 |
public static void greyWriteImage(double[][] data){
BufferedImage image = new BufferedImage(data.length, data[0].length, BufferedImage.TYPE_INT_RGB);
for(int x = 0; x < data.length; x++){
for(int y = 0; y < data[0].length; y++){
if(data[x][y] > 1){
data[x][y] = 1;
}
Color color = new Color((float)data[x][y], (float)data[x][y], (float)data[x][y]);
image.setRGB(x, y, color.getRGB());
}
try{
File file = new File("noise.png");
file.createNewFile();
ImageIO.write(image, "PNG", file);
}catch(Exception e){
e.printStackTrace();
}
}
} | 4 |
public static ArrayList<String> parseInputFile(String filename) {
ArrayList<String> commands = new ArrayList<String>();
File input = new File(filename);
try {
Scanner scanner = new Scanner(input);
while (scanner.hasNextLine()) {
commands.add(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return commands;
} | 2 |
private void loadDatabase() {
// Declare a few local variables for later use
ClassLoader currentClassLoader = null;
Field cacheField = null;
boolean cacheValue = true;
try {
// Store the current ClassLoader, so it can be reverted later
currentClassLoader = Thread.currentThread().getContextClassLoader();
// Set the ClassLoader to Plugin ClassLoader
Thread.currentThread().setContextClassLoader(this.classLoader);
// Get a reference to the private static "defaultUseCaches"-field in
// URLConnection
cacheField = URLConnection.class.getDeclaredField("defaultUseCaches");
// Make it accessible, store the default value and set it to false
cacheField.setAccessible(true);
cacheValue = cacheField.getBoolean(null);
cacheField.setBoolean(null, false);
// Setup Ebean based on the configuration
this.ebeanServer = EbeanServerFactory.create(this.serverConfig);
}
catch (Exception ex) {
throw new RuntimeException(
"Failed to create a new instance of the EbeanServer",
ex);
}
finally {
// Revert the ClassLoader back to its original value
if (currentClassLoader != null) {
Thread.currentThread().setContextClassLoader(currentClassLoader);
}
// Revert the "defaultUseCaches"-field in URLConnection back to its
// original value
try {
if (cacheField != null) {
cacheField.setBoolean(null, cacheValue);
}
}
catch (Exception e) {
System.out.println("Failed to revert the \"defaultUseCaches\"-field back to its original value, URLConnection-caching remains disabled.");
}
}
} | 4 |
public void print(){
ListNode<T> currentNode=head;
while(currentNode!=null){
System.out.println(currentNode.getData());
currentNode=currentNode.getNext();
}
} | 1 |
private static String resolveEnvVariables(String path) {
for (String i : env.keySet()) {
String p = i.replace("(", "\\(").replace(")", "\\)");
String r = env.get(i).replace("\\", "\\\\");
path = Pattern.compile("%"+p+"%", Pattern.CASE_INSENSITIVE).matcher(path).replaceAll(r);
}
return path;
} | 1 |
public synchronized List<Product> addPreferencesClient(Client client,
Product product) {
if (client != null && product!=null && listOfAllPreferences.get(client) != null) {//if there is already a list
List<Product> listAux = listOfAllPreferences.get(client);
listAux.add(product);
listOfAllPreferences.put(client, listAux);
logger.info("Client preferences: " + client.getName()
+ " added or updated successfully");
return listOfAllPreferences.get(client);
}else if(client != null && product!=null && listOfAllPreferences.get(client) == null){//if the list does not exist
List<Product> listAux = new LinkedList<Product>();
listAux.add(product);
listOfAllPreferences.put(client, listAux);
return listOfAllPreferences.get(client);
}
return null;
} | 6 |
public void addVariablesWithLambdaProductions(Grammar grammar, Set lambdaSet) {
while (areMoreVariablesWithLambdaProductions(grammar, lambdaSet)) {
String variable = getNewVariableWithLambdaProduction(grammar,
lambdaSet);
addVariableToLambdaSet(variable, lambdaSet);
}
} | 1 |
BetLine(TeamType type, int moneyLine, String strTot) {
if (type.equals(TeamType.HOME)) {
home = getDecC(moneyLine);
away = getAnotherC(home);
} else {
away = getDecC(moneyLine);
home = getAnotherC(away);
}
Pattern p = Pattern.compile("([0-9]\\.*[0-9]*)([ou]*)([0-9]*)");
Matcher m = p.matcher(strTot);
if (!m.find()) {
System.out.println(strTot);
throw new Error();
}
total = Double.parseDouble(m.group(1));
over = under = 1.95;
if (m.group(2).length() > 0) {
if (m.group(2).equals("o")) {
over = getDecC(-(100 + Integer.parseInt(m.group(3))));
under = getAnotherC(over);
} else {
under = getDecC(-(100 + Integer.parseInt(m.group(3))));
over = getAnotherC(under);
}
}
} | 4 |
public List<String> DBExpiredCharNameSearch(Set<String> skipNames)
{
DBConnection D=null;
String buf=null;
final List<String> expiredPlayers = new ArrayList<String>();
final long now=System.currentTimeMillis();
try
{
D=DB.DBFetch();
final ResultSet R=D.query("SELECT * FROM CMCHAR");
if(R!=null) while(R.next())
{
final String username=DB.getRes(R,"CMUSERID");
if((skipNames!=null)&&(skipNames.contains(username)))
continue;
buf=DBConnections.getRes(R,"CMPFIL");
final String secGrps=CMLib.xml().restoreAngleBrackets(CMLib.xml().returnXMLValue(buf,"SECGRPS"));
final SecGroup g=CMSecurity.instance().createGroup("", CMParms.parseSemicolons(secGrps,true));
if(g.contains(SecFlag.NOEXPIRE, false))
continue;
long expiration;
if(CMLib.xml().returnXMLValue(buf,"ACCTEXP").length()>0)
expiration=CMath.s_long(CMLib.xml().returnXMLValue(buf,"ACCTEXP"));
else
{
final Calendar C=Calendar.getInstance();
C.add(Calendar.DATE,CMProps.getIntVar(CMProps.Int.TRIALDAYS));
expiration=C.getTimeInMillis();
}
if(now>=expiration)
expiredPlayers.add(username);
}
}
catch(final Exception sqle)
{
Log.errOut("MOB",sqle);
}
finally
{
DB.DBDone(D);
}
return expiredPlayers;
} | 8 |
public void updateElementPosition(Element element, Position newPosition) {
if (element == null || newPosition == null)
throw new IllegalArgumentException("The given parameters are invalid!");
getSquare(getElementPosition(element)).removeElement(element);
getSquare(newPosition).addElement(element);
} | 2 |
@Override
public void affectPhyStats(Physical affected, PhyStats affectableStats)
{
super.affectPhyStats(affected,affectableStats);
if(affected!=null)
{
if(affected instanceof Room)
{
final Room R=(Room)affected;
for(int i=0;i<R.numItems();i++)
{
final Item I=R.getItem(i);
if(I!=null)
I.setExpirationDate(0);
}
}
else
if(affected instanceof Container)
{
if(((Container)affected).owner() instanceof Room)
{
((Container)affected).setExpirationDate(0);
final List<Item> V=((Container)affected).getDeepContents();
for(int v=0;v<V.size();v++)
V.get(v).setExpirationDate(0);
}
}
else
if(affected instanceof Item)
((Item)affected).setExpirationDate(0);
}
} | 8 |
private JMenuBar makeMenus() {
ActionListener listener = new ActionListener() {
// An object that will serve as listener for menu items.
public void actionPerformed(ActionEvent evt) {
// This will be called when the user makes a selection
// from the File menu. This routine just checks
// which command was selected and calls another
// routine to carry out the command.
String cmd = evt.getActionCommand();
if (cmd.equals("New"))
doNew();
else if (cmd.equals("Open..."))
doOpen();
else if (cmd.equals("Save..."))
doSave();
else if (cmd.equals("Quit"))
doQuit();
}
};
JMenu fileMenu = new JMenu("File");
JMenuItem newCmd = new JMenuItem("New");
newCmd.addActionListener(listener);
fileMenu.add(newCmd);
JMenuItem openCmd = new JMenuItem("Open...");
openCmd.addActionListener(listener);
fileMenu.add(openCmd);
JMenuItem saveCmd = new JMenuItem("Save...");
saveCmd.addActionListener(listener);
fileMenu.add(saveCmd);
fileMenu.addSeparator();
JMenuItem quitCmd = new JMenuItem("Quit");
quitCmd.addActionListener(listener);
fileMenu.add(quitCmd);
JMenuBar bar = new JMenuBar();
bar.add(fileMenu);
return bar;
} // end makeMenus() | 4 |
public void quantizeImage(ImageBean img)
{
int[][] newPix = new int[img.getWidth()][img.getHeight()];
for (int x = img.getWidth(); x-- > 0; )
for (int y = img.getHeight(); y-- > 0; )
newPix[x][y] = img.getPixels()[(y * img.getWidth() + x)];
int[] newColMap = Quantize.quantizeImage(newPix, 254);
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
img.pixels[(y * img.getWidth() + x)] = newColMap[newPix[x][y]];
}
}
for (int i = 0; i < img.pixels.length; i++) {
int[] rgb = unpack(img.pixels[i]);
if ((rgb[0] == 255) && (rgb[1] == 0) && (rgb[2] == 255))
img.pixels[i] = 0;
}
} | 8 |
public boolean canPlayCard(Card card) {
return Game.linkedGet().isCardPlayable(card) && (turnPlays < 1 || card.value == Game.linkedGet().getPlayPile().peek().value);
} | 2 |
public ArrayList<ITask> CSVLoad(String fileName) throws IOException {
File csvFile = new File(fileName);
if (!csvFile.exists())
throw new FileNotFoundException("Le fichier n'existe pas");
if (csvFile.isDirectory())
throw new FileNotFoundException("Le chemin designe un repertoire et non un fichier");
if (!csvFile.getAbsolutePath().endsWith(".csv"))
throw new FileNotFoundException("Le fichier n'est pas du type CSV (Comma Separated Value)");
StringTokenizer lineParser;
BufferedReader reader = new BufferedReader(new FileReader(csvFile));
ArrayList<ArrayList> dataTable = new ArrayList<ArrayList>();
ArrayList<String> dataRow;
String line = null;
String value = null;
while ((line = reader.readLine()) != null) {
dataRow = new ArrayList<String>();
lineParser = new StringTokenizer(line, ";");
while (lineParser.hasMoreElements()) {
value = (String) lineParser.nextElement();
dataRow.add(value);
}
dataTable.add(dataRow);
}
//createTasks(dataTable);
return tasks;
} | 5 |
public String toString() {
if (instance == null)
return "new " + type;
else
return instance.toString();
} | 1 |
@POST
@Path("/create/multiple/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response createNewMultipleAccount(Account[] accounts){
Response.ResponseBuilder builder = null;
try {
for(Account account : accounts){
registry.register(account);
}
builder = Response.ok();
}catch(Exception e){
Map<String, String> responseObj = new HashMap<String, String>();
responseObj.put("error", e.getMessage());
builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
}
return builder.build();
} | 2 |
public void insererClef(E clef, double priorite) throws Exercice1Exception {
if (clef == null) {
throw new Exercice1Exception("La clef ne peut être null");
}
if (rechercheClef(clef, SEARCH_TREE) != NIL) { // SEARCH_LIST marche nickel
throw new Exercice1Exception("La clef existe déjà");
}
if (recherchePriorite(priorite, SEARCH_TREE) != NIL) { // SEARCH_LIST marche nickel
throw new Exercice1Exception("La priorite existe déjà");
}
NoeudArbre<E> noeud = new NoeudArbre(clef, priorite);
listNoeudArbres.add(noeud);
//On insère d'abord dans l'AB dans tenir compte de la priorité
insererNoeudAB(noeud);
//On remonte ensuite le noeud en fonction de la priorité
remonterNoeud(noeud);
} | 3 |
@EventHandler
public void punchWool(PlayerInteractEvent event) {
CTFTeam team = null;
TeamPlayer player = null;
for (CTFTeam t: Teams){
for (TeamPlayer p: t.getTeamPlayers()){
if (p.getPlayer().equals(event.getPlayer())){
player = p;
team = t;
}
}
}
if (player == null){
return;
}
if (event.getAction() == Action.LEFT_CLICK_BLOCK){
if (event.getClickedBlock().getType() == Material.WOOL) {
if (event.getClickedBlock().getData() != team.getColor().getWoolData()){
event.getClickedBlock().breakNaturally();
}
}
}
event.setCancelled(true);
} | 7 |
public boolean isOutsideBounds(Bullet b){
if( b.pointY > 640 || b.pointX > 480 || b.pointY < 0 ){
return true;
}
else return false;
} | 3 |
private DataContainer getFromAllTablesInDB() {
DataContainer allData = new DataContainer();
Set<String> tableNames = balancer.getAllAvailableTableNames();
Map<String, TableDescription> tableDescriptions = balancer.getTablesInDataBaseDescription();
for (String tableName : tableNames) {
try {
Map<String, Row> allRowsInCurrentTable = balancer.getAll(tableName);
TableDescription tableDescription = tableDescriptions.get(tableName);
allData.put(tableDescription, allRowsInCurrentTable);
} catch (DataBaseTableException e) {
log(loggers, "unable to get data from table: " + tableName);
}
}
return allData;
} | 2 |
public MainWindow()
{
super("简易词法&语法分析器");
this.setBounds(0, 0, 500, 260);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
this.setLocationRelativeTo(null);
//初始化控件
buttons.add(btnAnalysisDefault);
buttons.add(btnAnalysisCustom);
buttons.add(btnShowSysLable);
buttons.add(btnShowSource);
// buttons.add(btnShowLable);
buttons.add(btnShowPre);
buttons.add(btnShowBinary);
buttons.add(btnGrammaticalAnalysis);
// buttons.add(btnShowGAResult);
// buttons.add(btnHelp);
label.setBounds(100, 10, 260, 30);
label.setText("Easy Lexical Analysis Tool");
label.setFont(new java.awt.Font("MS Song", Font.BOLD, 20));
this.getContentPane().add(label);
labelVersion.setBounds(360, 18, 50, 20);
labelVersion.setText("v2.0");
labelVersion.setFont(new java.awt.Font("MS Song", Font.BOLD, 15));
// labelVersion.setBackground(Color.RED);
this.getContentPane().add(labelVersion);
labelAuthor.setBounds(350, 30, 150, 30);
labelAuthor.setText("2013.5 by Bottle");
labelAuthor.setFont(new java.awt.Font("MS Song", Font.ITALIC, 10));
this.getContentPane().add(labelAuthor);
btnAnalysisDefault.setBounds(50, 60, 180, 30);
this.getContentPane().add(btnAnalysisDefault);
btnAnalysisCustom.setBounds(250, 60, 180, 30);
this.getContentPane().add(btnAnalysisCustom);
btnShowSysLable.setBounds(50, 100, 180, 30);
this.getContentPane().add(btnShowSysLable);
btnShowSource.setBounds(250, 100, 180, 30);
this.getContentPane().add(btnShowSource);
// btnShowLable.setBounds(50, 100, 180, 30);
// this.getContentPane().add(btnShowLable);
btnShowPre.setBounds(50, 140, 180, 30);
this.getContentPane().add(btnShowPre);
btnShowBinary.setBounds(250, 140, 180, 30);
this.getContentPane().add(btnShowBinary);
btnGrammaticalAnalysis.setBounds(50, 180, 180, 30);
this.getContentPane().add(btnGrammaticalAnalysis);
// btnShowGAResult.setBounds(250, 180, 180, 30);
// this.getContentPane().add(btnShowGAResult);
// btnHelp.setBounds(250, 140, 180, 30);
// this.getContentPane().add(btnHelp);
//设置其他按钮不可点击
for (int i = 3; i < buttons.size(); i++)
{
buttons.get(i).setEnabled(false);
}
//设置监听
for (int i = 0; i < buttons.size(); i++)
{
buttons.get(i).addActionListener(new MyListener(i));
}
} | 2 |
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
//GEN-FIRST:event_jButton1ActionPerformed
list = new BreakfastDao();
} catch (SAXException ex) {
Logger.getLogger(addItemToBreakfastMenu.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(addItemToBreakfastMenu.class.getName()).log(Level.SEVERE, null, ex);
}
Name = getItemName();
Description = getItemDescriptionName();
Price = getItemPrice();
PictureName = getPictureName();
if(Name.equals("") || Description.equals("") || Price.equals("") || PictureName.equals("")){
JOptionPane.showMessageDialog(this,
"YOU MUST ENTER ALL INFORMATION",
"CHECK VALUES AGAIN",
JOptionPane.ERROR_MESSAGE);
}
else{
list.addBreakfast(Name,Description, 1,Price,PictureName);
System.out.println(getItemName()+' '+getItemDescriptionName()+" " + getItemPrice()+" "+getPictureName());
JOptionPane.showMessageDialog(this,
"YOUR ITEM HAS BEEN ADDED!!!",
"CONFIRMATION DIALOG",
JOptionPane.WARNING_MESSAGE);
itemNameValue.setText("");
itemDescriptionValue.setText("");
itemPriceValue.setText("0");
itemPictureValue.setText("");
adminLogInDialog.breakfastMenu.removeAll();
try {
adminLogInDialog.breakfastMenu.setUpComponents();//adminEditAppetizerMenu();
} catch (SAXException ex) {
Logger.getLogger(addItemToBreakfastMenu.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(addItemToBreakfastMenu.class.getName()).log(Level.SEVERE, null, ex);
}
adminLogInDialog.breakfastEditPane.revalidate();
}
}//GEN-LAST:event_jButton1ActionPerformed | 8 |
private void insertSplayTree(SplayTreeNode currentNode, SplayTreeNode newNode) {
if (currentNode == null) {
this.root = newNode;
} else {
if (newNode.value.compareTo(currentNode.value) < 0) {
if (currentNode.left == null) {
currentNode.left = newNode;
newNode.parent = currentNode;
} else {
insertSplayTree(currentNode.left, newNode);
}
} else if (newNode.value.compareTo(currentNode.value) > 0) {
if (currentNode.right == null) {
currentNode.right = newNode;
newNode.parent = currentNode;
} else {
insertSplayTree(currentNode.right, newNode);
}
} else {
System.out.println("\nValue " + newNode.value + " already exists. Ignoring...");
}
}
} | 5 |
public List<Integer> genNormal(int len, int range) {
List<Integer> list = new ArrayList<>();
for (int idx = 0; idx < len; ++idx)
list.add(RAND_.nextInt(range));
return list;
} | 1 |
public void completeSchedule(Match[] schedule) {
jPanel1.setLayout(new BoxLayout(jPanel1, BoxLayout.Y_AXIS));
jPanel1.add(Box.createRigidArea(new Dimension(0, 6)));
for (Match match : schedule) {
if (!match.searchFor(2771)) {
continue;
}
MatchBatterySetup mbs = new MatchBatterySetup();
mbs.setLabels(match);
jPanel1.add(mbs);
jPanel1.add(Box.createRigidArea(new Dimension(0, 6)));
rows.add(mbs);
}
this.schedule = schedule;
} | 2 |
private static void handleDecipherment() {
BigInteger exponent=null, module=null, cypher=null;
try {
exponent = new BigInteger(DeciphermentFrame.getInstance().tfExponent.getText());
if(exponent==null || exponent.compareTo(new BigInteger("0"))<=0) throw new IllegalStateException();
} catch(Exception e) {
JOptionPane.showMessageDialog(DeciphermentFrame.getInstance(), "Exposant incorrect!","Erreur!",JOptionPane.ERROR_MESSAGE);
return;
}
try {
module = new BigInteger(DeciphermentFrame.getInstance().tfModule.getText());
if(module==null || module.compareTo(new BigInteger("0"))<=0) throw new IllegalStateException();
} catch(Exception e) {
JOptionPane.showMessageDialog(DeciphermentFrame.getInstance(), "Module incorrect!","Erreur!",JOptionPane.ERROR_MESSAGE);
return;
}
try {
cypher = new BigInteger(DeciphermentFrame.getInstance().textAreaCypher.getText());
if(cypher==null || cypher.compareTo(new BigInteger("0"))<=0) throw new IllegalStateException();
} catch(Exception e) {
JOptionPane.showMessageDialog(DeciphermentFrame.getInstance(), "Cypher incorrect!","Erreur!",JOptionPane.ERROR_MESSAGE);
return;
}
String message = RSA.dechiffrementRSA(cypher, exponent, module);
DeciphermentFrame.getInstance().textAreaMessage.setText(message);
} | 9 |
@Override
public void actionPerformed(ActionEvent e) {
//System.out.println("ToggleExpansionAction");
OutlinerCellRendererImpl textArea = null;
boolean isIconFocused = true;
Component c = (Component) e.getSource();
if (c instanceof OutlineButton) {
textArea = ((OutlineButton) c).renderer;
} else if (c instanceof OutlineLineNumber) {
textArea = ((OutlineLineNumber) c).renderer;
} else if (c instanceof OutlineCommentIndicator) {
textArea = ((OutlineCommentIndicator) c).renderer;
} else if (c instanceof OutlinerCellRendererImpl) {
textArea = (OutlinerCellRendererImpl) c;
isIconFocused = false;
}
// Shorthand
Node node = textArea.node;
JoeTree tree = node.getTree();
OutlineLayoutManager layout = tree.getDocument().panel.layout;
//System.out.println(e.getModifiers());
switch (e.getModifiers()) {
case 1:
if (isIconFocused) {
toggleExpansion(node, tree, layout, true);
} else {
toggleExpansionText(node, tree, layout, true);
}
break;
default:
if (isIconFocused) {
toggleExpansion(node, tree, layout, false);
} else {
toggleExpansionText(node, tree, layout, false);
}
break;
}
} | 7 |
public static void ex3() throws NumberFormatException, IOException{
System.out.print("Valor del array => ");
int valor=Integer.parseInt(stdin.readLine());
double [] array=new double[valor];
for(int i=0; i<valor; i++){
array[i]=Math.random()*100;
System.out.print(array[i]+"\t");
}
System.out.print("\nColumna del array que vols borrar => ");
int col=Integer.parseInt(stdin.readLine());
for(int i=0; i<valor; i++){
if(i==col-1){}
else System.out.print(array[i]+"\t");
}
System.out.println("");
} | 3 |
public int[] plusOne(int[] digits) {
int i = digits.length;
if(i==0){
return digits;
}
boolean inc =true;
for (;i>0;i--){
if (digits[i-1]==9&&inc){
digits[i-1] = 0;
}
else if (inc){
digits[i-1]++;
inc = false;
return digits;
}
else {
return digits;
}
}
if(i==0&&inc){
int []result = new int[digits.length+1];
result[0] = 1;
for (int j=0;j<digits.length;j++){
result[j+1] = digits[j];
}
return result;
}
return digits;
} | 8 |
public Object getDefault() {
return this.def;
} | 0 |
public void move(){
if (x<0 || x > 1450 || y < 0 || y >1000) {
this.switchDirection();
}
if(direction=='u'){y-=5;}
else if(direction=='d'){y+=5;}
else if(direction=='l'){x-=5;}
else if(direction=='r'){x+=5;}
} | 8 |
private void printStringsFromSetHelper(char[] n, int k, StringBuilder s){
if(s.length() == k){
System.out.println(s.toString());
return;
}
for(int i=0; i<n.length; i++){
StringBuilder builder = new StringBuilder(s);
builder.append(n[i]);
printStringsFromSetHelper(n, k, builder);
}
} | 2 |
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
sc.nextLine();
System.out.println("Lumberjacks:");
while(T>0)
{
T--;
String line = sc.nextLine();
StringTokenizer tokens = new StringTokenizer(line," ");
boolean isIncreasingOrder = true;
boolean isDecreasingOrder = true;
int previousValue = 0;
int present = 0;
while(tokens.hasMoreTokens())
{
String valString = tokens.nextToken();
int val = Integer.valueOf(valString);
if(present==0)
{
previousValue = val;
present++;
}
else
{
if(isIncreasingOrder)
{
if(previousValue>=val)
isIncreasingOrder = false;
}
if(isDecreasingOrder)
{
if(previousValue<=val)
isDecreasingOrder = false;
}
}
previousValue= val;
}
if(isIncreasingOrder || isDecreasingOrder)
System.out.println("Ordered");
else
System.out.println("Unordered");
}
} | 9 |
private static String[] _processAnnotation(String s, StreamTokenizer st)
throws IOException {
s = s.trim();
List<String> tokens = new ArrayList<String>();
Matcher annotationNameMatcher = _ANNOTATION_NAME_REGEXP.matcher(s);
Matcher annotationParametersMatcher =
_ANNOTATION_PARAMETERS_REGEXP.matcher(s);
if (annotationNameMatcher.matches()) {
String annotationName = annotationNameMatcher.group();
tokens.add(annotationName.replace("@", ""));
}
else if (annotationParametersMatcher.matches()) {
if (!s.trim().endsWith(")")) {
while (st.nextToken() != StreamTokenizer.TT_EOF) {
if (st.ttype == StreamTokenizer.TT_WORD) {
s += st.sval;
if (s.trim().endsWith(")")) {
break;
}
}
}
}
annotationParametersMatcher =
_ANNOTATION_PARAMETERS_REGEXP.matcher(s);
if (annotationParametersMatcher.matches()) {
String annotationName =
annotationParametersMatcher.group(1);
String annotationParameters =
annotationParametersMatcher.group(2);
tokens.add(annotationName.replace("@", ""));
tokens = _processAnnotationParameters(
annotationParameters,tokens);
}
}
return tokens.toArray(new String[tokens.size()]);
} | 7 |
public Game(final int typeFirst, String firstName, final int typeSecond, String secondName) {
// TODO: Use enum!!!!
if ((typeFirst >= PLAYER_TYPE_AMOUNT) || (typeSecond >= PLAYER_TYPE_AMOUNT)) {
// return
} else {
pack = new Pack();
switch (typeFirst) {
case 0:
first = new AI(firstName, pack.getTrump());
break;
case 1:
first = new Human(firstName, pack.getTrump());
break;
}
switch (typeSecond) {
case 0:
second = new AI(secondName, pack.getTrump());
break;
case 1:
second = new Human(secondName, pack.getTrump());
break;
}
currentPlayer = first;
opponentPlayer = second;
play();
}
} | 6 |
public boolean containsValue( Object val ) {
byte[] states = _states;
V[] vals = _values;
// special case null values so that we don't have to
// perform null checks before every call to equals()
if ( null == val ) {
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL && null == vals[i] ) {
return true;
}
}
} else {
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL &&
( val == vals[i] || val.equals( vals[i] ) ) ) {
return true;
}
}
} // end of else
return false;
} | 8 |
@Override
public void setSex(String sex) {
super.setSex(sex);
} | 0 |
@Override
public void drawImage(Function f, MyPanel image, double x, double y) {
Graphics g = image.getGraphics();
Graphics2D g2 = (Graphics2D) g;
g2.translate(150, 150);
g2.scale(x, y);
for (Line l : lines) {
Complex tmp1 = f.evaluate(l.c1);
int p = 10;
for (int t = 0; t <= p; t++) {
double re = ((p - t) * l.c1.getRe() / p + t * l.c2.getRe() / p);
double im = ((p - t) * l.c1.getIm() / p + t * l.c2.getIm() / p);
Complex tmp2 = f.evaluate(new Complex(re, im));
Line tmpLine = new Line(tmp1, tmp2);
tmpLine.paint(g2);
tmp1 = tmp2;
}
}
} | 2 |
public Integer getLimit(Object[] args) {
if (limitIndex == -1) {
return limit;
}
Object arg = args[limitIndex];
if (arg == null) {
return null;
} else if (arg instanceof Integer) {
return (Integer) arg;
} else {
return null;
}
} | 3 |
public Object next() {
int pos = rand.nextInt(pool.size());
Iterator i = pool.iterator();
while (pos > 0)
i.next();
return (String) i.next();
} | 1 |
@Override
public boolean okMessage(Environmental host, CMMsg msg)
{
if(((msg.sourceMinor()==CMMsg.TYP_QUIT)
||(msg.sourceMinor()==CMMsg.TYP_SHUTDOWN)
||((msg.targetMinor()==CMMsg.TYP_EXPIRE)&&(msg.target()==oldRoom))
||(msg.sourceMinor()==CMMsg.TYP_ROOMRESET))
&&(msg.source().location()!=null)
&&(msg.source().location().getGridParent()==affected))
{
if(oldRoom!=null)
oldRoom.bringMobHere(msg.source(),false);
if(msg.source()==invoker)
unInvoke();
}
return super.okMessage(host,msg);
} | 9 |
public void remove(String[] command) {
int id = Integer.parseInt(command[0]);
for (int i = 0; i < compuertas.getLength(); i++) {
if (compuertas.get(i).equals(id)) compuertas.remove(i);
}
for (int i = 0; i < salidas.getLength(); i++) {
if (salidas.get(i).equals(id)) salidas.remove(i);
}
for (int i = 0; i < entradas.getLength(); i++) {
if (entradas.get(i).equals(id)) entradas.remove(i);
}
} | 6 |
public void feed(Object obj) {
synchronized(BalancedPoolStageDriver.this) {
if ( !isInState(RUNNING, STOP_REQUESTED)
|| workers.size() > 1
|| (workers.size() == 1 && workers.peek().runnability == Runnability.RUNNABLE)) {
try {
if (log.isDebugEnabled()) log.debug(stage + ": Queueing object: " + obj);
this.queue.put(obj);
} catch (InterruptedException e) {
throw new Error("Assertion failure: thread interrupted while attempting to enqueue data object.", e);
}
return; //short circuit out of here
}
}
try {
if (log.isDebugEnabled()) log.debug(stage + ":Processing object directly: " + obj);
BalancedPoolStageDriver.this.process(obj);
} catch (StageException e) {
recordProcessingException(obj, e);
if (faultTolerance == FaultTolerance.NONE) throw fatalError(e);
}
} | 9 |
public void diceRolled(int roll) {
int ainum = _ais.size();
int rest = _players.size() - ainum;
synchronized(_players) {
for (Hex h : _hexes) {
if (h.getRollNum() == roll) {
for (Vertex vertex : h.getVertices()) {
int p = vertex.getOwner();
if (p != -1) {
_players.get(p).addCard(h.getResource());
if (vertex.getObject() == 2) { //if city
_players.get(p).addCard(h.getResource());
if(p >= rest) {
_server.getClientPool().broadcast("10/9AI player " + (p-rest + 1) + " received two " + h.getResource(),null);
}
} else if(p >= rest){
_server.getClientPool().broadcast("10/9AI player " + (p-rest + 1) + " received one " + h.getResource(),null);
}
}
}
}
}
}
for (AIPlayer ai : _ais) ai.registerDieRoll(roll);
} | 8 |
private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length)
return false;
for (int i = 0; i < a.length; i++)
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i]))
return false;
return true;
} | 6 |
public void generate() {
MapArray = new Tile[size][size];
// System.out.println("passed ");
// assign grass
for (int j = 0; j < size; j++) {
for (int k = 0; k < size; k++) {
MapArray[j][k] = new Tile();
}
}
// System.out.println("passed 1 ");
int TreasureX = (int) (Math.random() * size);
int TreasureY = (int) (Math.random() * size);
System.out
.println(TreasureX + "," + TreasureY + " and size is:" + size);
MapArray[TreasureY][TreasureX].setType('T');
System.out.println("passed 2");
double WaterTiles1 = (size * size) / 4;
double WaterTiles2 = (size * size) * 0.35;
int WaterTiles = (int) (WaterTiles1 + (Math.random() * (WaterTiles2 - WaterTiles1)));
//int WaterTiles = WaterTiles;
System.out.println("WaterTiles= " + WaterTiles);
int count = 0;
do {
int xwater = (int) (Math.random() * size);
int ywater = (int) (Math.random() * size);
if (MapArray[ywater][xwater].getType() != 'T'
&& MapArray[ywater][xwater].getType() != 'W') {
MapArray[ywater][xwater].setType('W');
count++;
}
} while (count <= WaterTiles);
// System.out.println(TreasureX);
// System.out.println(TreasureY);
// for (int i = 0; i < NumOfPlayers; i++) {
// players.get(i).setMap(new Map(MapTemplate.clone()));
// maps.add(players.get(i).getMap());
// }
// Din kolla trid titlaq thawn taht
System.out.println("passed final");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(MapArray[i][j].getType() + " ");
}
System.out.println("");
}
} | 7 |
@Override
public boolean createWhen() {
return stage.count%15==0 && (6<stage.second() && stage.second()<8);
} | 2 |
public static double atanh(double a) {
boolean negative = false;
if (a < 0) {
negative = true;
a = -a;
}
double absAtanh;
if (a > 0.15) {
absAtanh = 0.5 * FastMath.log((1 + a) / (1 - a));
} else {
final double a2 = a * a;
if (a > 0.087) {
absAtanh = a
* (1 + a2
* (F_1_3 + a2
* (F_1_5 + a2
* (F_1_7 + a2
* (F_1_9 + a2
* (F_1_11 + a2
* (F_1_13 + a2
* (F_1_15 + a2
* F_1_17))))))));
} else if (a > 0.031) {
absAtanh = a
* (1 + a2
* (F_1_3 + a2
* (F_1_5 + a2
* (F_1_7 + a2
* (F_1_9 + a2
* (F_1_11 + a2
* F_1_13))))));
} else if (a > 0.003) {
absAtanh = a
* (1 + a2
* (F_1_3 + a2
* (F_1_5 + a2 * (F_1_7 + a2 * F_1_9))));
} else {
absAtanh = a * (1 + a2 * (F_1_3 + a2 * F_1_5));
}
}
return negative ? -absAtanh : absAtanh;
} | 6 |
public static int[] getPlayersCountInPositions(int range, L2Character npc, boolean invisible)
{
int frontCount = 0;
int backCount = 0;
int sideCount = 0;
for (L2PcInstance player : npc.getKnownList().getKnownType(L2PcInstance.class))
{
if (player.isDead())
continue;
if (!invisible && player.getAppearance().getInvisible())
continue;
if (!Util.checkIfInRange(range, npc, player, true))
continue;
if (player.isInFrontOf(npc))
frontCount++;
else if (player.isBehind(npc))
backCount++;
else
sideCount++;
}
int[] array =
{
frontCount,
backCount,
sideCount
};
return array;
} | 7 |
public double rate(EnhancedMove move) {
int dropHeight = move.getBoard().dropHeight(move.getPiece(), move.getX());
Point[] pos = move.getPiece().getBody();
Board board = move.getBoard();
int neighbors = 0;
for(int i = 0; i < 4; i ++){
int tarX = pos[i].x + move.getX();
int tarY = pos[1].y + dropHeight;
for(int x = tarX-1; x < tarX+2; x++){
for(int y = tarY-1; y < tarY+2; y++){
if(board.canPlace(move.piece, x, y))
neighbors += board.getGrid(x, y) ? 1 : 0;
else
neighbors ++;
}
}
}
return weight * neighbors;
} | 5 |
static public void main(String args[]) {
double x, y;
OSGB osgb = new OSGB();
if (args.length < 2) {
/*
* Caister Water Tower
*/
x = 651409.903;
y = 313177.271;
} else {
Double d;
d = new Double(args[0]);
x = d.doubleValue();
d = new Double(args[1]);
y = d.doubleValue();
}
DPoint p = osgb.GridToLongitudeAndLatitude(x, y);
double phi, lambda;
lambda = (180.0 / Math.PI) * p.getX();
phi = (180.0 / Math.PI) * p.getY();
System.out.println("Grid coordinates (" + x + ", " + y
+ ") map to longitude " + lambda + ", latitude " + phi);
double ls = Math.abs(lambda);
double ps = Math.abs(phi);
int ld, lm, pd, pm;
ld = (int) ls;
ls = 60.0 * (ls - ld);
lm = (int) ls;
ls = 60.0 * (ls - lm);
pd = (int) ps;
ps = 60.0 * (ps - pd);
pm = (int) ps;
ps = 60.0 * (ps - pm);
System.out.print((lambda < 0.0) ? "West " : "East ");
System.out.println(ld + " " + lm + " " + ls);
System.out.print((phi < 0.0) ? "South " : "North ");
System.out.println(pd + " " + pm + " " + ps);
p = osgb.LatitudeAndLongitudeToGrid(p);
System.out.println("Reverse transform:");
System.out.println(" Easting = " + p.getX());
System.out.println(" Northing = " + p.getY());
} | 3 |
public void fish(Item rod)
{
switch(rod.type)
{
case OLD_ROD:
enemy[0]=Mechanics.randomEncounter(Pokemon.Species.MAGIKARP,20,5,Pokemon.Species.PSYDUCK,20,10,Pokemon.Species.GOLDEEN,20,10,
Pokemon.Species.TENTACOOL,30,5,Pokemon.Species.KRABBY,10,10);
break;
case GOOD_ROD:
enemy[0]=Mechanics.randomEncounter(Pokemon.Species.MAGIKARP,20,15,Pokemon.Species.SLOWPOKE,20,10,Pokemon.Species.SEAKING,20,24,
Pokemon.Species.TENTACOOL,30,15,Pokemon.Species.POLIWAG,10,18);
break;
case SUPER_ROD:
enemy[0]=Mechanics.randomEncounter(Pokemon.Species.SLOWPOKE,20,20,Pokemon.Species.HORSEA,20,20,Pokemon.Species.SEEL,20,15,
Pokemon.Species.MAGIKARP,30,19,Pokemon.Species.STARYU,10,30);
break;
}
fishing=true;
wildEncounter();
} | 3 |
public static List UniteList(List x,List y){
if ((x == null) || (x.size() == 0) || (y == null) || (y.size() == 0)) {
return new ArrayList();
}
if(x.size()>y.size()){
x.retainAll(y);
return x;
}else{
y.retainAll(x);
return y;
}
} | 5 |
public TransformsType createTransformsType() {
return new TransformsType();
} | 0 |
public static List<Oppilas> haeOppilaatByName(String etunimi, String sukunimi) {
Connection c = connect();
if (c == null) return null;
try {
List<Oppilas> oppilaat = new ArrayList<Oppilas>();
PreparedStatement ps = c.prepareStatement("SELECT * FROM oppilas " + "JOIN ryhma ON oppilas.ryhma = ryhma.ryhmaID " + "WHERE etunimi LIKE ? AND sukunimi LIKE ?");
ps.setString(1, "%" + etunimi + "%");
ps.setString(2, "%" + sukunimi + "%");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
oppilaat.add(oppilasResultSetista(rs));
}
return oppilaat;
} catch (SQLException e) {
return null;
} finally {
closeConnection(c);
}
} | 3 |
@Override
public int countZero() {
int count = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (Double.compare(matrix.get(i, j), 0.0) == 0) {
count += 1;
}
}
}
return count;
} | 3 |
private String getCorrectWorldFileName(File folder, String text)
{
int i = 1;
for(int ii = 0;ii<ILLEGAL_WORLD_NAMES.length;ii++)
{
if(text.equalsIgnoreCase(ILLEGAL_WORLD_NAMES[ii]))
text = "_"+text+"_";
}
for(int ii =0;ii<ILLEGAL_WORLD_NAME_COMPONENTS.length;ii++)
{
text = text.replace(ILLEGAL_WORLD_NAME_COMPONENTS[ii], '_');
}
if(new File(folder, text).exists())
{
while(new File(folder, text+ " ("+i+")").exists())
{
i++;
}
return text+" ("+i+")";
}
return text;
} | 5 |
private void initForClass(Map<Class<?>, S> context, S system, Class<? extends Object> systemClass) {
for (Field field : systemClass.getDeclaredFields()) {
final Inject inject = field.getAnnotation(Inject.class);
if (inject != null) {
final Object value = context.get(field.getType());
if (value != null) {
field.setAccessible(true);
try {
field.set(system, value);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} else {
if (!inject.optional())
throw new RuntimeException("Unknown objects of type " + field.getType().getName() + " requested in " + systemClass.getName() + ", but none found in context");
}
}
}
} | 7 |
private void ejecutarQuery() {
if (txtDB.getText().equals("") || txtQuery.getText().equals("")) {
lblResultado.setText("Falta rellenar alguno de los campos...");
} else {
lblResultado.setText("Enviando consulta...");
lblEstado.setText("Iniciando conexion...");
controlador.enviarDatos(txtDB.getText(), txtQuery.getText());
}
} | 2 |
private static byte encodeConnectionId(int connectionId) throws ConnectionIdOutOfRangeException {
if(connectionId != Packet.ANONYMOUS_CONNECTION_ID && (connectionId < Packet.MINIMUM_CONNECTION_ID || connectionId > Packet.MAXIMUM_CONNECTION_ID))
throw new ConnectionIdOutOfRangeException(connectionId);
return (byte) (connectionId > Byte.MAX_VALUE ? connectionId + 2*Byte.MIN_VALUE : connectionId);
} | 4 |
public void read() {
try {
if (this.in == null) {
this.in =
new InputStreamReader(new FileInputStream(this.curFile));
}
while (this.in.ready()) {
this.inputInt = this.in.read();
try {
if (this.textArea == null) {
return;
}
if (!this.running) {
this.textArea.getDocument().insertString(
this.textArea.getDocument().getLength(),
"*READ TERMINATED*", null);
return;// abort mid-read
}
if (!(this.textArea.getDocument() == null)) {
this.textArea.getDocument().insertString(
this.textArea.getDocument().getLength(),
(char) this.inputInt + "", null);
}
}
catch (final BadLocationException e) {
e.printStackTrace();
return;
}
}
}
catch (final IOException e) {
e.printStackTrace();
return;
}
} | 7 |
private TheaterSeats loadSeatsFromDisk(File name){
FileInputStream fis;
ObjectInputStream ois;
TheaterSeats theaterSeats = null;
try {
fis = new FileInputStream(name);
ois = new ObjectInputStream(fis);
try{
theaterSeats = (TheaterSeats) ois.readObject();
}catch (EOFException e) {
//carry on!
}
ois.close();
fis.close();
return theaterSeats;
} catch (FileNotFoundException e) {
System.out.println("loadSeats() - File Not Found.");
return null;
} catch (IOException e) {
System.out.println("loadSeats() - Fatal Error.");
return null;
} catch (ClassNotFoundException e) {
System.out.println("loadSeats() - No TheaterSeats Found.");
return null;
}
} | 4 |
public List<Keyword> findKeywords(List<String> kwInput) {
ArrayList<Keyword> res = new ArrayList<Keyword>();
for (String s: kwInput) {
for (Keyword kw: keywordList) {
if (kw.getWord().equals(s)) {
res.add(kw);
}
}
}
return res;
} | 3 |
public static String nowString(){
String dateString = "";
Calendar cal = Calendar.getInstance();
dateString += String.valueOf( cal.get(Calendar.YEAR)) + "年" ;
dateString += String.valueOf( cal.get(Calendar.MONTH) + 1) + "月";
dateString += String.valueOf( cal.get(Calendar.DATE)) + "日";
dateString += String.valueOf( cal.get(Calendar.HOUR_OF_DAY)) + "時";
dateString += String.valueOf( cal.get(Calendar.MINUTE)) + "分";
dateString += String.valueOf( cal.get(Calendar.SECOND)) + "秒";
return dateString;
} | 0 |
public void enterCommand(String command, Player player) {
try {
String[] commandString = command.split(" ");
if (SubCommand.isHelpCommand(commandString[0]) || commandString[0].equals("")) {
help(commandString);
} else if (SubCommand.isBackCommand(commandString[0])) {
displayDefault(player);
}
else {
switch (state) {
case NEWGAME:
if (SubCommand.isYesCommand(commandString[0])) {
rebootGame();
}
break;
case BATTLE:
executeBattleCommand(commandString, player);
break;
case DOCKED:
executeDockCommand(commandString, player);
break;
case DEFAULT:
executePrimaryCommand(commandString, player);
break;
}
}
} catch (CommandException e) {
gui.displayError(e.getMessage());
}
} | 9 |
public int from() { return v; } | 0 |
public LegendEntry(PlotData2D data, int dataIndex) {
javax.swing.ToolTipManager.sharedInstance().setDismissDelay(5000);
m_plotData = data;
m_dataIndex = dataIndex;
// this.setBackground(Color.black);
/* this.setPreferredSize(new Dimension(0, 20));
this.setMinimumSize(new Dimension(0, 20)); */
if (m_plotData.m_useCustomColour) {
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if ((e.getModifiers() & e.BUTTON1_MASK) == e.BUTTON1_MASK) {
Color tmp = JColorChooser.showDialog
(LegendPanel.this, "Select new Color",
m_plotData.m_customColour);
if (tmp != null) {
m_plotData.m_customColour = tmp;
m_legendText.setForeground(tmp);
if (m_Repainters.size() > 0) {
for (int i=0;i<m_Repainters.size();i++) {
((Component)(m_Repainters.elementAt(i))).repaint();
}
}
LegendPanel.this.repaint();
}
}
}
});
}
m_legendText = new JLabel(m_plotData.m_plotName);
m_legendText.setToolTipText(m_plotData.getPlotNameHTML());
if (m_plotData.m_useCustomColour) {
m_legendText.setForeground(m_plotData.m_customColour);
}
this.setLayout(new BorderLayout());
this.add(m_legendText, BorderLayout.CENTER);
/* GridBagLayout gb = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx=0;constraints.gridy=0;constraints.weightx=5; */
m_pointShape = new JPanel() {
private static final long serialVersionUID = -7048435221580488238L;
public void paintComponent(Graphics gx) {
super.paintComponent(gx);
if (!m_plotData.m_useCustomColour) {
gx.setColor(Color.black);
} else {
gx.setColor(m_plotData.m_customColour);
}
Plot2D.drawDataPoint(10,10,3,m_dataIndex,gx);
}
};
// m_pointShape.setBackground(Color.black);
m_pointShape.setPreferredSize(new Dimension(20, 20));
m_pointShape.setMinimumSize(new Dimension(20, 20));
this.add(m_pointShape, BorderLayout.WEST);
} | 7 |
public void move() { //la miscarea automobilului, distanta creste, drumul de misca proportional distantei;
distance += speed;
speed += acceleration;
if (speed > MAX_SPEED) speed = MAX_SPEED;
if (speed <= MIN_SPEED) speed = MIN_SPEED;
pozY += deltaY;
if (pozY <= MAX_TOP) pozY = MAX_TOP;
if (pozY >= MAX_BOTTOM) pozY = MAX_BOTTOM;
if (backgroundLayer2 - speed <= 0) { //schimbam bucatile de drum in ciclu;
backgroundLayer1 = 0;
backgroundLayer2 = MAX_WIDTH_IMG;
} else {
backgroundLayer1 -= speed;
backgroundLayer2 -= speed;
}
} | 5 |
public static void main(String[] args) {
int i = 0;
outer:
for(; true; ) {
inner:
for(; i<10; i++) {
System.out.println("i = "+i);
if(i == 2) {
System.out.println("continue;");
continue;
}
if(i == 3) {
System.out.println("break;");
i++;
break;
}
if(i == 7) {
System.out.println("continue outer;");
i++;
continue outer;
}
if(i == 8) {
System.out.println("break outer;");
break outer;
}
for(int k=0; k<5; k++) {
if(k == 3) {
System.out.println("continue inner");
continue inner;
}
}
}
}
} | 8 |
public byte[] coding(byte[] data) {
int bufLen = data.length + (data.length + 6 ) / 7 ;
ByteBuffer buf = ByteBuffer.allocate(bufLen);
for(int i = 0; i != data.length; i++) {
int right = (i % 7) + 1;
int left = 7 - right;
byte value = (byte)((data[i] & 0xFF) >> right);
value |= convertByte;
buf.put(value);
convertByte = (byte)((data[i]<< left) & 0x7F);
if(i % 7 == 6 || i == data.length - 1) {
buf.put(convertByte);
convertByte = 0x00;
}
}
return buf.array();
} | 3 |
@Override
public synchronized Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (flavor.equals(flavors[STRING])) {
return nodeSet.toString();
} else if (flavor.equals(flavors[NODESET])) {
return nodeSet.clone();
} else {
throw new UnsupportedFlavorException(flavor);
}
} | 2 |
private void asetaViereiset(Ruutu ruutu, int x, int y) {
int miinat = 0;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
//tarkistetaan ettei ruutun omaa pommia lasketa
if ((i == 0 && j == 0)) {
//tarkistetaan että ruutu on kentän sisällä
} else if ((x + i) > -1 && (y + j) > -1 && (x + i) < this.leveys && (y + j) < this.korkeus) {
Ruutu apu = ruudut[x + i][y + j];
if (apu.getMiina()) {
miinat++;
}
}
}
}
ruutu.viereistenMiinojenMaara(miinat);
} | 9 |
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.