text stringlengths 14 410k | label int32 0 9 |
|---|---|
public int compare(Object arg1, Object arg2)
{
Point p1 = (Point) arg1;
Point p2 = (Point) arg2;
if (p1.x > p2.x) return 1;
else if(p1.x == p2.x)
{
if (p1.y > p2.y) return 1;
else if (p1.y == p2.y) return 0;
}
return -1;
} | 4 |
private void halveArraySize() {
Person[] smallerArray = new Person[(personArray.length/2)];
for (int i = 0; i < (personArray.length/2); i++) {
smallerArray[i] = this.personArray[i];
}
this.personArray = smallerArray;
} | 1 |
@Override
public boolean canAttack(Board board, Field currentField, Field occupiedField) {
return this.validSetupForAttack(currentField, occupiedField) && occupiedField.distanceBetweenRank(currentField) == this.forwardDistance(1) && Math.abs(occupiedField.distanceBetweenFile(currentField)) == 1;
} | 2 |
public void exec() {
List<Double> annOut = network.run();
if (annOut.get(0) > .5 && annOut.get(1) <= .5) {
headingDelta = 5;
movement = 0;
hunger += .0009;
} else if (annOut.get(0) > .5 && annOut.get(1) > .5) {
headingDelta = 0;
movement = 3;
hunger += .0009;
} else if (annOut.get(0) <= .5 && annOut.get(1) > .5) {
headingDelta = -5;
movement = 0;
hunger += .0009;
} else {
headingDelta = 0;
movement = 0;
hunger += .0009;
}
} | 6 |
public boolean configureFor(int stage) {
if (stage == STAGE_GET_SEED) {
toPlant = findPlantTile(actor, nursery) ;
if (toPlant == null) { abortBehaviour() ; return false ; }
if (nursery.stocks.amountOf(seedMatch()) > 0) {
this.stage = STAGE_GET_SEED ;
}
else this.stage = STAGE_PLANTING ;
}
if (stage == STAGE_SAMPLING) {
toCut = findCutting(actor) ;
if (toCut == null) { abortBehaviour() ; return false ; }
this.stage = STAGE_SAMPLING ;
}
return false ;
} | 5 |
public void feedCitiesProcessDisasters() {
players.get(currentplayer).feedCities();
players.get(currentplayer).processDisasters();
int numSkulls = players.get(currentplayer).getSkulls();
if (numSkulls == 3) {
for (int i = 0; i < players.size(); i++) {
if (i != currentplayer || players.size() == 1) {
players.get(i).infectWithPestilence();
}
}
} else if (numSkulls >= 5) {
if (!players.get(currentplayer).getDevelopementList().isDevelopmentBought(DevelopmentList.RELIGION)){
players.get(currentplayer).inflictRevolt();
}
else{
for (int i = 0; i < players.size(); i++) {
if (i != currentplayer) {
players.get(i).inflictRevolt();
}
}
}
}
} | 8 |
@Override
public String toString() {
return "{id=" + id +"}";
} | 0 |
public void testPropertySetMinute() {
Partial test = new Partial(TYPES, VALUES);
Partial copy = test.property(DateTimeFieldType.minuteOfHour()).setCopy(12);
check(test, 10, 20, 30, 40);
check(copy, 10, 12, 30, 40);
try {
test.property(DateTimeFieldType.minuteOfHour()).setCopy(60);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.property(DateTimeFieldType.minuteOfHour()).setCopy(-1);
fail();
} catch (IllegalArgumentException ex) {}
} | 2 |
protected void load() {
boolean loaded = false;
try {
load(file);
loaded = true;
}
catch (final FileNotFoundException e) {}
catch (final IOException e) {
plugin.logException(e, "cannot load " + file);
}
catch (final InvalidConfigurationException e) {
if (e.getCause() instanceof YAMLException) plugin.severe("Config file " + file + " isn't valid! \n" + e.getCause());
else if (e.getCause() == null || e.getCause() instanceof ClassCastException) plugin.severe("Config file " + file + " isn't valid!");
else plugin.logException(e, "cannot load " + file + ": " + e.getCause().getClass());
plugin.info("Saving a backup of " + name + " to " + backup("invalid"));
}
final InputStream inStream = plugin.getResource(file.getName());
if (inStream != null) {
setDefaults(YamlConfiguration.loadConfiguration(inStream));
if (!loaded) plugin.info("Writing default " + name + " to " + file);
}
if (!loaded) {
options().copyDefaults(true);
save();
}
else upgrade();
} | 9 |
public Integer getQuantity() {
return quantity;
} | 0 |
public Timestamp getModifyDateGmt() {
return this.modifyDateGmt;
} | 0 |
protected void verifySignature(RandomAccessFile randomaccessfile) throws IOException, InvalidLodFileException
{
randomaccessfile.seek(0L);
boolean matchedSignature = true;
for (int i = 0; i < SIGNATURE_NEW_MM7.length; i++)
{
int aByte = randomaccessfile.read();
if (aByte != SIGNATURE_NEW_MM7[i])
{
matchedSignature = false;
break;
}
}
if (false == matchedSignature)
{
randomaccessfile.seek(0L);
matchedSignature = true;
for (int i = 0; i < SIGNATURE_GAME_MM7.length; i++)
{
int aByte = randomaccessfile.read();
if (aByte != SIGNATURE_GAME_MM7[i])
{
matchedSignature = false;
break;
}
}
}
if (false == matchedSignature)
{
randomaccessfile.seek(0L);
matchedSignature = true;
for (int i = 0; i < SIGNATURE_GAME_MM8.length; i++)
{
int aByte = randomaccessfile.read();
if (aByte != SIGNATURE_GAME_MM8[i])
{
matchedSignature = false;
break;
}
}
}
if (false == matchedSignature)
{
throw new InvalidLodFileException("Invalid Signature");
}
} | 9 |
protected String getGlobalLinkerFlags() {
final StringBuilder builder = new StringBuilder();
if (globalOverrideLinkerFlags == null
|| globalOverrideLinkerFlags.isEmpty()) {
if (parent != null)
builder.append(parent.getGlobalLinkerFlags());
else
builder.append(config.ldflags());
} else {
builder.append(globalOverrideLinkerFlags);
}
if (globalLinkerFlags != null && !globalLinkerFlags.isEmpty()) {
if (builder.length() > 0)
builder.append(' ');
builder.append(globalLinkerFlags);
}
String dyn = getDynLinkerFlags();
if (!dyn.isEmpty()) {
if (builder.length() > 0)
builder.append(' ');
builder.append(dyn);
}
return builder.toString();
} | 8 |
public FieldMetadata getNamedField(final String fieldName) {
if (StringUtils.isBlank(fieldName)) return null;
for (FieldMetadata field : fields) {
if (field.getName().equals(fieldName)) return field;
}
return null;
} | 3 |
private String startTimeToString()
{
long start = this.videoSection.getStart();
if (videoSection.getTimeUnit() == TimeUnit.SECONDS)
{
start *= 1000;
}
int millisecond = (int) (start % 1000);
start /= 1000;
int second = (int) (start % 60);
start /= 60;
int minute = (int) (start % 60);
start /= 60;
int hour = (int) start;
return timeToString(hour, minute, second, millisecond);
} | 1 |
public int dijkstra(int s, int t) {
for (int i = 0; i < cost.length; i++) {
dis[i] = INF;
vis[i] = false;
}
PriorityQueue<Edge> q = new PriorityQueue<Edge>();
q.add(new Edge(s, 0, -1));
dis[s] = 0;
while (!q.isEmpty()) {
Edge u = q.poll();
if (u.id == t)
return u.w;
for (int j = 0; j < adj[u.id].size(); j++) {
Edge v = adj[u.id].get(j);
int w = v.w + ((u.e != v.e && u.e != -1) ? 60 : 0);
if (u.w + w < dis[v.id]) {
dis[v.id] = u.w + w;
q.add(new Edge(v.id, dis[v.id], v.e));
}
}
}
return INF;
} | 7 |
@Override
public Clip getSoundClip(EnActionResult actionResult) {
if (moveClip == null) {
moveClip = openClip(SoundPlayerWav.SOUND_MOVE);
}
if (treasureClip == null) {
treasureClip = openClip(SoundPlayerWav.SOUND_TREASURE);
}
if (winClip == null) {
winClip = openClip(SoundPlayerWav.SOUND_WIN);
}
switch (actionResult) {
case MOVE: {
return moveClip;
}
case DIE: {
return super.getDieClip();
}
case COLLECT_TREASURE: {
return treasureClip;
}
case WIN: {
return winClip;
}
}
return null;
} | 7 |
public int aroonOscLookback( int optInTimePeriod )
{
if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) )
optInTimePeriod = 14;
else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) )
return -1;
return optInTimePeriod;
} | 3 |
public String getGameStateName(){
String stateName;
switch(gameState){
case 0:
stateName = "New hand";
break;
case 1:
stateName = "Fold";
break;
case 2:
stateName = "Bet";
break;
case 3:
stateName = "Raise";
break;
case 4:
stateName = "Call";
break;
case 5:
stateName = "Check";
break;
case 6:
stateName = "All in";
break;
default: stateName = "";
break;
}
return stateName;
} | 7 |
public Word getAnswer(String s){
Iterator<Word> iterator = list.iterator();
Word w = null;
boolean flag = false;
while (iterator.hasNext()){
w = iterator.next();
if (w.getEWord().equals(s)){
System.out.println(w);
flag = true;
break;
}
}
if (!flag){
// System.out.println("Nothing was find!");
return null;
}
else
return w;
} | 3 |
public void setIautosSellerInfo(IautosSellerInfo iautosSellerInfo) {
this.iautosSellerInfo = iautosSellerInfo;
} | 0 |
private void fetchAttributes() {
int len = GL20.glGetProgrami(program, GL20.GL_ACTIVE_ATTRIBUTES);
// max length of all uniforms stored in program
int strLen = GL20.glGetProgrami(program, GL20.GL_ACTIVE_ATTRIBUTE_MAX_LENGTH);
attributes = new Attrib[len];
for (int i = 0; i < len; i++) {
Attrib a = new Attrib();
// TODO: use proper FloatBuffer method instead of these convenience
// methods
a.name = GL20.glGetActiveAttrib(program, i, strLen);
a.size = GL20.glGetActiveAttribSize(program, i);
a.type = GL20.glGetActiveAttribType(program, i);
a.location = GL20.glGetAttribLocation(program, a.name);
attributes[i] = a;
}
} | 1 |
private static boolean formQueryHotel(Criteria crit, List params, StringBuilder sb, StringBuilder sbw, Boolean f2345, Boolean f5) {
List list = new ArrayList<>();
StringBuilder str = new StringBuilder(" ( ");
String qu = new QueryMapper() {
@Override
public String mapQuery() {
Appender.append(DAO_HOTEL_STARS, DB_HOTEL_STARS, crit, list, str, OR);
return str.toString() + " ) ";
}
}.mapQuery();
if (!list.isEmpty()) {
if (!f2345) {
sb.append(LOAD_QUERY_DIRECT);
}
if (!f5) {
sb.append(LOAD_QUERY_STAY);
}
sb.append(LOAD_QUERY_HOTEL);
if (!params.isEmpty()) {
sbw.append(AND);
}
sbw.append(qu);
params.addAll(list);
return true;
} else {
return false;
}
} | 4 |
Level(GameEngine eng, String file_prefix) {
priority = -1;
engine = eng;
try {
layout = ImageIO.read(new File(file_prefix + ".layout.png"));
visual = ImageIO.read(new File(file_prefix + ".visual.png"));
LevelGeometry g = new LevelGeometry(engine, layout, visual);
drawable = g;
geometry = g;
for (int i = 0; i < layout.getHeight(); i++)
for (int j = 0; j < layout.getWidth(); j++) {
int lc = getLayRGB(j, i);
if(lc == playerColor)
engine.addObject(new Player(j, i, engine));
else if(lc == snakeColor)
engine.addObject(WolfSnake.createSnake(engine, j, i));
else if(lc == wolfColor)
engine.addObject(WolfSnake.createWolf(engine, j, i));
else if(lc == swolfColor)
engine.addObject(WolfSnake.createSnowWolf(engine, j, i));
else if(lc == saurusColor)
engine.addObject(new Saurus(engine, j, i));
}
}
catch (Exception e) {
e.printStackTrace();
}
} | 8 |
public static ArrayList<Media> getAllRentedMedia() {
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<Media> mediaList = new ArrayList<Media>();
Media m = null;
try {
Statement stmnt = conn.createStatement();
String sql = "SELECT * FROM Media m WHERE m.media_id = (SELECT media_id FROM MediaCopies mc, Rentals r WHERE mc.media_id = m.media_id AND mc.copy_id = r.product_id AND (r.type = 'DVD' OR r.type = 'CD') AND r.rental_id = (SELECT rental_id FROM RentTransactions rt WHERE rt.rent_trans_id = r.rental_id AND rt.closed = 0))";
ResultSet res = stmnt.executeQuery(sql);
while(res.next()) {
m = new Media(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"));
mediaList.add(m);
}
}
catch(SQLException e) {
System.out.println(e);
}
return mediaList;
} | 5 |
public String getAccessString() {
StringBuffer sb = new StringBuffer();
if (AccessFlags.isPublic(this.accessFlags))
sb.append("public ");
if (AccessFlags.isPrivate(this.accessFlags))
sb.append("private ");
if (AccessFlags.isProtected(this.accessFlags))
sb.append("protected ");
if (AccessFlags.isAbstract(this.accessFlags))
sb.append("abstract ");
if (AccessFlags.isStatic(this.accessFlags))
sb.append("static ");
if (AccessFlags.isSynchronized(this.accessFlags))
sb.append("synchronized ");
if (AccessFlags.isFinal(this.accessFlags))
sb.append("final ");
if (AccessFlags.isNative(this.accessFlags))
sb.append("native ");
return sb.toString().trim();
} | 8 |
public void attackClosestUnit() {
ArrayList<Cell> attackableCells = getAttackableCells(map);
if (attackableCells.size() == 0) {
map.resetPreviousCells();
Queue<Cell> queue = new LinkedList<Cell>();
queue.add(this.getCell());
ArrayList<Cell> expandedNodes = new ArrayList<Cell>();
Cell c = attackClosestUnit_(queue, expandedNodes);
ArrayList<Cell> moveableCells = getMoveableCells(map);
if (c != null) {
boolean loop = true;
while (loop && !moveableCells.contains(c)) {
if (c.getPreviousCell() == null) {
loop = false;
} else {
c = c.getPreviousCell();
}
}
}
if (c != null) {
this.moveToCell(this, this.getCell(), c, true);
}
map.resetPreviousCells();
} else {
Cell attackCell = attackableCells.get(0);
if (attackCell.getBuilding() != null) {
this.attackBuilding(this, attackCell.getBuilding(), true);
} else if (attackCell.getUnit() != null) {
this.attackUnit(this, attackCell.getUnit(), true);
}
}
} | 8 |
public static void dfsCat() {
Stack<Integer> s = new Stack<Integer>();
s.push(hcat);
vcat[hcat] = true;
while (!s.isEmpty()) {
int cur = s.pop();
for (int i = 0; i < gcat[cur].size(); i++) {
int neigh = gcat[cur].get(i);
if (!vcat[neigh]) {
vcat[neigh] = true;
s.push(neigh);
}
}
}
} | 3 |
public String encrypt (String input) {
//Below checks whether the string contains any digit characters
if(input.matches(".*\\d.*")) throw new IllegalArgumentException();
//Below the replaceAll is used to ignore non-characters until first appearance of a character
String formatted = input.toUpperCase().replaceAll("[^A-Z]", "");
if(formatted.length() == 0) throw new IllegalArgumentException();
char[] characters = formatted.toCharArray();
//Create a 5x5 table with only capital letters of the cipher
char[][] Table5x5 = _makeTable5x5(this.cipherKey.replaceAll("[^A-Z]", ""));
int[] rows = new int[characters.length];
int[] cols = new int[characters.length];
for(int i = 0; i < characters.length; i++) {
for(int row = 0; row < 5; row++) {
for(int column = 0; column < 5; column++) {
//If the letter in the table is equal to the character in the array,
//Then the row and column # of that letter (in table5x5) is stored
//in rows[i] and cols[i]
if(Table5x5[row][column] == characters[i]) {
rows[i] = row;
cols[i] = column;
}
if(characters[i] == 'J' || characters[i] == 'I'){
rows[i] = jirow;
cols[i] = jicol;
}
}
}
}
int[] combined = new int[characters.length * 2];
System.arraycopy(rows, 0, combined, 0, characters.length);
System.arraycopy(cols, 0, combined, characters.length, characters.length);
char[] values = new char[characters.length];
for(int i = 0; i < combined.length; i=i+2) {
values[i/2] = Table5x5[combined[i]][combined[i+1]];
}
return new String(values);
} | 9 |
private static void intersectFrom(Scope scope1, Scope scope2,
Set<String> matchedNames,
Collection<Variable> vars) {
Set<Variable> privates1 = scope1.mPrivateVars;
Variable[] vars1 = scope1.getLocallyDeclaredVariables();
for (int i=0; i<vars1.length; i++) {
Variable var1 = vars1[i];
if (privates1 != null && privates1.contains(var1)) {
continue;
}
String varName = var1.getName();
if (matchedNames.contains(varName)) {
// This variable has already been moved into the intersection.
continue;
}
else {
matchedNames.add(varName);
}
Variable var2 = scope2.getDeclaredVariable(varName, true);
if (var2 == null) {
// No matching public variable in scope2, so continue.
continue;
}
Type type1 = var1.getType();
Type type2 = var2.getType();
// Find common type.
Type type = type1.getCompatibleType(type2);
if (type == null) {
continue;
}
// Find a variable to hold common type.
Variable var = null;
if (type.equals(type1)) {
var = var1;
}
else if (type.equals(type2)) {
var = var2;
}
else {
// Create a new variable with the common type.
var = new Variable(var1.getSourceInfo(), varName, type, var != null ? var.isStaticallyTyped() : false);
}
vars.add(var);
}
} | 9 |
public void playGame() {
while (!isOver()) {
showTrack();
move();
}
showTrack();
showWinners();
} | 1 |
public int hashCode() {
int code = 0;
for (final E item : this) {
code = code ^ item.hashCode();
}
return code;
} | 1 |
public List<String> getNameCombinations() {
List<String> nameComb = new ArrayList<String>();
nameComb.add(getLastName() + ", " + getFirstName() + " "
+ getMiddleName());
nameComb.add(getFirstName() + " " + getMiddleName() + " "
+ getLastName() + " " + getSuffix());
return nameComb;
} | 0 |
private static void Transform(int i, int[] buffer, int messageLenBytes, byte[] message, byte[] paddingBytes, int[] state) {
int index = i << 6;
for (int j = 0; j < 64; j++, index++) {
buffer[j >>> 2] = ((int) ((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8);
} // end for
int a = state[0];
int b = state[1];
int c = state[2];
int d = state[3];
for (int k = 0; k < 64; k++) {
int div16 = k >>> 4;
int f = 0;
int bufferIndex = k;
switch (div16) {
case 0:
f = (state[1] & state[2]) | (~state[1] & state[3]);
break;
case 1:
f = (state[1] & state[3]) | (state[2] & ~state[3]);
bufferIndex = (bufferIndex * 5 + 1) & 0x0F;
break;
case 2:
f = state[1] ^ state[2] ^ state[3];
bufferIndex = (bufferIndex * 3 + 5) & 0x0F;
break;
case 3:
f = state[2] ^ (state[1] | ~state[3]);
bufferIndex = (bufferIndex * 7) & 0x0F;
break;
// end switch
} // end for
int temp = state[1] + Integer.rotateLeft(state[0] + f + buffer[bufferIndex] + T_TABLE[k], S_TABLE[(div16 << 2) | (k & 3)]);
state[0] = state[3];
state[3] = state[2];
state[2] = state[1];
state[1] = temp;
} // end for
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
} | 7 |
public static StandardObject lookupVariableType(Symbol variablename) {
{ StandardObject entry = ((((KeyValueList)(Stella.$LOCALVARIABLETYPETABLE$.get())) != null) ? ((StandardObject)(KeyValueList.lookupVariableTable(((KeyValueList)(Stella.$LOCALVARIABLETYPETABLE$.get())), variablename))) : ((StandardObject)(null)));
StandardObject type = null;
if (entry == null) {
if (variablename == Stella.SYM_STELLA_NULL) {
return (Stella.SGT_STELLA_UNKNOWN);
}
type = Symbol.lookupGlobalVariableType(variablename);
Symbol.registerReferenceToGlobalVariable(variablename);
}
else {
if (Surrogate.subtypeOfP(Stella_Object.safePrimaryType(entry), Stella.SGT_STELLA_KEY_VALUE_LIST)) {
{ KeyValueList entry000 = ((KeyValueList)(entry));
type = ((StandardObject)(entry000.lookup(Stella.KWD_TYPE)));
}
}
else {
type = entry;
}
}
if (type == null) {
{ Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get();
try {
Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true);
Stella.signalTranslationError();
if (!(Stella.suppressWarningsP())) {
Stella.printErrorContext(">> ERROR: ", Stella.STANDARD_ERROR);
{
Stella.STANDARD_ERROR.nativeStream.println();
Stella.STANDARD_ERROR.nativeStream.println(" Undeclared variable `" + Stella_Object.deUglifyParseTree(variablename) + "'.");
}
;
}
} finally {
Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000);
}
}
return (Stella.SGT_STELLA_UNKNOWN);
}
if (type == Stella.SGT_STELLA_UNINITIALIZED) {
{ Object old$PrintreadablyP$001 = Stella.$PRINTREADABLYp$.get();
try {
Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true);
Stella.signalTranslationError();
if (!(Stella.suppressWarningsP())) {
Stella.printErrorContext(">> ERROR: ", Stella.STANDARD_ERROR);
{
Stella.STANDARD_ERROR.nativeStream.println();
Stella.STANDARD_ERROR.nativeStream.println(" Reference to defined but uninitialized variable `" + Stella_Object.deUglifyParseTree(variablename) + "'.");
}
;
}
} finally {
Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$001);
}
}
return (Stella.SGT_STELLA_UNKNOWN);
}
return (type);
}
} | 8 |
public static void choldc_f77(int n, double a[][], double diagmx,
double tol, double addmax[]) {
/*
Here is a copy of the choldc FORTRAN documentation:
SUBROUTINE CHOLDC(NR,N,A,DIAGMX,TOL,ADDMAX)
C
C PURPOSE
C -------
C FIND THE PERTURBED L(L-TRANSPOSE) [WRITTEN LL+] DECOMPOSITION
C OF A+D, WHERE D IS A NON-NEGATIVE DIAGONAL MATRIX ADDED TO A IF
C NECESSARY TO ALLOW THE CHOLESKY DECOMPOSITION TO CONTINUE.
C
C PARAMETERS
C ----------
C NR --> ROW DIMENSION OF MATRIX
C N --> DIMENSION OF PROBLEM
C A(N,N) <--> ON ENTRY: MATRIX FOR WHICH TO FIND PERTURBED
C CHOLESKY DECOMPOSITION
C ON EXIT: CONTAINS L OF LL+ DECOMPOSITION
C IN LOWER TRIANGULAR PART AND DIAGONAL OF "A"
C DIAGMX --> MAXIMUM DIAGONAL ELEMENT OF "A"
C TOL --> TOLERANCE
C ADDMAX <-- MAXIMUM AMOUNT IMPLICITLY ADDED TO DIAGONAL OF "A"
C IN FORMING THE CHOLESKY DECOMPOSITION OF A+D
C INTERNAL VARIABLES
C ------------------
C AMINL SMALLEST ELEMENT ALLOWED ON DIAGONAL OF L
C AMNLSQ =AMINL**2
C OFFMAX MAXIMUM OFF-DIAGONAL ELEMENT IN COLUMN OF A
C
C
C DESCRIPTION
C -----------
C THE NORMAL CHOLESKY DECOMPOSITION IS PERFORMED. HOWEVER, IF AT ANY
C POINT THE ALGORITHM WOULD ATTEMPT TO SET L(I,I)=SQRT(TEMP)
C WITH TEMP < TOL*DIAGMX, THEN L(I,I) IS SET TO SQRT(TOL*DIAGMX)
C INSTEAD. THIS IS EQUIVALENT TO ADDING TOL*DIAGMX-TEMP TO A(I,I)
C
C
*/
int i,j,jm1,jp1,k;
double aminl,amnlsq,offmax,sum,temp;
addmax[1] = 0.0;
aminl = Math.sqrt(diagmx*tol);
amnlsq = aminl*aminl;
// FORM COLUMN J OF L
for (j = 1; j <= n; j++) {
// FIND DIAGONAL ELEMENTS OF L
sum = 0.0;
jm1 = j - 1;
jp1 = j + 1;
for (k = 1; k <= jm1; k++) {
sum += a[j][k]*a[j][k];
}
temp = a[j][j] - sum;
if (temp >= amnlsq) {
a[j][j] = Math.sqrt(temp);
} else {
// FIND MAXIMUM OFF-DIAGONAL ELEMENT IN COLUMN
offmax = 0.0;
for (i = jp1; i <= n; i++) {
if (Math.abs(a[i][j]) > offmax) offmax = Math.abs(a[i][j]);
}
if (offmax <= amnlsq) offmax = amnlsq;
// ADD TO DIAGONAL ELEMENT TO ALLOW CHOLESKY DECOMPOSITION TO CONTINUE
a[j][j] = Math.sqrt(offmax);
addmax[1] = Math.max(addmax[1],offmax-temp);
}
// FIND I,J ELEMENT OF LOWER TRIANGULAR MATRIX
for (i = jp1; i <= n; i++) {
sum = 0.0;
for (k = 1; k <= jm1; k++) {
sum += a[i][k]*a[j][k];
}
a[i][j] = (a[i][j] - sum)/a[j][j];
}
}
return;
} | 8 |
@Override
public boolean tick(Tickable ticking, int tickID)
{
if((affected!=null)&&(affected instanceof MOB)&&(tickID==Tickable.TICKID_MOB))
{
final MOB mob=(MOB)affected;
if(tickUp==1)
{
if(success==false)
{
final StringBuffer str=new StringBuffer(L("You get distracted from your search.\n\r"));
commonTell(mob,str.toString());
unInvoke();
return super.tick(ticking,tickID);
}
}
if(((MOB)affected).location()!=searchRoom)
{
searchRoom=((MOB)affected).location();
bonusThisRoom=0;
((MOB)affected).recoverCharStats();
}
else
if(bonusThisRoom<affected.phyStats().level())
{
bonusThisRoom+=5;
((MOB)affected).recoverCharStats();
}
}
return super.tick(ticking,tickID);
} | 7 |
public static void main(String[] args) throws IOException {
byte[] b = new byte[16];
for(int i = 0 ; i < b.length;i ++)
{
b[i] = (byte)i;
}
MyOwnStream1 mosrm = new MyOwnStream1(b);
//指定下次读取的位置
mosrm.mark(3);
//需要用reset方法来重置下次读取的位置为mark指定的位置
mosrm.reset();
while(true)
{
int c = mosrm.read();
if(c < 0 )
{
break;
}
System.out.print( c + " ");
}
System.out.println();
mosrm.close();
} | 3 |
public IDassign(String type) {
this.nextIDchar = new Character[type.length()];
Pattern patrn = Pattern.compile("[...a-z_]");
Matcher match = patrn.matcher(type);
for (int i = 0; i < 3; i++) {
if (i == 1) {
patrn = Pattern.compile("[...A-Z_]");
match = patrn.matcher(type);
}
else if (i == 2) {
patrn = Pattern.compile("[...0-9_]");
match = patrn.matcher(type);
}
while (match.find()) {
if (i == 0) {
this.nextIDchar[match.start()] = 'a';
}
else if (i == 1) {
this.nextIDchar[match.start()] = 'A';
}
else if (i == 2) {
this.nextIDchar[match.start()] = '0';
}
}
}
//transfers collected data to the id template & prevents nulls
for (int i = 0; i < type.length(); i++) {
if (this.nextIDchar[i] == null) {
this.nextIDchar[i] = type.charAt(i);
}
this.nextID += this.nextIDchar[i];
}
} | 9 |
public void build(AssemblyType type) {
Mass one;
Mass two;
double restLength;
double constant;
NodeList nodes = myDoc.getElementsByTagName(SPRING);
for (int i = 0; i < nodes.getLength(); i++) {
restLength = -1;
constant = 1;
Node springItem = nodes.item(i);
NamedNodeMap nodeMap = springItem.getAttributes();
one = myMassMap.get(nodeMap.getNamedItem(A).getNodeValue());
two = myMassMap.get(nodeMap.getNamedItem(B).getNodeValue());
getNodeMapItems(0, restLength, constant, nodeMap, REST, CONST);
if (restLength == -1) {
//make
AssemblyFactory.buildAssembly(type).make();
} else {
//makefull
AssemblyFactory.buildAssembly(type).makeFull();
}
}
} | 2 |
public Component getEditorComponent(final PropertyEditor editor)
{
String[] tags = editor.getTags();
String text = editor.getAsText();
if (editor.supportsCustomEditor())
{
return editor.getCustomEditor();
}
else if (tags != null)
{
// make a combo box that shows all tags
final JComboBox comboBox = new JComboBox(tags);
comboBox.setSelectedItem(text);
comboBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent event)
{
if (event.getStateChange() == ItemEvent.SELECTED)
editor.setAsText((String) comboBox.getSelectedItem());
}
});
return comboBox;
}
else
{
final JTextField textField = new JTextField(text, 10);
textField.getDocument().addDocumentListener(new DocumentListener()
{
public void insertUpdate(DocumentEvent e)
{
try
{
editor.setAsText(textField.getText());
}
catch (IllegalArgumentException exception)
{
}
}
public void removeUpdate(DocumentEvent e)
{
try
{
editor.setAsText(textField.getText());
}
catch (IllegalArgumentException exception)
{
}
}
public void changedUpdate(DocumentEvent e)
{
}
});
return textField;
}
} | 5 |
private static void printGridletList(GridletList list, String name,
boolean detail)
{
int size = list.size();
Gridlet gridlet = null;
String indent = " ";
System.out.println();
System.out.println("============= OUTPUT for " + name + " ==========");
System.out.println("Gridlet ID" + indent + "STATUS" + indent +
"Resource ID" + indent + "Cost");
// a loop to print the overall result
int i = 0;
for (i = 0; i < size; i++)
{
gridlet = (Gridlet) list.get(i);
System.out.print(indent + gridlet.getGridletID() + indent
+ indent);
System.out.print( gridlet.getGridletStatusString() );
System.out.println( indent + indent + gridlet.getResourceID() +
indent + indent + gridlet.getProcessingCost() );
}
if (detail == true)
{
// a loop to print each Gridlet's history
for (i = 0; i < size; i++)
{
gridlet = (Gridlet) list.get(i);
System.out.println( gridlet.getGridletHistory() );
System.out.print("Gridlet #" + gridlet.getGridletID() );
System.out.println(", length = " + gridlet.getGridletLength()
+ ", finished so far = " +
gridlet.getGridletFinishedSoFar() );
System.out.println("======================================\n");
}
}
} | 3 |
JobFuturePair(PageJob job, Future<?> future) {
this.job = job; this.future = future;
} | 1 |
public void onJoin(String channel, String sender, String login, String hostname) {
if (!sender.equals(bot.getNick())) {
if (status == GameStatus.PRE)
sendNotice(sender, getFromFile("GAME-STARTED", NOTICE));
else if (status != GameStatus.IDLE)
sendNotice(sender, getFromFile("GAME-PLAYING", NOTICE));
}
} | 3 |
public static void main(String[] args)
{
// 只能在List下面的类型
GenericTestExtends<? extends List> ge = null;
//引用指向不同类
ge = new GenericTestExtends<ArrayList>();
ge = new GenericTestExtends<LinkedList>();
// ge = new GenericTestExtends<HashMap>();
// 只能在List上面的类型
GenericTestExtends<? super List> ge2 = null;
// ge2 = new GenericTestExtends<ArrayList>();
ge2 = new GenericTestExtends<Object>();
GenericTestExtends<String> ge3 = new GenericTestExtends<String>();
ge3.setFoo("hello world !");
// GenericTestExtends<? extends Object> ge4 = ge3; //和一句下面一样
GenericTestExtends<?> ge4 = ge3;
System.out.println(ge4.getFoo());
ge4.setFoo(null);
System.out.println(ge4.getFoo());
/**
* 使用<?>或者<? extends SomeClass>的声明方式,意味着您只能
* 通过该名称来取得所参考实例的信息,或者是移除某些信息,但不能增加它的
* 信息,因为只知道当中放置的是SomeClass的子类,但不一定是什么类的实例
* ,编译器不让您加入信息,理由是,如果可以加入信息的话,那么您旧的记得取回的
* 实例是什么类型,让后转换为原来的类型方可进行操作,这就失去了使用泛型的意义。
*/
// ge4.setFoo("welcome!");
} | 3 |
@Override
public void mousePressed(final MouseEvent e) {
// if handler is clicked don't do anything
for (final Element el : getGraphicPanel().getSelectionManager().getSelectedElements()) {
if (el.getComponent().getHandlers().isHandlerAt(e.getPoint())) {
System.out.println("Handler hit");
return;
}
}
final Element el = getGraphicPanel().getElementAt(e.getPoint());
if (el != null) {
System.out.println("Element hit");
if (!getGraphicPanel().getSelectionManager().isElementSelected(el)) {
getGraphicPanel().getSelectionManager().clearSelection();
getGraphicPanel().getSelectionManager().addToSelection(el);
AppCore.getInstance().updateDetails(el.getDetails());
}
}
if (el == null) {
getGraphicPanel().getSelectionManager().clearSelection();
AppCore.getInstance().updateDetails(getPanel().getProcess().getDetails());
}
getGraphicPanel().repaint();
} | 5 |
public boolean isBlockTile(Block block) {
Set<Integer> tilesKeys = tilesLocations.keySet();
SerializableLocation blockLocation = new SerializableLocation(block.getLocation());
for(Integer key : tilesKeys) {
for(int i = 0; i < tilesLocations.get(key).size(); ++i) {
SerializableLocation keyBlockLocation = tilesLocations.get(key).get(i);
if(blockLocation.equals(keyBlockLocation))
return true;
}
} return false;
} | 3 |
public boolean checkhit(Coord c) {
init();
if (spr != null)
return (spr.checkhit(c));
return (false);
} | 1 |
@Override
public void keyReleased(KeyEvent arg0)
{
if (arg0.getKeyCode() == KeyEvent.VK_W || arg0.getKeyCode() == KeyEvent.VK_A || arg0.getKeyCode() == KeyEvent.VK_S || arg0.getKeyCode() == KeyEvent.VK_D)
{
if (arg0.getKeyCode() == KeyEvent.VK_W)
{
playerAction("halt", "U");
}
if (arg0.getKeyCode() == KeyEvent.VK_A)
{
playerAction("halt", "L");
}
if (arg0.getKeyCode() == KeyEvent.VK_S)
{
playerAction("halt", "D");
}
if (arg0.getKeyCode() == KeyEvent.VK_D)
{
playerAction("halt", "R");
}
}
if (arg0.getKeyCode() == KeyEvent.VK_K)
{
playerAction("stop_defend", Model.getInstance().findUnitByID(LocalModel.getInstance().getMyPlayerID(), LocalModel.getInstance().getUnitTypeDeclaration()).getDirection());
}
} | 9 |
public void update(GameContainer gc, Player player, int deltaT) {
float rotateSpeed = 0.06f;
Input input = gc.getInput();
if (input.isKeyDown(Input.KEY_Q) && angle < 90) {
angle += rotateSpeed * deltaT;
} else if (input.isKeyDown(Input.KEY_E) && angle > 2) {
angle -= rotateSpeed * deltaT;
}
x = Math.round(player.x*16+8);
y = Math.round(player.y*16+8);
} | 4 |
public boolean equals(Vector3f r) {
return x == r.getX() && y == r.getY() && z == r.getZ();
} | 2 |
public Entradas getEntradasIdEntrada() {
return entradasIdEntrada;
} | 0 |
public synchronized void actualiza(long tiempoTranscurrido) {
if (cuadros.size() > 1) {
tiempoDeAnimacion += tiempoTranscurrido;
if (tiempoDeAnimacion >= duracionTotal) {
tiempoDeAnimacion = tiempoDeAnimacion % duracionTotal;
indiceCuadroActual = 0;
}
while (tiempoDeAnimacion > getCuadro(indiceCuadroActual).tiempoFinal) {
indiceCuadroActual++;
}
}
} | 3 |
@Override
public void pop() {
if (amount != 0) {
for (int i = 0; i < amount + 1; i++) {
stack[i] = stack[i + 1];
}
amount--;
}
} | 2 |
private static List<URL> getJarUrls(String jarString, Shell shell) {
String[] jars = jarString.split(";");
List<URL> urls = new ArrayList<URL>();
if (jars != null) {
for (int i = 0; i < jars.length; i++) {
String jar = jars[i];
if (jar != null && !"".equals(jar.trim())) {
try {
URL url = new URL("file:" + jar);
urls.add(url);
} catch (MalformedURLException e) {
MessageDialog.openError(shell, "Jar File Error",
"Error in jar file path specified in preferences. file: "
+ jar);
}
}
}
}
return urls;
} | 5 |
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
GUI.init();
System.out.println("...SOS...");
String in = GUI.askString("Connection setup", "To join a game, type an ip address. To host one, type \"host\"");
Render.loadStep = "Loading resources...";
new Thread(new ClientTickerThread(), "Client Ticker Thread").start();
ResourceContainer.load();
while(!initialized) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
initialized = false;
if(in.equalsIgnoreCase("host")) {
Render.loadStep = "Hosting a game...";
new Thread(new ServerThread(), "Server Thread").start();
isServer = true;
ServerData.world.isRemote = false;
while(!initialized) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
initialized = false;
/*for(byte i = 0; i <50; i ++){
ServerData.world.objects[i] = new Projectile(4000,1000+Math.random()*4000,ServerData.world,(byte)i, -5,-5);
}*/
ServerData.world.ships[5] = new Ship(400,500,0,ServerData.world, (byte) 5);
//ServerData.world.ships[5].velX = 0;
ServerData.world.ships[5].velRot = 0;
ServerData.world.ships[6] = new Ship(700,3000,0,ServerData.world, (byte) 6);
//ServerData.world.ships[0].velX = 0;
ServerData.world.ships[6].velRot = 0;
ShipPresets.loadDefault(ServerData.world.ships[5]);
ShipPresets.loadDefault(ServerData.world.ships[6]);
SoundHandler.playSound("/sound/effects/blip1.wav");
new Thread(new TickerThread(), "Ticker Thread").start();
Config.address = "localhost";
} else {
Config.address = in;
}
Render.loadStep = "Connecting to "+Config.address+"...";
try{
Config.server = InetAddress.getByName(Config.address);
new Thread(new ClientThread(), "Client Thread").start();
while(!initialized) {
Render.loadspeed+=0.15;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
SoundHandler.playSound("/sound/effects/blip1_space.wav");
} catch (Exception e) {
SoundHandler.playSound("/sound/effects/error1.wav");
JOptionPane.showMessageDialog(null, "Could not connect to "+in+", maybe you mistyped?", "Connection error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
} | 8 |
public static Borne getBorneById(int id_borne) {
Borne borne = null;
Statement stat;
try {
stat = ConnexionDB.getConnection().createStatement();
stat.executeUpdate("use nemovelo");
ResultSet res = stat.executeQuery("select * from borne where id_borne="+ id_borne);
int fk_id_station;
String serialNumber, etat;
while (res.next()) {
id_borne = res.getInt("id_borne");
serialNumber = res.getString("serialNumber");
etat = res.getString("etat");
fk_id_station = res.getInt("fk_id_station");
borne = new Borne(id_borne, serialNumber, etat, fk_id_station);
}
} catch (SQLException e) {
while (e != null) {
System.out.println(e.getErrorCode());
System.out.println(e.getMessage());
System.out.println(e.getSQLState());
e.printStackTrace();
e = e.getNextException();
}
}
return borne;
} | 3 |
@Override
public String toString() {
StringBuilder movieString = new StringBuilder();
Iterator<String> it = keywords.iterator();
Iterator<String> actorIterator = actorList.iterator();
movieString.append("-Movie- \n").append("director: ").append(director).append('\n');
movieString.append("# scenes: ").append(sceneNum).append('\n');
movieString.append("cast: ");
while (actorIterator.hasNext()) {
String s = actorIterator.next();
movieString.append(s);
if (actorIterator.hasNext()) {
movieString.append(',');
}
}
movieString.append('\n');
movieString.append("title: ").append(title).append('\n');
movieString.append("keywords: ");
while (it.hasNext()) {
String s = it.next();
movieString.append(s);
if (it.hasNext()) {
movieString.append(',');
}
}
movieString.append('\n');
movieString.append('\n');
return movieString.toString();
} | 4 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PingMessage other = (PingMessage) obj;
if (correlationId == null) {
if (other.correlationId != null)
return false;
} else if (!correlationId.equals(other.correlationId))
return false;
if (_id == null) {
if (other._id != null)
return false;
} else if (!_id.equals(other._id))
return false;
return true;
} | 9 |
public void insertWord(String word) {
//Start at root
TrieNode curNode = root;
//loop through each char in the string
for (char c : word.toCharArray()) {
//get the index of where the string should be stored in the children array
int index = getIndex(c);
//if -1 then the char is invalid
if (index != -1) {
/*
*if the child at that index is null then assign a new TreeNode with
*the current char and set its parents to the curNode
*/
if (curNode.children[index] == null) {
curNode.children[index] = new TrieNode(c);
curNode.children[index].parent = curNode;
}
/*If the child is not null, set isleaf to false and set curNode to the child*/
if (curNode.children[index] != null) {
curNode.isLeaf = false;
curNode = curNode.children[index];
}
}
}
//set the curNode as a word = true
curNode.isWord = true;
} | 4 |
private void gameKeyPressed(int key){
switch(key){
case KeyEvent.VK_W:
//UP
break;
case KeyEvent.VK_S:
//DOWN
break;
case KeyEvent.VK_A:
//LEFT
mainModel.wilbert.moveLeft();
break;
case KeyEvent.VK_D:
//RIGHT
mainModel.wilbert.getBody().applyLinearImpulse(new Vec2(0.01f, 0.0f),mainModel.wilbert.getBody().getPosition());
break;
case KeyEvent.VK_SPACE:
//JUMP
break;
case KeyEvent.VK_H:
//ACTION 1 (punch or hit with object in hand)
break;
case KeyEvent.VK_J:
//ACTION 2
break;
case KeyEvent.VK_K:
//ACTION 3 (kick)
break;
case KeyEvent.VK_L:
//ACTION 4
break;
}
} | 9 |
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof Pair)) {
return false;
} else {
Pair<?, ?> oP = (Pair<?, ?>) o;
return (key == null ?
oP.getKey() == null :
key.equals(oP.getKey())) &&
(value == null ?
oP.getValue() == null :
value.equals(oP.getValue()));
}
} | 9 |
public final Hashtable<Integer,Integer> distributionOff() {
final Hashtable<Integer,Integer> offd = new Hashtable<Integer,Integer>();
for (int m=0; m<this.m; m++) {
final Integer key = off[m].size();
Integer value = offd.get(key);
if (value==null) offd.put(key, value);
else value++;
}
return offd;
} | 2 |
* @param row
* The row of the bracket to match.
* @param col
* The column of the bracket to match.
* @param match
* The BracketMatch instance for this match attempt.
*/
private void findMatchForward(int row, int col, BracketMatch match) {
int y = row;
int blockType = 0;
StringBuilder sb = code.getsb(y);
// Figure out what kind of block we're in, if any.
ArrayList<TokenMarkerInfo> tmall = marker.getStyles(code.get(y));
int offset;
for (offset = 0; offset < tmall.size(); offset++) {
TokenMarkerInfo tm = tmall.get(offset);
if (col < tm.startPos) {
break; // The blocks have skipped us.
}
if (col >= tm.startPos && col < tm.endPos) {
blockType = tm.blockHash;
break;
}
}
if (subFindMatchForward(match, sb, tmall, offset, col, blockType, y)) {
return;
}
for (y++; y < code.size(); y++) {
tmall = marker.getStyles(code.get(y));
if (subFindMatchForward(match, code.getsb(y), tmall, 0, 0, blockType, y)) {
return;
}
}
} | 7 |
public static void hm_main(String args[]){
int map_type = Integer.parseInt(args[0]);
int NUM_THREADS = Integer.parseInt(args[1]);
int init_capacity = Integer.parseInt(args[2]);
int load = Integer.parseInt(args[3]);
System.out.println("Running with " + NUM_THREADS + " threads.");
System.out.println("Running with " + init_capacity + " capacity.");
if(load == 0){
System.out.println("Running with 90% get, 5% put, 5% remove.");
}
else{
System.out.println("Running with 34% get, 33% put, 33% remove.");
}
HM<Integer, String> map;
if(map_type == 0){
System.out.println("Running a Flat-Combining map");
map = new FCHM<Integer, String>(init_capacity);
}
else if (map_type == 1){
System.out.println("Running a Fine Grained map");
map= new FGHM<Integer, String>(init_capacity);
}
else if (map_type == 2){
System.out.println("Running ConcurrentHashMap");
map= new CHM<Integer, String>(init_capacity);
}
else if (map_type == 3){
System.out.println("Running a Non Blocking map (by Cliff Click)");
map= new NonBlockingHashMap<Integer, String>(init_capacity);
}
else{
System.out.println("Running a Lock Free map (Split Order)");
map= new LFHM<Integer, String>(init_capacity);
}
//FCHM<Integer, String> map= new FCHM<Integer, String>(50);
//FGHM<Integer, String> map= new FGHM<Integer, String>(50);
AtomicLong throughput = new AtomicLong(0);
CyclicBarrier bar = new CyclicBarrier(NUM_THREADS);
HMThread[] threads = new HMThread[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; i++){
threads[i] = new HMThread(map, throughput, bar, load);
threads[i].start();
}
for(HMThread thread : threads){
try {
thread.join();
} catch (InterruptedException e) {
System.err.println("Thread interrupted.");
e.printStackTrace();
}
}
System.out.println("Threads finished with: " + throughput.get());
} | 8 |
@Test
public void test_insertions() {
int m = 3;
int n = 5;
Matrix m1 = new MatrixArrayList(m, n);
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++)
m1.insert(i, j, (double) (i * j));
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++)
assertEquals(m1.get(i, j), (double) (i * j), 0.01);
}
} | 4 |
public boolean GetHasMemory()
{
return hasMemory;
} | 0 |
public static void generateNewPopulation( Individual[] pop )
{
sumFitness = 0;
for( int i=0; i<POPULATION_SIZE; i++ )
sumFitness += pop[i].fitness;
generation[ currentGeneration++ ] = sumFitness / POPULATION_SIZE;
Individual[] tempGen = new Individual[POPULATION_SIZE];
for( int i=0; i<POPULATION_SIZE; i++ )
{
tempGen[i] = new Individual( pop[ select(sumFitness) ], pop[ select(sumFitness) ] );
if( Math.random() < MUTATION_RATE )
tempGen[i].genotype[ (int) Math.random() * GENOME_SIZE ] = Math.abs( tempGen[i].genotype[ (int) Math.random() * GENOME_SIZE ] - 1 );
}
population = tempGen;
} | 3 |
public void keyPressed(final KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT)
moveXcoord = -game.speed;
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
moveXcoord = game.speed;
if (e.getKeyCode() == KeyEvent.VK_UP)
moveYcoord = -game.speed;
if (e.getKeyCode() == KeyEvent.VK_DOWN)
moveYcoord = game.speed;
} | 4 |
private void strize(){
for(int i=0; i<m;i++)
{
stolbiki[i] = new Stolbec(n);
for(int j=0; j<n; j++){
stolbiki[i].setone(j, stroki[j].get(i) );
}
}
} | 2 |
public int countSquares(String[] field){
n = field.length;
m = field[0].length();
map = field;
int result = 0;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
for(int u=i; u<n; u++){
for(int v=j+1; v<m; v++){
if(different(i,j,u,v)) continue;
int x=u-i, y=v-j;
int ii=i+y, jj=j-x;
if(!valid(ii,jj) || different(i,j,ii,jj)) continue;
int uu=u+y, vv=v-x;
if(!valid(uu,vv) || different(i,j,uu,vv)) continue;
result++;
}
}
}
}
return result;
} | 9 |
public static Polynomial getIrreducible(final int degree, final int start) {
int test = start;
Polynomial polynomial = new Polynomial(test);
while(polynomial.getWeight() % 2 == 0 || !polynomial.isMonomial() || polynomial.getDegree() < degree || !polynomial.isIrreducible()) {
test++;
polynomial = new Polynomial(test);
if(polynomial.getDegree() > degree) {
return null;
}
}
return polynomial;
} | 5 |
private void helpPressed() {
if (getTray() == null ||
fHelpButton != null && fHelpButton.getSelection()) { // help button was not selected before
if (getShell() != null) {
Control c = getShell().getDisplay().getFocusControl();
while (c != null) {
if (c.isListening(SWT.Help)) {
c.notifyListeners(SWT.Help, new Event());
break;
}
c = c.getParent();
}
if (fHelpButton != null && getTray() != null) {
fHelpButton.setSelection(true);
}
}
} else {
closeTray();
}
} | 8 |
@Override
public boolean hasNext() {
return Math.abs( x - line.getX2()) > 0.9 || ( Math.abs(y - line.getY2()) > 0.9);
} | 1 |
public static boolean isVersionLessThan(String isThis, String lessThanThis){
int A[] = parseVersion(isThis);
int B[] = parseVersion(lessThanThis);
if(A[0] < B[0]){
return true;
}
if(A[0] == B[0]){
if(A[1] < B[1]){
return true;
}
if(A[1] == B[1]){
if(A[2] < B[2]){
return true;
}
if(A[2] == B[2]){
if(A[3] < B[3]){
return true;
}
return false;
}
return false;
}
return false;
}
return false;
} | 7 |
public static PartitionMetadata findLeader(Collection<BrokerReference> replicaBrokers, Collection<BrokerReference> seedBrokers, String topicId, int partitionId) {
PartitionMetadata returnMetaData = null;
loop:
for (BrokerReference seed : seedBrokers) {
SimpleConsumer consumer = null;
try {
consumer = new SimpleConsumer(seed.getHostname(), seed.getPort(), 100000, 64 * 1024, "leaderLookup");
List<String> topics = Collections.singletonList(topicId);
TopicMetadataRequest req = new TopicMetadataRequest(topics);
TopicMetadataResponse resp = consumer.send(req);
List<TopicMetadata> metaData = resp.topicsMetadata();
for (TopicMetadata item : metaData) {
for (PartitionMetadata part : item.partitionsMetadata()) {
if (part.partitionId() == partitionId) {
returnMetaData = part;
break loop;
}
}
}
} catch (Exception e) {
System.out.println("Error communicating with Broker [" + seed + "] to find Leader for [" + topicId
+ ", " + partitionId + "] Reason: " + e);
} finally {
if (consumer != null) consumer.close();
}
}
if (returnMetaData != null) {
replicaBrokers.clear();
for (kafka.cluster.Broker replica : returnMetaData.replicas()) {
replicaBrokers.add(new BrokerReference(replica.host(), replica.port()));
}
}
return returnMetaData;
} | 8 |
static Object redirect(Object proxy, InvocationHandler handler, Method m, Object... args) throws Throwable
{
try
{
return handler.invoke(proxy, m, args);
}
catch(Throwable t)
{
if(t == null)
{
throw new Exception("An exception was here, but apparently it decided to go away.");
}
if((t instanceof RuntimeException) || (t instanceof Error))
{
throw t;
}
for(Class c : m.getExceptionTypes())
{
if(c.isInstance(t))
{
throw t;
}
}
throw new UndeclaredThrowableException(t);
}
} | 6 |
public void move(int Direction , int Delta) {
if(y < Game.HEIGHT - 32) {
if(Direction == 3) {
dir = 3;
y += pace;
currentLengthD += pace;
}
}
if(x > 0) {
if(Direction == 1) {
dir = 1;
x -= pace;
currentLengthL += pace;
}
}
if(x < Game.WIDTH - 32) {
if(Direction == 2) {
dir = 2;
x += pace;
currentLengthR += pace;
}
}
if(y > 0) {
if(Direction == 0) {
dir = 0;
y -= pace;
currentLengthU += pace;
}
}
} | 8 |
public FillResult tryFillCanvas(TextMetaInfo textInfo,
StyleConfig styleConfig) {
FillResult result = new FillResult();
int maxCanvasHeight = styleConfig.getCanvasHeight();
// 所有textLine取出来,算出最高的
// 在这里用set过滤掉指向相同文本的textLine,相同文字的图片块在画布上只绘制一次
Set<TextLine> textLineList = new HashSet<TextLine>();
int maxLineHeight = Integer.MIN_VALUE;
for (Entry<String, TextField> textFieldentry : textInfo
.getTextFieldMap().entrySet()) {
for (TextLine textLine : textFieldentry.getValue().getTextLines()) {
if (textLine.getHeight() > maxLineHeight) {
maxLineHeight = textLine.getHeight();
}
textLineList.add(textLine);
}
}
// 按高度区间分类,每个区间最高为上一区间最高值的一半
Map<Integer, List<TextLine>> textLineListMap = new HashMap<Integer, List<TextLine>>();
for (TextLine textLine : textLineList) {
int height = maxLineHeight;
while (textLine.getHeight() <= height / 2) {
height = height / 2;
}
List<TextLine> list = textLineListMap.get(height);
if (list == null) {
list = new ArrayList<TextLine>();
textLineListMap.put(height, list);
}
list.add(textLine);
}
// 为每个区间排序
for (Entry<Integer, List<TextLine>> entry : textLineListMap.entrySet()) {
Collections.sort(entry.getValue(), new Comparator<TextLine>() {
@Override
public int compare(TextLine o1, TextLine o2) {
return o2.getWidth() - o1.getWidth();
}
});
}
// 算画布宽度
int maxWidth = _calculateMaxWidth(textInfo, styleConfig);
// 填充
List<CanvasInfo> canvasList = _fill(textLineListMap, maxLineHeight,
maxWidth, maxCanvasHeight);
result.setCanvasInfoList(canvasList);
result.setTextInfo(textInfo);
return result;
} | 7 |
public void configureAndShow(JoeTree tree) {
configure(tree);
super.show();
} | 0 |
private void btn_eliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_eliminarActionPerformed
final int row = this.table_ticket.getSelectedRow();
if (row >= 0) {
final Ticket tic = this.tableTicketModel.getTicket(row);
int i = JOptionPane.showConfirmDialog(this, "¿Desea eliminar el ticket: " +tic.getTicket() + "?", "Eliminar registro", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (i == 0) {
this.progress_bar.setVisible(true);
new Thread(new Runnable() {
@Override
public void run() {
try {
tableTicketModel.eliminarTicket(tic, row);
actualizarTabla();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Ha ocurrido un error , el registro no se pudo eliminar.");
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progress_bar.setVisible(false);
}
});
}
}).start();
}
}else{
JOptionPane.showMessageDialog(null, "Seleccione el ticket a eliminar");
}
}//GEN-LAST:event_btn_eliminarActionPerformed | 3 |
public static void testDictionary(String apiKey) throws NetworkException, AnalysisException {
DictionaryManager dictionaryManager = new DictionaryManager(apiKey);
// Delete all dictionaries in our account.
{
for (Dictionary dict : dictionaryManager.allDictionaries()) {
System.out.println("Deleting current dictionary: " + dict.getId());
dictionaryManager.deleteDictionary(dict);
}
}
// Create a new dictionary
Dictionary newDict = Dictionary.builder().setId("developers").build();
dictionaryManager.createDictionary(newDict);
Dictionary teamsDictionary = dictionaryManager.getDictionary("developers");
System.out.println("Got dict:");
System.out.println(teamsDictionary.getId());
{
List<DictionaryEntry> newEntries = new ArrayList<DictionaryEntry>();
List<String> types = Arrays.asList("cpp_developer", "writer");
newEntries.add(DictionaryEntry.builder().setText("Bjarne Stroustrup").setId("DEV2").addData("types", types).build());
dictionaryManager.addEntries(newDict.getId(), newEntries);
}
// Loop over all entries in a specific dictionary
PagedAllEntries allEntries = dictionaryManager.allEntries(newDict.getId());
System.out.println("Dictionary contains : " + allEntries.getTotal() + " total entries.");
for (DictionaryEntry entry : allEntries.getEntries()) {
System.out.println("Dictionary entry in 'developers':");
System.out.println(entry.getId() + " " + entry.getText());
}
// Retrieve them directly by ID
{
DictionaryEntry entry = dictionaryManager.getEntry(newDict.getId(), "DEV2");
System.out.println("Entry text: " + entry.getText());
}
// Try extracting the new entry from some sample text.
TextRazor client = new TextRazor(apiKey);
client.setEntityDictionaries(Arrays.asList(newDict.getId()));
client.addExtractor("entities");
AnalyzedText response = client.analyze("Although it is very early in the process, higher-level parallelism is slated to be a key theme of the next version of C++, says Bjarne Stroustrup");
for (Entity entity : response.getResponse().getEntities()) {
String customEntityId = entity.getCustomEntityId();
if (null != customEntityId) {
System.out.println("Found custom entity: " + customEntityId);
for (String type : entity.getData().get("types")) {
System.out.println("Type: " + type);
}
}
}
} | 5 |
public void delLines(int[] indexRows)
{
// modif bellier.l - merci pour le code
//la fonction remove d'une arraylist effectue également un rétractage
//indiceRow contient des indices "erronés" d'où l'intéret de delay
for (int i = indexRows.length - 1; i >=0 ; i--) {
observable.notifyObservers(new ArgObserverTable(
ArgObserverTable.DELETE, (String) rows.get(indexRows[i])[1]));
rows.remove(indexRows[i]);
}
//Actualise le tableau
fireTableDataChanged();
} | 1 |
@Override
public BeerReadOnly getBeer(String beerId) {
return persistenceService.get(beerId);
} | 0 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Mitglied)) {
return false;
}
Mitglied other = (Mitglied) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} | 5 |
public static void main(String[]args){
FabrykaKomputerow fabrykaKomputerow = new FabrykaKomputerow();
System.out.println("PC");
Komputer pc = fabrykaKomputerow.wydajKomputer("PC");
System.out.println("\n\nLaptop");
Komputer laptop = fabrykaKomputerow.wydajKomputer("Laptop");
} | 0 |
public void addEvent(Event e)
{
events.add(e);
} | 0 |
public static Map<String, String> simpleCommandLineParser(String[] args) {
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i <= args.length; i++) {
String key = (i > 0 ? args[i - 1] : null);
String value = (i < args.length ? args[i] : null);
if (key == null || key.startsWith("-")) {
if (value != null && value.startsWith("-"))
value = null;
if (key != null || value != null)
map.put(key, value);
}
}
return map;
} | 9 |
public static boolean wordBreak(String s, Set<String> dict) {
if(dict.size() <=0) return false;
Pattern pattern;
Matcher matcher;
Iterator<String> iterator=dict.iterator();
while(iterator.hasNext()){
pattern=Pattern.compile(iterator.next());
matcher= pattern.matcher(s);
s=matcher.replaceAll("");
}
if(s.equals(""))
return true;
return false;
} | 3 |
public final void setUnitPrice(double unitPrice) {
if(unitPrice < 0) {
throw new IllegalArgumentException();
}
this.unitPrice = unitPrice;
} | 1 |
@Basic
@Column(name = "CSA_CANTIDAD")
public int getCsaCantidad() {
return csaCantidad;
} | 0 |
public void validate(final Object object, final Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "Cannot be empty", "Cannot be empty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "description", "Cannot be empty", "Cannot be empty");
} | 0 |
@Override
public Dimension getPreferredContentSize() {
int width = 0;
int height = 0;
int dividerHeight = getRowDividerHeight();
for (TreeRow row : new TreeRowViewIterator(this, mRoot.getChildren())) {
height += getRowHeight(row) + dividerHeight;
}
for (TreeColumn column : mColumns) {
width += column.getWidth();
}
int size = mColumns.size() - 1;
if (size > 0) {
width += size * getColumnDividerWidth();
}
return new Dimension(width, height);
} | 3 |
public Productos() {
initComponents();
mostrarProductosTabla();
} | 0 |
public Production[] getAnswer()
{
/* Collections.sort(myAnswer, new Comparator<Production>(){
public int compare(Production o1, Production o2) {
return (o2.getRHS().length()-o1.getRHS().length());
}
});
*/
Production[] answer=new Production[myAnswer.size()];
for (int i=0; i<myAnswer.size(); i++)
{
answer[i]=myAnswer.get(i);
}
return answer;
} | 1 |
public void connect() {
MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
//builder.socketTimeout(0);
builder.socketKeepAlive(true);
boolean notConnected = true;
while (notConnected && !shutdown) {
try {
Utils.printWithDate("Connect to MongoDB at " + hostname + " (Port " + port + ") ... ", Utils.DEBUGLEVEL.GENERAL);
mongoClient = new MongoClient( new ServerAddress(hostname, port), builder.build() );
//cause exceptions if database is not open
mongoClient.getDatabaseNames();
notConnected = false;
} catch (Exception e) {
if (shutdown) return;
Utils.printWithDate("MongoDB: could not connect to " + hostname + "; retrying ...", Utils.DEBUGLEVEL.WARNING);
}
}
if (shutdown) return;
Utils.printWithDate("connected", Utils.DEBUGLEVEL.GENERAL);
isConnected = true;
} | 5 |
@Test
public void testSphereColliding(){
// spheres at an arbitrary location and is obviously not colliding
Sphere s4441 = new Sphere(new Vector3f(4.0f,4.0f,4.0f),1.0f);
Sphere s8881 = new Sphere(new Vector3f(8.0f,8.0f,8.0f),1.0f);
Sphere s0004 = new Sphere(new Vector3f(),4.0f);
Sphere s0505051 = new Sphere(new Vector3f(0.5f,0.5f,0.5f),1.0f);
Sphere s050501 = new Sphere(new Vector3f(0.5f,0.5f,0.0f),1.0f);
assertFalse(GJKSimplex.isColliding(s4441, SphereTest.UNIT_SPHERE));
// Order shouldn't matter for detection
assertFalse(GJKSimplex.isColliding(SphereTest.UNIT_SPHERE, s4441));
assertFalse(GJKSimplex.isColliding(s4441, s050501));
assertFalse(GJKSimplex.isColliding(s4441, s0505051));
// According to the simplex algorithm two of the same object should be colliding
// We handle this before we test them against each other to keep the detection simpler
assertTrue(SphereTest.UNIT_SPHERE.isColliding(SphereTest.UNIT_SPHERE));
assertEquals(SphereTest.UNIT_SPHERE.isColliding(SphereTest.UNIT_SPHERE), GJKSimplex.isColliding(SphereTest.UNIT_SPHERE, SphereTest.UNIT_SPHERE));
assertEquals(s4441.isColliding(s4441),GJKSimplex.isColliding(s4441, s4441));
// partially colliding Spheres
assertTrue(GJKSimplex.isColliding(SphereTest.UNIT_SPHERE, s0505051));
assertTrue(GJKSimplex.isColliding(s0505051,SphereTest.UNIT_SPHERE));
// Partially Colliding
assertTrue(GJKSimplex.isColliding(s050501, s0505051));
// non unit radius
assertTrue(GJKSimplex.isColliding(SphereTest.UNIT_SPHERE, s0004));
assertFalse(GJKSimplex.isColliding(s4441, s0004));
assertFalse(GJKSimplex.isColliding(s0004,s8881));
// NOTE the case of 0 radius and 0 distance of each other is undefined, the algorithms differ with their interpretation
for(int range = 1; range < 64; range++){
for(int i = 0; i < 64; i++){
Sphere sphere1 = new Sphere(Vector3Test.getRandom(range),gen.nextFloat() * range / 64.0f);
Sphere sphere2 = new Sphere(Vector3Test.getRandom(range),gen.nextFloat() * range / 64.0f);
try {
assertEquals(sphere1.isColliding(sphere2),GJKSimplex.isColliding(sphere1, sphere2));
assertEquals(sphere2.isColliding(sphere1),GJKSimplex.isColliding(sphere2, sphere1));
} catch (AssertionError e){
System.err.println(e);
System.err.println("Distance " + sphere1.distance(sphere2));
System.err.println(sphere1);
System.err.println(sphere2);
throw e;
}
}
//System.out.print(".");
}
} | 3 |
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_P) { //Presiono letra P
pausa = !pausa; //cambio valor de pausa
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) { //Presiono flecha izquierda
barra.setDireccion(1);
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) { //Presiono flecha derecha
barra.setDireccion(2);
}
if (Ajustes && e.getKeyCode() == KeyEvent.VK_S) { //Presiono tecla S
sonido = !sonido;
}
if (Ajustes && e.getKeyCode() == KeyEvent.VK_M) { //Presiono tecla M
musica = !musica;
}
} | 7 |
private int readUInt8(byte[] uint16, int offset) throws IOException {
int b0 = uint16[0 + offset] & 0x000000FF;
return b0;
} | 0 |
public static Tree decisionTreeLearning(
ArrayList<HashMap<String, String>> examples,
ArrayList<String> attributes, String goalAttribute,
HashMap<String, String[]> attributeValues,
ArrayList<HashMap<String, String>> parentExamples) {
print("Attributes: " + attributes);
print("Examples: " + examples);
if (examples.isEmpty()) {
print("examples.isEmpty()\n");
return new Tree(new GoalNode(pluralityValue(parentExamples,
goalAttribute)));
} else if (hasSameClassifications(examples, goalAttribute)) {
print("hasSameClassifications(examples)\n");
return new Tree(new GoalNode(examples.get(0).get(goalAttribute)));
} else if (attributes.size() == 1) {
print("attributes.isEmpty()\n");
return new Tree(new GoalNode(
pluralityValue(examples, goalAttribute)));
}
String A = "";
double largestImportance = -1;
for (int i = 0; i < attributes.size() - 1; i++) {
String attr = attributes.get(i);
double importance = Importance2.informationGain(attr, examples,
attributeValues, goalAttribute);
print("A: " + attr + "\timportance: " + importance);
if (importance > largestImportance) {
largestImportance = importance;
A = attr;
}
}
print(A);
Tree tree = new Tree(new AttributeNode(A));
for (String vk : attributeValues.get(A)) {
ArrayList<HashMap<String, String>> exs = getExs(A, vk, examples);
ArrayList<String> attributesMinusA = cloneArrayList(attributes);
attributesMinusA.remove(A);
print("A: " + A);
print("vk: " + vk);
print("exs:" + exs);
print("attributesMinusA: " + attributesMinusA);
print("");
Tree subtree = decisionTreeLearning(exs, attributesMinusA,
goalAttribute, attributeValues, examples);
tree.appendSubtree(vk, subtree);
}
return tree;
} | 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.