method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
c53722d4-be76-4d14-97c9-507862864829 | 1 | public Object opt(String key) {
return key == null ? null : this.map.get(key);
} |
c5ff458b-577b-4bcb-a44a-a33af8ac6cb8 | 7 | public static void renderSpecialCases(Shape s, Texture tex, Graphics2D g) {
if (s instanceof Rectangle) {
Rectangle r = (Rectangle) s;
if (tex.getStyle() == TextureFactory.INSULATION) {
g.setColor(new Color(tex.getForeground()));
int m = 20; // default number of repeats
int minLength = 20;
Arc2D.Float arc = new Arc2D.Float();
Line2D.Float line = new Line2D.Float();
if (r.width > r.height) {
float a = (float) r.width / (float) m;
if (a < minLength) {
m = Math.round((float) r.width / (float) minLength);
a = (float) r.width / (float) m;
}
float b = (float) r.height / 3f;
arc.width = a;
arc.height = b;
float u = r.x;
for (int i = 0; i < m; i++) {
arc.x = u;
arc.y = r.y;
arc.start = 0;
arc.extent = 180;
g.draw(arc);
line.x1 = u;
line.y1 = r.y + b * 0.5f;
line.x2 = u + a * 0.5f;
line.y2 = r.y + r.height - b * 0.5f;
g.draw(line);
line.x1 = u + a;
g.draw(line);
arc.x = u - a * 0.5f;
arc.y = r.y + r.height - b;
arc.extent = -91;
g.draw(arc);
arc.x = u + a * 0.5f;
arc.start = 270;
g.draw(arc);
u += a;
}
} else {
float a = (float) r.height / (float) m;
if (a < minLength) {
m = Math.round((float) r.height / (float) minLength);
a = (float) r.height / (float) m;
}
float b = (float) r.width / 3f;
arc.width = b;
arc.height = a;
float v = r.y;
for (int i = 0; i < m; i++) {
arc.y = v;
arc.x = r.x;
arc.start = 90;
arc.extent = 180;
g.draw(arc);
line.y1 = v;
line.x1 = r.x + b * 0.5f;
line.y2 = v + a * 0.5f;
line.x2 = r.x + r.width - b * 0.5f;
g.draw(line);
line.y1 = v + a;
g.draw(line);
arc.y = v - a * 0.5f;
arc.x = r.x + r.width - b;
arc.start = 0;
arc.extent = -91;
g.draw(arc);
arc.y = v + a * 0.5f;
arc.start = 90;
g.draw(arc);
v += a;
}
}
}
}
} |
d8d4918f-2dc2-4065-acdc-2bbf54314bd5 | 2 | public boolean isLesser(int i, int j) {
//E[] arrEs = new E[10];
assert i > 0 && j > 0;
this.arrayAccess += 2;
this.comparisions++;
if (this.array[i - 1].compareTo(this.array[j - 1]) < 0) {
return true;
} else
return false;
} |
4f88328f-41d6-44e5-8ae5-a960b92b1d03 | 0 | public int getSavedFunctionAddress() {
return savedFunctionAddress;
} |
b7ba6800-0ce9-474f-a5da-213d9f995ac7 | 4 | private int readFully(byte[] b, int offs, int len)
throws BitstreamException
{
int nRead = 0;
try
{
while (len > 0)
{
int bytesread = source.read(b, offs, len);
if (bytesread == -1)
{
while (len-->0)
{
b[offs++] = 0;
}
break;
//throw newBitstreamException(UNEXPECTED_EOF, new EOFException());
}
nRead = nRead + bytesread;
offs += bytesread;
len -= bytesread;
}
}
catch (IOException ex)
{
throw newBitstreamException(STREAM_ERROR, ex);
}
return nRead;
} |
468dbb48-e085-4a27-99c5-1b127ed682e8 | 2 | public void onEvent(Event event) {
if (event instanceof ScannedRobotEvent) {
onScannedRobot((ScannedRobotEvent) event);
} else if (event instanceof RobotDeathEvent) {
onRobotDeath((RobotDeathEvent) event);
}
} |
7ddd2335-9831-447e-bee5-b704b6b02497 | 0 | public static void setOpenOrRead(boolean b) {
openOrRead = b;
} |
11d4f32b-7a8f-4662-8556-ef9dbb9da0f6 | 2 | public boolean hasDatumName(String datumName){
for (TileObjectDisplayDatum datum : displayData){
if (datum.getName().equals(datumName)){
return true;
}
}
return false;
} |
9876f79b-912d-45e6-957b-439e6cc61596 | 4 | public void run() {
try {
userInfo = new UserInfo();
Packet pc[];
userInfo.sendMessage("Send Info");
userInfo.setUser("Mahi");
oos.writeObject(userInfo);
oos.flush();
System.out.println("Connection established");
while (true)
{
pc = (Packet[])ois.readObject();
if(pc!=null)
{
updatePackets(pc);
}
}
} catch (Exception ex) {
System.out.println("Exception In run of new Client "+ ex);
}finally{
try {
ois.close();
oos.close();
} catch (Exception ex) {
}
}
} |
bc12b1f4-e6fc-4ec5-aac7-c1d2613fd0f1 | 8 | public String toString(){
StringBuffer sb = new StringBuffer();
switch(type){
case TYPE_VALUE:
sb.append("VALUE(").append(value).append(")");
break;
case TYPE_LEFT_BRACE:
sb.append("LEFT BRACE({)");
break;
case TYPE_RIGHT_BRACE:
sb.append("RIGHT BRACE(})");
break;
case TYPE_LEFT_SQUARE:
sb.append("LEFT SQUARE([)");
break;
case TYPE_RIGHT_SQUARE:
sb.append("RIGHT SQUARE(])");
break;
case TYPE_COMMA:
sb.append("COMMA(,)");
break;
case TYPE_COLON:
sb.append("COLON(:)");
break;
case TYPE_EOF:
sb.append("END OF FILE");
break;
}
return sb.toString();
} |
0991505e-c378-40a8-a0c5-0d46bd6c26e6 | 2 | public void loadPlanetImages(){
planetImages = new ArrayList();
int i = 0;
while(true){
String name = "planets/p_" + i + ".png";
File file = new File("images/" + name);
if(!file.exists()){
break;
}
//System.out.println(i + " : " + file);
planetImages.add(getSmallerImage(loadImage(name), .5f));
i++;
}
} |
1b114a10-6ef4-4dfa-b67a-f60a14668c1b | 1 | public Flyweight factory(String data) {
if (flies.containsKey(data)) {// files.containsKey是如果此映射包含对于指定
// 键的映射关系,则返回 true
return flies.get(data);// 返回指定键所映射的值;如果对
// 于该键来说,此映射不包含任何映射关系,则返回 null
} else {
Flyweight fly = new ConcreteFlyweight(data);
flies.put(data, fly);
return fly;
}
} |
d79de806-e8d6-425c-bc29-fa6d88730f20 | 5 | public static void main(String[] args)
{
Graph G = null;
try
{
G = new Graph(new In(args[0]));
}
catch (Exception e)
{
System.out.println(e);
System.exit(1);
}
int s = Integer.parseInt(args[1]);
IPaths paths = new Paths(G, s);
for (int v = 0; v < G.V(); v++)
{
System.out.print(s + " to " + v + " : ");
if (paths.hasPathTo(v))
for (int x : paths.pathTo(v))
if (x == s)
System.out.print(x);
else
System.out.print("-" + x);
System.out.println();
}
} |
de23239f-fa65-4e69-97e4-af43c23e6098 | 6 | protected void handleControlPropertyChanged(final String PROPERTY) {
if ("RESIZE".equals(PROPERTY)) {
resize();
} else if ("SELECTED".equals(PROPERTY)) {
getSkinnable().fireSelectEvent(getSkinnable().isSelected() ? new TButton.SelectEvent(getSkinnable(), getSkinnable(), TButton.SelectEvent.SELECT) : new TButton.SelectEvent(getSkinnable(), getSkinnable(), TButton.SelectEvent.DESELECT));
on.setVisible(getSkinnable().isSelected());
ledOn.setVisible(getSkinnable().isSelected());
off.setVisible(!getSkinnable().isSelected());
ledOff.setVisible(!getSkinnable().isSelected());
text.setTranslateY(getSkinnable().isSelected() ? (height - text.getLayoutBounds().getHeight()) * 0.49 + (3.0 / 144.0) * height : (height - text.getLayoutBounds().getHeight()) * 0.49);
} else if ("TEXT".equals(PROPERTY)) {
text.setText(getSkinnable().getText());
} else if ("LED_COLOR".equals(PROPERTY)) {
getSkinnable().setStyle("-led-color: " + Util.colorToCss(getSkinnable().getLedColor()) + ";");
ledOnGlow.setColor(getSkinnable().getLedColor());
ledOnInnerShadow.setColor(getSkinnable().getLedColor().darker().darker().darker());
ledOnInnerShadow1.setColor(getSkinnable().getLedColor().darker());
}
} |
438c7172-c789-4803-9bbc-b0c06281a01d | 3 | @Override
public void close()
{
if (isNotReady())
{
return;
}
for (Client c : clients)
{
c.close();
}
try
{
onClose();
}
catch (Exception e)
{
// ignore
}
clients.clear();
closed = true;
} |
f4c5a85f-fba0-4e33-8c15-eb11f4c1d0d3 | 4 | public static void main(String[] args) {
long start = System.nanoTime();
int max = 0;
for (int i = 100; i < 1000; i++) {
for (int j = 100; j < 1000; j++) {
int current = i * j;
if (isPalindromic(current) && current > max) {
max = current;
}
}
}
System.out.println(max);
System.out.println("Done in " + (double) (System.nanoTime() - start)
/ 1000000000 + " seconds.");
} |
f36f9d9d-f3ff-4103-9364-3080828d7ef3 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(consultap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(consultap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(consultap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(consultap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new consultap().setVisible(true);
}
});
} |
51c57ae9-87be-4520-ae1d-5e8309b57b01 | 5 | static boolean checkIfMove(String cmd) {
for (int i = 2; i < 10; i++) {
for (int j = 2; j < 10; j++) {
for (int k = 2; k < 10; k++) {
for (int l = 2; l < 10; l++) {
if (cmd.indexOf(Board.boardOfMoves[i][j] + Board.boardOfMoves[k][l]) != -1) {
receivedMove = Board.boardOfMoves[i][j] + Board.boardOfMoves[k][l];
return true;
}
}
}
}
}
return false;
} |
30aac187-aa09-4e50-8281-6f7ef10ddcc9 | 9 | public static void Seed_cycle(Network net, int stop) {
int i, j, k, n;
double h_err, delta, e;
double mse = 0.0F;
double err[] = new double[Config.NUM_OUTPUTS];
Neuron h;
for(i=0; i<stop; ++i) {
System.out.println("Cycle " + i + ", MSE " + mse/600);
mse = 0.0;
for(j=0; j<Config.NUM_SEED_EXAMPLES; ++j) {
for(k=0; k<Config.NUM_INPUTS; ++k)
net.input[k] = seed_in[j][k];
Sane_NN.Activate_net(net);
/* get output errors*/
for (k=0; k<Config.NUM_OUTPUTS; ++k)
err[k] = (seed_out[j][k] - net.sigout[k])
* net.sigout[k] * (1-net.sigout[k]);
for(k=0; k<Config.NUM_OUTPUTS; ++k) {
e = seed_out[j][k] - net.sigout[k];
mse += e*e;
}
/*error propogation*/
for(k=0; k<Config.NUM_HIDDEN; ++k) {
h = net.hidden[k];
h_err = 0.0;
for(n=0; n<h.numout; ++n) {
h_err += err[h.out_conn[n]] * h.out_weight[n];
delta = S_ETA * err[h.out_conn[n]] * h.sigout
+ S_ALPHA * h.out_delta[n];
h.out_weight[n] += delta;
h.out_delta[n] = (float) delta;
} /* end for-n */
if (h_err != 0.0F) {
h_err = h_err * h.sigout * (1.0F - h.sigout);
for(n=0;n<h.numin;++n) {
delta = S_ETA * h_err * Sane_Util.sgn(net.input[h.in_conn[n]])
+ S_ALPHA * h.in_delta[n];
h.in_weight[n] += delta;
h.in_delta[n] = (float) delta;
} /* end for-n */
} /* end if h-err */
} /* end for-k */
} /* end for-j */
} /* end for-i */
} /* end Seed_cycle */ |
7b1ab2f6-287e-499e-9c73-fbab99a5329d | 9 | public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
while ((line = in.readLine()) != null && line.length() != 0) {
int[] ab = readInts(line);
int a = ab[0], b = ab[1];
if (a == 0 && b == 0)
break;
double maxSize = Double.MIN_VALUE, size = 0;
int ans = Integer.MAX_VALUE;
for (int i = 1; i <= a; i++) {
size = (a / (1.0 * i)) - b;
if (size > 0) {
size = 0.3 * Math.sqrt(size) * i;
if (Math.abs(maxSize - size) <= 1e-12) {
ans = Integer.MAX_VALUE;
break;
} else if (size > maxSize) {
maxSize = size;
ans = i;
}
}
}
if (ans == Integer.MAX_VALUE)
out.append("0\n");
else
out.append(ans + "\n");
}
System.out.print(out);
} |
d9a53c91-9a0e-424d-81ad-acbab5e0ed3d | 0 | public int getPage() {
return page;
} |
2db8d451-22e9-4f12-a1e3-27a1e0d858f3 | 5 | public void onMessage( Message msg ) {
//deal with message from server
try {
msg.acknowledge(); // acknowledge to know that it is already received
String received = ((TextMessage)msg).getText();
if( registerInProgress ) {
registerInProgress = false;
System.out.println( "\n" + received );
/*
if( received.equals("Your account has been registered.\nYou can now logon and whisper.") ) {
registerInProgress = false;
}*/
return;
}
if(received.equals("!loginFailed")){
this.loginInProgress = false;
System.out.println("\n!Login Failed: Username or password is incorrect. ");
return;
}else{
this.user.setOnlineStatus(true);
this.loginInProgress = false;
}
//System.out.println(received.substring(0, 8)); //logging
// check if successful server join
if (received.substring(0, 8).equals("!Success")) {
// get the room id in the message
System.out.println(received);
String roomid = received.substring(received.indexOf(":") + 2);
// made chatroom
this.makingChatroomCheck = false;
this.completeJoinChatroom(roomid);
return;
}
// print receive message
System.out.println(received);
if (received.substring(0, 1).equals(">")) {
this.replyTo = received.substring(received.indexOf(" ", 11 ) + 1,
received.indexOf(":"));
}
} catch (JMSException e) {
e.printStackTrace();
}
return;
} |
fa062280-fa35-4f4f-9aa7-ef233c5ee7e3 | 5 | public void setData(GameData gd) {
// the towers
for (Entry<int[], Tower> entry : gd.getTowers().entrySet()) {
int[] pos = entry.getKey();
Tower tower = entry.getValue();
Tile t = map.get(pos[0] * size + pos[1]);
Field f = (Field) t;
tower.setField(f);
tower.addListener(listener);
towers.add(tower);
}
// the swamps
for (Entry<int[], Swamp> entry : gd.getSwamps().entrySet()) {
int[] pos = entry.getKey();
Swamp s = entry.getValue();
s.setListener(listener);
Tile prev = map.set(pos[0] * size + pos[1], s);
for (Tile t : prev.getNeighbours()){
s.setNeighbour(t);
}
// tell neighbouring tiles that they have a new neighbour
for (Tile tl : s.getNeighbours()) {
tl.setNeighbour(s);
tl.removeNeighbour(prev);
}
}
// restoring the enemies
for (Entry<int[], Enemy> entry : gd.getEnemies().entrySet()) {
// get the values
int[] pos = entry.getKey();
Enemy e = entry.getValue();
// get the tile
Tile t = map.get(pos[0] * size + pos[1]);
// add the enemy
((Road) t).enter(e);
}
// set the MP
MagicPower.setMP(gd.getMp());
// set the gem
gem = gd.getGem();
//the counter
this.counter=gd.getCounter();
} |
18a9da56-2694-4163-9e75-edd76cc31b54 | 1 | public static List<Couleur> selectCouleur(String libelle) throws SQLException {
String query;
List<Couleur> couleurs = new ArrayList<Couleur>();
Couleur couleur;
ResultSet resultat;
query = "SELECT * from COULEUR";
PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query);
resultat = pStatement.executeQuery();
while (resultat.next()) {
couleur = new Couleur(resultat.getInt("ID_COULEUR"), resultat.getString("COULIBELLE"));
couleurs.add(couleur);
}
return couleurs;
} |
ca3172d4-56f5-43e3-94fd-00f923b94d25 | 3 | public boolean updatePassword(Token t, User u, Map<String,String> parameters)
{
if (!parameters.containsKey("current_password") || !parameters.containsKey("password"))
{
GoCoin.log(new Exception("Invalid parameters for resetPasswordWithToken!"));
return false;
}
//TODO: pull out map keys as constants
String path = "/users/"+u.getId()+"/password";
//get a new http client and set the options
//NOTE: since its a post request, the parameters get converted into JSON
HTTPClient client = GoCoin.getHTTPClient();
client.setRequestOption(HTTPClient.KEY_OPTION_PATH,path);
client.setRequestOption(HTTPClient.KEY_OPTION_METHOD,HTTPClient.METHOD_PUT);
client.addAuthorizationHeader(t);
//create the json map
Map<String,String> body = new LinkedHashMap<String,String>();
body.put("current_password",parameters.get("current_password"));
body.put("currentpassword",parameters.get("current_password"));
body.put("password",parameters.get("password"));
body.put("newpassword",parameters.get("password"));
//set the body
client.setRequestBody(GoCoin.toJSON(body));
try
{
//make the PUT request
client.doPUT(client.createURL(HTTPClient.URL_TYPE_API));
//check the response
GoCoin.checkResponse(client);
//return true if we got a 204
return true;
}
catch (Exception e)
{
GoCoin.log(e);
return false;
}
} |
fe0c9511-759a-4b48-8ded-86ea8f420c48 | 8 | private void read(SocketSessionImpl session) {
ByteBuffer buf = ByteBuffer.allocate(session.getReadBufferSize());
SocketChannel ch = session.getChannel();
try {
int readBytes = 0;
int ret;
try {
while ((ret = ch.read(buf.buf())) > 0) {
readBytes += ret;
}
} finally {
buf.flip();
}
session.increaseReadBytes(readBytes);
if (readBytes > 0) {
session.getFilterChain().fireMessageReceived(session, buf);
buf = null;
if (readBytes * 2 < session.getReadBufferSize()) {
session.decreaseReadBufferSize();
} else if (readBytes == session.getReadBufferSize()) {
session.increaseReadBufferSize();
}
}
if (ret < 0) {
scheduleRemove(session);
}
} catch (Throwable e) {
if (e instanceof IOException)
scheduleRemove(session);
session.getFilterChain().fireExceptionCaught(session, e);
} finally {
if (buf != null)
buf.release();
}
} |
61f67d35-63b8-4090-a25b-1bf77af10f8e | 7 | public boolean searchMatrix(int[][] matrix, int target) {
int len = matrix.length;
int i;
for(i=0;i<len;i++) {
if(matrix[i][0] == target) {
return true;
}else if(matrix[i][0] > target) {
break;
}
}
if(i==0) {
return false;
}
if(matrix[i-1][matrix[0].length-1] < target) {
return false;
}
int rowLen = matrix[0].length;
for(int j=rowLen-1;j>0;j--) {
if(matrix[i-1][j] == target) {
return true;
}
}
return false;
} |
0f89f487-1eee-458a-b431-f97996333da3 | 1 | public void setStatustextZoomedFontstyle(Fontstyle fontstyle) {
if (fontstyle == null) {
this.statustextZoomedFontStyle = UIFontInits.STATUSZOOMED.getStyle();
} else {
this.statustextZoomedFontStyle = fontstyle;
}
somethingChanged();
} |
3916ba70-2a10-435a-8b66-b8dc2797041c | 8 | public void actionPerformed(ActionEvent event) {
Object target = event.getSource();
if (target instanceof JMenuItem) {
JMenuItem item = (JMenuItem)target;
int[] indexes = fOnlineList.getSelectedIndexes();
if (indexes == null || indexes.length == 0)
return;
if (item == fCopyIntoToMenu) {
String toList = "";
for (int i = 0; i < indexes.length; i++) {
toList += fOnlineList.getItem(indexes[i]);
if ((i + 1) < indexes.length)
toList += ", ";
}
fMainUI.setToList(toList);
setAllSelected(false);
} else if (item == fOpenMessagingDialogMenu) {
openAction(indexes);
setAllSelected(false);
} else if (item == fSelectAllMenu)
setAllSelected(true);
}
} |
0dbd2040-ece8-4301-9277-58564baf5d44 | 2 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((col == null) ? 0 : col.hashCode());
result = prime * result + ((row == null) ? 0 : row.hashCode());
return result;
} |
6be54b97-2ebd-43e7-abd9-9781052368dd | 8 | @Override
public boolean equals(Object o)
{
if(o == null)
return false;
if(!(o instanceof Stueckliste))
return false;
Stueckliste stl = (Stueckliste)o;
if(!stl.getBauteil().equals(this.getBauteil()))
return false;
if(!stl.getGueltigAb().equals(this.getGueltigAb()))
return false;
if(!stl.getGueltigBis().equals(this.getGueltigBis()))
return false;
if(stl.getId()!=this.getId())
return false;
if(stl.getPositionen().size() != this.getPositionen().size())
return false;
if (!stl.getPositionen().equals(this.getPositionen()))
return false;
return true;
} |
7ef02c96-3e9e-417a-a350-a0ab7940d693 | 0 | public void setLastName(String lastName) {
this.lastName = lastName;
} |
6a320a5e-5756-4a88-88a5-4a7bd4957a82 | 7 | public void transferHeatToParticles(List list, double amount) {
if (list == null || list.isEmpty())
return;
double k0 = getKEOfParticles(list);
if (k0 < ZERO)
assignTemperature(list, 1);
Atom a = null;
Object o = null;
for (Iterator it = list.iterator(); it.hasNext();) {
o = it.next();
if (o instanceof Atom) {
a = (Atom) o;
k0 = EV_CONVERTER * a.mass * (a.vx * a.vx + a.vy * a.vy);
if (k0 <= ZERO)
k0 = ZERO;
k0 = (k0 + amount) / k0;
if (k0 <= ZERO)
k0 = ZERO;
k0 = Math.sqrt(k0);
a.vx *= k0;
a.vy *= k0;
}
}
} |
12bcbad1-c069-447f-832e-e0ce40b88cf6 | 0 | @Override
public String toString() {
return "Value: " + value + " Unit: " + unit;
} |
a6cc4d0d-d866-4ac2-98d4-f1a168530e5b | 3 | public void TakeCape(String god, int reqSkillNum, int lvlReq, int XPSkillNum, int XPamount, int item, int itemAmount, int delay, int emote) {
if(theifTimer == 0) {
if(playerLevel[reqSkillNum] >= lvlReq) {
setAnimation(emote);
sendMessage("You bow down to "+god);
sendMessage("You recieve the cape of "+god+".");
addSkillXP(XPamount, XPSkillNum);
addItem(item, itemAmount);
theifTimer = delay;
}
else if(playerLevel[reqSkillNum] < lvlReq) {
sendMessage("You need a "+statName[reqSkillNum]+" level of "+lvlReq+" to pray to "+god+".");
}
}
} |
57612707-ac84-4108-8e6a-c5df169ebf46 | 1 | @Override
public void run() {
if(TreasureHunt.getInstance().started)
TreasureManager.getInstance().startTreasureHunt();
else
TreasureHunt.getInstance().started = true;
} |
d125548e-d522-4db3-86dd-ff3dddde5aae | 4 | private GameStatus MapSpielZustand(Spielzustaende spielzustaende) {
switch (spielzustaende) {
case Armeen_hinzufuegen:
return GameStatus.PlacingUnits;
case Angriff:
return GameStatus.Attack;
case Verschieben:
return GameStatus.Move;
case Beenden:
return GameStatus.Finished;
default:
throw new RuntimeException("Gamestatus not defined");
}
} |
94fb8cc2-dce2-4243-9d4e-de58d00974f0 | 2 | public void testPropertySetWeekOfWeekyear() {
DateTime test = new DateTime(2004, 6, 7, 0, 0, 0, 0);
DateTime copy = test.weekOfWeekyear().setCopy(4);
assertEquals("2004-06-07T00:00:00.000+01:00", test.toString());
assertEquals("2004-01-19T00:00:00.000Z", copy.toString());
try {
test.weekOfWeekyear().setCopy(54);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.weekOfWeekyear().setCopy(0);
fail();
} catch (IllegalArgumentException ex) {}
} |
96bf045e-ef25-4d55-845e-9ba72ff79724 | 3 | public void allow() {
try {
if (process != null)
process.exitValue();
process = Runtime.getRuntime().exec(BROWSER_BINARY);
} catch (IllegalThreadStateException e) {
/* process is still running */
} catch (IOException e) {
e.printStackTrace();
}
} |
a77e64fb-6381-48b3-9fc3-215e47e9c4f0 | 2 | private boolean isKColorable(int k) {
for(HashSet<Value> edges : adjacencyList.values()) {
if(edges.size() >= k) {
return false;
}
}
return true;
} |
dc38eb33-6db9-4279-a633-4c68c60efdb6 | 9 | public void setReadings (List<Reading> readings) {
XModel model = null;
try {
model = As.XModel (this.textDocument);
model.lockControllers();
this.paragraphCursor.gotoStartOfParagraph (false);
this.paragraphCursor.gotoEndOfParagraph (true);
this.viewCursor.gotoRange (this.paragraphCursor, false);
XTextCursor textCursor = this.viewCursor.getText().createTextCursorByRange (this.paragraphCursor);
XPropertySet propertySet = As.XPropertySet (textCursor);
XPropertyState propertyState = As.XPropertyState (textCursor);
propertyState.setPropertyToDefault ("RubyText");
propertyState.setPropertyToDefault ("RubyAdjust");
int index = 0;
TextPortionIterator textPortionIterator = new TextPortionIterator (this.paragraphCursor);
Object textPortion = textPortionIterator.nextTextPortion();
for (Reading reading : readings) {
// Find start
XTextRange readingStart = null;
XTextRange readingEnd = null;
boolean startFound = false;
while (!startFound && (textPortion != null)) {
XTextRange textRange = As.XTextRange (textPortion);
String content = textRange.getString();
if (reading.start < (index + content.length())) {
textCursor.gotoRange (textRange.getStart(), false);
textCursor.goRight ((short)(reading.start - index), false);
readingStart = textCursor.getStart();
startFound = true;
} else {
index += content.length();
textPortion = textPortionIterator.nextTextPortion();
}
}
// Find end
boolean endFound = false;
while (!endFound && (textPortion != null)) {
XTextRange textRange = As.XTextRange (textPortion);
String content = textRange.getString();
if ((reading.start + reading.length - 1) < (index + content.length())) {
textCursor.gotoRange (textRange.getStart(), false);
textCursor.goRight ((short)(reading.start + reading.length - index), false);
readingEnd = textCursor.getStart();
endFound = true;
} else {
index += content.length();
textPortion = textPortionIterator.nextTextPortion();
}
}
// Set reading
textCursor.gotoRange (readingStart, false);
textCursor.gotoRange (readingEnd, true);
propertySet.setPropertyValue ("RubyText", reading.text);
propertySet.setPropertyValue ("RubyAdjust", new Short ((short)RubyAdjust.CENTER.getValue()));
}
} catch (Throwable t) {
ExceptionHelper.dealWith (t);
} finally {
if (model != null) {
model.unlockControllers();
}
}
} |
b89c6d15-b74c-4a0d-8c50-dec6a565ad89 | 1 | public void printWall(){
for (Message m : this.wall) {
System.out.println(m);
}
} |
138a2d65-bfe0-47c2-bd3d-2a6ad32534a6 | 8 | private Vector extractViewCommentFromHTML(String scriptName)
{
if (lastHTMLReply == null)
{
if (debugLevel>0)
System.err.println("Thread "+this.getName()+": There is no previous HTML reply<br>");
return null;
}
int[] pos = randomComputeLastIndex(scriptName, true);
if (pos == null)
return null;
// Now we have chosen a 'scriptName?...' we can extract the parameters
String comment_table = null;
Integer storyId = null;
Integer commentId = null;
Integer filter = null;
Integer display = null;
int newLast = computeLastIndex("comment_table=", pos[1]);
if (newLast != pos[1])
comment_table = lastHTMLReply.substring(pos[1]+"comment_table=".length()+1, newLast);
pos[1] = newLast;
newLast = computeLastIndex("storyId=", pos[1]);
if (newLast != pos[1])
storyId = new Integer(lastHTMLReply.substring(pos[1]+"storyId=".length()+1, newLast));
pos[1] = newLast;
newLast = computeLastIndex("commentId=", pos[1]);
if (newLast != pos[1])
commentId = new Integer(lastHTMLReply.substring(pos[1]+"commentId=".length()+1, newLast));
pos[1] = newLast;
newLast = computeLastIndex("filter=", pos[1]);
if (newLast != pos[1])
filter = new Integer(lastHTMLReply.substring(pos[1]+"filter=".length()+1, newLast));
pos[1] = newLast;
newLast = computeLastIndex("display=", pos[1]);
if (newLast != pos[1])
display = new Integer(lastHTMLReply.substring(pos[1]+"display=".length()+1, newLast));
Vector result = new Vector(5);
result.add(comment_table);
result.add(storyId);
result.add(commentId);
result.add(filter);
result.add(display);
return result;
} |
0b8b0da4-3a23-4bda-9d40-00cef4f7e14f | 4 | public int find(int x) {
checkValidElement(x);
int root = x;
while (root >= 0 && up[root] >= 0) // find element
root = up[root];
if (x != root) { // if x not a root, do path compression
int oldParent = up[x]; // prime loop
while (oldParent != root) {
up[x] = root; // point directly at your root; this is the path compression.
x = oldParent; // go one level up the tree
oldParent = up[x];
}
}
return root;
} |
22c19748-fee7-4d50-b3a3-901cb77870fb | 7 | public String toString() {
String ret;
switch (ttype) {
case TT_EOF:
ret = "EOF";
break;
case TT_EOL:
ret = "EOL";
break;
case TT_WORD:
ret = sval;
break;
case TT_NUMBER:
ret = "n=" + nval;
break;
case TT_NOTHING:
ret = "NOTHING";
break;
default: {
/*
* ttype is the first character of either a quoted string or
* is an ordinary character. ttype can definitely not be less
* than 0, since those are reserved values used in the previous
* case statements
*/
if (ttype < 256 &&
((ctype[ttype] & CT_QUOTE) != 0)) {
ret = sval;
break;
}
char s[] = new char[3];
s[0] = s[2] = '\'';
s[1] = (char) ttype;
ret = new String(s);
break;
}
}
return "Token[" + ret + "], line " + LINENO;
} |
c4357f46-509e-43ff-bdb4-a0cdc02da48b | 3 | public boolean isMesmoDia(Calendar dia){// nao vai funcionar com compareTo nem equls por causa das horas
if(this.data.get(Calendar.YEAR) == dia.get(Calendar.YEAR) ){
if(this.data.get(Calendar.MONTH) == dia.get(Calendar.MONTH) ){
if(this.data.get(Calendar.DAY_OF_MONTH) == dia.get(Calendar.DAY_OF_MONTH) ){
return true;
}
}
}
return false;
} |
7ee134ca-2192-4a79-b722-fc43d1967289 | 9 | */
@Override
public LegendItemCollection getLegendItems() {
if (this.fixedLegendItems != null) {
return this.fixedLegendItems;
}
LegendItemCollection result = new LegendItemCollection();
int count = this.datasets.size();
for (int datasetIndex = 0; datasetIndex < count; datasetIndex++) {
XYDataset dataset = getDataset(datasetIndex);
if (dataset != null) {
XYItemRenderer renderer = getRenderer(datasetIndex);
if (renderer == null) {
renderer = getRenderer(0);
}
if (renderer != null) {
int seriesCount = dataset.getSeriesCount();
for (int i = 0; i < seriesCount; i++) {
if (renderer.isSeriesVisible(i)
&& renderer.isSeriesVisibleInLegend(i)) {
LegendItem item = renderer.getLegendItem(
datasetIndex, i);
if (item != null) {
result.add(item);
}
}
}
}
}
}
return result;
} |
4cab5ed9-3420-4538-b4ce-8b99eaee2078 | 9 | public static double sqrt(double a) throws IllegalArgumentException {
if(a == 0) {
return 0;
}
if (a < 0) {
throw new IllegalArgumentException("Can not sqrt a negative number!");
}
// write a as m * 10^2n where 1 < m < 100
// then sqrt(a) is around 1.8 * 10^n or 5.6 * 10^n depending on m
// 1.8 ~ geometric mean of sqrt(1) and sqrt(10). (when m is between 1 and 10)
// 5.6 ~ geometric mean of sqrt(10) and sqrt(100). (when m is between 10 and 100)
// see http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Rough_estimation for more info
double mantissa = a;
double tenToTheN = 1;
if (a >= 100) {
while (mantissa / 100 > 1) {
mantissa /= 100;
tenToTheN = tenToTheN * 10;
}
} else if (a < 1) {
while (mantissa * 100 <= 1) {
mantissa *= 100;
tenToTheN = tenToTheN / 10;
}
}
double roughEstimation;
if (mantissa < 10) {
roughEstimation = 1.8 * tenToTheN;
} else {
roughEstimation = 5.6 * tenToTheN;
}
// newton's method
// sqrt(a) is same as solving for x in the following:
// x^2 - a = 0
// f(x) = x^2 - a
// f'(x) = 2x
// see http://en.wikipedia.org/wiki/Methods_of_computing_square_roots for more info
// loop should break well before max_iteration_count
final int max_iteration_count = 40;
double x = roughEstimation;
for (int i = 1; i < max_iteration_count; i++) {
double x_n = 0.5 * (x + (a / x));
if(abs(x_n - x) < Double.MIN_VALUE) {
x = x_n;
return x;
}
x = x_n;
}
return x;
} |
7d3355cf-4ff0-4177-8191-c383052f2233 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(OperaCadenas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OperaCadenas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OperaCadenas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OperaCadenas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OperaCadenas().setVisible(true);
}
});
} |
c0dcdde9-6ab2-48cf-8035-6a2f55876ffe | 5 | public static byte[] toByteArray(Serializable object)
{
ByteArrayOutputStream bOS = null;
ObjectOutput oOS = null;
byte[] bytes = null;
try { // Write object to a byte[] using ByteArrayOutputStream and ObjectOutputStream
bOS = new ByteArrayOutputStream ();
oOS = new ObjectOutputStream (bOS);
oOS.writeObject (object);
bytes = bOS.toByteArray ();
} catch (IOException e) {
e.printStackTrace ();
} finally { // Close ByteArrayOutputStream and ObjectOutputStream
if (bOS != null) {
try {
bOS.close ();
} catch (IOException ex) {}
}
if (oOS != null) {
try {
oOS.close ();
} catch (IOException ex) {}
}
}
return bytes;
} |
6e38ac2c-0fda-4c55-9a95-00303836d926 | 0 | public static String readFileUtf8(String path) throws IOException {
return readFile(path, Charset.forName("UTF8"));
} |
fbd9007d-4d57-4512-8cd7-678e6896d21d | 3 | public static TreePath getNextMatch(JTree tree, String prefix) {
int max = tree.getRowCount();
if (prefix == null) {
throw new IllegalArgumentException();
}
// start search from the next/previous element froom the selected element
int row = 0;
do {
TreePath path = tree.getPathForRow(row);
String text = tree.convertValueToText(path.getLastPathComponent(), tree.isRowSelected(row), tree.isExpanded(row), true, row, false);
if (text.startsWith(prefix)) {
return path;
}
row = (row + 1 + max) % max;
} while (row != 0);
return null;
} |
cf3960d6-32d9-4993-9e86-57e6aeb9f0ad | 0 | Type getType()
{
return type;
} |
88454a8d-d616-4937-a1c3-f2870915ea54 | 5 | public static ArrayList<String> createTagPool(Map imagesTags) {
if (PRINT == 1)
System.out.println("Creating tagpool...\n");
ArrayList<String> tagpool = new ArrayList<String>();
/* Iterate through the map */
Iterator itMap = imagesTags.entrySet().iterator();
while (itMap.hasNext()) {
Map.Entry pairFromMap = (Map.Entry) itMap.next();
/* Select the list of tags in the pair (ArrayList) */
ArrayList tagList = (ArrayList) pairFromMap.getValue();
/* Iterate through that list and add tags */
for (String s : (ArrayList<String>) tagList) {
/* If it doesn't already include the tag... */
if (!(tagpool.contains(s))) {
tagpool.add(s);
}
}
}
if (PRINT == 1)
System.out.println("Created tagpool.\n");
return tagpool;
} |
ad990d23-290e-412a-a477-cfd9693149b5 | 9 | public Object saveState(FacesContext context) {
if (context == null) {
throw new NullPointerException();
}
if (attachedObjects == null) {
return null;
}
if (initialState) {
Object[] attachedObjects = new Object[this.attachedObjects.size()];
boolean stateWritten = false;
for (int i = 0, len = attachedObjects.length; i < len; i++) {
T attachedObject = this.attachedObjects.get(i);
if (attachedObject instanceof StateHolder) {
StateHolder sh = (StateHolder) attachedObject;
if (!sh.isTransient()) {
attachedObjects[i] = sh.saveState(context);
}
if (attachedObjects[i] != null) {
stateWritten = true;
}
}
}
return ((stateWritten) ? attachedObjects : null);
} else {
Object[] attachedObjects = new Object[this.attachedObjects.size()];
for (int i = 0, len = attachedObjects.length; i < len; i++) {
attachedObjects[i] = UIComponentBase.saveAttachedState(context, this.attachedObjects.get(i));
}
return (attachedObjects);
}
} |
fb4b9114-5a8a-495a-b630-8e83b9d32b27 | 4 | public static void main(String[] args) throws IOException, InterruptedException
{
Controller appli = null;
//System.out.println(System.getProperty("os.version")); System.exit(0);
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
Logger.init("trace.log");
if( args.length > 0)
appli = new Controller( args[0] ); // launch with a config file
else
appli = new Controller();
appli.launch();
} |
ad6701d5-c455-4ffa-ad6a-fb2b08f6919d | 5 | private Path nearestPath(String s){
List<Path> potential = new ArrayList<Path>();
List<Path> next = new ArrayList<Path>();
TrieNode node = getNode(s);
//That node doesn't exist.
if(node == null) return null;
Path top = new Path(node);
potential.add(top);
while(!potential.isEmpty()){
for(Path p : potential){
if(p.getNode().isWord()){
//Success! We're a valued node!
return p;
} else{
//We have potential paths under us, even if we're not successful.
//So, add those potential paths. If we have no children, this path
//will just be ignored. But WTF, how did we get a null at the
//leaf of the tree?
for(Entry<Character, TrieNode> entry : p.getNode().getChildMap().entrySet()){
Character c = entry.getKey();
TrieNode child = entry.getValue();
Path q = new Path(p, child, c);
next.add(q);
}
}
}
//Move next into potential.
potential.clear();
potential.addAll(next);
next.clear();
}
//This will occur when some moron puts null values in our leaves
return null;
} |
66bc8897-629c-4878-bf4e-0318ce1a21de | 2 | public void commit(Transaction t) {
for(int i: t.getWriteVars()) {
if(hasVariable(i)) {
variablesSnapshot.put(i, variables.get(i));
}
}
accessTransactionLog.remove(t);
} |
0c64ed10-cf08-4e47-8efc-a2d922146f2a | 8 | @Override
public Types.MOVEMENT activeMovement(VGDLSprite sprite, Direction action, double speed)
{
if(speed == 0)
{
if(sprite.speed == 0)
speed = 1;
else
speed = sprite.speed;
}
if(speed != 0 && action != null && !(action.equals(Types.DNONE)))
{
if(sprite.rotateInPlace)
{
boolean change = sprite._updateOrientation(action);
if(change)
return Types.MOVEMENT.ROTATE;
}
if(sprite._updatePos(action, (int) (speed * this.gridsize.width)))
return Types.MOVEMENT.MOVE;
}
return Types.MOVEMENT.STILL;
} |
9653f34e-00e5-480b-b4bf-8380646ae912 | 9 | public static int maxDepth(TreeNode root) {
if(root==null) return 0;
Stack<TreeNode> stack = new Stack<TreeNode>();
HashMap<TreeNode, Integer> depthTable = new HashMap<TreeNode, Integer>();
stack.add(root);
depthTable.put(root,1);
int maxDepth = 1;
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
Integer depth = depthTable.get(node);
if(!(node.right==null || depthTable.containsKey(node.right))) {
stack.add(node.right);
depthTable.put(node.right, depth+1);
}
if(!(node.left==null || depthTable.containsKey(node.left))) {
stack.add(node.left);
depthTable.put(node.left, depth+1);
}
if(node.left==null && node.right==null) {
if(depth>maxDepth) {
maxDepth = depth;
}
}
}
return maxDepth;
} |
4253ad6c-1b06-4d2e-961e-530b15b00703 | 7 | public void allocatePartPERanges(int partId, PERangeList selected,
double startTime, double finishTime) {
if(partId >= partitions.length || partId < 0) {
throw new IndexOutOfBoundsException("Partition " + partId +
" does not exist.");
}
Iterator<ProfileEntry> it = avail.itValuesFromPrec(startTime);
PartProfileEntry last = (PartProfileEntry)it.next();
PartProfileEntry newAnchor = null;
// The following is to avoid having to iterate the
// profile more than one time to update the entries.
if(Double.compare(last.getTime(),startTime) == 0) {
last.increaseJob();
}
else {
newAnchor = last.clone(startTime);
last = newAnchor;
}
PartProfileEntry nextEntry = null;
while(it.hasNext()) {
nextEntry = (PartProfileEntry)it.next();
if(nextEntry.getTime() <= finishTime) {
last.getAvailRanges(partId).remove(selected);
last = nextEntry;
continue;
}
break;
}
if(Double.compare(last.getTime(),finishTime) == 0) {
last.increaseJob();
}
else {
add(last.clone(finishTime));
last.getAvailRanges(partId).remove(selected);
}
if(newAnchor != null) {
add(newAnchor);
}
} |
82143a87-844d-4491-b936-e2d7ae5b8f38 | 0 | public void incrementFood() {
this.food++;
} |
fc516efa-6bd6-4b01-96c9-68df99033143 | 1 | public void removeAdmin(String name) {
String delete = "DELETE FROM ADMIN WHERE NAME=?";
try {
PreparedStatement ps = conn.prepareStatement(delete);
ps.setString(1, name);
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
} |
1d6ec2fa-d091-4be4-aa66-36326010a2ce | 1 | public void previousQuestion()
{
if(i == 0)
{
i = QuestionCount -1;
}
else
{
// Current Question Id incremented by 1
i--;
}
// Display question in form
this.setUp();
} |
5a4dcf11-fbb1-4909-916b-8bd5d42d28bf | 2 | public INISection getSection(String name){
for(INISection section : sections){
if(section.getName().equals(name)){
return section;
}
}
Debug.error("Section '" + name + "' does not exist!");
return null;
} |
b138f2c3-a783-4ae5-a203-3d519c538baa | 5 | @Override
public void run() {
if (bot.hasMessage()) {
message = bot.getMessage();
channel = bot.getChannel();
}
if (this.message.startsWith("~kick")) {
Vote.voteYes = 0;
Vote.voteNo = 0;
Vote.voters.clear();
tokenize(false, 5, message);
User[] users = Main.bot.getUsers(channel);
String totalUsers = "";
int userCount = 0;
int voteRequired = 1;
for (User user : users) {
++userCount;
totalUsers = totalUsers + " " + user.toString();
}
voteRequired = 2;
Main.bot.sendMessage(channel, totalUsers);
Main.bot.sendMessage(channel, "A vote was called (!vote y, or !vote n): [" + voteRequired + "/" + userCount + "]");
try {
Thread.sleep(30000L);
} catch (InterruptedException ex) {
Logger.getLogger(Kick.class.getName()).log(Level.SEVERE, null, ex);
}
Main.bot.sendMessage(channel, "yes: " + Vote.voteYes + " no: " + Vote.voteNo);
if ( (Vote.voteYes - Vote.voteNo) >= voteRequired ) {
Main.bot.kick(channel, parameters, "vote success.");
} else {
Main.bot.sendMessage(channel, "Vote failed.");
return;
}
}
} |
3ec0959e-e0d0-4768-9027-c1e29dad3f14 | 3 | public void renderPlayer(int xp, int yp, Sprite sprite) {
for (int y = 0; y < 32; y++) {
int ya = yp + y;
for (int x = 0; x < 32; x++) {
int xa = xp + x;
int color = sprite.pixels[x + y * 32];
if (color != 0xFFFF00FF) {
pixels[xa + ya * WIDTH] = color;
}
}
}
} |
fa1089b7-93ec-4221-b4d8-ec8d90d7ee02 | 3 | public static final long pow(long x, long n) throws Exception {
if(n < 0) return div (1, pow (x, (0 - n)));
long r = 1;
while (n != 0) {
if ((n & 1L) != 0) r = mul(r, x);
n >>= 1;
x = mul(x, x);
}
return r;
} |
af1ff64e-62d9-4bd3-94e6-23439043e1f6 | 5 | public Boolean book(User currentUser, Integer borrowableId,
Integer quantity, Integer borrowerId, Date start, Date end,
String reason) {
// Date verifications
// Time before the beggining of the booking (reservation)
DateInterval reservationStartInterval = new DateInterval(new Date(),
start);
if (reservationStartInterval.getLength() > currentUser
.getMaxReservationLength()) {
return false;
}
// Duration of the booking
DateInterval bookingInterval = new DateInterval(start, end);
if (bookingInterval.getLength() > currentUser.getMaxBookingLength()) {
return false;
}
BorrowableStock currentStock = this.stock.get(borrowableId);
// Get the current booking total
Integer totalItems = currentStock.getCalendar()
.getCurrentBorrowedTotal(borrowerId);
if (currentStock == null
|| !currentStock.isAvailable(quantity, start, end)
|| !currentStock.getModel().canBook(
currentUser.getUserType().toString(),
reservationStartInterval.getLength(),
bookingInterval.getLength(), totalItems)) {
return false;
}
return currentStock.getCalendar().book(borrowerId, quantity,
bookingInterval, reason, currentStock.getModel());
} |
d344a4ab-b593-432c-bb36-eadf706ebd02 | 2 | public double[][] getArrayCopy(){
double[][] c = new double[this.numberOfRows][this.numberOfColumns];
for(int i=0; i<numberOfRows; i++){
for(int j=0; j<numberOfColumns; j++){
c[i][j]=this.matrix[i][j];
}
}
return c;
} |
5bc1d085-4522-4cf9-8a14-59daea6d5c29 | 3 | 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++;
}
}
} |
5e3fbb56-e239-436b-b488-fed5272a182d | 8 | public String rechercher() throws IOException {
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String inputLine;
System.out.println(recherche());
inputLine = br.readLine();
String[] part = inputLine.split(" ");
switch(Integer.decode(part[0]))
{
case 1:
for(String str : iPub.getExistingHashtags()) {
System.out.println(str + "\n");
}
return rechercher();
case 2:
System.out.println("Entrez le roartag à rechercher >> ");
inputLine = br.readLine();
break;
case 3:
for(String str : iPub.getRegisteredusers()) {
System.out.println(str + "\n");
}
return rechercher();
case 4:
System.out.println("Entrez l'auteur à rechercher >> ");
inputLine = br.readLine();
break;
}
System.out.println("Recherche en cours...");
if(Integer.decode(part[0]) == 4)
return pullAuteur(20, inputLine);
if(Integer.decode(part[0]) == 2)
return pullHastag(20, inputLine);
return "Erreur";
} |
52d84f78-efeb-411c-94bf-1190e37e8619 | 8 | private Point yBinarySearch(Point bottom, Point top) {
int x = bottom.x; // the same for right and left
Point mid;
while (true) {
if (abs(bottom.y - top.y) == 1) {
if (abs(bottom.dF) <= abs(top.dF)) {
return bottom;
} else {
return top;
}
}
mid = new Point(x, (top.y + bottom.y) / 2);
if (mid.dF == 0 || mid.dF == bottom.dF || mid.dF == top.dF) return mid;
//System.out.println((mid.dF + " : " + left.dF + " :: " + right.dF));
//System.out.println("left.x : " + left.x + " right x : " + right.x + " x : " + mid.x);
if (mid.dF * bottom.dF < 0) {
bottom = mid;
}
if (mid.dF * top.dF < 0) {
top = mid;
}
}
} |
e848c9e5-67e9-45b6-84d3-aea740b0cdd5 | 6 | public static boolean isdni(String dni){
boolean aux=false;
if(dni.length()!=9){//tiene que tener 9 caracteres
aux=false;
}else if((dni.charAt(dni.length()-1))>90 ||(dni.charAt(dni.length()-1))<65){//mirar si el ultimo es letra
aux=false;
}else{//mirar que los 8 primeros sean numeros
int i=0;
do{
i++;
}while(dni.charAt(i)>47 && dni.charAt(i)<58);
if(i!=8){
aux=false;
}else{
aux=true;
}
}
return aux;
} |
dd8054c9-a5e7-4563-b91a-941499bbaa8f | 7 | private boolean colorExists(P p, int x, int y) {
for (int i = 0; i < this.tabSizeX; i++) {
for (int j = 0; j < this.tabSizeY; j++) {
if (x==i && y==j && x>=0 && y>=0) continue; // nie sprawdzam sama siebie bo sie zapetle ;)
if (this.P[i][j].colorMatch(p)) return true;
}//j
}//i
return false;
} |
8412f19e-4c26-43f9-9974-75ee0487872f | 4 | @Override
public Description select(int id) {
Description description = null;
ResultSet result;
try {
result = this .connect
.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE
).executeQuery(
"SELECT * FROM Description "+
"INNER JOIN (Composer_Lien INNER JOIN Lien ON Composer_Lien.Id_Lien = Lien.Id_Lien) ON Description.Id_Description = Composer_Lien.Id_Description INNER JOIN Image ON Description.Id_Description = Image.Id_Description WHERE Description.Id_Description ="+id
);
if(result.first()){
LinkDao lienDao = new LinkDao();
ImageDao imageDao = new ImageDao();
ArrayList<Link> listLien = new ArrayList<>();
ArrayList<Image> listImage = new ArrayList<>();
result.beforeFirst();
while(result.next())
listLien.add(lienDao.select(result.getInt("Id_Lien")));
result.beforeFirst();
while(result.next())
listImage.add(imageDao.select(result.getInt("Id_Image")));
result.first();
description = new Description(id, result.getString("Texte_Description"), listLien, listImage);
}
} catch (SQLException ex) {
Logger.getLogger(PlaceDao.class.getName()).log(Level.SEVERE, null, ex);
}
return description;
} |
9f6b122d-29a5-4244-b191-43ff97360086 | 1 | public long computeHashValueForPattern(String pattern, int patternLength) {
long hash = 0;
for(int index = 0; index < patternLength; index++) {
hash = (hash * alphabet + pattern.charAt(index)) % primeNumber;
comparisons++;
}
return hash;
} |
696fe2c1-3fd4-426d-bd52-af3910b32c0f | 7 | private void generateCampo() {
window.getContentPane().removeAll(); // rimuovo tutti gli oggetti dentro al jpanel quindi bottoni e tutto
boolean b = false; // necessario per stampare il colore del background dei bottoni che fa da sfondo scacchiera
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) { // doppio for per scorrere tutto il campo fittizio
campoB[i][j] = new ButtonPieces((b) ? Color.GRAY : Color.WHITE, i, j, this, (i * 8 + j)); // ad ogni i,j genero un bottone che (dipendente da b) sarà grigio o bianco
window.add(campoB[i][j]); // aggiungerà alla finestra il bottone e le sue proprietà
if (control.getPezzo(i, j) instanceof Pedina) { // infine inserisco le icone sui bottoni, se sarà pedina userà il metodo che fornirà il bottone dell'icona pedina
campoB[i][j].setIcon(control.getPezzo(i, j) != null ? control.getPezzo(i, j).getColore() : null); // se alla posizione i,j c'è un oggetto, passo il colore al metodo setIcon che in base a quello mi darà l'icona giusta
} else { // se invece sarà un damone lo fornirà dell'icona damone, valido sia per il giocatore che per il PC
campoB[i][j].setSuperIcon(control.getPezzo(i, j) != null ? control.getPezzo(i, j).getColore() : null); // metodo identico al precedente che però setta icone differenti se l'oggetto è un damone
}
b = (j != 7) ? !b : b; // inverte il boolean del colore del campo
}
}
window.revalidate(); // Aggiorna la situazione grafica rivalutando il tutto, questo comando permette di visualizzare i cambiamenti
} |
24494204-8d64-4fd3-a893-17b057549b36 | 0 | public YamlPermissionGroup(String n, ConfigurationSection config) {
super(n, config);
} |
4aff75d9-d763-4c53-aae6-10ebed8a977b | 1 | @Override
public int attack(double agility, double luck) {
if(random.nextInt(100) < luck)
{
System.out.println("I just stabbed the enemy in the back!");
return random.nextInt((int) agility) * 4;
}
return 0;
} |
56510cc3-1765-44ca-8748-12cd2d075b6e | 5 | private void addAccount() {
String name = nameField.getText().trim();
try {
Account account = new Account(name.trim());
account.setType((AccountType) type.getSelectedItem());
String text = defaultAmountField.getText();
if (text != null && !text.trim().equals("")) {
try {
BigDecimal defaultAmount = new BigDecimal(text);
defaultAmount = defaultAmount.setScale(2);
account.setDefaultAmount(defaultAmount);
} catch (NumberFormatException nfe) {
account.setDefaultAmount(null);
}
}
accounts.addBusinessObject(account);
Main.fireAccountDataChanged(account);
} catch (DuplicateNameException e) {
ActionUtils.showErrorMessage(ActionUtils.ACCOUNT_DUPLICATE_NAME, name);
} catch (EmptyNameException e) {
ActionUtils.showErrorMessage(ActionUtils.ACCOUNT_NAME_EMPTY);
}
nameField.setText("");
defaultAmountField.setText("");
} |
aa2ffb5f-ab24-44e2-a233-b116983d27be | 6 | public boolean dig(Tile t, Dude dude) {
if (dude.isAt(t.getX() - 1, t.getY())
|| dude.isAt(t.getX() + 1, t.getY())
|| dude.isAt(t.getX(), t.getY() + 1)
|| dude.isAt(t.getX() + 1, t.getY() - 1)) {
// finish building tile
if (t.getStructure() != null) {
removeStructure(t.getStructure());
}
t.setHeight(t.getHeight() - 1);
t.hasDigTask = false;
// plays audio
if (mixingDesk != null) {
mixingDesk.addAudioPlayer("PlaceItem.wav", true);
}
// set tile non transparent
// reassign dude to new task
return true;
} else {
// otherwise reassign dude and repush task
// tasks.add(new Task(t, "dig"));
return false;
}
} |
f27a4ffa-5556-462e-b83b-b919cac02f16 | 3 | @Override
public List<Loja> listAll() {
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
List<Loja> lojas = new ArrayList<>();
try{
conn = ConnectionFactory.getConnection();
pstm = conn.prepareStatement(LIST);
rs = pstm.executeQuery();
while (rs.next()){
Loja l = new Loja();
l.setId_loja(rs.getInt("id_loja"));
l.setNome(rs.getString("nome_lj"));
l.setEndereco(rs.getString("endereco_lj"));
l.setTelefone(rs.getString("telefone_lj"));
l.setCep(rs.getString("cep_lj"));
lojas.add(l);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Erro ao listar lojas " + e);
}finally{
try{
ConnectionFactory.closeConnection(conn, pstm, rs);
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Erro ao desconectar com o banco " + e);
}
}
return lojas;
} |
c5ea9424-6a22-4a37-8ee0-1eb2ebd8f5b2 | 1 | public List<Edge> getEdges()
{
if (this.allEdges.isEmpty())
{
return Collections.emptyList();
} else
{
return this.allEdges;
}
} |
d76815c7-21c9-4bd3-a0bc-558bf3e9e70c | 7 | public static void main(String args[]){
Scanner lea = new Scanner(System.in);
FileWriter fw = null;
char resp = 's';
do{
System.out.println("Ingrese dir de Arch Texto: ");
String path = lea.next();
System.out.println("Lo quiere append? ");
char app = lea.next().charAt(0);
try {
fw = new FileWriter(path , app == 's' ? true : false);
String texto;
do{
System.out.println("Texto a Escribir: ");
texto = lea.nextLine();
if( !texto.equals("SALIR")){
fw.write( texto + "\n" );
fw.flush();
}
}while( !texto.equals("SALIR"));
System.out.println("Quiere otro archivo?: ");
resp = lea.next().charAt(0);
if( resp != 's' )
fw.close();
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
}
}while(resp == 's');
//leer de texto
System.out.println("Dir de Arch txt: ");
try{
File file = new File(lea.next());
FileReader fr = new FileReader(file);
char buffer[] = new char[(int)file.length()];
int bleidos = fr.read(buffer);
System.out.println("Contenido:\n");
System.out.println(buffer);
System.out.println("Cantidad leida: " + bleidos +
" size del archivo: " + file.length());
}
catch(Exception e){
System.out.println("Error: " + e.getMessage());
}
} |
d5a5d34f-a8da-4ff2-a891-d14fc12189fc | 6 | @EventHandler
public void CreeperMiningFatigue(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getCreeperConfig().getDouble("Creeper.MiningFatigue.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getCreeperConfig().getBoolean("Creeper.MiningFatigue.Enabled", true) && damager instanceof Creeper && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, plugin.getCreeperConfig().getInt("Creeper.MiningFatigue.Time"), plugin.getCreeperConfig().getInt("Creeper.MiningFatigue.Power")));
}
} |
b54339a8-4882-4d64-a533-97e6f99a55fe | 0 | @Override
protected EntityManager getEntityManager() {
return em;
} |
c8a17c54-a038-4436-86b8-3c531d030e58 | 1 | public void tickDownUnitStatuses(int currentPlayerIndex)
{
for (Unit unit : units) {
unit.tickDownStatuses(currentPlayerIndex);
}
} |
804899c6-4843-4eca-b07e-b3c8e4bce8a7 | 4 | public boolean onCommand(Player player, String[] args) {
File fichier_language = new File(OneInTheChamber.instance.getDataFolder() + File.separator + "Language.yml");
FileConfiguration Language = YamlConfiguration.loadConfiguration(fichier_language);
if(player.hasPermission(getPermission())){
if(args.length < 2){
String notEnoughArgs = Language.getString("Language.Error.Not_enough_args");
UtilSendMessage.sendMessage(player, notEnoughArgs);
return true;
}if(args.length > 1){
String arenaName = args[0];
if(ArenaManager.getArenaManager().getArenaByName(arenaName) != null){
Arena arena = ArenaManager.getArenaManager().getArenaByName(arenaName);
String displayName = args[1];
arena.setDisplayName(displayName);
arena.saveConfig();
String succes = Language.getString("Language.Setup.Display_name").replaceAll("%displayname", displayName).replaceAll("%arena", arenaName);
UtilSendMessage.sendMessage(player, succes);
return true;
}else{
String doesntExist = Language.getString("Language.Error.Arena_does_not_exist").replaceAll("%arena", arenaName);
UtilSendMessage.sendMessage(player, doesntExist);
return true;
}
}
}else{
String notPerm = Language.getString("Language.Error.Not_permission");
UtilSendMessage.sendMessage(player, notPerm);
return true;
}
return true;
} |
a130f9b1-b632-4445-92d9-e58dbda1af1c | 5 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + aantalDeelnames;
result = prime * result + id;
result = prime * result
+ ((leerjaar == null) ? 0 : leerjaar.hashCode());
result = prime * result + ((leraar == null) ? 0 : leraar.hashCode());
result = prime * result
+ ((onderwerp == null) ? 0 : onderwerp.hashCode());
result = prime * result
+ ((opdrachten == null) ? 0 : opdrachten.hashCode());
result = prime * result
+ ((quizStatus == null) ? 0 : quizStatus.hashCode());
return result;
} |
33444f0a-167c-4a1e-b14d-6a8e25ad9d6a | 4 | public final void convertStringToCalendar(final String dateString) throws NullPointerException, EmptyException{
if(dateString == null || dateString.isEmpty()){
throw new RuntimeException("String date not be null");
}
if(dateString.isEmpty()){
throw new EmptyException("String date must not be empty");
}
Calendar calendar = Calendar.getInstance();
DateFormat df = new SimpleDateFormat("MMM dd, yyyy H:mm a");
try {
calendar.setTime(df.parse(dateString));
Date d = calendar.getTime();
System.out.println(df.format(d) + "\t - Converted to Calendar Object");
} catch (ParseException pe) {
System.out.println("Illegal format -- required: \tMonth day, year time am/pm\n"
+ "\t\t\t\tEample: March 15, 2014 2:30 PM");
}
} |
1b21c33e-890f-46ac-9c8e-b35421a011db | 4 | public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (!plugin.hasPerm(sender, "mute", true)) {
sender.sendMessage(ChatColor.YELLOW
+ "You do not have permission to use /" + label);
return true;
}
if (args.length == 0)
return false;
if (plugin.playerMatch(args[0]) != null) {
Player player = plugin.getServer().getPlayer(args[0]);
String pName = player.getName();
UserTable ut = plugin.getDatabase().find(UserTable.class).where()
.ieq("userName", pName).findUnique();
if (ut.isMuted()) {
ut.setMuted(false);
plugin.getServer().broadcastMessage(
ChatColor.YELLOW + player.getDisplayName()
+ " has been unmuted.");
} else {
ut.setMuted(true);
plugin.getServer().broadcastMessage(
ChatColor.YELLOW + player.getDisplayName()
+ " has been muted.");
}
plugin.getDatabase().save(ut);
} else {
sender.sendMessage("Player could not be found.");
}
return true;
} |
650b5636-400b-4b18-b748-f3268250af40 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ContatoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ContatoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ContatoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ContatoJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ContatoJFrame().setVisible(true);
}
});
} |
77223881-5313-4cd9-bb8a-505dcec15166 | 0 | static public ArrayList<Cuenta> getAll(){
return cuentas;
} |
d7a4eae9-1344-4624-a8f7-a39dc340447f | 9 | public JFreeChart MakeChart() {
DefaultPieDataset chartDataSet = new DefaultPieDataset();
Object[] column1Data =
super.getDataset().GetColumnData(super.getAttribute1());
Object[] column2Data =
super.getDataset().GetColumnData(super.getAttribute2());
boolean addDataset = true;
String errors = "";
int errorCounter = 0;
for (int i=0; i<super.getDataset().GetNoOfEntrys();i++) {
Comparable<Object> nextValue1;
nextValue1 = (Comparable<Object>) column1Data[i];
Double nextValue2 = null;
boolean addThis = true;
try {
int intNextValue2 =
Integer.parseInt(column2Data[i].toString());
nextValue2 = (Double) ((double) intNextValue2);
} catch (NumberFormatException nfe) {
try {
double doubleNextValue2 =
Double.parseDouble(column2Data[i].toString());
nextValue2 = (Double) doubleNextValue2;
} catch (NumberFormatException nfe2) {
String strNextValue2 = column2Data[i].toString();
if (strNextValue2.equalsIgnoreCase("True")) {
nextValue2 = TRUE;
} else if (strNextValue2.equalsIgnoreCase("False")) {
nextValue2 = FALSE;
} else {
addThis = false;
}
}
} catch (Exception e) {
addThis = false;
}
if (addThis == true) {
chartDataSet.setValue( nextValue1, nextValue2 );
} else {
addDataset = false;
if (errorCounter < MAX_ERROR_LENGTH) {
errors = errors + "\n"
+ column2Data[i].toString();
errorCounter++;
}
}
}
if (addDataset == false) {
chartDataSet = new DefaultPieDataset(); //Reset
JOptionPane.showMessageDialog(null,
"Your selected y-axis has data in the wrong format" + "\n" +
"The following data needs to be a number in order to be" +
" represented."
+ errors);
}
JFreeChart chart = ChartFactory.createRingChart(
super.getHeader(),
chartDataSet,
true, //include legend
true,
false );
return chart;
} |
e99fe8fa-6010-441e-af95-565924c33e39 | 2 | public static double readHashTopValue(HashMap<String, Integer> scores, int k) {
List list = new LinkedList(scores.entrySet());
int count = 0;
int value = 0;
double res = 0;
for (Iterator it = list.iterator(); count < k && it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
value = (Integer) entry.getValue();
res += (double) value * Math.log(2) / Math.log(count + 2);
// res += (Integer) entry.getValue();
count++;
}
return res;
} |
33a50fb5-efc2-4754-98d5-85637557e721 | 1 | public void makeDeclaration(Set done) {
for (int i = 0; i < subExpressions.length; i++)
subExpressions[i].makeDeclaration(done);
} |
b02c42b7-90d9-41c1-a665-4e0759fc6af8 | 0 | public static void main(String[] args) {
Ex4 x = new Ex4();
} |
28b2ef1e-ecf1-4dfa-b06a-6c60eb10f3e6 | 7 | void processItemResponseMessage(Event event)
{
String itemName = (String)_itemHandles.get(event.getHandle());
OMMItemEvent ie = (OMMItemEvent)event;
OMMMsg ommMsg = ie.getMsg();
short ommMsgType = ommMsg.getMsgType();
String ommMsgTypeStr = OMMMsg.MsgType.toString((byte)ommMsgType);
System.out.println("<-- " + _className + "Received for " + itemName + " "
+ event.toString() + " " + ommMsgTypeStr);
GenericOMMParser.parse(ommMsg);
byte messageType = ommMsg.getMsgType();
switch (messageType)
{
case OMMMsg.MsgType.ACK_RESP:
{
_mainApp.processAckResponse(_className, ommMsg);
break;
}
case OMMMsg.MsgType.REFRESH_RESP:
{
_itemRefreshCount++;
System.out.println(INFO_APPNAME + "Received Item Refresh " + _itemRefreshCount
+ " for Item " + itemName);
if( ommMsg.has(OMMMsg.HAS_PERMISSION_DATA) )
{
byte[] permLock = ommMsg.getPermissionData();
_itemLocks.put( event.getHandle(), permLock );
}
// if configured, send posts after item streams are open
if ((_bSendPostAfterItemOpen_ip == true) && (_itemRefreshCount == _itemOpenCount))
{
System.out.println(INFO_APPNAME
+ "All "
+ _itemOpenCount
+ " item(s) are opened; Starting to do Posts, based on configuration in "
+ APPNAME);
// slow down for service to come up
ExampleUtil.slowDown(1000);
sendPosts();
}
break;
}
case OMMMsg.MsgType.UPDATE_RESP:
{
break;
}
case OMMMsg.MsgType.STATUS_RESP:
{
_mainApp.processStatusResponse(_className, ommMsg);
break;
}
default:
System.out.println(_className + ": Received Item Response - "
+ OMMMsg.MsgType.toString(ommMsg.getMsgType()));
break;
}
} |
31b1f15a-3ef9-4422-b01f-11e6ff990d96 | 6 | public double getAggregate( String dsName, String consolFun ) throws RrdException
{
Source src = getSource( dsName );
if( consolFun.equalsIgnoreCase("MAX") )
return src.getAggregate( Source.AGG_MAXIMUM );
else if ( consolFun.equalsIgnoreCase("MIN") )
return src.getAggregate( Source.AGG_MINIMUM );
else if ( consolFun.equalsIgnoreCase("LAST") )
return src.getAggregate( Source.AGG_LAST);
else if ( consolFun.equalsIgnoreCase("FIRST") )
return src.getAggregate( Source.AGG_FIRST );
else if ( consolFun.equalsIgnoreCase("TOTAL") )
return src.getAggregate( Source.AGG_TOTAL );
else if ( consolFun.equalsIgnoreCase("AVERAGE") )
return src.getAggregate( Source.AGG_AVERAGE );
else
throw new RrdException("Unsupported consolidation function [" + consolFun + "]");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.