text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public boolean isOfSameType(Type t) {
if (t == null)
return true;
if ((t.isConstant || isConstant) && !t.actualType.equals("nil") && !actualType.equals("nil")) {
String tbaseType = t.actualType;
String baseType = actualType;
if (dimensions != null) {
baseType = actualType.split("\\[")[0];
}
if (t.dimensions != null)
tbaseType = t.actualType.split("\\[")[0];
return tbaseType.equals(baseType);
}
return t.actualType.equals("nil") || actualType.equals("nil") || getName().equals(t.getName());
} | 9 |
public void ParseSource(String source)
{
this.Source = source.replaceFirst(":","");
String[] source_nicksplit = Source.split("!");
Nick = source_nicksplit[0];
String[] source_hostnamesplit = source_nicksplit[1].split("@");
Ident = source_hostnamesplit[0];
Hostname = source_hostnamesplit[1];
} | 0 |
@Override
public void startSetup(Attributes atts) {
super.startSetup(atts);
addActionListener(this);
} | 0 |
public boolean peutAttaquerUnTerritoire(Territoire to){
List<Territoire> occupes = this.peuple.getTerritoiresOccupes();
// Recherche d'un territoire pouvant attaquer
if (occupes.size() > 0) {
Iterator<Territoire> it = occupes.iterator();
while (it.hasNext()) {
Territoire tmp = it.next();
if (this.peuple.peutAttaquer(tmp, to))
return true;
}
}
return false;
} | 3 |
public Polynomial gcd(Polynomial x) throws Exception {
Polynomial a = monic();
Polynomial b = x.monic();
while (true) {
if (a.degree() < b.degree()) {
Polynomial t = a;
a = b;
b = t;
}
if (b.degree() < 0) return a; // gcd(a,0) == a
Polynomial z = x().pow(a.degree() - b.degree());
a = a.sub(b.mul(z)).monic(); // cancel the highest degree of a
}
} | 3 |
@Override
/**
* This function has to apply some change to colorArr Color c is curColor in
* GridPanel
*/
public ArrayList<Delta> apply(Color c, int x, int y, Color[][] colorArr) {
dMap = new ArrayList<>();
this.colorArr = colorArr;
q = new LinkedList<>();
q.push(new Point(x, y));
while (!q.isEmpty()) {
bucketHelper(c);
}
return dMap;
} | 1 |
public CardPane()
{
} | 0 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Observation other = (Observation) obj;
if (!Arrays.equals(capteurs, other.capteurs))
return false;
return true;
} | 4 |
private void fugit()
{
for(int i = 0;i < robotar.size();i++)
{
robotar.get(i).increaseLifetime();
}
for(int i = 0;i < rp.size();i++)
{
rp.get(i).increaseLifetime();
}
for(int i = 0;i < sp.size();i++)
{
sp.get(i).increaseLifetime();
sp.get(i).decreaseDeathtime();
}
for(int i = 0;i < tp.size();i++)
{
tp.get(i).increaseLifetime();
}
for(int i = 0;i < kp.size();i++)
{
kp.get(i).increaseLifetime();
}
} | 5 |
public static ArrayList<MusterReaction> findMusterReactionByTestId(ArrayList<MusterReaction> musterReactions, int id) {
ArrayList<MusterReaction> outputReactions = new ArrayList<MusterReaction>();
for(MusterReaction mr:musterReactions) {
if(mr.muster==id) {
outputReactions.add(mr);
}
}
return outputReactions;
} | 2 |
public static void main(String[] args) {
new Compare().search( 5, 3, 4);
} | 0 |
private void qs(int low, int high){
int i = low;
int j = high;
//select middle element as a pivot
int pivot = elements[ low + ((high - low)/2) ];
// split elements into two list
while (i <= j){
// iterate through the left side, searching for elements
// that are bigger than pivot
while (elements[i] < pivot) {
i++;
}
// iterate through the right side, searching for elements
// that are smaller than pivot
while (elements[j] > pivot) {
j--;
}
/*if we have found an element in the left side which is smaller than pivot,
* or we have found an element in the right side which is larger than pivot
* then swap them
*/
if (i <= j){
swap(i, j);
i++;
j--;
}
}
//call recursively
if (low < j){
qs(low, j);
}
if (i < high){
qs(i, high);
}
} | 6 |
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
if(!jTextField7.isEnabled()){
jTextField7.setText("");
}
if(!jTextField8.isEnabled()){
jTextField8.setText("");
}
if(jButton4.getText().equals("Confirmar")){
if(controlarCampos()){
jButton2.setEnabled(true);
jButton1.setText("Abandonar Asiento");
cargarTabla();
borrarCamposAstoBasicos();
mensajeError(" ");
}
else
{
mensajeError("Debe completar todos los campos");
}
}
else
{
if(controlarCampos()){
jButton4.setText("Confirmar");
actualizarTabla();
mensajeError(" ");
borrarCamposAstoBasicos();
}
else
mensajeError("Debe completar todos los campos");
}
}//GEN-LAST:event_jButton4ActionPerformed | 5 |
@Before
public void setUp() {
dynamicArray = new DynamicArray();
arrayList = new ArrayList();
} | 0 |
public void drop(DropTargetDropEvent dtde)
{
// Method Instances
boolean doChangePosition;
TreePath pathAfter;
int idxNew, idxOld;
BrowserItems.DefaultTreeItem itemParent;
BrowserItems.DefaultTreeItem itemSource;
BrowserItems.DefaultTreeItem itemAfter;
QueryTokens._Expression token;
doChangePosition = false;
pathAfter = tree.getClosestPathForLocation(dtde.getLocation().x, dtde.getLocation().y);
idxNew = 0;
if (pathSource == null)
return;
itemSource = (BrowserItems.DefaultTreeItem) pathSource.getLastPathComponent();
itemAfter = (BrowserItems.DefaultTreeItem) pathAfter.getLastPathComponent();
if (itemAfter.isNodeSibling(itemSource))
{
itemParent = (BrowserItems.DefaultTreeItem) itemSource.getParent();
idxOld = itemParent.getIndex(itemSource);
idxNew = itemParent.getIndex(itemAfter);
doChangePosition = idxOld != idxNew;
if (idxOld > idxNew)
idxNew++;
}
else
{
itemParent = itemAfter;
doChangePosition = itemParent.isNodeChild(itemSource);
}
if (doChangePosition)
{
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
model.insertNodeInto(itemSource, itemParent, idxNew);
}
else if (itemSource.getParent().toString().indexOf(SQLReservedWords.SELECT) != -1
&& itemAfter.toString().indexOf(SQLReservedWords.GROUP_BY) != -1)
//&& itemSource instanceof BrowserItems.DefaultTreeItem)
{
token = (QueryTokens._Expression) itemSource.getUserObject();
queryBuilderPane.sqlBrowserViewPanel.addGroupByClause(new QueryTokens.Group(token));
}
else if (itemSource.getParent().toString().indexOf(SQLReservedWords.SELECT) != -1
&& itemAfter.toString().indexOf(SQLReservedWords.ORDER_BY) != -1)
//&& itemSource instanceof BrowserItems.DefaultTreeItem)
{
token = (QueryTokens._Expression) itemSource.getUserObject();
queryBuilderPane.sqlBrowserViewPanel.addOrderByClause(new QueryTokens.Order(token));
}
} | 8 |
@Override
public int hashCode() {
int hash = 0;
hash += (sucursalidSucursal != null ? sucursalidSucursal.hashCode() : 0);
return hash;
} | 1 |
public void obterArvoreCMC(int raiz) throws Exception {
int n = this.grafo.numVertices();
this.pesoAresta = new double[n];
int vs[] = new int[n + 1];
this.antecessor = new int[n];
for (int u = 0; u < n; u++) {
this.antecessor[u] = -1;
pesoAresta[u] = Double.MAX_VALUE;
vs[u + 1] = u;
}
pesoAresta[raiz] = 0;
FPHeapMinIndireto heap = new FPHeapMinIndireto(pesoAresta, vs);
heap.constroi();
while (!heap.vazio()) {
int u = heap.retiraMin();
if (!this.grafo.listaAdjVazia(u)) {
Grafo.Aresta adj = grafo.primeiroListaAdj(u);
while (adj != null) {
int v = adj.v2();
if (this.pesoAresta[v] > (this.pesoAresta[u] + adj.peso())) {
antecessor[v] = u;
heap.diminuiChave(v, this.pesoAresta[u] + adj.peso());
}
adj = grafo.proxAdj(u);
}
}
}
} | 5 |
@Override
// Viento HORA ESTADO KMS/H
public InterfazCommand parse(String nombre) {
double velViento = 0;
String hora;
InterfazCommand c = null;
String[] atributos = nombre.split("\\s");
if (atributos.length >= 3)
{
if (atributos[0].equalsIgnoreCase("viento"))
{
hora = atributos[1];
System.out.println(atributos[1]);
if(atributos.length == 3)
{
if(atributos[2].equalsIgnoreCase(Constantes.VIENTO_NULO))
{
velViento = 0;
}
c = new ComandoViento(hora, velViento);
}
else
{
if (atributos[2].equalsIgnoreCase(Constantes.VIENTO_A_FAVOR.toString()))
{
velViento = Double.parseDouble(atributos[3]);
velViento = velViento * -1;
}
else if(atributos[2].equalsIgnoreCase(Constantes.VIENTO_EN_CONTRA))
{
velViento = Double.parseDouble(atributos[3]);
}
c = new ComandoViento(hora, velViento);
}
}
}
return c;
} | 6 |
public static void initTimer(final int streamServerID, final String streamKey, final String id ){
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
try {
JGroovex.markStreamKeyOver30Seconds(0, streamServerID, streamKey, id);
} catch (IOException e) {
e.printStackTrace();
}
timer.cancel();
}
}, 30 * 1000);
} | 1 |
public void visitMethodInsn(
final int opcode,
final String owner,
final String name,
final String desc){
if(mv != null)
{
mv.visitMethodInsn(opcode, owner, name, desc);
}
pop(desc);
if(opcode != Opcodes.INVOKESTATIC)
{
Object t = pop();
if(opcode == Opcodes.INVOKESPECIAL && name.charAt(0) == '<')
{
Object u;
if(t == Opcodes.UNINITIALIZED_THIS)
{
u = owner;
}
else
{
u = uninitializedTypes.get(t);
}
for(int i = 0; i < locals.size(); ++i)
{
if(locals.get(i) == t)
{
locals.set(i, u);
}
}
for(int i = 0; i < stack.size(); ++i)
{
if(stack.get(i) == t)
{
stack.set(i, u);
}
}
}
}
pushDesc(desc);
labels = null;
} | 9 |
public void bfs(Node rt)
{
Queue<Node> q = new ArrayDeque<Node>();
if(rt != null) q.add(rt);
while(!q.isEmpty())
{
Node tNode = q.remove();
System.out.print(tNode.value+" ");
if(tNode.left!=null)
q.add(tNode.left);
if(tNode.right!=null)
q.add(tNode.right);
}
} | 4 |
private void initializeCommonRegions(int x) {
this.commonRegions = new long[2][6][x];
for(int i=0; i<this.commonRegions.length; i++) {
for(int j=0; j<this.commonRegions[0].length; j++) {
for(int k=0; k<this.commonRegions[0][0].length; k++) {
this.commonRegions[i][j][k] = this.initTemps[2];
}
}
}
} | 3 |
public static Field getField(Class cls, String fieldName)
{
Assert.notNull(cls, "cls cannot be null");
Assert.notNull(fieldName, "fieldName cannot be null");
// First check for public field using getField()
Field field = null;
try
{
field = cls.getField(fieldName);
}
catch(NoSuchFieldException ignore) {}
// If that fails, use getDeclaredField() going up the class hierarchy
Class sup = cls;
while(null == field && sup != null)
{
try
{
field = sup.getDeclaredField(fieldName);
}
catch(NoSuchFieldException ignore) {}
sup = sup.getSuperclass();
}
// Last resort: throw IllegalArgumentException
if(field == null)
{
throw new IllegalArgumentException(
"Cannot find \"" + fieldName + "\" method on : " + cls
);
}
return field;
} | 5 |
private static Object processJsonArrayAsCollection(JsonElement jsonElement, Class<?> parameterClass, Class<?> genericClass) throws JsonException, IllegalAccessException, InstantiationException {
if (jsonElement.getType() != JsonType.ARRAY) throw new JsonException("Json Element is not Array");
if (!Collection.class.isAssignableFrom(parameterClass)) throw new JsonException("Incompatible types");
Collection newCollection;
if (parameterClass.isInterface()) {
if (parameterClass.isAssignableFrom(ArrayList.class)) newCollection = new ArrayList();
else throw new JsonException("Unsupported collection type");
} else newCollection = (Collection)parameterClass.newInstance();
Iterator<JsonElement> it = jsonElement.iterator();
while (it.hasNext()) newCollection.add(getSubObject(it.next(), genericClass));
return newCollection;
} | 7 |
public double backPropagate(double[] input, double[] output)
{
double new_output[] = execute(input);
double error;
int i;
int j;
int k;
/* doutput = correct output (output) */
// Calcoliamo l'errore dell'output
for(i = 0; i < fLayers[fLayers.length - 1].Length; i++)
{
error = output[i] - new_output[i];
fLayers[fLayers.length - 1].Neurons[i].Delta = error * fTransferFunction.evaluteDerivate(new_output[i]);
}
for(k = fLayers.length - 2; k >= 0; k--)
{
// Calcolo l'errore dello strato corrente e ricalcolo i delta
for(i = 0; i < fLayers[k].Length; i++)
{
error = 0.0;
for(j = 0; j < fLayers[k + 1].Length; j++)
error += fLayers[k + 1].Neurons[j].Delta * fLayers[k + 1].Neurons[j].Weights[i];
fLayers[k].Neurons[i].Delta = error * fTransferFunction.evaluteDerivate(fLayers[k].Neurons[i].Value);
}
// Aggiorno i pesi dello strato successivo
for(i = 0; i < fLayers[k + 1].Length; i++)
{
for(j = 0; j < fLayers[k].Length; j++)
fLayers[k + 1].Neurons[i].Weights[j] += fLearningRate * fLayers[k + 1].Neurons[i].Delta *
fLayers[k].Neurons[j].Value;
fLayers[k + 1].Neurons[i].Bias += fLearningRate * fLayers[k + 1].Neurons[i].Delta;
}
}
// Calcoliamo l'errore
error = 0.0;
for(i = 0; i < output.length; i++)
{
error += Math.abs(new_output[i] - output[i]);
//System.out.println(output[i]+" "+new_output[i]);
}
error = error / output.length;
return error;
} | 7 |
private boolean setupPermissions() {
RegisteredServiceProvider<Permission> rsp = getServer().getServicesManager().getRegistration(Permission.class);
perms = rsp.getProvider();
return perms != null;
} | 0 |
private static int calcLight(int radius, int radiusSq, int distX,
int distY, double dither, Color color) {
int distCenterSq = distY * distY + distX * distX;
if (distCenterSq > radiusSq) {
return 0;
}
return toData(((double) radius / (double) (distCenterSq)), dither,
color);
} | 1 |
@Override
public void mouseDragged(MouseEvent e) {
List<GuiControl> controlList = new ArrayList<GuiControl>();
controlList.addAll(this.controlList);
for (GuiControl c : controlList)
c.mouseDragged(e);
if (e.getModifiersEx() == MouseEvent.BUTTON3_DOWN_MASK) {
scrollX -= e.getX() - diffX;
scrollY -= e.getY() - diffY;
if (scrollX < 0)
scrollX = 0;
if (scrollY < 0)
scrollY = 0;
int mapWidth = mapCache.length;
int mapHeight = mapCache[0].length;
if (scrollX > (int) (mapWidth * tileSize * zoom - width))
scrollX = (int) (mapWidth * tileSize * zoom - width);
if (scrollY > (int) (mapHeight * tileSize * zoom - height))
scrollY = (int) (mapHeight * tileSize * zoom - height);
diffX = e.getX();
diffY = e.getY();
}
} | 6 |
public static OpCode parseOpCode(String str) {
for (OpCode op : values())
if (op.toString().equalsIgnoreCase(str))
return op;
return null;
} | 2 |
public int integerBreak(int n) {
if(n==2) return 1;
if(n==3) return 2;
int n3=n/3;
int left=n-3*n3;
int n2=0;
if(left==1){
n3-=1;
n2=2;
}else if(left==2){
n2=1;
}
return Double.valueOf(Math.pow(3, n3) * Math.pow(2, n2)).intValue();
} | 4 |
@Override
public void actionPerformed(ActionEvent e) {
String teksti = syotekentta.getText();
if (!teksti.isEmpty()) {
teksti = teksti.substring(0, teksti.length() - 1);
syotekentta.setText(teksti);
}
} | 1 |
public void createStatement(){
try {
stmt = con.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
} | 1 |
public static KernighanLin processWithVertices(Graph g, Set<Vertex> vertexSet) {
Graph newG = new Graph();
for (Vertex v : vertexSet)
newG.addVertex(v);
for (Edge e : g.getEdges()) {
Pair<Vertex> endpoints = g.getEndpoints(e);
if (vertexSet.contains(endpoints.first) &&
vertexSet.contains(endpoints.second))
newG.addEdge(e, endpoints.first, endpoints.second);
}
return process(newG);
} | 4 |
public boolean isSpaceAboveRobot() {
if(robot.getLocation().y <= 0) return false;
if(robot.getLocation().y <= GROUND_LEVEL) return true;
for(Rectangle hole:holes) {
if(((hole.y + hole.height) == robot.getLocation().y) &&
(robot.getLocation().x == hole.x)) {
return true;
}
}
return false;
} | 5 |
@Override
public double convertTo(int type) {
switch (type) {
case UnitConstants.FEET_SECOND:
return getValue() * 3.28084;
case UnitConstants.FEET_MINUTE:
return getValue() * 196.8504;
case UnitConstants.MILES_MINUTE:
return getValue() * 0.0372822;
case UnitConstants.MILES_HOUR:
return getValue() * 2.236936;
case UnitConstants.METER_SECOND:
return getValue();
case UnitConstants.KILOMETER_MINUTE:
return getValue() * 0.06;
case UnitConstants.KILOMETER_HOUR:
return getValue() * 3.6;
case UnitConstants.KNOTS:
return getValue() * 1.943844;
}
return 0;
} | 8 |
public GutterIconInfo[] getTrackingIcons(int line)
throws BadLocationException {
List retVal = new ArrayList(1);
if (trackingIcons!=null) {
int start = textArea.getLineStartOffset(line);
int end = textArea.getLineEndOffset(line);
if (line==textArea.getLineCount()-1) {
end++; // Hack
}
for (int i=0; i<trackingIcons.size(); i++) {
GutterIconImpl ti = getTrackingIcon(i);
int offs = ti.getMarkedOffset();
if (offs>=start && offs<end) {
retVal.add(ti);
}
else if (offs>=end) {
break; // Quit early
}
}
}
GutterIconInfo[] array = new GutterIconInfo[retVal.size()];
return (GutterIconInfo[])retVal.toArray(array);
} | 6 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ChangesetCounter that = (ChangesetCounter) o;
if (counter != that.counter) return false;
if (day != that.day) return false;
if (hour != that.hour) return false;
if (month != that.month) return false;
if (year != that.year) return false;
return true;
} | 8 |
private boolean bottomLeftCorner(int particle, int cubeRoot) {
for(int i = 0; i < cubeRoot; i++){
if(particle == i * cubeRoot * cubeRoot){
return true;
}
}
return false;
} | 2 |
@Override
public void paint(Graphics g) {
g.setColor(super.getBackground());
g.fillRect(0, 0, this.getWidth(), this.getHeight());
if(autosize)
{
if(selected)
{
Image tmp = this.highlighted.getImage().getScaledInstance(this.getWidth(), this.getHeight(), java.awt.Image.SCALE_SMOOTH);
g.drawImage(new ImageIcon(tmp).getImage(), 0, 0, null);
}
else
{
Image tmp = this.normal.getImage().getScaledInstance(this.getWidth(), this.getHeight(), java.awt.Image.SCALE_SMOOTH);
g.drawImage(new ImageIcon(tmp).getImage(), 0, 0, null);
}
}
else
{
if(selected)
g.drawImage(this.highlighted.getImage(), 0, 0, null);
else
g.drawImage(this.normal.getImage(), 0, 0, null);
}
} | 3 |
public void visitForceChildren(final TreeVisitor visitor) {
if (visitor.reverse()) {
expr.visit(visitor);
} else {
expr.visit(visitor);
}
} | 1 |
static void v(DangerousMonster d) {
d.menace();
d.destroy();
} | 0 |
private void updateLiteralRuleAssociationList_addRule(final Rule newRule) throws TheoryException {
// Set<Literal> literalList = newRule.getLiteralList();
Map<String, Rule> ruleList = null;
// theory type checking
if (newRule.hasTemporalInfo()) theoryType = TheoryType.TDL;
else if (newRule.hasModalInfo() && theoryType.compareTo(TheoryType.SDL) <= 0) theoryType = TheoryType.MDL;
// else if (!"".equals(newRule.getMode().getName()) && theoryType == TheoryType.SDL) theoryType =
// TheoryType.MDL;
for (Literal literal : newRule.getLiteralList()) {
// for (Literal l : newRule.getLiteralList()) {
// Literal literal=l instanceof LiteralVariable ? DomUtilities.getLiteral(l):l;
// for (Literal literal : literalList) {
// if (literal.containsTemporalInfo()) theoryType = TheoryType.TDL;
// else if (!"".equals(literal.getMode().getName()) && theoryType == TheoryType.SDL) theoryType =
// TheoryType.MDL;
ruleList = literalRuleAssoList.get(literal);
if (null == ruleList) {
ruleList = new TreeMap<String, Rule>();
// if (literal instanceof LiteralVariable){
// Literal l=DomUtilities.getLiteral(literal);
// Map<String,Rule>ruleList2=literalRuleAssoList.get(l);
// if (null!=ruleList2){
// ruleList.putAll(ruleList2);
// literalRuleAssoList.remove(l);
// }
// }
literalRuleAssoList.put(literal, ruleList);
}
if (!ruleList.containsKey(newRule.getLabel())) ruleList.put(newRule.getLabel(), newRule);
// literal variable and boolean operation handling
if (literal instanceof LiteralVariable) {
LiteralVariable lv = (LiteralVariable) literal;
if (lv.isLiteralVariable()) literalVariablesInRules.add(lv);
else if (lv.isLiteralBooleanFunction()) literalBooleanFunctionsInRules.add(lv);
}
}
} | 9 |
@Override
public void prepareInternal(int skips, boolean assumeOnSkip) {
//System.out.println("DelayUntil "+skips);
if(isCachable()) {
if (!assumeOnSkip) {
move.prepareInternal(0, false);
while(true) {
State s = curGb.newState();
boolean ret = move.doMove();
curGb.restore(s);
if(ret)
break;
move.prepareInternal(1, true);
}
}
while(skips-- > 0) {
boolean ret;
do {
move.prepareInternal(1, true);
State s = curGb.newState();
ret = move.doMove();
curGb.restore(s);
} while(!ret);
}
} else {
State init = curGb.newState();
int delay = -1;
do {
boolean ret;
do {
++delay;
move.prepareInternal(delay, false);
ret = move.doMove();
curGb.restore(init);
} while(!ret);
}
while(skips-- > 0);
move.prepareInternal(delay, false);
}
//System.out.println("delayed "+delay+" steps until condition met ("+skips+" skips)");
} | 8 |
@Override
public void update(Observable arg1, Object arg2) {
if (this.controller != null) {
LOGGER.log(Level.FINE, "Updating GUI");
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
LOGGER.log(Level.FINE, "Number of connected clients: "
+ client.getUsers().size());
LinkedList<User> clients = client.getUsers();
LOGGER.log(Level.FINE, "Removing all children");
treeRoot.removeAllChildren();
for (User connectedUser : clients) {
if (!connectedUser.getIP().equals(
client.getMulticastAddress())) {
LOGGER.log(Level.FINE, "New user detected: "
+ connectedUser.getName());
DefaultMutableTreeNode user = new DefaultMutableTreeNode(
connectedUser);
treeRoot.add(user);
}
}
connectedPlayers.updateUI();
frame.repaint();
for (int i = 0; i < connectedPlayers.getRowCount(); i++) {
connectedPlayers.expandRow(i);
}
}
});
}
} | 4 |
public void onKeyReleased(int key) {
keys[key] = false;
if (key == Keyboard.KEY_RIGHT && !keys[Keyboard.KEY_LEFT]) {
player.setSpeed(0.0f, player.speed.y, player.speed.z);
}
if (key == Keyboard.KEY_LEFT && !keys[Keyboard.KEY_RIGHT]) {
player.setSpeed(0.0f, player.speed.y, player.speed.z);
}
if (key == Keyboard.KEY_UP && !keys[Keyboard.KEY_DOWN]) {
player.setSpeed(player.speed.x, 0.0f, player.speed.z);
}
if (key == Keyboard.KEY_DOWN && !keys[Keyboard.KEY_UP]) {
player.setSpeed(player.speed.x, 0.0f, player.speed.z);
}
if (key == Keyboard.KEY_SPACE)
player.setSpeed(player.speed.x, player.speed.y, 2.5f);
} | 9 |
private TokenizerProperty searchString(String image, boolean removeIt) {
char startChar = getStartChar(image.charAt(0));
PropertyList list = getList(startChar);
PropertyList prev = null;
while (list != null) {
TokenizerProperty prop = list._property;
String img = prop.getImages()[0];
int res = compare(img, image, 1);
if (res == 0) {
if (removeIt) {
if (prev != null) {
prev._next = list._next;
} else {
list = list._next;
if (startChar >= 0 && startChar < DIRECT_INDEX_COUNT) {
_asciiArray[startChar] = list;
} else if (list != null) {
_nonASCIIMap.put(new Character(startChar), list);
} else {
_nonASCIIMap.remove(new Character(startChar));
}
}
}
return prop;
} else if (res < 0) {
break;
}
prev = list;
list = list._next;
}
return null;
} | 8 |
private void btnExcelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcelActionPerformed
final int totalFilas = this.table_ticket.getRowCount();
if (totalFilas > 0) {
final String rutaExcel = dir.getRuta_excel();
final ArrayList<Ticket> tickets = this.tableTicketModel.getArrayTicket(totalFilas);
final JTable table = this.table_ticket;
int i = JOptionPane.showConfirmDialog(this, "¿Desea exportar a Excel?", "Informe", JOptionPane.YES_NO_OPTION);
if (i == 0) {
this.progress_bar.setVisible(true);
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
new Thread(new Runnable() {
@Override
public void run() {
try {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd/MM/yyyy");
String desde = "01/01/1990";
try {
desde = sdf.format(txt_fechadesde.getDate());
desde = desde.replace("/", "-");
} catch (Exception e) {
desde = "01/01/1990";
}
String hasta = "01/01/2020";
try {
hasta = sdf.format(txt_fechahasta.getDate());
hasta = hasta.replace("/", "-");
} catch (Exception e) {
hasta = "01/01/2020";
}
tableTicketModel.exportarTicket(table, tickets, rutaExcel, desde, hasta);
} catch (IOException ex) {
Logger.getLogger(BuscarRegistro.class.getName()).log(Level.SEVERE, null, ex);
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progress_bar.setVisible(false);
setCursor(Cursor.getDefaultCursor());
}
});
}
}).start();
}
}else{
JOptionPane.showMessageDialog(null, "Primero debe realizar una búsqueda");
}
}//GEN-LAST:event_btnExcelActionPerformed | 5 |
public boolean sendPocsagMessage(PocsagMessage message) {
String tmp;
if (serialPort == null ) {
serialPort = openConnection(Config.btsPort, Config.btsBauds);
if (serialPort == null) {
return true;
}
}
try {
BufferedReader in = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
PrintStream out = new PrintStream(serialPort.getOutputStream());
out.println("CONFIG FREQ " + message.getFrequency());
System.out.println("CONFIG FREQ " + message.getFrequency());
tmp = in.readLine();
if ("OK".equals(tmp) == false) {
throw new IOException("Imposible to set the frequency " + message.getFrequency());
}
out.println("CONFIG BAUDS " + message.getBauds());
System.out.println("CONFIG BAUDS " + message.getBauds());
tmp = in.readLine();
if ("OK".equals(tmp) == false) {
throw new IOException("Imposible to set the baud rate " + message.getBauds());
}
String s = "SEND " + message.getMsgType().toString().charAt(0) + " " + message.getRIC() + " " + message.getMessage();
out.println(s);
System.out.println(s);
// Skip the debug info with the data sent through the radio interface and search for the OK
while ((tmp = in.readLine()) != null)
if ("OK".equals(tmp) == true) {
break;
}
if (tmp == null)
throw new IOException("Imposible to send command " + s);
} catch (Exception e) {
LOGGER.severe("Error sending data to BTS: " + e);
} finally {
closeConnection();
}
return false;
} | 8 |
private int buildMatchHistory(int match, JPanel panel, int maxRounds) {
Vector columns = cdata.getColumnData(match);
int numRounds = cdata.getNumRounds(match);
int firstRound = 0;
// for (int i=firstRound; i<numRounds; i++) {
for (int i = numRounds - 1; i >= 0; i--) {
Color backColor;
// if ((i % 2 == 0 && maxRounds % 2 == 0) || (i % 2 == 1 &&
// maxRounds % 2 == 1))
if (match % 2 == 0)
backColor = new Color(220, 220, 220);
else
backColor = new Color(204, 204, 204);
JPanel mNumPanel = new JPanel();
JLabel mNum = new JLabel("" + (match + 1));
mNum.setForeground(Color.black);
mNum.setHorizontalAlignment(SwingConstants.CENTER);
mNumPanel.setBackground(backColor);
mNumPanel.add(mNum);
if (columns == null || columns.size() < 1)
gridbag.setConstraints(mNumPanel, endRowConstraints);
else
gridbag.setConstraints(mNumPanel, normalConstraints);
panel.add(mNumPanel);
if (columns != null && columns.size() > 0) {
for (int k = 0; k < columns.size(); k++) {
Hashtable column = (Hashtable) columns.get(k);
Color foreColor = (Color) column.get("color");
JPanel columnPanel = new JPanel();
JLabel columnLabel = new JLabel();
String data = (String) column.get(new Integer(i));
if (data == null)
data = "";
columnLabel.setText(data);
columnLabel.setForeground(foreColor);
columnLabel.setHorizontalAlignment(SwingConstants.CENTER);
columnPanel.add(columnLabel);
columnPanel.setBackground(backColor);
if (k == (columns.size() - 1))
gridbag.setConstraints(columnPanel, endRowConstraints);
else
gridbag.setConstraints(columnPanel, normalConstraints);
panel.add(columnPanel);
}
}
}
return numRounds;
} | 9 |
private void drawMenu(Graphics2D g){
g.setColor(Color.WHITE);
g.drawString("ASTEROIDS", (getWidth()-fm.stringWidth("ASTEROIDS"))/2, 100);
if (mainMenuTextAreas[0].contains(MouseInfo.getPointerInfo().getLocation()))
g.setColor(Color.RED);
else
g.setColor(Color.WHITE);
g.drawString("Play", (getWidth()-fm.stringWidth("Play"))/2, 250);
if (mainMenuTextAreas[1].contains(MouseInfo.getPointerInfo().getLocation()))
g.setColor(Color.RED);
else
g.setColor(Color.WHITE);
g.drawString("Load", (getWidth()-fm.stringWidth("Load"))/2, 350);
if (mainMenuTextAreas[2].contains(MouseInfo.getPointerInfo().getLocation()))
g.setColor(Color.RED);
else
g.setColor(Color.WHITE);
g.drawString("Options", (getWidth()-fm.stringWidth("Options"))/2, 450);
if (mainMenuTextAreas[3].contains(MouseInfo.getPointerInfo().getLocation()))
g.setColor(Color.RED);
else
g.setColor(Color.WHITE);
g.drawString("High Scores", (getWidth()-fm.stringWidth("High Scores"))/2, 550);
if (mainMenuTextAreas[4].contains(MouseInfo.getPointerInfo().getLocation()))
g.setColor(Color.RED);
else
g.setColor(Color.WHITE);
g.drawString("Quit", (getWidth()-fm.stringWidth("Quit"))/2, 650);
} | 5 |
public static void convertFolderToXML(String dir, boolean recursive)
{
File file = R2DFileUtility.getResource(dir);
if(!file.exists() || !file.isDirectory())
return;
R2DFileFilter filter = new R2DFileFilter();
for(File f : file.listFiles())
{
//Log.debug(f.isFile()+" "+filter.accept(file, f.getName()));
if(f.isFile() && filter.accept(file, f.getName()))
{
try
{
String localPath = R2DFileUtility.getRelativeFile(f).getPath();
R2DFileManager read = new R2DFileManager(localPath,null);
read.read();
f.renameTo(new File(f.getAbsolutePath()+".orig"));
R2DFileManager write = new R2DFileManager(localPath.substring(0,localPath.length()-4)+".xml",null);
write.setCollection(read.getCollection());
write.write();
} catch(IOException e)
{
throw new Remote2DException(e);
}
} else if(f.isDirectory() && recursive)
convertFolderToXML(R2DFileUtility.getRelativeFile(f).getPath(),recursive);
}
} | 8 |
private String needAbort(String transaction, Set<String> conflicts) {
transactionEntity thisone = transInfo.get(transaction);
for (String conflict : conflicts)
if (thisone.timestamp > transInfo.get(conflict).timestamp)
return conflict;
return null;
} | 2 |
public boolean isValid() {
return this.valid;
} | 0 |
public String getCameraType ()
{
switch (statusTable [1]) {
// case 0: ?
// case 1: return "DC-50";
// case 2: return "DC-120";
// case 3: return "DC-200";
// case 4: return "DC-210/215";
case 5: return "DC-240";
case 6: return "DC-280";
// FIXME:
case 7: return "DC-3400 (?)";
case 8: return "DC-5000 (?)";
default: return "Unknown-" + getCameraType ();
}
} | 4 |
public static void main (String args[]) {
Map<String, String> map = new HashMap();
fillData(map);
for (String key : map.keySet()) {
System.out.println(key + " " + map.get(key));
}
map.put("Added lately", "testing");
map.remove("Intellij");
for (String key : map.keySet()) {
System.out.println(key + " " + map.get(key));
}
} | 2 |
public static void main(String[] args) {
for (int i = 1; i <= 1000; i++) {
/**
* This is true if the number is divisible by 3.
*/
final boolean fizz = i % 3 == 0;
/**
* This is true if the number is divisible by 5.
*/
final boolean buzz = i % 5 == 0;
/**
* This is true if the number is divisible by 3 and 5.
*/
final boolean fizzbuzz = i % 3 == 0 && i % 5 == 0;
if (fizzbuzz)
System.out.print("[FizzBuzz]: ");
else if (fizz)
System.out.print("[Fizz]: ");
else if (buzz)
System.out.print("[Buzz]: ");
System.out.println(i);
}
} | 5 |
public static void defend(SimulatedPlanetWars simpw) { //send ships from the lowest growing planet to the best one
// Tested
int maxGR = 0;
int minGR = 5;
Planet source = null;
Planet dest = null;
for (Planet p : simpw.MyPlanets()){
if (p.GrowthRate()>maxGR){
maxGR = p.GrowthRate();
dest = p;
}
if (p.GrowthRate()<minGR){
minGR = p.GrowthRate();
source = p;
}
}
if (source != null && dest != null) {
simpw.IssueOrder(source, dest);
}
updateLearning(-1);
} | 5 |
private void doFinishAction() {
switch (finishAction) {
case (NONE) : break;
case (HIDE) : {
if (component instanceof GUIComponentGroup) {
((GUIComponentGroup) component).hide();
}
break;
}
case (SHOW) : {
if (component instanceof GUIComponentGroup) {
((GUIComponentGroup) component).show();
}
break;
}
case (VISIBLE) : {
component.setVisible(true);
break;
}
case (INVISIBLE) : {
component.setVisible(false);
break;
}
}
finishAction = NONE;
} | 7 |
public Boolean isStringValid(String in) {
//System.out.println("M " + in + " M");
Boolean returnVal=Boolean.TRUE;
if (in==null || in.length()==0) return returnVal;
Stack<Character> stk=new Stack<Character>();
try {
for (Character x: in.toCharArray()) {
if (startChars.indexOf(x)!=-1)
stk.push((Character)x);
else {
int termIndex=endChars.indexOf(x);
if (termIndex==-1)
continue;
Character current=stk.peek();
if (startChars.indexOf(current.charValue())==termIndex)
stk.pop();
}
}
if (stk.empty()==false)
returnVal=Boolean.FALSE;
}
catch (EmptyStackException e) {
returnVal=Boolean.FALSE;
}
catch (Exception e) {
// FIXME: weak error handling, just in case
e.printStackTrace();
returnVal=Boolean.FALSE;
}
return returnVal;
} | 9 |
public static boolean isServerUpdateAvailable()
{
if( Settings.isOfflineMode() )
return false;
File tempFile;
boolean missingFile = false;
boolean outOfDateFile = false;
refreshLookupValues();
// Loop over local and remote application versions
// If there is a difference in the version, there is an update
for( int i = 0; i < entriesToCheck.size(); i++ )
{
String value = RemoteUtils.getConfigEntry( entriesToCheck.get(i) );
if( value == null ) return false;
outOfDateFile |= !(value).equals( lookupEntries.get(i) );
}
// Loop over the remote required files.
// If there is a missing file locally, there is an update
String[] files = RemoteUtils.getRemoteFiles();
for( String f : files ) {
tempFile = new File(Settings.WEAVE_ROOT_DIRECTORY, f.trim());
if( !tempFile.exists() ) {
missingFile = true;
break;
}
}
return ( missingFile || outOfDateFile );
} | 6 |
public Read() throws IOException {
byte [] b = new byte [50000];
String fileName = System.getProperty("user.dir") + "/output/test.mp3";
File inputFile = new File(fileName);
InputStream is = new FileInputStream(inputFile);
is.read(b,0,50000);
for(int i = 0; i < b.length; i++)
{
StringBuffer sb = new StringBuffer();
sb.append("byte [" + i + "]: " + b[i]);
if((i % 418) == 25) sb.append(" <-- begin of frame " + (i / 418 + 1));
if((i % 418) == 29){
sb.append(" <-- main_data_beg: ");
int beg = (b[i] >= 0) ? ((b[i] << 1)+((b[i+1]>>> 7) & 1)): (((b[i] + 256) << 1)+((b[i+1]>>> 7) & 1));
sb.append(beg);
}
if((i % 418) == 61) sb.append(" <-- begin of data in frame");
LOGGER.info(sb.toString());
}
is.close();
} | 5 |
private int[] defaultRgbArray(int width, int height) {
int[] rgbs = new int[width * height];
// fill everything with UnpassableSandTiles
Arrays.fill(rgbs, 0xffA8A800);
// add SandTiles for player bases
for (int y = 0 + 4; y < height - 4; y++) {
for (int x = (width / 2) - 5; x < (width / 2) + 4; x++) {
rgbs[x + y * width] = 0xff888800;
}
}
for (int y = 0 + 5; y < height - 5; y++) {
for (int x = (width / 2) - 3; x < (width / 2) + 2; x++) {
rgbs[x + y * width] = 0xffA8A800;
}
}
return rgbs;
} | 4 |
public boolean initGUI()
{
InventoryOpenEvent ioe = new InventoryOpenEvent(this);
Bukkit.getPluginManager().callEvent(ioe);
if(ioe.isCancelled())
return false;
cont.setLayout(ContainerType.OVERLAY).setAnchor(WidgetAnchor.CENTER_CENTER).setWidth(width).setHeight(height).setX(-width/2).setY(-height/2);
cont.addChild(extend.getBackground().setPriority(RenderPriority.High));
for(int i = 0; i < slots.size(); i++)
cont.addChild(slots.get(i));
for(int z = 0; z < extend.getWidgets().size(); z++)
cont.addChild(extend.getWidgets().get(z));
pl.getMainScreen().attachPopupScreen(popup = (PopupScreen) new GenericPopup()
{
@Override
public void onScreenClose(ScreenCloseEvent e)
{
onClose(e);
}
@Override
public void handleItemOnCursor(ItemStack is) {
if(is.getTypeId() == 0 || is.getAmount() == 0) return;
eject(is);
}
@Override
public void onTick() {
super.onTick();
InventoryWidget.this.onTick();
}
}.attachWidget(MorgulPlugin.thisPlugin, cont));
return true;
} | 5 |
protected void drawDays() {
Calendar tmpCalendar = (Calendar) calendar.clone();
tmpCalendar.set(Calendar.HOUR_OF_DAY, 0);
tmpCalendar.set(Calendar.MINUTE, 0);
tmpCalendar.set(Calendar.SECOND, 0);
tmpCalendar.set(Calendar.MILLISECOND, 0);
Calendar minCal = Calendar.getInstance();
minCal.setTime(minSelectableDate);
minCal.set(Calendar.HOUR_OF_DAY, 0);
minCal.set(Calendar.MINUTE, 0);
minCal.set(Calendar.SECOND, 0);
minCal.set(Calendar.MILLISECOND, 0);
Calendar maxCal = Calendar.getInstance();
maxCal.setTime(maxSelectableDate);
maxCal.set(Calendar.HOUR_OF_DAY, 0);
maxCal.set(Calendar.MINUTE, 0);
maxCal.set(Calendar.SECOND, 0);
maxCal.set(Calendar.MILLISECOND, 0);
int firstDayOfWeek = tmpCalendar.getFirstDayOfWeek();
tmpCalendar.set(Calendar.DAY_OF_MONTH, 1);
int firstDay = tmpCalendar.get(Calendar.DAY_OF_WEEK) - firstDayOfWeek;
if (firstDay < 0) {
firstDay += 7;
}
int i;
for (i = 0; i < firstDay; i++) {
days[i + 7].setVisible(false);
days[i + 7].setText("");
}
tmpCalendar.add(Calendar.MONTH, 1);
Date firstDayInNextMonth = tmpCalendar.getTime();
tmpCalendar.add(Calendar.MONTH, -1);
Date day = tmpCalendar.getTime();
int n = 0;
Color foregroundColor = getForeground();
while (day.before(firstDayInNextMonth)) {
days[i + n + 7].setText(Integer.toString(n + 1));
days[i + n + 7].setVisible(true);
if ((tmpCalendar.get(Calendar.DAY_OF_YEAR) == today
.get(Calendar.DAY_OF_YEAR))
&& (tmpCalendar.get(Calendar.YEAR) == today
.get(Calendar.YEAR))) {
days[i + n + 7].setForeground(sundayForeground);
} else {
days[i + n + 7].setForeground(foregroundColor);
}
if ((n + 1) == this.day) {
days[i + n + 7].setBackground(selectedColor);
selectedDay = days[i + n + 7];
} else {
days[i + n + 7].setBackground(oldDayBackgroundColor);
}
if (tmpCalendar.before(minCal) || tmpCalendar.after(maxCal)) {
days[i + n + 7].setEnabled(false);
} else {
days[i + n + 7].setEnabled(true);
}
n++;
tmpCalendar.add(Calendar.DATE, 1);
day = tmpCalendar.getTime();
}
for (int k = n + i + 7; k < 49; k++) {
days[k].setVisible(false);
days[k].setText("");
/* this was a try to display the days of the adjacent months, too,
* but some points are missing:
* - only the last week should be filled
*
*/
// days[k].setVisible(true);
// days[k].setEnabled(false);
// days[k].setText(Integer.toString(k-(n+i+6)));
}
drawWeeks();
} | 9 |
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("GSB-2014-eq1_initialPU");
} | 0 |
public ColorPallet(ColorPalletState initColorPalletState)
{
// WE'LL KEEP THE STATE, SINCE WE'LL USE
// IT EVERY TIME WE REFRESH
state = initColorPalletState;
XMLUtilities xmlloader = new XMLUtilities();
Document palletSettings = null;
try {
palletSettings = xmlloader.loadXMLDocument(PoseurSettings.COLOR_PALLET_SETTINGS_XML, PoseurSettings.COLOR_PALLET_SETTINGS_SCHEMA);
} catch(InvalidXMLFileFormatException ixffe)
{
JOptionPane.showMessageDialog(this, ixffe.toString());
System.exit(0);
}
Node root = palletSettings.getFirstChild();
NodeList children = root.getChildNodes();
int numColorsInPallet = xmlloader.getIntData(palletSettings, PoseurSettings.PALLET_SIZE_NODE);
int numRows = xmlloader.getIntData(palletSettings, PoseurSettings.PALLET_ROWS_NODE);
int numFixedColors;
int red, green, blue;
Color[] palletColors = new Color[numColorsInPallet];
Node currentNode = root;
int x=0;
while (true)
{
if ((currentNode = xmlloader.getNodeInSequence(palletSettings, PoseurSettings.PALLET_COLOR_NODE, x))==null)
{
break;
}
Node colorNode = currentNode.getFirstChild();
red = Integer.parseInt(colorNode.getTextContent());
colorNode = colorNode.getNextSibling();
green = Integer.parseInt(colorNode.getTextContent());
colorNode = colorNode.getNextSibling();
blue = Integer.parseInt(colorNode.getTextContent());
palletColors[x]=new Color (red,green,blue);
x++;
}
numFixedColors = x;
Color defaultColor = PoseurSettings.UNASSIGNED_COLOR_PALLET_COLOR;
Node defaultColorNode;
if ((defaultColorNode = xmlloader.getChildNodeWithName(palletSettings, PoseurSettings.DEFAULT_COLOR_NODE))!=null)
{
red = Integer.parseInt(defaultColorNode.getChildNodes().item(0).getTextContent());
green = Integer.parseInt(defaultColorNode.getChildNodes().item(1).getTextContent());
blue = Integer.parseInt(defaultColorNode.getChildNodes().item(2).getTextContent());
defaultColor = new Color(red, green, blue);
}
state.loadColorPalletState(palletColors, numRows, numFixedColors, defaultColor);
colorPalletButtons = new JButton[numColorsInPallet];
for (int i = 0; i < numColorsInPallet; i++)
{
// CONSTRUCT AND ADD EACH BUTTON ONE AT A TIME
colorPalletButtons[i] = new JButton();
}
// AND NOW ARRANGE THEM INSIDE THIS PALLET
int colorPalletRows = state.getColorPalletRows();
int colorPalletSize = colorPalletButtons.length;
GridLayout gL = new GridLayout(colorPalletRows, colorPalletSize/colorPalletRows);
this.setLayout(gL);
Border etchedBorder = BorderFactory.createEtchedBorder();
this.setBorder(etchedBorder);
// NOW PUT THE BUTTONS INTO THE COLOR PALLET PANEL
// WITH THEIR PROPER INITIAL COLORS
int row = 0;
int col = 0;
for (int i = 0; i < colorPalletSize; i++)
{
if (col == (colorPalletRows/colorPalletRows))
{
col = 0;
row++;
}
this.add(colorPalletButtons[i]);
colorPalletButtons[i].setBackground(state.getColorPalletColor(i));
}
} | 7 |
public void chgDir()
{
switch(dir)
{
case 0:
sprt = img1.getImage();
if(Game.tickCount2 == game.DELAY){
dir = 1;
}
break;
case 1:
sprt = img2.getImage();
if(Game.tickCount2 == game.DELAY){
dir = 0;
}
break;
case 2:
sprt = img3.getImage();
if(Game.tickCount2 == game.DELAY){
dir = 3;
}
break;
case 3:
sprt = img4.getImage();
if(Game.tickCount2 == game.DELAY){
dir = 2;
}
break;
}
} | 8 |
public void setUserlistImagePadding(int[] padding) {
if ((padding == null) || (padding.length != 4)) {
this.userlistImg_Padding = UIPaddingInits.USERLIST_IMAGE.getPadding();
} else {
this.userlistImg_Padding = padding;
}
somethingChanged();
} | 2 |
public String getSource() { return Source; } | 0 |
private final String getChunk(String s, int slength, int marker)
{
StringBuilder chunk = new StringBuilder();
char c = s.charAt(marker);
chunk.append(c);
marker++;
if (isDigit(c))
{
while (marker < slength)
{
c = s.charAt(marker);
if (!isDigit(c))
break;
chunk.append(c);
marker++;
}
} else
{
while (marker < slength)
{
c = s.charAt(marker);
if (isDigit(c))
break;
chunk.append(c);
marker++;
}
}
return chunk.toString();
} | 5 |
@Override
public void execute() {
p.setBackground(Color.white);
} | 0 |
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
JSONObject jb = new JSONObject();
InputStreamReader reader =
new InputStreamReader(request.getInputStream(), "utf-8");
String receivedString = "";
char[] buff = new char[1024];
int length = 0;
while ((length = reader.read(buff)) != -1)
{
receivedString = new String(buff, 0, length);
}
try {
JSONObject receivedObject = new JSONObject(receivedString);
String userId = receivedObject.getString("userId");
String publisherId = receivedObject.getString("publisherId");
String commentContent = receivedObject.getString("commentContent");
String eventId = receivedObject.getString("eventId");
String publishTime = receivedObject.getString("publishTime");
try{
Mongo mongo =new Mongo();
DB scheduleDB = mongo.getDB("schedule");
DBCollection eventCollection = scheduleDB.getCollection("event_"+publisherId);
DBObject eventQuery = new BasicDBObject();
eventQuery.put("_id", new ObjectId(eventId));
DBObject commentAdd = new BasicDBObject();
DBCollection userCollection = scheduleDB.getCollection("user");
DBObject userQuery = new BasicDBObject();
userQuery.put("_id", new ObjectId(userId));
DBCursor userCur = userCollection.find(userQuery);
if(userCur.hasNext()){
DBObject userObject = userCur.next();
String publisherName = userObject.get("username").toString();
String publisherImage = userObject.get("image").toString();
commentAdd.put("publisherName", publisherName);
commentAdd.put("publisherImage", publisherImage);
commentAdd.put("publisherId", userId);
commentAdd.put("commentContent", commentContent);
ObjectId commentId = new ObjectId();
commentAdd.put("_id",commentId.toString());
commentAdd.put("publishTime", publishTime);
DBObject comment = new BasicDBObject();
comment.put("comments", commentAdd);
DBObject commentPush = new BasicDBObject();
commentPush.put("$push", comment);
WriteResult wr = eventCollection.update(eventQuery, commentPush,true,true);
if(wr.getN() == 0){
jb.put("result", Primitive.DBSTOREERROR);
}else{
DBObject updateCommentCount = new BasicDBObject();
DBObject countIncrease = new BasicDBObject();
countIncrease.put("commentCount", 1);
updateCommentCount.put("$inc", countIncrease);
WriteResult wr2 = eventCollection.update(eventQuery,
updateCommentCount);
if(wr2.getN()!=0){
JSONObject commentJSONObject = new JSONObject();
commentJSONObject.put("_id", commentId.toString());
commentJSONObject.put("publisherName", publisherName);
commentJSONObject.put("publisherImage", publisherImage);
commentJSONObject.put("publisherId", publisherId);
commentJSONObject.put("commentContent", commentContent);
commentJSONObject.put("publishTime", publishTime);
jb.put("result", Primitive.ACCEPT);
jb.put("comment", commentJSONObject);
}else{
jb.put("result", Primitive.DBSTOREERROR);
}
}
}else{
jb.put("result", Primitive.DBSTOREERROR);
}
}catch(MongoException e){
jb.put("result", Primitive.DBCONNECTIONERROR);
e.printStackTrace();
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
String jbString = new String(jb.toString().getBytes(),"UTF-8");
writer.write(jbString);
writer.flush();
writer.close();
} | 6 |
@Override
public void setForeground(Color color) {
mColor = color;
if (mLink == null || mLink.getClientProperty(ERROR_MESSAGE_KEY) == null) {
super.setForeground(color);
}
} | 2 |
public static double evaluateState(SimulatedPlanetWars pw){
// CHANGE HERE
double enemyShips = 1.0;
double myShips = 1.0;
for (Planet planet: pw.EnemyPlanets()){
enemyShips += planet.NumShips();
}
for (Planet planet: pw.MyPlanets()){
myShips += planet.NumShips();
}
return myShips/enemyShips;
} | 2 |
public static void EndTimeReport()
{
FileWriter fstream =null;
BufferedWriter out =null;
String ENDTIME = now("hh:mm:ss").toString();
try
{
fstream = new FileWriter(filename, true);
out = new BufferedWriter(fstream);
out.write("<table border=1 cellspacing=1 cellpadding=1 >\n");
out.write("<tr>\n");
out.write("<h4> <FONT COLOR=660000 FACE=Arial SIZE=4.5> <u>Test Executive Summary :</u></h4>\n");
//out.write("<h4> <FONT COLOR=660000 FACE= Arial SIZE=4.5> <u>"+"SuiteName"+" Report :</u></h4>\n");
out.write("<td width=150 align=left bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE=Arial SIZE=2.75><b>Run Date</b></td>\n");
out.write("<td width=150 align=left><FONT COLOR=#153E7E FACE=Arial SIZE=2.75><b>"+RUN_DATE+"</b></td>\n");
out.write("</tr>\n");
out.write("<tr>\n");
// out.newLine();
out.write("<tr>\n");
out.write("<td width=150 align=left bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE=Arial SIZE=2.75><b>Run StartTime</b></td>\n");
out.write("<td width=150 align=left><FONT COLOR=#153E7E FACE=Arial SIZE=2.75><b>"+testStartTime+"</b></td>\n");
out.write("</tr>\n");
out.write("<tr>\n");
// out.newLine();
out.write("<td width=150 align= left bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE= Arial SIZE=2.75><b>Run EndTime</b></td>\n");
out.write("<td width=150 align= left ><FONT COLOR=#153E7E FACE= Arial SIZE=2.75><b>"+ENDTIME+"</b></td>\n");
out.write("</tr>\n");
out.write("<td width=150 align= left bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE= Arial SIZE=2.75><b>Environment</b></td>\n");
out.write("<td width=150 align= left ><FONT COLOR=#153E7E FACE= Arial SIZE=2.75><b>"+"ENVIRONMENT"+"</b></td>\n");
out.write("</tr>\n");
out.write("<tr>\n");
out.write("<td width=150 align= left bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE= Arial SIZE=2.75><b>Release</b></td>\n");
out.write("<td width=150 align= left ><FONT COLOR=#153E7E FACE= Arial SIZE=2.75><b>"+"RELEASE"+"</b></td>\n");
out.write("</tr>\n");
out.write("</table>\n");
//---------------------------
out.write("</body>\n");
out.write("</html>\n");
out.close();
}
catch(Throwable t)
{
}
} | 1 |
public int lengthOfLongestSubstring(String s) {
if(s.length()==0) {
return 0;
}
int j=1;
for(; j<s.length(); j++) {
int i=0;
for(; i<j; i++) {
if(s.charAt(i)==s.charAt(j)) {
break;
}
}
if(i!=j) {
break;
}
}
int headLen = j;
int subLen = lengthOfLongestSubstring(s.substring(1));
if(headLen>subLen) {
return headLen;
} else {
return subLen;
}
} | 6 |
public IntNode getLink( )
{
return link;
} | 0 |
public static void main(String args[]) {
//<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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CalendarEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
CalendarEditor dialog = new CalendarEditor(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);
}
});
} | 3 |
public JSONArray toJSONArray(JSONArray names) throws JSONException {
if (names == null || names.length() == 0) {
return null;
}
JSONArray ja = new JSONArray();
for (int i = 0; i < names.length(); i += 1) {
ja.put(this.opt(names.getString(i)));
}
return ja;
} | 3 |
public static String typeName(char _typeChar) {
String returnName = null;
switch (_typeChar) {
case SIGC_VOID:
returnName = "void";
break;
case SIGC_INT:
returnName = "int";
break;
case SIGC_DOUBLE:
returnName = "double";
break;
case SIGC_FLOAT:
returnName = "float";
break;
case SIGC_SHORT:
returnName = "short";
break;
case SIGC_CHAR:
returnName = "char";
break;
case SIGC_BYTE:
returnName = "byte";
break;
case SIGC_LONG:
returnName = "long";
break;
case SIGC_BOOLEAN:
returnName = "boolean";
break;
}
return (returnName);
} | 9 |
public synchronized void actionPerformed(ActionEvent event) {
Object target = event.getSource();
if (target instanceof MenuItem) {
MenuItem item = (MenuItem)target;
int[] indexes = fOnlineList.getSelectedIndexes();
if (indexes == null || indexes.length == 0)
return;
if (item == fCopyIntoToMenu) {
String toList = "";
for (int i = 0; i < indexes.length; i++) {
toList += fOnlineList.getItem(indexes[i]);
if ((i + 1) < indexes.length)
toList += ", ";
}
fMainUI.setToList(toList);
setAllSelected(false);
} else if (item == fOpenMessagingDialogMenu) {
openAction(indexes);
setAllSelected(false);
} else if (item == fSelectAllMenu)
setAllSelected(true);
}
} | 8 |
public void setAddress2(String address2) {
this.address2 = address2;
} | 0 |
private void trInsertionSort (final int ISA, final int ISAd, final int ISAn, int first, int last) {
final int[] SA = this.SA;
int a, b;
int t, r;
for (a = first + 1; a < last; ++a) {
for (t = SA[a], b = a - 1; 0 > (r = trGetC (ISA, ISAd, ISAn, t) - trGetC (ISA, ISAd, ISAn, SA[b]));) {
do {
SA[b + 1] = SA[b];
} while ((first <= --b) && (SA[b] < 0));
if (b < first) {
break;
}
}
if (r == 0) {
SA[b] = ~SA[b];
}
SA[b + 1]= t;
}
} | 6 |
public PainelDesenho() {
super();
this.addMouseListener(new EventosMouse());
objetos = new ArrayList<FiguraGeometrica>();
} | 0 |
public void writeFile()
{
File file=new File("monsters.dat");
FileOutputStream fout;
ObjectOutputStream out;
try {
fout=new FileOutputStream(file);
out=new ObjectOutputStream(fout);
out.writeObject(current_id-2);
out.flush();
for(int i=0; i<current_id-1; i++){
out.writeObject(monsters.get(i));
out.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 3 |
public Tea() {
this.setName("Coffee");
this.setPrice(new BigDecimal(15));
} | 0 |
public static Session getInstance() {
if (instance == null ) {
instance = new Session();
}
return instance;
} | 1 |
private static void writeToFile(String out) {
if (fileWriter == null) {
try {
fileWriter = new FileWriter("out.log");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
fileWriter.write(out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fileWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 4 |
public void setjTextFieldCP(JTextField jTextFieldCP) {
this.jTextFieldCP = jTextFieldCP;
} | 0 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PacketVO other = (PacketVO) obj;
if (packetId != other.packetId)
return false;
return true;
} | 4 |
public void update()
{
Window window = Window.getInstance();
JPanel panel = window.getPanel();
if (pauseDelay > 0)
pauseDelay--;
if (keyboard.isDown(KeyEvent.VK_P) && pauseDelay <= 0)
{
if (!paused)
{
window.setPanel(new PausePanel());
}
else
{
window.setPanel(new GamePanel());
}
pauseDelay = 20;
}
paused = panel.getClass() != GamePanel.class;
if (paused)
return;
if (currentRound.isDone())
{
Round previousRound = rounds.remove(0);
session.incrementRound();
currentRound = null;
if (rounds.size() > 0)
{
currentRound = rounds.get(0);
currentRound.setSession(previousRound.getSession());
currentRound.init();
}
}
if (rounds.size() > 0) {
currentRound.update();
if (panel instanceof GamePanel)
{
GamePanel gamePanel = (GamePanel)panel;
gamePanel.draw(currentRound.getRenders());
gamePanel.drawStrings(currentRound.getStringRenders());
gamePanel.repaint();
}
} else {
window.setPanel(new GameFinishPanel(session));
}
} | 9 |
public String getBackground() {
if (styles == null) {
return null;
}
else {
return styles.get("bg");
}
} | 1 |
public short evaluate_short(Object[] dl) throws Throwable {
if (Debug.enabled)
Debug.println("Wrong evaluateXXXX() method called,"+
" check value of getType().");
return 0;
}; | 1 |
public double[] rawItemMedians(){
if(!this.dataPreprocessed)this.preprocessData();
if(!this.variancesCalculated)this.meansAndVariances();
return this.rawItemMedians;
} | 2 |
private void printFinals(int maxRound, ArrayList<Match> finals, ArrayList<Match> sFinals, ArrayList<Match> qFinals) throws SQLException
{
/*
* Quarter Finals
*/
if (maxRound >= 7)
{
printShowQFinalHeader();
for (Match m : qFinals)
{
System.out.printf("%3s %-2d %-6s %-20s %-8s %-20s\n", "", m.getId(), ":",
teammgr.getById(m.getHomeTeamId()).getSchool(), " VS ",
teammgr.getById(m.getGuestTeamId()).getSchool());
}
}
else
{
printShowQFinalHeader();
System.out.printf("%3s %-2s %-6s %-20s %-8s %-20s\n", "", "-", ":",
"Winner of Group A", " VS ", "Second of Group B");
System.out.printf("%3s %-2s %-6s %-20s %-8s %-20s\n", "", "-", ":",
"Winner of Group B", " VS ", "Second of Group A");
System.out.printf("%3s %-2s %-6s %-20s %-8s %-20s\n", "", "-", ":",
"Winner of Group C", " VS ", "Second of Group D");
System.out.printf("%3s %-2s %-6s %-20s %-8s %-20s\n", "", "-", ":",
"Winner of Group D", " VS ", "Second of Group C");
}
/*
* Semi Finals
*/
if (maxRound >= 8)
{
printShowSemiFinalHeader();
for (Match m : sFinals)
{
System.out.printf("%3s %-2d %-6s %-20s %-8s %-20s\n", "", m.getId(), ":",
teammgr.getById(m.getHomeTeamId()).getSchool(), " VS ",
teammgr.getById(m.getGuestTeamId()).getSchool());
}
}
else
{
printShowSemiFinalHeader();
System.out.printf("%3s %-2s %-6s %-20s %-8s %-20s\n", "", "-", ":",
"QuarterFinalWinner 1", " VS ", "QuarterFinalWinner 2");
System.out.printf("%3s %-2s %-6s %-20s %-8s %-20s\n", "", "-", ":",
"QuarterFinalWinner 3", " VS ", "QuarterFinalWinner 4");
}
/*
* Final
*/
if (maxRound == 9)
{
printShowFinalHeader();
for (Match m : finals)
{
System.out.printf("%3s %-2d %-6s %-20s %-8s %-20s\n", "", m.getId(), ":",
teammgr.getById(m.getHomeTeamId()).getSchool(), " VS ",
teammgr.getById(m.getGuestTeamId()).getSchool());
}
}
else
{
printShowFinalHeader();
System.out.printf("%3s %-2s %-6s %-20s %-8s %-20s\n", "", "-", ":",
"SemiFinalWinner 1", " VS ", "SemiFinalWinner 2");
}
} | 6 |
public TarHeader readNextFileHeader() throws IOException {
if(this.lastHeader != null) {
throw new RuntimeException("Must first read file content of last entry");
}
// Read a complete File entry
byte[] header = new byte[512];
do {
if(-1 == Util.readBlocking(header, inputStream)) {
return null;
}
this.lastHeader = new TarHeader(header);
} while(this.lastHeader == null);
this.lastHeader = new TarHeader(header);
return new TarHeader(header);
} | 3 |
private long neuerZaehler(char operation, Bruch tmpBruch2) {
// Anhand der übergebenen Operation wird die Rechnugn durchgeführt
switch (operation) {
case '+':
return (this.zaehler * tmpBruch2.nenner)
+ (tmpBruch2.zaehler * this.nenner);
case '-':
return (this.zaehler * tmpBruch2.nenner)
- (tmpBruch2.zaehler * this.nenner);
case '*':
return (this.zaehler * tmpBruch2.zaehler);
case ':':
Bruch kehrwertBruch = tmpBruch2.kehrwert();
return (this.zaehler * kehrwertBruch.zaehler);
}
return 0;
} | 4 |
public static void zoom(Model3D m, double d, int w, int h) {
if (h < 6 || w < 6)
return;
m.setDecalageX(w / 2);
m.setDecalageY(h / 2);
double smlX = w, hgX = 0, smlY = h, hgY = 0;
for (int i = 0; i < m.getPoints().size(); i++) {
if (m.getPoints().get(i).x < smlX) {
smlX = m.getPoints().get(i).x;
} else if (m.getPoints().get(i).x > hgX) {
hgX = m.getPoints().get(i).x;
} else if (m.getPoints().get(i).y < smlY) {
smlY = m.getPoints().get(i).y;
} else if (m.getPoints().get(i).y > hgY) {
hgY = m.getPoints().get(i).y;
}
}
double sizeX, sizeY;
sizeX = hgX - smlX;
sizeY = hgY - smlY;
if (sizeX > sizeY) {
m.zoom((w / sizeX) * d);
} else {
m.zoom((h / sizeY) * d);
}
} | 8 |
public Person2(int id, String Name, Double height) {
this.id = id;
this.Name = Name;
this.height = height;
} | 0 |
public boolean isProduction(Production production) {
return myProductions.contains(production);
} | 0 |
Subsets and Splits