method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
ff0ba124-51dc-4477-b302-f5aa29ed2ca6 | 5 | @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 Message)) {
return false;
}
Message other = (Message) object;
if ((this.messageId == null && other.messageId != null) || (this.messageId != null && !this.messageId.equals(other.messageId))) {
return false;
}
return true;
} |
78906067-8181-47b4-a479-0e26a8bbab8b | 8 | public double getValue (double x, double y, double z)
{
// This method could be more efficient by caching the seed values. Fix
// later.
x *= frequency;
y *= frequency;
z *= frequency;
int xInt = (x > 0.0? (int)x: (int)x - 1);
int yInt = (y > 0.0? (int)y: (int)y - 1);
int zInt = (z > 0.0? (int)z: (int)z - 1);
double minDist = 2147483647.0;
double xCandidate = 0;
double yCandidate = 0;
double zCandidate = 0;
// Inside each unit cube, there is a seed point at a random position. Go
// through each of the nearby cubes until we find a cube with a seed point
// that is closest to the specified position.
for (int zCur = zInt - 2; zCur <= zInt + 2; zCur++)
{
for (int yCur = yInt - 2; yCur <= yInt + 2; yCur++)
{
for (int xCur = xInt - 2; xCur <= xInt + 2; xCur++)
{
// Calculate the position and distance to the seed point inside of
// this unit cube.
double xPos = xCur + NoiseGen.ValueNoise3D (xCur, yCur, zCur, seed);
double yPos = yCur + NoiseGen.ValueNoise3D (xCur, yCur, zCur, seed + 1);
double zPos = zCur + NoiseGen.ValueNoise3D (xCur, yCur, zCur, seed + 2);
double xDist = xPos - x;
double yDist = yPos - y;
double zDist = zPos - z;
double dist = xDist * xDist + yDist * yDist + zDist * zDist;
if (dist < minDist)
{
// This seed point is closer to any others found so far, so record
// this seed point.
minDist = dist;
xCandidate = xPos;
yCandidate = yPos;
zCandidate = zPos;
}
}
}
}
double value;
if (enableDistance)
{
// Determine the distance to the nearest seed point.
double xDist = xCandidate - x;
double yDist = yCandidate - y;
double zDist = zCandidate - z;
value = (Math.sqrt(xDist * xDist + yDist * yDist + zDist * zDist)
) * SQRT_3 - 1.0;
} else {
value = 0.0;
}
// Return the calculated distance with the displacement value applied.
return value + (displacement * (double)NoiseGen.ValueNoise3D (
(int)(Math.floor (xCandidate)),
(int)(Math.floor (yCandidate)),
(int)(Math.floor (zCandidate)), seed));// added seed here, not in original
// but there isn't a working method
// without seed
} |
e4ba748d-57aa-4413-a7e9-5552d9e7063e | 0 | public static void setNow(long timestamp) {
timeDiff = timestamp - new Date().getTime();
} |
5132ebd7-629d-4a0b-9c91-f53385afe703 | 0 | public void setStatus(int status) {
this.status = status;
} |
01d6f57b-2247-4c42-ae2a-ebedf8de5655 | 7 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
Physical target=mob;
if((auto)&&(givenTarget!=null))
target=givenTarget;
if(target.fetchEffect(this.ID())!=null)
{
mob.tell(mob,target,null,L("<T-NAME> <T-IS-ARE> already affected by @x1.",name()));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> attain(s) sparkling eyes!"):L("^S<S-NAME> @x1 for divine revelation, and <S-HIS-HER> eyes begin to sparkle.^?",prayWord(mob)));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,0);
}
}
else
return beneficialWordsFizzle(mob,null,L("<S-NAME> @x1 for divine revelation, but <S-HIS-HER> prayer is not heard.",prayWord(mob)));
// return whether it worked
return success;
} |
cdc38d03-053f-4610-9484-f1b04b1d0c78 | 9 | private ArrayList<Desire> findDesires() {
ArrayList<Desire> returnDesires = new ArrayList<Desire>();
for (Agent a : level.agents) {
if (!getToBoxDesireCompleted(a)) {
for (Box b : level.boxes) {
//System.err.println("adding box goal with " + b.getId());
if (a.getColor() == b.getColor()
&& !(b.getAtField() instanceof Goal && ((Goal) b
.getAtField()).getId() == b.getId())) {
returnDesires.add(new Desire(a, b));
}
}
} else {
for (Goal g : level.goals) {
// System.err.println("adding goal goal with " + g.getId());
if (g.getId() == a.desire.box.getId() && g.object == null) {
System.err.println("adding desire "+ g.x + "." + g.y);
returnDesires.add(new Desire(a, a.desire.box, g));
}
}
}
a.desire = null;
}
return returnDesires;
} |
f0c5e6cd-57ae-4c8c-ab9c-7fa4e59b843a | 5 | private static PrintStream getStream(String type) {
if (type == null) return null;
if (type.equals("stdout")) {
return System.out;
} else if (type.equals("stderr")) {
return System.err;
} else if (type.startsWith("file:")) {
String relativeDir = Settings.get(Settings.DEBUG_DIR);
try {
return new PrintStream(new FileOutputStream(relativeDir + "/" + type.substring(5)));
} catch (FileNotFoundException e) {
System.out.println("WARNING: Cannot log to file: " + relativeDir + "/" + type.substring(5) + ", Redirecting to sysout");
return System.out;
}
}
return null;
} |
c0a3529d-1d2f-466d-9a19-1eac33c8f904 | 4 | public Hashtable getDictionary(Hashtable dictionaryEntries, String key) {
Object o = getObject(dictionaryEntries, key);
if (o instanceof Hashtable) {
return (Hashtable) o;
} else if (o instanceof Vector) {
Vector v = (Vector) o;
Hashtable h1 = new Hashtable();
for (Enumeration e = v.elements(); e.hasMoreElements();) {
Object o1 = e.nextElement();
if (o1 instanceof Map) {
h1.putAll((Map) o1);
}
}
return h1;
}
return null;
} |
4dca6bc8-123c-42f2-bc04-843182ed29ee | 9 | protected Apply(Element apply, FieldMetaInfo.Optype opType, ArrayList<Attribute> fieldDefs,
TransformationDictionary transDict)
throws Exception {
super(opType, fieldDefs);
String functionName = apply.getAttribute("function");
if (functionName == null || functionName.length() == 0) {
// try the attribute "name" - a sample file produced by MARS
// uses this attribute name rather than "function" as defined
// in the PMML spec
functionName = apply.getAttribute("name");
}
if (functionName == null || functionName.length() == 0) {
throw new Exception("[Apply] No function name specified!!");
}
//System.err.println(" *** " + functionName);
m_function = Function.getFunction(functionName, transDict);
// now read the arguments
NodeList children = apply.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
String tagName = ((Element)child).getTagName();
if (!tagName.equals("Extension")) {
//System.err.println(" ++ " + tagName);
Expression tempExpression =
Expression.getExpression(tagName, child, m_opType, m_fieldDefs, transDict);
if (tempExpression != null) {
m_arguments.add(tempExpression);
}
}
}
}
if (fieldDefs != null) {
updateDefsForArgumentsAndFunction();
}
} |
a740d621-3f9f-4388-bb73-05659c1a89e9 | 8 | private Map<String, Object> values(final int type,
final ValueVisitor defaultVisitor) {
Class<?> clazz = getClass();
final FieldDefinitionImpl thiz = this;
final Map<String, Object> map = new HashMap<String, Object>();
SpringReflectionUtils.doWithFields(clazz,
new SpringReflectionUtils.FieldCallback() {
public void doWith(Field field)
throws IllegalArgumentException,
IllegalAccessException {
if (!field.isAnnotationPresent(FieldDefinition.class)) {
return;
}
FieldDefinition def = field
.getAnnotation(FieldDefinition.class);
// 映射名
String key = def.mappingName();
if (type == 1) {// 属性名
key = def.propertyName();
} else if (type == 2) {// 列名
key = def.columnName();
}
// 忽略未声明的值
if (key.equals("")) {
return;
}
Object value = null;
field.setAccessible(true);
value = field.get(thiz);
Class<?> targetClass = field.getType();
Map<String, Object> params = new HashMap<String, Object>(
1);
params.put("escape", def.escape());
if (visitors.containsKey(targetClass)) {
ValueVisitor visitor = visitors.get(targetClass);
value = visitor.target(targetClass, value, params);
} else if (defaultVisitor != null) {
value = defaultVisitor.target(targetClass, value,
params);
}
map.put(key, value);
}
}, SpringReflectionUtils.COPYABLE_FIELDS);
return map;
} |
e80f64ce-5ea6-4001-a0e2-a8c724e24473 | 2 | public void simulateGrowth() {
for (Planet p: planets){
if(p.Owner() == 0)
continue;
Planet newp = new Planet(p.PlanetID(), p.Owner(), p.NumShips()+p.GrowthRate() ,
p.GrowthRate(), p.X(), p.Y());
planets.set(p.PlanetID(), newp);
}
} |
06115791-2e7f-463e-a23e-2ba5de5ae7f4 | 5 | @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 Comment)) {
return false;
}
Comment other = (Comment) object;
if ((this.commentID == null && other.commentID != null) || (this.commentID != null && !this.commentID.equals(other.commentID))) {
return false;
}
return true;
} |
7231cae2-8c2d-471b-b34f-2e5d448a37c3 | 5 | public void tick(){
gsm.tick();
if (FallingBlocks.lives <= 0) {
Sound.playGameOverSound();
gameOverB();
}
if (SinglePlayerState.p1Score == 10) {
Sound.playGameOverSound();
gameOverS1();
}
if (SinglePlayerState.compScore == 10) {
Sound.playGameOverSound();
gameOverS2();
}
if (MultiPlayerState.p1Score == 10 ) {
Sound.playGameOverSound();
gameOverS1();
}
if (MultiPlayerState.p2Score == 10 ) {
Sound.playGameOverSound();
gameOverM2();
}
} |
703e5457-3419-4de9-99f0-a7bb60994583 | 6 | private void updateGraphics() {
if (isInit) {
setBorder(BorderFactory.createTitledBorder("init"));
} else {
setBorder(null);
}
switch (aspect) {
case POINT:
setBackground(Color.yellow);
setIcon(new ImageIcon("dot.jpg"));
break;
case VIDE:
setBackground(Color.white);
setIcon(null);
break;
case MUR:
setBackground(Color.black);
setIcon(new ImageIcon("wall.jpg"));
break;
case ANY:
case AGENT:
setBackground(Color.blue);
setIcon(new ImageIcon("agent.jpg"));
break;
}
// inciter à repeindre cet objet à la prochaine occasion
repaint();
} |
5c804fed-0d77-4438-bab7-0a8a7f24d095 | 8 | @Override
public boolean execute(MOB mob, List<String> commands, int metaFlags)
throws java.io.IOException
{
String parm = (commands.size() > 1) ? CMParms.combine(commands,1) : "";
if((!mob.isAttributeSet(MOB.Attrib.AUTODRAW) && (parm.length()==0))||(parm.equalsIgnoreCase("ON")))
{
mob.setAttribute(MOB.Attrib.AUTODRAW,true);
mob.tell(L("Auto weapon drawing has been turned on. You will now draw a weapon when one is handy, and sheath one a few seconds after combat."));
}
else
if((mob.isAttributeSet(MOB.Attrib.AUTODRAW) && (parm.length()==0))||(parm.equalsIgnoreCase("OFF")))
{
mob.setAttribute(MOB.Attrib.AUTODRAW,false);
mob.tell(L("Auto weapon drawing has been turned off. You will no longer draw or sheath your weapon automatically."));
}
else
if(parm.length() > 0)
{
mob.tell(L("Illegal @x1 argument: '@x2'. Try ON or OFF, or nothing to toggle.",getAccessWords()[0],parm));
}
return false;
} |
d45aac0c-9933-446a-87ef-95268e68ebc9 | 5 | @Override
public BMPImage apply(BMPImage image) {
BMPImage filteredImage = new BMPImage(image);
int redGap = 256/redBits;
int greenGap = 256/greenBits;
int blueGap = 256/blueBits;
BMPImage.BMPColor[][] bitmap = image.getBitMap();
BMPImage.BMPColor[][] filteredBitmap = filteredImage.getBitMap();
for(int i = 1; i <= filteredImage.getHeight(); i++) {
for(int j = 1; j <= filteredImage.getWidth(); j++) {
int er = filteredBitmap[i][j].red % redGap;
int eg = filteredBitmap[i][j].green % greenGap;
int eb = filteredBitmap[i][j].blue % blueGap;
filteredBitmap[i][j].red -= er;
filteredBitmap[i][j].green -= eg;
filteredBitmap[i][j].blue -= eb;
filteredBitmap[i][j+1].red += (int)(er * 7.0/16);
filteredBitmap[i][j+1].green += (int)(eg * 7.0/16);
filteredBitmap[i][j+1].blue += (int)(eb * 7.0/16);
filteredBitmap[i+1][j-1].red += (int)(er * 3.0/16);
filteredBitmap[i+1][j-1].green += (int)(eg * 3.0/16);
filteredBitmap[i+1][j-1].blue += (int)(eb * 3.0/16);
filteredBitmap[i+1][j].red += (int)(er * 5.0/16);
filteredBitmap[i+1][j].green += (int)(eg * 5.0/16);
filteredBitmap[i+1][j].blue += (int)(eb * 5.0/16);
filteredBitmap[i+1][j+1].red += (int)(er * 1.0/16);
filteredBitmap[i+1][j+1].green += (int)(eg * 1.0/16);
filteredBitmap[i+1][j+1].blue += (int)(eb * 1.0/16);
if(filteredBitmap[i][j].red > 255) filteredBitmap[i][j].red = 255;
if(filteredBitmap[i][j].green > 255) filteredBitmap[i][j].green = 255;
if(filteredBitmap[i][j].blue > 255) filteredBitmap[i][j].blue = 255;
}
}
return filteredImage;
} |
3bc134eb-1ce9-4698-ab53-8e0657d31cdd | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vertex other = (Vertex) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
} |
d529fd35-94fd-472b-87d1-d7578ce9e116 | 3 | private void moveCursorLeft(boolean shiftDown) {
if (shiftDown) {
int start = textField.getSelectionStart();
if (start > 0) {
textField.setSelectionStart(start - 1);
}
} else {
int pos = textField.getCaretPosition();
if (pos > 0)
textField.setCaretPosition(pos - 1);
}
} |
09d1e5c0-df2f-48c0-b359-84a9fbc92072 | 2 | private void selectMove(int selected) {
IMove[] moves = battle.getPlayer().getPokemon().get_moves();
System.out.println(selectedMove + " - " + moves.length);
if(selected >= moves.length)
selectedMove = 0;
else if(selected < 0)
selectedMove = moves.length - 1;
else
selectedMove = selected;
System.out.println(selectedMove + " - " + moves.length);
} |
ebe0758d-d6df-44fa-98e4-8ca4be3065ec | 9 | public void run()
{
short ret = MsgDumperCmnDef.MSG_DUMPER_SUCCESS;
MsgDumperCmnDef.WriteDebugFormatSyslog(__FILE__(), __LINE__(), "Thread[%s]=> The worker thread is running", worker_thread_name);
while (!exit.get())
{
synchronized(this)
{
// wait for input data
try
{
wait();
// Move the message
for (Iterator<MsgDumperCmnDef.MsgCfg> it = buffer_list.iterator() ; it.hasNext() ;)
{
MsgDumperCmnDef.MsgCfg new_item = it.next();
// MsgDumperCmnDef.WriteDebugFormatSyslog(__FILE__(), __LINE__(), "Thread[%s]=> Move the message[%s] to another buffer", worker_thread_name, new_item);
write_list.add(new_item);
}
buffer_list.clear();
}
catch (InterruptedException e)
{
MsgDumperCmnDef.WriteDebugFormatSyslog(__FILE__(), __LINE__(), "Thread[%s]=> Got an InterruptedException in the thread , due to: %s", worker_thread_name, e.toString());
}
catch (Exception e)
{
MsgDumperCmnDef.WriteErrorFormatSyslog(__FILE__(), __LINE__(), "Thread[%s]=> Exception occur while moving the data, due to: %s", worker_thread_name, e.toString());
ret = MsgDumperCmnDef.MSG_DUMPER_FAILURE_UNKNOWN;
}
}
if (write_list.size() > 0)
{
// Open the device......
ret = msg_dumper.open_device();
if (MsgDumperCmnDef.CheckMsgDumperFailure(ret))
break;
Iterator it = write_list.iterator();
while(it.hasNext())
{
ret = msg_dumper.write_msg((MsgDumperCmnDef.MsgCfg)it.next());
if (MsgDumperCmnDef.CheckMsgDumperFailure(ret))
{
MsgDumperCmnDef.WriteErrorFormatSyslog(__FILE__(), __LINE__(), "Thread[%s]=> Fail to write message, due to %d", worker_thread_name, ret);
break;
}
}
write_list.clear();
// Close the device
ret = msg_dumper.close_device();
if (MsgDumperCmnDef.CheckMsgDumperFailure(ret))
break;
}
}
MsgDumperCmnDef.WriteDebugFormatSyslog(__FILE__(), __LINE__(), "Thread[%s]=> The worker thread of writing message is going to die", worker_thread_name);
} |
53e79d6b-3400-4796-b441-eafe6f70c181 | 0 | @Test
public void isEmptyReturnsFalseAfterSingleEnqueue() {
q.enqueue(0);
assertFalse(q.isEmpty());
} |
5f19742c-6c4a-4836-beb0-452a7fa700d4 | 8 | public int longestValidParentheses(String s) {
if (s == null || s.length() == 0) {
return 0;
}
List<int[]> spans = new LinkedList<>();
Deque<Integer> deque = new LinkedList<>();
int maxSpan = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
deque.add(i);
} else if (c == ')') {
Integer start = deque.pollLast();
if (start != null) {
insert(spans, new int[] { start, i });
}
}
}
for (int[] span : spans) {
int len = span[1] - span[0];
if (len > maxSpan) {
maxSpan = len + 1;
}
}
return maxSpan;
} |
092f536c-4617-447a-b132-bdfe74ff6a99 | 6 | private void copyRGBtoABGR(ByteBuffer buffer, byte[] curLine) {
if (transPixel != null) {
byte tr = transPixel[1];
byte tg = transPixel[3];
byte tb = transPixel[5];
for (int i = 1, n = curLine.length; i < n; i += 3) {
byte r = curLine[i];
byte g = curLine[i + 1];
byte b = curLine[i + 2];
byte a = (byte) 0xFF;
if (r == tr && g == tg && b == tb) {
a = 0;
}
buffer.put(a).put(b).put(g).put(r);
}
} else {
for (int i = 1, n = curLine.length; i < n; i += 3) {
buffer.put((byte) 0xFF).put(curLine[i + 2]).put(curLine[i + 1]).put(curLine[i]);
}
}
} |
3d95939d-dd19-44a8-bd86-44148a654126 | 8 | public Unit getUnitAt(Position p) {
if ( p.getRow() == 2 && p.getColumn() == 3 ||
p.getRow() == 3 && p.getColumn() == 2 ||
p.getRow() == 3 && p.getColumn() == 3 ) {
return new StubUnit(GameConstants.ARCHER, Player.RED);
}
if ( p.getRow() == 4 && p.getColumn() == 4 ) {
return new StubUnit(GameConstants.ARCHER, Player.BLUE);
}
return null;
} |
51244953-9295-41d4-a767-1e3a930ec46c | 6 | public void dispose(boolean cache) {
if (streamInput != null) {
if (!cache) {
try {
streamInput.dispose();
}
catch (IOException e) {
logger.log(Level.FINE, "Error disposing stream.", e);
}
streamInput = null;
}else{
library.removeObject(this.getPObjectReference());
}
}
synchronized (imageLock) {
if (image != null) {
image.dispose(cache, (streamInput != null));
if (!cache || !image.isCachedSomehow()) {
image = null;
}
}
}
} |
2a6f199b-22f1-4296-9c2a-3d4183700a79 | 8 | private void decodeLobbyLogin(InputStream buffer) {
int clientRev = buffer.readInt();
int rsaBlockSize = buffer.readShort(); // RSA block size
int rsaHeaderKey = buffer.readByte(); // RSA header key
System.out.println(" " + rsaBlockSize + " " + rsaHeaderKey + " "
+ clientRev);
int[] loginKeys = new int[4];
for (int data = 0; data < 4; data++) {
loginKeys[data] = buffer.readInt();
}
buffer.readLong();
String pass = buffer.readString();
@SuppressWarnings("unused")
long serverSeed = buffer.readLong();
@SuppressWarnings("unused")
long clientSeed = buffer.readLong();
buffer.decodeXTEA(loginKeys, buffer.getOffset(), buffer.getLength());
String name = buffer.readString();
boolean isHD = buffer.readByte() == 1;
boolean isResizable = buffer.readByte() == 1;
System.out.println(" Is resizable? " + isResizable);
for (int i = 0; i < 24; i++)
buffer.readByte();
String settings = buffer.readString();
@SuppressWarnings("unused")
int unknown = buffer.readInt();
int[] crcValues = new int[35];
for (int i = 0; i < crcValues.length; i++)
crcValues[i] = buffer.readInt();
System.out.println(name + ", " + pass);
Player player;
if (!SerializableFilesManager.containsPlayer(name)) {
player = new Player(name);
player.setPassword(pass);
// session.getLoginPackets().sendClientPacket(2);
// return;
} else {
player = SerializableFilesManager.loadPlayer(name);
if (player == null) {
session.getLoginPackets().sendClientPacket(20);
return;
}
if (!player.getPassword().equals(pass)) {
session.getLoginPackets().sendClientPacket(3);
return;
}
}
if (player.isPermBanned()
|| (player.getBanned() > System.currentTimeMillis()))
session.getLoginPackets().sendClientPacket(4);
else {
player.init(session, name);
session.getLoginPackets().sendLobbyDetails(player);// sendLoginDetails(player);
session.setDecoder(3, player);
session.setEncoder(2, player);
SerializableFilesManager.savePlayer(player);
// player.start();
}
} |
ba428af5-5650-43f3-8d68-5274d045a043 | 2 | public OutputStream getOutputStream ()
{
if ("bulk" != getType () || isInput ())
throw new IllegalArgumentException ();
spi = getDevice ().getSPI ();
return new BulkOutputStream (spi, getEndpoint ());
} |
744a70a6-43a8-4aad-b399-e540e357186c | 8 | @EventHandler
public void onDamage(EntityDamageEvent event) {
if (event.getEntity() instanceof Player) {
if (MPlayer.getElement((Player) event.getEntity()).equals(Element.EARTH) && event.getCause().equals(DamageCause.FALL)) {
event.setCancelled(true);
} else if (MPlayer.getElement((Player) event.getEntity()).equals(Element.FIRE) && (event.getCause().equals(DamageCause.FIRE) || event.getCause().equals(DamageCause.FIRE_TICK))) {
event.setCancelled(true);
} else if (MPlayer.getElement((Player) event.getEntity()).equals(Element.WATER) && event.getCause().equals(DamageCause.DROWNING)) {
event.setCancelled(true);
}
}
} |
8e472a28-bf59-41ae-a7d6-1912d5375fe5 | 9 | @Override
public boolean tick(Tickable ticking, int tickID)
{
if(tickID==Tickable.TICKID_MOB)
{
if(affected instanceof MOB)
{
final MOB mob=(MOB)affected;
if(!mob.isInCombat())
if((mob.amFollowing()==null)
||(mob.location()==null)
||(mob.amDead())
||((invoker!=null)
&&((mob.location()!=invoker.location())||(!CMLib.flags().isInTheGame(invoker, true)))))
{
unInvoke();
}
}
}
return super.tick(ticking,tickID);
} |
0ccb3ee9-2439-4d8e-87cc-fa3db31ff68c | 5 | @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 Tenant)) {
return false;
}
Tenant other = (Tenant) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} |
683cb0fa-8569-4e77-8cc8-b00a9cbdc785 | 2 | public static boolean isLich (Entity entity) {
if (entity instanceof Skeleton) {
Skeleton lich = (Skeleton) entity;
LeatherArmorMeta chestMeta;
ItemStack lichChest = new ItemStack(Material.LEATHER_CHESTPLATE, 1, (short) - 98789);
chestMeta = (LeatherArmorMeta) lichChest.getItemMeta();
chestMeta.setColor(Color.fromRGB(52, 52, 52));
lichChest.setItemMeta(chestMeta);
if (lich.getEquipment().getChestplate().equals(lichChest)) {
return true;
}
}
return false;
} |
19328dea-e663-4eb9-bae9-2c1dd56f640e | 6 | private IpInfo jsoupParser(String Html) {
IpInfo ipLookup = new IpInfo();
int count = 0;
Document doc = Jsoup.parse(Html);
Elements e = doc.getElementsByTag("input");
for (int i = 0; i < e.size(); i++) {
if (i == 1) {
Element element = e.get(i);
String nodeValue = element.attr("value");
if (!nodeValue.equalsIgnoreCase("Limit Exceeded")) {
ipLookup.setCountry(nodeValue);
count++;
} else {
count = 0;
break;
}
}
if (i == 3) {
Element element = e.get(i);
String nodeValue = element.attr("value");
ipLookup.setRegion(nodeValue);
count++;
}
if (i == 4) {
Element element = e.get(i);
String nodeValue = element.attr("value");
ipLookup.setCity(nodeValue);
count++;
}
}
if (count == 0) {
ipLookup.setErrorMsg("Cannot get country info for " + baseUrl);
logger.severe(this.toString() + " " + Html);
PriorityManager.getInstance().registerServiceError(this.getClass().getSimpleName());
}
return ipLookup;
} |
c1d5407b-50e8-49df-8151-85310b448a66 | 1 | public static Gender buildGender(String genderStr) {
return genderStr.equals(MALE_DESC) ? MALE : FEMALE;
} |
874f62fe-71de-464c-8257-145c5aa27e22 | 1 | @Override
public void notifySubscription(String file, int number) throws RemoteException {
System.out.println("Notification: "+file+" got downloaded "+number+" times!.");
try {
shell.writeLine("Notification: "+file+" got downloaded "+number+" times!.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
8240dae1-dab8-4dc0-b53b-822c878dabe9 | 0 | public void setRoadHaul(String roadHaul) {
this.roadHaul = roadHaul;
} |
3d2a5efb-ec2d-423f-871e-2bc8c390a93d | 8 | private void writeJSON(Object value) throws JSONException {
if (JSONObject.NULL.equals(value)) {
write(zipNull, 3);
} else if (Boolean.FALSE.equals(value)) {
write(zipFalse, 3);
} else if (Boolean.TRUE.equals(value)) {
write(zipTrue, 3);
} else {
if (value instanceof Map) {
value = new JSONObject((Map) value);
} else if (value instanceof Collection) {
value = new JSONArray((Collection) value);
} else if (value.getClass().isArray()) {
value = new JSONArray(value);
}
if (value instanceof JSONObject) {
write((JSONObject) value);
} else if (value instanceof JSONArray) {
write((JSONArray) value);
} else {
throw new JSONException("Unrecognized object");
}
}
} |
df38571f-892d-4b59-b0f8-06a69c7cc0b9 | 9 | private TokenString tokenizeCurrentLine() {
TokenString tokenString = new TokenString();
boolean finishedLine = false;
// Sorts through the list of TokenTypes, ordering them from longest to shortest.
TokenType[] types = TokenType.values();
Arrays.sort(types, Comparator.comparing((TokenType t) -> t.length()).reversed());
while (!finishedLine) {
if (source.get(currentLine).length() == 0) {
finishedLine = true;
continue;
}
boolean matched = false;
for (TokenType t : types) {
if (t.match(source.get(currentLine))) {
int position = currentPosition;
consume(t.length());
tokenString.append(new Token(t, t.tokenValue, currentLine, position));
matched = true;
break;
}
}
if (!matched) {
if (Character.isDigit(source.get(currentLine).charAt(0))) {
tokenString.append(tokenizeNumericalLiteral());
} else if (isIdentifierCharacter(source.get(currentLine).charAt(0))) {
tokenString.append(tokenizeIdentifier());
} else if (source.get(currentLine).charAt(0) == '"') {
tokenString.append(tokenizeStringLiteral());
} else if (Character.isWhitespace(source.get(currentLine).charAt(0))) {
tokenString.append(new Token(TokenType.WHITESPACE, "", currentLine, currentPosition));
consume(1);
} else {
Handler.reportError(new Handler.BuildError(3, currentLine, currentPosition, Character.toString(source.get(currentLine).charAt(0))));
consume(1);
}
}
Handler.abortIfErrors();
}
return tokenString;
} |
3566d7b9-5c63-4095-bc00-84fcd1a85e6b | 8 | public boolean nextToCell(int x, int y, IMapCell cell) {
int xL = x - 1;
int xR = x + 1;
int yL = y - 1;
int yR = y + 1;
if (xL >= 0 && getCell(xL, y).equals(cell)) {
return true;
}
if (xR < getX() && getCell(xR, y).equals(cell)) {
return true;
}
if (yL >= 0 && getCell(x, yL).equals(cell)) {
return true;
}
if (yR < getY() && getCell(x, yR).equals(cell)) {
return true;
}
return false;
} |
4bb06ae8-91c4-4ea4-8e27-1b80960bd16a | 7 | 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 {
String property = System.getProperty("os.name");
String lookAndFeel = (property.contains("Windows")) ? "Windows" : "Nimbus";
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if (lookAndFeel.equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainFrame.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.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 MainFrame().setVisible(true);
}
});
} |
f329884c-f6e0-4fc6-80c1-0470d507c394 | 1 | public static String getString() throws BadInput{
//return System.console().readLine();
try {
return br.readLine();
} catch(IOException e) {
throw new BadInput("Couln't get input. IO problem?");
}
} |
8ed09c07-07e8-4977-8248-6bcd2ea01455 | 5 | public boolean isMatch(String s, String p) {
if (s == null || p == null)
return false;
if ("".equals(p)) {
if ("".equals(s))
return true;
return false;
}
this.s = s;
this.p = p;
f = new Boolean[s.length() + 1][];
for (int i = 0; i <= s.length(); i++)
f[i] = new Boolean[p.length() + 1];
f[0][0] = true;
return search(s.length(), p.length());
} |
f1d8ff33-df88-4fbb-92a0-221d2094269e | 7 | public static void makePlayerList() {
final int MAX_PLAYERS = 3, MIN_PLAYERS = 1;
int numPlayers;
String playerName;
System.out.print("How many people are playing (1-3)? ");
do {
try {
numPlayers = scan.nextInt();
}
catch(InputMismatchException e) {
numPlayers = -1;
}
scan.nextLine();
if (numPlayers < 0)
System.out.print("Invalid input.\nHow many people are playing? ");
else if (numPlayers < MIN_PLAYERS)
System.out.printf("Sorry, you must have at least %d player.\nHow many people are playing? ", MIN_PLAYERS);
else if (numPlayers > MAX_PLAYERS)
System.out.printf("Sorry, you cannot have more than %d players.\nHow many people are playing? ", MAX_PLAYERS);
} while (numPlayers < MIN_PLAYERS || numPlayers > MAX_PLAYERS);
for (int i = 0; i < numPlayers; i++) {
System.out.printf("What is player %d's name? ", i + 1);
playerName = scan.next();
playerList.add(new Player(playerName));
}
} |
5677d483-bb6d-496b-b304-c58a9afb14d8 | 5 | @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 Transactions)) {
return false;
}
Transactions other = (Transactions) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} |
8cf3d204-5861-4dbc-afd0-877a54f562a2 | 3 | public Level(String name) {
double checkRatioEnemyType = 0;
for(double e : ratioEnemyType)
checkRatioEnemyType += e;
if( checkRatioEnemyType != 1.0) {
System.out.println("La somme des ratios des types d'ennemies du level " + name + " est différente de 1. (" + checkRatioEnemyType + ")");
System.exit(1);
}
map = new Map(name + ".tile");
EntityXML.convertToEntities(this, ConverterEntitiesToXML.inverseConvert(name));
this.name = name;
switch(this.name){
case "map":
timeBeforeMobSpawn = 10.;
percent_mobByAvailablePositions = 0.000;
nbMaxEnemies = 50;
break;
default:
timeBeforeMobSpawn = 20.;
percent_mobByAvailablePositions = 0.000;
nbMaxEnemies = 10;
}
} |
dd373cbc-1f4b-4e65-a0e5-c005c5bee20d | 1 | public void toggleConnectionActions(boolean setVisible) {
if (setVisible) {
String name = InputHandler.getCurrentServerTab().getTabName();
disconnectFromServer.setText("Odpojit od " + name);
}
joinToChannel.setVisible(setVisible);
disconnectFromAll.setVisible(setVisible);
disconnectFromServer.setVisible(setVisible);
} |
bfaa98dd-a07f-4055-86a4-4a49a1af49d2 | 7 | public static String findMLIA() {
String fmlmsg = "";
try {
HttpURLConnection con = (HttpURLConnection) new URL("http://mylifeisaverage.com/" + getPage()).openConnection();
StringBuilder sb = new StringBuilder();
con.connect();
InputStream input = con.getInputStream();
byte[] buf = new byte[2048];
int read;
while ((read = input.read(buf)) > 0) {
sb.append(new String(buf, 0, read));
}
final String find = "<div class=\"sc\">";
int random = Randomizer.nextInt(10);
for (int i = 0; i < random; i++) {
String gb = sb.substring(sb.indexOf(find) + 1);
sb = new StringBuilder();
sb.append(gb);
}
int firstPost = sb.indexOf(find);
StringBuilder send = new StringBuilder();
for (int i = firstPost + find.length(); i < sb.length(); i++) {
char ch = sb.charAt(i);
if (ch == '<') {
if (sb.charAt(i + 1) == '/') {
if (sb.charAt(i + 2) == 'd') {
break;
}
}
}
send.append(ch);
}
String sendTxt = send.toString();
sendTxt = ignore(sendTxt);
final String find2 = " ";
sendTxt = sendTxt.substring(sendTxt.indexOf(find2));
sendTxt = sendTxt.substring(8);
fmlmsg = "[MLIA Bot] " + sendTxt;
input.close();
con.disconnect();
} catch (Exception e) {
System.err.println("[MLIA Bot] There has been an error displaying the MLIA.");
e.printStackTrace();
}
return fmlmsg;
} |
38911e62-f372-48be-aef3-56f19bef4995 | 6 | @Override
public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
g.setAntiAlias(true);
g.setColor(new Color(255, 255, 255));
if (!terrainMode) {
g.setColor(new Color(209, 217, 224));
}
g.fillRect(0, 0, Game.width, Game.height);
if (terrainMode) {
for (int i = 0; i < Terrain.energy.length; i++) {
for (int j = 0; j < Terrain.energy[0].length; j++) {
g.setColor(new Color(0F, 0F, 0F, Terrain.getEnergy(i, j) / (Terrain.starting * 2F)));
g.fillRect(i * 20, j * 20, 20, 20);
}
}
}
for (int i = 0; i < entities.size(); i++) {
Entity e = entities.get(i);
if (!terrainMode) {
e.render(container, game, g);
}
}
} |
0a054cd4-bbf1-4e2b-a702-1e3020c307f9 | 9 | public CellElement getPointerWithPolicy(int policy) {
if (m_pointers.size() == 0) {
return null;
}
CellElement retCell = null;
switch (policy) {
case POINTER_POLICY_ANY:
retCell = (CellElement) m_pointers.firstElement();
break;
case POINTER_POLICY_CLOCKWISE:
// Clockwise:
// 1. bottom
// 2. diag
// 3. left
retCell = getPositionalPointer(POINTERPOS_BOTTOM);
if (retCell == null) {
retCell = getPositionalPointer(POINTERPOS_DIAG);
}
if (retCell == null) {
retCell = getPositionalPointer(POINTERPOS_LEFT);
}
break;
case POINTER_POLICY_COUNTERCLOCKWISE:
// Clockwise:
// 1. Left
// 2. diag
// 3. bottom
retCell = getPositionalPointer(POINTERPOS_LEFT);
if (retCell == null) {
retCell = getPositionalPointer(POINTERPOS_DIAG);
}
if (retCell == null) {
retCell = getPositionalPointer(POINTERPOS_BOTTOM);
}
break;
case POINTER_POLICY_RANDOM:
retCell = getPointer( (int) (Math.random() * m_pointers.size()));
}
return retCell;
} |
dfbcc4f8-4b93-4f39-addd-39d3bfb3bcb3 | 4 | public void addToOutput(String message) {
try {
Element p = houtput.getParagraphElement(houtput.getLength());
houtput.insertAfterEnd(p, "<div align=left> "+message+" </div>");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (client.scrollflag) {
output.setCaretPosition(output.getDocument().getLength());
}
} |
49f261a5-0fa6-47c3-b86d-24a2dc74e113 | 9 | public static long f( int h, int w ){
if(h>=0 && w < mem[h].length && mem[h][w]!=-1) return mem[h][w];
if( w == 1 && h == 0 ) return mem[h][w]=1;
if( h>=1 && w==0 ) return mem[h][w]=1;
if( w < 0 || h < 0 ) return 0;
else return mem[h][w]=f( h-1, w )+f( h+1, w-1 );
} |
4c77c0ec-179f-421a-9fde-fa2665f54772 | 0 | @AfterClass
public static void tearDownClass() {
} |
c444081f-a572-4a2d-b876-99df5e5fc869 | 0 | @Override
public Object getWatchKey() {
return watchKey;
} |
fac2d940-9d6d-415c-b0a4-f0eadc04aa02 | 3 | public int[] getSucc(int i) throws ArrayIndexOutOfBoundsException{
if ((i<0) || (i>=nbVertices))
throw new ArrayIndexOutOfBoundsException();
int[] tab = new int[succ.get(i).size()];
for(int j=0;j<tab.length;j++){
tab[j] = succ.get(i).get(j);
}
return tab;
} |
09a2a196-d684-4b6b-9e93-c44e7a81737f | 5 | public final void filter(final Object o) throws JSONException {
if (o instanceof Element) {
Element element = (Element) o;
String elemName = element.getName();
List children = element.getContent();
List attribute = element.getAttributes();
Iterator ita = attribute.iterator();
Iterator itc = children.iterator();
current++;
tree.add(current, new JSONObject());
// Attributes
while (ita.hasNext()) {
Object child = ita.next();
filter(child);
}
// Children
while (itc.hasNext()) {
Object child = itc.next();
filter(child);
}
handleArray(elemName);
tree.remove(current);
current--;
} else if (o instanceof Attribute) {
handleAttribute((Attribute) o);
} else if (o instanceof Text) {
handleText((Text) o);
}
} |
05531cb5-b34a-48b6-a8b6-5b59658e3cd6 | 4 | @Override
public final void set( GraphSite site ) {
if( this.site != null ) {
for( GraphItem item : children ) {
this.site.removeItem( item );
}
removeFrom( this.site );
}
this.site = site;
if( site != null ) {
addTo( site );
for( GraphItem item : children ) {
site.addItem( item );
}
}
} |
4bd1fdad-13e5-41b1-b36d-87a5e2cc7ce0 | 1 | private void simpleSetLocal(int index, Type type, Frame frame) {
frame.setLocal(index, type);
if (type.getSize() == 2)
frame.setLocal(index + 1, Type.TOP);
} |
a7acf043-c563-4dda-9a29-d53d48335579 | 7 | public void mouseClicked(int x, int y, MouseHelper helper) {
if (helper == MouseHelper.LEFT_CLICK) {
if ((x >= theComponent.getX()) && ((x <= (theComponent.getX() + buttonWidth)))) {
if ((y >= theComponent.getY()) && (y <= (theComponent.getY() + buttonHeight))) {
if ((y > theComponent.getY()) && (y < (theComponent.getY() + buttonHeight))) {
clicked = true;
} else {
clicked = true;
}
}
}
}
} |
f4ea5226-6fe1-484b-a6f5-cf8068340812 | 8 | public boolean isUpgradeable(ItemStack is){
if(!(is.getType() == Material.WOOD_SWORD || is.getType() == Material.GOLD_SWORD || is.getType() == Material.IRON_SWORD || is.getType() == Material.DIAMOND_SWORD))return false;
if(is.hasItemMeta()){
ItemMeta im = is.getItemMeta();
if(im.hasLore()){
for(String s : im.getLore()){
if(s.startsWith(ChatColor.GRAY + "Damage")){
return true;
}
}
}
}
return false;
} |
741d35bd-2675-436c-92bc-d867a00e65e0 | 0 | private static int getShortLittleEndian(byte[] a, int offs) {
return (a[offs] & 0xff) | (a[offs + 1] & 0xff) << 8;
} |
befd4b5b-fb64-48d0-8652-7bd205ba802a | 2 | public void addCollectable(int tileX, int tileY, int tileType)
{
Tile collectable = null;
if(tileType == TileTypes.DIAMOND)
{
collectable = new TileCollectableDiamond(tileX * Tile.TILE_SIZE, tileY * Tile.TILE_SIZE, true);
}
else if(tileType == TileTypes.GOLD)
{
collectable = new TileCollectableGold(tileX * Tile.TILE_SIZE, tileY * Tile.TILE_SIZE, true);
}
collectables[tileX][tileY] = collectable;
} |
c4f7aded-5c94-4986-b131-04d2757e8eaa | 2 | private static PixImage array2PixImage(int[][] pixels) {
int width = pixels.length;
int height = pixels[0].length;
PixImage image = new PixImage(width, height);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setPixel(x, y, (short) pixels[x][y],
(short) pixels[x][y], (short) pixels[x][y]);
}
}
return image;
} |
950f0202-ebc0-43e0-a9a4-cebaceafe61f | 5 | @Override
public void drawShape(Graphics graphics) {
int xn, yn, xm, ym;
int xa, ya, xb, yb, xc, yc, xd, yd;
// xn and yn is the first point the user clicked
// xm and ym is the second point the user clicked
xn = super.getXi();
yn = super.getYi();
xm = super.getXo();
ym = super.getYo();
graphics.setColor(super.getColor());
int dx = xm - xn;
int dy = ym - yn;
// Scenario for slope less than 1.
if (Math.abs(dx) > Math.abs(dy)) {
if (xn > xm) {
int tempX = xn;
xn = xm;
xm = tempX;
int tempY = yn;
yn = ym;
ym = tempY;
} else {
xn = super.getXi();
yn = super.getYi();
xm = super.getXo();
ym = super.getYo();
}
xa = xn;
xb = xm;
xc = xn;
xd = xm;
if (yn > ym) {
ya = ym;
yb = ym;
yc = yn;
yd = yn;
} else {
ya = yn;
yb = yn;
yc = ym;
yd = ym;
}
// Scenario for slope is greater or equal to 1.
} else {
if (yn > ym) {
int tempX = xn;
xn = xm;
xm = tempX;
int tempY = yn;
yn = ym;
ym = tempY;
} else {
xn = super.getXi();
yn = super.getYi();
xm = super.getXo();
ym = super.getYo();
}
ya = yn;
yb = yn;
yc = ym;
yd = ym;
if (xn > xm) {
xa = xm;
xb = xn;
xc = xm;
xd = xn;
} else {
xa = xn;
xb = xm;
xc = xn;
xd = xm;
}
}
this.drawTriangle(graphics, xa, ya, xb, yb, xc, yc, xd, yd);
} |
c1a304f7-0871-493b-b11d-ba5ac1e95cde | 9 | public boolean checkCanMove(Block[][] boardMatrix, int firstBlockX, int firstBlockY, int secBlockX, int secBlockY, int thirdBlockX, int thirdBlockY,
int fourthBlockX, int fourthBlockY)
{
for (int i = 0; i < getBlocks().length; i++) {
Block tempBlock = getBlocks()[i];
int x = tempBlock.getX();
int y = tempBlock.getY();
// XXX Handle array bounds.
// int boardWidth = boardCons.getBoardWidth();
// if(y + thirdBlockY >= boardWidth || y + firstBlockY >=
// boardWidth)
// return false;
// if(y + thirdBlockY < 0 || y + firstBlockY < 0)
// return false;
if (i == 0) {
if (boardMatrix[x + firstBlockX][y + firstBlockY] != null)
return false;
}
if (i == 1) {
if (boardMatrix[x + secBlockX][y + secBlockY] != null)
return false;
}
if (i == 2) {
if (boardMatrix[x + thirdBlockX][y + thirdBlockY] != null)
return false;
}
if (i == 3) {
if (boardMatrix[x + fourthBlockX][y + fourthBlockY] != null)
return false;
}
}
return true;
} |
3c4745df-aeb3-4480-84c9-2692515d91ab | 6 | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Subscription o = (Subscription) obj;
return (edition == null ? o.edition == null : edition.equals(o.edition)) &&
(type == null ? o.type == null : type.equals(o.type));
} |
5500c704-dae9-4956-8aeb-d5bee881f1de | 6 | private void listen( HttpServletRequest request, HttpServletResponse response ) {
RequestDispatcher dispatcher = null;
ChatClientHelper helper = null;
int action = 0;
try {
if( request.getParameter( "action" ) == null ){
logger.info( "No action parameter, redirecting to default action" );
action = Definitions.DEFAULT_ACTION;
}else{
action = Integer.parseInt( request.getParameter( "action" ) );
}
} catch ( NumberFormatException e ){
logger.error( "Wrong action parameter, redirecting to error 404" );
action = Definitions.ERROR_404;
} catch ( Exception e ){
logger.error( "System failure, redirecting to error 500" );
logger.error( "Unknown error", e );
action = Definitions.ERROR_500;
}
try{
helper = new ChatClientHelper( );
helper.dispatch( request, response, action );
dispatcher = request.getRequestDispatcher( "jsp/redirect.jsp" );
dispatcher.forward( request, response );
} catch ( ServletException e ) {
logger.error( "?:SERVLETERROR", e );
} catch ( IOException e ) {
logger.error( "?:IOERROR", e );
} catch ( Exception e ){
logger.error( "?:ERROR", e );
}
} |
0e275400-2f4c-44d9-a8d1-bfec49ddfb40 | 8 | private void submitSQL(ArrayList<VulnLocation> params, String url, String method) {
String sqlAttack = "' OR 1=1; --";
String response = "";
String normalResponse = "";
SubmitForm submitForm = new SubmitForm(url);
SubmitForm submitNormalForm = new SubmitForm(url);
try {
for(VulnLocation vuln:params){
submitNormalForm.addRequestPair(vuln.getParameter(),"");
}
if(method.equals("GET"))
normalResponse = submitNormalForm.submitGet();
else if(method.equals("POST"))
normalResponse = submitNormalForm.submitPost();
else
System.out.println("mauvaise méthode");
for(VulnLocation vuln:params){
submitForm.addRequestPair(vuln.getParameter(),sqlAttack);
if(method.equals("GET"))
response = submitForm.submitGet();
else if(method.equals("POST"))
response = submitForm.submitPost();
else
System.out.println("mauvaise méthode");
if(!response.equals(normalResponse)){
out.write(vuln.toString() + "\n");
}
submitForm.clearParameters();
}
}
catch(Exception e){
System.out.println(e);
}
} |
53c52be1-a429-480d-854c-714fec581999 | 1 | protected void calculateMean()
{
double sum = 0.0;
for (double a : data) {
sum += a;
}
mean = sum / size;
} |
d83b9233-2669-4d07-b020-72c18ce2be0b | 4 | @Override
public boolean isAllowedToBorrow(Loan loan, StockController stockController) {
if (stockController.numberOfLoans(this) < 1) {
if (loan.getQuantity() < 2) {
if (CalendarController.differenceDate(loan.getStart(),
loan.getEnd()) < 8) {
if (CalendarController.differenceDate(
new GregorianCalendar(), loan.getStart()) < 8) {
return true;
}
}
}
}
return false;
} |
9300a3a8-8aeb-4548-b9d9-2990618437f7 | 6 | public void addListener( Object listener )
{
Class<?> listenerClass = listener.getClass();
for (Class<?> listenerInterface : listenerClass.getInterfaces())
{
RemoteInterface ri = listenerInterface.getAnnotation( RemoteInterface.class );
if (ri != null)
{
addInterface( listenerInterface );
for (RemoteMethodEntry entry : entries[ri.id()])
{
if (entry != null)
{
entry.listener = listener;
}
}
}
}
} |
b2a096e9-90d2-4e1d-892d-df24ae6b6221 | 6 | public static int majorityElement(int[] arr) {
if(arr.length == 0 || arr.length == 1) {
System.out.println("Error: Input array's length is less than 2.");
System.exit(0);
}
Integer count;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < arr.length; i++) {
if((count = map.get(arr[i])) != null) {
count += 1;
map.put(arr[i], count);
}
else
map.put(arr[i], 1);
count = 0;
}
for(Map.Entry<Integer, Integer> me : map.entrySet()) {
if(me.getValue() > arr.length/2)
return me.getKey();
}
return Integer.MIN_VALUE;
} |
a3b2f52c-9d85-4a25-bdb9-2434b70ef779 | 5 | private void doCommand(String cmd) {
if (cmd.startsWith("S")) {
doSleep(Integer.parseInt(cmd.substring(1)));
} else if (cmd.startsWith("X")) {
doShutdown();
} else if (cmd.startsWith("R")){
doRecovery();
} else if (cmd.equals("help")) {
doHelp();
} else if (cmd.equals("$DONE")) {
logger.info("DONE ALL OPERATIONS");
} else {
logger.info("Bad command: '{}'. Try 'help'", cmd);
}
} |
748b27e0-04a1-410d-8337-6dbab7e71d93 | 5 | public ArrayList<Activity> orderActivitiesByTime(ArrayList<Activity> activities, LinkedHashSet<Integer> activityIds) {
ArrayList<Activity> reorderedActivities = new ArrayList<>();
// if (activityIds != null) {
for (int i : activityIds) {
for (Activity a : activities) {
if (i == a.getIdActivity()) {
reorderedActivities.add(a);
break;
}
}
}
for (Activity a : activities) {
if (!reorderedActivities.contains(a)) reorderedActivities.add(a);
}
// }
return reorderedActivities;
} |
c252c523-1853-41d1-8ddc-87ee4cb3e581 | 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(OptionsIssuer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OptionsIssuer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OptionsIssuer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OptionsIssuer.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 OptionsIssuer().setVisible(true);
}
});
} |
fdb106c5-319a-4185-ad85-32d22d3f37f3 | 1 | private void compute_pcm_samples11(Obuffer buffer)
{
final float[] vp = actual_v;
//int inc = v_inc;
final float[] tmpOut = _tmpOut;
int dvp =0;
// fat chance of having this loop unroll
for( int i=0; i<32; i++)
{
final float[] dp = d16[i];
float pcm_sample;
pcm_sample = (float)(((vp[11 + dvp] * dp[0]) +
(vp[10 + dvp] * dp[1]) +
(vp[9 + dvp] * dp[2]) +
(vp[8 + dvp] * dp[3]) +
(vp[7 + dvp] * dp[4]) +
(vp[6 + dvp] * dp[5]) +
(vp[5 + dvp] * dp[6]) +
(vp[4 + dvp] * dp[7]) +
(vp[3 + dvp] * dp[8]) +
(vp[2 + dvp] * dp[9]) +
(vp[1 + dvp] * dp[10]) +
(vp[0 + dvp] * dp[11]) +
(vp[15 + dvp] * dp[12]) +
(vp[14 + dvp] * dp[13]) +
(vp[13 + dvp] * dp[14]) +
(vp[12 + dvp] * dp[15])
) * scalefactor);
tmpOut[i] = pcm_sample;
dvp += 16;
} // for
} |
55da44b5-f0e8-4e97-b84b-bd720da53a7c | 1 | public int reverse(int x) { // 无需处理符号位
int y = 0;
while(x !=0){
y = y*10 + x % 10;
x = x/10;
}
return y;
} |
c1d61d04-87b1-442b-b56d-0707ce5c2228 | 4 | public void input() {
if (Input.getKeyDown(Keyboard.KEY_UP)) {
System.out.println("We've just pressed up!");
}
if (Input.getKeyUp(Keyboard.KEY_UP)) {
System.out.println("We've just released up!");
}
if (Input.getMouseDown(1)) {
System.out.println("We've just pressed RMB @" + Input.getMousePosition());
}
if (Input.getMouseUp(1)) {
System.out.println("We've just released RMB @" + Input.getMousePosition());
}
} |
a5f8298e-de8f-4229-b52b-31929197ebe3 | 2 | public ArrayList<Double> FDWT(ArrayList<Double> _pic) {
ArrayList<Double> _temp = new ArrayList<Double>(_pic.size());
//Initialize _temp
_temp = (ArrayList<Double>) _pic.clone();
for (int j = _pic.size(); j >= 2; j = j / 2) {
for (int i = 0; i < j / 2; i += 1) {
double _average = (_pic.get(2 * i) + _pic.get(2 * i + 1)) / 2;
double _minus = _pic.get(2 * i) - _average;
_temp.set(i, _average);
_temp.set(j / 2 + i, _minus);
}
_pic = (ArrayList<Double>) _temp.clone();
}
return _pic;
} |
d7b0efbb-7dbd-4b1c-85ca-2ed676db5da8 | 5 | public static void NewGame(GameType type, GameModes mode, InetAddress addr, int nPlayers, int nPlanets, int nRows, int nCols)
{
if(type == null || mode == null) {
System.err.println("Must select a type and mode!");
return;
}
Instance.gameType = type;
Instance.gameMode = mode;
if(debug) System.out.println("Mode is " + ModeToString(mode));
if(type == GameType.NETWORK) {
Instance.setUPConnection(addr);
// read number of players from network game
TurnManager.initManager(nPlayers);
} else if (type == GameType.LOCAL) {
TurnManager.initManager(nPlayers);
}
Instance.setUpMap(nRows, nCols, nPlanets);
Instance.gameOver = false;
Instance.winner = -1;
Instance.selectedObj = null;
//ISectors.view.BattleMap.Instance.loadBattleMap(nRows, nCols);//Implemented in BattleWindow.
} |
501940be-f8b4-4e6a-9e39-027ee1fa7e5f | 6 | @Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args)
{
if (commandLabel.equalsIgnoreCase("censor"))
{
if (sender instanceof Player)
{
Player p = (Player) sender;
if (p.hasPermission("censors.censor"))
{
if (args.length != 1)
{
return false;
}
else
{
PlayerData playerdata = PlayerData.getPlayerData(p);
switch (args[0])
{
case "on":
p.sendMessage("Censor enabled.");
playerdata.setCensorEnabled(true);
return true;
case "off":
p.sendMessage("Censor disabled.");
playerdata.setCensorEnabled(false);
return true;
}
}
}
else
{
p.sendMessage(ChatColor.RED + "You do not have permission to use this command.");
return true;
}
}
else
{
sender.sendMessage("You cannot use this command from the console.");
return true;
}
}
return false;
} |
b35695ae-3a50-4c7e-89b5-18dd1488c169 | 9 | @Override
public void draw(Graphics g) {
if (state) {
if (color == 1)
g.drawImage(imgred, pos_x, pos_y, width, height, null);
else if (color == 2)
g.drawImage(imgblue, pos_x, pos_y, width, height, null);
else if (color == 3)
g.drawImage(imgwhite, pos_x, pos_y, width, height, null);
else if (color == 4)
g.drawImage(imgpurple, pos_x, pos_y, width, height, null);
else if (color == 5)
g.drawImage(imggreen, pos_x, pos_y, width, height, null);
else if (color == 6)
g.drawImage(imgspecial, pos_x, pos_y, width, height, null);
else if (color == 7)
g.drawImage(imgbomb, pos_x, pos_y, width, height, null);
else if (color == 8)
g.drawImage(imgblack, pos_x, pos_y, width, height, null);
}
} |
3b92152a-86a3-42bd-aea8-ae2d37e86ea5 | 8 | @Override
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking, tickID))
return false;
if((affected!=null)&&(affected instanceof Room))
{
final Room R=(Room)affected;
if(isRaining(R))
for(int i=0;i<R.numInhabitants();i++)
{
final MOB M=R.fetchInhabitant(i);
if(M!=null)
{
final MOB invoker=(invoker()!=null) ? invoker() : M;
if(CMLib.dice().rollPercentage()>M.charStats().getSave(CharStats.STAT_SAVE_ACID))
CMLib.combat().postDamage(invoker,M,this,CMLib.dice().roll(1,M.phyStats().level()+(2*getXLEVELLevel(invoker())),1),CMMsg.MASK_ALWAYS|CMMsg.TYP_ACID,Weapon.TYPE_MELTING,L("The acid rain <DAMAGE> <T-NAME>!"));
CMLib.combat().postRevengeAttack(M, invoker);
}
}
}
return true;
} |
8f3c55da-d8fc-45d4-8545-986a5ec03041 | 1 | @Test
public void TestRemoveStudent() throws InstanceNotFoundException {
try {
familyService.removeStudent(1);
} catch (InstanceNotFoundException e) {
e.printStackTrace();
}
assertEquals(familyService.getStudents().size(), 3);
} |
cf9ef043-d304-412a-aba2-e711c1c0cff3 | 8 | public void loadSchema(String catalogFile) {
String line = "";
try {
BufferedReader br = new BufferedReader(new FileReader(new File(catalogFile)));
while ((line = br.readLine()) != null) {
//assume line is of the format name (field type, field type, ...)
String name = line.substring(0, line.indexOf("(")).trim();
//System.out.println("TABLE NAME: " + name);
String fields = line.substring(line.indexOf("(") + 1, line.indexOf(")")).trim();
String[] els = fields.split(",");
ArrayList<String> names = new ArrayList<String>();
ArrayList<Type> types = new ArrayList<Type>();
String primaryKey = "";
for (String e : els) {
String[] els2 = e.trim().split(" ");
names.add(els2[0].trim());
if (els2[1].trim().toLowerCase().equals("int"))
types.add(Type.INT_TYPE);
else if (els2[1].trim().toLowerCase().equals("string"))
types.add(Type.STRING_TYPE);
else {
System.out.println("Unknown type " + els2[1]);
System.exit(0);
}
if (els2.length == 3) {
if (els2[2].trim().equals("pk"))
primaryKey = els2[0].trim();
else {
System.out.println("Unknown annotation " + els2[2]);
System.exit(0);
}
}
}
Type[] typeAr = types.toArray(new Type[0]);
String[] namesAr = names.toArray(new String[0]);
TupleDesc t = new TupleDesc(typeAr, namesAr);
HeapFile tabHf = new HeapFile(new File(name + ".dat"), t);
addTable(tabHf,name,primaryKey);
System.out.println("Added table : " + name + " with schema " + t);
}
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
} catch (IndexOutOfBoundsException e) {
System.out.println ("Invalid catalog entry : " + line);
System.exit(0);
}
} |
1a6a9c4b-13ef-4955-a236-9955ec5c6e03 | 3 | public int hashCode() {
int hc = 13 * sort;
if (sort == OBJECT || sort == ARRAY) {
for (int i = off, end = i + len; i < end; i++) {
hc = 17 * (hc + buf[i]);
}
}
return hc;
} |
5ae6d502-2dce-483d-a240-b25cc37626a0 | 8 | static int checkStyleBit(Shell parent, int style) {
int mask = SWT.PRIMARY_MODAL | SWT.APPLICATION_MODAL | SWT.SYSTEM_MODAL;
if ((style & SWT.SHEET) != 0) {
style &= ~SWT.SHEET;
if ((style & mask) == 0) {
style |= parent == null ? SWT.APPLICATION_MODAL
: SWT.PRIMARY_MODAL;
}
}
if ((style & mask) == 0) {
style |= SWT.APPLICATION_MODAL;
}
style &= ~SWT.MIRRORED;
if ((style & (SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT)) == 0) {
if (parent != null) {
if ((parent.getStyle() & SWT.LEFT_TO_RIGHT) != 0)
style |= SWT.LEFT_TO_RIGHT;
if ((parent.getStyle() & SWT.RIGHT_TO_LEFT) != 0)
style |= SWT.RIGHT_TO_LEFT;
}
}
return checkBits(style, SWT.LEFT_TO_RIGHT, SWT.RIGHT_TO_LEFT, 0, 0, 0,
0);
} |
c0283c52-5d01-4180-8d44-847e360c3264 | 2 | private void createTablesIfNotExist(Connection cnn) {
if (tableExists("cb_users", cnn)) {
logger.info("table cb_users already exists");
} else {
logger.info("create table cb_users");
String sql =
"CREATE TABLE `cb_users` ( \n" +
" `username` varchar(255) NOT NULL, \n" +
" `password` varchar(255) DEFAULT NULL, \n" +
" PRIMARY KEY (`username`) \n" +
") \n";
executeStatement(sql, cnn);
}
if (tableExists("cb_groups", cnn)) {
logger.info("table cb_groups already exists");
} else {
logger.info("create table cb_groups");
String sql =
"CREATE TABLE `cb_groups` ( \n" +
" `groupname` varchar(255) NOT NULL, \n" +
" `username` varchar(255) NOT NULL, \n" +
" `ID` int(11) NOT NULL AUTO_INCREMENT, \n" +
" PRIMARY KEY (`ID`), \n" +
" UNIQUE KEY `ID_UNIQUE` (`ID`) \n" +
") \n";
executeStatement(sql, cnn);
}
} |
3f30f0e8-9a39-4380-985d-de09b323ef67 | 5 | public CycList allIndicesOf(Object elem) {
CycList result = new CycList();
if (elem == null) {
for (int i = 0; i < size(); i++) {
if (get(i) == null) {
result.add(i);
}
}
} else {
for (int i = 0; i < size(); i++) {
if (elem.equals(get(i))) {
result.add(i);
}
}
}
return result;
} |
60d2ccff-ba40-4d4c-b8f3-46169ededaf9 | 8 | private void go() throws IOException {
// Create a new selector
Selector selector = Selector.open();
// Open a listener on each port, and register each one
// with the selector
for (int i=0; i<ports.length; ++i) {
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking( false );
ServerSocket ss = ssc.socket();
InetSocketAddress address = new InetSocketAddress( ports[i] );
ss.bind( address );
//关注新连接事件
SelectionKey key = ssc.register( selector, SelectionKey.OP_ACCEPT );
System.out.println( "Going to listen on "+ports[i] );
}
while (true) {
int num = selector.select();
//selectKeys是逐渐累加的,不会自动移除Key
Set selectedKeys = selector.selectedKeys();
Iterator it = selectedKeys.iterator();
while (it.hasNext()) {
SelectionKey key = (SelectionKey)it.next();
if ((key.readyOps() & SelectionKey.OP_ACCEPT)
== SelectionKey.OP_ACCEPT) {
//这个channel就是go()中注册的channel,
//其中指定ServerSocketChannel关注OP_ACCEPT,
//此key为OP_ACCEPT类型,所以channel必为ServerSocketChannel
ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
// Accept the new connection
SocketChannel sc = ssc.accept();
sc.configureBlocking( false );
// Add the new connection to the selector
SelectionKey newKey = sc.register( selector, SelectionKey.OP_READ );
it.remove();
System.out.println( "Got connection from "+sc );
} else if ((key.readyOps() & SelectionKey.OP_READ)
== SelectionKey.OP_READ) {
// Read the data
SocketChannel sc = (SocketChannel)key.channel();
boolean isEof = true;
while (true) {
echoBuffer.clear();
int r = sc.read( echoBuffer );
if (r<=0) {
break;
}
isEof = isEOF(echoBuffer);
echoBuffer.flip();
sc.write( echoBuffer );
}
if(isEof){
sc.close();
}
it.remove();
}
}
}
} |
44143879-d27b-4a44-a186-64b2d43fc923 | 7 | public ArrayList<FeatureResult> extractFeaturesFrom(MouseLogParser parser) {
ArrayList<FeatureResult> fr=new ArrayList<FeatureResult>();
fr.addAll(parser.getUserProfile().extract());
try {
// want to dynamically 'load' feature set
//so we can add features without having to modify this code.
//All features must implement the Feature interface
Reflections reflections = new Reflections("edu.pace.mouse.biometric.features");
Set<Class<? extends Feature>> setclasses = reflections.getSubTypesOf(Feature.class);
Object []classes = (Object[])setclasses.toArray();
String t1;
for(int i=0;i<classes.length-1;i++){
int index = i;
t1 = classes[i].toString();
for(int j=i+1;j<classes.length;j++){
if (t1.compareTo(classes[j].toString())>0){
index = j;
t1 = classes[j].toString();
}
}
if (i != index){
Object temp = classes[index];
classes[index]=classes[i];
classes[i] = temp;
}
}
Constructor constructor;
for (int i = 0; i < classes.length; i++) {
constructor = ((Class)classes[i]).getConstructor(new Class[] { MouseLogParser.class });
((Feature) constructor.newInstance(parser)).extract();
fr.addAll(((Feature) constructor.newInstance(parser)).extract());
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return fr;
} |
e6e0955b-1593-44fc-8764-e124d1f4790a | 0 | public int getImgWidth() {
return imgWidth;
} |
f1a9a02a-2288-47ba-8e1e-4694df15832d | 1 | private static void registerGeneral(String field, Class<? extends FrameNode> type, Property prop) {
generalFields.add(new GeneralNameValueConfig(field,type,prop));
} |
3183897a-57a2-4d36-a7f4-71f5cfeb9d12 | 9 | private static Set<Trace> checkArgs(String[] args) {
boolean error = false;
if (args.length != 2) {
error = true;
} else {
if (args[0].equals("d")) {
switch (args[1]) {
case "L1":
return Utils.demoL1eventLog();
case "L2":
return Utils.demoL2eventLog();
case "L7":
return Utils.demoL7eventLog();
case "LLT":
return Utils.demoLLTeventLog();
case "chap7":
return Utils.chapter7EventLog();
default:
error = true;
break;
}
} else if (args[0].equals("f")) {
return Utils.readInputFromCSV(args[1]);
} else {
error = true;
}
}
if (error) {
usage();
System.exit(1);
}
return new HashSet<>();
} |
76274130-b699-4045-82de-0d56ba2e09f1 | 4 | public static void main(String[] args) throws FileNotFoundException, InvalidCantidadDeTokensDeLookaheadException, BufferDeTokensVacioException, IOException, ElementoFueraDeIndiceEnBufferException {
// Menú de prueba para probar el Lexer, Parser y Traducción.
int i = 1;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Escriba 1 realizar el análisis léxico, escriba 2 para realizar el análisis sintáctico, y escriba 3 para realizar una traducción de JSON a XML: ");
try {
i = Integer.parseInt(br.readLine());
} catch(NumberFormatException nfe){
System.err.println("Invalid Format!");
} // Fin de obtencion de parámetro de operación
if (i == 1) { // Lexer
realizarLexer();
} else if (i == 2) { // Parser
realizarParser();
} else if (i == 3) { // Translate
realizarTraduccion();
}
} |
d5c0963c-775c-498a-af49-19203ca0a77f | 8 | @Override
public void Throttle(double value) {
double forward = 2.1;
double center = 1.50;
double reverse = 1.00;
double ms;
value = (value > 1) ? 1 : value;
value = (value < -1) ? -1 : value;
switch (direction){
case Positive:
value = (value > 0.0) ? 0.0 : value;
break;
case Negative:
value = (value < 0.0) ? 0.0 : value;
break;
case All:
value = 0;
default:
break;
}
if (value > 0)
{
ms = center + value * (forward - center);
}
else
{
ms = center + value * (center - reverse);
}
canipede.SetPWMValue(pwmChannel, (short)(ms * 1e6 / 200));
} |
1f86d6a5-f4f2-485b-b150-58f80c202f7a | 1 | public void testConstructor_ObjectStringEx3() throws Throwable {
try {
new YearMonth("10:20:30.040");
fail();
} catch (IllegalArgumentException ex) {
// expected
}
} |
69bfa3c9-acdb-4ba4-89e7-513da57ef330 | 0 | public Node<K> getLeft() {
return left;
} |
659f0e18-9594-4997-9ce3-72dd497c016a | 3 | public boolean isInUserAgentString(String agentString)
{
for (String alias : aliases)
{
if (agentString != null && agentString.toLowerCase().indexOf(alias.toLowerCase()) != -1)
return true;
}
return false;
} |
17392726-2272-4f24-9405-dfbdbf38f6ef | 8 | public Image getCurrentImage()
{
DefaultFont font = DefaultFont.getDefaultFont();
Image[] charecters = font.getStringImage(currentInput);
Image currentImage = (isSelected) ? selectedImage : unSelectedImage;
int[] pixels = currentImage.getPixels();
int IWidth = currentImage.getWidth();
int IHeight = currentImage.getHeight();
int linenum = 0;
int verticleIndent = 0;
if(maxlines == 1)
verticleIndent = IHeight/2;
for(int i = 0; i < charecters.length; i++)
{
if(i > maxchars/maxlines)
{
linenum = i / (maxchars/maxlines);
}
Image image = charecters[i];
int[] pix = image.getPixels();
int w = image.getWidth();
int h = image.getHeight();
for(int yLoc = 0; yLoc < h; yLoc++)
{
for(int xLoc = 0; xLoc < w; xLoc++)
{
if (pix[w * yLoc + xLoc] != ScreenManager.getInstance().getOmmitColor())
pixels[currentImage.getWidth() * (((yLoc + verticleIndent)+linenum*h) - (verticleIndent==0?0:(image.getHeight()/2))) + (indent + (i*w + xLoc))] = pix[w * yLoc + xLoc];
}
}
}
return new Image(pixels, IWidth, IHeight);
} |
3cebdeca-09e5-4859-b1e8-de458593d1ef | 7 | public static OOXMLElement parseOOXML( XmlPullParser xpp, Stack<String> lastTag, WorkBookHandle bk )
{
BodyPr b = null;
P para = null;
try
{ // need: endParaRPr?
int eventType = xpp.getEventType();
while( eventType != XmlPullParser.END_DOCUMENT )
{
if( eventType == XmlPullParser.START_TAG )
{
String tnm = xpp.getName();
if( tnm.equals( "bodyPr" ) )
{ // default text properties
lastTag.push( tnm );
b = (BodyPr) BodyPr.parseOOXML( xpp, lastTag );
}
else if( tnm.equals( "p" ) )
{ // part of p element
lastTag.push( tnm );
para = (P) P.parseOOXML( xpp, lastTag, bk );
}
}
else if( eventType == XmlPullParser.END_TAG )
{
String endTag = xpp.getName();
if( endTag.equals( "txPr" ) )
{
lastTag.pop();
break;
}
}
eventType = xpp.next();
}
}
catch( Exception e )
{
log.error( "txPr.parseOOXML: " + e.toString() );
}
TxPr tPr = new TxPr( b, para );
return tPr;
} |
14a9d18a-6a6e-4d12-ba59-872f7f3cea31 | 2 | private void doParse(String contents) {
try {
InputSource xmlParserSource = new InputSource(new StringReader(contents));
reader.parse(xmlParserSource);
} catch (IOException ioe) {
System.out.println("IOException when running parser.");
ioe.printStackTrace();
System.out.println("IOException when running parser.");
} catch (SAXException se) {
//System.out.println("SAXException when running parser." + se);
//se.printStackTrace();
//System.out.println("SAXException when running parser.");
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.