text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
private void addAndRemoveModels() {
boolean changed=false;
for (int i = 0; i < models.size(); i++) {
if (models.get(i).getIsNoNeedMore()) {
if (!models.get(i).getIsComplex())
explode(models.get(i).getCenter(), models.get(i).getMaxWidth() * 10, models.get(i).getMaxWidth());
models.get(i).destroy();
removeModel(i);
changed=true;
}
}
if (addModelBuffer.size() > 0) {
models.addAll(addModelBuffer);
addModelBuffer.clear();
changed=true;
}
if (changed) renumerateModels();
} | 5 |
public void removePlayer(Player p ){
if(blau.contains(p)){
blau.remove(p);
}
if(rot.contains(p)){
rot.remove(p);
}
if(grün.contains(p)){
grün.remove(p);
}
if(gelb.contains(p)){
gelb.remove(p);
}
} | 4 |
public static double logLikelihoodScore(ICTClassifier<Double, CTDiscreteNode> model, int nodeIndex,
Collection<ITrajectory<Double>> dataset,
ILearningAlgorithm<Double, CTDiscreteNode> paramsLearningAlg,
boolean dimensionPenalty) throws RuntimeException {
if( dataset == null)
throw new RuntimeException("Error: dataset didn't set");
if( paramsLearningAlg.getStructure() != null)
throw new RuntimeException("Error: parameter algorithm used in the scoring function for structural learning can not have structure setted");
CTDiscreteNode node = model.getNode(nodeIndex);
if( node.isStaticNode())
throw new IllegalArgumentException("Error: this scoring function is not defined for static nodes");
double llScore = 0.0;
double mxx = (Double) paramsLearningAlg.getParameter("Mxx_prior");
double tx = (Double) paramsLearningAlg.getParameter("Tx_prior");
SufficientStatistics[] ss = paramsLearningAlg.learn(model, dataset).getSufficientStatistics();
// Marginal value calculation
double mx = mxx*(node.getStatesNumber() - 1);
for(int fsE = 0; fsE < node.getStatesNumber(); ++fsE) {
for(int pE = 0; pE < node.getNumberParentsEntries(); ++pE) {
// Calculate MargLq (q-value)
llScore += Gamma.logGamma( ss[nodeIndex].Mx[pE][fsE] + 1);
llScore += (mx + 1) * Math.log( tx);
llScore -= Gamma.logGamma( mx + 1);
llScore -= (ss[nodeIndex].Mx[pE][fsE] + 1) * Math.log( ss[nodeIndex].Tx[pE][fsE]);
// Calculate MargLth (theta)
llScore += Gamma.logGamma( mx);
llScore -= Gamma.logGamma( ss[nodeIndex].Mx[pE][fsE]);
for(int ssE = 0; ssE < node.getStatesNumber(); ++ssE) {
if( fsE == ssE)
continue;
llScore += Gamma.logGamma( ss[nodeIndex].Mxx[pE][fsE][ssE]);
llScore -= Gamma.logGamma( mxx);
}
}
}
// llScore = llScore - ln|X|*Dim[X]/2
if( dimensionPenalty) {
double dimX = (node.getStatesNumber() - 1) * node.getStatesNumber() * node.getNumberParentsEntries();
llScore -= Math.log( dataset.size()) * dimX / 2;
}
return llScore;
} | 8 |
private void openSockets() {
boolean requestSocketOpened = false;
boolean echoSocketOpened = false;
for (int i = 0; i <= SOCKET_OPEN_MAX_ATTEMPTS; i++) {
try {
requestSocket = new DatagramSocket(REQUEST_PORT);
requestSocketOpened = true;
break;
} catch (IOException e) {
U.sleep(150);
}
}
for (int i = 0; i <= SOCKET_OPEN_MAX_ATTEMPTS; i++) {
try {
echoSocket = new DatagramSocket(ECHO_PORT);
echoSocketOpened = true;
break;
} catch (IOException e) {
U.sleep(150);
}
}
if (requestSocketOpened && echoSocketOpened) {
socketsClosed = false;
log("echo sockets have been opened");
} else {
log("error: echo sockets have not been opened");
}
} | 6 |
public static void narrclick() {
// in case no card has been played yet
if ((display[0] == 0 || display[0] == 13) && newhand[0] >= 1) {
newhand[0]--;
display[0] = 13;
display[1]++;
}
// in case another card has been played
else if (display[0] != 0 && newhand[0] >= 1) {
newhand[0]--;
display[1]++;
}
} | 5 |
private String getTopType(int pos) throws BadBytecode {
Frame frame = getFrame(pos);
if (frame == null)
return null;
CtClass clazz = frame.peek().getCtClass();
return clazz != null ? Descriptor.toJvmName(clazz) : null;
} | 2 |
public void mousePressed(MouseEvent e) {
Mappable mappable=map.getMapObjectAt(e.getX(), e.getY());
setSelected(mappable);
boolean ctrlDown=(e.getModifiersEx() & InputEvent.CTRL_DOWN_MASK) !=0;
boolean altDown=(e.getModifiersEx() & InputEvent.ALT_DOWN_MASK) !=0;
if(mappable!=null && SwingUtilities.isRightMouseButton(e)){
popupMenu.show(this,e.getX(),e.getY());
} else if(selected!=null && ctrlDown){
eventProc=eventProcessors.get("rotate");
} else if(selected!=null && altDown){
eventProc=eventProcessors.get("face");
} else if(selected!=null){
eventProc=eventProcessors.get("move");
} else if(SwingUtilities.isRightMouseButton(e)){
eventProc=eventProcessors.get("measure");
} else{
eventProc=eventProcessors.get("select");
}
eventProc.mousePressed(e);
} | 8 |
Object unpack(Info vi, Buffer opb){
int acc=0;
InfoResidue0 info=new InfoResidue0();
info.begin=opb.read(24);
info.end=opb.read(24);
info.grouping=opb.read(24)+1;
info.partitions=opb.read(6)+1;
info.groupbook=opb.read(8);
for(int j=0; j<info.partitions; j++){
int cascade=opb.read(3);
if(opb.read(1)!=0){
cascade|=(opb.read(5)<<3);
}
info.secondstages[j]=cascade;
acc+=Util.icount(cascade);
}
for(int j=0; j<acc; j++){
info.booklist[j]=opb.read(8);
}
if(info.groupbook>=vi.books){
free_info(info);
return (null);
}
for(int j=0; j<acc; j++){
if(info.booklist[j]>=vi.books){
free_info(info);
return (null);
}
}
return (info);
} | 6 |
private void knightBottomRightPossibleMove(Piece piece, Position position)
{
int x1 = position.getPositionX();
int y1 = position.getPositionY();
if((x1 >= 0 && y1 >= 1) && (x1 <= 5 && y1 < maxHeight))
{
if(board.getChessBoardSquare(x1+2, y1-1).getPiece().getPieceType() != board.getBlankPiece().getPieceType())
{
if(board.getChessBoardSquare(x1+2, y1-1).getPiece().getPieceColor() != piece.getPieceColor())
{
// System.out.print(" " + coordinateToPosition(x1+2, y1-1)+"*");
Position newMove = new Position(x1+2, y1-1);
piece.setPossibleMoves(newMove);
}
}
else
{
// System.out.print(" " + coordinateToPosition(x1+2, y1-1));
Position newMove = new Position(x1+2, y1-1);
piece.setPossibleMoves(newMove);
}
}
} | 6 |
public void SQLExceptionInterpreter(SQLException e) {
if (gui.debug) {
System.out.println(e.getErrorCode());
e.printStackTrace();
}
switch (e.getErrorCode()) {
case 2627:
gui.setState("double PRIMARY KEY");
break;
case 515:
gui.setState("Null as PRIMARY KEY");
break;
default:
new ErrorDialog(e, gui);
break;
}
} | 3 |
public String getPassword() {
return password;
} | 0 |
public boolean isDiagonal(){
boolean test = true;
for(int i=0; i<this.numberOfRows; i++){
for(int j=0; j<this.numberOfColumns; j++){
if(i!=j && this.matrix[i][j]!=0.0D)test = false;
}
}
return test;
} | 4 |
@Override
public synchronized void redo() throws CannotRedoException {
if (!canRedo())
return;
AbstractDocument.DefaultDocumentEvent lastRedo = null;
AbstractDocument.DefaultDocumentEvent nextRedo;
UndoableEdit ue;
while((ue = super.editToBeRedone()) != null) {
if (!canRedo()) {
break;
}
if (ue instanceof AbstractDocument.DefaultDocumentEvent) {
nextRedo = (AbstractDocument.DefaultDocumentEvent)ue;
if (lastRedo == null || lastRedo.getPresentationName().equals(nextRedo.getPresentationName())) {
boolean breakFlag = false;
if (lastRedo != null) {
breakFlag = (Math.abs(nextRedo.getOffset() - lastRedo.getOffset()) > 1);
}
super.redo();
lastRedo = nextRedo;
if (breakFlag) {
break;
}
} else {
break;
}
} else {
// あり得ない
throw new RuntimeException();
//super.redo();
//break;
}
}
} | 8 |
private void vouch (String filename, String certname) throws IOException, GeneralSecurityException{
//create a read-only copy of the file
File readOnlyCopy = new File(filename);
readOnlyCopy.setWritable(false);
String privkeyloc = null;
//adapted from http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/security/apisign/examples/VerSig.java
@SuppressWarnings("resource")
FileInputStream fis = new FileInputStream(certname);
ByteArrayInputStream bis = null;
byte value[] = new byte[fis.available()];
fis.read(value);
bis = new ByteArrayInputStream(value);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate)certFactory.generateCertificate(bis);
privkeyloc = "./ClientPrivateKeys/" + cert.getSubjectDN().getName() + "_pri.key";
File vouchSig = GenSig.generate(readOnlyCopy.getAbsolutePath(), certname, privkeyloc);
try {
if(VerSig.verifySign(certname, vouchSig.getAbsolutePath(), filename)){
//pull up the file
System.out.println(vouchSig.getName());
addReplaceFile(COMMAND.V, vouchSig.getName());
addReplaceFile(COMMAND.U, certname);
vouchSig.delete();
}
else{
System.out.println("Signature could not be verified, vouching failed");
}
/*if(readOnlyCopy.exists()){
readOnlyCopy.delete();
}*/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 3 |
public List<IngredientRecipe> getPotentialIngredientList(State state, Domain domain, IngredientRecipe tlIngredient) {
List<IngredientRecipe> ingredients = new ArrayList<IngredientRecipe>();
Collection<IngredientRecipe> allIngredients = this.allIngredients.values();
Set<String> necessaryTraits = tlIngredient.getNecessaryTraits().keySet();
for (String trait : necessaryTraits) {
for (IngredientRecipe ing : allIngredients) {
if (ing.getTraits().contains(trait)) {
if (ingredients.contains(ing)) {
IngredientRecipe i = ingredients.get(ingredients.indexOf(ing));
i.setUseCount(i.getUseCount()+1);
} else {
ingredients.add(ing);
}
}
}
}
List<IngredientRecipe> contents = tlIngredient.getContents();
for (IngredientRecipe ingredient : contents) {
if (ingredient.isSimple()) {
if (ingredients.contains(ingredient)) {
IngredientRecipe ing = ingredients.get(ingredients.indexOf(ingredient));
ing.setUseCount(ing.getUseCount()+1);
} else {
ingredients.add(ingredient);
}
} else {
List<IngredientRecipe> toAdd = getPotentialIngredientList(state, domain, ingredient);
for (IngredientRecipe i : toAdd) {
if (ingredients.contains(i)) {
IngredientRecipe ing = ingredients.get(ingredients.indexOf(i));
ing.setUseCount(ing.getUseCount()+i.getUseCount());
} else {
ingredients.add(i);
}
}
}
}
return ingredients;
} | 9 |
@SuppressWarnings("unchecked")
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>)event;
} | 1 |
public SimpleList<String> minaXMLStructure (){
try {
String path = new File(".").getCanonicalPath();
FileInputStream file =
new FileInputStream(new File(path
+ "/xml/papabuilding.xml"));
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
System.out.println("************************************");
String expression01 = "/Structures/Structure[@class='Mina']";
Node node01 = (Node) xPath.compile(expression01)
.evaluate(xmlDocument, XPathConstants.NODE);
if(null != node01) {
nodeList = node01.getChildNodes();
for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++){
Node nod = nodeList.item(i);
if(nod.getNodeType() == Node.ELEMENT_NODE){
System.out.println(nodeList.item(i).getNodeName()
+ " : " + nod.getFirstChild().getNodeValue());
list.append(nod.getFirstChild().getNodeValue());
}
}
}
System.out.println("************************************");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return list;
} | 9 |
private void fill(char[][] board, int i, int j) {
int row = board.length;
int col = board[0].length;
if (i < 0 || i >= row || j < 0 || j >= col || board[i][j] != 'O') {
return;
}
//add, the number make up by (curRow * col + curCol)
queue.offer(i * col + j);
//replace to T
board[i][j] = 'T';
} | 5 |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof RingPlot)) {
return false;
}
RingPlot that = (RingPlot) obj;
if (this.separatorsVisible != that.separatorsVisible) {
return false;
}
if (!ObjectUtilities.equal(this.separatorStroke,
that.separatorStroke)) {
return false;
}
if (!PaintUtilities.equal(this.separatorPaint, that.separatorPaint)) {
return false;
}
if (this.innerSeparatorExtension != that.innerSeparatorExtension) {
return false;
}
if (this.outerSeparatorExtension != that.outerSeparatorExtension) {
return false;
}
if (this.sectionDepth != that.sectionDepth) {
return false;
}
return super.equals(obj);
} | 8 |
@Override
public void addScript(ScriptingEngine S)
{
if(scripts==null)
scripts=new SVector<ScriptingEngine>(1);
if(S==null)
return;
if(!scripts.contains(S))
{
ScriptingEngine S2=null;
for(int s=0;s<scripts.size();s++)
{
S2=scripts.get(s);
if((S2!=null)&&(S2.getScript().equalsIgnoreCase(S.getScript())))
return;
}
if(scripts.size()==0)
CMLib.threads().startTickDown(this,Tickable.TICKID_EXIT_BEHAVIOR,1);
scripts.add(S);
}
} | 7 |
public void repositionFlyUps() {
// removeDeadFlyUps();
int basePosition = 15 + (!permanentFlyUp.equals("") ? 0 : 15);
for(FlyUp fly:flyups) {
fly.setDistanceAboveRobot(basePosition);
basePosition += 15;
}
} | 2 |
@Test
public void testGet() {
final double height = 10;
final double width = 8;
assertEquals("Side should be LEFT", Side.get(0, 2, width, height), Side.LEFT);
assertEquals("Side should be LEFT", Side.get(0, 2.5, width, height), Side.LEFT);
assertEquals("Side should be LEFT", Side.get(0, 8.5, width, height), Side.LEFT);
assertEquals("Side should be TOP", Side.get(1, 0, width, height), Side.TOP);
assertEquals("Side should be TOP", Side.get(2.5, 0, width, height), Side.TOP);
assertEquals("Side should be TOP", Side.get(4, 0, width, height), Side.TOP);
assertEquals("Side should be TOP", Side.get(5, 0, width, height), Side.TOP);
assertEquals("Side should be RIGHT", Side.get(width, 0.0001, width, height), Side.RIGHT);
assertEquals("Side should be RIGHT", Side.get(width, 3.5, width, height), Side.RIGHT);
assertEquals("Side should be RIGHT", Side.get(width, 4.8, width, height), Side.RIGHT);
assertEquals("Side should be RIGHT", Side.get(width, height - 0.0001, width, height), Side.RIGHT);
assertEquals("Side should be BOTTOM", Side.get(0.5, height, width, height), Side.BOTTOM);
assertEquals("Side should be BOTTOM", Side.get(2.5, height, width, height), Side.BOTTOM);
assertEquals("Side should be BOTTOM", Side.get(4.7, height, width, height), Side.BOTTOM);
assertEquals("Side should be BOTTOM", Side.get(7.99, height, width, height), Side.BOTTOM);
assertEquals("Side should be null (middle of rect)", Side.get(3, 3.5, width, height), null);
assertEquals("Side should be null (middle of rect)", Side.get(5, 8, width, height), null);
assertEquals("Side should be null (x < 0)", Side.get(-0.0001, 3, width, height), null);
assertEquals("Side should be null (x < 0)", Side.get(-2.5, 3, width, height), null);
assertEquals("Side should be null (x > width)", Side.get(width + 0.0001, 3, width, height), null);
assertEquals("Side should be null (x > width)", Side.get(width + 20, 3, width, height), null);
assertEquals("Side should be null (y < 0)", Side.get(3, -0.0001, width, height), null);
assertEquals("Side should be null (y < 0)", Side.get(3, -15, width, height), null);
assertEquals("Side should be null (y > height)", Side.get(3, height + 0.0001, width, height), null);
assertEquals("Side should be null (y > height)", Side.get(3, height + 25, width, height), null);
Side s;
s = Side.get(0, 0, width, height);
assertTrue("Side should be LEFT or TOP (top-left corner)", s == Side.LEFT || s == Side.TOP);
s = Side.get(width, 0, width, height);
assertTrue("Side should be TOP or RIGHT (top-right corner)", s == Side.TOP || s == Side.RIGHT);
s = Side.get(0, height, width, height);
assertTrue("Side should be LEFT or BOTTOM (bottom-left corner)", s == Side.LEFT || s == Side.BOTTOM);
s = Side.get(width, height, width, height);
assertTrue("Side should be RIGHT or BOTTOM (bottom-right corner)", s == Side.RIGHT || s == Side.BOTTOM);
} | 4 |
public static void writeElementStart(
StringBuffer buf,
int depth,
boolean empty,
String line_ending,
String name,
Map attributes
) throws IllegalArgumentException {
if (isValidXMLElementName(name)) {
indent(buf, depth);
buf.append("<").append(name);
if (attributes != null) {
Iterator it = attributes.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
Object value = attributes.get(key);
try {
writeAttribute(buf, key.toString(), value.toString());
} catch (NullPointerException npe) {
throw new IllegalArgumentException("Attribute map contained a null for key: [" + key + "] value: [" + value + "]");
}
}
}
if (empty) {
buf.append("/>");
} else {
buf.append(">");
}
if (line_ending != null) {
buf.append(line_ending);
}
} else {
throw new IllegalArgumentException("Invalid element name: " + name);
}
} | 6 |
public boolean isFightCaveNpc(int i) {
switch (npcs[i].npcType) {
case 2627:
case 2630:
case 2631:
case 2741:
case 2743:
case 2745:
return true;
}
return false;
} | 6 |
public void disableArena() {
if (this.arenastate == ArenaState.STAT_READY
|| this.arenastate == ArenaState.STAT_STARTED)
this.endGame(EndReason.END_REASON_ARENADISABLE);
else if (this.arenastate == ArenaState.STAT_OPEN) {
for (Player p : players) {
this.removeplayer(p);
p.sendMessage(ChatColor.RED + "ر!");
}
}
} | 4 |
public synchronized void remove(long channelId, int clientId) {
int i=0;
for(TVChannel chann:channels){
if(chann.getChannelId()==channelId && chann.getClientId()==clientId){
channels.remove(i++);
}
}
} | 3 |
public void addItemtoRedo(ArrayList<UndoableItem> udi) {
redoStack.push(udi);
} | 0 |
private void setVerLength(int verLength) {
if (verLength < 10)
throw new IllegalArgumentException("The size of the grid has to be at least 10x10!");
this.verLength = verLength;
} | 1 |
public void run()
{
DataInputStream stream1 = new DataInputStream(this.file1);
DataInputStream stream2 = new DataInputStream(this.file2);
try {
while (!suspending) {
// Deserialize if its an already existing object and resume from there or simply go with the this reference
String line1 = stream1.readLine();
String line2 = stream2.readLine();
// Terminate if either of the files end
if (line1 == null || line2 == null) break;
//Keep the line number count
lineCount++;
if (!line1.equals(line2)) {
System.out.println("Line "+ lineCount);
}
// Make cmp take longer so that we don't require extremely large files for interesting results
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("stopped");
return;
}
}
}
catch (EOFException e) {
//End of File
} catch (IOException e) {
System.out.println ("cmp: Error: " + e);
}
suspending = false;
} | 7 |
public Detalle(int idDetalle, Tpv tpv, Encargo encargo, Producto producto, String otro, double cantidad, double precio) {
this.idDetalle = idDetalle;
this.tpv = tpv;
this.encargo = encargo;
this.producto = producto;
this.otro = otro;
this.cantidad = cantidad;
this.precio = precio;
} | 0 |
@Override
public Server getServer() { return Plugin.getServer(); } | 0 |
private float computeFix(List<JstatItem> jstatItemList) {
List<Float> fixList = new ArrayList<Float>();
for(JstatItem item : jstatItemList) {
if(item.getOU() > fismb)
fixList.add(item.getOU() - fismb);
}
if(fixList.isEmpty())
return 0;
else {
float sum = 0;
for(Float f : fixList)
sum += f;
return sum / fixList.size();
}
} | 4 |
private void sendEvent(String eventMessage) throws MMTConnectorException, IOException {
String postMessage = EventParameterName + "=" + eventMessage;
HttpURLConnection connection = (HttpURLConnection) this.getConnectorConfig().getServerURL().openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setReadTimeout(15000);
connection.setRequestProperty("charset", "utf-8");
if (this.getConnectorConfig().isKeepAlive()) {
connection.setRequestProperty("connection", "keep-alive");
} else {
connection.setRequestProperty("connection", "close");
}
connection.setRequestProperty("Content-Length", "" + Integer.toString(postMessage.getBytes().length));
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(postMessage);
wr.flush();
wr.close();
//connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String responseMessage = new String();
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseLine;
while ((responseLine = responseBuffer.readLine()) != null) {
responseMessage = responseMessage.concat(responseLine + "\n");
}
//System.out.println("The response of the probe is:" + responseMessage);
responseBuffer.close();
connection.disconnect();
} else {
connection.disconnect();
throw new MMTConnectorException("Connector Exception: Connection returned a response code of \"" + connection.getResponseCode() + "\".", connection.getResponseCode());
}
} | 3 |
@RequestMapping({"/", "index"})
public String index() {
return "index";
} | 0 |
public AdjustMoneyEditor() {
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setTitle("Adjust Money Editor");
setBounds(100, 100, 343, 234);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
JLabel lblValueToAdjust = new JLabel("Value to Adjust");
lblValueToAdjust.setBounds(10, 11, 125, 14);
contentPanel.add(lblValueToAdjust);
adjustSpinner = new JSpinner();
adjustSpinner.setBounds(10, 36, 50, 20);
contentPanel.add(adjustSpinner);
rdbtnActivator = new JRadioButton("Activator");
rdbtnActivator.setSelected(true);
buttonGroup.add(rdbtnActivator);
rdbtnActivator.setBounds(10, 97, 89, 23);
contentPanel.add(rdbtnActivator);
rdbtnSource = new JRadioButton("Source");
buttonGroup.add(rdbtnSource);
rdbtnSource.setBounds(103, 97, 61, 23);
contentPanel.add(rdbtnSource);
rdbtnSelect = new JRadioButton("Select...");
buttonGroup.add(rdbtnSelect);
rdbtnSelect.setBounds(168, 97, 74, 23);
contentPanel.add(rdbtnSelect);
selectCombo = new JComboBox<String>();
selectCombo.setModel(buildSelectCombo());
selectCombo.setBounds(168, 129, 109, 22);
contentPanel.add(selectCombo);
lblTarget = new JLabel("Target");
lblTarget.setBounds(10, 74, 46, 14);
contentPanel.add(lblTarget);
allButton = new JRadioButton("All");
allButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(allButton.isSelected()) {
percentSpinner.setEnabled(false);
}
}
});
buttonGroup_1.add(allButton);
allButton.setBounds(127, 34, 53, 23);
contentPanel.add(allButton);
percentButton = new JRadioButton("%");
buttonGroup_1.add(percentButton);
percentButton.setBounds(184, 34, 46, 23);
contentPanel.add(percentButton);
percentSpinner = new JSpinner();
percentSpinner.setModel(new SpinnerNumberModel(new Float(0), new Float(-1), new Float(1), new Float(1)));
percentSpinner.setBounds(238, 36, 37, 20);
contentPanel.add(percentSpinner);
staticButton = new JRadioButton("Static");
staticButton.setSelected(true);
buttonGroup_1.add(staticButton);
staticButton.setBounds(68, 34, 55, 23);
contentPanel.add(staticButton);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
save();
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
setModalityType(ModalityType.APPLICATION_MODAL);
setVisible(true);
} | 1 |
@SuppressWarnings({ "deprecation", "unused" })
public static boolean areItemsInDatabase(Player pl, ItemStack is, int qty) {
if (is == null)
return false;
int playerID = getPlayerId(pl.getUniqueId());
WebInventoryMeta wim = new WebInventoryMeta(is);
ResultSet rs = null;
try {
Connection conn = MineAuction.db.getConnection();
PreparedStatement ps = conn
.prepareStatement("SELECT COUNT(*) FROM ma_items WHERE id=? AND itemDamage=? AND enchantments = ? AND qty >=?");
ps.setInt(1, is.getType().getId());
ps.setShort(2, is.getDurability());
ps.setString(3, wim.getItemEnchantments());
ps.setInt(4, qty);
rs = ps.executeQuery();
// Iterate over resultSet
while (rs.next()) {
return rs.getInt(1) > 0 ? true : false;
}
return false;
} catch (Exception e) {
e.printStackTrace();
}
return false;
} | 4 |
private boolean jj_3_43() {
if (jj_3R_62()) return true;
if (jj_3R_56()) return true;
return false;
} | 2 |
public boolean jumpMayBeChanged() {
return subBlock.jump != null || subBlock.jumpMayBeChanged();
} | 1 |
@Override
public void deserialize(Buffer buf) {
worldX = buf.readShort();
if (worldX < -255 || worldX > 255)
throw new RuntimeException("Forbidden value on worldX = " + worldX + ", it doesn't respect the following condition : worldX < -255 || worldX > 255");
worldY = buf.readShort();
if (worldY < -255 || worldY > 255)
throw new RuntimeException("Forbidden value on worldY = " + worldY + ", it doesn't respect the following condition : worldY < -255 || worldY > 255");
mapId = buf.readInt();
subAreaId = buf.readShort();
if (subAreaId < 0)
throw new RuntimeException("Forbidden value on subAreaId = " + subAreaId + ", it doesn't respect the following condition : subAreaId < 0");
prismSide = buf.readByte();
} | 5 |
private int getNextPiece(Peer p) {
boolean[] peerBitfield = p.getBitfield();
boolean[] bitfield = tracker.getHost().getBitfield();
if(peerBitfield == null)
return -1;
for(int i = 0; i < bitfield.length; i++){
if(!bitfield[i] && peerBitfield[i]){
return i;
}
}
return -1;
} | 4 |
public void run() {
GroundItem spice = Util.getSpice();
int count = Inventory.getCount(spice.getId());
if (lootSpice()) {
int time = 0;
while (Inventory.getCount(spice.getId()) <= count && time <= 5000) {
time += 50;
Time.sleep(50);
}
}
} | 3 |
public KjStroke getReducedNoise(){
KjStroke result = new KjStroke();
if (pointList.size()<=2){
for(int i=0;i<pointList.size();i++){
result.addPoint(pointList.get(i));
}
} else {
result.addPoint(pointList.get(0));
for(int i=1;i<pointList.size()-1;i++){
ArrayList<Point> temp = new ArrayList<Point>();
temp.add(pointList.get(i));
for (int j=1;j<=REDUCE_NOISE_LEVEL;j++){
if (i-j>0) {
temp.add(pointList.get(i-j));
}
if (i+j<pointList.size()-1){
temp.add(pointList.get(i+j));
}
}
int x=0,y=0;
for(int j=0;j<temp.size();j++){
x += temp.get(j).x;
y += temp.get(j).y;
}
result.addPoint(new Point(x/temp.size(),y/temp.size()));
}
result.addPoint(pointList.get(pointList.size()-1));
}
return result;
} | 7 |
public Aresta retiraAresta(int v1, int v2) {
int index;
for (index = v1; this.prox[index] != 0; index = this.prox[index])
if (this.cab[this.prox[index]] == v2)
break;
int ind = this.prox[index];
if (this.cab[ind] == v2) {
Aresta aresta = new Aresta(v1, v2, this.peso[ind]);
this.cab[ind] = this.cab.length;
if (this.prox[ind] == 0)
this.cab[v1] = index;
this.prox[index] = this.prox[ind];
return aresta;
} else
return null;
} | 4 |
@Override
public int compareTo(Object obj) {
String objString = null;
String ourString = null;
// if obj is not effectively one of us ...
if (! this.getClass().isInstance(obj)) {
throw new ClassCastException ();
}
// get the strings
objString = ((StrungDocumentInfo)obj).getString();
ourString = string;
// if we're ignoring case
if (ignoreCase) {
// we'll compare in uppercase
objString = objString.toUpperCase();
ourString = ourString.toUpperCase();
}
// compare
return ourString.compareTo(objString);
} | 2 |
private boolean hiddenField(String name) {
boolean hidden = false;
for (int i = 0; i < HIDDEN.length; i++) {
if (HIDDEN[i].equals(name))
hidden = true;
}
return hidden;
} | 2 |
private CvSeq findBiggestContour(IplImage imgThreshed) {
CvSeq bigContour = null;
CvSeq contours = new CvSeq(null);
cvFindContours(imgThreshed, contourStorage, contours, Loader.sizeof(CvContour.class), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
float maxArea = SMALLEST_AREA;
CvBox2D maxBox = null;
while (contours != null && !contours.isNull()) {
if (contours.elem_size() > 0) {
CvBox2D box = cvMinAreaRect2(contours, contourStorage);
if (box != null) {
CvSize2D32f size = box.size();
float area = size.width() * size.height();
if (area > maxArea) {
maxArea = area;
bigContour = contours;
}
}
}
contours = contours.h_next();
}
return bigContour;
} | 5 |
static Coordinates nextBackwardPosition(Coordinates position, Direction direction) {
if (direction == NORTH)
return new Coordinates(position.getX(), position.getY() - 1);
if (direction == SOUTH)
return new Coordinates(position.getX(), position.getY() + 1);
if (direction == EAST)
return new Coordinates(position.getX() - 1, position.getY());
return new Coordinates(position.getX() + 1, position.getY());
} | 3 |
@Override
public void extract() throws XMLStreamException, FileNotFoundException
{
FileInfo simc = this.bfis.get(Parser.Types.SIMC.toString());
this.factory = XMLInputFactory.newInstance();
this.readerRaw = factory.createXMLStreamReader(new BufferedInputStream(new FileInputStream(simc.getFile())));
this.reader = factory.createFilteredReader(readerRaw, this.newLineFilter);
while (reader.hasNext())
{
int next = reader.next();
switch (next)
{
case XMLStreamConstants.START_ELEMENT:
this.newElement(reader.getLocalName());
break;
case XMLStreamConstants.CHARACTERS:
tagContent = reader.getText().trim();
break;
case XMLStreamConstants.END_ELEMENT:
this.endElement(reader.getLocalName());
break;
}
if(precincts.size() >= 1000)
{
this.save();
}
parserMessages.sendProgress(reader.getLocation().getLineNumber(), simc.getLines());
}
this.save();
} | 5 |
boolean isLeapYear(int year) {
if (year == 0) {
throw new IllegalArgumentException("Illegal year: " + year);
}
return mod(year, 4) == (year > 0 ? 0 : 3);
} | 2 |
public World(int size)
{
this.size = size;
w = new String[size+1][size+1];
for (int x = 0; x <= size; x++)
{
for (int y = 0; y <= size; y++)
{
w[x][y] = UNKNOWN;
}
}
setVisited(1, 1);
} | 2 |
@Test
public void testCheckCellStatus() throws IOException {
System.out.println("checkCellStatus");
int[] cell = new int[2];
cell[0] = 1;
cell[1] = 1;
Sense.condition cond = Sense.condFromString("FRIEND");
AntBrain ab = new AntBrain("cleverbrain1.brain");
Ant a = new Ant(ab,false,0);
World instance = new World();
boolean expResult = false;
boolean result = instance.checkCellStatus(cell, cond, a);
assertEquals(expResult, result);
} | 0 |
public static void pollIO() {
// Clear KeyPresses
for(int i=0; i<keyPress.length; i++) keyPress[i] = false;
// Update Keyboard Table
while(Keyboard.next()) {
if(Keyboard.getEventKeyState()) {
keyDown[Keyboard.getEventKey()] = true;
} else {
keyDown[Keyboard.getEventKey()] = false;
keyPress[Keyboard.getEventKey()] = true;
}
}
// Update Mouse Tables
mouseX = Mouse.getX();
mouseY = Mouse.getY();
mousedX = Mouse.getDX();
mousedY = Mouse.getDY();
while(Mouse.next()) {
if(Mouse.getEventButtonState()) {
if(Mouse.getEventButton() == 0) leftMouse = true;
else if(Mouse.getEventButton() == 1) rightMouse = true;
} else {
if(Mouse.getEventButton() == 0) leftMouse = true;
else if(Mouse.getEventButton() == 1) rightMouse = true;
}
}
} | 9 |
private void LoadContent() {
try {
URL carImgUrl = this.getClass().getResource("/raceresources/resources/images/car2.png");
carImg = ImageIO.read(carImgUrl);
carImgWidth = carImg.getWidth();
carImgHeight = carImg.getHeight();
URL carWonImgUrl = this.getClass().getResource("/raceresources/resources/images/car2.png");
carWonImg = ImageIO.read(carWonImgUrl);
URL carCrashedImgUrl = this.getClass().getResource("/raceresources/resources/images/car2.png");
carCrashedImg = ImageIO.read(carCrashedImgUrl);
// URL carFireImgUrl = this.getClass().getResource("/raceresources/resources/images/car_fire.png");
// carFireImg = ImageIO.read(carFireImgUrl);
} catch (IOException ex) {
Logger.getLogger(Car.class.getName()).log(Level.SEVERE, null, ex);
}
} | 1 |
public static void run(TestOptions testOption){
if (testOption == TestOptions.ALL_TESTS){
for (TestOptions option : TestOptions.values()){
if (option != TestOptions.ALL_TESTS){
if (option != TestOptions.PCB442 && option != TestOptions.PR2392){
runTestingInstance(option);
}
}
}
}
else{
runTestingInstance(testOption);
}
} | 5 |
public int restriccionTabu(double cambio, int indice1, int indice2)
{
String url = "jdbc:derby://localhost:1527/PDPIVP";
String selectdatos="SELECT * FROM EstructuraTabu";
double resultadotabu=0;
double resultadofinal=0;
int indice1_var=0;
int indice2_var=0;
int tabu=0;
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
//catch SQLException
Connection con = DriverManager.getConnection(url, "Balam", "Balam");
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery(selectdatos);
for (int i=0;i<3;i++){
rs.next();
indice1_var=rs.getInt("Indice1");
indice2_var=rs.getInt("Indice2");
if(indice1_var==indice1){
if(indice2_var==indice2){
tabu=1;
}
}
}
rs = stmt.executeQuery("SELECT * FROM ResultadosIVP");
rs.next();
resultadofinal=Double.parseDouble(rs.getString("ResultadoFinal"));
resultadotabu=Double.parseDouble(rs.getString("ResultadoTabu"));
resultadotabu+=cambio;
if(resultadotabu<resultadofinal){
tabu=0;
}
}
catch(ClassNotFoundException e){
System.out.println("no se encontro la clase \n"+
"error ClassNotFoundException");
System.out.println(e.toString());
}
catch(SQLException e){
System.out.println("error de conexion \n"+
"error SQLException");
System.out.println(e.toString());
}
return tabu;
} | 6 |
public static void main(String[] args) {
Estrutura ed = new Estrutura(100);
Scanner scan = new Scanner(System.in);
String cor;
double altura;
while (true) {
menuPrincipal();
String res = scan.next();
switch (res){
case "1":
System.out.println("Digite a cor");
cor = scan.next();
System.out.println("Digite o tamanho");
altura = Double.parseDouble(scan.next());
ed.insert(cor, altura);
break;
case "2":
menuConsulta();
String resC = scan.next();
switch (resC){
case "1":
System.out.println("Digite a cor");
cor = scan.next();
ed.buscaPorCor(cor);
break;
case "2":
System.out.println("Digite o tamanho");
altura = Double.parseDouble(scan.next());
ed.buscaPorAltura(altura);
break;
case "3":
ed.displayAll();
break;
}
break;
default :
return;
}
}
} | 6 |
public static void addFille(Personne pers, Fille fille) {
List enfants;
try {
if (pers instanceof Pere) {//Un pere ajoute un fils
//On recupere la liste des enfants du pere
enfants = ((Pere) pers).getEnfants();
fille.setPere((Pere) pers);
if (enfants.contains(fille) == false) {//verification si il n'est pas deja ajouter
try {
enfants.add(fille);
} catch (Exception e) {
System.out.println("erreur d'ajout de la fille pour le pere");
e.printStackTrace();
}
} else {
System.out.println("Cette personne est deja ajouter dans la la liste de vos enfants");
return;
}
} else if (pers instanceof Mere) {//Une mère ajoute un fils
enfants = (((Mere) pers).getEnfants());
fille.setMere((Mere) pers);
if (enfants.contains(fille) == false) {//verification si il n'est pas deja ajouter
try {
enfants.add(fille);
} catch (Exception e) {
System.out.println("Erruer d'ajout de la fille pour la mère");
e.printStackTrace();
}
} else {
System.out.println("Cette personnes est déja dans votre liste d'enfant");
return;
}
}
} catch (Exception e) {
System.out.println(" Cette personne ne peut pas ajouter de fille ");
e.printStackTrace();
}
} | 7 |
@Override
public void select(int howMany, Population from, Population to) {
double fitnessSum = 0.0;
for (int i = 0; i < from.getPopulationSize(); i++) {
fitnessSum += from.get(i).getFitnessValue();
}
double[] fitnesses = new double[from.getPopulationSize()];
for (int i = 0; i < fitnesses.length; i++) {
fitnesses[i] = from.get(i).getFitnessValue() / fitnessSum;
}
double ball = rng.nextDouble();
double step = 1.0/howMany;
double sum = 0;
int index = 0;
for (int i = 0; i < howMany; i++) {
ball += step;
if(ball > 1){
ball -= 1;
index = 0;
sum = 0;
}
for (; index <= fitnesses.length; index++) {
sum += fitnesses[index];
if (sum > ball) {
to.add((Individual) from.get(index).clone());
from.get(index).setLogNotes(from.get(index).getLogNotes() + " " + this.getClass().getCanonicalName());
break;
}
if(index == fitnesses.length - 1){
index = 0;
sum = 0;
}
}
}
} | 7 |
private void handleMetaInput() {
if (this.equalsHelper.state()) {
this.tileSize += 5;
if (this.tileSize > 100) {
this.tileSize = 100;
}
} else if (this.minusHelper.state()) {
this.tileSize -= 5;
if (this.tileSize < 25) {
this.tileSize = 25;
}
}
} | 4 |
public void deleteLevel(int id)
{
try
{
PreparedStatement ps = con.prepareStatement( "DELETE FROM teacher WHERE id=?" );
ps.setInt( 1, id );
ps.executeUpdate();
ps.close();
}
catch( SQLException e )
{
e.printStackTrace();
}
} | 1 |
public void sendRobotData() {
HashMap<String, Player> players = new HashMap<String, Player>(registry.getPlayerManager().getPlayers());
try {
for (String key : players.keySet()) {
Player p = (Player) players.get(key);
if (p != null && p.getRobot().getIsActivated()) {
UDPRobot up = p.createRobotUpdate();
if (up != null) {
try {
sendPacket(up);
} catch (IOException e) {
e.printStackTrace();
//running = false;
}
}
}
}
} catch (ConcurrentModificationException concEx) {
//another thread was trying to modify players while iterating
//we'll continue and the new item can be grabbed on the next update
}
} | 6 |
@Override
public void pressedBuyItem(ItemType itemType) {
ItemData itemStats = Game.getItemData(itemType);
if (HeroInfo.INSTANCE.isHeroAlive()) {
if (money >= itemStats.buyCost && HeroInfo.INSTANCE.hasSpaceForItem(itemType) && GamePlayState.isHeroAliveAndCloseEnoughToMerchant()) {
HeroInfo.INSTANCE.equipItem(itemType);
loseMoney(itemStats.buyCost);
if (itemStats.isUnique) {
removeAvailableItem(itemType);
}
}
}
} | 5 |
private final boolean inputNotCorrect(JFileChooser c) {
if (tf_credName.getText().equals("") || tf_credID.getText().equals("")
|| tf_credIBAN.getText().equals("")
|| tf_credBIC.getText().equals("")
|| tf_execDate.getText().equals("")) {
JOptionPane.showMessageDialog(c,
texte.getString("D_MISSING_VALUES_TEXT"),
texte.getString("D_MISSING_VALUES"),
JOptionPane.ERROR_MESSAGE);
return true;
} else if (Check.wrongDate(props.getProperty(StaticString.P_EXEC_DATE))) {
JOptionPane.showMessageDialog(c,
texte.getString("D_ILLEGAL_DATE_TEXT"),
texte.getString("D_ILLEGAL_DATE"),
JOptionPane.ERROR_MESSAGE);
return true;
}
return false;
} | 6 |
private void add(int previous, int index, Node node) {
Node[] children = node.getChildren(); // nodes following current node
if(node.getChildren().length > 0 && node.hasSinglePath() && node.getChildren()[0].getKey() != TERMINATING_CHARACTER) { // If node has only one path, put the rest in tail array
baseBuffer.put(index, tailIndex); // current index of tail array
addToTail(node.children[0]);
checkBuffer.put(index, previous);
return; // No more child to process
}
int base = findBase(index, children); // Get base value for current index
baseBuffer.put(index, base);
if(previous >= 0){
checkBuffer.put(index, previous); // Set check value
}
for(Trie.Node child : children) { // For each child to double array trie
add(index, index + base + child.getKey(), child);
}
} | 5 |
private void actionShowScores(int difficulty) {
String msg = "<html>";
msg += "<font size=4>";
msg += "Best results - ";
switch (difficulty) {
case Grid.DIFFICULTY_EASY: msg += "easy"; break;
case Grid.DIFFICULTY_MEDIUM: msg += "medium"; break;
case Grid.DIFFICULTY_HARD: msg += "hard"; break;
case Grid.DIFFICULTY_EXTREME: msg += "extreme"; break;
}
msg += " difficulty:";
msg += "</font>";
msg += "<table>";
for (int i = 0; i < 10; i++) {
msg += "<tr><td>";
msg += Scores.getName(difficulty, i);
msg += "</td><td>";
msg += StopwatchLabel.convertTime(Scores.getTime(difficulty, i));
msg += "</td></tr>";
}
msg += "</table></html>";
JOptionPane.showMessageDialog(MainFrame.this, msg,
MainFrame.this.getTitle(), JOptionPane.PLAIN_MESSAGE);
} | 5 |
public User(String n) {
name = n;
} | 0 |
public void setMACKey(EncryptedDataType value) {
this.macKey = value;
} | 0 |
public void run() {
switch(serv) {
case WORLDNAMES:
setWorldNames(services.getAllWorldNames(lang));
System.out.println("worldnames: "+worldNames.size());
break;
case MAPNAMES:
setMapNames(services.getAllMapNames(lang));
System.out.println("mapnames: "+mapNames.size());
break;
case EVENTNAMES:
setEventNames(services.getAllEventNames(lang));
System.out.println("eventnames: "+eventNames.size());
break;
case EVENTS:
setEvents(services.getEventsByWorld(2201));
System.out.println("events: "+events.size()+" updated." + new Date());
break;
case EVENTDETAILS:
setEventDetails(services.getAllEventDetails(lang));
System.out.println("eventdetails: "+eventDetails.size());
}
} | 5 |
public static void dehoist(Node currentNode) {
currentNode.getTree().getDocument().hoistStack.dehoist();
return;
} | 0 |
public boolean equals(Object obj) {
if (obj == this)
return true;
if (obj == null)
return false;
if (obj.getClass() != this.getClass())
return false;
Picture that = (Picture) obj;
if (this.width() != that.width())
return false;
if (this.height() != that.height())
return false;
for (int x = 0; x < width(); x++)
for (int y = 0; y < height(); y++)
if (!this.get(x, y).equals(that.get(x, y)))
return false;
return true;
} | 8 |
public static File getFile(Component parent, String title, boolean write) {
JFileChooser fc = new JFileChooser();
fc.setDialogTitle(title);
if (write) {
fc.showSaveDialog(parent);
} else {
fc.showOpenDialog(parent);
}
File f = fc.getSelectedFile();
if (f == null || (!write && !f.exists()) || (f.exists() && !f.isFile())) {
return null;
}
if (write && f.exists()) {
int r = JOptionPane.showConfirmDialog(parent, "File \""
+ f.getName() + "\" exists. Overwrite?");
if (r != 0) {
return null;
}
}
return f;
} | 9 |
public String getHostname() {
return _hostname;
} | 0 |
protected boolean isMatchingStrategyList( List<StrategyT> aStrategyList1, List<StrategyT> aStrategyList2 )
{
if ( ( aStrategyList1 != null ) && ( aStrategyList2 != null ) )
{
if ( aStrategyList1.size() == aStrategyList2.size() )
{
for ( int i=0; i < aStrategyList1.size(); i++ )
{
if ( aStrategyList1.get( i ).getName().equals( aStrategyList2.get( i ).getName() ) == false )
{
return false;
}
}
return true; // -- list matches in size and names/order --
}
return false;
}
else if ( ( aStrategyList1 == null ) && ( aStrategyList2 == null ) )
{
return true;
}
else
{
return false;
}
} | 7 |
public ArrayList<Integer[]> selection2(ArrayList<Integer[]> population, int size) {
if (size > population.size()) {
return population;
}
ArrayList<Integer[]> parents = new ArrayList<>();
//int matchLength = grades.length / size;
while (parents.size() < size) {
Collections.shuffle(population);
double[] grades = gradeEveryone(population);
int best = 0;
for(int i = 1 ; i < size; ++i){
if(grades[i]<grades[best]){
best = i;
}
}
parents.add(population.get(best));
}
return parents;
} | 4 |
public boolean equals(Auction auction){
if(this.id == auction.id){
return true;
}
else{
return false;
}
} | 1 |
int truncatetable(String tableName) throws ClassNotFoundException, InstantiationException, SQLException, IllegalAccessException {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url, dbUser, dbPass);
Statement stm = con.createStatement();
String query = "TRUNCATE messaging." + tableName + "";
if (stm.execute(query) == true) {
return 1;
} else {
return 0;
}
} | 1 |
public void flush()
{
if (myBitsToGo != BITS_PER_BYTE) {
try{
write( (myBuffer << myBitsToGo) );
}
catch (java.io.IOException ioe){
throw new RuntimeException("error writing bits on flush " + ioe);
}
myBuffer = 0;
myBitsToGo = BITS_PER_BYTE;
}
try{
myOutput.flush();
}
catch (java.io.IOException ioe){
throw new RuntimeException("error on flush " + ioe);
}
} | 3 |
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true){
int n = sc.nextInt();
if(n==0)break;
C[] c = new C[n];
for(int i=0;i<n;i++)c[i]=new C(new Point(sc.nextDouble(), sc.nextDouble()), sc.nextDouble());
int m = sc.nextInt();
while(m--!=0){
Point u = new Point(sc.nextDouble(), sc.nextDouble());
Point v = new Point(sc.nextDouble(), sc.nextDouble());
Line line = new Line(u, v);
boolean danger = true;
for(int i=0;i<n;i++){
//ccwの関係でLineには向きがある
//両方の向きの最大値をとらないと、うまくいかない
double dsp = Math.max(distanceSP(line, c[i].center), distanceSP(new Line(v, u), c[i].center));
if(dsp <= c[i].r){
double n1 = norm(new Point(u.x-c[i].center.x, u.y-c[i].center.y));
double n2 = norm(new Point(v.x-c[i].center.x, v.y-c[i].center.y));
if(!(n1 <= c[i].r && n2 <= c[i].r))
danger = false;
}
}
System.out.println(danger?"Danger":"Safe");
}
}
} | 9 |
private int travelTree(TreeNode node) {
if(node == null) return 0;
int left = travelTree(node.left);
if(left == -1) return -1;
int right = travelTree(node.right);
if(right == -1) return -1;
if(Math.abs(left - right) > 1) return -1;
return left > right ? left + 1 : right + 1;
} | 5 |
@Override
public void handleQuitRequestWith(QuitEvent event, QuitResponse response) {
if (!UIUtilities.inModalState()) {
mAllowQuitIfNoSignificantWindowsOpen = false;
if (closeFrames(true)) {
if (closeFrames(false)) {
saveState();
response.performQuit();
return;
}
}
mAllowQuitIfNoSignificantWindowsOpen = true;
}
response.cancelQuit();
} | 3 |
static LinkedList<Part> sort2(LinkedList<Part> unsorted)
{
if (unsorted.size() <= 1)
return unsorted;
int mid = unsorted.size()/2;
int size = unsorted.size();
LinkedList<Part> sorted = new LinkedList<Part>();
LinkedList<Part> first = new LinkedList<Part>();
LinkedList<Part> second = new LinkedList<Part>();
for (int i = 0; i < mid; i++)
first.addLast(unsorted.removeFirst());
for (int i = mid; i < size; i++)
second.addLast(unsorted.removeFirst());
first = sort2(first);
second = sort2(second);
int i = 0;
int j = 0;
while (i < mid && j < size-mid)
{
if (first.getFirst().index < second.getFirst().index)
{
sorted.addLast(first.removeFirst());
i++;
}
else
{
sorted.addLast(second.removeFirst());
j++;
}
}
while (i < mid)
{
sorted.addLast(first.removeFirst());
i++;
}
while (j < size-mid)
{
sorted.addLast(second.removeFirst());
j++;
}
return sorted;
} | 8 |
public Message toMsgAlbe(String ocsfMsg) {
Message msg = new Message();
StringTokenizer st = new StringTokenizer(ocsfMsg);
msg.setRoomNumber(Integer.parseInt(st.nextToken()));
Room r = s.getRoom(msg.getRoomNumber());
String id = st.nextToken();
msg.setWhat(Integer.parseInt((msg.getRoomNumber()==0 || msg.getWhat()==1)?id:st.nextToken()));
if(!(msg.getRoomNumber()==0) && !(msg.getWhat()==1)){
for(Player p : r.players){
if(p.getId().equals(id)){
msg.setTo(p);
break;
}
}
msg.setWhat(Integer.parseInt(st.nextToken()));
}
if(msg.getRoomNumber()>0){
id = st.nextToken();
for(Player p : r.players){
if(p.getId().equals(id)){
msg.setFrom(p);
break;
}
}
}
msg.setStr(st.nextToken());
return msg;
} | 9 |
private void processWithClassName(ClassLoader classloader, String className, String prefix, TmpStatics tmpStatics) {
Class clazz;
String identification = null;
try {
clazz = classloader.loadClass(className);
Field id = clazz.getField("ID");
identification = (String) id.get(clazz);
} catch (NoSuchFieldException | ClassNotFoundException | IllegalAccessException e) {
e.printStackTrace();
return;
}
if (!identification.startsWith(prefix)) return;
int from = identification.indexOf(':');
String chain = identification.substring(0, from);
if (CommandHandler.class.isAssignableFrom(clazz)) {
String cmdName = identification.substring(from + 1);
tmpStatics.add(chain, cmdName, clazz);
} else if (ConfigHandler.class.isAssignableFrom(clazz)) {
int to = identification.indexOf(':', from + 1);
String cmdName = identification.substring(from + 1, to);
String cfgName = identification.substring(to + 1);
tmpStatics.add(chain, cmdName, cfgName, clazz);
}
} | 4 |
public static void init() {
codes.put("HALT", "HaltCode");
codes.put("POP", "PopCode");
codes.put("FALSEBRANCH", "FalseBranchCode");
codes.put("GOTO", "GoToCode");
codes.put("STORE", "StoreCode");
codes.put("LOAD", "LoadCode");
codes.put("LIT", "LitCode");
codes.put("ARGS", "ArgsCode");
codes.put("CALL", "CallCode");
codes.put("RETURN", "ReturnCode");
codes.put("BOP", "BopCode");
codes.put("READ", "ReadCode");
codes.put("WRITE", "WriteCode");
codes.put("LABEL", "LabelCode");
codes.put("DUMP", "DumpCode");
} | 0 |
@Override
public boolean isInternal(Position<T> p) throws InvalidPositionException {
checkPosition(p);
return (hasLeft(p) || hasRight(p));
} | 1 |
public int calcHLine2(State m) {
int line, column;
int hLine = 0;
for (line = 0; line < m.puzzle.getHeight(); line++) {
for (column = 0; column < m.puzzle.getLength(); column++) {
if ((column == (m.puzzle.getLength() - 1))
&& (line < m.puzzle.getHeight() - 1)) {
if (m.puzzle.getValue(line, column) != (m.puzzle.getValue(line + 1, 0) - 1)) {
hLine++;
}
} else if ((column < m.puzzle.getLength() - 1)
&& (m.puzzle.getValue(line, column) != (m.puzzle.getValue(line, column + 1) - 1))) {
hLine++;
}
}
}
return hLine;
} | 7 |
private void play() {
String gameid = askForNewGame();
int attemptCount = sendAnAttempt(gameid, null);
if (attemptCount == -1) {
System.out.println("PERDU");
} else {
System.out.println("J'ai gagné en " + attemptCount + "!");
}
} | 1 |
public void reorderList(ListNode head) {
// 1. get the middle node of the list (even / odd) and tail node
// 2. divide the list into halves
// 3. reverse the second half, merge two lists
if (head == null)
return;
if (head.next == null)
return;
ListNode fast = head, slow = head;
// temp head of merged list
ListNode res = new ListNode(0);
ListNode cur = res;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
// if fast is the second from last
ListNode firstHalf, secondHalf;
firstHalf = head;
if (fast.next != null) {
secondHalf = reverseList(slow.next);
slow.next = null;
} else {
secondHalf = reverseList(slow);
ListNode tmp = head;
while (tmp.next != slow)
tmp = tmp.next;
tmp.next = null;
}
while (firstHalf != null && secondHalf != null) {
cur.next = firstHalf;
firstHalf = firstHalf.next;
cur = cur.next;
cur.next = secondHalf;
secondHalf = secondHalf.next;
cur = cur.next;
}
if (secondHalf != null)
cur.next = secondHalf;
} | 9 |
public synchronized boolean hasMessage() {
while(_buffers.size() > 0) {
ByteBuffer bytes = _buffers.remove(0);
CharBuffer chars = CharBuffer.allocate(bytes.remaining());
this._decoder.decode(bytes, chars, false); // false: more bytes may follow. Any unused bytes are kept in the decoder.
chars.flip();
this._stringBuf.append(chars);
}
return this._stringBuf.indexOf(this._messageSeparator) > -1;
} | 1 |
public void clearMap(GameAction gameAction) {
for (int i=0; i<keyActions.length; i++) {
if (keyActions[i] == gameAction) {
keyActions[i] = null;
}
}
for (int i=0; i<mouseActions.length; i++) {
if (mouseActions[i] == gameAction) {
mouseActions[i] = null;
}
}
gameAction.reset();
} | 4 |
public void setValue(BigDecimal aValue)
{
BigDecimal tempValue = aValue;
// 12/15/2010 Scott Atwell if ( ( getMinimum() != null ) && ( tempValue.compareTo( getMinimum() ) < 0 ) )
if ( ( getMinimum() != null ) && ( tempValue != null ) && ( tempValue.compareTo( getMinimum() ) < 0 ) )
{
tempValue = getMinimum();
}
// 12/15/2010 Scott Atwell else if ( ( getMaximum() != null ) && ( tempValue.compareTo( getMaximum() ) > 0 ) )
else if ( ( getMaximum() != null ) && ( tempValue != null ) && ( tempValue.compareTo( getMaximum() ) > 0 ) )
{
tempValue = getMaximum();
}
// 12/15/2010 Scott Atwell text.setText( tempValue.toPlainString() );
if ( tempValue != null )
{
text.setText( tempValue.toPlainString() );
}
else
{
text.setText( "" );
}
text.selectAll();
text.setFocus();
} | 7 |
private int addConfigFields(JPanel p, String groupName)
{
GridBagConstraints c = new GridBagConstraints();
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
c.insets = new Insets(1, 1, 1, 1);
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 1;
for (final Field f : CraftConfig.class.getFields())
{
final Setting s = f.getAnnotation(Setting.class);
Object obj = null;
try
{
obj = f.get(null).toString();
if (s == null || obj == null)
continue;
if (!s.group().equals(groupName))
continue;
if (s.level() > CraftConfig.showLevel)
continue;
final Component comp = getSwingComponentForField(f, s);
if (comp == null)
continue;
final JLabel label = new JLabel(s.title() + ":");
JButton helpButton = null;
if (!s.description().equals(""))
{
helpButton = new JButton("?");
helpButton.setMargin(new java.awt.Insets(0, 1, 0, 1));
helpButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(label, s.description());
}
});
helpButton.setBackground(levelColor(s.level()));
}
comp.setPreferredSize(new Dimension(100, 25));
c.weightx = 0;
c.gridx = 0;
p.add(helpButton, c);
c.weightx = 1;
c.gridx = 1;
p.add(label, c);
c.gridx = 2;
p.add(comp, c);
c.gridy++;
} catch (IllegalArgumentException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
return c.gridy;
} | 9 |
private double edgeY(int x, int y, double[][] smoothedGray) {
return 1*smoothedGray[x-1][y-1] - 1*smoothedGray[x+1][y-1] +
2*smoothedGray[x-1][y] - 2*smoothedGray[x+1][y] +
1*smoothedGray[x-1][y+1] - 1*smoothedGray[x+1][y+1];
} | 0 |
public void setImgPath_CommandBtn(Path img, Imagetype type) {
switch (type) {
case KEYFOCUS:
this.imgComBtn_KFoc = handleImage(img, UIResNumbers.COMBTN_KFOC.getNum());
if (this.imgComBtn_KFoc == null) {
this.imgComBtn_KFoc = UIDefaultImagePaths.COMBTN_KFOC.getPath();
deleteImage(UIResNumbers.COMBTN_KFOC.getNum());
}
break;
case MOUSEFOCUS:
this.imgComBtn_MFoc = handleImage(img, UIResNumbers.COMBTN_MFOC.getNum());
if (this.imgComBtn_MFoc == null) {
this.imgComBtn_MFoc = UIDefaultImagePaths.COMBTN_MFOC.getPath();
deleteImage(UIResNumbers.COMBTN_MFOC.getNum());
}
break;
case PRESSED:
this.imgComBtn_Pre = handleImage(img, UIResNumbers.COMBTN_PRE.getNum());
if (this.imgComBtn_Pre == null) {
this.imgComBtn_Pre = UIDefaultImagePaths.COMBTN_PRE.getPath();
deleteImage(UIResNumbers.COMBTN_PRE.getNum());
}
break;
case DEFAULT:
this.imgComBtn_Def = handleImage(img, UIResNumbers.COMBTN_DEF.getNum());
if (this.imgComBtn_Def == null) {
this.imgComBtn_Def = UIDefaultImagePaths.COMBTN_DEF.getPath();
deleteImage(UIResNumbers.COMBTN_DEF.getNum());
}
if (img != null) {
this.imgComBtn_Def_addToLayout = true;
} else {
this.imgComBtn_Def_addToLayout = false;
}
break;
default:
throw new IllegalArgumentException();
}
somethingChanged();
} | 9 |
@Override
public boolean equals(Object object) {
if (!(object instanceof UserGroup)) {
return false;
}
UserGroup other = (UserGroup) object;
if ((this.groupName == null && other.groupName != null) || (this.groupName != null && !this.groupName.equals(other.groupName))) {
return false;
}
return true;
} | 5 |
public void parseMethod(TypeDeclaration typeDecl, MethodDeclaration methodDecl, Method method) {
Type[] types = method.getArgumentTypes();
int offset;
if (Modifier.isStatic(methodDecl.getAccess())) {
offset = 0;
} else {
// Reference to this is first argument for member method.
offset = 1;
}
for (int i=0; i<types.length; i++) {
VariableDeclaration variableDecl = new VariableDeclaration(VariableDeclaration.LOCAL_PARAMETER);
variableDecl.setName(VariableDeclaration.getLocalVariableName(method, offset, 0));
variableDecl.setType(types[i]);
methodDecl.addParameter(variableDecl);
offset += types[i].getSize();
}
if (methodDecl.getCode() == null) return;
Log.getLogger().debug("Parsing " + methodDecl.toString());
Pass1 pass1 = new Pass1(jc);
try {
pass1.parse(method, methodDecl);
} catch (Throwable ex) {
ASTNode node = null;
if (ex instanceof ParseException) {
node = ((ParseException) ex).getAstNode();
} else {
node = Pass1.getCurrentNode();
}
if (J2JSCompiler.compiler.isFailOnError()) {
throw Utils.generateException(ex, methodDecl, node);
} else {
String msg = Utils.generateExceptionMessage(methodDecl, node);
J2JSCompiler.errorCount++;
Log.getLogger().error(msg + "\n" + Utils.stackTraceToString(ex));
}
Block body = new Block();
ThrowStatement throwStmt = new ThrowStatement();
MethodBinding binding = MethodBinding.lookup("java.lang.RuntimeException", "<init>", "(java/lang/String)V;");
ClassInstanceCreation cic = new ClassInstanceCreation(methodDecl, binding);
cic.addArgument(new StringLiteral("Unresolved decompilation problem"));
throwStmt.setExpression(cic);
body.appendChild(throwStmt);
methodDecl.setBody(body);
}
// Remove from body last expressionless return statement.
if (J2JSCompiler.compiler.optimize && methodDecl.getBody().getLastChild() instanceof ReturnStatement) {
ReturnStatement ret = (ReturnStatement) methodDecl.getBody().getLastChild();
if (ret.getExpression() == null) {
methodDecl.getBody().removeChild(ret);
}
}
Pass1.dump(methodDecl.getBody(), "Body of " + methodDecl.toString());
// if (typeDecl.getClassName().equals("java.lang.String")) {
// if (methodDecl.isInstanceConstructor()) {
//
// }
// }
return;
} | 9 |
public void checkParameters(String[] args) {
if ((args.length == 1) && args[0].equalsIgnoreCase("-help")) {
System.out.println("Parameters: \r\n (1) total number of entries [optional, defaulfs to 10,000]");
}
if (args.length > 0) {
documentCount = Integer.parseInt(args[0]);
}
} | 3 |
public static void main(String args[]) throws SQLException {
//Troca o LookAndFeel
try {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Servidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Servidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Servidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Servidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//----------------------------------------------------------
try {
//Inicia um servidor socket
ServerSocket server = new ServerSocket(5436);
//Chama a interface grafica
m = new Main();
m.setVisible(true);
m.atualizaPedidos();
//O servidor fica escutando a porta 5555 para novas conexoes
while (true) {
Socket conexao = server.accept();
Thread t = new Servidor(conexao);
t.start();
}
} catch (IOException e) {
}
} | 6 |
private void visitExpr(FormatDecl.BitField f, String name, int bit, int[] result) {
Expr e = f.field;
if ( matches(e, name) ) {
for ( int cntr = 0; cntr < f.getWidth(); cntr++ ) result[cntr] = cntr + bit;
} else if ( e.isBitRangeExpr() ) {
FixedRangeExpr bre = (FixedRangeExpr)e;
if ( matches(bre.expr, name) ) {
for ( int cntr = 0; cntr < f.getWidth(); cntr++ ) {
int indx = cntr+bre.low_bit;
// we don't care about bits beyond the end of our declared operand
if ( indx < result.length )
result[indx] = cntr + bit;
}
}
} else if ( e instanceof IndexExpr ) {
IndexExpr be = (IndexExpr)e;
if ( matches(be.expr, name) && be.index.isLiteral() ) {
int value = ((Literal.IntExpr)be.index).value;
result[value] = bit;
}
}
} | 9 |
public final void updatePosition(int x, int y, boolean flag) {
if (animationId != -1 && Sequence.sequenceCache[animationId].walkProperties == 1) {
animationId = -1;
}
if (!flag) {
int destX = x - walkQueueX[0];
int destY = y - walkQueueY[0];
if (destX >= -8 && destX <= 8 && destY >= -8 && destY <= 8) {
if (walkQueueLocationIndex < 9) {
walkQueueLocationIndex++;
}
for (int i1 = walkQueueLocationIndex; i1 > 0; i1--) {
walkQueueX[i1] = walkQueueX[i1 - 1];
walkQueueY[i1] = walkQueueY[i1 - 1];
runningFlags[i1] = runningFlags[i1 - 1];
}
walkQueueX[0] = x;
walkQueueY[0] = y;
runningFlags[0] = false;
return;
}
}
walkQueueLocationIndex = 0;
anInt1542 = 0;
anInt1503 = 0;
walkQueueX[0] = x;
walkQueueY[0] = y;
this.x = walkQueueX[0] * 128 + anInt1540 * 64;
this.y = walkQueueY[0] * 128 + anInt1540 * 64;
} | 9 |