text stringlengths 14 410k | label int32 0 9 |
|---|---|
public String findShortestPath(int id,String source,String target,
boolean reverse_cost ) {
String rTable = "road_profile_"+id;
StringBuffer sb = new StringBuffer();
JSONObject jobj = new JSONObject();
JSONObject jstat = new JSONObject();
JSONArray jfeats = new JSONArray();
int sCode = 200;
String sMessage = "Command completed successfully";
double len = 0d;
sb.append("select gid,class,name,cost,");
sb.append("st_length(the_geom::geography) as length,");
sb.append("st_asgeojson(st_linemerge(the_geom)) as the_geom ");
sb.append("from find_astar_sp('").append(source).append("','");
sb.append(target).append("',").append(RouteProperties.getBbox_sp());
sb.append(",'").append( rTable );
sb.append("',").append(RouteProperties.getDirected());
sb.append(",").append( reverse_cost ).append(")");
if( dbConn != null ) {
try {
Connection conn = dbConn.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sb.toString());
while( rs.next() ) {
JSONObject jfeat = new JSONObject();
JSONObject jcrs = new JSONObject();
JSONObject jcprop= new JSONObject();
JSONObject jprop = new JSONObject();
JSONObject jgeom = new JSONObject(rs.getString("the_geom"));
jcprop.put("code", RouteProperties.getSrid() );
jcrs.put("type", "EPSG");
jcrs.put("properties", jcprop);
jprop.put("id", rs.getDouble("gid"));
jprop.put("length", rs.getDouble("length"));
jprop.put("class", rs.getString("class"));
jprop.put("name", rs.getString("name"));
jprop.put("cost", rs.getDouble("cost"));
jfeat.put("crs", jcrs);
jfeat.put("geometry", jgeom);
jfeat.put("type", "Feature");
jfeat.put("properties", jprop);
jfeats.add(jfeat);
len += rs.getBigDecimal("length").doubleValue();
}
rs.close();
stmt.close();
conn.close();
}
catch(Exception ex) {
sCode = 400;
sMessage = "Database Query Error";
ex.printStackTrace();
}
}
else {
sCode = 400;
sMessage = "Database Connection Error";
}
try {
jstat.put("code", new Integer(sCode));
jstat.put("success", true);
jstat.put("message",sMessage);
jobj.put("type", "FeatureCollection");
jobj.put("features", jfeats);
jobj.put("total", new Double(len));
jobj.put("status",jstat);
}
catch( Exception e ) {
;
}
return jobj.toString();
} | 4 |
public boolean isAllCall() {
for(Player player : playerList) {
if((player.getState().equals(Player.States.WAIT))
|| (player.getActionChip() != state.getBetChip() && !player.getState().equals(Player.States.FOLD) && !player.getState().equals(Player.States.ALL_IN) && !player.getState().equals(Player.States.LOSE))){
return false;
}
}
return true;
} | 6 |
@Override public String toString(){
StringWriter aux = new StringWriter();
if (logType == LogType.EXCEPTION | logType == LogType.LEVEL_TIME_MESSAGE){
aux.write(separator);
aux.write("[" + level + "] - [" + time + "] --- " + message + "\n");
}
else if (logType == LogType.MESSAGE){
aux.write(message);
}
if (logType == LogType.EXCEPTION & exception != null){
aux.write("\tException:" + exception.getMessage() + "\n" + stackTraceString(exception));
}
if (logType == LogType.EXCEPTION | logType == LogType.LEVEL_TIME_MESSAGE){
aux.write(separator);
}
aux.write("\n");
return aux.toString();
} | 4 |
public static void main(String [] args){
Zegana.initalize(args);
if(quit)
return;
while(genCount != end){
genCount++;
simulate();
populate();
}
} | 2 |
public String NumbersCalculation(int i) {
String s=String.valueOf(i);
if (i==10)
s="0.";
if(checkCalculatorSequence(position -1) && position >0) {
if (isANumber(calculatorSequence.get(position - 1))){
if (i==10)
s=".";
setCalculatorSequence(position -1, calculatorSequence.get(position -1) + s);
}
else {
setCalculatorSequence(position, s);
}
}
else{
setCalculatorSequence(position, s);
}
if (i==10)
hasDot=true;
return getMessage();
} | 6 |
public void addScore(boolean onBeat, int bpm) {
if (lastScore < 1000 * 60 / bpm / 1.5f) {
lastScore = 0;
return;
}
if (onBeat) {
int scaleX = Level.getScaledX(level.getXPosition(), x);
int width = Level.getScaledX(level.getXPosition(), x + 1) - scaleX;
float scale = 1.0f / Constants.TILE_WIDTH * width;
accumulativeX += 5;
addEffect(new PlayerScoreEffect(getRenderCentreX(),
getRenderCentreY(), scale));
if (beatSound != null) {
beatSound.play();
}
}
lastScore = 0;
} | 3 |
public static String readFastaFile(String path)
{
Scanner sc;
try
{
sc = new Scanner(new File(path));
} catch (Exception e)
{
sc = new Scanner("");
}
String sequence;
StringBuilder sb = new StringBuilder();
if (sc.hasNextLine())
{
sc.nextLine();
}
while (sc.hasNextLine())
{
sb.append(sc.nextLine());
}
sequence = sb.toString();
sequence = sequence.replace("\n", "");
sequence = sequence.replaceAll("\\s+", "");
sc.close();
return sequence;
} | 3 |
public static double[] LineEquation (int x1, int y1, int x2, int y2)
{
double[] arr = new double[7];
// Cramer's Rule to solve system of equation ( 2 x 2 )
if (x1 - x2 != 0)
{
// y = ax + b
arr[0] = (double)(y1 - y2) / (double)(x1 - x2);
arr[1] = (double)(x1*y2 - y1*x2) / (double)(x1 - x2);
arr[2] = 0;
}
else
{
// line equation based on x = ay + b
arr[0] = 0;
arr[1] = x1;
arr[2] = 1;
}
if (x1 < x2)
{
arr[3] = x1;
arr[5] = x2;
arr[4] = y1;
arr[6] = y2;
}
else if (x1 > x2)
{
arr[3] = x2;
arr[5] = x1;
arr[4] = y2;
arr[6] = y1;
}
else if (x1 == x2)
{
if (y1 < y2)
{
arr[3] = x1;
arr[5] = x2;
arr[4] = y1;
arr[6] = y2;
}
else
{
arr[3] = x2;
arr[5] = x1;
arr[4] = y2;
arr[6] = y1;
}
}
return arr;
} | 5 |
public String[] query(String table, int ID, String nameID) {
String[] result = null;
try {
String stm = null;
stm = "select * from " + table + " WHERE " + nameID + " = " + ID + " order by " +nameID;
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement(stm);
rs = pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int n = rsmd.getColumnCount();
result = new String[n];
while (rs.next()) {
for (int j = 1; j <= n; j++) {
result[j - 1] = "" + rs.getString(j);
}
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(QueryMethod.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (pst != null) {
pst.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(QueryMethod.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
}
return result;
} | 6 |
@Override
public void keyTyped(KeyEvent e)
{
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
} | 0 |
public void checkLRBounds() {
if (getX() > 400)
setX(400);
if (getX() < -15)
setX(-15);
if (getY() < 10)
setY(10);
} | 3 |
public static List<Element> intArrToList(int[] arr) {
List<Element> elements = new ArrayList<Element>();
for(int i = 0; i < arr.length; i++){
Element elem = new Element(i, arr[i]);
elements.add(elem);
}
return elements;
} | 1 |
final boolean method954(int i, byte i_23_, int i_24_, r var_r) {
anInt1630++;
r_Sub2 var_r_Sub2 = (r_Sub2) var_r;
i_24_ += 1 + ((r_Sub2) var_r_Sub2).anInt10484;
if (i_23_ != 88)
aClass232ArrayArray1623 = null;
i += 1 + ((r_Sub2) var_r_Sub2).anInt10489;
int i_25_ = i_24_ * ((Class104) this).anInt1624 + i;
int i_26_ = ((r_Sub2) var_r_Sub2).anInt10487;
int i_27_ = ((r_Sub2) var_r_Sub2).anInt10482;
int i_28_ = -i_27_ + ((Class104) this).anInt1624;
if (i_24_ <= 0) {
int i_29_ = -i_24_ + 1;
i_26_ -= i_29_;
i_24_ = 1;
i_25_ += ((Class104) this).anInt1624 * i_29_;
}
if ((anInt1612 ^ 0xffffffff) >= (i_26_ + i_24_ ^ 0xffffffff)) {
int i_30_ = -anInt1612 + (1 + (i_24_ + i_26_));
i_26_ -= i_30_;
}
if ((i ^ 0xffffffff) >= -1) {
int i_31_ = -i + 1;
i_27_ -= i_31_;
i_25_ += i_31_;
i_28_ += i_31_;
i = 1;
}
if (((Class104) this).anInt1624 <= i - -i_27_) {
int i_32_ = -((Class104) this).anInt1624 + 1 + (i + i_27_);
i_27_ -= i_32_;
i_28_ += i_32_;
}
if (i_27_ <= 0 || (i_26_ ^ 0xffffffff) >= -1)
return false;
int i_33_ = 8;
i_28_ += (-1 + i_33_) * ((Class104) this).anInt1624;
return Class59_Sub1.method552(i_28_, i_26_, (byte) 112, i_33_, i_27_,
i_25_, ((Class104) this).aByteArray1617);
} | 7 |
public Collection<BookingEntity> getBookings() {
return bookings;
} | 0 |
public static int binarySearch(int[] array, int k) {
if(array==null || array.length==0) {
return -1;
}
int start = 0;
int end = array.length-1;
while(start <= end) {
// Attention: This is wrong way
// it fails if the sum of low and high
// is greater than the maximum positive
// int value
// int mid = (start + end)/2;
// Right way is:
int mid = start + (end-start)/2;
if(array[mid] == k) {
return mid;
} else if(array[mid] > k) {
end = mid - 1;
} else if(array[mid] < k) {
start = mid + 1;
}
}
return -1;
} | 6 |
public Categorie recalculerDerniereReponse(Reponse ancienneReponse) {
if (ancienneReponse.equals(getDerniereReponse())) {
derniereReponse = null;
for (Sujet sujet : getSujets()) {
if (getDerniereReponse() == null || sujet.getDerniereReponse().getTempsMillis() > getDerniereReponse().getTempsMillis()) {
this.derniereReponse = sujet.getDerniereReponse();
}
}
if (getCategorieParent() == null)
return this;
Categorie cat = getCategorieParent().recalculerDerniereReponse(ancienneReponse);
return cat != null ? cat : this;
}
return null;
} | 6 |
public List<OpenChatRoomDTO> getOpenChatRooms() {
List<OpenChatRoomDTO> openchatroomDTOs = new ArrayList<OpenChatRoomDTO>();
List<Openchatroom> openchatrooms = new OpenchatroomDAO().readAll();
int participantsCounter = 0;
String currentPerformer = null;
for (Openchatroom openchatroom : openchatrooms) {
if (! openchatroom.getUserName().equals(currentPerformer)) {
if (currentPerformer != null) {
OpenChatRoomDTO openChatRoomDTO = new OpenChatRoomDTO();
openChatRoomDTO.setPerformer(currentPerformer);
openChatRoomDTO.setNumberOfParticipants(participantsCounter);
openchatroomDTOs.add(openChatRoomDTO);
}
currentPerformer = openchatroom.getUserName();
participantsCounter = 1;
} else {
participantsCounter++;
}
}
if (currentPerformer != null) {
OpenChatRoomDTO openChatRoomDTO = new OpenChatRoomDTO();
openChatRoomDTO.setPerformer(currentPerformer);
openChatRoomDTO.setNumberOfParticipants(participantsCounter);
openchatroomDTOs.add(openChatRoomDTO);
}
return openchatroomDTOs;
} | 4 |
public int length() {
return this.map.size();
} | 0 |
public static void paintFocus(Graphics2D g, Shape shape, int pixelSize) {
Color focusColor = getFocusRingColor();
Color[] focusArray = new Color[] {
new Color(focusColor.getRed(), focusColor.getGreen(), focusColor.getBlue(), 235),
new Color(focusColor.getRed(), focusColor.getGreen(), focusColor.getBlue(), 130),
new Color(focusColor.getRed(), focusColor.getGreen(), focusColor.getBlue(), 80)
};
if (JVM.usingQuartz) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
} else {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
}
g.setStroke(new BasicStroke((2 * pixelSize) + 1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.setColor(focusArray[2]);
g.draw(shape);
if (((2 * pixelSize) + 1) > 0) {
g.setStroke(new BasicStroke(((2 * pixelSize) - 2) + 1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.setColor(focusArray[1]);
g.draw(shape);
}
if ((((2 * pixelSize) - 4) + 1) > 0) {
g.setStroke(new BasicStroke(((2 * pixelSize) - 4) + 1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.setColor(focusArray[0]);
g.draw(shape);
}
} | 3 |
public OpenFileFormat getDefaultOpenFileFormat() {
return defaultOpenFileFormat;
} | 0 |
public String readAndVerifyMessage() {
byte[] message = null;
byte[] signature = null;
byte[] pubKeyEnc = null;
try {
// die Datei wird geoeffnet und die Daten gelesen
DataInputStream is = new DataInputStream(new FileInputStream(
fileName));
// die Laenge der Nachricht
int len = is.readInt();
message = new byte[len];
// die Nachricht
is.read(message);
// die Laenge der Signatur
len = is.readInt();
signature = new byte[len];
// die Signatur
is.read(signature);
// die Laenge des oeffentlichen Schluessels
len = is.readInt();
pubKeyEnc = new byte[len];
// der oeffentliche Schluessel
is.read(pubKeyEnc);
// Datei schliessen
is.close();
} catch (IOException ex) {
Error("Datei-Fehler beim Lesen der signierten Nachricht!", ex);
}
try {
// nun wird aus der Kodierung wieder ein public key erzeugt
KeyFactory keyFac = KeyFactory.getInstance("RSA");
// aus dem Byte-Array koennen wir eine X.509-Schluesselspezifikation
// erzeugen
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKeyEnc);
// und in einen abgeschlossene, providerabhaengigen Schluessel
// konvertieren
PublicKey pubKey = keyFac.generatePublic(x509KeySpec);
// Nun wird die Signatur ueberprueft
// als Erstes erzeugen wir das Signatur-Objekt
Signature rsaSig = Signature.getInstance("SHA1withRSA");
// zum Verifizieren benoetigen wir den oeffentlichen Schluessel
rsaSig.initVerify(pubKey);
// Daten fuer die kryptographische Hashfunktion (hier: SHA1) liefern
rsaSig.update(message);
// Signatur verifizieren:
// 1. Verschluesselung der Signatur (mit oeffentlichem RSA-Schluessel)
// 2. Vergleich des Ergebnisses mit dem kryptogr. Hashwert
boolean ok = rsaSig.verify(signature);
if (ok)
System.out.println("Signatur erfolgreich verifiziert!");
else
System.out.println("Signatur konnte nicht verifiziert werden!");
} catch (NoSuchAlgorithmException ex) {
Error("Es existiert keine Implementierung fuer RSA.", ex);
} catch (InvalidKeySpecException ex) {
Error("Fehler beim Konvertieren des Schluessels.", ex);
} catch (SignatureException ex) {
Error("Fehler beim ueberpruefen der Signatur!", ex);
} catch (InvalidKeyException ex) {
Error("Falscher Algorithmus?", ex);
}
// als Ergebnis liefern wir die urpspruengliche Nachricht
return new String(message);
} | 6 |
@Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == start) {
menu.dispose();
Game peli = new Game(setting.getDifficulty());
peli.run();
peli.gameStart();
}else if (ae.getSource() == contin) {
Game peli = new Game(setting.getDifficulty());
try {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("ohha/save.txt");
Scanner lukija = new Scanner(stream);
peli.setDifficulty(Integer.parseInt(lukija.nextLine()));
peli.setLevel(Integer.parseInt(lukija.nextLine()));
peli.run();
peli.getPlayer().setStrength(Integer.parseInt(lukija.nextLine()));
peli.getPlayer().setAttackSpeed(Integer.parseInt(lukija.nextLine()));
peli.getPlayer().setDefence(Integer.parseInt(lukija.nextLine()));
peli.getPlayer().setMaxHealth(Integer.parseInt(lukija.nextLine()));
peli.getPlayer().gainExperiencePoints(Integer.parseInt(lukija.nextLine()));
peli.getPlayer().gainSkillPoints(Integer.parseInt(lukija.nextLine()));
while(lukija.hasNextLine()) {
peli.getPlayer().addSkill(peli.getSkillMap().get(lukija.nextLine()));
}
}catch (Exception e) {
e.printStackTrace();
}
menu.dispose();
peli.gameStart();
}else if (ae.getSource() == settings) {
if (!menuCreated) {
setting.run();
menuCreated = true;
}else {
setting.asetaNakyvaksi();
setting.getFrame().setLocationRelativeTo(null);
}
}else if (ae.getSource() == quit) {
System.exit(0);
}
} | 7 |
public void visitFormalTypeParameter(final String name) {
declaration.append(seenFormalParameter ? ", " : "<").append(name);
seenFormalParameter = true;
seenInterfaceBound = false;
} | 1 |
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 |
private static final void packObjectSpawns() {
Logger.log("ObjectSpawns", "Packing object spawns...");
if (!new File("data/map/packedSpawns").mkdir())
throw new RuntimeException(
"Couldn't create packedSpawns directory.");
try {
BufferedReader in = new BufferedReader(new FileReader(
"data/map/unpackedSpawnsList.txt"));
while (true) {
String line = in.readLine();
if (line == null)
break;
if (line.startsWith("//"))
continue;
String[] splitedLine = line.split(" - ");
if (splitedLine.length != 2)
throw new RuntimeException("Invalid Object Spawn line: "
+ line);
String[] splitedLine2 = splitedLine[0].split(" ");
String[] splitedLine3 = splitedLine[1].split(" ");
if (splitedLine2.length != 3 || splitedLine3.length != 4)
throw new RuntimeException("Invalid Object Spawn line: "
+ line);
int objectId = Integer.parseInt(splitedLine2[0]);
int type = Integer.parseInt(splitedLine2[1]);
int rotation = Integer.parseInt(splitedLine2[2]);
WorldTile tile = new WorldTile(
Integer.parseInt(splitedLine3[0]),
Integer.parseInt(splitedLine3[1]),
Integer.parseInt(splitedLine3[2]));
addObjectSpawn(objectId, type, rotation, tile.getRegionId(),
tile, Boolean.parseBoolean(splitedLine3[3]));
}
in.close();
} catch (Throwable e) {
Logger.handle(e);
}
} | 8 |
public Admin(JPanel adminpanel, JPanel userpanel, JTextField[] userdata, JSlider months, JLabel[] errMess) {
this.errMess = errMess;
for (int i = 0; i < this.errMess.length; i++) {
this.errMess[i].setText("");
}
this.adminpanel = adminpanel;
this.adminpanel.removeAll();
this.userpanel = userpanel;
this.months = months;
this.userdata = userdata;
String[][] userList = null;
try {
//read the list of all users
userList = CSVHandling.readCSVStringArr2(Sims_1._usersFileName);
} catch (Exception e) {
e.printStackTrace();
}
if (!(userList == null)) {
for (int i = 0; i < userList.length; i++) {
try {
//add the users to Admin.users
users.add(new User(userList[i][0]));
} catch (Exception e) {
e.printStackTrace();
}
}
}
//init the array of buttons to open user-data
userButtons = new JButton[users.size()];
LinkedList<User> usersHelp = (LinkedList<User>) users.clone();
for (int i = 0; i < userButtons.length; i++) {
//display the username as button-label
userButtons[i] = new JButton(usersHelp.pop().getAccountname());
//set size of the buttons and the position in the panel
userButtons[i].setSize(150, 50);
userButtons[i].setLocation(10 + 160 * (i / 9), 80 + (i % 9) * 60);
userButtons[i].addActionListener(new AdminActionListener(i));
this.adminpanel.add(userButtons[i]);
userButtons[i].setVisible(true);
}
} | 6 |
protected RegularExpression getExpression() {
return environment.getExpression();
} | 0 |
private void prepareSignatures(
final Map<String, ByteClass> byteClasses,
final Multimap<String, String> rdepends,
final BiMap<String, String> nameMaps,
final BiMap<Signature, Signature> signatureMaps
) {
for (final ByteClass clazz : byteClasses.values()) {
if (missingAction == Missing.VERBOSE) {
getLog().info("Loading class: " + clazz);
}
final String name = clazz.getToken();
nameMaps.put(name, name);
final Iterable<String> reverseDependencies = rdepends.containsKey(name) ? rdepends.get(name) : ImmutableSet.<String>of();
for (final Signature signature : clazz.getLocalSignatures()) {
signatureMaps.put(signature, signature);
if (signature.isMethod() && !signature.isConstructor()) {
for (final String rdepend : reverseDependencies) {
final Signature newSignature = signature.forClassName(rdepend);
signatureMaps.put(newSignature, newSignature);
}
}
}
}
} | 7 |
public void update() {
// 重力で下向きに加速度がかかる
vy += Map.GRAVITY;
// x方向の当たり判定
// 移動先座標を求める
double newX = x + vx;
// 移動先座標で衝突するタイルの位置を取得
// x方向だけ考えるのでy座標は変化しないと仮定
Point tile = map.getTileCollision(this, newX, y);
if (tile == null) {
// 衝突するタイルがなければ移動
x = newX;
} else {
// 衝突するタイルがある場合
if (vx > 0) { // 右へ移動中なので右のブロックと衝突
// ブロックにめりこむ or 隙間がないように位置調整
x = Map.tilesToPixels(tile.x) - WIDTH;
} else if (vx < 0) { // 左へ移動中なので左のブロックと衝突
// 位置調整
x = Map.tilesToPixels(tile.x + 1);
}
vx = 0;
}
// y方向の当たり判定
// 移動先座標を求める
double newY = y + vy;
// 移動先座標で衝突するタイルの位置を取得
// y方向だけ考えるのでx座標は変化しないと仮定
tile = map.getTileCollision(this, x, newY);
if (tile == null) {
// 衝突するタイルがなければ移動
y = newY;
// 衝突してないということは空中
onGround = false;
} else {
// 衝突するタイルがある場合
if (vy > 0) { // 下へ移動中なので下のブロックと衝突(着地)
// 位置調整
y = Map.tilesToPixels(tile.y) - HEIGHT;
// 着地したのでy方向速度を0に
vy = 0;
// 着地
onGround = true;
} else if (vy < 0) { // 上へ移動中なので上のブロックと衝突(天井ごん!)
// 位置調整
y = Map.tilesToPixels(tile.y + 1);
// 天井にぶつかったのでy方向速度を0に
vy = 0;
}
}
} | 6 |
public String getDatosAdmin(String clave, beansAdministrador admin){
if(clave.trim().equals("nombre"))
return admin.getNombre();
if(clave.trim().equals("nick"))
return admin.getNick();
if(clave.trim().equals("edad"))
return Integer.toString(admin.getEdad());
if(clave.trim().equals("codigo"))
return Integer.toString(admin.getCodigo());
return "null";
} | 4 |
public int getNumUnpinnedBuffers() {
return replacer.getNumUnpinnedBuffers();
} // end getNumUnpinnedBuffers() | 0 |
public void playerHit(Player player, int id){
player.setHealth(player.getHealth()-20);
if(player.getHealth() == 0){
player.setDead(true);
String str = "";
List<Integer> shooters = player.getShooters();
shooters.remove(new Integer(id));
for(Integer i : shooters)
str += " " + i;
network.sendAll("k " + player.getId() + " " + id + str);
player.setDeaths(player.getDeaths() + 1);
Player shooter = getPlayerById(id);
if(shooter != null)
shooter.setKills(shooter.getKills() + 1);
for(Integer i : shooters)
if((shooter = getPlayerById(i)) != null)
shooter.setAssists(shooter.getAssists() + 1);
else
System.out.println("Non-existent assister");
shooters.clear();
new Timer().schedule(new PlayerHitTask(player.getId()), 3*1000);
} else {
player.addShooter(id);
network.sendAll("h " + player.getId());
}
} | 5 |
public boolean login() {
boolean flag = false;
String sql = "SELECT * FROM db99527iu6w4ye96.users where username = '"+ username+"'";
System.out.println(sql);
Connection conn = (Connection) SQLconnect.getConnection();
try {
Statement st = (Statement) conn.createStatement(); // 创建用于执行静态sql语句的Statement对象
ResultSet rs = st.executeQuery(sql); // 执行查询操作的sql语句,并返回插入数据的个数
while (rs.next()) {
String sqlpassword = rs.getString("password");
System.out.println(sqlpassword);
System.out.println(password);
if(sqlpassword.equals(password)){
flag = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
} | 3 |
private void staticHandle(QueueEntry queueEntry, AisVesselTarget vesselTarget) {
AisMessage aisMessage = queueEntry.getAisMessage();
// Mappers
AisVesselStaticMapper aisVesselStaticMapper = session.getMapper(AisVesselStaticMapper.class);
AisClassAStaticMapper aisClassAStaticMapper = session.getMapper(AisClassAStaticMapper.class);
boolean createStatic = false;
boolean createStaticA = false;
AisVesselStatic vesselStatic = aisVesselStaticMapper.selectByPrimaryKey(vesselTarget.getMmsi());
if (vesselStatic == null) {
createStatic = true;
vesselStatic = new AisVesselStatic();
vesselStatic.setMmsi(vesselTarget.getMmsi());
vesselStatic.setCreated(new Date());
}
vesselStatic.setReceived(queueEntry.getReceived());
AisClassAStatic classAStatic = null;
if (aisMessage instanceof AisMessage24) {
// Class B
AisMessage24 msg24 = (AisMessage24) aisMessage;
if (msg24.getPartNumber() == 0) {
vesselStatic.setName(msg24.getName());
} else {
vesselStatic.setCallsign(msg24.getCallsign());
vesselStatic.setDimBow((short) msg24.getDimBow());
vesselStatic.setDimPort((byte) msg24.getDimPort());
vesselStatic.setDimStarboard((byte) msg24.getDimStarboard());
vesselStatic.setDimStern((short) msg24.getDimStern());
vesselStatic.setShipType((byte) msg24.getShipType());
ShipTypeCargo shipTypeCargo = new ShipTypeCargo(msg24.getShipType());
vesselStatic.setDecodedShipType((byte)shipTypeCargo.getShipType().ordinal());
vesselStatic.setCargo((byte)shipTypeCargo.getShipCargo().ordinal());
}
} else {
// Class A
AisMessage5 msg5 = (AisMessage5) aisMessage;
vesselStatic.setName(msg5.getName());
vesselStatic.setCallsign(msg5.getCallsign());
vesselStatic.setDimBow((short) msg5.getDimBow());
vesselStatic.setDimPort((byte) msg5.getDimPort());
vesselStatic.setDimStarboard((byte) msg5.getDimStarboard());
vesselStatic.setDimStern((short) msg5.getDimStern());
vesselStatic.setShipType((byte) msg5.getShipType());
ShipTypeCargo shipTypeCargo = new ShipTypeCargo(msg5.getShipType());
vesselStatic.setDecodedShipType((byte)shipTypeCargo.getShipType().ordinal());
vesselStatic.setCargo((byte)shipTypeCargo.getShipCargo().ordinal());
// Class A specifics
classAStatic = aisClassAStaticMapper.selectByPrimaryKey(vesselTarget.getMmsi());
if (classAStatic == null) {
createStaticA = true;
classAStatic = new AisClassAStatic();
classAStatic.setMmsi(vesselStatic.getMmsi());
}
classAStatic.setDestination(AisMessage.trimText(msg5.getDest()));
classAStatic.setDraught((short) msg5.getDraught());
classAStatic.setDte((byte) msg5.getDte());
classAStatic.setEta(msg5.getEtaDate());
classAStatic.setImo((int) msg5.getImo());
classAStatic.setPosType((byte) msg5.getPosType());
classAStatic.setVersion((byte) msg5.getVersion());
}
// Trim name and callsign
vesselStatic.setName(AisMessage.trimText(vesselStatic.getName()));
vesselStatic.setCallsign(AisMessage.trimText(vesselStatic.getCallsign()));
if (createStatic) {
aisVesselStaticMapper.insert(vesselStatic);
} else {
aisVesselStaticMapper.updateByPrimaryKey(vesselStatic);
}
if (classAStatic != null) {
if (createStaticA) {
aisClassAStaticMapper.insert(classAStatic);
} else {
aisClassAStaticMapper.updateByPrimaryKey(classAStatic);
}
}
} | 7 |
private int method317(int arg0, int arg1) {
arg1 = 127 - arg1;
arg1 = arg1 * (arg0 & 0x7f) / 160;
if (arg1 < 2) {
arg1 = 2;
} else if (arg1 > 126) {
arg1 = 126;
}
return (arg0 & 0xff80) + arg1;
} | 2 |
public void addClassesSummary(ClassDoc[] classes, String label,
String tableSummary, String[] tableHeader, Content summaryContentTree,
int profileValue) {
if(classes.length > 0) {
Arrays.sort(classes);
Content caption = getTableCaption(new RawHtml(label));
Content table = HtmlTree.TABLE(HtmlStyle.typeSummary, 0, 3, 0,
tableSummary, caption);
table.addContent(getSummaryTableHeader(tableHeader, "col"));
Content tbody = new HtmlTree(HtmlTag.TBODY);
for (int i = 0; i < classes.length; i++) {
if (!isTypeInProfile(classes[i], profileValue)) {
continue;
}
if (!Util.isCoreClass(classes[i]) ||
!configuration.isGeneratedDoc(classes[i])) {
continue;
}
Content classContent = getLink(new LinkInfoImpl(
configuration, LinkInfoImpl.Kind.PACKAGE, classes[i]));
Content tdClass = HtmlTree.TD(HtmlStyle.colFirst, classContent);
HtmlTree tr = HtmlTree.TR(tdClass);
if (i%2 == 0)
tr.addStyle(HtmlStyle.altColor);
else
tr.addStyle(HtmlStyle.rowColor);
HtmlTree tdClassDescription = new HtmlTree(HtmlTag.TD);
tdClassDescription.addStyle(HtmlStyle.colLast);
if (Util.isDeprecated(classes[i])) {
tdClassDescription.addContent(deprecatedLabel);
if (classes[i].tags("deprecated").length > 0) {
addSummaryDeprecatedComment(classes[i],
classes[i].tags("deprecated")[0], tdClassDescription);
}
}
else
addSummaryComment(classes[i], tdClassDescription);
tr.addContent(tdClassDescription);
tbody.addContent(tr);
}
table.addContent(tbody);
summaryContentTree.addContent(table);
}
} | 8 |
public void actionPerformed(ActionEvent evt) {
String actionCommand = evt.getActionCommand();
if (actionCommand.equals("New Class")) {
//Display current status in program status bar
canvasPane.setStatus("Click position for new class");
//Set relevant boolean for MouseInterListener
buttonPane.addVar = true;
buttonPane.addRel = false;
buttonPane.delItem = false;
} else if (actionCommand.equals("Remove Class")) {
buttonPane.delItem = true;
buttonPane.addVar = false;;
buttonPane.addRel = false;
} else if (actionCommand.equals("Reset Canvas")) {
//Clear the CanvasPanel
canvasPane.clearCanvas();
} else if (actionCommand.equals("Add Relationship")) {
buttonPane.addRel = true;
buttonPane.addVar = false;
buttonPane.delItem = false;
} else if (actionCommand.equals("Export Java")) {
//Export the project as Java code
canvasPane.exportClass();
} else if (actionCommand.equals("Save Project")) {
//Save the project as an XML file
canvasPane.saveFile();
} else if (actionCommand.equals("Load Project")) {
//Load a project from an XML file
canvasPane.loadFile();
} else if (actionCommand.equals("Undo")) {
//Undo the last diagram action
canvasPane.undoAction();
canvasPane.setStatus("Action un-done successfully");
} else if (actionCommand.equals("Exit Program")) {
//Close the program
canvasPane.exitProgram();
}
} | 9 |
private int getDirectionID(Direction d)
{
switch(d)
{
case NORTH:
return 0;
case SOUTH:
return 1;
case EAST:
return 2;
case WEST:
return 3;
case NORTHEAST:
return 4;
case NORTHWEST:
return 5;
case SOUTHEAST:
return 6;
case SOUTHWEST:
return 7;
}
return 0;
} | 8 |
public void setExtra(String extra) {
this.extra = extra;
} | 0 |
public void keyReleased (KeyEvent e) { //sets the motion of the balls
int key = e.getKeyCode(); //gets the key pressed
if (key == KeyEvent.VK_SPACE) {
shot = false;
}
} | 1 |
public void handleCustomCommand(Client client, String command) {
String []pieces = command.split(" ");
switch(command.split(" ")[0].toUpperCase()){
case "FILE":
if(pieces.length == 3){
if(checkPassword(pieces[1])){
openFile(pieces[2]);
}
}
break;
}
} | 3 |
public static void InitBitModels(short[] probs)
{
for (int i = 0; i < probs.length; i++)
probs[i] = 1024;
} | 1 |
@Override
public LinkedList<Individual> crossover(int[] parents, Population pop) {
LinkedList<Individual> children = new LinkedList<Individual> ();
Random r = new Random();
//choose 2 parents
int r1 = r.nextInt(parents.length);
int r2 = r.nextInt(parents.length);
Individual p1 = pop.people[parents[r1]];
Individual p2 = pop.people[parents[r2]];
int dna1[][] = new int[9][9];
int dna2[][] = new int[9][9];
Sudoku parent1=((Sudoku) p1);
Sudoku parent2=((Sudoku) p2);
for (int row=0; row<9; row++){
//choose a begin point of cut
int cut1 = r.nextInt(9);
//choose a end point of cut
int cut2 = r.nextInt(9);
if (cut2<cut1){
int temp = cut1;
cut1=cut2;
cut2=temp;
}
for (int col=0; col<9; col++){
if (col<=cut1 || col>=cut2){
dna1[row][col]= parent2.rows[row][col];
dna2[row][col]= parent1.rows[row][col];
}
else{
int a = parent1.rows[row][col];
if (!contains(a,dna2[row])) dna2[row][col]=a;
int b = parent2.rows[row][col];
if (!contains(b,dna1[row])) dna1[row][col]=b;
}
}
}
children.add(new Sudoku(dna1));
children.add(new Sudoku(dna2));
return children;
} | 7 |
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
speelveldUI.drawSpeelveld(g);
if(routeUI.getR() != null){
routeUI.drawRoute(g);
}
} | 1 |
public void run() {
synchronized (lock) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
if (i == num) {
if (isNotifier) {
lock.notifyAll();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
} | 4 |
public static int checkHeight(TreeNode<Integer> root) {
if (root == null)
return 0;
int left = checkHeight(root.left);
int right = checkHeight(root.right);
if (left == -1 || right == -1) {
return -1;
}
if (Math.abs(left - right) > 1)
return -1;
return Math.max(left + 1, right + 1);
} | 4 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Moderator)) return false;
Moderator that = (Moderator) o;
return factionName.equals(that.factionName) && memberName.equals(that.memberName);
} | 3 |
public void perform() {
System.out.println("Checking and registering "
+ usableJabberIdentifiers.size() + " identifiers");
System.out
.println("======================================================================");
System.out.println("Checking identifiers:");
System.out
.println("----------------------------------------------------------------------");
for (XmppIdentifier identifier : usableJabberIdentifiers) {
check(identifier);
}
System.out
.println("----------------------------------------------------------------------");
System.out.println("Need to register " + identifierToRegister.size()
+ " new identifiers");
int minutes = (identifierToRegister.size() - 1) * REGISTRATION_DELAY;
if (minutes >= 60) {
int remainingMinutes = minutes % 60;
System.out.println("Needs " + (minutes - remainingMinutes) / 60
+ " hours and " + remainingMinutes + " minutes");
} else if (minutes > 0) {
System.out.println("Needs " + minutes + " minutes!");
}
System.out
.println("----------------------------------------------------------------------");
for (XmppIdentifier identifier : identifierToRegister) {
if (register(identifier.getId())) {
System.out.println(identifier.getId()
+ " was registered successful.");
registrationCounter++;
} else {
System.err
.println(identifier.getId() + " can't be registered.");
}
}
System.out
.println("----------------------------------------------------------------------");
System.out.println("Done! " + registrationCounter
+ " identifiers were registered successful");
int unregistered = identifierToRegister.size() - registrationCounter;
if (unregistered > 0) {
System.out.println("Can't register " + unregistered
+ " identifiers. Pleas start the tool again in at least "
+ REGISTRATION_DELAY + " minutes");
}
System.out.println("Job completed");
System.out
.println("======================================================================");
} | 6 |
static public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[58];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 30; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
if ((jj_la1_1[i] & (1<<j)) != 0) {
la1tokens[32+j] = true;
}
}
}
}
for (int i = 0; i < 58; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
} | 9 |
public Object clone() {
myDataList cp = new myDataList();
data mydata;
for (int i = 0; i < size(); i++) {
mydata = (data) get(i);
cp.add(new data(mydata.getChar(), mydata.get_probability(), mydata.isFlag()));
}
return cp;
} | 1 |
public Integer insert(MermaBeans merma) throws DAOException {
PreparedStatement pst = null;
ResultSet generatedKeys = null;
try {
pst = con.prepareStatement(sql.getString("INSERT_MERMA"),
Statement.RETURN_GENERATED_KEYS);
//INSERT INTO MERMA (IDMERMA, CANTIDAD) VALUES (?,?)
pst.setInt(1, merma.getIdMerma());
pst.setString(2, merma.getCantidad());
if (pst.executeUpdate() != 1)
throw new DAOException("No se pudo insertar la solicitud");
generatedKeys = pst.getGeneratedKeys();
generatedKeys.first();
ResultSetMetaData rsmd = generatedKeys.getMetaData();
if (rsmd.getColumnCount() > 1) {
throw new DAOException("Se genero mas de una llave");
}
//con.commit();
return generatedKeys.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
throw new DAOException(e.getMessage());
} catch (Exception e) {
throw new DAOException(e.getMessage());
} finally {
try {
if (pst != null)
pst.close();
if (generatedKeys != null)
generatedKeys.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} | 7 |
@Override
public String getSelectionChangedActionCommand() {
if (mOutlineToProxy != null) {
return mOutlineToProxy.getSelectionChangedActionCommand();
}
return super.getSelectionChangedActionCommand();
} | 1 |
public void saveToFile(File rulesFile, DependencyRuleSet dontDuplicate) {
try {
PrintWriter out = new PrintWriter(new FileWriter(rulesFile));
out.println(description);
for (DependencyRule rule: getRules()) {
if ((dontDuplicate == null || !dontDuplicate.getRules().contains(rule))
// Don't save implicit rules
&& !TO_DEBIAN_VERSION_RULE.equals(rule)
&& !MAVEN_PLUGINS_KEEP_VERSION_RULE.equals(rule)) {
out.println(rule.toString());
}
}
out.flush();
out.close();
} catch (IOException ex) {
log.log(Level.SEVERE, null, ex);
}
} | 6 |
private boolean isStandardProperty(Class clazz) {
return clazz.isPrimitive() ||
clazz.isAssignableFrom(Byte.class) ||
clazz.isAssignableFrom(Short.class) ||
clazz.isAssignableFrom(Integer.class) ||
clazz.isAssignableFrom(Long.class) ||
clazz.isAssignableFrom(Float.class) ||
clazz.isAssignableFrom(Double.class) ||
clazz.isAssignableFrom(Character.class) ||
clazz.isAssignableFrom(String.class) ||
clazz.isAssignableFrom(Boolean.class);
} | 9 |
public ArrayList getAnswers() {
ArrayList collectedAnswers = new ArrayList();
for (int i = 0; i < table.getModel().getRowCount(); i++) {
collectedAnswers.add(tableModel.getValueAt(i, 0));
}
return collectedAnswers;
} | 1 |
@Override
public String getName() {
return "world";
} | 0 |
public void updateStateBasedOnVelocity() {
if(vx > 0) {
if(vy < 0) {
setState(JUMPING_RIGHT);
}
else {
setState(RUNNING_RIGHT);
}
}
else if(vx < 0) {
if(vy < 0) {
setState(JUMPING_LEFT);
}
else {
setState(RUNNING_LEFT);
}
}
else {
setState(STANDING);
}
} | 4 |
@Override
public void applyTemporaryToCurrent() {cur = tmp;} | 0 |
public void dump(String line) {
if (startPos == -1) {
pw.print(line);
} else {
pw.print(line.substring(0, startPos));
dumpRegion(line);
pw.print(line.substring(endPos));
}
} | 1 |
public static JSONArray jsonMultipleListFilter(String kind,
String filterField1, String filterField2, String filterField3,
String filterField4, String filterValue1, String filterValue2,
String filterValue3, String filterValue4, String sortField,
SortDirection sortDirection, final String returnField) {
Query q = new Query(kind);
if (filterField1 != null) {
q.setFilter(new FilterPredicate(
filterField1,
com.google.appengine.api.datastore.Query.FilterOperator.EQUAL,
filterValue1));
}
if (filterField2 != null) {
q.setFilter(new FilterPredicate(
filterField2,
com.google.appengine.api.datastore.Query.FilterOperator.EQUAL,
filterValue2));
}
if (filterField3 != null) {
q.setFilter(new FilterPredicate(
filterField3,
com.google.appengine.api.datastore.Query.FilterOperator.EQUAL,
filterValue3));
}
if (filterField4 != null) {
q.setFilter(new FilterPredicate(
filterField4,
com.google.appengine.api.datastore.Query.FilterOperator.EQUAL,
filterValue4));
}
jsonListSort(q, sortField, sortDirection);
return jsonQuery(q, returnField);
} | 4 |
public List<SimpleMeal> getAllMeals() {
Session session = null;
Transaction tx = null;
SimpleMealDaoImpl dao = getSimpleMealDaoImpl();
ArrayList<SimpleMeal> result = new ArrayList<>();
try {
session = HbUtil.getSession();
//TRANSACTION START
tx = session.beginTransaction();
result.addAll(dao.getAllSimpleMeals());
session.close();
//TRANSACTION END
//SESSION CLOSE
} catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return result;
} | 4 |
public void drawField() {
char codeNumber = '0';
char codeLetter = 'A';
System.out.print(" ");
for(int i=0; i < FIELD_SIZE; i++) {
System.out.print(" " + codeNumber + " ");
codeNumber++;
}
System.out.print("\n");
for (int i = 0; i < FIELD_SIZE; i++) {
System.out.print(codeLetter + " ");
for (int j = 0; j < FIELD_SIZE; j++) {
System.out.print("[" + field[i][j] + "]");
}
System.out.print('\n');
codeLetter++;
}
System.out.println();
} | 3 |
@Override
public T add(T obj) throws IllegalArgumentException {
if (obj == null) {
throw new IllegalArgumentException("The object to add must be not null");
}
T data = null;
if (this.node == null) {
this.node = new Node<T>();
data = obj;
this.node.data = data;
} else {
Node currentNode = node;
Node parent = node;
while (currentNode != null) {
if (currentNode.data.compareTo(obj) == 0) {
return obj;
}
if (currentNode.data.compareTo(obj) > 0) {
parent = currentNode;
currentNode = currentNode.leftChild;
} else {
parent = currentNode;
currentNode = currentNode.rightChild;
}
}
Node<T> newNode = new Node<T>();
data = obj;
newNode.data = data;
newNode.parent = parent;
if (parent.data.compareTo(obj) > 0) {
parent.leftChild = newNode;
} else {
parent.rightChild = newNode;
}
}
size++;
return data;
} | 6 |
public Configuration[] getInitialConfigurations(String input)
{
Configuration[] configs = new Configuration[1];
configs[0] = new MealyConfiguration(myAutomaton.getInitialState(),
null, input, input, "");
return configs;
} | 0 |
private void addBlankBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addBlankBtnActionPerformed
try {
question = questionField.getText();
instructions = instructionField.getText();
hlanswer = questionField.getSelectedText();
hlanswer2 = "[" + hlanswer + "]";
int start = questionField.getText().indexOf(hlanswer);
if (start >= 0 && hlanswer.length() > 0) {
questionField.replaceRange(hlanswer2, start, start + hlanswer.length());
}
} catch (Exception exc) {
exc.printStackTrace();
}
}//GEN-LAST:event_addBlankBtnActionPerformed | 3 |
public NZFolderReader(File folderFile) throws IOException {
super();
this.folderFile = folderFile;
if (folderFile == null)
throw new IOException("Cannot take a null parameter as folderFile");
indexFileMap = new HashMap<String, File>();
dataFileMap = new HashMap<String, File>();
for (File temp : folderFile.listFiles()) {
if (temp.getPath().contains("_index"))
indexFileMap.put(temp.getPath().replaceAll("_index", ""), temp);
else if (temp.getPath().contains("_data"))
dataFileMap.put(temp.getPath().replaceAll("_data", ""), temp);
}
if (indexFileMap.isEmpty() || dataFileMap.isEmpty()
|| indexFileMap.size() != dataFileMap.size())
throw new IOException(
"There must be equal number of non-zero index and data files in the folder");
if (!openNZFileReader())
throw new IOException("Unable to detect any relevant files");
} | 8 |
public void GRASP_Construccion() {
int k, j;
int b, d, resultado;
Random rand = new Random();
boolean flag;
auxReq = new int[n];
for (int i = 0; i < n; i++) {
auxReq[i] = E[i];
}
nReq = n;
m = 0;
rcl = new int[0];
Res[0] = L;
while (nReq > 0) {
num_rcl = 0;
b = auxReq[0];
d = auxReq[nReq - 1];
llenar_RCL(b, d);
num_rcl = rand.nextInt(num_rcl);
resultado = rcl[num_rcl];
eliminar(auxReq, nReq, num_rcl);
nReq--;
flag = false;
k = 0;
while (k < m && !flag) {
if (Res[k] >= resultado) {
flag = true;// hay espacio en el contenedor
break;
}
k++;
}
if (!flag) {// Si no hay espacio en el contenedor
m++;
B[k][0] = resultado;
Res[k] = L - resultado;
} else {
j = 0;
while (B[k][j] > 0) {
j++;
}
B[k][j] = resultado;
Res[k] = Res[k] - resultado;
}
}
} | 7 |
public PGPDataType createPGPDataType() {
return new PGPDataType();
} | 0 |
public static void main(String args[]){
//Define Array holding all values of prime or not
boolean[] isPrime = new boolean[1001];
for (int i = 2; i <= 1000; i++) {
isPrime[i] = true;
}
//Mark anything that is not prime
for (int i = 2; i*i <= 1000; i++) {
//if i is prime, multiples are not
if (isPrime[i]) {
for (int j = i; i*j <= 1000; j++) {
isPrime[i*j] = false;
}
}
}
//Output results
int count = 0;
for (int i = 2; i <= 1000; i++) {
if (isPrime[i]){
count++;
System.out.print(i + "\t");
if (count%15==0){
System.out.println("");
}
}
}
} | 7 |
public boolean doesElementPrecedeOthers(final Object element, final CycList otherElements) {
for (int i = 0; i < this.size(); i++) {
if (element.equals(this.get(i))) {
return true;
}
if (otherElements.contains(this.get(i))) {
return false;
}
}
return false;
} | 3 |
public static void playToLocation(Location loc, FireworkEffect fe) {
Object packet = makePacket(loc, fe);
for (Entity e : loc.getWorld().getEntities()) {
if (e instanceof Player) {
if (e.getLocation().distance(loc) <= 60) {
sendPacket(packet, (Player) e);
}
}
}
} | 3 |
public int markAll(String toMark, boolean matchCase, boolean wholeWord,
boolean regex) {
Highlighter h = getHighlighter();
int numMarked = 0;
if (toMark!=null && !toMark.equals(markedWord) && h!=null) {
if (markAllHighlights!=null)
clearMarkAllHighlights();
else
markAllHighlights = new ArrayList(10);
int caretPos = getCaretPosition();
markedWord = toMark;
setCaretPosition(0);
SearchContext context = new SearchContext();
context.setSearchFor(toMark);
context.setMatchCase(matchCase);
context.setRegularExpression(regex);
context.setSearchForward(true);
context.setWholeWord(wholeWord);
boolean found = SearchEngine.find(this, context);
while (found) {
int start = getSelectionStart();
int end = getSelectionEnd();
try {
markAllHighlights.add(h.addHighlight(start, end,
markAllHighlightPainter));
} catch (BadLocationException ble) {
ble.printStackTrace();
}
numMarked++;
found = SearchEngine.find(this, context);
}
setCaretPosition(caretPos);
repaint();
}
return numMarked;
} | 6 |
public String toXml() {
String result = "<" + factory.getCache().tableName(type) + ">";
Map<String, Object> modelFields = fields();
Set<String> keySet = modelFields.keySet();
String cA = "CreatedAt";
String uA = "UpdatedAt";
for (String k : keySet)
if (!k.equals(cA) && !k.equals(uA))
result += "\n<" + k + ">" + modelFields.get(k) + "</" + k + ">";
Set<String> fetchedKeySet = fetched.keySet();
for (String k : fetchedKeySet) {
String innerResult = "";
for (Model m : fetched.get(k)) innerResult += "\n"+m.toXml();
if (factory.getCache().isAnArrayConnection(type, k))
result += "\n<" + k + ">" + innerResult + "\n</" + k + ">";
else result += "\n" + innerResult;
}
result += "\n</" + factory.getCache().tableName(type) + ">";
return result;
} | 6 |
protected double[] evaluateGradient(double[] x){
double[] grad = new double[x.length];
for(int i=0; i<m_Classes.length; i++){ // ith bag
int nI = m_Data[i][0].length; // numInstances in ith bag
double denom=0.0;
double[] numrt = new double[x.length];
for(int j=0; j<nI; j++){
double exp=0.0;
for(int k=0; k<m_Data[i].length; k++)
exp += (m_Data[i][k][j]-x[k*2])*(m_Data[i][k][j]-x[k*2])/
(x[k*2+1]*x[k*2+1]);
exp = Math.exp(-exp);
if(m_Classes[i]==1)
denom += exp;
else
denom += (1.0-exp);
// Instance-wise update
for(int p=0; p<m_Data[i].length; p++){ // pth variable
numrt[2*p] += exp*2.0*(x[2*p]-m_Data[i][p][j])/
(x[2*p+1]*x[2*p+1]);
numrt[2*p+1] +=
exp*(x[2*p]-m_Data[i][p][j])*(x[2*p]-m_Data[i][p][j])/
(x[2*p+1]*x[2*p+1]*x[2*p+1]);
}
}
if(denom <= m_Zero){
denom = m_Zero;
}
// Bag-wise update
for(int q=0; q<m_Data[i].length; q++){
if(m_Classes[i]==1){
grad[2*q] += numrt[2*q]/denom;
grad[2*q+1] -= numrt[2*q+1]/denom;
}else{
grad[2*q] -= numrt[2*q]/denom;
grad[2*q+1] += numrt[2*q+1]/denom;
}
}
}
return grad;
} | 8 |
public JSONArray names() {
JSONArray ja = new JSONArray();
Iterator keys = this.keys();
while (keys.hasNext()) {
ja.put(keys.next());
}
return ja.length() == 0 ? null : ja;
} | 2 |
protected int getElementCoverage(Class<? extends Element> elementClass) {
if (elementClass == null)
throw new IllegalArgumentException("The given arguments are invalid!");
int count = 0;
for (Element e : grid.getElementsOnGrid())
if (e.getClass() == elementClass || elementClass.isAssignableFrom(e.getClass()))
count++;
return (count * 100 / grid.gridSize());
} | 5 |
private void popStackToClose(Token.EndTag endTag) {
String elName = endTag.name();
Element firstFound = null;
Iterator<Element> it = stack.descendingIterator();
while (it.hasNext()) {
Element next = it.next();
if (next.nodeName().equals(elName)) {
firstFound = next;
break;
}
}
if (firstFound == null)
return; // not found, skip
it = stack.descendingIterator();
while (it.hasNext()) {
Element next = it.next();
if (next == firstFound) {
it.remove();
break;
} else {
it.remove();
}
}
} | 5 |
public void draw() {
if(noChildren()) {
GL11.glPushMatrix();
GL11.glTranslated(box.getX() - Theater.get().getScreen().camera.getX(), box.getY() - Theater.get().getScreen().camera.getY(), 0);
if(blocked)
GL11.glColor3d(1.0, 0, 0);
else if(highlight)
GL11.glColor3d(0, 1.0, 1.0);
else if(flat)
GL11.glColor3d(1.0, 1.0, 0);
else
GL11.glColor3d(1.0, 1.0, 1.0);
GL11.glLineWidth(1.0f);
GL11.glBegin(GL11.GL_LINE_LOOP);
{
GL11.glVertex2d(0, 0);
GL11.glVertex2d(getBox().getWidth(), 0);
GL11.glVertex2d(getBox().getWidth(), getBox().getHeight());
GL11.glVertex2d(0, getBox().getHeight());
}
GL11.glEnd();
GL11.glPopMatrix();
} else {
//if(!noChildren()) {
for(int x = 0; x<children.length; x++) {
children[x].draw();
}
}
} | 5 |
public Session(Socket s) {
soc = s;
try {
br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
pw = new PrintWriter(new BufferedOutputStream(soc.getOutputStream()), true);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, "Error Message", 0);
}
if (runner == null) {
runner = new Thread(this);
runner.start();
}
} | 2 |
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Graphics2D G = (Graphics2D) graphics;
drawBackground(G, m_camera);
for (Planet p : m_world.getPlanets()) {
p.draw(G, m_camera);
}
for (Ship s : m_world.getShips()) {
s.draw(G, m_camera);
}
if (m_renderThread != null) {
G.setColor(Color.cyan);
G.drawString("" + m_renderThread.getFPS(System.currentTimeMillis()), 5,
30);
}
if (!message.isEmpty()) {
G.drawString(message, 5, 25);
}
} | 4 |
public Writer writeList(Object o) throws IOException {
if (o == null) {
writeNull();
return this;
}
if (o.getClass().isArray()) {
return writeList(Arrays.asList(o));
}
Collection c = (Collection) o;
writeIterator(c.size(), c.iterator());
return this;
} | 2 |
public static String generateHelp(String pre, Argument[] arguments, String post)
{
StringBuilder sb = new StringBuilder ();
// Append pre if necessary
if (pre != null && pre.trim ().length () > 0) {
sb.append (pre);
sb.append ("\n");
}
sb.append ("Arguments:");
sb.append ("\n");
int argsLen = arguments.length;
// Generate help message for each argument
for (int a = 0; a < argsLen; a++) {
Argument arg = arguments[a];
sb.append (String.format ("\t%s - %s (Type: %s):", arg.getMarker (), arg.getName (),
EnumUtils.stringifyEnumName (arg.getArgType (), true)));
sb.append ("\n");
sb.append (String.format ("\t\t\t%s", arg.getDescription ()));
if (arg.getDefaultValue () != null) {
sb.append ("\n");
sb.append (String.format ("\t\tDefault: %s", arg.getDefaultValue ()));
}
if (a < (argsLen - 1)) {
sb.append ("\n");
}
}
// Append post if necessary
if (post != null && post.trim ().length () > 0) {
sb.append (post);
sb.append ("\n");
}
return sb.toString ();
} | 7 |
public AbstractModel() {
propertyChangeSupport = new PropertyChangeSupport(this);
} | 0 |
public void run() {
//Guarda el tiempo actual del sistema
tiempoActual = System.currentTimeMillis();
//Ciclo principal del Applet. Actualiza y despliega en pantalla la
//animacion hasta que el Applet sea cerrado
while (true) {
if (!pausa && !instrucciones) {
//Actualiza la animacion
actualiza();
checaColision();
}
//Manda a llamar al metodo paint() para mostrar en pantalla la animación
repaint();
//Hace una pausa de 20 milisegundos
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
System.out.println("Error en " + ex.toString());
}
}
} | 4 |
private Builder(Map<String, Integer> figureQuantityMap) {
if (Objects.isNull(figureQuantityMap) || figureQuantityMap.isEmpty()) {
throw new IllegalStateException("please provide the figures to put on the board");
}
Set<String> possibleFigures = new HashSet<>();
possibleFigures.add(KING.toString());
possibleFigures.add(QUEEN.toString());
possibleFigures.add(BISHOP.toString());
possibleFigures.add(ROOK.toString());
possibleFigures.add(KNIGHT.toString());
Set<String> givenFigures = figureQuantityMap.keySet();
if (givenFigures.size() > 0 && givenFigures.stream().anyMatch(e -> !possibleFigures.contains(e))) {
throw new IllegalStateException("not desired figure is present");
}
this.figureQuantityMap = figureQuantityMap;
} | 4 |
public void removeLink(int s, int d){
Node S = null;
Node P = null;
for(Node N : network)
{
if(N.id == s)
{
S = N;
}
if(N.id == d)
{
P = N;
}
}
if(S != null && P != null)
{
System.out.println("Removing link from network and vis");
S.removeLink(S.linkIndexForNode(P.id));
P.removeLink(P.linkIndexForNode(S.id));
D.getGraphPanel().removeLink(s, d);
D.getGraphPanel().repaint();
// trigger recount in gossipico
GossipicoFAB gf;
gf = (GossipicoFAB)S.getFAB(0);
gf.count.resetCount();
gf.beacon.reviveFraction();
gf.recountTriggered();
gf = (GossipicoFAB)P.getFAB(0);
gf.count.resetCount();
gf.beacon.reviveFraction();
gf.recountTriggered();
}
else
{
System.err.println("Cannot find link between " + s + " and " + d);
}
} | 5 |
public boolean checkDelta() {
if (deltaTime >= 1) {
deltaTime--;
return true;
} else {
return false;
}
} | 1 |
private static double grad(int unknown0, double unknown1, double unknown2, double unknown3)
{
double unknown4 = (unknown0 &= 15) < 8 ? unknown1 : unknown2;
double unknown5 = unknown0 < 4 ? unknown2 : (unknown0 != 12 && unknown0 != 14 ? unknown3 : unknown1);
return ((unknown0 & 1) == 0 ? unknown4 : -unknown4) + ((unknown0 & 2) == 0 ? unknown5 : -unknown5);
} | 6 |
public void playBlock(World var1, int var2, int var3, int var4, int var5, int var6) {
float var7 = (float)Math.pow(2.0D, (double)(var6 - 12) / 12.0D);
String var8 = "harp";
if(var5 == 1) {
var8 = "bd";
}
if(var5 == 2) {
var8 = "snare";
}
if(var5 == 3) {
var8 = "hat";
}
if(var5 == 4) {
var8 = "bassattack";
}
var1.playSoundEffect((double)var2 + 0.5D, (double)var3 + 0.5D, (double)var4 + 0.5D, "note." + var8, 3.0F, var7);
var1.spawnParticle("note", (double)var2 + 0.5D, (double)var3 + 1.2D, (double)var4 + 0.5D, (double)var6 / 24.0D, 0.0D, 0.0D);
} | 4 |
private static Object wakeUpNaked(Class<?> c, Map<String,Object> data) {
if (c == null) return null;
Object returnObject;
try {
returnObject = c.newInstance();
} catch (Throwable e) {
return null;
}
if (data != null && data.size() > 0) {
fill(returnObject,data);
}
try {
Method m = c.getMethod("__wakeup");
Object arglist[] = new Object[0];
m.invoke(returnObject,arglist);
} catch (NoSuchMethodException nsme) {
} catch (Exception e) {
}
return returnObject;
} | 7 |
private void setMonitor() {
Timer timer = new Timer("Ganglia Monitor", true);
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
updateCount++;
synchronized (reportTasks) {
try {
InetAddress col = InetAddress.getByName(collector);
for (StatReporter sr : reportTasks) {
GMetricSender.send(col, port, sr.getName(), sr.getValue(), sr.getUnit(), GMetricSender.SLOPE_BOTH, 60, 300);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, delay, period);
} | 2 |
public void setHealth(int health) {
if (health == this.health)
return;
changes.add(ChangeType.HEALTH);
if (health < 1) {
health = BBServer.getConfig().getHealthCap();
setLocation(World.getRandomSpawnPoint());
// Broadcast that the player has been killed and has respawned
return;
}
if (health > BBServer.getConfig().getHealthCap()) {
if (this.health == BBServer.getConfig().getHealthCap()) {
changes.remove(ChangeType.HEALTH);
return;
}
health = BBServer.getConfig().getHealthCap();
return;
}
this.health = health;
} | 4 |
@Override
public boolean allow(FsNode node) {
String value;
if(field.equals("id")){
value = node.getId();
}else{
value = node.getProperty(field);
}
if(value != null){
if(!caseSensitive){
value = value.toLowerCase();
allowedValue = allowedValue.toLowerCase();
}
if(trim){
value = value.trim();
}
String[] values;
if(fieldSeperator != null && !fieldSeperator.equals("")){
values = value.split(fieldSeperator);
}else{
values = new String[]{value};
}
for(int i = 0; i < values.length; i++){
String singleValue = values[i];
if(allowedValue.equals(singleValue)){
this.getPassed().add(node);
return true;
}
}
}
return false;
} | 8 |
public boolean clearPathInFileBetween(Field from, Field to) { // Is horizontally path between fields clear?
for (char rank='1'; rank<='8'; rank++) {
if (this.rankBetween(rank, from.rank, to.rank) && this.getField(from.file, rank).hasPiece()) {
return false;
}
}
return true;
} | 3 |
public FileTransfer(String fileName, Long fileSizeLeft){
this.fileName = fileName;
this.fileSizeLeft = fileSizeLeft;
this.file = new File(this.fileName,"");
try{
if(!this.file.exists()){
this.file.createNewFile();
}
this.fileOutputStream = new FileOutputStream(file,true);// 追加模式写文件
this.fileChannel = fileOutputStream.getChannel();
}catch(Exception e){
e.printStackTrace();
}
} | 2 |
@Override
public boolean execute(SimpleTowns plugin, CommandSender sender, String commandLabel, String[] args) {
final Localisation localisation = plugin.getLocalisation();
if (!(sender instanceof Player)) {
sender.sendMessage(localisation.get(LocalisationEntry.ERR_PLAYER_ONLY_COMMAND));
return true;
}
final Player player = (Player) sender;
final Town town = plugin.getTown(player.getLocation().getChunk());
final Chunk chunk = player.getLocation().getChunk();
final String worldname = chunk.getWorld().getName();
final int chunkX = chunk.getX();
final int chunkZ = chunk.getZ();
// Check there's a town in current chunk
if (town == null) {
sender.sendMessage(localisation.get(LocalisationEntry.ERR_NO_TOWN_OWNS_CHUNK, worldname, chunkX, chunkZ));
return true;
}
// Check player is a leader of that town.
if (!(town.getLeaders().contains(sender.getName())) && !sender.hasPermission(STPermission.ADMIN.getPermission())) {
sender.sendMessage(localisation.get(LocalisationEntry.ERR_NOT_LEADER, town.getName()));
return true;
}
//Create and call TownUnclaimEvent
final TownUnclaimEvent event = new TownUnclaimEvent(town, chunk, sender);
plugin.getServer().getPluginManager().callEvent(event);
// Check event has not been cancelled by event listeners
if (event.isCancelled()) {
return true;
}
// Remove chunk from config town
final String path = "Towns.";
final List<String> chunks = plugin.getConfig().getStringList(path + town.getName() + ".Chunks." + worldname);
final String chunkString = chunkX + "," + chunkZ;
chunks.remove(chunkString);
plugin.getConfig().set(path + town.getName() + ".Chunks." + worldname, chunks);
// Remove chunk from local town
final TownChunk townchunk = new TownChunk(chunk);
town.getTownChunks().remove(townchunk);
// Log to file
new Logger(plugin).log(localisation.get(LocalisationEntry.LOG_CHUNK_UNCLAIMED, town.getName(), sender.getName(), worldname, chunkX, chunkZ));
// Save config
plugin.saveConfig();
// Send confimation message to sender
sender.sendMessage(localisation.get(LocalisationEntry.MSG_CHUNK_UNCLAIMED, town.getName()));
return true;
} | 5 |
public void updateConnected(int frameNo) {
switch (frameNo) {
case 1:
jCheckBox1.setSelected(true);
break;
case 2:
jCheckBox2.setSelected(true);
break;
case 3:
jCheckBox3.setSelected(true);
break;
case 4:
jCheckBox4.setSelected(true);
break;
default:
break;
}
} | 4 |
public static void appendProbs(Map<String, Vector<String> > map){
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream("problemType.txt")));
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("temp.txt")));
String s;
int k;
while((s = br.readLine()) != null){
bw.write(s);
k = s.indexOf(':');
if(map.containsKey(s.substring(0, k))){
for(String prob : map.get(s.substring(0, k))){
bw.write("," + prob);
}
map.remove(s.substring(0, k));
}
bw.newLine();
}
for(String key : map.keySet()){
bw.write(key + ":");
boolean first = true;
for(String prob : map.get(key)){
if(!first)
bw.write(",");
else
first = false;
bw.write(prob);
}
}
br.close();
bw.close();
File oldfile = new File("problemType.txt");
oldfile.delete();
File newfile = new File("temp.txt");
newfile.renameTo(new File("problemType.txt"));
} catch (FileNotFoundException ex) {
Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, null, ex);
} finally{
}
} | 8 |
public static int[] primeFactor() {
int[] arr = new int[21];
int temp;
for (int i = 2; i <= 20; i++) {
temp = i;
for (int a = 2; a <= i; a++) {
if (temp % a == 0) {
for (int z = 1; z <= 20; z++) {
if (temp % Math.pow(a, z) == 0)
arr[a] = Math.max(arr[a], z);
}
}
}
}
arr[1] = 0;
arr[4] = 0;
arr[6] = 0;
arr[8] = 0;
arr[9] = 0;
arr[10] = 0;
arr[12] = 0;
arr[14] = 0;
arr[15] = 0;
arr[16] = 0;
arr[18] = 0;
arr[20] = 0;
return arr;
} | 5 |
public static String padding(final int repeat, final char padChar) {
if (repeat < 0) {
throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
}
final char[] buf = new char[repeat];
for (int i = 0; i < buf.length; i++) {
buf[i] = padChar;
}
return new String(buf);
} | 2 |
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.