text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public void merge(int[] myList, int low1, int mid, int low2, int high)
{
/* check if stopButton has been selected */
if(stopFlag == true)
{
return;
}
/* create a temp array to hold the sorted ints, initialize iterators etc. */
int[] tempArray = new int[(mid - low1) + (high - low2) + 2];
int s1 = low1; /* starting point for lower half */
int s2 = low2; /* starting point for upper half */
int d = 0; /* index for tempArray */
int k = 0;
while(s1 <= mid && s2 <= high) /* while elements remaining in BOTH halves */
{
/* compare one element from lower half with one element from upper half;
* put the smaller of the two ints into tempArray */
if(myList[s1] < myList[s2])
{
tempArray[d++] = myList[s1++];
}
else
{
tempArray[d++] = myList[s2++];
}
}//end while(s1 <= mid && s2 <= high)
/* at this point, either s1 has reached mid or s2 has reached high (ie one of the
* two halves is exhausted), so copy whatever is left of the array half (that
* hasn't been exhausted) into tempArray */
/* copy over remaining elements in lower half of array if s1 isnt already at mid */
while(s1 <= mid)
{
tempArray[d++] = myList[s1++];
}
/* copy over remaining elements in upper half of array if s2 isnt already at high */
while(s2 <= high)
{
tempArray[d++] = myList[s2++];
}
/* copy merge-sorted tempArray over to myList */
for(k = 0, s1 = low1; s1 <= high; s1++, k++)
{
myList[s1] = tempArray[k];
repaint();
try
{
sortThread.sleep(getMsSleepDuration());
}
catch(InterruptedException e)
{
System.out.println("Error: sleep interrupted" + e);
}
}//end for loop
}//end merge() | 8 |
public void movimiento(){
while(carro.getCaminoEnSeguimiento().darPrimerNodo()!=null)
{
if(carro.evaluarSiguienteMovimiento()){
try {
sleep(movingTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
carro.avanzarEnCamino();
}
else
{
try {
sleep(waitingTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} | 4 |
public Object getValueAt(int row, int col) {
if (row > -1 && col > -1 && data != null) {
return data[row][col];
} else {
return null;
}
} | 3 |
public static void main(String[] args) {
try {
Socket sk = new Socket("192.168.1.220",9090);
sk.getOutputStream().write("GET /echo HTTP/1.1\r\n".getBytes("utf-8"));
sk.getOutputStream().write("Upgrade: websocket\r\n".getBytes("utf-8"));
sk.getOutputStream().write("Connection: Upgrade\r\n".getBytes("utf-8"));
sk.getOutputStream().write("Host: 192.168.1.220:9090\r\n".getBytes("utf-8"));
sk.getOutputStream().write("Origin: null\r\n".getBytes("utf-8"));
sk.getOutputStream().write("Sec-WebSocket-Key: tO03f6yG86XB6K2k0UEfRg==\r\n".getBytes("utf-8"));
sk.getOutputStream().write("Sec-WebSocket-Version: 13\r\n".getBytes("utf-8"));
sk.getOutputStream().write("Sec-WebSocket-Extensions: x-webkit-deflate-frame\r\n\r\n".getBytes("utf-8"));
sk.getOutputStream().flush();
Thread.currentThread().sleep(200);
createInputMonitorThread(sk.getInputStream(),sk.getOutputStream());
/*GET /echo HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 192.168.1.220:9090
Origin: null
Sec-WebSocket-Key: tO03f6yG86XB6K2k0UEfRg==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame*/
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 3 |
private static ArrayList<Double> loadFunctionData( String filename ){
ArrayList<Double> fnData = new ArrayList<Double>();
try
{
java.io.InputStream in = Wavelet.class.getResourceAsStream(filename);
CSVReader reader = new CSVReader(new InputStreamReader(in));
List<String[]> myEntries = reader.readAll();
for(int i = 0; i < myEntries.size(); i++)
{
String[] content = myEntries.get(i);
for(int j = 0; j< content.length; j++)
{
fnData.add( Double.parseDouble( content[j]) );
}
}
reader.close();
}
catch(Exception ex){}
return fnData;
}// end loadFunctionData method. | 3 |
public String getData() {
if (data == null)
return null;
return data.toString();
} | 1 |
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 0) {
return motherLangWordList.get(rowIndex);
}
if (columnIndex == 1) {
return translationList.get(rowIndex);
}
if (columnIndex == 2) {
return idList.get(rowIndex);
}
else {
return "0";
}
} | 3 |
public static void main(String args[]){
int i=0;
int j=0;
for(i=1;i<10;i++){
for(j=1;j<10;j++){
totalarray[i][j] = cross;
}
}
for(i=1;i<4;i++){
for(j=1;j<4;j++){
subarray(i,j);
}
}
finalwin = checkarray(bigarraydecision,zero);
finalwin = checkarray(bigarraydecision,cross);
System.out.print(finalwin);
} | 4 |
public static <T> T fromJson(final String inJson, Class<T> objClass) {
try {
boolean errorFound = false;
// if API returned errors or warnings
if (GsonErrors.class.isAssignableFrom(objClass)) {
GsonErrors gsonErrors = gson.fromJson(inJson, GsonErrors.class);
if (gsonErrors != null) {
// print errors
if (gsonErrors.getErrors() != null) {
errorFound = true;
Logging.error("The API returned the following error(s): ");
for (String error : gsonErrors.getErrors()) {
Logging.error(error);
}
}
// print warnings
if (gsonErrors.getWarnings() != null) {
errorFound = true;
Logging.warn("The API returned the following warning(s): ");
for (String warning : gsonErrors.getWarnings()) {
Logging.warn(warning);
}
}
if (errorFound) return null;
}
}
T resultObj = gson.fromJson(inJson, objClass);
return resultObj;
} catch (Exception e) {
return null;
}
} | 8 |
protected List<Exit> findExits(Modifiable M,XMLTag piece, Map<String,Object> defined, BuildCallback callBack) throws CMException
{
try
{
final List<Exit> V = new Vector<Exit>();
final String tagName="EXIT";
final List<XMLLibrary.XMLTag> choices = getAllChoices(null,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(M,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Build Exit: "+CMStrings.limit(valPiece.value(),80)+"...");
defineReward(M,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
final Exit E=buildExit(valPiece,defined);
if(callBack != null)
callBack.willBuild(E, valPiece);
V.add(E);
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
catch(PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
} | 8 |
public static void main(String[] args) {
// Initialization
Deck playDeck = new Deck();
playDeck.shuffle();
Hand playerHand = new Hand();
playerHand.drawNewHand(playDeck);
Hand computerHand = new Hand();
computerHand.drawNewHand(playDeck);
// Playing the game
playerHand.evaluate();
int[] playerScore = playerHand.getEvaluation();
computerHand.evaluate();
int[] computerScore = computerHand.getEvaluation();
int[] genList = { 0, 1, 2, 3 };
for (int num : genList) {
if (playerScore[num] > computerScore[num]) {
System.out.println("Win");
break;
} else if (playerScore[num] < computerScore[num]) {
System.out.println("Lose");
break;
}
else if (num == 3){
System.out.println("Draw");
break;
}
}
System.out.println(playerScore[0]+ " " +playerScore[1]+ " " +playerScore[2]+ " " +playerScore[3]);
System.out.println(computerScore[0] + " " + computerScore[1] + " " + computerScore[2] + " " + computerScore[3]);
} | 4 |
@Override
public void run() {
Object value = null;
RoomInfo roomInfo;
String resultString;
try {
oIn = new ObjectInputStream(new BufferedInputStream(
socket.getInputStream()));
value = oIn.readObject();
try {
roomInfo = getByEvent((String) value);
if(roomInfo!=null)
{
resultString = roomInfo.toJSONObject().toJSONString();
System.out.println(TAG+" normal return: "+resultString);
}
else
{
resultString = "";
System.out.println(TAG+" error? or isStarted false ");
}
oOut = new ObjectOutputStream(new BufferedOutputStream(
socket.getOutputStream()));
oOut.writeObject(resultString);
oOut.flush();
System.out.println("success");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
} catch (ClassNotFoundException e) {
} finally {
freeResources(socket, oIn, oOut);
}
} | 4 |
public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
for (Map.Entry<T, E> entry : map.entrySet()) {
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
} | 2 |
@Override
public boolean equals(Object obj) {
if (obj instanceof BulkItem) {
BulkContainer objBulk = (BulkContainer) obj;
if (objBulk.food == this.food && objBulk.amount == this.amount
&& objBulk.unit == this.unit && objBulk.container == this.container)
return true;
else
return false;
}//if
else
return false;
}//equals(Object obj) | 5 |
public void keyReleased(KeyEvent evt){
switch(evt.getKeyCode()){
case KeyEvent.VK_W:
upPress = 0;
break;
case KeyEvent.VK_S:
downPress = 0;
break;
case KeyEvent.VK_A:
leftPress = 0;
break;
case KeyEvent.VK_D:
rightPress = 0;
break;
case KeyEvent.VK_I:
doPath = false;
break;
}
} | 5 |
public TeaNode getNode(String[] valuesCombination) {
String[] strValues = new String[2];
strValues[0] = valuesCombination[0];
strValues[1] = valuesCombination[2];
Double sugar = valuesCombination[1] == null ? 0
: Double.parseDouble(valuesCombination[1]);
for (TeaNode node : this.nodes()) {
if(ArrayUtils.isEquals(node.valuesCombination, valuesCombination)) {
return node;
}
}
return null;
} | 3 |
private static boolean
backrefMatcher(REGlobalData gData, int parenIndex,
char[] chars, int end)
{
int len;
int i;
int parenContent = gData.parens_index(parenIndex);
if (parenContent == -1)
return true;
len = gData.parens_length(parenIndex);
if ((gData.cp + len) > end)
return false;
if ((gData.regexp.flags & JSREG_FOLD) != 0) {
for (i = 0; i < len; i++) {
if (upcase(chars[parenContent + i]) != upcase(chars[gData.cp + i]))
return false;
}
}
else {
for (i = 0; i < len; i++) {
if (chars[parenContent + i] != chars[gData.cp + i])
return false;
}
}
gData.cp += len;
return true;
} | 7 |
public List<infoNode> getInfo() {
ArrayList<infoNode> info = new ArrayList<infoNode>();
NodeList infoNodes = node.getChildNodes();
for (int i = 0; i < infoNodes.getLength(); i++) {
Node node = infoNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
infoNode infoNode = new infoNode(node);
info.add(infoNode);
}
}
return info;
} | 2 |
private boolean initialize()
{
CommPortIdentifier portID = null;
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
System.out.println("Trying ports:");
while(portID == null && ports.hasMoreElements())
{
CommPortIdentifier testPort = (CommPortIdentifier) ports.nextElement();
System.out.println(" " + testPort.getName());
if(testPort.getName().startsWith(portName))
{
try
{
serialPort = (SerialPort) testPort.open(programName, 1000);
portID = testPort;
System.out.println("Connected on " + portID.getName());
break;
}
catch(PortInUseException e)
{
System.out.println(e);
}
}
}
if(portID == null || serialPort == null)
{
System.out.println("Could not connect to Arduino!");
return false;
}
try
{
serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
Thread.sleep(2000);
return true;
}
catch(Exception e)
{
System.out.println(e);
}
return false;
} | 7 |
public void report_error(String message, Object info) {
StringBuffer m = new StringBuffer("Error");
if (info instanceof java_cup.runtime.Symbol) {
java_cup.runtime.Symbol s = ((java_cup.runtime.Symbol) info);
if (s.left >= 0) {
m.append(" in line "+(s.left+1));
if (s.right >= 0)
m.append(", column "+(s.right+1));
}
}
m.append(" : "+message);
System.err.println(m);
} | 3 |
private void makePacks(List<Card> cardList) {
for (Card.Suit suit : Card.Suit.values()) {
//No kings.
for (int i = 0; i < Card.Rank.values().length - 1; i++) {
cardList.add(new Card(suit, Card.Rank.values()[i], true));
}
//No kings or aces.
for (int i = 1; i < Card.Rank.values().length - 1; i++) {
cardList.add(new Card(suit, Card.Rank.values()[i], true));
}
}
} | 3 |
private void jBt_IngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBt_IngresarActionPerformed
// TODO add your handling code here:
ButtonModel bm = this.bGr_Motivo.getSelection();
if(bm!=null){
if(this.jRb_Archivo1.isSelected()) // Si es ingreso manual, pasa a la pantalla solicitando los datos
{
panelSuperior(getPanelInterno2());
}else
{
boolean ok =false;
if(this.jRb_Archivo.isSelected())
{
try {
File archivo = fileChooser.abrirArchivo();
if(archivo!=null){
Utilitario.mensajeProcedimientoCorrecto("Se realizo el ingreso de las caravanas correctamente", "Ingreso de Caravanas");
//this.dispose();
ok = true;
}
} catch (InputMismatchException e) {
Utilitario.mensajeError("Archivo seleccionado no pudo ser encontrado.", "ERROR");
}catch (Exception exc){
Utilitario.mensajeError(exc.toString(),"ERROR");
}
}
if(ok){
getPanelIngresoD().actualizar();
panelSuperior(getPanelIngresoD());;
}
}
}else{
Utilitario.mensajeError("Debe seleccionar un motivo.", "ERROR");
}
}//GEN-LAST:event_jBt_IngresarActionPerformed | 7 |
private void paintOnScreen() {
try {
graphics = buffer.getDrawGraphics();
graphics.drawImage( bi, 0, 0, null );
if( !buffer.contentsLost() )
buffer.show();
Thread.yield(); // Let the OS have a little time...
} finally {
// release resources
if( graphics != null )
graphics.dispose();
if( g2d != null )
g2d.dispose();
}
} | 3 |
@Override
public void collideWith(Element e) {
if (e instanceof PlayerCTF) {
final PlayerCTF playerEntered = (PlayerCTF) e;
// You have to enter your own StartingPosition
if (player.equals(playerEntered)) {
final PlayerFlag inventoryFlag = playerEntered.getInventory().findFlag();
if (inventoryFlag != null) {
// The flag you bring in has to be of an other player
if (!inventoryFlag.getPlayer().equals(player)) {
getGrid().addElementToPosition(inventoryFlag, inventoryFlag.getPlayerInfo().getBeginPosition());
playerEntered.addCapturedPlayerFlag(inventoryFlag.getPlayerInfo());
playerEntered.getInventory().remove(inventoryFlag);
}
}
}
}
} | 4 |
public boolean matchesAndOneAbove(Card other) {
return (other.getSuit() == this.suit && this.rank.ordinal() == other.getRank().ordinal() + 1);
} | 1 |
public boolean SurviveVisions(int[] inTargets, byte[] inVisions){ // returns true if this set of visions is compatible
// with this GameState. In the boolean array, 1 means innocent, 2 means wolf, 0 means no target.
boolean output = true;
for(int n = 0; n < NumPlayers; n++){
if(this.playerTest(n+1) == 2){
if(inTargets[n] == 0) return true; // No vision was had, therefore no conflict.
output = ((playerTest(inTargets[n]) <= (-3)) || (playerTest(inTargets[n]) >= 3)); // output is now
// true if the Seer saw a wolf.
output = (((inVisions[n] == 2) && output) || ((inVisions[n] == 1) && !output));
}
}
return output;
} | 7 |
private void preprocessDataTwo(double commonError){
// Check row and column lengths
this.numberOfRows = this.values.length;
this.numberOfColumns = this.values[0].length;
for(int i=1; i<this.numberOfRows; i++){
if(this.values[i].length!=this.numberOfColumns)throw new IllegalArgumentException("All rows of the value matrix must be of the same length");
}
this.diagonalLength = this.numberOfRows;
if(this.numberOfRows>this.numberOfColumns)this.diagonalLength = this.numberOfColumns;
// Fill errors matrix
this.errors = new double[this.numberOfRows][this.numberOfColumns];
for(int i=0; i<this.numberOfRows; i++){
for(int j=0; j<this.numberOfColumns; j++){
this.errors[i][j] = commonError*commonError;
}
}
} | 5 |
SlotAction parseSlotAction (Model model, Set<String> variables) throws Exception
{
String operator = "";
if (t.getToken().equals("-") || t.getToken().equals("<") || t.getToken().equals(">")
|| t.getToken().equals("<=") || t.getToken().equals(">="))
{
operator = t.getToken();
t.advance();
}
Symbol slot = Symbol.get (operator+t.getToken());
if (slot.isVariable() && !variables.contains(slot.getString()))
model.recordWarning ("variable '" + slot.getString() + "' is not set", t);
t.advance();
Symbol value = Symbol.get (t.getToken());
if (value.isVariable() && !variables.contains(value.getString()))
model.recordWarning ("variable '" + value.getString() + "' is not set", t);
t.advance();
return new SlotAction (model, slot, value);
} | 9 |
public void generate(int files, int payments) {
int x;
int y;
int total = 0;
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
for (x = 0; x < files; x++) {
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("PAYMENTS");
doc.appendChild(rootElement);
for (y = 0; y < payments; y++) {
++total;
String payer = "payer" + total;
String recipient = "recipient" + total;
String details = "details" + total;
Element payment = doc.createElement("payment");
rootElement.appendChild(payment);
switch (y % 3) {
case 0:
addPhysicalElements(doc, payment, payer,
"physical_payer");
addPhysicalElements(doc, payment, recipient,
"physical_recipient");
addDetailsElements(doc, payment, details);
break;
case 1:
addLegalElements(doc, payment, payer, "legal_payer");
addLegalElements(doc, payment, recipient,
"legal_recipient");
addDetailsElements(doc, payment, details);
break;
case 2:
addPhysicalElements(doc, payment, payer,
"physical_payer");
addLegalElements(doc, payment, recipient,
"legal_recipient");
addDetailsElements(doc, payment, details);
}
}
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
String fileFullPath = GENERATE_PATH + x + ".xml";
StreamResult result = new StreamResult(new File(fileFullPath));
transformer.transform(source, result);
logger.debug("File {} successfully generated!", fileFullPath);
}
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
} | 7 |
public int GetTravelTime()
{
//return the travel time
return this.offBusTicks - this.onBusTicks;
} | 0 |
public void disconnect() {
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {} // not much else I can do
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {} // not much else I can do
try{
if(socket != null) socket.close();
}
catch(Exception e) {} // not much else I can do
// inform the GUI
if(cg != null)
cg.connectionFailed();
} | 7 |
protected boolean canHaveAsElement(Position pos, Element elem) {
return elem != null && pos != null && grid.getElementsOnPosition(pos).isEmpty();
} | 2 |
public static double binaryShannonEntropyDit(double p) {
if (p > 1.0) throw new IllegalArgumentException("The probabiliy, " + p + ", must be less than or equal to 1");
if (p < 0.0) throw new IllegalArgumentException("The probabiliy, " + p + ", must be greater than or equal to 0");
double entropy = 0.0D;
if (p > 0.0D && p < 1.0D) {
entropy = -p * Math.log10(p) - (1 - p) * Math.log10(1 - p);
}
return entropy;
} | 4 |
protected void avoid(mxCellState edge, mxCellState vertex)
{
mxIGraphModel model = graph.getModel();
Rectangle labRect = edge.getLabelBounds().getRectangle();
Rectangle vRect = vertex.getRectangle();
if (labRect.intersects(vRect))
{
int dy1 = -labRect.y - labRect.height + vRect.y;
int dy2 = -labRect.y + vRect.y + vRect.height;
int dy = (Math.abs(dy1) < Math.abs(dy2)) ? dy1 : dy2;
int dx1 = -labRect.x - labRect.width + vRect.x;
int dx2 = -labRect.x + vRect.x + vRect.width;
int dx = (Math.abs(dx1) < Math.abs(dx2)) ? dx1 : dx2;
if (Math.abs(dx) < Math.abs(dy))
{
dy = 0;
}
else
{
dx = 0;
}
mxGeometry g = model.getGeometry(edge.getCell());
if (g != null)
{
g = (mxGeometry) g.clone();
if (g.getOffset() != null)
{
g.getOffset().setX(g.getOffset().getX() + dx);
g.getOffset().setY(g.getOffset().getY() + dy);
}
else
{
g.setOffset(new mxPoint(dx, dy));
}
model.setGeometry(edge.getCell(), g);
}
}
} | 6 |
public State getState()
{
return state;
} | 0 |
public void draw(Graphics2D g) {
int w = getWidth();
int h = getHeight();
RoundRectangle2D box = new RoundRectangle2D.Float(
0, 0, w, h, 20, 20);
g.setColor(background);
g.fill(box);
GradientPaint paint;
/*
GradientPaint paint = new GradientPaint(
0, 0, Color.DARK_GRAY, 0, h, Color.LIGHT_GRAY);
g.setPaint(paint);
*/
int bx = (int)getBallX();
int by = (int)getBallY();
int bw = (int)getBallWidth();
int minX = (int)getBallX(this.min);
int maxX = (int)getBallX(this.max);
g.setColor(isEnabled() ? Color.GRAY : background);
g.setStroke(new BasicStroke(1.5f));
g.drawLine(minX, by, maxX, by);
g.drawLine(maxX + (int)getMargin(), 0, maxX + (int)getMargin(), h);
g.setColor(isEnabled() ? Color.LIGHT_GRAY : background);
g.setStroke(new BasicStroke(1.5f));
g.draw(box);
// Draw ticks
//g.drawLine(minX, by - bw/4, minX, by + bw/4);
//g.drawLine(maxX, by - bw/4, maxX, by + bw/4);
Ellipse2D ball = new Ellipse2D.Double(
bx - bw/2, by - bw/2, bw, bw);
g.setColor(isEnabled() ? Color.GRAY : background);
g.fill(ball);
int y1 = by - bw/2;
int y2 = down? by + bw * 2 : by + bw/2;
if (isEnabled()) {
paint = new GradientPaint(
0, y1, new Color(0xddffffff, true),
0, y2, new Color(0x00ffffff, true));
g.setPaint(paint);
g.fill(ball);
paint = new GradientPaint(
0, by - bw/2, Color.LIGHT_GRAY,
0, by + bw/2, Color.BLACK);
g.setPaint(paint);
g.draw(ball);
}
g.setColor(Color.LIGHT_GRAY);
g.setFont(font);
String s = decimalValue.format(value) + unit;
g.drawString(s, w - getGutter() + 5, h - 17);
g.setFont(new Font(null, 0, 14));
g.drawString(getText(), minX, h - 4);
} | 5 |
@Override
public String get(long i)
{
if (ptr != 0) {
short strLen = stringLengths.getShort(i);
if (strLen < 0) return null;
long offset = sizeof * i * maxStringLength * CHARSET_SIZE;
for (int j = 0; j < strLen; j++) {
byteArray[j] = Utilities.UNSAFE.getByte(ptr + offset + sizeof * j);
}
try {
return new String(byteArray, 0, strLen, CHARSET);
} catch (UnsupportedEncodingException ex) {
return null;
}
} else {
if (isConstant()) {
return data[0];
} else {
return data[(int) i];
}
}
} | 5 |
public void sortBySuit() {
// Sorts the cards in the vHand so that cards of the same suit are
// grouped together, and within a suit the cards are sorted by value.
// Note that aces are considered to have the lowest value, 1.
Vector vNewHand = new Vector();
while (vHand.size() > 0) {
int pos = 0; // Position of minimal card.
Card c = (Card)vHand.elementAt(0); // Minumal card.
for (int i = 1; i < vHand.size(); i++) {
Card c1 = (Card)vHand.elementAt(i);
if ( c1.getSuit() < c.getSuit() ||
(c1.getSuit() == c.getSuit() && c1.getValue() < c.getValue()) ) {
pos = i;
c = c1;
}
}
vHand.removeElementAt(pos);
vNewHand.addElement(c);
}
vHand = vNewHand;
} | 5 |
public static void main(String[] args) {
ArrayList<Commands> inputCommands;
ArrayList<Commands> outputCommands;
ArrayList<Commands> sorted;
Scanner inputText = new Scanner(System.in);
String text;
String path = "";
System.out.println("Enter path-name or leave blank for a sample text: ");
boolean check = false;
while(check == false){
text = inputText.nextLine();
if(text.equals("")){
path = "src\\Files\\sample.txt";
break;
} else {
path = text;
} if(!Units.CheckGetCommandList(path)){
break;
}
System.out.println("Not a valid path, enter path-name or leave blank for a sample text: ");
}
inputCommands = FileReader.getCommandList(path);
outputCommands = Logic.formatCommandList(inputCommands);
sorted = Logic.Sort(outputCommands);
//Prints everything with a dynamic length
String format = "%1$-9s %2$-20s %3$-19s %4$-1s";
System.out.format(format,"Command:","Source path:","Target path:","Catalog:");
System.out.print("\n");
for (Commands print : sorted) {
System.out.format(format, print.getCommand()
, print.getPath()
, print.getMovePath()
, print.getCatalog()
+ "\n");
}
} | 4 |
public String getRecommendListForPreferentialAttachment() {
String recommend = "";
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/NETWORK_TEST?"
+ "user=root&password=root");
connect.setAutoCommit(false);
statement = connect.createStatement();
for (String node : this.nodeList) {
String sql = "select d2.node as recommend, (d1.degree * d2.degree) as score "
+ "from (select START_NODE as node, count(*) as degree from network_test." + this.table
+ " where START_NODE = '" + node + "'"
+ ") as d1, (select START_NODE as node, count(*) as degree from network_test." + this.table
+ " group by START_NODE) as d2 where d1.node <> d2.node "
+ "and (d1.node, d2.node) not in (select * from network_test." + this.table
+ ") order by score desc limit 10";
resultSet = statement.executeQuery(sql);
recommend += node + ":";
while (resultSet.next()) {
String recommendNode = resultSet.getString("Recommend");
recommend += recommendNode + ",";
}
recommend += "\n";
}
connect.commit();
statement.close();
connect.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
if(statement!=null)
statement.close();
} catch(SQLException se2) {
}// nothing we can do
try{
if(connect!=null)
connect.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
return recommend;
} | 8 |
public Route geefRoute(Knooppunt start, Knooppunt stop) throws IllegalArgumentException {
if(knooppuntOpMuur(stop) == true || knooppuntOpMuur(start) == true) throw new IllegalArgumentException("start en/of stop mogen niet op een muur vallen");
if (start.equals(stop)) {
Route routeNaarZelfdePunt = new Route();
routeNaarZelfdePunt.appendKnooppunt(start);
routeNaarZelfdePunt.appendKnooppunt(stop);
return routeNaarZelfdePunt;
}
RouteMetaData bezochtevelden[][] = new RouteMetaData[this.speelveld.length][this.speelveld[0].length];
bezoekVeld(start, bezochtevelden, null, 0);
printBezochteVelden(bezochtevelden);
return contrueerRoute(bezochtevelden, stop);
} | 3 |
private boolean cargarProductosVendidos(int idVenta, LinkedList<Pair> productos, LinkedList<BigDecimal> preciosFinales) {
boolean resultOp = true;
Iterator itr = productos.iterator();
Articulo prod;
Pair par;
BigDecimal cant;
Venta v = Venta.findById(idVenta);
if (v.getBoolean("pago")) {
Iterator itr2 = preciosFinales.iterator();
while (itr.hasNext()) {
par = (Pair) itr.next(); //saco el par de la lista
BigDecimal precioFinal = (BigDecimal) itr2.next();
prod = (Articulo) par.first(); //saco el producto del par
cant = ((BigDecimal) par.second()).setScale(2, RoundingMode.CEILING);//saco la cantidad del par
ArticulosVentas prodVendido = ArticulosVentas.create("venta_id", idVenta, "articulo_id", prod.get("id"), "cantidad", cant, "precio_final", precioFinal);
resultOp = resultOp && prodVendido.saveIt();
}
} else {
while (itr.hasNext()) {
par = (Pair) itr.next(); //saco el par de la lista
prod = (Articulo) par.first(); //saco el producto del par
cant = ((BigDecimal) par.second()).setScale(2, RoundingMode.CEILING);//saco la cantidad del par
ArticulosVentas prodVendido = ArticulosVentas.create("venta_id", idVenta, "articulo_id", prod.get("id"), "cantidad", cant);
resultOp = resultOp && prodVendido.saveIt();
}
}
return resultOp;
} | 5 |
public boolean mousedown(Coord c, int button) {
if (folded) {
if (!c.isect(Coord.z, isz.add(cl.sz())))
return false;
if (c.isect(Coord.z.add(cl.sz()), isz))
return true;
}
if (awnd != null)
awnd.setfocus(awnd);
else
parent.setfocus(this);
raise();
if (super.mousedown(c, button))
return (true);
if (!c.isect(Coord.z, sz))
return (false);
if (button == 1) {
ui.grabmouse(this);
doff = c;
if (c.isect(new Coord(sz.x - gzsz.x, 0), gzsz))
rsm = true;
else
dm = true;
}
return (true);
} | 8 |
public static void closeDB() {
try {
if (connection != null) {
connection.close();
}
if (statement != null) {
statement.close();
}
if (rs != null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} | 4 |
protected void gmcpSaySend(String sayName, MOB mob, Environmental target, CMMsg msg)
{
if((mob.session()!=null)&&(mob.session().getClientTelnetMode(Session.TELNET_GMCP)))
{
mob.session().sendGMCPEvent("comm.channel", "{\"chan\":\""+sayName+"\",\"msg\":\""+
MiniJSON.toJSONString(CMLib.coffeeFilter().fullOutFilter(null, mob, mob, target, null, CMStrings.removeColors(msg.sourceMessage()), false))
+"\",\"player\":\""+mob.name()+"\"}");
}
final Room R=mob.location();
if(R!=null)
for(int i=0;i<R.numInhabitants();i++)
{
final MOB M=R.fetchInhabitant(i);
if((M!=null)&&(M!=msg.source())&&(M.session()!=null)&&(M.session().getClientTelnetMode(Session.TELNET_GMCP)))
{
M.session().sendGMCPEvent("comm.channel", "{\"chan\":\""+sayName+"\",\"msg\":\""+
MiniJSON.toJSONString(CMLib.coffeeFilter().fullOutFilter(null, M, mob, target, null, CMStrings.removeColors(msg.othersMessage()), false))
+"\",\"player\":\""+mob.name()+"\"}");
}
}
} | 8 |
private static Relationshiptype setBeanProperties(ResultSet resultset) {
Relationshiptype relationshiptype = new Relationshiptype();
try {
relationshiptype.setId(resultset.getInt("id"));
relationshiptype.setName_a_b(resultset.getString("name_a_b"));
relationshiptype.setLabel_a_b(resultset.getString("label_a_b"));
relationshiptype.setName_b_a(resultset.getString("name_b_a"));
relationshiptype.setLabel_b_a(resultset.getString("label_b_a"));
relationshiptype.setDescription(resultset.getString("description"));
String contact_type_a = resultset.getString("contact_type_a");
if (contact_type_a.equals("Individual")) {
relationshiptype.setContact_type_a(Relationshiptype.Enum_contact_type.INDIVIDUAL);
}
if (contact_type_a.equals("Organization")) {
relationshiptype.setContact_type_a(Relationshiptype.Enum_contact_type.ORGANIZATION);
}
if (contact_type_a.equals("Household")) {
relationshiptype.setContact_type_a(Relationshiptype.Enum_contact_type.HOUSEHOLD);
}
String contact_type_b = resultset.getString("contact_type_b");
if (contact_type_b.equals("Individual")) {
relationshiptype.setContact_type_b(Relationshiptype.Enum_contact_type.INDIVIDUAL);
}
if (contact_type_b.equals("Organization")) {
relationshiptype.setContact_type_b(Relationshiptype.Enum_contact_type.ORGANIZATION);
}
if (contact_type_b.equals("Household")) {
relationshiptype.setContact_type_b(Relationshiptype.Enum_contact_type.HOUSEHOLD);
}
relationshiptype.setContact_sub_type_a(resultset.getString("contact_sub_type_a"));
relationshiptype.setContact_sub_type_b(resultset.getString("contact_sub_type_b"));
relationshiptype.setIs_reserved(resultset.getBoolean("is_reserved"));
relationshiptype.setIs_active(resultset.getBoolean("is_active"));
return relationshiptype;
} catch (SQLException ex) {
Logger.getLogger(RelationshiptypeController.class.getName()).log(Level.SEVERE, null, ex);
return null;
} catch (Exception e) {
Logger.getLogger(RelationshiptypeController.class.getName()).log(Level.SEVERE, null, e);
return null;
}
} | 8 |
@Override
public Extension[] getChildren()
{
NodeList children = configEntry.getChildNodes();
if(children != null) {
Extension[] res = new Extension[children.getLength()];
int newIndex = 0;
for(int i = 0; i < children.getLength(); i++) {
Node entry = children.item(i);
// make sure that it is not a pure text entry
if(entry.hasAttributes() || entry.hasChildNodes()) {
res[newIndex] = new XMLExtension(entry);
newIndex++;
}
}
// did we omit some entries? Resize array.
if(newIndex != children.getLength()) {
res = Arrays.copyOf(res, newIndex);
}
return res;
}
return null;
} | 5 |
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int t = 1; t <= T; t++) {
int N = sc.nextInt();
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = sc.nextInt();
}
int min = N, ind = arr[0];
for (int i = 0; i < N; i++) {
int a = 0, b = 0;
for (int j = 0; j < N; j++) {
if (i == j) {
continue;
}
if (arr[j] < arr[i]) {
a++;
}
if (arr[j] > arr[i]) {
b++;
}
}
if (Math.abs(a - b) < min) {
min = Math.abs(a - b);
ind = arr[i];
}
}
System.out.println("Case " + t + ": " + ind);
}
} | 8 |
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((dir == null) ? 0 : dir.hashCode());
result = prime * result + ((hexLoc == null) ? 0 : hexLoc.hashCode());
return result;
} | 2 |
@Override
public boolean halt(Event lastEvent, OurSim ourSim) {
boolean halt = true;
List<Job> finishedJobsList = new LinkedList<Job>();
for (ActiveEntity entity : ourSim.getGrid().getAllObjects()) {
if (entity instanceof Broker) {
Broker broker = (Broker) entity;
List<Job> jobs = broker.getJobs();
int currentlyFinished = 0;
for (Job job : jobs) {
if (job.getState().equals(ExecutionState.FINISHED)) {
currentlyFinished++;
finishedJobsList.add(job);
}
}
halt &= currentlyFinished >= finishedJobs;
}
}
if (halt) {
for (Job job : finishedJobsList) {
System.out.println(job.getEndTime());
}
}
return halt;
} | 6 |
public void declareWinner() {
int white, black;
white = black = 0;
String string;
for(int i = 0 ; i < board_row; i++) {
for(int j = 0; j < board_col; j++) {
ChipColor color = board_array[i][j].getChipColor();
if(color == ChipColor.WHITE)
white++;
else if(color == ChipColor.BLACK)
black++;
}
}
if(white > black)
this.winner_string = "You win";
else
this.winner_string = "You lose";
this.winner = true;
this.repaint();
} | 5 |
public void save() throws IOException {
JSONObject json = new JSONObject();
json.put("startYear", startDate.getYear());
json.put("startMonth", startDate.getMonth());
json.put("startDay", startDate.getDay());
json.put("username", username);
json.put("displayName", displayName);
json.put("isRightHanded", isRightHanded);
json.put("favoriteDiscName", favoriteDiscName);
json.put("favoriteCourseName", favoriteCourseName);
json.put("gamesPlayed", gamesPlayed);
json.put("holesInOne", holesInOne);
json.put("albatrosses", albatrosses);
json.put("eagles", eagles);
json.put("birdies", birdies);
json.put("pars", pars);
json.put("bogeys", bogeys);
json.put("doubleBogeys", doubleBogeys);
json.put("tripleBogeys", tripleBogeys);
json.put("worstHole", worstHole);
json.put("lifetimeThrows", lifetimeThrows);
json.put("lifetimeOverUnder", lifetimeOverUnder);
try {
File file = new File("profiles/" + username + ".json");
FileWriter fw = new FileWriter(file.getAbsolutePath());
fw.write(json.toString());
fw.close();
} catch (IOException ex) {
Logger.getLogger(Profile.class.getName()).log(Level.SEVERE, null, ex);
}
saveDiscs();
} | 1 |
public boolean getBoolean(String key) throws JSONException {
Object object = this.get(key);
if (object.equals(Boolean.FALSE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a Boolean.");
} | 6 |
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(string != null) {
for(int i=0;i<string.length;i++) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics lm = font.getLineMetrics(string[i], frc);
float width = (float) font.getStringBounds(string[i], frc).getWidth();
float height = lm.getAscent() + lm.getDescent();
nextX += width;
nextY = height*lines + 14;
float x;
float y;
if(getX()+nextX > getX()+getWidth()-4) {
lines++;
x = 4;
y = nextY + height;
nextX = width + 4;
nextY = height*lines + 14;
} else {
x = nextX - width;
y = nextY;
}
g2.setColor(color[i]);
g2.drawString(string[i], x, y);
}
nextX = 4;
nextY = 4;
lines = 0;
}
} | 3 |
public Object getInternal() {
return internal;
} | 0 |
private String readByteArray() {
StringBuffer buf = new StringBuffer();
int count = 0;
char w = (char) 0;
// read individual bytes and format into a character array
while ((loc < stream.length) && (stream[loc] != '>')) {
char c = (char) stream[loc];
byte b = (byte) 0;
if (c >= '0' && c <= '9') {
b = (byte) (c - '0');
} else if (c >= 'a' && c <= 'f') {
b = (byte) (10 + (c - 'a'));
} else if (c >= 'A' && c <= 'F') {
b = (byte) (10 + (c - 'A'));
} else {
loc++;
continue;
}
// calculate where in the current byte this character goes
int offset = 1 - (count % 2);
w |= (0xf & b) << (offset * 4);
// increment to the next char if we've written four bytes
if (offset == 0) {
buf.append(w);
w = (char) 0;
}
count++;
loc++;
}
// ignore trailing '>'
loc++;
return buf.toString();
} | 9 |
private void AITurn() throws CloneNotSupportedException {
Coordinates toHit = new Coordinates();
do {
// first time hit any ship
if (strategie == null && lastAttackResult == true) {
strategie = new AttackStrategie(lastAttack);
toHit = strategie.getNextAttack(lastAttackResult);
} // go on with strategie ;)
else if (strategie != null) {
toHit = strategie.getNextAttack(lastAttackResult);
// to do chech if allready in hit fields
if (toHit == null) {
strategie = null;
toHit = getRandomCoordinates();
}
} else {
toHit = getRandomCoordinates();
}
} while (alreadyHit.contains(toHit));
alreadyHit.add(toHit);
// to do
// hit field with coordinates
lastAttack = toHit;
Message<Coordinates> hitMessage = new MessageFactory<Coordinates>().createMessage(eMessageType.attack, toHit);
// game
game.handleOponentMessage(hitMessage);
} | 5 |
public String convert(HashMap<String, Integer> dv) {
// El mensaje debe ser en la forma IP:costo para cada elemento del dv en vez del espacio como separador del vector
StringBuilder result = new StringBuilder();
result.append("From:");
result.append(Setup.ROUTER_NAME);
result.append("\n");
result.append("Type:DV\n");
result.append("Len:");
result.append(dv.size());
result.append("\n");
for(String name : dv.keySet()) {
int costo = dv.get(name);
result.append(name);
result.append(":");
result.append(costo);
result.append("\n");
}
return result.toString();
} | 1 |
public void monitorFileModify(Path file) {
try {
if(file.startsWith(sourceDir) &&
!Files.isDirectory(file)){
Path subPath = sourceDir.relativize(file);
for(Path targetDir : targetDirs){
Path newPath = targetDir.resolve(subPath);
if(!newPath.toFile().exists() || !FileUtils.contentEquals(newPath.toFile(),file.toFile())){
Files.createDirectories(newPath.getParent());
logger.info("cp "+file.toString()+" "+newPath.toString());
new File(newPath.toString()).setWritable(true);
Files.copy(file, newPath, REPLACE_EXISTING);
}
}
}
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
}
} | 6 |
public void setDescriptor(String desc) {
if (!desc.equals(getDescriptor()))
descriptor = constPool.addUtf8Info(desc);
} | 1 |
@Override
public JSONObject addPUserPollActivity(String userId, String name,
String option) throws JSONException {
boolean isSuccess=false;
JSONObject mainobj=new JSONObject();
try {
pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(Poll.class, ":p.contains(pollName)");
List<Poll> result = (List<Poll>) query.execute(name);
if (result != null)
if (result.size() > 0) {
result.get(0).addCount(option);
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage());
mainobj.put("Response", "Error");
return mainobj;
}
//Now adding user attempted status to User DB
try {
pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(User.class, ":p.contains(userId)");
List<User>result = (List<User>) query.execute(userId);
if(result!=null)
if(result.size()>0)
{
isSuccess=result.get(0).addUserPollActivity(name);
if(isSuccess)
{
mainobj=getPollStatus(name);
}
else
{
mainobj.put("Response", "Error");
}
}
pm.close();
} catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage());
mainobj.put("Response", "Error");
return mainobj;
}
return mainobj;
} | 7 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
MInterface other = (MInterface) obj;
if (operations == null) {
if (other.operations != null)
return false;
} else if (!operations.containsAll(other.operations) || !other.operations.containsAll(operations)) // any order
return false;
if (pub != other.pub)
return false;
return true;
} | 8 |
public String getSchemeSpecificPart() {
StringBuffer schemespec = new StringBuffer();
if (m_userinfo != null || m_host != null || m_port != -1) {
schemespec.append("//"); //$NON-NLS-1$
}
if (m_userinfo != null) {
schemespec.append(m_userinfo);
schemespec.append('@');
}
if (m_host != null) {
schemespec.append(m_host);
}
if (m_port != -1) {
schemespec.append(':');
schemespec.append(m_port);
}
if (m_path != null) {
schemespec.append( (m_path));
}
if (m_queryString != null) {
schemespec.append('?');
schemespec.append(m_queryString);
}
if (m_fragment != null) {
schemespec.append('#');
schemespec.append(m_fragment);
}
return schemespec.toString();
} | 9 |
private void export() {
if(modelCompareShipping == null) return;
Integer columnCount = jTableReport.getColumnCount() == 0 ? 1 : jTableReport.getColumnCount();
Integer rowCount = jTableReport.getRowCount() + 5;
Object[][] data = new Object[rowCount][columnCount];
StringBuilder line = new StringBuilder();
if(jComboBoxRegion.getSelectedIndex() == 0) {
List<Agent> selectedAgent = modelSelectedAgent.getList();
line.append("Клиенты: ");
for(Agent agent : selectedAgent) {
line.append(agent.getId() + "; ");
}
} else {
line.append("Регион: " + jComboBoxRegion.getSelectedItem().toString());
if(jRadioButtonRegionPrice.isSelected()){
line.append(" Региональный прайс: " + ((RegionPrice) jComboBoxRegionPrice.getSelectedItem()).toString());
}else if(jRadioButtonGroupPrice.isSelected()){
line.append(" Групповой прайс: " + ((GroupPrice) jComboBoxGroupPrice.getSelectedItem()).toString());
}else{
line.append(" Все:");
}
}
String first = "Период 1: с " + new SimpleDateFormat(Application.TABLE_DATE).format(jXDatePickerFirstStart.getDate()) + " по " + new SimpleDateFormat(Application.TABLE_DATE).format(jXDatePickerFirstEnd.getDate());
String second = "Период 2: с " + new SimpleDateFormat(Application.TABLE_DATE).format(jXDatePickerSecondStart.getDate()) + " по " + new SimpleDateFormat(Application.TABLE_DATE).format(jXDatePickerSecondEnd.getDate());
data[0][0] = line.toString();
data[1][0] = first;
data[2][0] = second;
JTableHeader[] headers = new JTableHeader[columnCount];
for(int i = 0; i < columnCount; i++) {
JTableHeader header = jTableReport.getTableHeader();
data[4][i] = header.getColumnModel().getColumn(i).getHeaderValue();
}
for(int i = 0; i < rowCount - 5; i++) {
for(int j = 0; j < columnCount; j++) {
data[i + 5][j] = jTableReport.getValueAt(i, j);
}
}
data[1][11] = "=SUBTOTAL(9,L7:L" + rowCount + ")";
data[2][11] = "=SUBTOTAL(3,L7:L" + rowCount + ")";
data[1][12] = "=SUBTOTAL(9,M7:M" + rowCount + ")";
data[2][12] = "=SUBTOTAL(3,M7:M" + rowCount + ")";
data[1][13] = "=P3*100/(P3-R3)-100";
data[1][14] = "=Q3*100/(Q3-S3)-100";
data[1][15] = "=SUBTOTAL(9,P7:P" + rowCount + ")";
data[1][16] = "=SUBTOTAL(9,Q7:Q" + rowCount + ")";
data[1][17] = "=SUBTOTAL(9,R7:R" + rowCount + ")";
data[1][18] = "=SUBTOTAL(9,S7:S" + rowCount + ")";
data[1][19] = "=SUBTOTAL(9,T7:T" + rowCount + ")";
data[1][20] = "=SUBTOTAL(9,U7:U" + rowCount + ")";
ServiceApplication.openOpenSaveJDialogXLS(this, data);
} | 9 |
public String getAddressDetail() {
StringBuilder addressDetail = new StringBuilder();
addressDetail.append(getStreetName() + "\n" + getCityName() + ", "
+ getStateName() + "\n" + getCountry() + "\nPin: "
+ getZipCode());
return addressDetail.toString();
} | 0 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
fillFibo(45);
int testCases = Integer.parseInt(in.readLine().trim());
for (int t = 0; t < testCases; t++) {
int n = Integer.parseInt(in.readLine().trim());
int prev = -1, p;
while (n != 0) {
p = bs(n);
for (int i = p + 1; prev != -1 && i < prev; i++)
out.append('0');
out.append('1');
n -= fibo[p];
prev = p;
}
for (int i = 1; prev != -1 && i < prev; i++)
out.append('0');
out.append('\n');
}
System.out.print(out);
} | 6 |
public static Packet01JSON decode(byte[] data) throws IOException {
ByteArrayInputStream stream = new ByteArrayInputStream(data);
try {
stream.reset();
return new Packet01JSON(mapper.readValue(stream, Map.class));
} catch (Exception e) {
System.out.println("odd, unknown error");
e.printStackTrace();
}
return null;
} | 1 |
public void run() {
try {
Telnet.writeLine(cs, "<fggreen> >>> Welcome to AdaMUD <<< <reset>");
Telnet.flushInput(cs);
while((player = s.getPlayerDB().login(cs, s)) == null);
player.look();
while (true) {
System.out.println("Waiting for message");
String message = Telnet.readLine(cs).trim();
if(message == null) {
//Disconnected
break;
}
if(message.equals("bye")) {
Telnet.writeLine(cs, "Goodbye!");
break;
}
parseCommand(message);
}
cs.close();
}
catch (IOException e) {
System.out.println("Client error: " + e);
}
finally {
s.getPlayerDB().remove(player);
s.remove(cs);
}
} | 5 |
public static int uniforme(double... probas) {
// TODO à revoir
double p = rand.nextDouble();
// System.out.println("p : " + p);
boolean stop = false;
int i = 0;
double proba = 0;
while (!stop && i < probas.length) {
// System.out.println("i : " + i);
proba += probas[i];
// System.out.println("proba : "+proba);
if (p < proba) {
stop = true;
}
i++;
}
return i - 1;
} | 3 |
public short deinitialize()
{
exit.set(true);
// Stop the packet sniffing
MsgAnalyzerCmnDef.WriteDebugSyslog("De-initialize the SerialReceiver object\n");
short ret = serial_receiver.deinitialize();
if (MsgAnalyzerCmnDef.CheckFailure(ret))
return ret;
// Notify the worker thread of analyzing serial data to die...
// t.interrupt();
MsgAnalyzerCmnDef.WriteDebugSyslog("Notify the worker thread of analyzing the serial data it's going to die...");
synchronized(this)
{
notify();
}
MsgAnalyzerCmnDef.WriteDebugSyslog("Wait for the worker thread of analyzing serial data's death...");
try
{
//wait till this thread dies
t.join();
// System.out.println("The worker thread of receiving serial data is dead");
MsgAnalyzerCmnDef.WriteDebugSyslog("Wait for the worker thread of analyzing serial data's death Successfully !!!");
}
catch (InterruptedException e)
{
MsgAnalyzerCmnDef.WriteDebugSyslog("The analyzing serial data worker thread throws a InterruptedException...");
}
catch(Exception e)
{
MsgAnalyzerCmnDef.WriteErrorSyslog("Error occur while waiting for death of analyzing serial data worker thread, due to: " + e.toString());
}
return ret;
} | 3 |
public int Problem41() {
for (int n=9;n>=1;n--) {
int[] digits = new int[n];
for (int i=0;i<digits.length;i++) {
digits[i]=i+1;
}
int result=-1;
do {
if(Utility.isPrime(Utility.toInteger(digits))) {
result = Utility.toInteger(digits);
}
}while (Utility.nextPermutation(digits));
if (result!=-1) {
return result;
}
}
throw new RuntimeException("Not Found");
} | 5 |
private Cmds getCommand(String message) {
int begin = message.indexOf(' ') + 1;
int end = message.indexOf(' ', begin);
if(end == NOT_FOUND)
end = message.length();
String cmd = message.substring(begin, end).toUpperCase();
try {
return Cmds.valueOf(cmd);
} catch (IllegalArgumentException iae) {
return Cmds.INVALID;
}
} | 2 |
private void assignGamePoints() {
// Get our card points and game value.
int curCardPoints = countCardPoints(declarerIndex);
int curGameValue = gameValue();
// Grab our player and tricks won pile for them.
PlayerInfo player = players[declarerIndex];
Pile pile = player.getTricksWonPile();
// There are 4 possible win conditions:
boolean wonGame = false;
if (gameType.getGameType() == GameTypeOptions.GameType.Null) {
// If it's null, and declarer won no tricks.
wonGame = pile.getNumCards() == 0;
} else if (gameType.getSchwarz()) {
// If schwarz and declarer won all tricks.
wonGame = (pile.getNumCards() == 30);
} else if (gameType.getSchneider()) {
// If schneider and declarer won at-least 90 card points.
wonGame = (curCardPoints >= 90 && curGameValue >= highestBid);
} else {
// If any other case, declarer must've won over 60 points.
wonGame = (curCardPoints > 60 && curGameValue >= highestBid);
}
// If we won the game, add to score, otherwise subtract
String tempParts = this.players[(declarerIndex)].getPlayer().getClass().getName().replaceAll("skatgame.", "");
if(wonGame) {
player.setGameScore(player.getGameScore() + curGameValue);
this.roundStats.log("The " + tempParts + " has won " + curGameValue + " points this round.", this.indentationLevel);
} else {
player.setGameScore(player.getGameScore() - (2 * curGameValue));
this.roundStats.log("The " + tempParts +" has lost " + (2 * curGameValue) + " points this round.", this.indentationLevel);
}
// Let our players know the round stats (we used to not have rounds, so this was called game stats, whoops..)
int[] endGameScores = new int[PLAYER_COUNT];
for(int i = 0; i < endGameScores.length; i++)
endGameScores[i] = this.players[i].getGameScore();
for(PlayerInfo playerInfo : this.players)
playerInfo.getPlayer().endGameInfo(wonGame, endGameScores);
} | 8 |
public static boolean isValid(MouseEvent e, Canvas c, Palette pal)
{
if (pal != null && pal.getSelectedColor(e.getButton()) == null) return false;
Point p = e.getPoint();
if (p.x < 0 || p.y < 0) return false;
Dimension d = c.getImageSize();
if (p.x >= d.width || p.y >= d.height) return false;
return true;
} | 6 |
private VappClient createVApp(IControllerServices controllerServices, String vCloudUrl, String username, String password, String orgName, String vdcName, String vAppName, String catalogName, String templateName, String network) throws ConnectorException
{
VappClient vCloudApp = new VappClient(controllerServices);
try {
// logging in
String loginResponse = vCloudApp.login(vCloudUrl, username, orgName, password);
// getting org links
Document doc = RestClient.stringToXmlDocument(loginResponse);
String allOrgsLink = doc.getElementsByTagName(Constants.LINK).item(0).getAttributes().getNamedItem(Constants.HREF).getTextContent().trim();
//
//needs to be removed in case createVdc needs to be removed
String adminLink = doc.getElementsByTagName(Constants.LINK).item(1).getAttributes().getNamedItem(Constants.HREF).getTextContent().trim();
String orgLink = vCloudApp.retrieveOrg(allOrgsLink, orgName);
// To instantiate a vApp template you need the vDc on which the vApp is going to be deployed and the object
// references for the catalog in which the vApp template will be entered.
String vdcLink = vCloudApp.findVdc(orgLink, vdcName);
String catalogLink = vCloudApp.findCatalog(orgLink, catalogName);
String templateLink = vCloudApp.retrieveTemplate(catalogLink, templateName);
String response = vCloudApp.newvAppFromTemplate(vAppName, templateLink, catalogLink, vdcLink, network);
String vAppLink = vCloudApp.retrieveVappLink(response);
vCloudApp.setvAppLink(vAppLink);
}
catch (Exception e) {
throw new ConnectorException(e);
}
return vCloudApp;
} | 1 |
@Override
public void loadRcon() throws DataLoadFailedException {
Map<String, Object> data = getData("server", "name", "rcon");
load(PermissionType.RCON, "rcon", data);
} | 0 |
public final synchronized void close(){
if(fileFound){
try{
input.close();
}catch(java.io.IOException e){
System.out.println(e);
}
}
} | 2 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
}
});
} | 6 |
/* */ public void checkFire()
/* */ {
/* 114 */ for (int i = 0; i < Core.barricades.size(); i++) {
/* 115 */ Barricade b = (Barricade)Core.barricades.get(i);
/* 116 */ if (this.hitCheck.intersects(b.getBox())) {
/* 117 */ this.autoFire = false;
/* */ }
/* */ }
/* 120 */ for (int i = 0; i < Core.enemies.size(); i++) {
/* 121 */ EnemyRifle e = (EnemyRifle)Core.enemies.get(i);
/* 122 */ if ((this.hitCheck.intersects(e.collision)) && (e != this))
/* 123 */ this.autoFire = false;
/* */ }
/* */ } | 5 |
public static ArrayList<Model3D> clone(ArrayList<Model3D> l) {
ArrayList<Model3D> models = new ArrayList<Model3D>();
Model3D model;
for (Model3D m : l) {
model = new Model3D();
for (Face f : m.getFaces()) {
model.getFaces().add(new Face(new Point(f.p1.x, f.p1.y, f.p1.z), new Point(f.p2.x, f.p2.y, f.p2.z), new Point(f.p3.x, f.p3.y, f.p3.z)));
}
for (Segment s : m.getSegments()) {
model.getSegments().add(new Segment(new Point(s.p1.x, s.p1.y, s.p1.z), new Point(s.p2.x, s.p2.y, s.p2.z)));
}
for (Point p : m.getPoints()) {
model.getPoints().add(new Point(p.x, p.y, p.z));
}
model.setDecalageX(m.getDecalageX());
model.setDecalageY(m.getDecalageY());
model.setNom(m.getNom());
models.add(model);
}
return models;
} | 4 |
static List<Language> getLanguages(Path languageProperties) throws IOException {
if (!FileUtil.control(languageProperties)) {
throw new IOException();
}
if (languages == null) {
readLanguageProperties(languageProperties);
}
return languages;
} | 2 |
public void applyUpdate(Contact update) {
if (update == null) return;
if (update.getId() != 0 && update.getId() != this.getId() )
throw new IllegalArgumentException("Update contact must have same id as contact to update");
// Since title is used to display contacts, don't allow empty title
if (! isEmpty( update.getTitle()) ) this.setTitle(update.getTitle()); // empty nickname is ok
// other attributes: allow an empty string as a way of deleting an attribute in update (this is hacky)
if (update.getName() != null ) this.setName(update.getName());
else this.setName("");
if (update.getEmail() != null) this.setEmail(update.getEmail());
else this.setEmail("");
if (update.getPhoneNumber() != null ) this.setPhoneNumber(update.getPhoneNumber());
else this.setPhoneNumber("");
} | 7 |
int skipCommentsAndQuotes(char[] expressionChars, int position) {
String[] startSkip = getStartSkip();
for (int i = 0; i < startSkip.length; i++) {
// 判断表达是否和注释的起始标识匹配
if (expressionChars[position] == startSkip[i].charAt(0)) {
boolean match = true;
for (int j = 1; j < startSkip[i].length(); j++) {
if (!(expressionChars[position + j] == startSkip[i].charAt(j))) {
match = false;
break;
}
}
// 如果匹配需要返回跳过后的表达式位置
if (match) {
return endIndexOfCommentsAndQuotes(expressionChars, i, position);
}
}
}
return position;
} | 5 |
protected synchronized void refreshDicWords(String dicPath) {
int index = dicPath.lastIndexOf(".dic");
String dicName = dicPath.substring(0, index);
if (allWords != null) {
try {
Map/* <String, Set<String>> */temp = FileWordsReader
.readWords(dicHome + dicPath, charsetName);
allWords.put(dicName, temp.values().iterator().next());
} catch (FileNotFoundException e) {
// 如果源文件已经被删除了,则表示该字典不要了
allWords.remove(dicName);
} catch (IOException e) {
throw toRuntimeException(e);
}
if (!isSkipForVacabulary(dicName)) {
this.vocabularyDictionary = null;
}
// 如果来的是noiseWord
if (isNoiseWordDicFile(dicName)) {
this.noiseWordsDictionary = null;
// noiseWord和vocabulary有关,所以需要更新vocabulary
this.vocabularyDictionary = null;
}
// 如果来的是noiseCharactors
else if (isNoiseCharactorDicFile(dicName)) {
this.noiseCharactorsDictionary = null;
// noiseCharactorsDictionary和vocabulary有关,所以需要更新vocabulary
this.vocabularyDictionary = null;
}
// 如果来的是单元
else if (isUnitDicFile(dicName)) {
this.unitsDictionary = null;
}
// 如果来的是亚洲人人姓氏
else if (isConfucianFamilyNameDicFile(dicName)) {
this.confucianFamilyNamesDictionary = null;
}
// 如果来的是以字母,数字等组合类语言为开头的词汇
else if (isLantinFollowedByCjkDicFile(dicName)) {
this.combinatoricsDictionary = null;
}
}
} | 9 |
@Override
public void process(WatchedEvent event) {
System.out.println("[" + Thread.currentThread() + "event : "
+ event);
switch (event.getType()) {
case None:
switch (event.getState()) {
case Disconnected:
case Expired:
System.out.println("[" + Thread.currentThread()
+ "Session has expired");
synchronized (lock) {
dead = true;
lock.notifyAll();
}
break;
case SyncConnected:
System.out.println("[" + Thread.currentThread()
+ "Connected to the server");
synchronized (lock) {
dead = false;
lock.notifyAll();
// populateView();
}
break;
}
zk.register(this);
break;
case NodeCreated:
System.out.println("Node " + event.getPath() + " created");
// FLE+
// nodeDataChanged(event.getPath());
break;
case NodeChildrenChanged:
System.out.println("Children changed for node "
+ event.getPath());
populateChildren(event.getPath());
break;
case NodeDeleted:
System.out.println("Node " + event.getPath() + " deleted");
nodeDeleted(event.getPath());
break;
case NodeDataChanged:
System.out.println("Data changed for node "
+ event.getPath());
nodeDataChanged(event.getPath());
break;
}
} | 8 |
public void mouseReleased(MouseEvent event) {
adapter.mouseReleased(event);
} | 0 |
public static DatarateProperty createSoftRequirement(int bandwidthKBitSec, double percentageMinimalRequired)
{
if(percentageMinimalRequired > 1) percentageMinimalRequired = 1.0d;
if(percentageMinimalRequired < 0) percentageMinimalRequired = 0;
// do we require 100% of requested at minimum?
if(percentageMinimalRequired >= (1.0d -EPS)) {
// a very hard soft requirement ;-)
return new DatarateProperty(bandwidthKBitSec, Limit.MIN);
} else {
/*
* Depending on the maximum and the percentage of minimal acceptable
* of that data rate, we calculate a new expectation value and variance
* for a normal distribution, which represents that requirement.
*/
double DStrich = ((1.0d +percentageMinimalRequired)/2.0d) *bandwidthKBitSec;
double sigma = (DStrich -(percentageMinimalRequired *bandwidthKBitSec)) /3.0d;
return new DatarateProperty((int)Math.round(DStrich), sigma*sigma, Limit.MIN);
}
} | 3 |
private double getHeightScalingConstant(){
double s = 0.0;
if(!maxWeightMap.isEmpty() && !davidAvgGVC){
for(Map.Entry<String, Double> entry : maxWeightMap.entrySet()){
s += entry.getValue();
}
} else if (!averageAttributeWeights.isEmpty() && davidAvgGVC) {
for (Map.Entry<String, Double> entry : averageAttributeWeights.entrySet()) {
s += entry.getValue();
}
}
return s;
} | 6 |
public Collection<ProvinciaDTO> buscarPorDepartamento (int iddepa)
{
Connection con = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
con = UConnection.getConnection();
String sql = "SELECT p.* "
+ "FROM ubprovincia p "
+ "WHERE p.IdDepa = ?";
pstm = con.prepareStatement(sql);
pstm.setInt(1, iddepa);
rs = pstm.executeQuery();
Vector<ProvinciaDTO> ret = new Vector<ProvinciaDTO>();
ProvinciaDTO dto = null;
while(rs.next())
{
dto = new ProvinciaDTO();
dto.setIdprov(rs.getInt("IdProv"));
dto.setProvincia(rs.getString("provincia"));
dto.setIddepa(rs.getInt("IdDepa"));
ret.add(dto);
}
return ret;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
finally
{
try {
if ( rs != null)
rs.close();
if (pstm != null)
pstm.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
} | 5 |
public void Display_store() {
final Iterator iter = IndStore.values().iterator();
while (iter.hasNext()) {
final Swizzler indswz = (Swizzler) iter.next();
System.out.println("\nIV: " + indswz.ind_var() + " tgt: "
+ indswz.target() + "\narray: " + indswz.array()
+ " init: " + indswz.init_val() + " end: "
+ indswz.end_val());
}
} | 1 |
@EventHandler(priority=EventPriority.LOWEST)
public void onPlayerInteract(final PlayerInteractEvent event) {
if(isPlaying.contains(event.getPlayer().getName())) {
if(event.getPlayer().getItemInHand() != null) {
if(event.getPlayer().getItemInHand().getType().equals(Material.MUSHROOM_SOUP)) {
if(event.getPlayer().getHealth() >= 20D) {
event.setCancelled(true);
return;
} else {
if((event.getPlayer().getHealth() + 7) > 20D) {
event.getPlayer().setHealth(20D);
} else {
event.getPlayer().setHealth(event.getPlayer().getHealth()+7);
}
event.getPlayer().getInventory().getItemInHand().setType(Material.BOWL);
return;
}
}
}
}
} | 5 |
public void eatMeat(int meat) {
this.meat -= meat;
if (this.meat <= 0) {
this.timeOfInertion = 0;
}
} | 1 |
private int jjMoveStringLiteralDfa23_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjMoveNfa_0(0, 22);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
return jjMoveNfa_0(0, 22);
}
switch(curChar)
{
case 45:
return jjMoveStringLiteralDfa24_0(active0, 0xfffe00000000000L);
default :
break;
}
return jjMoveNfa_0(0, 23);
} | 3 |
public boolean tablanvan(){
if(hovaakar1>-1 && hovaakar2>-1 && hovaakar1<8 && hovaakar2<8)
return true;
else {
logger.info("A lépés nem a táblán van!");
return false;
}
} | 4 |
@Override
protected void updateShareRate(Share share)
{
List<Long> history = historyData.get(share.name);
if(history != null && flag < history.size()){
share.setActualSharePrice(history.get(flag));
}else{
flag = 1;
}
} | 2 |
@Test
public void delMinReturnsCorrectValueAfterSingleInsert() {
h.insert(v);
assertEquals(v, h.delMin());
} | 0 |
public String getToken() {
cadtmp = null;
for (int x = this.getBegin(); x < this.getCad().length(); x++) {
chartmp = this.getCad().charAt(x);
this.setBegin(x);
if (chartmp != ' ') {
if (Pattern.matches(this.getMatchValue(), chartmp + "")) {
cadtmp = cadtmp + chartmp;
if (this.getMatchValue().equals(this.getMatchOperacion())) {
this.setBegin(x + 1);
// ListToken.add(new Nodo(cadtmp, this.getMatchName(this.getMatchValue())));
return cadtmp;
}
} else {
// if (!cadtmp.equals("")) {
//// ListToken.add(new Nodo(cadtmp, this.getMatchName(this.getMatchValue())));
// }
this.changeMatchValue(chartmp);
return cadtmp;
}
} else {
// if (!cadtmp.equals("")) {
//// ListToken.add(new Nodo(cadtmp, this.getMatchName(this.getMatchValue())));
// }
this.setBegin(x + 1);
return cadtmp;
}
}
// if (!cadtmp.equals("")) {
//// ListToken.add(new Nodo(cadtmp, this.getMatchName(this.getMatchValue())));
// }
this.setHaveToken(false);
return cadtmp;
} | 4 |
private static byte[][] ShiftRows(byte[][] state) {
byte[] t = new byte[4];
for (int r = 1; r < 4; r++) {
for (int c = 0; c < Nb; c++)
t[c] = state[r][(c + r) % Nb];
for (int c = 0; c < Nb; c++)
state[r][c] = t[c];
}
return state;
} | 3 |
public void setUse(String ID, boolean use)
{
int row = getIndex(ID);
if (row == -1)
return;
rows.get(row)[USE] = new Boolean(use);
} | 1 |
public static Graph randomTree4() {
int depth = 6;
Graph graph = new Graph(depth * 100, depth * 50);
int a = 0;
int b = 1;
int c = 0;
graph.addVertex(new Vertex(c++, 25, 25 + 25 * (depth - 1)));
for (int i = 1; i < depth; i++) {
for (int j = 0; j <= i; j++) {
graph.addVertex(new Vertex(c++, 25 + 50 * i, 25 + 25
* (depth - i - 1) + 50 * j));
}
graph.addEdge(b, a);
for (int j = b + 1; j < c - 1; j++) {
if (Math.random() < 0.5)
graph.addEdge(j, a + j - b);
else
graph.addEdge(j, a + j - b - 1);
}
graph.addEdge(c - 1, a + c - b - 2);
a = b;
b = c;
}
for (int i = depth; i < 2 * depth + 1; i++) {
for (int j = 0; j <= 2 * depth - i - 2; j++) {
graph.addVertex(new Vertex(c++, 25 + 50 * i, 75 + 25
* (i - depth - 1) + 50 * j));
}
for (int j = b; j < c; j++) {
if (Math.random() < 0.5)
graph.addEdge(j, a + j - b + 1);
else
graph.addEdge(j, a + j - b);
}
a = b;
b = c;
}
return graph;
} | 8 |
Subsets and Splits