text stringlengths 14 410k | label int32 0 9 |
|---|---|
public Object nextEntity(char ampersand) throws JSONException {
StringBuffer sb = new StringBuffer();
for (;;) {
char c = next();
if (Character.isLetterOrDigit(c) || c == '#') {
sb.append(Character.toLowerCase(c));
} else if (c == ';') {
break;
} else {
throw syntaxError("Missing ';' in XML entity: &" + sb);
}
}
String string = sb.toString();
Object object = entity.get(string);
return object != null ? object : ampersand + string + ";";
} | 5 |
public void prevValue() {
value--;
if (value < 0) {
value = values.length -1;
}
} | 1 |
public Extracciones(String ruta)
{
this.BDextracciones = new BD(ruta);
this.idProyecto = new ArrayList<Integer>();
this.proyectos = new ArrayList<Extraccion>();
int[] totalExtracciones;
File bd = new File(ruta);
if(bd.length() > 2000)
{
totalExtracciones = this.listadoExtracciones();
for(int i=0;i<totalExtracciones.length;i++)
{
this.proyectos.add(new Extraccion(totalExtracciones[i],ruta));
this.idProyecto.add(totalExtracciones[i]);
}
}
} | 2 |
protected Map<String, Object> parseProperties( DataStructure parent ) throws IOException {
// Properties format:
//
// properties ::= '(' (key '=' value)* ')'
//
// the first ( has already been read by now
Map<String, Object> result = new LinkedHashMap<String, Object>();
in.position(-1).clone();
int c;
while( (c = in.nextNonWhitespace()) != ')' ) {
if( c < 0 ) {
in.error("Unexpected end of file in property values");
}
if( result.isEmpty() ) {
// First pass, so push back
in.pushBack(c);
} else if( c != ',' ) {
in.error("Missing ',' in property values", in.position(-1));
}
String key = in.parseIdentifier("property");
c = in.nextNonWhitespace();
if( c != '=' ) {
in.error("Expected '=', found:" + (char)c, in.position(-1));
}
Object value = parsePropertyValue(parent);
result.put(key, value);
}
return result;
} | 5 |
@Override
public void anyActionPerformed(AnyActionEvent ev) {
try {
if (ev.isAnyOf(referToOthers)) {
referToOtherConnectors();
} else if (ev.isAnyOf(searchFile)) {
chooseClasspath();
} else if (ev.isAnyOf(searchDriver)) {
chooseDriverClass();
} else if (ev.isAnyOf(submit)) {
requestClose(true);
} else if (ev.isAnyOf(tryToConnect)) {
tryToConnect();
} else if (ev.isAnyOf(cancel)) {
requestClose(false);
}
} catch (Exception ex) {
WindowOutputProcessor.showErrorDialog(this, ex);
}
} | 7 |
public static synchronized String createGame(String rules, User user) {
for (GameRoom room : briscaGames) {
// if(room==null)continue;
if (!room.isBeenPlayed()) {
String roomname = ((rules.split(GameSocketServer.ROOMNAMEKEY)[1])
.split(",")[0]);
roomname = ManagerSocketServer.sanitizeWord(roomname);
room.setName(roomname);
room.setParameters(rules);
room.addPlayer(Player.getInstance(0, user));
return roomname;
}
}
return null;
} | 2 |
private void drawNorth(Terrain[][] currentBoard,
Entities[][] currentObjects, Graphics g) {
Location playerDir = boardState.getPlayerCoords();
for (int i = 0; i < currentBoard.length; i++) {
for (int j = 0; j < currentBoard[0].length; j++) {
//Isometric formula for x, i *0.5 * Width - j * 0.5 * Width, including offset to get
//the screen centered in the middle
double x = ((i + 5.5 - playerDir.x) * 0.5 * width / 10)
- ((j + 5.5 - playerDir.y) * 0.5 * width / 10)
+ (10 / 1.75) * (int) width / 13;
//Isometric formula for y, i * 0.5 * Height + j * 0.5 * Height including offset to get
//the screen centered in the middle
double y = ((i + 5.5 - playerDir.x) * 0.5 * height / 15)
+ ((j + 5.5 - playerDir.y) * 0.5 * height / 15)
+ (10 / 3) * (int) height / 21;
//Drawing constrained to screen ratios to handle different resolutions and resizing :)
if (currentBoard[i][j] != null)
g.drawImage(
currentBoard[i][j].img,
(int) x,
(int) y,
(int) width/10,
(int) height/15,
null);
else {
System.out.println("Error!");
}
}
}
for (int i = 0; i < currentBoard.length; i++) {
for (int j = 0; j < currentBoard[0].length; j++) {
//If an object exists on this tile
if (currentObjects[i][j] != null) {
//Same isometric formula for x, y values, except modified for the image size.
//Image width scaled - tile width should give the difference between the two, /2 to center
//in the middle of the tile (half the difference on each side of the tile).
double x = ((i + 5.5 - playerDir.x) * 0.5 * width / 10)
- ((j + 5.5 - playerDir.y) * 0.5 * width / 10)
+ (10 / 1.75) * (int) width / 13
- (currentObjects[i][j].imgs[0].getWidth(null) * (width / startingWidth) - width/10)/2;
//Same isometric formula for x, y values except modified for image height.
//We want the image to sit about 75% down the tile to look "centered". Adding
//0.75 of the tile height then subtracting the image height will give the desired
//effect
double y = ((i + 5.5 - playerDir.x) * 0.5 * height / 15)
+ ((j + 5.5 - playerDir.y) * 0.5 * height / 15)
+ (10 / 3) * (int) height / 21
+ (0.75 * height / 15) - (currentObjects[i][j].imgs[0].getHeight(null) * (height / startingHeight));
g.drawImage(
currentObjects[i][j].imgs[0],
(int) x,
(int) y,
(int) (currentObjects[i][j].imgs[0]
.getWidth(null) * (width / startingWidth)),
(int) (currentObjects[i][j].imgs[0]
.getHeight(null) * (height / startingHeight)),
null);
}
}
}
} | 6 |
@Override
public List<LogProfile> getLogFileNames() throws RemoteException {
List<LogProfile> logs=new LinkedList<LogProfile>();
try {
Session session=this.conn.openSession();
String cmd="ls -l "+this.home+"/logs";
session.execCommand(cmd);
InputStream stdout=new StreamGobbler(session.getStdout());
BufferedReader br=new BufferedReader(new InputStreamReader(stdout));
String line=br.readLine();
while(true){
line=br.readLine();
if(line==null){
break;
}
String[] attrs=line.split("[ ]+");
if(!attrs[7].endsWith(".log")){
continue;
}
LogProfile log=new LogProfile();
log.setName(attrs[7]);
log.setOwner(attrs[2]);
log.setGroup(attrs[3]);
log.setSize(Long.parseLong(attrs[4]));
logs.add(log);
}
br.close();
session.close();
} catch (IOException e) {
throw new RemoteException(e);
}
return logs;
} | 4 |
protected RawModel generateTerrain(Loader loader, String heightMap)
{
if (heightMap == null) return null;
BufferedImage image = null;
try {
image = ImageIO.read(new File("res/"+heightMap+".png"));
} catch (IOException e) {
e.printStackTrace();
}
int VERTEX_COUNT = image.getHeight();
int count = VERTEX_COUNT * VERTEX_COUNT;
float[] vertices = new float[count*3];
float[] normals = new float[count*3];
float[] textureCoords = new float[count*2];
int[] indices = new int[6*(VERTEX_COUNT-1)*(VERTEX_COUNT*1)];
int vertexPointer = 0;
for (int i = 0; i < VERTEX_COUNT; i++) {
for (int j = 0; j < VERTEX_COUNT; j++) {
vertices[vertexPointer*3] = (float)j/((float)VERTEX_COUNT-1) * SIZE;
vertices[vertexPointer*3+1] = getHeight(j, i, image);
vertices[vertexPointer*3+2] = (float)i/((float)VERTEX_COUNT-1) * SIZE;
Vector3f normal = calculateNormal(j, i, image);
normals[vertexPointer*3] = normal.x;
normals[vertexPointer*3+1] = normal.y;
normals[vertexPointer*3+2] = normal.z;
textureCoords[vertexPointer*2] = (float)j/((float)VERTEX_COUNT-1);
textureCoords[vertexPointer*2+1] = (float)i/((float)VERTEX_COUNT-1);
vertexPointer++;
}
}
int pointer = 0;
for (int gz = 0; gz < VERTEX_COUNT-1; gz++) {
for (int gx = 0; gx < VERTEX_COUNT-1; gx++) {
int topLeft = (gz*VERTEX_COUNT) + gx;
int topRight = topLeft + 1;
int bottomLeft = ((gz+1)*VERTEX_COUNT) + gx;
int bottomRight = bottomLeft + 1;
indices[pointer++] = topLeft;
indices[pointer++] = bottomLeft;
indices[pointer++] = topRight;
indices[pointer++] = topRight;
indices[pointer++] = bottomLeft;
indices[pointer++] = bottomRight;
}
}
for (int i = 0; i < vertices.length; i+=3)
{
System.out.println(vertices[i] + " " + vertices[i+1] + " " + vertices[i+2]);
}
return loader.loadToVAO(vertices, textureCoords, normals, indices);
} | 7 |
public void imprimir() {
for (int j = 0; j < ListToken.size(); j++) {//ahora imprimiremos las personas de nuestro ArrayList
System.out.println("============================================================");
Nodo persona = (Nodo) ListToken.get(j);
System.out.println("Lexico: " + persona.getValor());
System.out.println("Valor: " + persona.getDescripcion());
System.out.println("============================================================");
}
} | 1 |
public int[] getColumnInt(int colNum)
{
int nRows = 0;
int i = 0;
int[] ret;
if(colNum > 0){
try {
//get amount of rows
while(result.next()){
nRows ++;
}
//Check if there is more then 0 rows
if(nRows == 0)
return null;
ret = new int[nRows]; //create the Intarray with the now known size
result.first();
ret[i] = result.getInt(colNum);
i ++;
while(result.next()){
ret[i] = result.getInt(colNum);
i++;
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
return ret;
}
else
{
return null;
}
} | 5 |
public Args parse(String [] arguments) throws InvalidParameterException{
Args args = new Args();
if(arguments == null || arguments.length <= 0){
throw new InvalidParameterException("arguments is empty");
}
if(arguments.length < 2){
throw new InvalidParameterException("miss required arguments");
}
if(commands.contains(arguments[0].toLowerCase())){
args.setCommand(arguments[0]);
}else{
throw new InvalidParameterException("Unknown command "+arguments[0]);
}
if(JavaClassNameParser.isInvalidClassName(arguments[1])){
args.setTargetName(arguments[1]);
}else{
throw new InvalidParameterException(String.format("The targetName %s is not a valid class name!",arguments[1]));
}
if(arguments.length >= 3){
if(arguments[2].startsWith("-")){
parseOptions(arguments[2].substring(1),args);
}else{
parseTemplateGroup(arguments[2],args);
}
}
if(arguments.length >= 4){
parseTemplateGroup(arguments[3],args);
}
if(arguments.length >= 5){
parseConfigFileName(arguments[4],args);
}
return args;
} | 9 |
private static void displayMutualInformation (double[][] density, int numGridLines) {
double mutualInfo = 0.0;
// Calculate marginal probability in x1 direction
ArrayList<Double> x1MarginalProb = new ArrayList<Double> ();
for (int x1Ind = 0; x1Ind < numGridLines; x1Ind++) {
Double margProb = 0.0;
for (int x2Ind = 0; x2Ind < numGridLines; x2Ind++) {
margProb += density[x1Ind][x2Ind];
}
x1MarginalProb.add(margProb);
}
// Calculate marginal probability in x2 direction
ArrayList<Double> x2MarginalProb = new ArrayList<Double> ();
for (int x2Ind = 0; x2Ind < numGridLines; x2Ind++) {
Double margProb = 0.0;
for (int x1Ind = 0; x1Ind < numGridLines; x1Ind++) {
margProb += density[x1Ind][x2Ind];
}
x2MarginalProb.add(margProb);
}
// Calculate mutual information
for (int x1Ind = 0; x1Ind < numGridLines; x1Ind++) {
for (int x2Ind = 0; x2Ind < numGridLines; x2Ind++) {
if (density[x1Ind][x2Ind] > 0.0) {
double logXYxy = density[x1Ind][x2Ind]/ (x1MarginalProb.get(x1Ind) * x2MarginalProb.get(x2Ind));
mutualInfo += density[x1Ind][x2Ind] * Math.log10(logXYxy / Math.pow(Settings.discretization, 2));
}
}
}
System.out.println(mutualInfo);
} // end displayMutualInformation | 7 |
private boolean tryInsertIntoChain(final int chainNumber, long key) {
int chainDisplacement = primaryIndex.getChainDisplacement(chainNumber);
//try to store record in main bucket
int pageToStore;
final int keySignature;
if (chainDisplacement > 253) {
return storeRecordInMainBucket(chainNumber, key);
} else {
int chainSignature = primaryIndex.getChainSignature(chainNumber);
keySignature = LinearHashingTableHelper.calculateSignature(key);
if (keySignature < chainSignature) {
moveLargestRecordToRecordPool(chainNumber, (byte) chainSignature);
final boolean result = storeRecordInMainBucket(chainNumber, key);
storeRecordFromRecordPool();
return result;
} else if (keySignature == chainSignature) {
recordPool.add(key);
size--;
moveLargestRecordToRecordPool(chainNumber, (byte) chainSignature);
Bucket bucket = file.get(chainNumber);
primaryIndex.updateSignature(chainNumber, bucket.keys, bucket.size);
storeRecordFromRecordPool();
return true;
} else {
if (chainDisplacement == 253) {
//allocate new page
return allocateNewPageAndStore(chainNumber, chainNumber, key, true);
} else {
pageToStore = findNextPageInChain(chainNumber, chainDisplacement);
}
}
}
//try to store in overflow bucket chain
while (true) {
int realPosInSecondaryIndex = pageIndicator.getRealPosInSecondaryIndex(pageToStore);
chainDisplacement = secondaryIndex.getChainDisplacement(realPosInSecondaryIndex);
if (chainDisplacement > 253) {
return storeRecordInOverflowBucket(pageToStore, key);
} else {
int chainSignature = secondaryIndex.getChainSignature(realPosInSecondaryIndex);
if (keySignature < chainSignature) {
moveLargestRecordToRecordPool(pageToStore, (byte) chainSignature);
final boolean result = storeRecordInOverflowBucket(pageToStore, key);
storeRecordFromRecordPool();
return result;
} else if (keySignature == chainSignature) {
recordPool.add(key);
size--;
moveLargestRecordToRecordPool(pageToStore, (byte) chainSignature);
Bucket bucket = file.get(pageToStore);
secondaryIndex.updateSignature(realPosInSecondaryIndex, bucket.keys, bucket.size);
storeRecordFromRecordPool();
return true;
} else {
if (chainDisplacement == 253) {
//allocate new page
return allocateNewPageAndStore(chainNumber, pageToStore, key, false);
} else {
pageToStore = findNextPageInChain(chainNumber, chainDisplacement);
}
}
}
}
} | 9 |
@Test
public void testCodageNRZ() {
float min = 0;
float max = 4;
src = new SourceFixe("1");
ena = new EmetteurNumeriqueAnalogique(min, max, 4, TypeCodage.NRZ);
src.connecter(ena);
try {
src.emettre();
ena.emettre();
} catch (InformationNonConforme e) {
}
int i = 0;
while(i < 4){
if(ena.getInformationEmise().iemeElement(i).floatValue() != max)fail();
i++;
}
src = new SourceFixe("0");
ena = new EmetteurNumeriqueAnalogique(min, max, 4, TypeCodage.NRZ);
src.connecter(ena);
try {
src.emettre();
ena.emettre();
} catch (InformationNonConforme e) {
}
i = 0;
while(i < 4){
if(ena.getInformationEmise().iemeElement(i).floatValue() != min)fail();
i++;
}
} | 6 |
public static int maxSum(int a[], int start, int end) {
int maxSum = 0;
// Trivial cases
if (start == end) {
return a[start];
} else if (start > end) {
return 0;
} else if (end - start == 1) {
return a[start] > a[end] ? a[start] : a[end];
} else if (start < 0) {
return 0;
} else if (end >= a.length) {
return 0;
}
System.out.println("DEBUG >> start :: " + start + " end :: " + end);
// Subproblem solutions, DP
for (int i = start; i <= end; i++) {
int possibleMaxSub1 = maxSum(a, i + 2, end);
int possibleMaxSub2 = maxSum(a, start, i - 2);
int possibleMax = possibleMaxSub1 + possibleMaxSub2 + a[i];
if (possibleMax > maxSum) {
maxSum = possibleMax;
}
}
return maxSum;
} | 8 |
public void inv_mdct(float[] in, float[] out, int block_type)
{
float[] win_bt;
int i;
float tmpf_0, tmpf_1, tmpf_2, tmpf_3, tmpf_4, tmpf_5, tmpf_6, tmpf_7, tmpf_8, tmpf_9;
float tmpf_10, tmpf_11, tmpf_12, tmpf_13, tmpf_14, tmpf_15, tmpf_16, tmpf_17;
tmpf_0 = tmpf_1 = tmpf_2 = tmpf_3 = tmpf_4 = tmpf_5 = tmpf_6 = tmpf_7 = tmpf_8 = tmpf_9 =
tmpf_10 = tmpf_11 = tmpf_12 = tmpf_13 = tmpf_14 = tmpf_15 = tmpf_16 = tmpf_17 = 0.0f;
if(block_type == 2)
{
/*
*
* Under MicrosoftVM 2922, This causes a GPF, or
* At best, an ArrayIndexOutOfBoundsExceptin.
for(int p=0;p<36;p+=9)
{
out[p] = out[p+1] = out[p+2] = out[p+3] =
out[p+4] = out[p+5] = out[p+6] = out[p+7] =
out[p+8] = 0.0f;
}
*/
out[0] = 0.0f;
out[1] = 0.0f;
out[2] = 0.0f;
out[3] = 0.0f;
out[4] = 0.0f;
out[5] = 0.0f;
out[6] = 0.0f;
out[7] = 0.0f;
out[8] = 0.0f;
out[9] = 0.0f;
out[10] = 0.0f;
out[11] = 0.0f;
out[12] = 0.0f;
out[13] = 0.0f;
out[14] = 0.0f;
out[15] = 0.0f;
out[16] = 0.0f;
out[17] = 0.0f;
out[18] = 0.0f;
out[19] = 0.0f;
out[20] = 0.0f;
out[21] = 0.0f;
out[22] = 0.0f;
out[23] = 0.0f;
out[24] = 0.0f;
out[25] = 0.0f;
out[26] = 0.0f;
out[27] = 0.0f;
out[28] = 0.0f;
out[29] = 0.0f;
out[30] = 0.0f;
out[31] = 0.0f;
out[32] = 0.0f;
out[33] = 0.0f;
out[34] = 0.0f;
out[35] = 0.0f;
int six_i = 0;
for(i=0;i<3;i++)
{
// 12 point IMDCT
// Begin 12 point IDCT
// Input aliasing for 12 pt IDCT
in[15+i] += in[12+i]; in[12+i] += in[9+i]; in[9+i] += in[6+i];
in[6+i] += in[3+i]; in[3+i] += in[0+i];
// Input aliasing on odd indices (for 6 point IDCT)
in[15+i] += in[9+i]; in[9+i] += in[3+i];
// 3 point IDCT on even indices
float pp1, pp2, sum;
pp2 = in[12+i] * 0.500000000f;
pp1 = in[ 6+i] * 0.866025403f;
sum = in[0+i] + pp2;
tmpf_1 = in[0+i] - in[12+i];
tmpf_0 = sum + pp1;
tmpf_2 = sum - pp1;
// End 3 point IDCT on even indices
// 3 point IDCT on odd indices (for 6 point IDCT)
pp2 = in[15+i] * 0.500000000f;
pp1 = in[ 9+i] * 0.866025403f;
sum = in[ 3+i] + pp2;
tmpf_4 = in[3+i] - in[15+i];
tmpf_5 = sum + pp1;
tmpf_3 = sum - pp1;
// End 3 point IDCT on odd indices
// Twiddle factors on odd indices (for 6 point IDCT)
tmpf_3 *= 1.931851653f;
tmpf_4 *= 0.707106781f;
tmpf_5 *= 0.517638090f;
// Output butterflies on 2 3 point IDCT's (for 6 point IDCT)
float save = tmpf_0;
tmpf_0 += tmpf_5;
tmpf_5 = save - tmpf_5;
save = tmpf_1;
tmpf_1 += tmpf_4;
tmpf_4 = save - tmpf_4;
save = tmpf_2;
tmpf_2 += tmpf_3;
tmpf_3 = save - tmpf_3;
// End 6 point IDCT
// Twiddle factors on indices (for 12 point IDCT)
tmpf_0 *= 0.504314480f;
tmpf_1 *= 0.541196100f;
tmpf_2 *= 0.630236207f;
tmpf_3 *= 0.821339815f;
tmpf_4 *= 1.306562965f;
tmpf_5 *= 3.830648788f;
// End 12 point IDCT
// Shift to 12 point modified IDCT, multiply by window type 2
tmpf_8 = -tmpf_0 * 0.793353340f;
tmpf_9 = -tmpf_0 * 0.608761429f;
tmpf_7 = -tmpf_1 * 0.923879532f;
tmpf_10 = -tmpf_1 * 0.382683432f;
tmpf_6 = -tmpf_2 * 0.991444861f;
tmpf_11 = -tmpf_2 * 0.130526192f;
tmpf_0 = tmpf_3;
tmpf_1 = tmpf_4 * 0.382683432f;
tmpf_2 = tmpf_5 * 0.608761429f;
tmpf_3 = -tmpf_5 * 0.793353340f;
tmpf_4 = -tmpf_4 * 0.923879532f;
tmpf_5 = -tmpf_0 * 0.991444861f;
tmpf_0 *= 0.130526192f;
out[six_i + 6] += tmpf_0;
out[six_i + 7] += tmpf_1;
out[six_i + 8] += tmpf_2;
out[six_i + 9] += tmpf_3;
out[six_i + 10] += tmpf_4;
out[six_i + 11] += tmpf_5;
out[six_i + 12] += tmpf_6;
out[six_i + 13] += tmpf_7;
out[six_i + 14] += tmpf_8;
out[six_i + 15] += tmpf_9;
out[six_i + 16] += tmpf_10;
out[six_i + 17] += tmpf_11;
six_i += 6;
}
}
else
{
// 36 point IDCT
// input aliasing for 36 point IDCT
in[17]+=in[16]; in[16]+=in[15]; in[15]+=in[14]; in[14]+=in[13];
in[13]+=in[12]; in[12]+=in[11]; in[11]+=in[10]; in[10]+=in[9];
in[9] +=in[8]; in[8] +=in[7]; in[7] +=in[6]; in[6] +=in[5];
in[5] +=in[4]; in[4] +=in[3]; in[3] +=in[2]; in[2] +=in[1];
in[1] +=in[0];
// 18 point IDCT for odd indices
// input aliasing for 18 point IDCT
in[17]+=in[15]; in[15]+=in[13]; in[13]+=in[11]; in[11]+=in[9];
in[9] +=in[7]; in[7] +=in[5]; in[5] +=in[3]; in[3] +=in[1];
float tmp0,tmp1,tmp2,tmp3,tmp4,tmp0_,tmp1_,tmp2_,tmp3_;
float tmp0o,tmp1o,tmp2o,tmp3o,tmp4o,tmp0_o,tmp1_o,tmp2_o,tmp3_o;
// Fast 9 Point Inverse Discrete Cosine Transform
//
// By Francois-Raymond Boyer
// mailto:boyerf@iro.umontreal.ca
// http://www.iro.umontreal.ca/~boyerf
//
// The code has been optimized for Intel processors
// (takes a lot of time to convert float to and from iternal FPU representation)
//
// It is a simple "factorization" of the IDCT matrix.
// 9 point IDCT on even indices
// 5 points on odd indices (not realy an IDCT)
float i00 = in[0]+in[0];
float iip12 = i00 + in[12];
tmp0 = iip12 + in[4]*1.8793852415718f + in[8]*1.532088886238f + in[16]*0.34729635533386f;
tmp1 = i00 + in[4] - in[8] - in[12] - in[12] - in[16];
tmp2 = iip12 - in[4]*0.34729635533386f - in[8]*1.8793852415718f + in[16]*1.532088886238f;
tmp3 = iip12 - in[4]*1.532088886238f + in[8]*0.34729635533386f - in[16]*1.8793852415718f;
tmp4 = in[0] - in[4] + in[8] - in[12] + in[16];
// 4 points on even indices
float i66_ = in[6]*1.732050808f; // Sqrt[3]
tmp0_ = in[2]*1.9696155060244f + i66_ + in[10]*1.2855752193731f + in[14]*0.68404028665134f;
tmp1_ = (in[2] - in[10] - in[14])*1.732050808f;
tmp2_ = in[2]*1.2855752193731f - i66_ - in[10]*0.68404028665134f + in[14]*1.9696155060244f;
tmp3_ = in[2]*0.68404028665134f - i66_ + in[10]*1.9696155060244f - in[14]*1.2855752193731f;
// 9 point IDCT on odd indices
// 5 points on odd indices (not realy an IDCT)
float i0 = in[0+1]+in[0+1];
float i0p12 = i0 + in[12+1];
tmp0o = i0p12 + in[4+1]*1.8793852415718f + in[8+1]*1.532088886238f + in[16+1]*0.34729635533386f;
tmp1o = i0 + in[4+1] - in[8+1] - in[12+1] - in[12+1] - in[16+1];
tmp2o = i0p12 - in[4+1]*0.34729635533386f - in[8+1]*1.8793852415718f + in[16+1]*1.532088886238f;
tmp3o = i0p12 - in[4+1]*1.532088886238f + in[8+1]*0.34729635533386f - in[16+1]*1.8793852415718f;
tmp4o = (in[0+1] - in[4+1] + in[8+1] - in[12+1] + in[16+1])*0.707106781f; // Twiddled
// 4 points on even indices
float i6_ = in[6+1]*1.732050808f; // Sqrt[3]
tmp0_o = in[2+1]*1.9696155060244f + i6_ + in[10+1]*1.2855752193731f + in[14+1]*0.68404028665134f;
tmp1_o = (in[2+1] - in[10+1] - in[14+1])*1.732050808f;
tmp2_o = in[2+1]*1.2855752193731f - i6_ - in[10+1]*0.68404028665134f + in[14+1]*1.9696155060244f;
tmp3_o = in[2+1]*0.68404028665134f - i6_ + in[10+1]*1.9696155060244f - in[14+1]*1.2855752193731f;
// Twiddle factors on odd indices
// and
// Butterflies on 9 point IDCT's
// and
// twiddle factors for 36 point IDCT
float e, o;
e = tmp0 + tmp0_; o = (tmp0o + tmp0_o)*0.501909918f; tmpf_0 = e + o; tmpf_17 = e - o;
e = tmp1 + tmp1_; o = (tmp1o + tmp1_o)*0.517638090f; tmpf_1 = e + o; tmpf_16 = e - o;
e = tmp2 + tmp2_; o = (tmp2o + tmp2_o)*0.551688959f; tmpf_2 = e + o; tmpf_15 = e - o;
e = tmp3 + tmp3_; o = (tmp3o + tmp3_o)*0.610387294f; tmpf_3 = e + o; tmpf_14 = e - o;
tmpf_4 = tmp4 + tmp4o; tmpf_13 = tmp4 - tmp4o;
e = tmp3 - tmp3_; o = (tmp3o - tmp3_o)*0.871723397f; tmpf_5 = e + o; tmpf_12 = e - o;
e = tmp2 - tmp2_; o = (tmp2o - tmp2_o)*1.183100792f; tmpf_6 = e + o; tmpf_11 = e - o;
e = tmp1 - tmp1_; o = (tmp1o - tmp1_o)*1.931851653f; tmpf_7 = e + o; tmpf_10 = e - o;
e = tmp0 - tmp0_; o = (tmp0o - tmp0_o)*5.736856623f; tmpf_8 = e + o; tmpf_9 = e - o;
// end 36 point IDCT */
// shift to modified IDCT
win_bt = win[block_type];
out[0] =-tmpf_9 * win_bt[0];
out[1] =-tmpf_10 * win_bt[1];
out[2] =-tmpf_11 * win_bt[2];
out[3] =-tmpf_12 * win_bt[3];
out[4] =-tmpf_13 * win_bt[4];
out[5] =-tmpf_14 * win_bt[5];
out[6] =-tmpf_15 * win_bt[6];
out[7] =-tmpf_16 * win_bt[7];
out[8] =-tmpf_17 * win_bt[8];
out[9] = tmpf_17 * win_bt[9];
out[10]= tmpf_16 * win_bt[10];
out[11]= tmpf_15 * win_bt[11];
out[12]= tmpf_14 * win_bt[12];
out[13]= tmpf_13 * win_bt[13];
out[14]= tmpf_12 * win_bt[14];
out[15]= tmpf_11 * win_bt[15];
out[16]= tmpf_10 * win_bt[16];
out[17]= tmpf_9 * win_bt[17];
out[18]= tmpf_8 * win_bt[18];
out[19]= tmpf_7 * win_bt[19];
out[20]= tmpf_6 * win_bt[20];
out[21]= tmpf_5 * win_bt[21];
out[22]= tmpf_4 * win_bt[22];
out[23]= tmpf_3 * win_bt[23];
out[24]= tmpf_2 * win_bt[24];
out[25]= tmpf_1 * win_bt[25];
out[26]= tmpf_0 * win_bt[26];
out[27]= tmpf_0 * win_bt[27];
out[28]= tmpf_1 * win_bt[28];
out[29]= tmpf_2 * win_bt[29];
out[30]= tmpf_3 * win_bt[30];
out[31]= tmpf_4 * win_bt[31];
out[32]= tmpf_5 * win_bt[32];
out[33]= tmpf_6 * win_bt[33];
out[34]= tmpf_7 * win_bt[34];
out[35]= tmpf_8 * win_bt[35];
}
} | 2 |
@Override
public void setState(IState state) {
if (this.state != null && this.state.equals("Rolling")){
this.state.getStatus();
this.state = state;
}
else
this.state = state;
} | 2 |
public static void duped(int[] array) {
Set<Integer> set = new HashSet<Integer>();
boolean noDuplicates = true;
for (int i = 0; i < array.length; i++)
if (!set.add(array[i])) {
System.out.println("duplicate");
noDuplicates = false;
break;
}
if (noDuplicates)
System.out.println("no duplicates");
} | 3 |
void test1()
{
try
{
Reader in = new StringReader(
"<p><UL><LI> left terms and list operators (leftward)</LI>\n"+
"<LI> left -></LI>\n"+
"<LI> nonassoc ++ --</LI>\n"+
"<LI> right **</LI>\n"+
"<LI> right ! ~ \\ and unary + and -</LI>\n"+
"<LI> left =~ !~ </LI>\n"+
"<LI> left * / % x</LI>\n"+
"<LI> left + - .</LI>\n"+
"<LI> left << >></LI>\n"+
"<LI> nonassoc named unary operators</LI>\n"+
"<LI> nonassoc < > <= >= lt gt le ge</LI>\n"+
"<LI> nonassoc == != <=> eq ne cmp</LI>\n"+
"<LI> left &</LI>\n"+
"<LI> left | ^</LI>\n"+
"<LI> left &&</LI>\n"+
"<LI> left ||</LI>\n"+
"<LI> nonassoc ..</LI>\n"+
"<LI> right ?:</LI>\n"+
"<LI> right = += -= *= etc.</LI>\n"+
"<LI> left , =></LI>\n"+
"<LI> nonassoc list operators (rightward)</LI>\n"+
"<LI> left not</LI>\n"+
"<LI> left and</LI>\n"+
"<LI> left or xor</LI>\n"+
"</UL>\n"+
"<a href=\"/cgi-bin/query?opt&\">"+
""
);
HtmlStreamTokenizer tok = new HtmlStreamTokenizer(in);
HtmlTag tag = new HtmlTag();
while (tok.nextToken() != HtmlStreamTokenizer.TT_EOF)
{
StringBuffer buf = tok.getWhiteSpace();
if (buf.length() > 0)
System.out.print(buf.toString());
if (tok.getTokenType() == HtmlStreamTokenizer.TT_TAG)
{
try
{
tok.parseTag(tok.getStringValue(), tag);
if (tag.getTagType() == HtmlTag.T_UNKNOWN)
throw new HtmlException("unkown tag");
System.out.print(tag.toString());
}
catch (HtmlException e)
{
// invalid tag, spit it out
System.out.print("<" + tok.getStringValue() + ">");
}
}
else
{
buf = tok.getStringValue();
if (buf.length() > 0)
System.out.print(buf.toString());
}
}
// hang out for a while
System.in.read();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
} | 7 |
private Dimension layoutSize(Container target, boolean preferred)
{
synchronized (target.getTreeLock())
{
// Each row must fit with the width allocated to the containter.
// When the container width = 0, the preferred width of the container
// has not yet been calculated so lets ask for the maximum.
int targetWidth = target.getSize().width;
if (targetWidth == 0)
targetWidth = Integer.MAX_VALUE;
int hgap = getHgap();
int vgap = getVgap();
Insets insets = target.getInsets();
int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
int maxWidth = targetWidth - horizontalInsetsAndGap;
// Fit components into the allowed width
Dimension dim = new Dimension(0, 0);
int rowWidth = 0;
int rowHeight = 0;
int nmembers = target.getComponentCount();
for (int i = 0; i < nmembers; i++)
{
Component m = target.getComponent(i);
if (m.isVisible())
{
Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();
// Can't add the component to current row. Start a new row.
if (rowWidth + d.width > maxWidth)
{
addRow(dim, rowWidth, rowHeight);
rowWidth = 0;
rowHeight = 0;
}
// Add a horizontal gap for all components after the first
if (rowWidth != 0)
{
rowWidth += hgap;
}
rowWidth += d.width;
rowHeight = Math.max(rowHeight, d.height);
}
}
addRow(dim, rowWidth, rowHeight);
dim.width += horizontalInsetsAndGap;
dim.height += insets.top + insets.bottom + vgap * 2;
// When using a scroll pane or the DecoratedLookAndFeel we need to
// make sure the preferred size is less than the size of the
// target containter so shrinking the container size works
// correctly. Removing the horizontal gap is an easy way to do this.
Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);
if (scrollPane != null)
{
dim.width -= (hgap + 1);
}
return dim;
}
} | 7 |
public void setStepToVictim(Scanner scanner) {
this.stepToVictim = Input.getPositiveNumber(scanner, "Enter step of Victim");
} | 0 |
@Override
public boolean onCommand(CommandSender sender, Command cmd,
String commandLabel, String[] args) {
if (args.length == 0) {
sender.sendMessage(ChatColor.BLUE
+ "-----------------------------------------------------");
sender.sendMessage(ChatColor.GOLD + "Developed by: "
+ ChatColor.GRAY + "Staartvin");
sender.sendMessage(ChatColor.GOLD + "Version: " + ChatColor.GRAY
+ plugin.getDescription().getVersion());
sender.sendMessage(ChatColor.YELLOW
+ "Type /ac help for a list of commands.");
return true;
} else if (args.length == 1) {
if (args[0].equalsIgnoreCase("reload")) {
if (!hasPermission("armorcontrol.reload", sender))
return true;
plugin.getConfigHandler().getFile().reloadConfig();
plugin.reloadConfig();
plugin.getConfigHandler().loadFiles();
plugin.getResManager().loadRestrictions();
sender.sendMessage(ChatColor.GREEN
+ "Armor Control has been successfully reloaded!");
return true;
} else if (args[0].equalsIgnoreCase("help")) {
sender.sendMessage(ChatColor.BLUE + "---------------["
+ ChatColor.GOLD + "Armor Control" + ChatColor.BLUE
+ "]--------------------");
sender.sendMessage(ChatColor.GOLD + "/armorcontrol"
+ ChatColor.BLUE
+ " --- Shows info about Armor Control");
sender.sendMessage(ChatColor.GOLD + "/ac help" + ChatColor.BLUE
+ " --- Shows a list of commands");
sender.sendMessage(ChatColor.GOLD + "/ac reload"
+ ChatColor.BLUE + " --- Reloads Armor Control");
return true;
}
} else if (args.length == 4) {
// /ac add <name> <data value> <level>
}
sender.sendMessage(ChatColor.BLUE
+ "-----------------------------------------------------");
sender.sendMessage(ChatColor.RED + "Command not recognised!");
sender.sendMessage(ChatColor.GOLD
+ "Type /ac help to get a list of commands.");
return true;
} | 6 |
public void tick(Map currentMap){
Random random = new Random();
double headM = (random.nextDouble()-.5)/10;
if(headM > .02 || headM < -.02){
heading += headM;
}
vel += (random.nextDouble()-.4)/100;
move(currentMap);
vel=vel%8;
stats.tick(0);
} | 2 |
private HashMap<Integer, Double> getSubFitness(int bottom, int top) {
HashMap<Integer, Double> result = new HashMap<Integer, Double>();
for(int i = 0; bottom < top; i++){
result.put(i, fitness.get(bottom));
bottom++;
}
return result;
} | 1 |
public boolean casesEqual(ContentCase... cases) {
ContentCase c0 = cases[0];
for (ContentCase c : cases) {
if (c.isEqual(c0)) {
c0 = c;
} else
return false;
}
return true;
} | 2 |
@Test
public void throwInvalidBudgetTypeExceptionWhenBudgetTypeIsNotEqualToAnnualOrMonthlyBudget() throws Exception {
try {
budgetFactory.requestBudgetByType("TEST");
fail("Budget Type is not valid.");
} catch (InvalidBudgetTypeException e) {
assertEquals("Invalid Budget Type.", e.getMessage());
}
} | 1 |
private ItemStack[] importEnderchest(CompoundTag tag)
{
ItemStack[] inv = new ItemStack[27];
for (Tag t : ((ListTag) tag.getValue().get("EnderItems")).getValue())
{
int slot = ((ByteTag) ((CompoundTag) t).getValue().get("Slot")).getValue();
if (slot < 36)
{
inv[slot] = CraftItemStack.asBukkitCopy(net.minecraft.server.v1_7_R1.ItemStack.createStack(((CompoundTag) t).toNBTTag()));
}
}
Enderchest = inv;
return inv;
} | 2 |
public static final int getBossRate(byte village) {
switch (village) {
case 0:
case 1:
case 2:
case 3:
return 10;
case 4:
return 20;
case 5:
return 12;
case 6:
return 20;
default:
return 10;
}
} | 7 |
public ISound createSound(String path) {
if(getExtension(path).equals("wav")) {
return new SoundWAV(path);
}
else if (getExtension(path).equals("mid")){
return new SoundMidi(path);
}
else {
return null;
}
} | 2 |
public int getN() {
return n;
} | 0 |
public static String create(mxICell cell)
{
String result = "";
if (cell != null)
{
mxICell parent = cell.getParent();
while (parent != null)
{
int index = parent.getIndex(cell);
result = index + mxCellPath.PATH_SEPARATOR + result;
cell = parent;
parent = cell.getParent();
}
}
return (result.length() > 1) ? result.substring(0, result.length() - 1)
: "";
} | 3 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RoverPosition that = (RoverPosition) o;
return !(xPosition != null ? !xPosition.equals(that.xPosition) : that.xPosition != null) && !(yPosition != null ? !yPosition.equals(that.yPosition) : that.yPosition != null);
} | 6 |
public Boolean equals(Gaussian that) {
return this.a == that.a && this.b == that.b;
} | 1 |
public void run()
{
try {
Socket socket = new Socket("localhost", 5100);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
DataInputStream in = new DataInputStream(socket.getInputStream());
String cmd = in.readUTF();
String name = cmd.split(":")[1];
System.out.println(cmd);
//
Random r = new Random(System.currentTimeMillis());
//double lat = -7.135855, lon = -34.842932;
float lat = rand(r, -90,90), lon = rand(r, -180,180);
float lat_c = -7.135855f, lon_c = -34.842932f;
float lat_step = (lat-lat_c) / 1000000f;
float lon_step = (lon-lon_c) / 1000000f;
System.out.println(name+": lat_step: "+lat_step+" lon_step: "+lon_step);
while(true)
{
lat_c+=( r.nextInt(2)==0 ? lat_step : 0 );
lon_c+=( r.nextInt(2)==0 ? lon_step : 0 );
System.out.println(name+": lat: "+lat_c+"/"+lat+" lon_c: "+lon_c+"/"+lon);
//
if(Math.abs(lat_c)>=Math.abs(lat) || Math.abs(lon_c)>=Math.abs(lon))
{
lat = rand(r, -90,90);
lon = rand(r, -180,180);
lat_step = (lat-lat_c) / 1000000f;
lon_step = (lon-lon_c) / 1000000f;
System.out.println(name+": lat_step: "+lat_step+" lon_step: "+lon_step);
}
//
out.writeUTF("setLocation:"+lat_c+"#"+lon_c);
Thread.sleep(2000);
}
}catch (IOException e) {
System.out.println("Conexão fechada");
}catch (InterruptedException e) {
// TODO: handle exception
}
} | 7 |
private static boolean isLocalMax(double[] frequencyData, int i) {
if (i - 1 < 0 || i + 1 >= frequencyData.length)
return false;
double left = frequencyData[i - 1];
double mid = frequencyData[i];
double right = frequencyData[i + 1];
if (right < mid && mid > left)
return true;
return false;
} | 4 |
public static Method getMutator(Class<?> declaringClass, String mutatorName, Class<?> argument)
{
Method res = null;
if (declaringClass != null)
{
// check this class
try
{
res = declaringClass.getDeclaredMethod(mutatorName, argument);
}
catch (NoSuchMethodException e)
{
// do nothing, keep iterating up
}
if (res == null)
{
res = getMutator(declaringClass.getSuperclass(), mutatorName, argument);
}
}
return res;
} | 5 |
@Override
public int getID() {
// TODO Auto-generated method stub
return 0;
} | 0 |
public static void closeNew() {
DIALOG.dispose();
DIALOG = null;
} | 0 |
public Point getTileCollision(Sprite sprite,
float newX, float newY)
{
float fromX = Math.min(sprite.getX(), newX);
float fromY = Math.min(sprite.getY(), newY);
float toX = Math.max(sprite.getX(), newX);
float toY = Math.max(sprite.getY(), newY);
// get the tile locations
int fromTileX = TileMapRenderer.pixelsToTiles(fromX);
int fromTileY = TileMapRenderer.pixelsToTiles(fromY);
int toTileX = TileMapRenderer.pixelsToTiles(
toX + sprite.getWidth() - 1);
int toTileY = TileMapRenderer.pixelsToTiles(
toY + sprite.getHeight() - 1);
// check each tile for a collision
for (int x=fromTileX; x<=toTileX; x++) {
for (int y=fromTileY; y<=toTileY; y++) {
if (x < 0 || x >= map.getWidth() ||
map.getTile(x, y) != null)
{
// collision found, return the tile
pointCache.setLocation(x, y);
return pointCache;
}
}
}
// no collision found
return null;
} | 5 |
public static long addAddress(Address address, long sessionID) throws SessionException {
if (sessionID <= NO_SESSION_ID) {
throw new SessionException("A valid session ID is required to add an address",
SessionException.SESSION_ID_REQUIRED);
}
Contact contact = (Contact) editContacts.get(new Long(sessionID));
if (contact == null) {
throw new SessionException("You must select a contact before adding an address",
SessionException.CONTACT_SELECT_REQUIRED);
}
if (addresses.indexOf(address) == -1) {
addresses.add(address);
}
contact.addAddress(address);
return sessionID;
} | 3 |
public static AsciiImage getHistogram(AsciiImage img) {
HashMap<Character,Integer> freqMap = new HashMap<Character, Integer>();
String oldCharset = img.getCharset();
String newCharset;
newCharset = oldCharset;
for(int i = 0; i<=9; i++) {
if (oldCharset.indexOf(i + '0') < 0)
newCharset = i + newCharset;
}
if(oldCharset.indexOf('.') < 0)
newCharset = newCharset + '.';
if(oldCharset.indexOf('#') < 0)
newCharset = '#' + newCharset;
int width = 3+oldCharset.length();
AsciiImage histo = new AsciiImage(width, 16, newCharset);
List<Integer> heights = new ArrayList<Integer>();
int max = 0;
Character mostFrequent = oldCharset.charAt(0);
//find the most frequent character
for(Character c:oldCharset.toCharArray()) {
int count = img.getPointList(c).size();
if(count > max) {
max = count;
mostFrequent = c;
}
freqMap.put(c,count);
}
for(Character c:oldCharset.toCharArray()) {
heights.add(getHeight(freqMap.get(c), freqMap.get(mostFrequent)));
}
//build the strings that make up the scale
List<String> scaleStrings = buildScale(freqMap.get(mostFrequent), img.getHeight()*img.getWidth());
String image = "";
//pad the strings to the width of the image and concatenate them to one image
for (String scaleString : scaleStrings) {
String s = pad(scaleString, width);
image += s + "\n";
}
Operation o = new LoadOperation(image);
try {
//fill the histogram with the scale
histo = o.execute(histo);
} catch (OperationException e) {
e.printStackTrace();
}
insertBars(histo, heights);
insertCharset(histo, oldCharset);
//flip the histogram, because it is upside down the way we created it now
return flip(histo);
} | 9 |
public SimpleEntry<URLConnection, String> GET(String url) throws IOException {
int redirects = 0;
SimpleEntry<URLConnection, String> r;
do {
r = cookies(LLHttpClient.GET(proxy(), url, connectTimeOut, readTimeOut, headers()));
url = check(r.getKey());
redirects++;
} while (follow && url != null && redirects < 5);
if (follow && redirects >= 5 && r != null && r.getKey() instanceof HttpURLConnection) {
if (((HttpURLConnection) r.getKey()).getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException(
"Detected recursive redirecting: " + url); }
}
return r;
} | 8 |
public MyRecord search(String name){
Node node=root;
MyRecord result=null;
//when node isn't leaf, find the record in the node, or find the right next level node to search
while(!node.isLeaf()){
int flag=0;
for(int i=0;i<node.getKeys().size();i++){
if(node.getKeys().get(i).getName().compareTo(name)==0){
result=node.getKeys().get(i);
return result;
}
else if(node.getKeys().get(i).getName().compareTo(name)>0){
node=node.getChildren().get(i);
flag=1;
break;
}
}
if(flag==0){node=node.getChildren().get(node.getChildren().size()-1);}
}
//when node is leaf
for(int i=0;i<node.getKeys().size();i++){
if(node.getKeys().get(i).getName().compareTo(name)==0){
result=node.getKeys().get(i);
return result;
}
}
return result;
} | 7 |
public ArrayList<Location> getValidAdjacentLocations(Location loc)
{
ArrayList<Location> locs = new ArrayList<Location>();
int d = Location.NORTH;
for (int i = 0; i < Location.FULL_CIRCLE / Location.HALF_RIGHT; i++)
{
Location neighborLoc = loc.getAdjacentLocation(d);
if (isValid(neighborLoc))
locs.add(neighborLoc);
d = d + Location.HALF_RIGHT;
}
return locs;
} | 2 |
@Override
public void mouseClicked(MouseEvent arg0) {
//System.out.println(arg0.getSource().toString());
if (status == VideoStatus.PLAYING){
pause();
}
int videoIndex = ((MyPanel)arg0.getSource()).videoIndex;
if(videoIndex != currentVideo){
currentVideo = videoIndex;
audio = new File(audiofilenames[currentVideo]);
}
int temp = ((MyPanel)arg0.getSource()).imgFrame;
videoFrame = temp;
imgPanel.img = vdo[currentVideo][videoFrame];
imgPanel.repaint();
try {
waveStream = new FileInputStream(audio);
} catch (FileNotFoundException e) {
System.out.println(e);
}
audioInputStream = null;
try {
InputStream bufferedIn = new BufferedInputStream(waveStream);
audioInputStream = AudioSystem.getAudioInputStream(waveStream);
//audioInputStream.skip(temp * buffersize);
} catch (UnsupportedAudioFileException e1) {
System.out.println(e1);
//throw new PlayWaveException(e1);
} catch (IOException e1) {
System.out.println(e1);
e1.printStackTrace();
//throw new PlayWaveException(e1);
}
// Obtain the information about the AudioInputStream
audioFormat = audioInputStream.getFormat();
info = new Info(SourceDataLine.class, audioFormat);
// opens the audio channel
dataLine = null;
try {
//System.out.println("img frame temp: " + temp);
long offset = temp * 30 * (long) audioFormat.getFrameRate() * (long)audioFormat.getFrameSize() / (long)numFrames;
System.out.println("skipping " + (long)offset + " bytes");
audioInputStream.skip(temp * 30 * (long) audioFormat.getFrameRate() * (long)audioFormat.getFrameSize() / (long)numFrames);
dataLine = (SourceDataLine) AudioSystem.getLine(info);
dataLine.open(audioFormat, buffersize);
} catch (LineUnavailableException e1) {
System.out.println(e1);
//throw new PlayWaveException(e1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 7 |
public boolean isObstacle()
{
return lookid == 1 || lookid == 3;
} | 1 |
public void renderTileEntitySignAt(TileEntitySign par1TileEntitySign, double par2, double par4, double par6, float par8)
{
Block var9 = par1TileEntitySign.getBlockType();
GL11.glPushMatrix();
float var10 = 0.6666667F;
float var12;
if (var9 == Block.signPost)
{
GL11.glTranslatef((float)par2 + 0.5F, (float)par4 + 0.75F * var10, (float)par6 + 0.5F);
float var11 = (float)(par1TileEntitySign.getBlockMetadata() * 360) / 16.0F;
GL11.glRotatef(-var11, 0.0F, 1.0F, 0.0F);
this.modelSign.signStick.showModel = true;
}
else
{
int var16 = par1TileEntitySign.getBlockMetadata();
var12 = 0.0F;
if (var16 == 2)
{
var12 = 180.0F;
}
if (var16 == 4)
{
var12 = 90.0F;
}
if (var16 == 5)
{
var12 = -90.0F;
}
GL11.glTranslatef((float)par2 + 0.5F, (float)par4 + 0.75F * var10, (float)par6 + 0.5F);
GL11.glRotatef(-var12, 0.0F, 1.0F, 0.0F);
GL11.glTranslatef(0.0F, -0.3125F, -0.4375F);
this.modelSign.signStick.showModel = false;
}
this.bindTextureByName("/item/sign.png");
GL11.glPushMatrix();
GL11.glScalef(var10, -var10, -var10);
this.modelSign.renderSign();
GL11.glPopMatrix();
FontRenderer var17 = this.getFontRenderer();
var12 = 0.016666668F * var10;
GL11.glTranslatef(0.0F, 0.5F * var10, 0.07F * var10);
GL11.glScalef(var12, -var12, var12);
GL11.glNormal3f(0.0F, 0.0F, -1.0F * var12);
GL11.glDepthMask(false);
byte var13 = 0;
for (int var14 = 0; var14 < par1TileEntitySign.signText.length; ++var14)
{
String var15 = par1TileEntitySign.signText[var14];
if (var14 == par1TileEntitySign.lineBeingEdited)
{
var15 = "> " + var15 + " <";
var17.drawString(var15, -var17.getStringWidth(var15) / 2, var14 * 10 - par1TileEntitySign.signText.length * 5, var13);
}
else
{
var17.drawString(var15, -var17.getStringWidth(var15) / 2, var14 * 10 - par1TileEntitySign.signText.length * 5, var13);
}
}
GL11.glDepthMask(true);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glPopMatrix();
} | 6 |
@Override
public void setAgility(int agi) {
if (agi >= 99) {// agility will be a % chance and must be < 100
this.agility = 99;
} else {
this.agility = agi;
}
} | 1 |
@Override
public Scanner scan(Lexer lexer) {
boolean terminated = false;
loop:
while (lexer.hasNext()) {
final char ch = lexer.next();
switch (ch) {
case '\\':
if (lexer.hasNext()) {
final char chn = lexer.next();
if (chn != '\n') {
break;
}
}
case '\n':
break loop;
case '"':
terminated = true;
break loop;
}
}
if (terminated) {
lexer.emit(TokenType.STRING);
return new InsideActionScanner();
} else {
return lexer.errorf("unterminated quoted string");
}
} | 7 |
public int[][] paintImages(int[][] currentBlockArray, int xMin, int xMax, int zMin, int zMax) {
BufferedImage[] images = getPaintImages("Theme1");
int h = images[0].getHeight();
int w = images[0].getWidth();
int i = 0;
level = 0;
wipZMin = zMin;
wipHeight = h;
String[] messages = new String[] {"Weem-atizing Elements", "Calculating the 'Epic'", "Removing Mukshapumpa", "Equipping Melvin", "Thanking Testers", "Sneaking up behind you...", "Injecting Bacon" };
boolean closeToGround = false;
Game.loadingText = "Making Things Interesting...";
for(int z = zMin; z <= zMax-h; z += h) {
if(messages.length > level) {
Game.loadingText = messages[level];
}
for(int x = xMin; x <= xMax-w; x += w) {
closeToGround = closeToGround(x, z, w, h);
//System.out.println("closeToGround "+closeToGround);
if(!closeToGround) {
i = getPaintImageIndex(currentBlockArray, images, x, z, xMin, xMax, (z == zMin));
if(i > -1) {
currentBlockArray = paintImage(currentBlockArray, images[i], x, z);
}
}
}
//System.out.println("level");
lastLevel = (ArrayList)currentLevel.clone();
currentLevel.clear();
level++;
//new level
}
currentBlockArray = spawnCaves(currentBlockArray, 5, xMin, xMax, zMin, zMax);
noExitImages.clear();
return currentBlockArray;
} | 5 |
protected boolean connect(){
LCD.clear();
LCD.drawString("Bluetooth:", 0, 0);
LCD.drawString("Connect -> Enter", 0, 1);
LCD.drawString("Don't -> Esc", 0, 2);
LCD.refresh();
while(true){
if ( Button.ENTER.isDown() ){
while(Button.ENTER.isDown()){try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}} //wait for button release
LCD.clear();
LCD.drawString("Waiting for", 0, 0);
LCD.drawString("Bluetooth...", 0, 1);
LCD.refresh();
connection = Bluetooth.waitForConnection(); // this method is very patient.
// Get I/O streams from BT connection
dataIn = connection.openDataInputStream();
dataOut = connection.openDataOutputStream();
if(dataIn == null || dataOut == null)
{
// Connection failed
LCD.clear();
LCD.drawString("Connection failed", 0, 0);
LCD.refresh();
Sound.beepSequence();
useHMI = false;
return false;
}
else
{
// Connection successful
LCD.clear();
LCD.drawString("Connected",0,0);
LCD.refresh();
Sound.beepSequenceUp();
useHMI = true;
return true;
}
}else if ( Button.ESCAPE.isDown() ){
while(Button.ESCAPE.isDown()){try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}} //wait for button release
useHMI = false;
return false;
}
}
} | 9 |
public List<SemestreDTO> getAllSemestres() {
List<SemestreDTO> semestres = new ArrayList<SemestreDTO>();
String sql = "select distinct(semestre) as semestre from calendario order by semestre desc";
PreparedStatement pst = null;
ResultSet rs = null;
Connection con =null;
try {
con = EscolarConnectionFactory
.getInstance().getConnection();
pst = con.prepareStatement(sql);
rs=pst.executeQuery();
SemestreDTO ningunSemestre = new SemestreDTO();
ningunSemestre.setSemestre("-------");
semestres.add(ningunSemestre);
while(rs.next()){
SemestreDTO semestre = new SemestreDTO();
semestre.setSemestre(rs.getString("semestre"));
semestres.add(semestre);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if (con != null)
con.close();
if (pst != null)
pst.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return semestres;
} | 6 |
FiguresChain(Map<String, Integer> figureQuantityMap) {
if (Objects.isNull(figureQuantityMap)) {
throw new IllegalStateException("figureQuantity map is null, however should not be");
}
this.figureQuantityMap = figureQuantityMap;
} | 1 |
@Override
public void createPartControl(Composite composite) {
composite.setLayout(new GridLayout(11, false));
Label label = new Label(composite, SWT.NONE);
label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
label.setText("文件");
fileText = new Text(composite, SWT.BORDER | SWT.READ_ONLY);
fileText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Button button_1 = new Button(composite, SWT.NONE);
button_1.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
FileDialog fileDialog = new FileDialog(getSite().getShell(), SWT.OPEN);
String file = fileDialog.open();
if (file != null)
fileText.setText(file);
}
});
button_1.setText("文件");
final Button button = new Button(composite, SWT.NONE);
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final String filePath = fileText.getText();
if (filePath == null || filePath.equals("")) {
styledText.append("请选择文件添加\n");
return;
} else {
service.addFile(filePath);
styledText.append("添加文件" + filePath + "成功\n");
fileText.setText("");
}
}
});
button.setText("添加");
Button button_3 = new Button(composite, SWT.NONE);
button_3.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
service.stop();
styledText.append("任务已清理\n");
}
});
button_3.setText("清空");
startBut = new Button(composite, SWT.NONE);
startBut.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final String text = "。";
if (text == null || text.equals("")) {
styledText.append("发送内容不能为空\n");
return;
}
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
styledText.setText("");
}
});
service.start(styledText, text, startBut);
} catch (IOException e) {
logger.error("", e);
}
}
});
t.start();
startBut.setEnabled(false);
}
});
startBut.setText("开始");
Button button_2 = new Button(composite, SWT.NONE);
button_2.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
service.stop();
startBut.setEnabled(true);
styledText.append("任务停止成功\n");
}
});
button_2.setText("停止");
new Label(composite, SWT.NONE);
new Label(composite, SWT.NONE);
new Label(composite, SWT.NONE);
new Label(composite, SWT.NONE);
Label label_2 = new Label(composite, SWT.NONE);
label_2.setText("输出");
new Label(composite, SWT.NONE);
new Label(composite, SWT.NONE);
new Label(composite, SWT.NONE);
new Label(composite, SWT.NONE);
new Label(composite, SWT.NONE);
new Label(composite, SWT.NONE);
new Label(composite, SWT.NONE);
new Label(composite, SWT.NONE);
new Label(composite, SWT.NONE);
new Label(composite, SWT.NONE);
styledText = new StyledText(composite, SWT.BORDER | SWT.V_SCROLL);
styledText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 11, 1));
Composite composite_1 = new Composite(composite, SWT.NONE);
composite_1.setLayout(new GridLayout(2, false));
composite_1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 11, 1));
Button button_4 = new Button(composite_1, SWT.NONE);
button_4.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
FileDialog fileDialog = new FileDialog(getSite().getShell(), SWT.SAVE);
String file = fileDialog.open();
try {
FileUtils.writePhones(service.getSuccess(), file);
} catch (IOException e1) {
logger.error("", e1);
}
}
});
button_4.setText("导出成功");
Button btnshibai = new Button(composite_1, SWT.NONE);
btnshibai.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
FileDialog fileDialog = new FileDialog(getSite().getShell(), SWT.SAVE);
String file = fileDialog.open();
try {
FileUtils.writePhones(service.getFailed(), file);
} catch (IOException e1) {
logger.error("", e1);
}
}
});
btnshibai.setText("导出失败");
// TODO Auto-generated method stub
} | 8 |
@Override
protected void _serialize(TagNode tagNode, Writer writer) throws IOException {
serializeOpenTag(tagNode, writer, false);
List<? extends BaseToken> tagChildren = tagNode.getAllChildren();
if ( !isMinimizedTagSyntax(tagNode) ) {
Iterator<? extends BaseToken> childrenIt = tagChildren.iterator();
while ( childrenIt.hasNext() ) {
Object item = childrenIt.next();
if (item != null) {
if (item instanceof CData) {
serializeCData((CData)item, tagNode, writer);
} else if ( item instanceof ContentNode ) {
serializeContentToken((ContentNode)item, tagNode, writer);
} else {
((BaseToken)item).serialize(this, writer);
}
}
}
serializeEndTag(tagNode, writer, false);
}
} | 7 |
public void run() {
System.out.println("run method running.");
while (true) {
String userCommand = this.readInputStream();
System.out.println("user command: " + userCommand);
String[] command = commandParser(userCommand.toLowerCase().trim());
if (!command[0].equals("close")) {
if (currentCommand.equals("")) {
switch (userCommand) {
case "close":
this.closeConnection();
break;
case "checkportfolio":
currentCommand = "checkportfolio";
this.checkportfolio();
break;
case "buy":
currentCommand = "buy";
break;
case "sell":
currentCommand = "sell";
break;
case "follow":
currentCommand = "follow";
break;
default:
this.unknowCommand(userCommand);
break;
}
} else {
this.unknowCommand(userCommand);
}
} else {
this.closeConnection();
break;
}
}
} | 8 |
@Override
public MessageResponse logout() throws IOException {
if(currentUser != null) {
currentUser.setOnline(false);
currentUser.getSubscriptions().clear();
currentUser = null;
return new MessageResponse("Successfully logged out.");
}
return new MessageResponse("You have to login first to perform this action!");
} | 1 |
private void buildBoard() throws GOLException, IOException {
initializeBoard();
int row = 0;
Scanner scanner = new Scanner(filePath);
while (scanner.hasNextLine()) {
fillBoardWithLine(scanner.nextLine(), row);
row++;
}
scanner.close();
} | 1 |
@Test
public void shouldThrowErrorWhenFileIsNotSelected() {
//when
try {
FileParser fileParser = new FileParser(null);
fileParser.parse();
} catch (GOLException e) {
//then
String msg = "Bitte Datei auswählen.";
assertEquals(msg, e.getMessage());
}
} | 1 |
private Token getNextToken() {
Token token = tokenizer.getToken();
if ( token == null ) {
return null;
}
else if ( token.isError() ) {
throwException( "Input contains syntax error" );
}
return token;
} | 2 |
private void setPolygon(boolean getPoly, Envelope env) throws JsonParseException, JsonMappingException, IOException{
@SuppressWarnings("unchecked")
//get json file paths for given extent
List<String> paths = jsonTree.query(env);
//reset/create new polygons array or new tree
if(getPoly)polygons = new Polygon[paths.size()];
else polygonTree = new STRtree();
//temporary path+polygon
String jsonPathTemp;
Polygon polygonTemp;
//get all polygons
for(int i=0;i<paths.size();i++){
jsonPathTemp = GeoJsonReader.readFile(paths.get(i));
polygonTemp = PolygonWorker.json2polygons(jsonPathTemp)[0];
//add polygon to array or tree
if(getPoly)polygons[i]=polygonTemp;
else polygonTree.insert(polygonTemp.getEnvelopeInternal(), polygonTemp);
}
} | 3 |
public void addLogger(final Logger logger) {
if (logger == null) {
throw new NullPointerException();
}
loggers.add(logger);
} | 1 |
private Link maybeSwitch(Link link){
Link secondLink = linkQueue.peek();
if(link != null && secondLink != null){
if(
link instanceof BackLink &&
link.getRank() == secondLink.getRank()&&
!(secondLink instanceof ShortcutLink)){
linkQueue.poll();
linkQueue.add(link);
link = secondLink;
}
else if( link.getRank() == secondLink.getRank() && secondLink instanceof MatchLink){
linkQueue.poll();
linkQueue.add(link);
link = secondLink;
}
}
return link;
} | 7 |
@Override
public void removeUpdate(DocumentEvent e) {
if(progress.isVisible()) {
progress.setVisible(false);
} else if(correct.isVisible()) {
correct.setVisible(false);
} else if(error.isVisible()) {
error.setVisible(false);
}
} | 3 |
private int alphabetaScore(GameState state, Color faction)
{
state = state.getCounter().score(state, false);
int playerScore = 0;
Color maxPlayer = null;
int maxScore = Integer.MIN_VALUE;
for(Player p : state.getPlayerList())
{
//determine the player's score
if(p.getFaction().equals(faction))
{
playerScore = p.getScore();
}
//determine the best score
if(p.getScore() >= maxScore)
{
maxScore = p.getScore();
if(!p.getFaction().equals(faction))
{
maxPlayer = p.getFaction();
}
}
}
//Okay, now we need to figure out if the player had the best score or not
if(maxPlayer != null)
{
//we need to find the player in 2nd place
maxScore = Integer.MIN_VALUE;
for(Player p : state.getPlayerList())
{
if(!p.getFaction().equals(faction))
{
if(p.getScore() >= maxScore)
{
maxScore = p.getScore();
}
}
}
// System.out.println("score: " + (playerScore - maxScore));
return playerScore - maxScore; //should always be a positive value
}
else
{
// System.out.println("score: " + (playerScore - maxScore));
return playerScore - maxScore; //should always be a negative value or 0
}
} | 8 |
static void split(BufferedReader br, String fileName, int count) {
int i = 0;
String line = null;
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(fileName);
bw = new BufferedWriter(fw);
while ((line = br.readLine()) != null && i < count) {
line = line.substring(1, line.length() - 1);
if (isNum(line)) {
bw.write(line + "\n");
i ++;
} else {
System.err.printf("fileName:%s, count:%d read string[%s] error, not num \n", fileName, count, line);
}
}
} catch (Exception e) {
System.err.printf("fileName:%s, count:%d error \n", fileName, count);
e.printStackTrace();
} finally {
closeIO(bw);
closeIO(fw);
}
} | 4 |
public boolean isWhiteWinner(){
boolean res = false;
if(this.blackPieces == 0){
res = true;
}
return res;
} | 1 |
private boolean isValidInput(final String s) {
return s.matches("[0-9]{1,}");
} | 0 |
public String encryption(String string, boolean decrypt,
SecurityManager securityManager) {
// get the security manager instance
if (securityManager != null && reference != null) {
// get the key
byte[] key = securityManager.getDecryptionKey();
// convert string to bytes.
byte[] textBytes =
Utils.convertByteCharSequenceToByteArray(string);
// Decrypt String
if (decrypt){
textBytes = securityManager.decrypt(reference,
key,
textBytes);
}else{
textBytes = securityManager.encrypt(reference,
key,
textBytes);
}
// convert back to a string
return Utils.convertByteArrayToByteString(textBytes);
}
return string;
} | 3 |
protected double [] makeDistribution(Instances neighbours, double[] distances)
throws Exception {
double total = 0, weight;
double [] distribution = new double [m_NumClasses];
// Set up a correction to the estimator
if (m_ClassType == Attribute.NOMINAL) {
for(int i = 0; i < m_NumClasses; i++) {
distribution[i] = 1.0 / Math.max(1,m_Train.numInstances());
}
total = (double)m_NumClasses / Math.max(1,m_Train.numInstances());
}
for(int i=0; i < neighbours.numInstances(); i++) {
// Collect class counts
Instance current = neighbours.instance(i);
distances[i] = distances[i]*distances[i];
distances[i] = Math.sqrt(distances[i]/m_NumAttributesUsed);
switch (m_DistanceWeighting) {
case WEIGHT_INVERSE:
weight = 1.0 / (distances[i] + 0.001); // to avoid div by zero
break;
case WEIGHT_SIMILARITY:
weight = 1.0 - distances[i];
break;
default: // WEIGHT_NONE:
weight = 1.0;
break;
}
weight *= current.weight();
try {
switch (m_ClassType) {
case Attribute.NOMINAL:
distribution[(int)current.classValue()] += weight;
break;
case Attribute.NUMERIC:
distribution[0] += current.classValue() * weight;
break;
}
} catch (Exception ex) {
throw new Error("Data has no class attribute!");
}
total += weight;
}
// Normalise distribution
if (total > 0) {
Utils.normalize(distribution, total);
}
return distribution;
} | 9 |
public Tree(HuntField field) {
this.field = field;
this.type = 'T';
while (true) {
myPosition = field.randomPositionGenerator();
if (myPosition == null) {
field.setItem(this, myPosition);
break;
}
}
} | 2 |
public List<Message> page(final int index) {
if (this.pageSize < 1) {
if (index != 0) throw new IllegalArgumentException("page index not available: " + index);
return this.contents;
}
final int last = ((index + 1) * this.pageSize) - 1;
return this.contents.subList(index * this.pageSize, ( last <= this.contents.size() ? last : this.contents.size() ));
} | 3 |
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final Location other = (Location) obj;
if (this.level != other.level && (this.level == null || !this.level.equals(other.level))) return false;
if (this.x != other.x) return false;
if (this.y != other.y) return false;
if (!this.direction.equals(other.direction)) return false;
return true;
} | 8 |
@Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (args.length == 1 && args[0].equalsIgnoreCase("help")) {
showHelp(sender);
return true;
}
if (args.length == 1 && args[0].equalsIgnoreCase("reload")) {
plugin.reload();
sender.sendMessage("Configuration reloaded from disk.");
return true;
}
return false;
} | 4 |
public void interpretaComando(CoreComando comando, ServidorCliente cliente) {
switch (comando) {
case DIREITA:
cliente.getPosicao().setX(cliente.getPosicao().getX() + 5);
//setStateImg("");
break;
case ESQUERDA:
cliente.getPosicao().setX(cliente.getPosicao().getX() - 5);
//setStateImg("");
break;
case PULA:
// for (int i = 0; i < 5; i++) {
cliente.getPosicao().setY(cliente.getPosicao().getY() - 40);
/* try {
Thread.sleep(25);
} catch (Exception e) {
e.printStackTrace();
}
//setStateImg("");
} */
default:
break;
}
} | 3 |
private boolean jj_3R_91() {
if (jj_3R_95()) return true;
return false;
} | 1 |
private void btn_Guardar_UsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_Guardar_UsuarioActionPerformed
try {
if (txtID_Usuario.getText().compareTo("") != 0 && txtpass_usuario.getPassword().toString().compareTo("") != 0
&& txtdni_usuario.getText().compareTo("") != 0 && txtnombres_usuario.getText().compareTo("") != 0
&& txtapellidos_usuario.getText().compareTo("") != 0 && txtTeleCelular_Usuario.getText().compareTo("") != 0
&& txtFechaNacimiento_Usuario.getDate() != null) {
char passArray[] = txtpass_usuario.getPassword();
String pass = new String(passArray);
if (new BLUsuario().Registrar(txtID_Usuario.getText(),
pass,
txtdni_usuario.getText(),
txtnombres_usuario.getText(),
txtapellidos_usuario.getText(),
new java.sql.Date(txtFechaNacimiento_Usuario.getDate().getTime()),
txtTeleCelular_Usuario.getText(),
((Cargo) cboCargo_Usuario.getSelectedItem()).getInt_id(),
txtDireccion_Usuario.getText(),
txtEmail_Usuario.getText())) {
limpiarFomulario_Usuario();
limpiarTabla(jtLista_Usuario);
gettabla_usuario_byfiltro("", 0);
JOptionPane.showMessageDialog(null, "Registro Exitoso", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Registro Fallido", "Mensaje", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, " No se admiten campos vacios ", "Mensaje", 1);
}
} catch (Exception e) {
System.out.println("Error al registrar comite" + e.getMessage());
}
} | 9 |
@Test
@Points(value = 5)
public void checkThatGridPackingConstructorIsDoingTheRightThingInternally()
{
// ************************************************************************************
// Note: This isn't a standard test case to run in industry, but is a great test case
// for students who will encounter this problem for the first time
// ************************************************************************************
TEST_GOAL_MESSAGE = "Check that GridPackingImpl_Student constructor is doing the right thing internally";
final int ROW_COUNT = 7;
final int COLUMN_COUNT = 3;
List<CatCage> catCageList = new ArrayList<CatCage>();
for (int i = 0; i < ROW_COUNT * COLUMN_COUNT; i++)
{
CatCage catCage = new CatCageImpl_Nunez("" + i, FEMALE_CARACAL, MALE_OCELOT, null, MALE_TIGER);
catCageList.add(catCage);
}
GridPacking<CatCage> gridPacking = new GridPackingImpl_Nunez<CatCage>(ROW_COUNT, COLUMN_COUNT, catCageList);
int i = 0;
for (int j = 0; j < ROW_COUNT; j++)
{
for (int k = 0; k < COLUMN_COUNT; k++)
{
CatCage catCage = gridPacking.getElementAt(j, k);
String identifier = catCage.getIdentifier();
assertEquals(String.format("idenifier should be %s, not %s", i, identifier), "" + i, identifier);
i++;
}
}
// ************************************************************************************
// THE REAL TEST IS COMING UP
// ************************************************************************************
int indexOfLastElement = catCageList.size() - 1;
catCageList.remove(indexOfLastElement);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Changing catCageList here should not
// affect the gridPacking. If you are
// failing this test after getting this
// far, figure out how catCageList and
// gridPacking are still "connected" at
// this point.
// ************************************************************************************
i = 0;
for (int j = 0; j < ROW_COUNT; j++)
{
for (int k = 0; k < COLUMN_COUNT; k++)
{
CatCage catCage = gridPacking.getElementAt(j, k);
String identifier = catCage.getIdentifier();
assertEquals(String.format("idenifier should be %s, not %s", i, identifier), "" + i, identifier);
i++;
}
}
} | 5 |
private void addWordRec(CharNode parent, String word, int charAt, int occur) {
CharNode child = null;
char data = word.charAt(charAt);
if (parent.children == null) {
parent.children = new ArrayList<>();
} else {
for (int i = 0; i < parent.children.size(); i++) {
CharNode node = parent.children.get(i);
if (node.data == data) {
child = node;
break;
}
}
}
if (child == null) {
child = new CharNode();
parent.children.add(child);
}
child.data = data;
if (child.freq == 0) child.freq = occur;
if (word.length() > charAt + 1) {
addWordRec(child, word, charAt + 1, occur);
} else {
child.terminal = true;
child.freq = occur;
}
} | 6 |
private void convertKosarak() throws IOException {
String thisLine; // variable to read a line
BufferedReader myInput = null;
try {
// Objects to read the file
FileInputStream fin = new FileInputStream(new File(input));
myInput = new BufferedReader(new InputStreamReader(fin));
int count = 0; // to count the number of line
// we read the file line by line until the end of the file
while ((thisLine = myInput.readLine()) != null) {
// we split the line according to spaces
String[] split = thisLine.split(" ");
// for each string on this line
for (String value : split) {
// we convert to integer and write it to file (it is an item)
Integer item = Integer.parseInt(value);
writer.write(item + " -1 "); // write an itemset separator
}
writer.write("-2"); // write end of line
count++;// increase the number of sequences
// if we have read enough sequences, we stop.
if(count == lineCount){
break;
}
writer.newLine(); // create new line
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (myInput != null) {
myInput.close();
}
}
} | 5 |
private void authenticationExchange() throws IOException {
// _console.writeline("authenticationExchange");
int scheme = readCard32();
if (scheme == 0) {
String reason = readString();
throw new VNCException("connection failed: " + reason);
} else if (scheme == 1) {
// no authentication needed
} else if (scheme == 2) {
try {
byte[] keyBytes = new byte[8];
for (int i = 0; (i < 8) && (i < password.length); ++i) {
keyBytes[i] = reverse((byte) password[i]);
}
Arrays.fill(password, '\0');
DESKeySpec keySpec = new DESKeySpec(keyBytes);
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
Arrays.fill(keyBytes, (byte) 0);
byte[] challenge = new byte[16];
readFully(challenge, 0, 16);
byte[] response = cipher.doFinal(challenge);
synchronized (out_) {
out_.write(response, 0, 16);
out_.flush();
}
} catch (Exception e) {
throw new VNCException("authentication: DES error");
}
int status = readCard32();
if (status == 0) {
// ok
} else if (status == 1) {
throw new VNCException("authentication failed");
} else if (status == 2) {
throw new VNCException("too many authentication failures");
}
} else {
throw new VNCException("unexpected authentication scheme: "
+ scheme);
}
} | 9 |
private void jButtonCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCheckActionPerformed
this.jTabbedPane.setSelectedComponent(this.jPanelTabQueue);
for (int i = 0; i < this.model.getRowCount(); i++) {
if (this.model.isSelected(i)) {
SignatureFileView sfv = new SignatureFileView(this.user.getFiles().get(i));
this.jPanelQueue.add(sfv);
SignatureChecker checker = new SignatureChecker();
checker.setSignatureListener(sfv.new CheckerListener(sfv));
checker.execute(this.user.getFiles().get(i), this.user.getKeys().getPublicKey());
}
}
}//GEN-LAST:event_jButtonCheckActionPerformed | 2 |
public int getLEShortA() { // method438
offset += 2;
int v = ((payload[offset - 1] & 0xff) << 8) + (payload[offset - 2] - 128 & 0xff);
if (v > 32767) {
v -= 0x10000;
}
return v;
} | 1 |
private static int[] stringToIntArray(String str) throws Exception
{
int slength=str.length();
int retval[] = new int[(int) Math.ceil(slength / 4.0)];
for (int i=0; i<retval.length; i++) {
// note little-endian encoding - endianness is irrelevant as long as
// it is the same in longsToStr()
int char0=(i*4<slength)?str.charAt(i*4):0;
int char1=(i*4+1<slength)?str.charAt(i*4+1):0;
int char2=(i*4+2<slength)?str.charAt(i*4+2):0;
int char3=(i*4+3<slength)?str.charAt(i*4+3):0;
retval[i] = char0 + (char1<<8) +
(char2<<16) + (char3<<24);
}
return retval;
} | 5 |
public boolean matchByStateAndSymbol(String state, String symbol, Symbol symbolRef) throws Exception{
if(!this.state.equals(state))
return false;
if(this.symbol != null && !this.symbol.isEmpty())
return this.symbol.equals(symbol);
return matchSymbolbySymbolRef(symbol, symbolRef);
} | 3 |
public Object nextValue() throws JSONException {
char c = this.nextClean();
String string;
switch (c) {
case '"':
case '\'':
return this.nextString(c);
case '{':
this.back();
return new JSONObject(this);
case '[':
this.back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuffer sb = new StringBuffer();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = this.next();
}
this.back();
string = sb.toString().trim();
if ("".equals(string)) {
throw this.syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
} | 7 |
public static void main(String[] args) throws Throwable{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
char[][][] letras=new char[][][]{
{{'A'},".-".toCharArray()},{{'B'},"-...".toCharArray()},{{'C'},"-.-.".toCharArray()},{{'D'},"-..".toCharArray()},
{{'E'},".".toCharArray()},{{'F'},"..-.".toCharArray()},{{'G'},"--.".toCharArray()},{{'H'},"....".toCharArray()},
{{'I'},"..".toCharArray()},{{'J'},".---".toCharArray()},{{'K'},"-.-".toCharArray()},{{'L'},".-..".toCharArray()},
{{'M'},"--".toCharArray()},{{'N'},"-.".toCharArray()},{{'O'},"---".toCharArray()},{{'P'},".--.".toCharArray()},
{{'Q'},"--.-".toCharArray()},{{'R'},".-.".toCharArray()},{{'S'},"...".toCharArray()},{{'T'},"-".toCharArray()},
{{'U'},"..-".toCharArray()},{{'V'},"...-".toCharArray()},{{'W'},".--".toCharArray()},{{'X'},"-..-".toCharArray()},
{{'Y'},"-.--".toCharArray()},{{'Z'},"--..".toCharArray()},{{'_'},"..--".toCharArray()},{{','},".-.-".toCharArray()},
{{'.'},"---.".toCharArray()},{{'?'},"----".toCharArray()}
};
StringBuilder sb=new StringBuilder();
for(int c=0,C=parseInt(in.readLine().trim());c++<C;){
sb.append(c+": ");
char[] A=in.readLine().trim().toCharArray();
int[] arr=new int[A.length];
String s="";
for(int i=0;i<A.length;i++)
for(int j=0;j<letras.length;j++)
if(letras[j][0][0]==A[i]){
arr[i]=letras[j][1].length;
s+=new String(letras[j][1]);
break;
}
A=s.toCharArray();
for(int i=arr.length-1,j=0;i>=0;i--){
char[] t=new char[arr[i]];
for(int k=0;k<arr[i];k++,j++)t[k]=A[j];
for(int k=0;k<letras.length;k++)
if(compare(letras[k][1],t))
sb.append(letras[k][0]);
}
sb.append("\n");
}
System.out.print(new String(sb));
} | 8 |
public void setNextByAddr(FlowBlock flow) {
/* nextByAddr can be set, when reordering block in transform exc */
// if (nextByAddr != null)
// throw new IllegalStateException("nextByAddr already set");
if (flow == END_OF_METHOD || flow == NEXT_BY_ADDR)
throw new IllegalArgumentException("nextByAddr mustn't be special");
SuccessorInfo info = (SuccessorInfo) successors.remove(NEXT_BY_ADDR);
SuccessorInfo flowInfo = (SuccessorInfo) successors.get(flow);
if (info != null) {
NEXT_BY_ADDR.predecessors.remove(this);
Jump jumps = info.jumps;
jumps.destination = flow;
while (jumps.next != null) {
jumps = jumps.next;
jumps.destination = flow;
}
successors.put(flow, info);
if (flowInfo != null) {
info.gen.addAll(flowInfo.gen);
info.kill.retainAll(flowInfo.kill);
jumps.next = flowInfo.jumps;
} else
flow.predecessors.add(this);
}
checkConsistent();
nextByAddr = flow;
flow.prevByAddr = this;
} | 5 |
public OSCPacketDispatcher() {
} | 0 |
private boolean setupCompleted() {
if (address.getText() == null || address.getText().trim().length() == 0) {
return false;
}
if (!loadGame) {
if (teamChoice.getSelection() == null) {
return false;
}
if (address.getText() == null
|| name.getText().trim().length() == 0) {
return false;
}
}
return true;
} | 6 |
public Builder temperature(int receivedTemperature) {
if (receivedTemperature > 25000) {
starClass = StellarClassification.O;
}
if (receivedTemperature <= 25000) {
starClass = StellarClassification.B;
}
if (receivedTemperature <= 11000) {
starClass = StellarClassification.A;
}
if (receivedTemperature <= 7500) {
starClass = StellarClassification.F;
}
if (receivedTemperature <= 6000) {
starClass = StellarClassification.G;
}
if (receivedTemperature <= 5000) {
starClass = StellarClassification.K;
}
if (receivedTemperature <= 3500) {
starClass = StellarClassification.M;
}
this.temperature = receivedTemperature;
return this;
} | 7 |
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(2048);
while (!Thread.currentThread().isInterrupted()) {
Socket client = server.accept();
// new Thread(new ClientHanldler(client)).start();
service.execute(new ClientHanldler(client));
}
service.shutdown();
} | 1 |
public String toHtml(){
String ret=parentRow();
for(Object s:this.events){
ret+=((AuditEvent)s).toHtml();
}
return ret;
} | 1 |
void implementMap()
{
props.add(Defaults.MAP_PROPERTY_COL);
returnTypes.add(Object[].class);
// add a dummy mutator
setters.add(null);
getters.add(null);
if (this.object != null)
{
// this should work:
// Set<?> entrySet =((Map<?,?>)object).entrySet();
// values.add(entrySet.toArray());
// unfortunately, it does not, as it causes problems later when we
// try to access the contents of the Set.
// This is caused by bug 4071957:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957
// therefore we have to map the inner class object onto an ordinary
// class object:
Set<?> entrySet = ((Map<?, ?>) object).entrySet();
ArrayList<MapEntry> ordinarySet = new ArrayList<MapEntry>();
for (Object o : entrySet)
{
Map.Entry<?, ?> entry = (Entry<?, ?>) o;
MapEntry nuEntry = new MapEntry();
nuEntry.setKey(entry.getKey());
nuEntry.setValue(entry.getValue());
ordinarySet.add(nuEntry);
}
values.add(ordinarySet.toArray());
}
} | 9 |
private void moveForward(Orientation orientation) throws MovementInvalidException{
//TODO check MarsRover space and throw exception
switch (orientation) {
case NORTH:
if(marsRover.getMaxCoordenateY() > getCoordenateY())
setCoordenateY(getCoordenateY() + 1);
else
throw new MovementInvalidException(MovementInvalidException.MAX_POSITION_ALREADY_REACHED);
break;
case WEST:
if(marsRover.getMinCoordenateX() < getCoordenateX())
setCoordenateX(getCoordenateX() - 1);
else
throw new MovementInvalidException(MovementInvalidException.MIN_POSITION_ALREADY_REACHED);
break;
case EAST:
if(marsRover.getMaxCoordenateX() > getCoordenateX())
setCoordenateX(getCoordenateX() + 1);
else
throw new MovementInvalidException(MovementInvalidException.MAX_POSITION_ALREADY_REACHED);
break;
case SOUTH:
if(marsRover.getMinCoordenateY() < getCoordenateY())
setCoordenateY(getCoordenateY() - 1);
else
throw new MovementInvalidException(MovementInvalidException.MIN_POSITION_ALREADY_REACHED);
break;
default:
break;
}
} | 8 |
protected void removeChild( GraphItem item ) {
children.remove( item );
if( site != null ) {
site.removeItem( item );
}
} | 1 |
@Override
public List<Packet> onContact(int selfID, Sprite interactor, int interactorID, List<Integer> dirtySprites, List<Integer> spritesPendingRemoveal, ChatBroadcaster chatter) {
if (interactor instanceof Player) {
if (!((Player) interactor).isAlive())
return new ArrayList<Packet>();
Player player = (Player) interactor;
player.setLife(player.getLife() - getDamage());
if (player.getLife() < 0) {
chatter.sendChatBroadcast("~ Player " + ((Player) interactor).getName() + " was killed by " + owner);
spritesPendingRemoveal.add(interactorID);
}
dirtySprites.add(interactorID);
spritesPendingRemoveal.add(selfID);
}
return new ArrayList<Packet>();
} | 3 |
public Connection nearBaseStation() {
for (int i = 0; i < connections.getLength(); i++) {
Connection connection = connections.get(i);
if (connection.getType() != CoreType.BASESTATION)
return connection;
}
return null;
} | 2 |
public void setData(int[][][] data, int demeCount) {
if(data.length==0 || demeCount==1)
return;
assert data.length * 2 == (demeCount * (demeCount - 1));
// first set deme labels...
xlabs =new String[data.length];
ylabs =new String[data.length];
int counter =0;
for (int i =0; i < demeCount; i++) {
for (int j =i + 1; j < demeCount; j++) {
xlabs[counter] ="Allele Freq. in Deme " + (i + 1);
ylabs[counter] ="Allele Freq. in Deme " + (j + 1);
counter++;
}
}
jafsData =data;
maxZ=-Integer.MAX_VALUE;
zRanks.clear();
for(int i=0;i<data.length;i++){
for(int j=0;j<data[i].length;j++){
for(int k=0;k<data[i][j].length;k++){
maxZ=Math.max(maxZ, data[i][j][k]);
zRanks.add(data[i][j][k]);
}
}
}
Collections.sort(zRanks);
setMaxZRank(.9);
System.out.println("Max:"+maxZ);
} | 7 |
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.