text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
MOB target=mob;
if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
if(target.fetchEffect(this.ID())!=null)
{
mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already sensing water."));
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> gain(s) sensitivity to water!"):L("^S<S-NAME> chant(s) and gain(s) sensitivity to water!^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,0);
}
}
else
beneficialVisualFizzle(mob,null,L("<S-NAME> chant(s), but nothing happens."));
return success;
} | 8 |
@After
public void tearDown() {
} | 0 |
public String getFirstPropertyValue(String name){
Property<String> prop = getFirstProperty(name);
if(prop == null){
return null;
}
if(prop.getValue() == null){
return null;
}
return prop.getValue();
} | 2 |
public void setup(Sprite.Drawer d, Coord cc, Coord off) {
init();
if (spr != null)
spr.setup(d, cc, off);
} | 1 |
@RequestMapping(value = {"/MovimientosBancarios"}, method = RequestMethod.GET)
public void readAll(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse) {
try {
ObjectMapper jackson = new ObjectMapper();
String json = jackson.writeValueAsString(movimientoBancarioDAO.findAll());
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
httpServletResponse.setContentType("application/json; charset=UTF-8");
noCache(httpServletResponse);
httpServletResponse.getWriter().println(json);
} catch (Exception ex) {
noCache(httpServletResponse);
httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
httpServletResponse.setContentType("text/plain; charset=UTF-8");
try {
noCache(httpServletResponse);
ex.printStackTrace(httpServletResponse.getWriter());
} catch (Exception ex1) {
noCache(httpServletResponse);
}
}
} | 2 |
protected static SuperString findWordAndPos(String s, int caretPos) {
caretPos--;
if (s.length() != 0 && containsSeparator(s, caretPos)) {
caretPos--;
} else if (caretPos > 0) {
int front;
int end;
do {
front = caretPos--;
} while (caretPos != -1 && !containsSeparator(s, caretPos));
do {
end = caretPos++;
} while (caretPos != s.length() && !containsSeparator(s, caretPos));
end++;
s = s.substring(front, end);
return new SuperString(s, end);
}
return null;
} | 7 |
public void recordRep(long zobrist) {
// TODO: Make this smoother with a better looking for empty places
int hashkey = (int) (zobrist % HASHSIZE);
if (hashtable[hashkey] == 0 || hashtable[hashkey] == zobrist) {
hashtable[hashkey] = zobrist;
return;
}
for (int i = 1; i < HASHSIZE; i++) {
if (hashtable[(hashkey + i) % HASHSIZE] == 0) {
hashtable[(hashkey + i) % HASHSIZE] = zobrist;
return;
}
}
logger.error("Error: Repetition table is full");
} // END recordRep | 4 |
@Override
public void refresh(RefreshEvent event) {
Class eventClass = event.getClass();
if (eventClass == LocalGameRefreshEvent.class) {
mainPanel.refreshGrid(event);
} else if (eventClass == TotalGameRefreshEvent.class) {
mainPanel.refreshRemainingMines(event);
} else if (eventClass == ChronometerEvent.class) {
mainPanel.refreshTime(event);
} else if (eventClass == ResizeEvent.class) {
Minesweeper.getInstance().resize(event);
mainPanel.resize(event);
mainPanel.refreshRemainingMines(event);
mainPanel.refreshImg(event);
} else if (eventClass == EndGameEvent.class) {
mainPanel.refreshRemainingMines(event);
mainPanel.refreshImg(event);
}
} | 5 |
public static List<Map<String,String>> getValueAsMapList(String headerLine, List<String> followingLines, MassBankRecordLine recordLine) {
List<Map<String, String>> result = new ArrayList<Map<String,String>>();
String headerValue = getValueAsString(headerLine, recordLine);
String[] headerValues = headerValue.split(" ");
if (followingLines != null) {
for (String followingLine : followingLines) {
if (followingLine != null) {
String followingValue = getValueAsString(followingLine, MassBankRecordLine.FOLLOWING_LINE);
String[] followingValues = followingValue.split(" ");
Map<String, String> map = new LinkedHashMap<String, String>();
if (headerValues.length == followingValues.length) {
for (int i = 0; i < headerValues.length; i++) {
map.put(headerValues[i], followingValues[i]);
}
} else {
// LOGGER.warn("there is a problem in multiple line value. (" + headerLine + ")");
}
result.add(map);
} else {
// LOGGER.warn("there is a problem in following line value. (" + followingLine + ")");
}
}
} else {
// LOGGER.warn("there is a problem in following lines of multiple line. (" + headerValue + ")");
}
return result;
} | 5 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Book other = (Book) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
if (!Objects.equals(this.title, other.title)) {
return false;
}
if (!Objects.equals(this.price, other.price)) {
return false;
}
if (!Objects.equals(this.description, other.description)) {
return false;
}
if (!Objects.equals(this.isbn, other.isbn)) {
return false;
}
if (!Objects.equals(this.nbOfPage, other.nbOfPage)) {
return false;
}
if (!Objects.equals(this.illustrations, other.illustrations)) {
return false;
}
return true;
} | 9 |
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return DATA_FLAVOR.equals(flavor) || DataFlavor.stringFlavor.equals(flavor);
} | 1 |
private void SetState(int state) {
if (state == token_source.curLexState)
return;
Token root = new Token(), last=root;
root.next = null;
// First, we build a list of tokens to push back, in backwards order
while (token.next != null) {
Token t = token;
// Find the token whose token.next is the last in the chain
while (t.next != null && t.next.next != null)
t = t.next;
// put it at the end of the new chain
last.next = t.next;
last = t.next;
// If there are special tokens, these go before the regular tokens,
// so we want to push them back onto the input stream in the order
// we find them along the specialToken chain.
if (t.next.specialToken != null) {
Token tt=t.next.specialToken;
while (tt != null) {
last.next = tt;
last = tt;
tt.next = null;
tt = tt.specialToken;
}
}
t.next = null;
}
if ( root.next != null ) {
token_source.backup( root.next.endColumn - last.beginColumn + 1 );
}
//while (root.next != null) {
// token_source.backup(root.next.image.length());
// root.next = root.next.next;
//}
jj_ntk = -1;
token_source.SwitchTo(state);
} | 7 |
public List formatResults(){
List results = new ArrayList();
Iterator i = searchResults.iterator();
String lastSampleId = "";
String preSampleId = "";
String preAssay = "";
List oneSampleRows = new ArrayList();
int dupResult = 0;
boolean newSample = false;
while(i.hasNext()){
Result r = (Result)i.next();
String sampleId = r.getSampleId();
String assay = r.getAssay();
String result = r.getResult();
//log.debug(" sampleId is " + sampleId + " assay is " + assay);
if(!preSampleId.equals(sampleId)){
for(int a=0;a<oneSampleRows.size();a++){
Result[] oneRow = (Result[])oneSampleRows.get(a);
results.add(oneRow);
}
oneSampleRows = new ArrayList();
Result[] oneRow = new Result[assays.size()];
oneSampleRows.add(oneRow);
preSampleId = sampleId;
newSample = true;
//log.debug("sample id changed, now the preSampleId is " + preSampleId);
}else{
newSample = false;
}
int columnNo = assays.indexOf(assay);
if(doStat){
assayStats[columnNo].addOneGenoType(result);
}
if(format.equals("yes")){
r.setResult(haploviewFormatResult(result));
}
// not a dup result
if(!preAssay.equals(assay) || newSample){
dupResult = 0;
preAssay = assay;
}else{
dupResult++;
if(oneSampleRows.size()<= dupResult){
Result[] oneRow = new Result[assays.size()];
oneSampleRows.add(oneRow);
int sampleRowNo = sampleIds.indexOf(sampleId);
sampleIds.add(sampleRowNo+1,sampleId);
}
}
//log.debug("the dupResult is "+ dupResult);
Result[] oneRow = (Result[])oneSampleRows.get(dupResult);
oneRow[columnNo] = r;
}
for(int a=0;a<oneSampleRows.size();a++){
Result[] oneRow = (Result[])oneSampleRows.get(a);
results.add(oneRow);
}
return results;
} | 9 |
public void setPassCriteria(String passCriteria)
{
this.passCriteria = passCriteria;
} | 0 |
protected void progressTask()
{
if(getTask().equals("eat"))
{
attemptToEat();
return;
}
if(getTask().equals("reproduce"))
{
attemptToReproduce();
return;
}
if(getTask().equals("wear backpack"))
{
attemptToWearBackpack();
return;
}
System.out.println(getName() + " doesn't know how to " + getTask() + "!");
} | 3 |
public void testMany () throws IOException {
Server server = new Server();
Kryo serverKryo = server.getKryo();
register(serverKryo);
startEndPoint(server);
server.bind(tcpPort);
final TestObjectImpl serverTestObject = new TestObjectImpl(4321);
final ObjectSpace serverObjectSpace = new ObjectSpace();
serverObjectSpace.register(42, serverTestObject);
server.addListener(new Listener() {
public void connected (final Connection connection) {
serverObjectSpace.addConnection(connection);
}
public void received (Connection connection, Object object) {
if (object instanceof MessageWithTestObject) {
assertEquals(256 + 512 + 1024, serverTestObject.moos);
stopEndPoints(2000);
}
}
});
// ----
Client client = new Client();
register(client.getKryo());
startEndPoint(client);
client.addListener(new Listener() {
public void connected (final Connection connection) {
new Thread() {
public void run () {
TestObject test = ObjectSpace.getRemoteObject(connection, 42, TestObject.class);
test.other();
// Timeout on purpose.
try {
((RemoteObject)test).setResponseTimeout(200);
test.slow();
fail();
} catch (TimeoutException ignored) {
}
try {
Thread.sleep(300);
} catch (InterruptedException ex) {
}
((RemoteObject)test).setResponseTimeout(3000);
for (int i = 0; i < 256; i++)
assertEquals(4321f, (float)test.other());
for (int i = 0; i < 256; i++)
test.moo();
for (int i = 0; i < 256; i++)
test.moo("" + i);
for (int i = 0; i < 256; i++)
test.moo("" + i, 0);
connection.sendTCP(new MessageWithTestObject());
}
}.start();
}
});
client.connect(5000, host, tcpPort);
waitForThreads();
} | 7 |
final void method1348(int i, Object object, Interface14 interface14) {
do {
try {
anInt2318++;
method1341(object, interface14, -114, 1);
if (i > 62)
break;
aClass107_2316 = null;
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("pq.K(" + i + ','
+ (object != null ? "{...}"
: "null")
+ ','
+ (interface14 != null
? "{...}" : "null")
+ ')'));
}
break;
} while (false);
} | 5 |
@Override
public void keyTyped(KeyEvent e)
{
if (e.getSource() == textWidth || e.getSource() == textHeight)
{
if (e.getKeyChar() > '9' || e.getKeyChar() < '0')
{
e.consume();
}
else if (Integer.parseInt(((JTextField) e.getSource()).getText()
+ e.getKeyChar()) > 254)
{
((JTextField) e.getSource()).setText("254");
e.consume();
}
else if (Integer.parseInt(((JTextField) e.getSource()).getText()
+ e.getKeyChar()) < 1)
{
((JTextField) e.getSource()).setText("1");
e.consume();
}
}
} | 6 |
public JPanelRender(JFrame window, final EventosDoTeclado evt, EventosDoRender imgevt){
this.window = window;
this.imgEvt = imgevt;
this.evt = evt;
window.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT || key == KeyEvent.VK_A) {
evt.teclaEsquerda();
} else if (key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_D) {
evt.teclaDireita();
} else if (key == KeyEvent.VK_UP || key == KeyEvent.VK_W) {
evt.teclaCima();
} else if (key == KeyEvent.VK_DOWN || key == KeyEvent.VK_S) {
evt.teclaBaixo();
} else if (key == KeyEvent.VK_SPACE) {
evt.teclaEspaco();
} else {
evt.teclaPress(key);
}
}
});
} | 9 |
public void randomColor() {
int randomInt = (new Random().nextInt(6) + 1);
switch (randomInt) {
case 1:
robot.setBodyColor(Color.GREEN);
robot.setBulletColor(Color.GREEN);
break;
case 2:
robot.setBodyColor(Color.GREEN);
robot.setBulletColor(Color.GREEN);
break;
case 3:
robot.setBodyColor(Color.MAGENTA);
robot.setBulletColor(Color.MAGENTA);
break;
case 4:
robot.setBodyColor(Color.YELLOW);
robot.setBulletColor(Color.YELLOW);
break;
case 5:
robot.setBodyColor(Color.YELLOW);
robot.setBulletColor(Color.YELLOW);
break;
case 6:
robot.setBodyColor(Color.RED);
robot.setBulletColor(Color.RED);
break;
case 7:
robot.setBodyColor(Color.PINK);
robot.setBulletColor(Color.PINK);
break;
default:
break;
}
} | 7 |
public int searchInsert(int[] A, int target) {
int sta = 0;
int end = A.length;
while (sta <= end){
int mid = (sta + end)/2;
if(A[mid] == target)
return mid;
else if(A[mid] < target)
sta = mid +1;
else
end = mid-1;
}
return sta;
} | 3 |
private void render(byte input[], int inputPosition, int inputWidth,
int output[], int outputPosition, int outputWidth,
int width, int height, int colour) {
int _width = -(width >> 2);
width = -(width & 3);
/*
* Iterate through the pixels.
*/
for (int row = -height; row < 0; row++) {
for (int col = _width; col < 0; col++) {
/*
* If the pixel in the current position is set,
* draw it with a given colour. If not, simply
* leave a space.
*/
if (input[inputPosition++] != 0)
output[outputPosition++] = colour;
else
outputPosition++;
if (input[inputPosition++] != 0)
output[outputPosition++] = colour;
else
outputPosition++;
if (input[inputPosition++] != 0)
output[outputPosition++] = colour;
else
outputPosition++;
if (input[inputPosition++] != 0)
output[outputPosition++] = colour;
else
outputPosition++;
}
for (int i = width; i < 0; i++)
if (input[inputPosition++] != 0)
output[outputPosition++] = colour;
else
outputPosition++;
outputPosition += outputWidth;
inputPosition += inputWidth;
}
} | 8 |
private void actionDelete( )
{
DefaultMutableTreeNode
selNd = getSelectedNode();
if ( selNd != null )
{
int[] selIdxs = getNodeIndexList(selNd);
if ( selIdxs.length == 1 )
{
audioVectors.remove(selIdxs[0]);
dataRootNd.remove(selIdxs[0]);
dataTr.updateUI();
}
else
{
((DefaultMutableTreeNode)dataRootNd.getChildAt(selIdxs[0])).remove(selIdxs[1]);
audioVectors.get(selIdxs[0]).remove(selIdxs[1]);
dataTr.updateUI();
}
}
} | 2 |
void setTotalForce(SimpleVector totalForce) {
this.totalForce = totalForce;
} | 0 |
public void agregarLinea(int p1,int p2,Color pColor,int pStroke)
{ int i=nConexiones;
if(p1>=nVertices||p2>=nVertices) return;
if(i>=MAXConexiones) if(aConexiones==null)
{ MAXConexiones=100;
aConexiones=new int[MAXConexiones];
aColores=new Color[MAXConexiones];
aStrokes=new Stroke[MAXConexiones];
}else
{ MAXConexiones*=2;
int nv[]=new int[MAXConexiones];
System.arraycopy(aConexiones,0,nv,0,aConexiones.length);
aConexiones=nv;
}
if(p1>p2)
{ int t=p1;
p1=p2;
p2=t;
}
aConexiones[i]=(p1<<16)|p2;
aColores[i]=pColor;
switch(pStroke)
{ case 0: aStrokes[i]=new BasicStroke(1f); break;
case 1: aStrokes[i]=new BasicStroke(1f, BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL, 1f, new float[]{10f,5f},10f); break;
case 2: aStrokes[i]=new BasicStroke(10f,BasicStroke.CAP_ROUND,BasicStroke.JOIN_BEVEL); break;
case 3: aStrokes[i]=new BasicStroke(1f, BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL, 1f, new float[]{10f,5f},10f); break;
default:aStrokes[i]=new BasicStroke(1f); break;
}
nConexiones=i+1;
} | 9 |
@Override
public void startSetup(Attributes atts) {
table.setModel(model);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setPreferredScrollableViewportSize(new Dimension(100,100));
// Get Column Labels
ArrayList colLabels = new ArrayList();
String colLabelsString = atts.getValue(A_COL_LABELS);
colLabels.add("New");
StringTokenizer tokenizer = new StringTokenizer(colLabelsString,DELIMITER);
while (tokenizer.hasMoreTokens()) {
colLabels.add(tokenizer.nextToken());
}
// Setup Table Model
model.setColumnCount(colLabels.size());
for (int i = 0; i < colLabels.size(); i++) {
colModel.getColumn(i).setHeaderValue(colLabels.get(i));
}
// Setup Remove Column
TableColumn removeColumn = colModel.getColumn(0);
removeColumn.setMinWidth(90);
removeColumn.setMaxWidth(90);
removeColumn.setResizable(false);
RemoveCellEditor editor = new RemoveCellEditor(this);
removeColumn.setCellRenderer(editor);
removeColumn.setCellEditor(editor);
removeColumn.setHeaderRenderer(removeColumnHeaderRenderer);
// Setup Table Header
table.getTableHeader().addMouseListener(this);
table.getTableHeader().setReorderingAllowed(false);
// Put it all together
JScrollPane component = new JScrollPane(table);
setComponent(component);
super.startSetup(atts);
table.addFocusListener(new TableListener(table, getPreference()));
} | 2 |
@Override
public void addcomment(User user, Book book, MediadComment comment) {
// TODO Auto-generated method stub
for (Book book1 : fdb.getBooks()) {
if (book1==book){
book1.addComment(comment);
break;
}
}
} | 2 |
private void toggleControls(){
String[] controls = new String[]{"Dir", "Orient", "Reflect", "XFact"};
boolean[] constate = new boolean[controls.length];
for(int abc = 0; abc < controls.length; abc++){
constate[abc] = gonzo.getControls(controls[abc]);}
bdlabel.setVisible(false);
for(int def = 0; def < orients.length; def++)
{orients[def].setVisible(false); orients[def].setEnabled(false);}
option[0].setVisible(false); option[0].setEnabled(false);
xfs.setVisible(false); xfs.setEnabled(false); xflab.setVisible(false);
if(constate[0]){bdlabel.setVisible(true);
for(int def = 0; def < orients.length; def++)
{orients[def].setVisible(true); orients[def].setEnabled(true);}
orients[0].setSelected(true); brushdir = 0;
option[0].setVisible(false); option[0].setEnabled(false);
}
if(constate[1]){ bdlabel.setVisible(true); boolean sig;
for(int def = 0; def < orients.length; def++)
{if(def < 4){sig = true;}else{sig = false;}
orients[def].setVisible(sig); orients[def].setEnabled(sig);}
orients[0].setSelected(true); brushdir = 0;
option[0].setVisible(false); option[0].setEnabled(false);
}
if(constate[2]){option[0].setVisible(true); option[0].setEnabled(true);
}
if(constate[3]){xfs.setEnabled(true);xfs.setVisible(true);/*xfs.setValue(1);*/xflab.setVisible(true);}
gonzo = null;
} | 9 |
private Object[] getNewAndArgs(Node nodeTest, List<Node> predResult,
String op) {
// TODO Auto-generated method stub
NodeTest[] args = ((NodeTest) nodeTest).getFunctionCalls().get(op);
List<NodeTest> newArgs = new ArrayList<>();
List<Node> predResultBackList = new ArrayList<>();
for (NodeTest arg : args) {
NodeTest ret = new NodeTest();
boolean val = false;
ret.setNodeType(NODE_TYPE_BOOLEAN);
if (arg.getNodeType() == NODE_TYPE_RELATIVE_LOCATIONPATH) {
if (((NodeTest) arg).getFunctionCalls().size() > 0) {
if (((NodeTest) arg).getFunctionCalls().containsKey(
"lessThan")) {
List<NodeTest[]> newArgs1 = getNewNotEqualArgs(arg,
predResult, "lessThan");
for (NodeTest[] args1 : newArgs1) {
ret = ((NodeTest) lessThan(args1[0], args1[1]));
}
}
if (((NodeTest) arg).getFunctionCalls().containsKey(
"greaterThan")) {
List<NodeTest[]> newArgs1 = getNewNotEqualArgs(arg,
predResult, "greaterThan");
for (NodeTest[] args1 : newArgs1) {
ret = (NodeTest) greaterThan(args1[0], args1[1]);
}
}
if (((NodeTest) arg).getFunctionCalls().containsKey(
FUNCTION_NOT + "")) {
List<NodeTest[]> newArgs1 = getNewNotEqualArgs(arg,
predResult, FUNCTION_NOT + "");
NodeTest rest = new NodeTest();
if (newArgs1.size() > 1) {
rest.setNodeType(NODE_TYPE_BOOLEAN);
} else {
rest.setNodeValue(Utils.asString(true));
}
ret = rest;
}
} else {
predResultBackList = (List<Node>) locationPath(predResult,
arg.getSteps());
ret.setNodeValue(Utils.asString(predResultBackList.size() > 0));
}
} else {
ret = arg;
}
newArgs.add(ret);
}
return newArgs.toArray();
} | 9 |
public static void sendPlayerToNewPlayerSpawn(BSPlayer player, boolean silent) {
if(!doesNewPlayerSpawnExist()){
player.sendMessage(Messages.SPAWN_DOES_NOT_EXIST);
return;
}
if(player==null){
return;
}
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream( b );
try {
out.writeUTF( "TeleportToLocation" );
out.writeUTF( player.getName() );
out.writeUTF( NewPlayerSpawn.getWorld() );
out.writeDouble( NewPlayerSpawn.getX() );
out.writeDouble( NewPlayerSpawn.getY() );
out.writeDouble( NewPlayerSpawn.getZ() );
out.writeFloat( NewPlayerSpawn.getYaw() );
out.writeFloat( NewPlayerSpawn.getPitch() );
} catch ( IOException e ) {
e.printStackTrace();
}
sendPluginMessageTaskSpawns( NewPlayerSpawn.getServer(), b );
if ( !player.getServer().getInfo().equals( NewPlayerSpawn.getServer() ) ) {
player.getProxiedPlayer().connect( NewPlayerSpawn.getServer() );
}
} | 4 |
public Graphics2D getGraphics(){
Window w = vc.getFullScreenWindow();
if(w != null){
BufferStrategy s = w.getBufferStrategy();
return (Graphics2D)s.getDrawGraphics();
}else{
return null;
}
} | 1 |
public boolean checkUserId(int uid) {
for(int i=1;i<=3;i++)
if( new User().checkUserId(uid))
{
return true;
}
return false;
} | 2 |
public static void abrirURL(String url) {
try {
URI uri = new URI(url);
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
if (desktop != null) {
desktop.browse(uri);
}
} catch (IOException | URISyntaxException ioe) {
JOptionPane.showMessageDialog(null,
"Error al abrir la ayuda, "+ioe.getMessage(),
"Aviso",
JOptionPane.ERROR_MESSAGE);
}
} | 3 |
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode head = null;
ListNode cur = null;
while (l1 != null || l2 != null) {
if (l1 == null) {
ListNode nc = new ListNode(l2.val);
cur.next = nc;
cur = nc;
l2 = l2.next;
} else if (l2 == null) {
ListNode nc = new ListNode(l1.val);
cur.next = nc;
cur = nc;
l1 = l1.next;
} else {
if (l1.val <= l2.val) {
if (cur == null) {
cur = new ListNode(l1.val);
head = cur;
} else {
ListNode nc = new ListNode(l1.val);
cur.next = nc;
cur = nc;
}
l1 = l1.next;
} else {
if (cur == null) {
cur = new ListNode(l2.val);
head = cur;
} else {
ListNode nc = new ListNode(l2.val);
cur.next = nc;
cur = nc;
}
l2 = l2.next;
}
}
}
return head;
} | 9 |
@Override
public void unInvoke()
{
final Physical affected=this.affected;
super.unInvoke();
if((affected instanceof Room)&&(this.unInvoked))
{
final Room R=(Room)affected;
final Room downR=R.getRoomInDir(Directions.DOWN);
if((downR!=null)
&&(R.roomID().length()==0)
&&(downR.roomID().length()>0)
&&(downR.getRoomInDir(Directions.UP)==R))
{
R.showHappens(CMMsg.MSG_OK_VISUAL, L("You climb down from the Crow`s Nest."));
CMLib.map().emptyRoom(R, downR, true);
for(int dir : Directions.CODES())
{
final Room airRoom=R.getRoomInDir(dir);
if(airRoom!=null)
{
CMLib.map().emptyRoom(airRoom, downR, true);
airRoom.destroy();
}
}
downR.rawDoors()[Directions.UP]=null;
downR.setRawExit(Directions.UP, null);
R.rawDoors()[Directions.DOWN]=null;
R.setRawExit(Directions.DOWN, null);
R.destroy();
downR.giveASky(0);
}
}
} | 8 |
public static Object getPrimaryKeyValue(Field f, Object obj)
{
try
{
if ( Proxy.isProxyClass (obj.getClass()))
{
try
{
return ((DeferedLoadMethodInterceptor) Proxy.getInvocationHandler(obj)).getpKey();
} catch (ClassCastException classCastException)
{
Logger.getLogger(XMLStoreSet.class.getName()).log(Level.SEVERE, null, classCastException);
return null;
}
}
return f.get(obj);
} catch (IllegalArgumentException ex)
{
Logger.getLogger(XMLStoreSet.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex)
{
Logger.getLogger(XMLStoreSet.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
} | 4 |
public void save(PrintWriter writer, String modifier)
{
try
{
if(parentAnimation == null)
{
writer.println(modifier + "Animation " + name);
writer.println(modifier + "Duration: " + duration + " frames");
}
else
{
writer.println(modifier + "Add Animation " + name + " at frame " + (frame == -1 ? 0 : frame));
writer.println(modifier + "Duration: " + duration + " frames");
}
if(hasSubAnimations())
{
writer.println(modifier + "SubAnimations");
writer.println(modifier + "{");
for(int i=0; i<subAnimations.size(); i++)
subAnimations.get(i).save(writer, modifier + "\t");
writer.println("}");
}
writer.println(modifier + "Poses");
writer.println(modifier + "{");
for(int i=0; i<poses.size(); i++)
poses.get(i).save(writer, modifier + "\t");
if(parentAnimation == null)
writer.println(modifier + "}");
else
writer.println(modifier + "};");
}
catch (Exception e)
{
e.printStackTrace();
}
} | 7 |
public void removeEdge( Vertex<T> v1, Vertex<T> v2 ) {
v1Pos = getVerticesIndexFor( v1 );
v2Pos = getVerticesIndexFor( v2 );
if ( v1Pos == -1 || v2Pos == -1 ) {
throw new IllegalArgumentException( "vertex not found" );
}
if ( this.adjMatrix[v1Pos][v2Pos] == 1 ) {
this.adjMatrix[v1Pos][v2Pos] = 0;
this.numberOfEdges--;
}
else {
throw new IllegalArgumentException( "edge not found" );
}
} | 3 |
public static void main(String[] args) throws Exception {
File indir = new File("/srv/haven/errors");
File outdir = new File("/srv/www/haven/errors");
Map<File, Report> reports = new HashMap<File, Report>();
Map<File, Exception> failed = new HashMap<File, Exception>();
for(File f : indir.listFiles()) {
if(f.getName().startsWith("err")) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(f));
try {
reports.put(f, (Report)in.readObject());
} finally {
in.close();
}
} catch(Exception e) {
failed.put(f, e);
}
}
}
OutputStream out;
out = new FileOutputStream(new File(outdir, "index.html"));
try {
makeindex(out, reports, failed);
} finally {
out.close();
}
for(File f : reports.keySet()) {
out = new FileOutputStream(new File(outdir, f.getName() + ".html"));
try {
makereport(out, reports.get(f));
} finally {
out.close();
}
}
} | 4 |
public VueMenu(CtrlAbstrait ctrlA) {
super(ctrlA);
initComponents();
VueAbstrait vueA = null;
this.ctrlM = new CtrlMenu(this, vueA);
} | 0 |
public RegImmInd(RegImmIndOp operation, Register sourceOperand, long immediateOffset, Register baseOperand) {
switch(sourceOperand.width()) {
case Byte:
if(immediateOffset < Byte.MIN_VALUE || immediateOffset > Byte.MAX_VALUE) {
throw new IllegalArgumentException("immediate operand does not fit into byte");
}
break;
case Word:
if(immediateOffset < Short.MIN_VALUE || immediateOffset > Short.MAX_VALUE) {
throw new IllegalArgumentException("immediate operand does not fit into word");
}
break;
case Long:
if(immediateOffset < Integer.MIN_VALUE || immediateOffset > Integer.MAX_VALUE) {
throw new IllegalArgumentException("immediate operand does not fit into double word");
}
break;
default:
// this case is always true by construction
}
this.operation = operation;
this.sourceOperand = sourceOperand;
this.baseOperand = baseOperand;
this.immediateOffset = immediateOffset;
} | 9 |
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(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
frmLogin dialog = new frmLogin(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} | 6 |
private void disableVoteButtons(JButton confirmButton) {
voteList.removeAll();
confirmButton.setVisible(false);
Enumeration<AbstractButton> allButtons = buttonGroup.getElements();
while (allButtons.hasMoreElements()) {
allButtons.nextElement().setVisible(false);
}
} | 1 |
public void marcarBoton(int numboton, Ficha ficha)
{
if(numboton==1)b1.setLabel(Character.toString(ficha.getFicha()));
if(numboton==2)b2.setLabel(Character.toString(ficha.getFicha()));
if(numboton==3)b3.setLabel(Character.toString(ficha.getFicha()));
if(numboton==4)b4.setLabel(Character.toString(ficha.getFicha()));
if(numboton==5)b5.setLabel(Character.toString(ficha.getFicha()));
if(numboton==6)b6.setLabel(Character.toString(ficha.getFicha()));
if(numboton==7)b7.setLabel(Character.toString(ficha.getFicha()));
if(numboton==8)b8.setLabel(Character.toString(ficha.getFicha()));
if(numboton==9)b9.setLabel(Character.toString(ficha.getFicha()));
} | 9 |
Tree decisionTreeLearning(List<List<Integer>> examples, List<Integer> attributes,
List<List<Integer>> parentExamples, boolean randImp) {
Tree tree;
// if examples is empty then return PLURALITY-VALUE(parent examples)
if (examples == null || examples.size() == 0) return new Tree(pluralityValue(parentExamples));
// else if all examples have the same classification then return the classification
else if (sameClassification(examples)) return new Tree(examples.get(0).get(examples.get(0).size() - 1));
// else if attributes is empty then return PLURALITY-VALUE(examples)
else if (attributes == null || attributes.size() == 0) return new Tree(pluralityValue(examples));
else {
// add a branch to tree with label (A = vk) and subtree subtree
int A; // the best tree
// A (best) ← argmaxa ∈ attributes IMPORTANCE(a, examples)
if (randImp) A = (int) randomImportance(attributes);
else A = (int) Math.round(gainImportance(attributes, examples));
// tree ← a new decision tree with root test A (best)
tree = new Tree(A);
attributes.remove((Integer) A);
// System.out.println(attributes.size());
// for each value vk of A (best) do
for (int i = 1; i < 3; i++) {
// exs ←{e : e∈examples and e.A = vk} {elements of examples with best = vk }
List<List<Integer>> exs = new ArrayList<>();
for (List<Integer> example : examples) {
if (example.get(A) == i) exs.add(example);
}
// subtree ← DECISION-TREE-LEARNING(exs, attributes − A, examples)
Tree subTree = decisionTreeLearning(exs, attributes, examples, randImp);
tree.addChild(i, subTree);
}
}
return tree;
} | 9 |
protected void endGameTimer() {
if (colorChanged == true) {
gameOverColor = Color.BLUE;
colorChanged = false;
} else {
gameOverColor = Color.RED;
colorChanged = true;
}
Graphics g = this.getGraphics();
drawSomebodyWon(g);
} | 1 |
public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
} | 6 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Sexo other = (Sexo) obj;
if (this.idSexo != other.idSexo && (this.idSexo == null || !this.idSexo.equals(other.idSexo))) {
return false;
}
return true;
} | 5 |
public static void println(String str) {
memo.append(str);
memo.append("\n");
} | 0 |
private double kernel(FeatureNode [] x, FeatureNode [] z) {
double ret = 0;
switch (model.params.kernel) {
case 0: //user defined
break;
case 1: //linear
ret = Kernel.kLinear(x, z);
break;
case 2: //polynomial
ret = Kernel.kPoly(x, z, model.params.a, model.params.b, model.params.c);
break;
case 3: //gaussian
ret = Kernel.kGaussian(x, z, model.params.a);
break;
case 4: //tanh
ret = Kernel.kTanh(x, z, model.params.a, model.params.b);
break;
}
return ret;
} | 5 |
public void visitPhiJoinStmt(final PhiJoinStmt stmt) {
if (stmt.target == from) {
stmt.target = (VarExpr) to;
((VarExpr) to).setParent(stmt);
} else {
final Iterator e = stmt.operands.keySet().iterator();
while (e.hasNext()) {
final Block block = (Block) e.next();
if (stmt.operandAt(block) == from) {
stmt.setOperandAt(block, (Expr) to);
((Expr) to).setParent(stmt);
return;
}
}
stmt.visitChildren(this);
}
} | 3 |
public static void main(String[] args) {
rosterDB = readCSV ("/home/arno/workspace/CampPlaner/data/roster.csv");
System.out.println (rosterDB);
try {
System.out.println ("saving...");
rosterDB.write ("rosterdb.xml");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Serializer serializer = new Persister();
File file = new File("rosterdb.xml");
try {
System.out.println ("loading...");
rosterDB = serializer.read(RosterDB.class, file);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println (rosterDB);
} | 2 |
public boolean init()
{
// dump command line arguments
ExampleUtil.dumpCommandArgs();
// read config
boolean debug = CommandLine.booleanVariable("debug");
if (debug)
{
// Enable debug logging
Logger logger = Logger.getLogger("com.reuters.rfa");
logger.setLevel(Level.WARNING);
Handler[] handlers = logger.getHandlers();
if (handlers.length == 0)
{
Handler handler = new ConsoleHandler();
handler.setLevel(Level.WARNING);
logger.addHandler(handler);
}
for (int index = 0; index < handlers.length; index++)
handlers[index].setLevel(Level.WARNING);
}
Context.initialize();
// Create a Session
String sessionName = CommandLine.variable("session");
_session = Session.acquire(sessionName);
if (_session == null)
{
System.out.println("Could not acquire session.");
Context.uninitialize();
return false;
}
System.out.println("RFA Version: " + Context.getRFAVersionInfo().getProductVersion());
// Create an Event Queue
_eventQueue = EventQueue.create("myEventQueue");
// Create a OMMPool.
_pool = OMMPool.create();
// Create an OMMEncoder
_encoder = _pool.acquireEncoder();
_encoder.initialize(OMMTypes.MSG, 5000);
// Initialize client for login domain.
_loginClient = new PostLoginClient(this);
// Initialize item manager for item domains
_itemManager = new PostItemManager(this);
// Create an OMMConsumer event source
_ommConsumer = (OMMConsumer)_session.createEventSource(EventSource.OMM_CONSUMER,
"myOMMConsumer", true);
// Application may choose to down-load the enumtype.def and RWFFldDictionary
// This example program loads the dictionaries from file only.
String fieldDictionaryFilename = CommandLine.variable("rdmFieldDictionary");
String enumDictionaryFilename = CommandLine.variable("enumType");
try
{
GenericOMMParser.initializeDictionary(fieldDictionaryFilename, enumDictionaryFilename);
}
catch (DictionaryException ex)
{
System.out.println("ERROR: Unable to initialize dictionaries.");
System.out.println(ex.getMessage());
if (ex.getCause() != null)
System.err.println(": " + ex.getCause().getMessage());
cleanup(-1);
return false;
}
OMMErrorIntSpec errIntSpec = new OMMErrorIntSpec();
_errorHandle = _ommConsumer.registerClient(_eventQueue, errIntSpec, _loginClient, null);
if (_itemManager.initialize() == false)
return false;
// Send login request
_loginClient.sendRequest();
return true;
} | 7 |
public String generate(List<String> joinTables, List<String> joinTableIds)
{
StringBuilder sb = new StringBuilder();
List<String> added = new ArrayList<String>();
for (int x = 0; x < joinTables.size(); x++)
{
if (!added.contains(joinTableIds.get(x)))
{
added.add(joinTableIds.get(x));
if (sb.length() > 0)
{
sb.append(" ");
sb.append(adapter.getJoinKeyword());
sb.append(" ");
}
JoinDescriptor jd = getJoinDescriptorForTable(joinTables.get(x), joinTableIds.get(x));
if (jd != null)
{
sb.append(jd.toString());
}
else
{
sb.append(joinTables.get(x));
sb.append(" AS ");
sb.append(joinTableIds.get(x));
}
}
}
return sb.toString();
} | 4 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UsuarioMapeo other = (UsuarioMapeo) obj;
if ((this.login == null) ? (other.login != null) : !this.login.equals(other.login)) {
return false;
}
if ((this.password == null) ? (other.password != null) : !this.password.equals(other.password)) {
return false;
}
if (this.admin_rol != other.admin_rol && (this.admin_rol == null || !this.admin_rol.equals(other.admin_rol))) {
return false;
}
return true;
} | 9 |
public RobbEffect(BattlePvP battle, boolean defender) {
super(battle, defender);
if(defender){
//suppress the siege machines of the battle looser
battle.getAttTroops()[3]=0;
// if there is no more troops, don't do anything
if(battle.getAttTroops()[0]>0 || battle.getAttTroops()[1]>0 || battle.getAttTroops()[2]>0){
battle.setState(Battle.BATTLE_CARD_EFFECT_END_BATTLE);
}else finish=true;
}else{
//suppress the siege machines of the battle looser
battle.getDefTerritory().getTroup().rmToop(0,0,0,battle.getDefTerritory().getTroup().getTroops()[3]);
// if there is no place to withdraw or no more troops, don't do anything
if(battle.getDefTerritory().canWithdraw() || battle.getDefTerritory().getTroup().getEffectif()>0){
battle.setState(Battle.BATTLE_CARD_EFFECT_END_BATTLE);
}else finish=true;
}
} | 6 |
@Override
public boolean isValidClassDivider(MOB killer, MOB killed, MOB mob, Set<MOB> followers)
{
if((mob!=null)
&&(mob!=killed)
&&(!mob.amDead())
&&((!mob.isMonster())||(!mob.charStats().getMyRace().racialCategory().endsWith("Elemental")))
&&((mob.getVictim()==killed)
||(followers.contains(mob))
||(mob==killer)))
return true;
return false;
} | 8 |
@Override
public Tipo validarSemantica() throws Exception {
Tipo izq,der;
izq=izquierdo.validarSemantica();
der=derecho.validarSemantica();
if (izq instanceof TipoInt || der instanceof TipoFloat){
if (der instanceof TipoInt || der instanceof TipoFloat ){
return new TipoBooleano();
}
else{
throw new Exception("Error Semantico no se puede comparar un Tipo Int o Float con un Tipo "+ der.toString());
}
}
else{
throw new Exception("Error Semantico no se puede comparar un Tipo Int o Float con un Tipo "+ der.toString());
}
} | 4 |
public BufferedImage parseUserSkin(BufferedImage var1) {
if(var1 == null) {
return null;
} else {
this.imageWidth = 64;
this.imageHeight = 32;
BufferedImage var2 = new BufferedImage(this.imageWidth, this.imageHeight, 2);
Graphics var3 = var2.getGraphics();
var3.drawImage(var1, 0, 0, (ImageObserver)null);
var3.dispose();
this.imageData = ((DataBufferInt)var2.getRaster().getDataBuffer()).getData();
this.func_884_b(0, 0, 32, 16);
this.func_885_a(32, 0, 64, 32);
this.func_884_b(0, 16, 64, 32);
boolean var4 = false;
int var5;
int var6;
int var7;
for(var5 = 32; var5 < 64; ++var5) {
for(var6 = 0; var6 < 16; ++var6) {
var7 = this.imageData[var5 + var6 * 64];
if((var7 >> 24 & 255) < 128) {
var4 = true;
}
}
}
if(!var4) {
for(var5 = 32; var5 < 64; ++var5) {
for(var6 = 0; var6 < 16; ++var6) {
var7 = this.imageData[var5 + var6 * 64];
if((var7 >> 24 & 255) < 128) {
var4 = true;
}
}
}
}
return var2;
}
} | 8 |
public void auto()
{
switch(nivel)
{
case 1:
break;
case 2:
if( defesa() ) return;
break;
case 3:
if( defesa() ) return;
if( ataque() ) return;
break;
default:
break;
}
random();
} | 6 |
public int increaseHandicap(int minX, int minY, int ex, int ey) {
if (ex > 90 && ex < 90 + minX) {
if (ey > 210 && ey < 210 + minY) {
if (handicap < 9) {
handicap++;
return handicap;
}
}
}
return handicap;
} | 5 |
public static long countSplitInversionsAndMerge(int start, int end, int leftStart, int leftEnd, int rightStart, int rightEnd) {
int subArray1[] = new int[leftEnd - leftStart + 1];
int subArray2[] = new int[rightEnd - rightStart + 1];
int count = 0;
for (int i = leftStart; i <= leftEnd; i++) {
subArray1[count++] = a[i];
}
count = 0;
for (int i = rightStart; i <= rightEnd; i++) {
subArray2[count++] = a[i];
}
// merge and count inversions
int leftPointer = 0, rightPointer = 0;
long inversions = 0;
for (int i = start; i <= end; i++) {
if(leftPointer >= subArray1.length) {
a[i] = subArray2[rightPointer++];
}else if(rightPointer >= subArray2.length) {
a[i] = subArray1[leftPointer++];
}else if (subArray1[leftPointer] <= subArray2[rightPointer]) {
a[i] = subArray1[leftPointer++];
}else if(subArray1[leftPointer] > subArray2[rightPointer]) {
for (int j = leftPointer; j < subArray1.length; j++) {
//System.out.println(subArray1[j] + "," + subArray2[rightPointer]);
}
a[i] = subArray2[rightPointer++];
inversions = inversions + subArray1.length - leftPointer;
}
}
return inversions;
} | 8 |
public void run() {
if (client_socket != null && os != null && is != null) {
try {
String responseLine;
while ((responseLine = is.readLine()) != null) {
System.out.println(responseLine);
if (client_socket.isClosed())
break;
os.println(inputLine.readLine());
}
os.close();
is.close();
client_socket.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Connection lost...",
"ERROR", JOptionPane.ERROR_MESSAGE);
System.out.println("Connection lost...");
}
}
} | 6 |
@Override
public String toString() {
String result = "Student [name=" + getName() + ", average=" + getAverage()
+ ", program=" + getProgram() + ", universities=[";
if (this.universityOne != null)
result += this.universityOne + ": " + (this.universityOneAccept ? "accepted" : "rejected") ;
if (this.universityTwo != null)
result += ", " + this.universityTwo + ": " + (this.universityTwoAccept ? "accepted" : "rejected") ;
if (this.universityThree != null)
result += ", " + this.universityThree + ": " + (this.universityThreeAccept ? "accepted" : "rejected") ;
result += "]]";
return result;
} | 6 |
public void handleDamage(EnemyClass enem)
{
if(enem.getWeapon().size() > 0)
{
for(int i = 0; i < enem.getWeapon().size(); i++)
{
if(enem.getGun().getBulletSize() == 0)
{
//do Nothing
}
else
{
if(enem.getGun().getProjectile(i).intersects(poly))
{
enem.getGun().getBulletArray().remove(i);
health = health -= 15;
}
}
}
}
} | 4 |
public static ListNode rotateRight(ListNode head, int n) {
if (head == null)
return null;
if (n == 0)
return head;
int length = 1;
ListNode countLength = head;
while (countLength.next != null) {
length++;
countLength = countLength.next;
}
if (n % length == 0)
return head;
int newHeadPos = length - (n % length);
ListNode newTail = head;
ListNode newHead = head;
ListNode tail = head;
int i = 0;
while (i < newHeadPos && newHead.next != null) {
newHead = newHead.next;
i++;
}
i = 0;
while (i < newHeadPos - 1 && newTail.next != null) {
newTail = newTail.next;
i++;
}
while (tail.next != null) {
tail = tail.next;
}
tail.next = head;
newTail.next = null;
return newHead;
} | 9 |
public PagePanel(Page page) {
this.page = page;
setLayout(null);
if (page.getFile() != null) {
try {
Scanner scanner = new Scanner(page.getFile());
StringBuilder contentBuilder = new StringBuilder();
while (scanner.hasNextLine()) {
contentBuilder.append(scanner.nextLine());
contentBuilder.append('\n');
}
scanner.close();
JLabel content = new JLabel(contentBuilder.toString());
content.setHorizontalAlignment(page.isCover() ? SwingConstants.CENTER : SwingConstants.LEFT);
content.setVerticalAlignment(page.isCover() ? SwingConstants.CENTER : SwingConstants.TOP);
content.setForeground(page.isCover() ? Color.WHITE : Color.BLACK);
content.setBounds(16, 16, 448, 608);
add(content);
} catch (FileNotFoundException exception) {
exception.printStackTrace();
}
}
} | 6 |
public void mmousedown(Coord mc, int button) {
Coord tc = mc.div(MCache.tileSize);
if(ol != null)
ol.destroy();
ol = map.new Overlay(tc, tc, 1 << 17);
sc = tc;
dm = true;
ui.grabmouse(ui.mapview);
} | 1 |
public static boolean hasCycle(ListNode head) {
if(null==head) return false;
ListNode pointerOne=head.next;
if(null==pointerOne) return false;
ListNode pointerTwo=head.next.next;
while (pointerOne!=null&&pointerTwo!=null&&pointerOne!=pointerTwo){
pointerOne=pointerOne.next;
if(null==pointerTwo.next) break;
pointerTwo=pointerTwo.next.next;
}
if(null==pointerOne||null==pointerTwo){
return false;
}
if(pointerOne==pointerTwo){
return true;
}
return false;
} | 9 |
public String nextCDATA() throws JSONException {
char c;
int i;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
if (end()) {
throw syntaxError("Unclosed CDATA");
}
sb.append(c);
i = sb.length() - 3;
if (i >= 0 && sb.charAt(i) == ']' &&
sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') {
sb.setLength(i);
return sb.toString();
}
}
} | 6 |
public void setUpText(String text, MinuetoFont font, MinuetoColor color, boolean antiAliased) {
/* The hardest part of build the image with the text string is
* figuring out the size of the string itself. **/
if (text == null) new NullPointerException();
if (font == null) new NullPointerException();
if (color == null) new NullPointerException();
BufferedImage bufferedImage;
Graphics2D graphics2D;
FontMetrics fontMetrics;
int width; /* Width of our image */
int height; /* Height of our image */
/* To calculate the size of the string, we need to get information
* about the screen (since the string size depends on the DPI
* resolution of the monitor). To get this information, we create
* a temporary 1x1 accelerated image and get the font metric
* information from the graphic 2D image. */
bufferedImage = ImageTools.createImage( 1, 1 );
graphics2D = bufferedImage.createGraphics();
/* Before getting the font metric, we need to set the font on the
* grpahic 2D object. */
graphics2D.setFont(font.getFont());
/* Enable or disable antialiasing. */
if (antiAliased == true) {
graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
} else {
graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
/* Ah! now we have the font metrics! */
fontMetrics = graphics2D.getFontMetrics();
/* It might seem simple, but figuring out that these 2 functions exist
* was insanely hard. The Java font engine can be quite complicated. */
height = fontMetrics.getHeight();
width = fontMetrics.stringWidth(text);
/* Since we should never create an image of width 0. */
if (width == 0) { width = 1; }
/* So now we know the proper size of the image. */
bufferedImage = ImageTools.createImage( width, height );
graphics2D = bufferedImage.createGraphics();
/* Set the font and the color. */
graphics2D.setFont(font.getFont());
graphics2D.setColor(color.getAWTColor());
/* Enable or disable antialiasing. */
if (antiAliased == true) {
graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
} else {
graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
/* Draw the string on the buffer. */
graphics2D.drawString(text, 0, fontMetrics.getAscent());
/* Set up the MinuetoImage */
super.setUpImage(bufferedImage);
} | 6 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AbstractQualifiedMetadata other = (AbstractQualifiedMetadata) obj;
if (qualifiedName == null) {
if (other.qualifiedName != null)
return false;
} else if (!qualifiedName.equals(other.qualifiedName))
return false;
return true;
} | 6 |
public void computeSALSA(int nIterations) {
for(int iter=0; iter < nIterations; iter++) {
// Hubs: sum of authority-neighbors values divided by their degree
for(SalsaVertex hub: hubs.values()) {
double nbSum = 0.0;
// Update the degree because not all authorities were selected
int degree = 0;
for(int authId : hub.neighbors) {
SalsaVertex auth = authorities.get(authId);
if (auth != null) {
nbSum += auth.value / auth.degree;
degree++;
}
}
hub.value = nbSum;
hub.degree = degree;
}
// Authorities: push from authority side.
// First: set values to zero
for(SalsaVertex auth: authorities.values()) {
auth.value = 0;
}
// Then, push hubs values to their auths
for(SalsaVertex hub: hubs.values()) {
double myContribution = hub.value / hub.degree;
for(int authId : hub.neighbors) {
SalsaVertex auth = authorities.get(authId);
if (auth != null) {
auth.value += myContribution;
}
}
}
}
} | 8 |
void damagePlayer(int hitpoints, AIConnection dealingPlayer){
if(health <= 0){
Debug.warn("Player is already dead.");
return;
}
Debug.stub("'" + this.username + "' received " + hitpoints
+ " damage from '" + dealingPlayer.username + "'!");
health -= hitpoints;
if(!(dealingPlayer.username.equals(this.username))){
dealingPlayer.givePoints(hitpoints); // damaged user other than self, award points
}
if(health <= 0){
Debug.game(this.username + " got killed by " + dealingPlayer.username);
if(!(dealingPlayer.username.equals(this.username))){
dealingPlayer.givePoints(20); // 20 bonus points for killing someone
}
score -= 40;
health = 0;
hasToPass = true;
needsRespawn = true;
}
} | 4 |
public void visit_l2f(final Instruction inst) {
stackHeight -= 2;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 1;
} | 1 |
public CtrlComptesRendus getCtrl() {
return ctrlCR;
} | 0 |
public void mouseEntered(MouseEvent mouseEvent) {
Iterator<PComponent> it = components.iterator();
while (it.hasNext()) {
PComponent comp = it.next();
if (shouldHandleMouse) {
if (comp.shouldHandleMouse())
comp.mouseEntered(mouseEvent);
}
else {
if (comp instanceof PFrame) {
for (PComponent component : ((PFrame) comp).getComponents())
if (component.forceMouse())
component.mouseEntered(mouseEvent);
}
else if (comp.forceMouse())
comp.mouseEntered(mouseEvent);
}
}
} | 7 |
public void setField(Field f) {
if (neighbours == null)
neighbours=new ArrayList<Road>();
if (closeNeighbours == null)
closeNeighbours=new ArrayList<Road>();
this.field = f;
field.setTower(this);
for (Tile tl : field.getNeighbours()) {
if (tl.getClass() == Road.class) {
neighbours.add((Road) tl);
closeNeighbours.add((Road) tl);
}
for (Tile t : tl.getNeighbours()) {
if (t.getClass() == Road.class)
neighbours.add((Road) t);
}
}
} | 6 |
public void testMinus_int() {
Days test2 = Days.days(2);
Days result = test2.minus(3);
assertEquals(2, test2.getDays());
assertEquals(-1, result.getDays());
assertEquals(1, Days.ONE.minus(0).getDays());
try {
Days.MIN_VALUE.minus(1);
fail();
} catch (ArithmeticException ex) {
// expected
}
} | 1 |
public String[] resolveColumns(String[] columns) throws SQLException {
String[] cols;
if (columns.length == 1 && columns[0].equals("*")) {
cols = new String[fields.length];
for (int i=0;i<fields.length;i++) {
cols[i] = fields[i].name();
}
} else {
cols = new String[columns.length];
for (int i=0; i<columns.length;i++) {
Field field = findField(columns[i]);
if (field == null) throw new SQLException("Unknown field '" + columns[i] + "' in table: '" + name + "'");
cols[i] = columns[i];
}
}
return cols;
} | 5 |
private void copySelectedText() {
Point selection = editor.getSelection();
System.out.println("copy-" + (System.currentTimeMillis() - lastClipboardTime));
if (selection.x < selection.y && System.currentTimeMillis() - lastClipboardTime > 400) {
lastClipboardText = (String)clipboard.getContents(TextTransfer.getInstance());
lastClipboardTime = System.currentTimeMillis();
//System.out.println("get clipboard before copy: '" + lastClipboardText + "'");
//System.out.println("save last clipboard time");
editor.copy();
currentClipboardText = (String)clipboard.getContents(TextTransfer.getInstance());
//System.out.println("get clipboard after copy: '" + currentClipboardText + "'");
}
} | 2 |
public static void warWithTwoCardsLeft(Hand p1, Hand p2, Hand extras)
{
int flag = 0;
// draw facedown cards
Card p1_facedown = p1.drawCard();
Card p2_facedown = p2.drawCard();
// add facedown cards to extras pile
extras.addCard(p1_facedown);
extras.addCard(p2_facedown);
Card p1_battleCard = p1.drawCard(); // face-up card
Card p2_battleCard = p2.drawCard(); // face-up card
int compareVal = p1_battleCard.compareRank(p2_battleCard);
if(compareVal > 0) // player 1's card is higher rank
{
p1.addCard(p1_battleCard);
p1.addCard(p2_battleCard);
while(!extras.isEmpty())
p1.addCard(extras.drawCard());
if(p2.isEmpty()) // set flag to -1 if player 2's deck is empty
flag = -1;
}
else if(compareVal < 0) // Player 2's card is higher rank
{
p2.addCard(p1_battleCard);
p2.addCard(p2_battleCard);
while(!extras.isEmpty())
p1.addCard(extras.drawCard());
if(p1.isEmpty()) // set flag to -1 if player 1's deck is empty
flag = -1;
}
else // War!
{
if(flag != -1)
{
System.out.println("ComingOutFromTwoCardsOnlyWar");
war(p1, p2, extras);
}
}
} | 7 |
private void changeRanges() {
boolean flag = false;
try {
int x = Integer.parseInt(a.getText());
if (x <= 0)
throw new IllegalArgumentException();
flag = true;
int y = Integer.parseInt(b.getText());
if (y <= 0)
throw new IllegalArgumentException();
if (x != drawingPanel.getXRange()){
ArrayList<Point2D[]> points = new ArrayList<Point2D[]>();
for (int i = 0; i < graphs.size(); i++){
points.add(graphs.get(i).getPoints(-x, x, 1200));
}
drawingPanel.setGraphs(points);
drawingPanel.setXRange(x);
}
if (y != drawingPanel.getYRange()){
drawingPanel.setYRange(y);
}
} catch (Exception ex){
new MessageDialog(this, "Invalid range\nPlease check your input!", MessageDialog.ERROR).setVisible(true);
a.setText(drawingPanel.getXRange() + "");
b.setText(drawingPanel.getYRange() + "");
if (flag){
b.requestFocus();
} else {
a.requestFocus();
}
}
} | 7 |
public boolean isOptOut() {
synchronized (optOutLock) {
try {
// Reload the metrics file
configuration.load(getConfigFile());
} catch (IOException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
} catch (InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
}
return configuration.getBoolean("opt-out", false);
}
} | 4 |
public void avaliarCodigoFonte() {
try {
//Compilação do código-fonte
String nameCommand = "gcc " + nameTestFile + ".c" + " -lcunit -o " + nameTestFile;
Process process = Runtime.getRuntime().exec(nameCommand);
BufferedReader entrada = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String resultado = "";
String linha = null;
while ((linha = entrada.readLine()) != null) {
resultado += linha;
}
entrada.close();
if (!resultado.equals("")) {
javax.swing.JOptionPane.showMessageDialog(null, "Tem erro de compilação");
hasCompileErrors = true;
if (countAttempts < 3) {
exerciseMark -= 0.5;
countAttempts += 1;
} else {
endOfAttempts = true;
}
} else {
assertProgram();
javax.swing.JOptionPane.showMessageDialog(null, "Nota testes de unidade : " + testMark);
if (testMark == 0) {
exerciseMark = 0;
} else {
//calculoDasMetricasEComparacaoComAsDaRespostaModelo();
calcExerciseMark();
}
javax.swing.JOptionPane.showMessageDialog(null, "Nota Exercício : " + exerciseMark);
javax.swing.JOptionPane.showMessageDialog(null, "Exercicio enviado com sucesso. Vamos fazer o próximo exercicio");
hasCompileErrors = false;
}
testFile.delete();
metricsFile.delete();
modelResponseFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
} | 5 |
public String getMergedfile(SmartlingKeyEntry updateEntry) throws IOException, JSONException {
// for each locale (for the specific project) , get translated file from smartling
updateEntry.setLocale("es");
String responseHtml = SmartlingRequestApi.getFileFromSmartling(updateEntry.getFileUri(), updateEntry.getProjectId(), updateEntry.getLocale());
if (responseHtml.contains("VALIDATION_ERROR"))
return responseHtml;
// Get List of updated Strings from App Engine DB
List<SmartlingKeyEntry> dbFile = getTranslationFromDb(datastore, updateEntry.getProjectId(), updateEntry.getLocale(), updateEntry.getFileUri());
if (dbFile.isEmpty()) {
log.info("No Updated Strings for ProjectId:" + updateEntry.getProjectId() + ";File:" + updateEntry.getFileUri() + ";Locale:" + updateEntry.getLocale());
return responseHtml;
}
// build map from Json (smarling)
HashMap<String, Object> smartlingFile = new ObjectMapper().readValue(responseHtml, HashMap.class);
for (int i = 0; i < dbFile.size(); i++) {
String keyInDb = dbFile.get(i).getKey();
String updatedEngVal = dbFile.get(i).getUpdatedEngVal();
String tranlatedVal = dbFile.get(i).getTranslationInLocale();
//String currentValInLocaleFile = (String) smartlingFile.get(keyInDb);
String currentValInLocaleFile = "new orgenize images";
if (currentValInLocaleFile == null || currentValInLocaleFile.isEmpty()) {
String error = "Key:" + keyInDb + " Not found in ProjectId:" + updateEntry.getProjectId() + ", But it's on DB. should we remove from DB???";
log.severe(error);
continue;
}
if (currentValInLocaleFile.equals(updatedEngVal)) {
String error = "Key:" + keyInDb + "found in ProjectId:" + updateEntry.getProjectId() + " But Still not translated in locale:" + updateEntry.getLocale() + ".value=" + currentValInLocaleFile;
smartlingFile.put(keyInDb,tranlatedVal);
log.info(error);
continue;
}
if (!currentValInLocaleFile.equals(updatedEngVal)) {
String error = "Key:" + keyInDb + "found in ProjectId:" + updateEntry.getProjectId() + " re-translated in locale:" + updateEntry.getLocale() + ".value=" + currentValInLocaleFile;
log.info(error);
// remove from DB !!!
removeKeyFromDb(datastore, updateEntry.getProjectId(), updateEntry.getLocale(), updateEntry.getFileUri(), keyInDb);
continue;
}
}
JSONObject returnJson = new JSONObject();
Iterator it = smartlingFile.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
if (!pairs.getKey().toString().equalsIgnoreCase("smartling"))
returnJson.put(pairs.getKey().toString() , pairs.getValue().toString());
}
return returnJson.toString();
} | 9 |
public void GetInput() {
if (Keyboard.isKeyDown(Keyboard.KEY_W))
Move(0, -4);
if (Keyboard.isKeyDown(Keyboard.KEY_S))
Move(0, 4);
if (Keyboard.isKeyDown(Keyboard.KEY_D))
Move(-4, 0);
if (Keyboard.isKeyDown(Keyboard.KEY_A))
Move(4, 0);
} | 4 |
public Wave18(){
super();
MobBuilder m = super.mobBuilder;
for(int i = 0; i < 330; i++){
if(i % 17 == 0)
add(m.buildMob(MobID.JIGGLYPUFF));
else if(i % 27 == 0)
add(m.buildMob(MobID.KADABRA));
else if(i % 5 == 0)
add(m.buildMob(MobID.PIDGEY));
else if (i % 4 == 0)
add(m.buildMob(MobID.MANKEY));
else if(i % 3 == 0)
add(m.buildMob(MobID.MEOWTH));
else if(i % 2 == 0)
add(m.buildMob(MobID.EKANS));
else
add(m.buildMob(MobID.VULPIX));
}
} | 7 |
public MultipartFile getFile() {
return file;
} | 0 |
private short parseTLVLength(byte[] data, short dataOffset, short[] result) {
if (data[dataOffset] == (byte) 0x81) {
result[0] = data[(short) (dataOffset + 1)];
return (short) (dataOffset + 2);
}
else {
if (data[dataOffset] == (byte) 0x82) {
result[0] = Util.makeShort(data[(short) (dataOffset + 1)], data[(short)(dataOffset + 2)]);
return (short) (dataOffset + 3);
}
else { ISOException.throwIt((short) (ISO7816.SW_WRONG_DATA + 2)); }
}
return dataOffset;
} | 2 |
public static void main(String[] args) {
Motor testMotor = new Motor();
boolean goON = true;
while (goON) {
System.out
.println("Input RPM (1=49 2=50 ...) or simply Return to continue");
int read = 0;
try {
read = System.in.read();
/** lol at flush */
System.in.skip(System.in.available());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (read != 10) {
testMotor.setPPMUnbounded(read * 10);
}
testMotor.update();
System.out.println("Motor RPM: " + testMotor.getCurrentRPM());
System.out.println("Byte read: " + read);
}
} | 3 |
private void selectPiece(Point p)
{
chosenPiece=null;
possibleMoves=null;
if(!myBoard.isOnBoard(p))//it isn't on the board
{
return;//chosenPiece and possible moves should be null
}
Piece thePiece = myBoard.getPiece(p);
if(thePiece==null)
{
return;//if the point doesn't have any piece in it, then chosenPiece and possible moves should be null
}
if(thePiece.isWhite==whitesTurn)//the piece chosen was the correct color
{
chosenPiece=thePiece;
}else
{
return;
}
possibleMoves=thePiece.possibleMoves();
if(thePiece instanceof King)
{
if(!thePiece.hasMoved())//the king hasn't moved yet, check if we can castle it
{
checkIfCanCastle();
}
}
//check if en passant is a legal move, and if it is, then add it to the list of possible moves
if(thePiece instanceof Pawn)
{
addPossibleEnPassantMoves(p);
}
} | 6 |
public static void insertUtilisateur(int idfonction, int idville, String nom, String prenom, String identifiant, String password) throws SQLException {
String query;
try {
query = "INSERT INTO UTILISATEUR (ID_FONCTION,ID_VILLE,UTILNOM,UTILPRENOM,IDENTIFIANT,PASSWORD) VALUES (?,?,?,?,?,?) ";
PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query);
pStatement.setInt(1, idfonction);
pStatement.setInt(2, idville);
pStatement.setString(3, nom);
pStatement.setString(4, prenom);
pStatement.setString(5, identifiant);
pStatement.setString(6, password);
pStatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(RequetesUtilisateur.class.getName()).log(Level.SEVERE, null, ex);
}
} | 1 |
private boolean isRepeatSubmit(HttpServletRequest request) {
String serverToken = (String) request.getSession(false).getAttribute(SUBMIT_TOKEN_NAME);
if (serverToken == null) {
return true;
}
String clinetToken = request.getParameter(SUBMIT_TOKEN_NAME);
if (clinetToken == null) {
return true;
}
if (!serverToken.equals(clinetToken)) {
return true;
}
return false;
} | 3 |
@Override
public void paint( Graphics2D g ) {
if( selection != null && selection.isSelected() ) {
g.setColor( color );
Rectangle bounds = item.getBoundaries();
int x = bounds.x-1;
int y = bounds.y-1;
int w = bounds.width+1;
int h = bounds.height+1;
for(int i = 0; i < thickness; i++ ){
g.drawRect( x, y, w, h );
x--;
y--;
w += 2;
h += 2;
}
}
} | 3 |
public TiarUserMessage tiarUserMessageDecode(String enc)
throws JSONException {
JSONObject obj = new JSONObject(enc);
TiarUserMessage TiarMessage = new TiarUserMessage();
JSONArray JArray = obj.getJSONArray(("GameBoard"));
int[] array = new int[9];
for (int i = 0; i < array.length; i++) {
array[i] = JArray.getInt(i);
}
TiarMessage.Gameboard = array;
TiarMessage.HasWon = obj.getInt("HasWon");
TiarMessage.IsDraw = obj.getInt("IsDraw");
TiarMessage.isValid = obj.getInt("IsValid");
return TiarMessage;
} | 1 |
private void startClientMonitor(){
while(noStopRequested){
try {
if(this.timeOut > 0){// 超时阀值
Iterator<Object> it = clients.keySet().iterator();
while(it.hasNext()){
Object key = it.next();
Client client = clients.get(key);
if(!client.isReadDataFlag()){// 超时没有收到数据
client.close();// 关闭连接
clients.remove(key);// 从映射表中删除连接
}else{
client.setReadDataFlag(false);// 将读取数据标识设置为false
}
}
this.clientMonitor.sleep(this.timeOut * 60 * 1000);// 暂停10分钟
}
} catch (Exception e) {
e.printStackTrace();
}
}
} | 5 |
public void update(double deltaTime){
if(animate){
// Perform sprite animation:
currentTime+=deltaTime;
// If the time has passed time for next frame:
if(currentTime > frameTime){
// Find out how many frames have passed in this time:
float frameAdvance = (float) Math.floor(currentTime/frameTime);
// If this is greater than max frames, loop it around (use modulus to get real frame advance)
int actualFrameAdvance = (int)frameAdvance%framesMap.size();
// Set the frame to the correct frame according to actualFrameAdvance (use modulus to take into account looping past end)
frame = (actualFrameAdvance+frame)%framesMap.size();
// Carry over remaining time left:
currentTime = currentTime%frameTime;
}
// Perform rotation:
rz += (zRotationPerSecond/1000f)*deltaTime;
// keep rz to within 0->360
rz = (360+rz)%360;
}
// Perform a specific rotation (will be called from performRotation() method):
if(performRotation){
// If this image is not animated, have to do the rotation in here:
if(!animate){
// Perform rotation:
rz += (zRotationPerSecond/1000f)*deltaTime;
// keep rz to within 0->360
rz = (360+rz)%360;
}
rotationSinceStart+=(Math.abs(zRotationPerSecond)/1000f)*deltaTime;
if(rotationSinceStart>rotationNeeded){
rz = rotationTarget;
zRotationPerSecond = 0;
rotationSinceStart = 0;
performRotation = false;
}
}
// Perform a scale operation:
if(performScaling){
// scaleTarget is how much scale needs to be increased by.
float scaleChange = (float)((deltaTime/1000)/timeToScale)*scaleChangeNeeded;
// Check to see if scale needs to be decreased or increased:
if(getScale()<=scaleTarget){
setScale(getScale() + scaleChange);
if(getScale()>=scaleTarget){
setScale(scaleTarget);
performScaling = false;
}
}else{
setScale(getScale() + scaleChange);
if(getScale()<=scaleTarget){
setScale(scaleTarget);
performScaling = false;
}
}
}
} | 9 |
public void updateType(int id, String string) {
type = string;
if(string == "Blank") {
updateImage(Database_Tiles.tiles[id], ImageLoader.blank);
}
if(string == "Field") {
updateImage(Database_Tiles.tiles[id], ImageLoader.field);
}
if(string == "Forest") {
updateImage(Database_Tiles.tiles[id], ImageLoader.forest);
}
if(string == "Industrial") {
updateImage(Database_Tiles.tiles[id], ImageLoader.in1);
}
if(string == "Commercial") {
updateImage(Database_Tiles.tiles[id], ImageLoader.cm1);
}
if(string == "Residential") {
updateImage(Database_Tiles.tiles[id], ImageLoader.rs1);
}
} | 6 |
private void updateStateTellCreator(List<Keyword> keywords, List<String> terms) {
//We should have come here by a keyword jump and the recipe shouldve been passed or set
if (keywords != null && !keywords.isEmpty()) {
for (Keyword kw : keywords) {
if (kw.getKeywordData().getType() == KeywordType.RECIPE) {
currRecipe = new Recipe((RecipeData)kw.getKeywordData().getDataReference().get(0));
return;
}
}
}
//If not, the recipe should've already been set, if not, we need a recipe Name.
if (currRecipe == null || currRecipe.getRecipeData() == null) {
getCurrentDialogState().setCurrentState(RecipeAssistance.RA_WAITING_FOR_RECIPE_NAME);
return;
}
if (keywords == null || keywords.isEmpty() && currRecipe != null) {
DialogManager.giveDialogManager().setInErrorState(true);
}
} | 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.