text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public boolean equals(Object other)
{
return other != null && other instanceof CharSequence ? toString().equals(other.toString()) : false;
} | 2 |
public static Position moveFromExplicitMoveString(Position pos, String move) {
//System.out.println("Get move from explicit: " + move);
//handle king side castle:
if(move.equals("O-O") || move.equals("O-O+")) {
return ChessMover.moveWeird(pos, Position.KING_SIDE_CASTLE);
//handle queen side castle:
} else if(move.equals("O-O-O") || move.equals("O-O-O+")) {
return ChessMover.moveWeird(pos, Position.QUEEN_SIDE_CASTLE);
//Handle promotion:
} else if(move.contains("=")) {
String piece = move.substring(move.indexOf("=") + 1, move.indexOf("=") + 2);
if(pos.isWhiteTurn()) {
piece = Position.WHITE + piece;
} else {
piece = Position.BLACK + piece;
}
return ChessMover.movePromote(pos, move.charAt(0), move.charAt(1) - '0', move.charAt(3), move.charAt(4) - '0', piece);
//handle normal move:
} else {
int startPosofCord = 0;
for(startPosofCord=0; startPosofCord<move.length(); startPosofCord++) {
if(move.charAt(startPosofCord) >='a' && move.charAt(startPosofCord) <='h') {
break;
}
}
return ChessMover.moveNormal(pos, move.charAt(startPosofCord), move.charAt(startPosofCord + 1) - '0', move.charAt(startPosofCord + 3), move.charAt(startPosofCord + 4) - '0');
}
} | 9 |
public int getProtons(String str)
{
for(int i = 0; i < eSymbol.length; i++) //look for symbols that match the string
if(str.equals(eSymbol[i]))
return i;
str = str.toLowerCase();
for(int i = 0; i < eName.length; i++) //look for names that match the string
if(str.equals(eName[i].toLowerCase()))
return i;
return 0;
} | 4 |
public void info() {
super.info();
System.out.println ("head:\t" + head);
} // end info() | 0 |
@Override
protected void finalize()
{
if(m_resource.RemoveReference() && !m_fileName.isEmpty())
{
s_loadedModels.remove(m_fileName);
}
} | 2 |
@Override
public void reduce(Text text, Iterator<IntWritable> intWritableIterator, OutputCollector<Text, IntWritable> textIntWritableOutputCollector, Reporter reporter) throws IOException {
} | 0 |
public void setAccount(Account account) {
this.account = account;
} | 0 |
public void transformPointer(Face face) {
if(face==Face.SOUTHERN){
rotationRequired = Math.toRadians(90);
}else if(face==Face.WESTERN){
rotationRequired = Math.toRadians(180);
}else if(face==Face.NORTHERN){
rotationRequired = Math.toRadians(270);
}else if(face==Face.EASTERN){
rotationRequired = Math.toRadians(0);
}
tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
} | 4 |
private static void readMagicItemsFromFile(String fileName,
ListMan lm) {
File myFile = new File(fileName);
try {
Scanner input = new Scanner(myFile);
while (input.hasNext()) {
// Read a line from the file.
String itemName = input.nextLine();
// Construct a new list item and set its attributes.
ListItem fileItem = new ListItem();
fileItem.setName(itemName);
fileItem.setCost(Math.random() * 10);
fileItem.setNext(null); // Still redundant. Still safe.
// Add the newly constructed item to the list.
lm.add(fileItem);
}
// Close the file.
input.close();
} catch (FileNotFoundException ex) {
System.out.println("File not found. " + ex.toString());
}
} | 2 |
protected void initate(int cells, boolean debug) {
this.debug = debug;
if (data == null) data = new byte[cells];
else
for (int i=0; i<data.length; i++)
data[i] = 0;
if (exec != null) exec.stop();
dataPointer = 0;
charPointer = 0;
posInput = 0;
breakCycle = false;
close = false;
ide.codeText.requestFocus();
ide.codeText.setCaretPosition(0);
inputData = new StringBuffer();
if (debug) {
ide.runInto.setEnabled(true);
ide.runOut.setEnabled(true);
}
if (model == null) model = new MemoryTableModel(this, cells);
else model.init(this, cells);
boolean first = false;
if (memoryTable == null) {
memoryTable = new ToolTipTable(model);
first = true;
} else memoryTable.setModel(model);
if (first) {
memoryTable.setCellSelectionEnabled(true);
//memoryTable.setFont(new Font("Consolas", Font.PLAIN, 14));
memoryScroll = new JScrollPane(memoryTable);
ide.dataPanel.add(memoryScroll, BorderLayout.CENTER);
memoryTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
ide.setExtendedState(IDEFrame.NORMAL);
ide.setExtendedState(IDEFrame.MAXIMIZED_BOTH);
}
} | 7 |
private void texData(BufferedImage img) {
if(glTexId == -1 || img == null) {
return;
}
int[] pixels = new int[textureWidth*textureHeight];
img.getRGB(0, 0, textureWidth, textureHeight, pixels, 0, textureWidth);
Out.dbg("TexData!");
ByteBuffer buf = BufferUtils.createByteBuffer(textureWidth*textureHeight*(hasAlpha ? 4 : 3));
for(int y=0;y<textureHeight;y++) {
for(int x=0;x<textureWidth;x++) {
int pixel = pixels[y*textureWidth+x];
buf.put((byte)((pixel >> 16) & 0xFF));
buf.put((byte)((pixel >> 8) & 0xFF));
buf.put((byte)((pixel) & 0xFF));
buf.put((byte)((pixel >> 24) & 0xFF));
Out.out("alpha: " + ((pixel >> 24) & 0xFF));
Out.out("red: " + ((pixel >> 16) & 0xFF));
Out.out("green: " + ((pixel >> 6) & 0xFF));
Out.out("blue: " + ((pixel >> 0) & 0xFF));
// buf.put((byte)0);
// buf.put((byte)0);
// buf.put((byte)0);
// buf.put((byte)0);
}
}
buf.flip();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, glTexId);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, textureWidth, textureHeight, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buf);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
} | 5 |
private boolean topEdge(int particle, int cubeRoot) {
for(int i = 1; i < cubeRoot + 1; i++){
if(particle < i * cubeRoot * cubeRoot - 1 && particle > i * cubeRoot * cubeRoot - cubeRoot){
return true;
}
}
return false;
} | 3 |
Class<?> getReturnType(String methodRoot) {
Class<?> returnType = null;
String methodName = "get" + methodRoot;
Widget[] widgets = getExampleWidgets();
try {
java.lang.reflect.Method method = widgets[0].getClass().getMethod(methodName, (Class<?>)null);
returnType = method.getReturnType();
} catch (Exception e) {
}
return returnType;
} | 4 |
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
int numAlum=teclado.nextInt(),
i=0, j=0;
double suma = 0, media=0,Suma=0;
//
System.out.println("numero de alumnos de la clase: "+numAlum);
int[]notas = new int[numAlum];
//
for(i = 0; i<notas.length;++i){
System.out.println("Alumno " + (i+1) + " nota final:");
notas[i]=teclado.nextInt();
}
//
for(i=0;i<notas.length;++i){
Suma = Suma + notas[i];
}
media=Suma/notas.length;
System.out.println("Nota media del curso: " +media);
//
System.out.println("Listado de las notas superiores a la media");
for(i=0; i<notas.length; i++)
if(notas[i]>media){
System.out.println("Alumno numero "+(i+1)+" - Nota final: " + notas[i]);
}
//
System.out.println("Nota maxima de los alumnos");
int maxima=0;
for(i=0;i<notas.length;++i){
if(maxima<notas[i]) maxima = notas[i];
}
System.out.println(maxima);
} | 6 |
public void stop() {
if (!isRunning)
return;
isRunning = false;
} | 1 |
public Codec( String extension, Class iCodecClass )
{
extensionRegX = "";
// Make sure an extension was specified:
if( extension != null && extension.length() > 0 )
{
// We are only interested in the file extension. The filename
// can begin with whatever:
extensionRegX = ".*";
String c;
for( int x = 0; x < extension.length(); x++ )
{
// Each character could be either upper or lower case:
c = extension.substring( x, x + 1 );
extensionRegX += "[" + c.toLowerCase( Locale.ENGLISH )
+ c.toUpperCase( Locale.ENGLISH ) + "]";
}
// The extension will be at the end of the filename:
extensionRegX += "$";
}
// remember the codec to use for this format:
this.iCodecClass = iCodecClass;
} | 3 |
public static String fromArray (byte[] data) {
// allocate result buffer
StringBuffer buf = new StringBuffer();
int size = data.length;
// compute padding
int padding = (3 - (size % 3)) % 3;
// process all bytes in array...
for (int n = 0; n < size; n += 3) {
// check for final (truncated) block
boolean eof = size < (n + 3);
// assemble three byte integer value
int val = (data[n] & 0xFF);
val = (val << 8) | (eof && padding == 2 ? 0 : (data[n+1] & 0xFF));
val = (val << 8) | (eof && padding > 0 ? 0 : (data[n+2] & 0xFF));
// convert to four-character encoding.
buf.append (charset.charAt ((val >> 18) & 0x3F));
buf.append (charset.charAt ((val >> 12) & 0x3F));
buf.append (eof && padding == 2 ? "=" : charset.charAt ((val >> 6) & 0x3F));
buf.append (eof && padding > 0 ? "=" : charset.charAt ( val & 0x3F));
}
// return representation
return buf.toString();
} | 9 |
public ImageIcon getFoldingIcon(mxCellState state)
{
if (state != null && isFoldingEnabled()
&& !getGraph().getModel().isEdge(state.getCell()))
{
Object cell = state.getCell();
boolean tmp = graph.isCellCollapsed(cell);
if (graph.isCellFoldable(cell, !tmp))
{
return (tmp) ? collapsedIcon : expandedIcon;
}
}
return null;
} | 5 |
private static <S> TreeNode<S> seekAccept(ArrayDeque<TreeNode<S>> stack) {
while (!stack.isEmpty()) {
TreeNode<S> top = stack.pop();
stack.addAll(top.children);
if (top.isAccept()) {
return top;
}
}
return null;
} | 2 |
public void wakeUp() {
if (getState() == STATE_NORMAL && getVelocityX() == 0) {
setVelocityX(-getMaxSpeed());
}
} | 2 |
protected static Ptg calcColumns( Ptg[] operands )
{
//
if( operands[0] instanceof PtgFuncVar )
{
// we need to return the col where the formula is.
PtgFuncVar pfunk = (PtgFuncVar) operands[0];
try
{
int loc = pfunk.getParentRec().getColNumber();
loc += 1;
return new PtgInt( loc );
}
catch( Exception e )
{
}
;
}
else
{
// It's ugly, but we are going to handle the four types of references seperately, as there is no good way
// to generically get this info
try
{
if( operands[0] instanceof PtgArea )
{
PtgArea pa = (PtgArea) operands[0];
int[] loc = pa.getIntLocation();
int ncols = (loc[3] - loc[1]) + 1;
return new PtgInt( ncols );
}
if( operands[0] instanceof PtgArray )
{
PtgArray parr = (PtgArray) operands[0];
return new PtgInt( parr.nc + 1 );
}
}
catch( Exception e )
{
}
;
}
return new PtgInt( -1 );
} | 5 |
public String getRadioButtonSelected()
{
String returnVal = null;
Enumeration<AbstractButton> allRadioButton=group.getElements();
while(allRadioButton.hasMoreElements())
{
JRadioButton temp=(JRadioButton)allRadioButton.nextElement();
if(temp.isSelected())
{
returnVal = temp.getText();
}
}
return returnVal;
} | 2 |
public Object clone() {
try {
SlotSet other = (SlotSet) super.clone();
if (count > 0) {
other.locals = new LocalInfo[count];
System.arraycopy(locals, 0, other.locals, 0, count);
}
return other;
} catch (CloneNotSupportedException ex) {
throw new jode.AssertError("Clone?");
}
} | 2 |
public Level NextLevel() {
if (currentlevel < maxlevel) {
Level lvl = new Level(levels[currentlevel].toString());
currentlevel++;
return lvl;
} else {
Framework.gameState = Framework.GameState.COMPLETED;
return null;
}
} | 1 |
public void selectedTeam(String team, String homeOrAway) {
try {
//load xml file to get team
File file = new File("teams/" + team + ".xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Players.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Players players = (Players) jaxbUnmarshaller.unmarshal(file);
if (homeOrAway == "home")
homeTeam = players.getPlayerList();
if (homeOrAway == "away")
awayTeam = players.getPlayerList();
} catch (JAXBException e) {
System.out.println("Incorrect teams selected.");
if (homeOrAway == "home")
getHomeTeam();
if (homeOrAway == "away")
getAwayTeam();
}
} | 5 |
public static void main(String[] args) {
new Car(22).start();
} | 0 |
private boolean isLowestRankingStraight(ArrayList<Integer> sortedHand) {
for (int i = 0; i<sortedHand.size()-3; i++) {
if (sortedHand.get(0) == 2 && //has 2
sortedHand.get(1) == 3 && //has 3
sortedHand.get(2) == 4 && //has 4
sortedHand.get(3) == 5 ) //has 5
return true;
}
return false;
} | 5 |
private static void unitTest() {
System.out.println("PARSE/ASSEMBLE TESTS");
// Dirs and Files
unitTestParseAssemble("http://www.organic.com");
unitTestParseAssemble("http://www.organic.com/");
unitTestParseAssemble("http://www.organic.com/file.jsp");
unitTestParseAssemble("http://www.organic.com/dir");
unitTestParseAssemble("http://www.organic.com/dir/");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp");
unitTestParseAssemble("http://www.organic.com/dir/dir2");
unitTestParseAssemble("http://www.organic.com/dir/dir2/");
unitTestParseAssemble("http://www.organic.com/dir/dir2/file.jsp");
// Query
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp??");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?=?");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?name");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?name=");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?name=value");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?=");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?==");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?=value");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?&");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?&&");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?&&&");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?&value");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?name&");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?name&value");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?name=value&name=value");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?name=&name=value");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?=&");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?&=");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?=&=");
unitTestParseAssemble("http://www.organic.com/dir/file.jsp?name=value+space&name=value%20space");
unitTestParseAssemble("http://www.organic.com?");
unitTestParseAssemble("http://www.organic.com?name=value");
// Fragments
unitTestParseAssemble("http://www.organic.com#");
unitTestParseAssemble("http://www.organic.com##");
unitTestParseAssemble("http://www.organic.com#fragment");
unitTestParseAssemble("http://www.organic.com?name=value#fragment");
// Ports
unitTestParseAssemble("http://www.organic.com:8080");
unitTestParseAssemble("http://www.organic.com:8080/");
unitTestParseAssemble("http://www.organic.com:8080?");
unitTestParseAssemble("http://www.organic.com:8080?name=value");
// All Together
unitTestParseAssemble("http://maynard:password@www.organic.com:8080/dir/file.jsp?name=value&name+space=value%20space#fragment");
// Relative URLs
unitTestParseAssemble("/file.jsp");
unitTestParseAssemble("/");
unitTestParseAssemble("../");
unitTestParseAssemble("file.jsp");
unitTestParseAssemble("dir/file.jsp?name=value");
unitTestParseAssemble("http:/file.jsp");
// Empty URL
unitTestParseAssemble("");
unitTestParseAssemble(null);
// Test Getters and Setters
MuteableURL m_url = new MuteableURL(null);
m_url.setProtocol("http");
m_url.setHost("www.organic.com");
m_url.setPath("/dir/file.jsp");
m_url.setQuery("this=that&these=those");
m_url.setFragment("fragment");
System.out.println(m_url.toString());
m_url.setFile("new_file.jsp");
System.out.println(m_url.toString());
m_url.setAbsolutePath(false);
System.out.println(m_url.toString());
m_url.setAbsolutePath(true);
System.out.println(m_url.toString());
m_url.setPath("../rel/file.jsp");
System.out.println(m_url.toString());
MuteableURL m_url2 = new MuteableURL(null);
m_url2.setProtocol("http");
m_url2.setHost("www.organic.com");
m_url2.setQuery("this=that&these=those");
System.out.println(m_url2.toString());
m_url2.setFile("new_file.jsp");
System.out.println(m_url2.toString());
m_url2.setAbsolutePath(false);
System.out.println(m_url2.toString());
} | 0 |
public DFS addBankJumpPointerTable(int address, int length) {
rom.labelType[address] = 3;
for(int i=0; i<length; i++) {
int ca = address + 3*i;
rom.type[ca] = ROM.DATA_BANKJUMPPOINTER;
if (i > 0 && i % 8 == 0)
rom.comment[ca] = "$" + Util.toHex(i);
int goalBank = rom.data[ca] & 0xFF;
int goalAddress = ((rom.data[ca+1]&0xFF) | ((rom.data[ca+2]&0xFF) << 8)) & 0xFFFF;
if(goalAddress >= 0x8000)
System.out.println("jump tabel entry to non-RAM location "+Integer.toHexString(goalAddress)+" at "+Integer.toHexString(address)+" element "+i);
else {
int fullAddress = goalAddress + (goalBank-1)*0x4000;
//System.out.println("addJump "+Integer.toHexString(fullAddress));
rom.payloadAsBank[ca] = fullAddress;
rom.payloadAsAddress[ca+1] = fullAddress;
if(rom.label[fullAddress] == null)
rom.labelType[fullAddress] = Math.max(rom.labelType[fullAddress], 3);
dfsStack.push(new DFSStackElem(fullAddress, new CPUState(), true));
}
}
return this;
} | 5 |
public void asetaPelaajanAlkusijainti(Piste sijainti) {
this.pelaajanAlkusijainti = sijainti;
} | 0 |
private boolean goBack(Command command){
int backage = 0;
if(!command.hasNthWord(2)){
backage = 1;
} else {
String sWord = command.getNthSegment(1);
try {
backage = Integer.parseInt(sWord);
} catch(NumberFormatException e) {
return false;
}
}
if(previousRooms.size() < backage) {
return false;
}
ArrayList<String> roomsToGo = new ArrayList<String>(backage);
for (int i = 1; i <= backage; i++) {
roomsToGo.add(previousRooms.get(previousRooms.size()-i));
}
for (int i = 0; i < roomsToGo.size()-1; i ++) {
previousRooms.add(roomsToGo.remove(i));
}
goRoom(roomsToGo.remove(0));
return true;
} | 5 |
public void setComment(String comment) {
this.comment = comment;
} | 0 |
static int Action(Client joueur) {
int tempDette = 0;
int choiceInt = -1;
boolean wrong = true;
boolean quit = true;
do {
System.out.println("Que voulez vous faire?"
+ "\n pour dormir tapez 1"
+ "\n pour appeler le room service tapez 2"
+ "\n pour partir tapez 3");
do {
String choice = keyboard.nextLine();
try {
choiceInt = Integer.parseInt(choice);
if (choiceInt != 1 && choiceInt != 2 && choiceInt != 3) {
throw new Exception("not 1, 2 or 3");
}
wrong = false;
} catch (Exception e) {
System.out.println("Mauvaise valeur inseree");
}
} while (wrong);
switch (choiceInt) {
case 1:
dormir(joueur);
break;
case 2:
tempDette += RoomService(joueur);
break;
default:
quit = false;
break;
}
} while (quit);
return tempDette;
} | 8 |
public static void main(String[] args) {
LabControl control = get();
if(args.length < 4){
control.err("wrong parameter count!");
control.halt();
}
if(args[3].equalsIgnoreCase("train")) control.executeTrainAction(args[0], args[1], args[2]);
if(args[3].equalsIgnoreCase("resumetrain")) control.executeResumeTrainAction(args[0], args[1], args[2]);
if(args[3].equalsIgnoreCase("lookup")) control.executeLookupAction(args[0], args[1], args[2]);
if(args[3].equalsIgnoreCase("decode")) control.executeDecodeAction(args[0], args[1], args[2]);
} | 5 |
public Board getDeepCopy() {
Piece[][] piecesCopy = new Piece[8][8];
for(int x = 0; x < pieces.length; x++) {
Piece[] row = pieces[x];
for(int y = 0; y < row.length; y++) {
if(row[y] != null) {
piecesCopy[x][y] = row[y].getDeepCopy();
}
}
}
return new Board(piecesCopy);
} | 3 |
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta)
throws SlickException{
if(MenuManager.getMenuType()==0)
MenuManager.menuUpdate(gc, sbg, delta);
else if(MenuManager.getMenuType()==1)
MenuManager.levelUpdate(gc, sbg, delta);
} | 2 |
private String calcWeekDay(final String input) throws ParseException {
String res = "";
String y,m,newInput;
StringTokenizer st = new StringTokenizer(input,"-");
y=st.nextToken();
m=st.nextToken();
newInput = new StringBuilder()
.append(y)
.append("-")
.append(Integer.parseInt(m)+1).toString();
Date date;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sdfSource = new StringBuilder()
.append(newInput)
.append("-")
.append(VALUE_DAY)
.toString();
date = sdf.parse(sdfSource);
sdf.applyPattern("EEEE");
res = sdf.format(date).toUpperCase();
return res;
} | 0 |
protected void mixnmatch(Organism org1, Organism org2) {
posX = (org1.posX + org2.posX) / 2;
posY = (org1.posY + org2.posY) / 2;
if (r.nextInt(2) == 1) {
speed = org1.speed;
} else {
speed = org2.speed;
}
if (r.nextInt(2) == 1) {
defense = org1.defense;
} else {
defense = org2.defense;
}
if (r.nextInt(2) == 1) {
attack = org1.attack;
} else {
attack = org2.attack;
}
} | 3 |
public static void main(String[] args) {
Collection<Integer> collection = new ArrayList<Integer>(
Arrays.asList(1, 2, 3, 4, 5)
);
Integer[] moreInts = { 6, 7, 8, 9, 10 };
collection.addAll(Arrays.asList(moreInts));
// Runs significantly faster, but you can't
// construct a Collection this way:
Collections.addAll(collection, 11, 12, 13, 14, 15);
Collections.addAll(collection, moreInts);
// Produces a list "backed by" an array:
List<Integer> list = Arrays.asList(16, 17, 18, 19, 20);
list.set(1, 99); // OK -- modify an element
// list.add(21); // Runtime error because the
// underlying array cannot be resized.
} | 0 |
@Test
public void getValofCol_test() {
try{
double [][]mat= {{3.0,2.0}, {1.0,3.0}};
int j=0;
double[]result = Matrix.getVecOfCol(mat, j);
double []exp= {3.0,1.0};
Assert.assertArrayEquals(exp, result, 0.0);
}
catch (Exception e) {
// TODO Auto-generated catch block
fail("Not yet implemented");
}
} | 1 |
public boolean checkPostion() {
if (x < 0 || x > 800 || y < 0 || y > 600)
return true;
return false;
} | 4 |
public void Assign(String name) {
boolean error = false;
if(Values.getType(name) == null) {
Error("Variable \'" + name + "\' has not been declared.");
return;
}
if(current.getId().equals("ASSIGN")) {
nextToken();
Expression(name);
}
else if(current.getId().equals("LSBRACKET")) {
nextToken();
if(current.getId().equals("VALNUM")) {
String index = current.getLexeme();
nextToken();
if(current.getId().equals("RSBRACKET")) {
nextToken();
if(current.getId().equals("ASSIGN")) {
nextToken();
ArrExpression(name,index);
}
else {
error = true;
}
}
else {
error = true;
}
}
else {
error = true;
}
if(error) {
Error("Invalid array assignment expression.");
}
}
else {
Error("Expecting expression to be assigned.");
}
} | 7 |
public void setState(String state) {
//Verify state Abbreviation (2) places
if(state == null || state.isEmpty() || state.length() > 2){
throw new IllegalArgumentException();
}
this.state = state;
} | 3 |
private EventJsonConverter() {
} | 0 |
public void raiseSalary(int employeeType) throws Exception
{
switch (employeeType) {
case JUNIOR:
this.salary = (salary * 105 + 10000) / 100;
break;
case MEDIOR:
this.salary = (salary * 106 + 20000) / 100;
break;
case SENIOR:
this.salary = (salary * 107) / 100;
break;
default:
throw new Exception("Invalid employeetype");
}
} | 3 |
public void testHeavyConcurrentAccess()
{
final int MAX = 1 << 20;
// Writers pop from this.
final AtomicStack<Integer> source = new AtomicStack<Integer>();
// Writers push to this, Readers pop from this (concurrent action!).
final AtomicStack<Integer> transfer = new AtomicStack<Integer>();
// Readers push to this.
final AtomicStack<Integer> target = new AtomicStack<Integer>();
// Start watch to get reference times
watch.start();
Runnable writer = new Runnable() {
public void run() {
System.out.format("Writer [%d] started at %d\n", Thread.currentThread().getId(), watch.millis());
int written = 0;
for (Integer x = source.pop(); x != null; x = source.pop()) {
transfer.push(x);
written++;
}
System.out.format("Writer [%d] stopped at %d with %d writes\n", Thread.currentThread().getId(), watch.millis(), written);
}
};
Runnable reader = new Runnable() {
public void run() {
sleep(2); // start off slower so there are items to pull
System.out.format("Reader [%d] started at %d\n", Thread.currentThread().getId(), watch.millis());
int read = 0;
for (Integer x = transfer.pop(); x != null; x = transfer.pop()) {
target.push(x);
read++;
}
System.out.format("Reader [%d] stopped at %d with %d reads\n", Thread.currentThread().getId(), watch.millis(), read);
}
};
// Fill source
for (int i = 0; i < MAX; i++) {
source.push(i);
}
GroupTask.initialize(6);
GroupTask.add(writer, 2);
GroupTask.add(reader, 4);
GroupTask.execute();
// Check target: sort numbers then check for existence
List<Integer> result = new ArrayList<Integer>();
for (Integer x = target.pop(); x != null; x = target.pop()) {
result.add(x);
}
Collections.sort(result);
assertEquals( MAX, result.size() );
for (int i = 0; i < MAX; i++) {
assertEquals( Integer.valueOf(i), result.get(i) );
}
} | 5 |
@SuppressWarnings("unchecked")
private static final Object[] decodeDictionary(byte[] bencoded_bytes, int offset) throws BencodingException
{
HashMap map = new HashMap();
++offset;
ByteBuffer info_hash_bytes = null;
while(bencoded_bytes[offset] != (byte)'e')
{
// Decode the key, which must be a byte string
Object[] vals = decodeString(bencoded_bytes, offset);
ByteBuffer key = (ByteBuffer)vals[1];
offset = ((Integer)vals[0]).intValue();
boolean match = true;
for(int i = 0; i < key.array().length && i < 4; i++)
{
if(!key.equals(ByteBuffer.wrap(new byte[]{'i', 'n','f','o'})))
{
match = false;
break;
}
}
int info_offset = -1;
if(match)
info_offset = offset;
vals = decode(bencoded_bytes, offset);
offset = ((Integer)vals[0]).intValue();
if(match)
{
info_hash_bytes = ByteBuffer.wrap(new byte[offset - info_offset]);
info_hash_bytes.put(bencoded_bytes,info_offset, info_hash_bytes.array().length);
}
else if(vals[1] instanceof HashMap)
{
info_hash_bytes = (ByteBuffer)vals[2];
}
if(vals[1] != null)
map.put(key,vals[1]);
}
return new Object[] {new Integer(++offset), map, info_hash_bytes};
} | 8 |
private void parsePacket(byte[] data, InetAddress address, int port) {
String message = new String(data).trim();
PacketTypes type = Packet.lookupPacket(message.substring(0, 2));
switch (type) {
default:
case INVALID:
break;
case LOGIN:
Packet00Login packet = new Packet00Login(data);
System.out.println("[" + address.getHostAddress() + ":" + port
+ "] " + packet.getUsername() + " has connected...");
PlayerMP player = null;
if (address.getHostAddress().equalsIgnoreCase("127.0.0.1")) {
player = new PlayerMP(game.level, 100, 100, game.input,
packet.getUsername(), address, port);
} else {
player = new PlayerMP(game.level, 100, 100,
packet.getUsername(), address, port);
}
if (player != null) {
this.connectedPlayers.add(player);
game.level.addEntity(player);
game.player = player;
}
break;
case DISCONNECT:
break;
}
} | 5 |
public double CalculateNDCG(Corpus corpus, int K, int numtopics,
TIntIntHashMap trainCitations) {
double CNDCG = 0;
System.out.println("Stat: test docs:" + corpus.docs.size()
+ ":Total citations in training:" + trainCitations.size());
for (int doc = 0; doc < corpus.docs.size(); doc++) {
ContextDocument document = (ContextDocument) corpus.docs.get(doc);
if (document.citationSetTest.size() == 0) {
continue;
}
TreeSet<DescSorter> sortedCitation = new TreeSet<DescSorter>();
int[] keys = trainCitations.keys();
for (int citation = 0; citation < keys.length; citation++) {// citations
// =
// citations
// from
// test
// set
double value = 0;
for (int t = 0; t < numtopics; t++) {// to do : change
value += corpus.theta_train[doc][t]
* corpus.psi_train[keys[citation]][t];
}
// System.out.println(corpus.citationAlphabet.lookupObject(
// citation).toString()
// + ":" + value);
String citationid = new Integer(keys[citation]).toString();
sortedCitation.add(new DescSorter(citationid, value));
}
Iterator<DescSorter> iter = sortedCitation.iterator();
document = (ContextDocument) corpus.docs.get(doc);
int k = 1, found = 0;
double prefectDCG = 1, DCG = 0;
for (int i = 2; i <= document.citationSetTest.size(); i++) {
prefectDCG += (Math.log(2) / Math.log(i));
}
while (iter.hasNext() && found < document.citationSetTest.size()) {
DescSorter desc = iter.next();
if (document.citationSetTest.contains(Integer.parseInt(desc
.getID()))) {
if (k == 1) {
DCG += 1;
} else {
DCG += (Math.log(2) / Math.log(k));
}
found++;
}
k++;
}
CNDCG += ((double) DCG / (prefectDCG * (corpus.docs.size())));
}
return CNDCG;
} | 9 |
public static ArrayList<MediaCopy> searchMediaByTitle(String title){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<MediaCopy> media = new ArrayList<MediaCopy>();
try {
PreparedStatement stmnt = conn.prepareStatement("SELECT * FROM Media m, MediaCopies mc WHERE m.media_id = mc.media_id AND title LIKE ? OR title LIKE ? AND mc.media_id = m.media_id");
stmnt.setString(1, title + "%");
stmnt.setString(2,"% "+ title + "%");
ResultSet res;
res = stmnt.executeQuery();
while(res.next()){
mediaCopy = new MediaCopy(StringDateSwitcher.toDateYear(res.getString("year")), res.getString("place_of_publication"), res.getString("title"), res.getString("genre"), res.getInt("media_id"), res.getString("creator"), res.getString("producer"), res.getString("type"), res.getInt("copy_id"), res.getBoolean("lendable"));
media.add(mediaCopy);
}
}
catch(SQLException e){
e.printStackTrace();
}
return media;
} | 5 |
public static void copyPEFiles(File startFolder) throws IOException {
File[] files = startFolder.listFiles();
if (files == null) {
System.out.println("Skipped unreadable file: "
+ startFolder.getCanonicalPath());
return;
}
for (File file : files) {
total++;
if (file.isDirectory()) {
copyPEFiles(file);
} else {
try {
new PESignature(file).read();
Files.copy(file.toPath(),
Paths.get(output.getAbsolutePath(), file.getName()));
written++;
} catch (FileFormatException e) {
noPE++;
} catch (FileAlreadyExistsException e) {
System.err.println("file already exists: " + file.getName()
+ " not copied!");
notLoaded++;
} catch (Exception e) {
System.err.println(e.getMessage());
notLoaded++;
}
if (total != prevTotal && total % 1000 == 0) {
prevTotal = total;
System.out.println("Files found: " + total);
System.out.println("PE Files found: " + written);
}
}
}
dirsRead++;
if (dirsRead % 500 == 0) {
System.out.println("Directories read: " + dirsRead);
System.out.println("Current Directory finished: "
+ startFolder.getAbsolutePath());
}
} | 9 |
public void testBigData6MB() throws TimeoutException, MemcachedException {
if(c instanceof QuickCachedClientImpl) {
c.setMaxSizeAllowedForValue(-1);
} else if(c instanceof XMemcachedImpl) {
//does not send the command to server at all for large value
//todo verify this
return;
} else if(c instanceof SpyMemcachedImpl) {
//does not send the command to server at all for large value
//todo verify this
return;
}
String readObject = null;
String key = null;
StringBuilder keyPrefix = new StringBuilder("testget");
StringBuilder valuePrefix = new StringBuilder();
int mb5 = 1024*1024*6;
for(int i=0;i<mb5;i++) {
valuePrefix.append("v");
}
//1 - String
key = keyPrefix.toString()+"1";
try {
c.set(key, 3600, valuePrefix.toString());
readObject = (String) c.get(key);
assertNotNull(readObject);
assertEquals(valuePrefix.toString(), readObject);
assertTrue(
"This should not have passed.. we should have got a exception"
, false);
} catch(Exception e) {
assertTrue("We are good", true);
}
} | 5 |
private void updateSettingsSaveBtnVisibility()
{
boolean show=false;
if( btnFkSettingsSave != null)
{
if( FkManager.getInstance().getBanner().compareTo( txtBanner.getText() ) != 0 )
{
show=true;
}
if( cmbLayout.getSelectionIndex() != -1 && cmbLayout.getItem(cmbLayout.getSelectionIndex()).compareTo(FkManager.getInstance().getCurrentLayout()) != 0 )
{
show=true;
}
if(show)
{
btnFkSettingsSave.setEnabled(true);
} else {
btnFkSettingsSave.setEnabled(false);
}
}
} | 5 |
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(TPF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TPF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TPF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TPF.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 TPF().setVisible(true);
}
});
} | 6 |
@Override
public void registUrl(String url, String keyword, String twitterUserName) {
try {
String query = "INSERT INTO " + TABLE_NAME;
query += " (url,search_word,twitter_user_name, created_at,updated_at) VALUES (?,?,?,?,?) ";
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, url);
stmt.setString(2, keyword);
stmt.setString(3, twitterUserName);
stmt.setString(4, Calender.nowString());
stmt.setString(5, Calender.nowString());
stmt.executeUpdate();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
return;
}
} | 1 |
public static void indent(Node node, StringBuffer buf) {
for (int i = 0, limit = node.getDepth(); i < limit; i++) {
buf.append("\t");
}
} | 1 |
public BankAccount getMainBankAccount() {
if (!Constants.Banking) {
return null;
}
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
BankAccount account = null;
try
{
conn = iConomy.getiCoDatabase().getConnection();
ps = conn.prepareStatement("SELECT * FROM " + Constants.SQLTable + "_BankRelations WHERE account_name = ? AND main = 1 LIMIT 1");
ps.setString(1, this.name);
rs = ps.executeQuery();
if (rs.next()) {
Bank bank = new Bank(rs.getInt("bank_id"));
account = new BankAccount(bank.getName(), rs.getInt("bank_id"), this.name);
}
} catch (Exception e) {
return null;
}
finally
{
if (ps != null) try {
ps.close();
} catch (SQLException ex) {
} if (conn != null) try {
conn.close();
} catch (SQLException ex) {
}
}
return account;
} | 7 |
private void systemListAddListener() {
systemList.addMouseMotionListener(genericMouseMotionListener);
systemList.addMouseListener(new MouseListener() {
private String chosenSystem;
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) { }
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseClicked(MouseEvent e) {
chosenSystem = listOfSystems.get(systemList.getSelectedIndex()).getFilename();
currentSystemName = listOfSystems.get(systemList.getSelectedIndex()).getName();
BookXMLParser bookParser = new BookXMLParser(chosenSystem);
listOfBooks = bookParser.readBookXML(chosenSystem);
bookListModel.clear();
bookList.removeAll();
bookListForContents = listOfBooks.getList();
for (Book currentBook : bookListForContents) {
bookListModel.addElement(currentBook.getTitle());
}
bookList.repaint();
systemDescription = listOfSystems.get(systemList.getSelectedIndex()).getDescription();
description.setText(null);
description.setText(systemDescription);
BufferedImage bookImage;
try{
bookImage = ImageIO.read(new File(listOfSystems.get(systemList.getSelectedIndex()).getLogoFileName()));
Image scaledBackground = bookImage.getScaledInstance((int)(scaleFactorX * (double)150),(int)(scaleFactorY * (double)214),java.awt.Image.SCALE_SMOOTH);
imageLabel.setIcon((new ImageIcon(scaledBackground)));
}catch(IOException e2){
e2.printStackTrace();
}
imageLabel.repaint();
}
});
} | 2 |
public void setValueAt(Object valor, int indiceLinha, int indiceColuna) {
//Obtém o objeto em questão, para alteração, de acordo com o índice de linha recebido
JobProtheus job = linhas.get(indiceLinha);
if (indiceColuna == 0){
job.setStatus((String) valor);
}else if (indiceColuna == 1) {
job.setRnc((String) valor);
}else if (indiceColuna == 2) {
job.setCentroTrabalho((String) valor);
}else if (indiceColuna == 3){
job.setJob((String) valor);
}else if (indiceColuna == 4){
job.setOperacao((Integer) valor);
}else if (indiceColuna == 5){
job.setProduto((String) valor);
}else if (indiceColuna == 6){
job.setDataEmissao((String) valor);
}else if (indiceColuna == 7){
job.setDescricaoProduto((String) valor);
}else if (indiceColuna == 8){
job.setQuantidadeLiberada((Integer) valor);
}
fireTableDataChanged();
} | 9 |
public void add(ChangeEffect changeEffect) {
// Passes the filter? => Add
if ((changeEffectResutFilter == null) || (!changeEffectResutFilter.filter(changeEffect))) changeEffects.add(changeEffect);
} | 2 |
private Gene matchingGeneSelect_secondMethod(Gene par1, Gene par2) {
int x = (Math.random() < 0.5) ? 0 : 1;
//TODO
return null;
} | 1 |
public void testMultipliedBy_int() {
Years test = Years.years(2);
assertEquals(6, test.multipliedBy(3).getYears());
assertEquals(2, test.getYears());
assertEquals(-6, test.multipliedBy(-3).getYears());
assertSame(test, test.multipliedBy(1));
Years halfMax = Years.years(Integer.MAX_VALUE / 2 + 1);
try {
halfMax.multipliedBy(2);
fail();
} catch (ArithmeticException ex) {
// expected
}
} | 1 |
static void preprocess(char[] p) {
int i = 0, j = -1, m = p.length;
b = new int[p.length + 1];
b[0] = -1;
while (i < m) {
while (j >= 0 && p[i] != p[j])
j = b[j];
b[++i] = ++j;
}
} | 3 |
@Override
public void fill(Parameter parameter, Type type, Annotation[] annotations)
{
Requirement requirement = Requirement.DEFAULT;
for (Annotation annotation : annotations)
{
if (annotation instanceof Optional)
{
requirement = Requirement.OPTIONAL;
}
}
parameter.offer(Properties.REQUIREMENT, requirement);
} | 2 |
public static boolean isVariableInProductions(Grammar grammar,
String variable) {
ProductionChecker pc = new ProductionChecker();
Production[] productions = grammar.getProductions();
for (int k = 0; k < productions.length; k++) {
if (ProductionChecker.isVariableInProduction(variable,
productions[k])) {
return true;
}
}
return false;
} | 2 |
public void run() {
position++;
} | 0 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
HtmlAttributeToken other = (HtmlAttributeToken) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
} | 9 |
public void setNewImage(String newImage)
{
URL loc = this.getClass().getResource("/karel/themes/" + newImage);
ImageIcon iia = new ImageIcon(loc);
Image image = iia.getImage();
this.setImage(image);
} | 0 |
String getSpaceGroupInfoText(String spaceGroup) {
if (frame == null)
return "";
SpaceGroup sg;
String strOperations = "";
int modelIndex = viewer.getDisplayModelIndex();
if (spaceGroup == null) {
if (modelIndex < 0)
return "no single current model";
if (frame.cellInfos == null)
return "not applicable";
CellInfo cellInfo = frame.cellInfos[modelIndex];
spaceGroup = cellInfo.spaceGroup;
if (spaceGroup.indexOf("[") >= 0)
spaceGroup = spaceGroup.substring(0, spaceGroup.indexOf("[")).trim();
if (spaceGroup == "spacegroup unspecified")
return "no space group identified in file";
sg = SpaceGroup.determineSpaceGroup(spaceGroup, cellInfo.getNotionalUnitCell());
strOperations = "\nSymmetry operations employed:" + frame.getModelSymmetryList(modelIndex);
}
else if (spaceGroup.equalsIgnoreCase("ALL")) {
return SpaceGroup.dumpAll();
}
else {
sg = SpaceGroup.determineSpaceGroup(spaceGroup);
if (sg == null)
sg = SpaceGroup.createSpaceGroup(spaceGroup);
}
if (sg == null)
return "could not identify space group from name: " + spaceGroup;
return sg.dumpInfo() + strOperations;
} | 9 |
public void stopGame() {
// Setting isRunning to false will
// make the thread stop (see run())
this.isRunning = false;
// Unset the game model...
this.view.setModel(null);
// Stop listening for events
this.view.removeKeyListener(this.keyListener);
// Make sure we wait until the thread has stopped...
if (this.gameThread != null) {
while (this.gameThread.isAlive()) {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
// Pass the call on.
Thread.currentThread().interrupt();
}
}
}
} | 3 |
public static double toDouble(String nb){
char[] nr=nb.toCharArray();
int i;
double f;
double result=0;
boolean fraction=false;
if(nb==null||nb.equals(""))
return 0;
for(i=0;i<nr.length &&!fraction;i++)
if(Character.isDigit(nr[i]))
{result*=10;
result+=(nr[i]-'0');
}
else
{fraction=true;
if(nr[i]!='.')
return 0.0;
}
for(f=10;i<nr.length;i++,f*=10)
{
if(Character.isDigit(nr[i]))
result+=(double)( (nr[i]-'0')/f);
else
return 0;
}
return result;
} | 8 |
public static void main (String [ ] args) {
int x = 1;
int y = 1;
while (x < 5) {
if (y < 5) {
x = x + 1;
if (y < 3) {
x = x - 1;
}
}
y = y + 2;
System.out.print (x + "" + y + " ");
x = x + 1;
}
System.out.println ( );
} | 3 |
static double[] eigenValues(double[][] A){
double[] values = new double[A.length];
String[][] stringA = new String[A.length][A.length];
for(int i = 0; i < A.length; i++)
for(int j = 0; j < A.length; j++){
if(i == j)
stringA[i][j] = String.valueOf(A[i][j]) + " - x";
else
stringA[i][j] = String.valueOf(A[i][j]);
}
return values;
} | 3 |
private void handleNumericAttribute(Instances trainInstances)
throws Exception {
m_c45S = new C45Split(m_attIndex, 2, m_sumOfWeights);
m_c45S.buildClassifier(trainInstances);
if (m_c45S.numSubsets() == 0) {
return;
}
m_errors = 0;
Instances [] trainingSets = new Instances [m_complexityIndex];
trainingSets[0] = new Instances(trainInstances, 0);
trainingSets[1] = new Instances(trainInstances, 0);
int subset = -1;
// populate the subsets
for (int i = 0; i < trainInstances.numInstances(); i++) {
Instance instance = trainInstances.instance(i);
subset = m_c45S.whichSubset(instance);
if (subset != -1) {
trainingSets[subset].add((Instance)instance.copy());
} else {
double [] weights = m_c45S.weights(instance);
for (int j = 0; j < m_complexityIndex; j++) {
Instance temp = (Instance)instance.copy();
if (weights.length == m_complexityIndex) {
temp.setWeight(temp.weight() * weights[j]);
} else {
temp.setWeight(temp.weight() / m_complexityIndex);
}
trainingSets[j].add(temp);
}
}
}
/* // compute weights (weights of instances per subset
m_weights = new double [m_complexityIndex];
for (int i = 0; i < m_complexityIndex; i++) {
m_weights[i] = trainingSets[i].sumOfWeights();
}
Utils.normalize(m_weights); */
Random r = new Random(1);
int minNumCount = 0;
for (int i = 0; i < m_complexityIndex; i++) {
if (trainingSets[i].numInstances() > 5) {
minNumCount++;
// Discretize the sets
Discretize disc = new Discretize();
disc.setInputFormat(trainingSets[i]);
trainingSets[i] = Filter.useFilter(trainingSets[i], disc);
trainingSets[i].randomize(r);
trainingSets[i].stratify(5);
NaiveBayesUpdateable fullModel = new NaiveBayesUpdateable();
fullModel.buildClassifier(trainingSets[i]);
// add the errors for this branch of the split
m_errors += NBTreeNoSplit.crossValidate(fullModel, trainingSets[i], r);
} else {
for (int j = 0; j < trainingSets[i].numInstances(); j++) {
m_errors += trainingSets[i].instance(j).weight();
}
}
}
// Check if minimum number of Instances in at least two
// subsets.
if (minNumCount > 1) {
m_numSubsets = m_complexityIndex;
}
} | 9 |
public String verificaMenorTempo()
{
double tempoTorno;
double tempoMandril;
double tempoFresa;
ordenaPeloTempoDeSaidaM(maquinaMandril);
ordenaPeloTempoDeSaidaF(maquinaFresa);
ordenaPeloTempoDeSaidaT(maquinaTorno);
if(maquinaTorno.get(0).getRolamento() != null)
{
tempoTorno=maquinaTorno.get(0).getInstante()+maquinaTorno.get(0).getRolamento().getTempoTorno();
}
else
{
tempoTorno=getTempoUniversal()+1;
}
if(maquinaFresa.get(0).getRolamento() != null)
{
tempoFresa=maquinaFresa.get(0).getInstante()+maquinaFresa.get(0).getRolamento().getTempoFresa();
}
else
{
tempoFresa=getTempoUniversal()+1;
}
if(maquinaMandril.get(0).getRolamento() != null)
{
tempoMandril=maquinaMandril.get(0).getInstante()+maquinaMandril.get(0).getRolamento().getTempoMandril();
}
else
{
tempoMandril=getTempoUniversal()+1;
}
if(tempoTorno <= tempoMandril && tempoTorno <= tempoFresa)
{
return "Torno";
}
if(tempoFresa <= tempoTorno && tempoFresa <= tempoMandril)
{
return "Fresa";
}
if(tempoMandril <= tempoTorno && tempoMandril <= tempoFresa)
{
return "Mandril";
}
return "Erro";
} | 9 |
public static int getNextIDDzien(){
if(dni[0]==null)
return 1;
for(int i=0 ; i<10 ; i++)
if(freeIDDni[i]!=0)
{
int d = freeIDDni[i];
freeIDDni[i]=0;
return d;
}
int ID;
boolean flaga=true;
while(true)
{
IteratorDni.first();
ID= dni[CountDni-1].id + 1;
while(IteratorDni.isDone())
{
if(ID==IteratorDni.currentItem().id)
{
flaga=false;
break;
}
IteratorDni.next();
}
if(flaga)
return ID;
}
} | 7 |
public static boolean addInfo(databook bk){
boolean flag=false;
try{
contct=connector.getConnection();
Sttt=contct.prepareStatement("insert into bk "+"values(?,?,?,?,?,?)");
Sttt.setString(1,bk.Gin());
Sttt.setString(2,bk.Gte());
Sttt.setString(4,bk.Gpe());
Sttt.setString(6,bk.Gpr());
if(Sttt.executeUpdate()==1)flag=true;
}catch(SQLException e){
System.out.println(e.getMessage());
}
connector.Close(contct, Sttt);
return flag;
} | 2 |
public RiverNode calculateNext() {
double[][] array = instance.array;
ArrayList<Integer[]> o = getNearbyRegions(array, x, y);
double min = array[x][y];
int mX = x, mY = y;
for (Integer[] i : o)
if (array[i[0]][i[1]] <= min) {
min = array[i[0]][i[1]];
mX = i[0];
mY = i[1];
}
return new RiverNode(mX, mY, instance, null, this);
} | 2 |
public ListNode rotateRightII(ListNode head, int n) {
int length = 0;
ListNode newHead = null, prevNewHead = null, end = null;
for (ListNode node = head; node != null; node = node.next) {
if (node.next == null) {
end = node;
}
length++;
}
if (length < 2 || n == 0 || n % length == 0) {
return head;
}
ListNode node = head;
for (int i = 0; i < length - n % length - 1; i++) {
node = node.next;
}
prevNewHead = node;
newHead = prevNewHead.next;
prevNewHead.next = null;
end.next = head;
return newHead != null ? newHead : head;
} | 7 |
@Override
public void onCommand(String command) {
final String[] splits = command.split(" ");
if (splits[0].equals("enlist")) {
// enlist <<node_id>> <<transaction_id>>
Integer tid = Integer.parseInt(splits[2]);
if(!_xacts.containsKey(tid)){
System.out.println("Invalid tid " + tid.toString());
return;
}
DtManager.Enlist(Integer.parseInt(splits[1]), _xacts.get(tid).Id);
} else if (splits[0].equals("createTx")) {
// create <<transaction_id>>
DistributedTransaction dt = DtManager.Create();
_xacts.put(Integer.parseInt(splits[1]), dt);
} else if (splits[0].equals("commit")) {
// commit <<transaction_id>>
Integer tid1 = Integer.parseInt(splits[1]);
if(!_xacts.containsKey(tid1)){
System.out.println("Invalid tid " + tid1.toString());
return;
}
DtManager.Commit(_xacts.get(tid1), new INotify() {
@Override
public void onCompleted(Status result, String data) {
System.out.println("Transaction " + splits[1] + " returned " + result.toString());
}
});
} else if (splits[0].equals("abort")) {
// commit <<transaction_id>>
try {
DtManager.Abort(_xacts.get(Integer.parseInt(splits[1])), new INotify() {
@Override
public void onCompleted(Status result, String data) {
System.out.println("Transaction " + splits[1] + " returned " + result.toString());
}
});
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} | 8 |
long f(int n) {
cache.put(1, 1L);
cache.put(2, 2L);
for (int i = 3; i <= n; i++) {
if (cache.get(i) == null) {
cache.put(i, cache.get(i - 1) + cache.get(i - 2));
}
}
return cache.get(n);
} | 2 |
public Collision collision( GameObject with )
{
if ( topX >= with.getX()+with.getWidth() ||
topX+width <= with.getX() ||
topY >= with.getY()+with.getHeight() ||
topY+height <= with.getY() )
return Collision.NO_HIT;
else {
return Collision.HIT;
}
} | 4 |
public List getList(Class type)
{
if (type == null) return entities;
List list = new ArrayList();
for (Object e : entities)
{
if (type.isInstance(e))
{
list.add(e);
}
}
return list;
} | 3 |
* @param options
* @return Cons
*/
public static Cons decomposeNamestring(String namestring, Cons options) {
{ PropertyList self000 = PropertyList.newPropertyList();
self000.thePlist = options;
{ PropertyList plist = self000;
Keyword breakoncap = Stella.KWD_CLEVER;
Keyword breakonnumber = Stella.KWD_CLEVER;
String breakonseparators = "-_ ";
Stella_Object.vetOptions(plist, Stella.getQuotedTree("((:BREAK-ON-CAP :BREAK-ON-NUMBER :BREAK-ON-SEPARATORS) \"/STELLA\")", "/STELLA"));
{ Stella_Object key = null;
Stella_Object value = null;
Cons iter000 = plist.thePlist;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest.rest) {
key = iter000.value;
value = iter000.rest.value;
{ GeneralizedSymbol testValue000 = ((GeneralizedSymbol)(key));
if (testValue000 == Stella.KWD_BREAK_ON_CAP) {
if (value != null) {
breakoncap = ((Keyword)(value));
}
else {
breakoncap = Stella.KWD_NO;
}
}
else if (testValue000 == Stella.KWD_BREAK_ON_NUMBER) {
if (value != null) {
breakonnumber = ((Keyword)(value));
}
else {
breakonnumber = Stella.KWD_NO;
}
}
else if (testValue000 == Stella.KWD_BREAK_ON_SEPARATORS) {
breakonseparators = ((StringWrapper)(value)).wrapperValue;
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + testValue000 + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
}
}
}
return (Stella.decomposeNamestringFull(namestring, breakoncap, breakonnumber, breakonseparators));
}
}
} | 6 |
protected static void add(DoItLater c) {
if (isHtmlOutput()) {
getInstance().actionQueue.add(new DoItLater() {
@Override
public void doIt() {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
});
getInstance().actionQueue.add(c);
}
} | 2 |
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (Exception ex) {
Logger.getLogger(ControlJson.class
.getName()).log(Level.SEVERE, null, ex);
}
} | 1 |
public List<Alignment> importAlignments() throws IOException, ImportException
{
boolean done = false;
List<Taxon> taxonList = null;
List<Alignment> alignments = new ArrayList<Alignment>();
while (!done) {
try {
NexusBlock block = findNextBlock();
if (block == NexusBlock.TAXA) {
taxonList = readTaxaBlock();
} else if (block == NexusBlock.CHARACTERS) {
if (taxonList == null) {
throw new MissingBlockException("TAXA block is missing");
}
List<Sequence> sequences = readCharactersBlock(taxonList);
alignments.add(new BasicAlignment(sequences));
} else if (block == NexusBlock.DATA) {
// A data block doesn't need a taxon block before it
// but if one exists then it will use it.
List<Sequence> sequences = readDataBlock(taxonList);
alignments.add(new BasicAlignment(sequences));
} else {
// Ignore the block..
}
} catch (EOFException ex) {
done = true;
}
}
if (alignments.size() == 0) {
throw new MissingBlockException("DATA or CHARACTERS block is missing");
}
return alignments;
} | 7 |
public ArrayList<String> getMovieXml(String movieName) throws TransformerConfigurationException, TransformerException{
URL url;
try {
url = new URL("http://www.omdbapi.com/?t="+movieName+"&y=&plot=short&r=xml");
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
TransformerFactory factory3 = TransformerFactory.newInstance();
Transformer xform = factory3.newTransformer();
// that’s the default xform; use a stylesheet to get a real one
xform.transform(new DOMSource(doc), new StreamResult(new File(System.getProperty("user.dir")+"/temp_movie.xml")));
this.readXMLfile();
} catch (MalformedURLException ex) {
Logger.getLogger(MuokkaaHenkiloJDialog.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(MuokkaaHenkiloJDialog.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MuokkaaHenkiloJDialog.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(MuokkaaHenkiloJDialog.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerConfigurationException ex) {
Logger.getLogger(MuokkaaHenkiloJDialog.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerException ex) {
Logger.getLogger(MuokkaaHenkiloJDialog.class.getName()).log(Level.SEVERE, null, ex);
}
return elokuvantiedot;
} | 6 |
public void make(Move m) throws IllegalMoveException {
FifteenMove fifteenMove = (FifteenMove) m;
isGameNew = false;
if (!isLegal(fifteenMove)) {
throw new IllegalMoveException(fifteenMove);
}
if (fifteenMove.equals(new FifteenMove(QUIT))) {
resignation(nextPlayer);
return;
}
if (nextPlayer == Game.FIRST_PLAYER) {
playerOneSet.add(fifteenMove);
if (playerOneSet.size() >= 3)
checkGameStatus(playerOneSet);
} else {
playerTwoSet.add(fifteenMove);
if (playerOneSet.size() >= 3)
checkGameStatus(playerTwoSet);
}
moveSet.remove(fifteenMove);
if (moveSet.size() == 1) // only 0 is left behind
gameStatus = Game.DRAW;
nextPlayer = (nextPlayer == Game.FIRST_PLAYER ? Game.SECOND_PLAYER
: Game.FIRST_PLAYER);
} | 7 |
private int getEdgeNumber(double edgeLenght) {
System.out.println("D: " + edgeLenght);
int edgeNumber = -1;
if (edgeLenght < (edgeA + moe) && edgeLenght > (edgeA - moe))
return 0;
else if (edgeLenght < (edgeB + moe) && edgeLenght > (edgeB - moe))
return 1;
else if (edgeLenght < (edgeC + moe) && edgeLenght > (edgeC - moe))
return 2;
else if (edgeLenght < (edgeD + moe) && edgeLenght > (edgeD - moe))
return 3;
return edgeNumber;
} | 8 |
public static State findBoxPathToGoal(Position box, Position goal, State currentState) {
HashSet<State> visited = new HashSet<>();
PriorityQueue<StateHolder> prio = new PriorityQueue<>();
// add the first state to the prio
prio.add(new StateHolder(currentState, box));
while(!prio.isEmpty()) {
StateHolder currentStateHolder = prio.poll();
State current = currentStateHolder.getState();
Position currentBox = currentStateHolder.getBox();
Position player = current.getPlayer();
if(current.getBoxes().contains(goal)) {
current.updateValue();
return current;
}
for (Position adjucent : getAdjucentPositions(currentBox, current)) {
// find out if we can reach it from our current position w/o
// moving any boxes
String path_to_adjucent = findPath(player, adjucent, current);
// check if there was such path
if (path_to_adjucent != null) {
// try to move the box
Movement moved_path = tryToMoveBox(currentBox, adjucent, current);
// check if we actually managed to move the box
if (moved_path != null) {
// create a new state
State new_state;
try {
// clone this state
new_state = (State) current.clone();
// update the BoxState we just moved
new_state.boxes.remove(currentBox);
new_state.boxes.add(moved_path.getBox());
// update the player state
new_state.player = moved_path.getPlayer();
// update the current path
new_state.current_path = new StringBuilder(new_state.current_path).
append(path_to_adjucent).append(moved_path.getPath()).toString();
//new_state.updateValue();
new_state.value = Position.manhattanDistance(moved_path.getBox(), goal);
/*Update the reachable positions*/
new_state.setReachPositions();
// add this state to the list to return
if(!visited.contains(new_state)) {
visited.add(new_state);
prio.add(new StateHolder(new_state, moved_path.getBox()));
}
} catch (CloneNotSupportedException ex) {
Logger.getLogger(State.class.getName()).log(Level.SEVERE, null, ex);
}
} // end checking if moved_path is null
} // end checking if path to box is null
} // end for each adjucent position to a box
}
return null;
} | 7 |
private boolean processNumberedReference() {
boolean isHexNumberedReference =
originalMessage.charAt(nextPotentialReferencePosition + 2) == 'x' ||
originalMessage.charAt(nextPotentialReferencePosition + 2) == 'X';
try {
int value = (!isHexNumberedReference) ?
Integer.parseInt(getReferenceSubstring(2)) :
Integer.parseInt(getReferenceSubstring(3), 16);
decodedMessage.append((char) value);
return true;
}
catch (NumberFormatException ex) {
return false;
}
} | 3 |
public void monitorarBatimentosCardiacos(float batimentos, Paciente paciente)
throws ControllerException {
try {
if (batimentos < 0) {
throw new ControllerException(
"valor de quantidade de batimentos/seg inválido");
}
if (ValidarPaciente(paciente)
&& (batimentos < 30 || batimentos > 100)) {
Publish publish = new Publish(paciente.getIdTopico(), uriHub);
Evento evento = new Evento(BATIMENTOS + "=" + batimentos,
Calendar.getInstance(), paciente);
eventoDAO.save(evento);
publish.publish(evento.getDescricao());
}
} catch (ObjetoNuloException | ValorInvalidoException e) {
throw new ControllerException(e.getMessage());
} catch (ComunicationException e) {
throw new ControllerException(e.getMessage());
} catch (DAOException e) {
throw new ControllerException(e.getMessage());
}
} | 7 |
public void update(GameContainer gc, StateBasedGame sb, int delta) {
for (Component component : getComponents()) {
component.update(gc, sb, delta);
}
int mousePosX = Mouse.getX();
int mousePosY = Math.abs(Mouse.getY() - Game.app.getHeight());
Input input = gc.getInput();
if ( mousePosX > getPosition().getX() && mousePosX < getPosition().getX() + image.getWidth()
&& mousePosY > getPosition().getY() && mousePosY < getPosition().getY() + image.getHeight() ) { // cursor is inside button
if (input.isMousePressed(0)) {
mousePressed = true;
input.clearKeyPressedRecord();
input.clearMousePressedRecord();
} else {
mousePressed = false;
}
}
} | 6 |
public void keyPressed(int k){
if(k == KeyEvent.VK_RIGHT) player.setRight(true);
if(k == KeyEvent.VK_LEFT) player.setLeft(true);
if(k == KeyEvent.VK_W) player.setJumping(true);
if(k == KeyEvent.VK_R) player.setScratching();
if(k == KeyEvent.VK_F) player.setFiring();
} | 5 |
private void init( File file )
{
fileRef = file ;
String fileName = fileRef.getName() ;
int i1 = fileName.indexOf( '_' ) ;
int i2 = fileName.indexOf( '.', -1 ) ;
prefix = "" ;
suffix = "" ;
// check the java style filename -> "name_language_country_variant.php"
if ( i1 > 0 ) // has _ => filename with language extension
{
prefix = fileName.substring( 0, i1 ) ;
if ( i2 > 0 )
{
suffix = fileName.substring( i2 ) ;
version = fileName.substring( i1 + 1, i2 ) ;
}
else // no valid suffix
{
version = fileName.substring( i1 + 1 ) ;
}
}
else // no _ => no language extension
{
version = "" ;
if ( i2 > 0 ) // only . in filename => no language extension
{
prefix = fileName.substring( 0, i2 ) ;
suffix = fileName.substring( i2 ) ;
// prefix is iso code => file like "language.php"
if (prefix.length() == 2)
{
// is it a iso code ?
String dummy = TLanguageNames.runtime.getLanguageName(prefix) ;
if (dummy.length() > 0)
{
lang = prefix ;
prefix = "" ;
}
}
}
else // no _ and . => filename without fileextension like .php
{
prefix = fileName ;
}
}
if ( version.length() > 0 )
{
// full structure "_languageID_countryID" = version
i1 = version.indexOf( '_' ) ;
if ( i1 > 1 ) // ignore any leading _
{
country = version.substring( i1 + 1 ) ;
lang = version.substring( 0, i1 ) ;
i1 = country.indexOf("_") ;
if ( i1 > 1) // variant available
{
String dummy = country ;
country = dummy.substring(0, i1) ;
variant = dummy.substring(i1+1) ;
}
}
else
{
lang = version ;
}
}
} | 8 |
private static void calcNoOfNodes(Node node) {
if (node instanceof Parent) {
if (((Parent) node).getChildrenUnmodifiable().size() != 0) {
ObservableList<Node> tempChildren = ((Parent) node).getChildrenUnmodifiable();
noOfNodes += tempChildren.size();
for (Node n : tempChildren) {
calcNoOfNodes(n);
}
}
}
} | 3 |
public SoundClip(String clipURL)
{
clipLoader = new AudioClipLoader();
try {
clip=clipLoader.loadClip(clipURL);
} catch (UnsupportedAudioFileException | IOException
| LineUnavailableException e)
{
e.printStackTrace();
}
} | 1 |
public void checkTriggers(){
Debug.println("Checking room triggers");
ArrayList<Trigger> all_trig = new ArrayList<Trigger>(triggers);
for(String item : items){
all_trig.addAll(Game.item_list.get(item).getTriggers());
}
for(String container : containers){
all_trig.addAll(Game.container_list.get(container).getTriggers());
}
for(String creature : creatures){
all_trig.addAll(Game.creature_list.get(creature).getTriggers());
}
for(Trigger trigger : all_trig){
Debug.println("Trigger found: checking");
if(trigger.used == false){// || trigger.permanent){
if(!trigger.hasCommand()){
if(trigger.checkConditionsTrue()){
trigger.used = true;
trigger.execute();
}
}
}
}
for(Trigger trigger : all_trig){
if(trigger.permanent){
trigger.used = false;
}
}
Debug.println("Done checking all room triggers");
} | 9 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Frm_RelReciboCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frm_RelReciboCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frm_RelReciboCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frm_RelReciboCliente.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 Frm_RelReciboCliente().setVisible(true);
}
});
} | 6 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.