method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
d9d2500c-eba3-47ae-9259-3ca6d69a7ef6 | 4 | private static void decodeInput(char keyChar) {
Movement.checkAllFalse();
switch (keyChar) {
case 'a':
Movement.MOVEMENT[Movement.LEFT] = true;
Miscellaneous.log("LEFT");
break;
case 'w':
Movement.MOVEMENT[Movement.UP] = true;
Miscellaneous.log("UP");
break;
case 's':
Movement.MOVEMENT[Movement.DOWN] = true;
Miscellaneous.log("DOWN");
break;
case 'd':
Movement.MOVEMENT[Movement.RIGHT] = true;
Miscellaneous.log("RIGHT");
break;
}
} |
1aad41b5-eb04-45a2-9931-582a2f591317 | 5 | public static void load(ImageSet imageSet){
DataBaseHandler db = new DataBaseHandler();
ResultSet resultado = null;
String sql = "select code, name, link from images";
try {
resultado = db.consultar(sql);
if(resultado != null){
while(resultado.next()){
String name, link;
int code;
code = Integer.parseInt(resultado.getObject(1).toString());
name = resultado.getObject(2).toString();
link = resultado.getObject(3).toString();
imageSet.add(new Image(code, name, link));
}
}
}catch(SQLException e){
}
finally{
try{
if(resultado != null){
resultado.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
} |
f6aa92db-41e4-4d1b-ad2e-3caece7cb300 | 1 | private void addPlayersOnGrid() {
for (Player p : players) {
grid.addElement(p);
grid.addElement(p.getLightTrail());
factory.addObservable(p);
factory.addObserver(p);
factory.addObservable(p.getLightTrail());
}
} |
f84efb5a-e6a1-4b3c-92d2-e93605f35d4d | 5 | public static String getSql(String path) {
String content = "";
StringBuffer strbuf = new StringBuffer();
File f = new File(path);
if (f.exists() && f.canRead()) {
System.out.println("Filehandle auf " + path);
BufferedReader read;
try {
read = new BufferedReader(new FileReader(f));
while ((content = read.readLine()) != null) {
strbuf.append(content);
}
read.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return strbuf.toString();
} |
48716935-4602-4a3e-bc92-b4bc37763519 | 9 | @Override
public CodeLineList generateCode(Code relatedClass, Method relatedMethod,
boolean forCodeGeneration) {
CodeLineList typeCodeList = this.getChild(0).generateCode(relatedClass,
relatedMethod, true);
CodeLine typeLine = typeCodeList.getCodeLine(0);
String type = typeLine.getCode();
if (type.contains(",")) {
if (type.contains("[")) {
String type0 = type.split(",")[0];
String type1 = type.split(",")[1];
int first = type1.indexOf('[');
int last = type1.lastIndexOf(']');
char[] c = new char[last - first + 1];
type1.getChars(first, last + 1, c, 0);
type = type0 + String.valueOf(c);
} else {
type = type.split(",")[0];
}
}
CodeLineList code = this.getChild(1).generateCode(relatedClass,
relatedMethod, true);
for (int i = 2; i < this.getNumberOfChildren(); i++) {
code.addCodeToLastLine(new CodeLine(", ", -1));
code.concatLast(this.getChild(i).generateCode(relatedClass,
relatedMethod, true));
}
LDNode ch = this.getChild(0).getChild(0);
if (ch.getNumberOfChildren() == 0
&& ch.firstToken.kind == PseuCoParserConstants.IDENTIFIER) {
if (CodeGen.needsPseuCoPrefix(type)) {
String oldType = type;
type = "PseuCo_" + type;
int size = code.getNUmberOfElements();
for (int i = 0; i < size; i++) {
CodeLine line = code.getCodeLine(i);
String c = line.getCode();
if (c.contains(oldType)) {
c = CodeGen.replace(c, oldType, type);
code.setCodeLine(
new CodeLine(c, line.getPseuCoLineNumbers()), i);
}
}
}
}
if (type.equals("ReentrantLock")) {
type = "final " + type;
}
CodeLineList returnCode = code.addCodeAtTheBeginning(new CodeLine(type
+ " ", typeLine.getPseuCoLineNumbers()));
passNodeFieldsToTheParentNode();
return returnCode;
} |
08b0a3fb-7b1f-47d2-85c9-18fc9be7a9d2 | 8 | public int hashCode()
{
int _hashCode = 0;
_hashCode = 29 * _hashCode + id;
_hashCode = 29 * _hashCode + (idModified ? 1 : 0);
if (email != null) {
_hashCode = 29 * _hashCode + email.hashCode();
}
_hashCode = 29 * _hashCode + (emailModified ? 1 : 0);
if (salt != null) {
_hashCode = 29 * _hashCode + salt.hashCode();
}
_hashCode = 29 * _hashCode + (saltModified ? 1 : 0);
if (password != null) {
_hashCode = 29 * _hashCode + password.hashCode();
}
_hashCode = 29 * _hashCode + (passwordModified ? 1 : 0);
_hashCode = 29 * _hashCode + (int) active;
_hashCode = 29 * _hashCode + (activeModified ? 1 : 0);
return _hashCode;
} |
c85b0750-935a-4ed6-980f-d57c4a0184eb | 3 | public boolean intersects(int x0, int y0, int x1, int y1) {
return !(x + xr < x0 || y + yr < y0 || x - xr > x1 || y - yr > y1);
} |
b10ca22e-9d79-4e4e-b899-0fdf1eeee580 | 6 | @Override
protected String buildSearchQuery() {
Category cat = (Category) e;
String query = ""
+ "SELECT * "
+ "FROM category "
+ "WHERE 1=1 ";
if (cat.getName() != null && !cat.getName().equals("")) {
query += " AND Name LIKE '%" + cat.getName() + "%' ";
}
if (cat.getDesc() != null && !cat.getDesc().equals("")) {
query += " AND `Desc` LIKE '%" + cat.getDesc() + "%' ";
}
if (cat.getDateCreated() != null) {
query += " AND DateCreated LIKE '" + cat.getDateCreated() + "%' ";
}
if (cat.getDateModified() != null) {
query += " AND _dateModified LIKE '" + cat.getDateModified() + "%' ";
}
return query;
} |
186c4a37-df7e-4002-868c-f96a39d9902f | 7 | public void action() throws Exception {
if (isEnd) {
return;
}
if (needStart) {
updatePosition();
if (FieldGame.isFreeFromBricks(id, pos_x, pos_y)) {
writeMailbox(BrickGame.bluetooth_mailboxSystem, direction,
BrickGame.bluetooth_mailboxGotIt);
writeMailbox(BrickGame.bluetooth_mailboxSystem, move_power,
BrickGame.bluetooth_mailboxGotIt);
writeMailbox(BrickGame.bluetooth_mailboxSystem, rotate_power,
BrickGame.bluetooth_mailboxGotIt);
writeMailbox(BrickGame.bluetooth_mailboxSystem, gap,
BrickGame.bluetooth_mailboxGotIt);
writeMailbox(BrickGame.bluetooth_mailboxSystem, maxdegree,
BrickGame.bluetooth_mailboxGotIt);
writeMailbox(BrickGame.bluetooth_mailboxSystem, forward,
BrickGame.bluetooth_mailboxGotIt);
needStart = false;
}
downdatePosition();
return;
}
if (direction == 0) {
if (Status.is_win()) {
writeMailbox(BrickGame.bluetooth_mailboxSystem, 0, -1);
isEnd = true;
return;
}
int newdirection = FieldGame.getMove(id);
if (newdirection < 1 || newdirection > 4) {
return;
}
direction = newdirection;
writeMailbox(BrickGame.bluetooth_mailboxSystem, newdirection, -1);
Gui.update();
} else {
receive_id();
}
} |
c713e413-f462-4de2-bd26-cdb1e9b64ff2 | 1 | public boolean getNappaimenTila(int nappain){
if (nappainTilat.containsKey(nappain)){
return nappainTilat.get(nappain);
} else {
return false;
}
} |
df27b71e-375f-4a40-93c1-0786e6c9ea95 | 5 | @Override
public void play()
{
switch( channelType )
{
case SoundSystemConfig.TYPE_NORMAL:
if( clip != null )
{
if( toLoop )
{
clip.stop();
clip.loop( Clip.LOOP_CONTINUOUSLY );
}
else
{
clip.stop();
clip.start();
}
}
break;
case SoundSystemConfig.TYPE_STREAMING:
if( sourceDataLine != null )
{
sourceDataLine.start();
}
break;
default:
break;
}
} |
e27a3164-067d-47c7-a6a0-811eb40ca0c0 | 1 | public void testIsEqual_LocalDate() {
LocalDate test1 = new LocalDate(2005, 6, 2);
LocalDate test1a = new LocalDate(2005, 6, 2);
assertEquals(true, test1.isEqual(test1a));
assertEquals(true, test1a.isEqual(test1));
assertEquals(true, test1.isEqual(test1));
assertEquals(true, test1a.isEqual(test1a));
LocalDate test2 = new LocalDate(2005, 7, 2);
assertEquals(false, test1.isEqual(test2));
assertEquals(false, test2.isEqual(test1));
LocalDate test3 = new LocalDate(2005, 7, 2, GregorianChronology.getInstanceUTC());
assertEquals(false, test1.isEqual(test3));
assertEquals(false, test3.isEqual(test1));
assertEquals(true, test3.isEqual(test2));
try {
new LocalDate(2005, 7, 2).isEqual(null);
fail();
} catch (IllegalArgumentException ex) {}
} |
c0153de6-f3a4-45a2-b9f6-372dafe3872b | 7 | private static boolean doesDetectedPolygonMatchesWithRoads(ArrayList<Position> detectedPolygon, ArrayList<Road> roads)
{
ArrayList<Road>[] roadListByNode = new ArrayList[detectedPolygon.size()];
for (int i = 0; i < detectedPolygon.size(); i++)
roadListByNode[i] = new ArrayList<Road>();
for (int i = 0; i < detectedPolygon.size(); i++)
{
for (int j = 0; j < roads.size(); j++)
{
Road currentRoad = roads.get(j);
if (currentRoad.isOnRoad(detectedPolygon.get(i)))
roadListByNode[i].add(currentRoad);
}
}
for (int i = 0; i < detectedPolygon.size(); i++)
{
if (i == detectedPolygon.size()-1)
// Traitement du dernier point
return isThereACommonRoad(roadListByNode[i], roadListByNode[0]);
else
{
// On abandonne si le point courrant et le suivant n'ont pas de routes en commun
if (!(isThereACommonRoad(roadListByNode[i], roadListByNode[i+1])))
return false;
}
}
return false;
} |
84c6dc65-331a-4cf1-8194-e2243ae06cde | 5 | @Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if(str == null) {
return;
} else if(str.length() + offs > maxLength) {
return;
}
char[] letters = str.toCharArray();
boolean numbers = true;
for(char c : letters) {
if(!Character.isDigit(c)) {
numbers = false;
break;
}
}
if(numbers) {
super.insertString(offs, new String(letters), a);
}
} |
a7635822-cd4e-43f8-aa71-721d349ae631 | 3 | @Override
public Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("No esta instalado el Driver JDBC");
e.printStackTrace();
}
try {
connection = DriverManager
.getConnection("jdbc:mysql://127.0.0.1/Banco", "root", "root");
} catch (SQLException e) {
System.out.println("Conexión fallida.");
e.printStackTrace();
}
if (connection != null) {
System.out.println("Conexión realizada");
} else {
System.out.println("Fallo al realizar la conexión");
}
return connection;
} |
04284480-7d18-4c9a-b424-df168ee44131 | 5 | public void run(){
setSizeField();
field.initField();
showField();
while (!check.win(player) && var.counter < field.sizeField * field.sizeField) {
player = Value.changePlayer(player);
playersMove(player);
showField();
if (check.win(player)) messageWin(player);
var.counter++;
}
if ((var.counter == (field.sizeField * field.sizeField)) && !check.win(player)) messageDraw();
var.exit = true;
} |
10e492e7-a7cf-44cd-b4aa-5cffa891fff8 | 1 | public void addPawn(final Pawn pawn) {
if (getSquareContent(pawn.getX(),
pawn.getY()) == null)
this.pawns.add(pawn);
} |
217c8b28-6384-4e38-a3cd-187cf365f910 | 2 | public static boolean percentChance(double percent){
if(percent > 100 || percent < 0){
throw new IllegalArgumentException("Percentage cannot be greater than 100 or less than 0!");
}
double result = new Random().nextDouble() * 100;
return result <= percent;
} |
e5568d1d-6cf2-4d64-857d-0cb9d326d20e | 4 | public static void saveReservation(Reservation reservation){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conn.setAutoCommit(false);
PreparedStatement stmnt = conn.prepareStatement("INSERT INTO Reservations VALUES(?,?,?)");
stmnt.setInt(1, reservation.getProductID());
stmnt.setInt(2, reservation.getMemberID());
stmnt.setString(3, reservation.getType());
stmnt.execute();
conn.commit();
conn.setAutoCommit(true);
}
catch(SQLException e){
System.out.println("insert fail!! - " + e);
}
} |
457600d8-48fe-43cf-80e9-690a4808f5f0 | 5 | public int search(int[] A, int target) {
if(target >=A[0]){
for(int i=0 ; i< A.length;i++){
if(A[i] == target)
return i;
}
}else
{
for(int i= A.length -1 ; i>=0;i--){
if(A[i] == target)
return i;
}
}
return -1;
} |
4921024c-a8b5-4d40-ab5a-4c7d11357fbc | 2 | public static String[] getParameterTypes(String methodTypeSig) {
int pos = 1;
int count = 0;
while (methodTypeSig.charAt(pos) != ')') {
pos = skipType(methodTypeSig, pos);
count++;
}
String[] params = new String[count];
pos = 1;
for (int i = 0; i < count; i++) {
int start = pos;
pos = skipType(methodTypeSig, pos);
params[i] = methodTypeSig.substring(start, pos);
}
return params;
} |
5cd0c58e-614a-43b5-9c8c-5213c4e5ddde | 2 | private void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} |
11014a2f-362a-4623-b8d7-6444bf941b5b | 5 | ClientThread(Socket socket) {
uid = uniqueID++;
this.socket = socket;
try {
//Creating I/O streams for a Client
output = new ObjectOutputStream(socket.getOutputStream());
input = new ObjectInputStream(socket.getInputStream());
//Read username that Client broadcasts to us
username = (String) input.readObject();
for (int i = 0; i < usernameList.size(); i++) {
if(usernameList.get(i) == "Empty slot") {
usernameList.set(i, username);
break;
}
}
gameFrame.repaint();
gameFrame.updatePlayerList(usernameList);
//Give Client a unique ID
output.writeObject(uid);
//Broadcasting grid to Clients that connect
MansionArea[][] grid = player.getBandit().getGrid();
output.writeObject(grid);
//Broadcasting username list to Clients that connect
output.writeObject(usernameList);
for(int i = clientList.size(); --i >= 0;) {
ClientThread ct = clientList.get(i);
ct.output.writeObject(usernameList);
System.out.println("Broadcasting username list: " + usernameList);
}
}
catch (IOException e) {
System.out.println(username + ": Exception creating IO Object Streams: " + e);
return;
} catch (ClassNotFoundException e) {
System.out.println(username + ": Exception with class: " + e);
}
} |
ff74ac83-ea02-4c29-93a9-fe9dd9e024e4 | 0 | public void setDescription(String description) {
this.description = description;
} |
e9bbd9ac-8889-48e8-b8f6-b39d50d3ae47 | 3 | public final JSONWriter object() throws JSONException {
if (this.mode == 'i') {
this.mode = 'o';
}
if (this.mode == 'o' || this.mode == 'a') {
this.append("{");
this.push(new JSONObject());
this.comma = false;
return this;
}
throw new JSONException("Misplaced object.");
} |
01f3e200-f180-4991-b4b9-ab559954f213 | 1 | @Override
public void commit() throws DaoException {
try {
mysqlConn.commit();
} catch (SQLException ex) {
throw new DaoConnectException("Error in commit connection in pool.");
}
} |
0ca18cfb-1593-48ee-85ad-9e17da40b7e5 | 9 | private void doCheatPrompt() { // hack
String input = JOptionPane.showInputDialog(null);
if ("yc with contacts".equals(input)) {
useMask = !useMask;
} else if ("17".equals(input)) {
player.addExp(171717);
player.setMaxHealth(171717);
player.setMaxMana(171717);
player.setHealth(171717);
player.setMana(171717);
} else if ("goh yun".equals(input)) {
isPlayerInvincible = !isPlayerInvincible;
} else if ("destroyer".equals(input)) {
map.monsters.clear();
} else if ("swat team".equals(input)) {
for (int i = 0; i < map.doors.size(); i++) {
map.doors.get(i).setClosed(false);
}
} else if ("supchut".equals(input)) {
for (int i = 0; i < Inventory.NUM_ITEMS; i++) {
inventory.getItem(i).setQuantity(1717);
}
} else if ("rage quit".equals(input)) {
createNewLevel();
}
} |
1aa7d3cb-7a77-4fb0-8bf4-ce30c0e9dde4 | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof GatewayAttributeEnumeration)) {
return false;
}
GatewayAttributeEnumeration other = (GatewayAttributeEnumeration) object;
if ((this.gatewayAttributeEnumerationPK == null && other.gatewayAttributeEnumerationPK != null) || (this.gatewayAttributeEnumerationPK != null && !this.gatewayAttributeEnumerationPK.equals(other.gatewayAttributeEnumerationPK))) {
return false;
}
return true;
} |
146f580c-49d1-4594-b554-ddb297ec2fe2 | 4 | public boolean testUser(String u) throws Exception {
Connection conn =null;
Statement stmt = null;
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url);
stmt = conn.createStatement();
String sql;
sql ="SELECT NAME from USERS WHERE USER_NAME = " + "'" + u + "'";
rs= stmt.executeQuery(sql);
// check if we got any result set
boolean b = rs.next();
return b;
}
catch(SQLException sqle){
throw new Exception(sqle);
}
finally{
try{
rs.close();
}
catch(Exception e) {}
try{
stmt.close();
}
catch(Exception e) {}
try {
conn.close();
}
catch(Exception e){}
}
} |
9ea347ea-4fb1-4a50-ab52-d7235d4df7cb | 5 | @Override
public Role findRoleByRoleIdAndAccountId(int roleId, int accountId) {
Role role = null;
Connection cn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
cn = ConnectionHelper.getConnection();
ps = cn.prepareStatement(QTPL_SELECT_BY_ACCOUNT_ID_AND_ROLE_ID);
ps.setInt(1, accountId);
ps.setInt(2, roleId);
rs = ps.executeQuery();
if (rs.next()) {
role = processResultSet(rs);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { ps.close(); } catch (SQLException e) { e.printStackTrace(); }
try { cn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
return role;
} |
123a64e4-f917-4166-b6bc-57c588430c39 | 0 | public void setTerminer(boolean terminer) {
this.terminer = terminer;
} |
f43c02d4-882b-42e0-96a7-1a0aa2d90436 | 2 | public ResultSet execute(String query) {
try {
Statement stm = this.con.createStatement();
if(stm.execute(query)){
return stm.getResultSet();
}
return null;
} catch (SQLException e) {
LogHandler.writeStackTrace(log, e, Level.SEVERE);
return null;
}
} |
13c8365b-4b71-480c-8d9f-5d9aa0682c84 | 1 | public void miseEnMain() {
Peuple p = joueurEnCours.getPeuple();
// Récupération des unités du plateau
Iterator<Territoire> it = p.getTerritoiresOccupes().iterator();
while (it.hasNext()) {
Territoire t = it.next();
int nb = t.getNbUnite();
t.setNbUnite(1);
p.addNbUniteEnMain(nb - 1);
}
// Application des bonus
p.calcBonusUniteAttaque();
} |
ccb8a28b-6ba3-4654-91e6-6d9526bd9f37 | 6 | protected void computeU( int k) {
u.reshape(m,1, false);
double u[] = this.u.data;
// find the largest value in this column
// this is used to normalize the column and mitigate overflow/underflow
double max = 0;
for( int i = k; i < m; i++ ) {
// copy the householder vector to vector outside of the matrix to reduce caching issues
// big improvement on larger matrices and a relatively small performance hit on small matrices.
double val = u[i] = B.get(i,k);
val = Math.abs(val);
if( val > max )
max = val;
}
if( max > 0 ) {
// -------- set up the reflector Q_k
double tau = 0;
// normalize to reduce overflow/underflow
// and compute tau for the reflector
for( int i = k; i < m; i++ ) {
double val = u[i] /= max;
tau += val*val;
}
tau = Math.sqrt(tau);
if( u[k] < 0 )
tau = -tau;
// write the reflector into the lower left column of the matrix
double nu = u[k] + tau;
u[k] = 1.0;
for( int i = k+1; i < m; i++ ) {
u[i] /= nu;
}
SimpleMatrix Q_k = SimpleMatrix.wrap(SpecializedOps.createReflector(this.u,nu/tau));
U = U.mult(Q_k);
B = Q_k.mult(B);
}
} |
fbcba97f-e03d-409d-85f9-9a0d2055ecc4 | 5 | private boolean isApplicableMethod(Method m, Class<? extends Annotation> httpMethodClass) {
Class<?>[] parameters = m.getParameterTypes();
if(!m.isAnnotationPresent(httpMethodClass))
return false;
if(!(parameters.length == 1 && parameters[0].equals(Arguments.class)))
throw new IllegalArgumentException("Wrong method signature: "+resource.getClass().getSimpleName()+"."+m.getName());
return true;
} |
7337f09b-f1e0-4005-bd7a-88d43096348e | 0 | public static void main(String[] args) {
w = new Worker();
} |
637d7caa-b4ab-4d3a-9278-8612d029b2c5 | 4 | public void actionPerformed( ActionEvent e )
{
// if any data available
if (TGlobal.projects.getCurrentData() != null)
{
if ( GUIGlobals.PROJECT_PROPERTIES_DIALOG == null )
GUIGlobals.PROJECT_PROPERTIES_DIALOG = new ProjectSettingsDialog() ;
if ( GUIGlobals.PROJECT_PROPERTIES_DIALOG.showModal() == TInternalDialog.MR_OKAY )
{
if (TGlobal.projects.getLanguages().hasDataVisibiltyChanged())
{
GUIGlobals.oPanel.updateDataVisibilty();
}
}
}
} |
2995f281-c17f-4898-8ebd-c4239599a669 | 8 | @SuppressWarnings({ "unchecked" })
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String studyPath = req.getPathInfo();
if (studyPath == null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
"Must specify study path.");
}
InputStream in = req.getInputStream();
OutputStream out = resp.getOutputStream();
ZOutputStream zOut = null;
DataInputStream dataIn = null;
DataOutputStream dataOut = null;
resp.setContentType("application/octet-stream");
log.info("Creating streams");
zOut = new ZOutputStream(out, JZlib.Z_BEST_COMPRESSION);
dataIn = new DataInputStream(in);
dataOut = new DataOutputStream(zOut);
log.info("Starting persistence manager");
PersistenceManager pm = PMF.get().getPersistenceManager();
log.info("Creating query");
Query query = pm.newQuery(Form.class);
query.setFilter("path == pathParam");
query.declareParameters("String pathParam");
query.setRange(0, 1);
log.info("Building study");
StudyDefList studyDefList = new StudyDefList();
StudyDef studyDef = new StudyDef(1, "A study", "varName");
studyDefList.addStudy(studyDef);
log.info("Reading download header from client");
String username = dataIn.readUTF();
String password = dataIn.readUTF();
String serializer = dataIn.readUTF();
String locale = dataIn.readUTF();
String action = req.getParameter("action");
log.info("Header received: username=" + username + ", password="
+ password + ", serializer=" + serializer + ", locale="
+ locale + ", action=" + action);
try {
log.info("Reading action");
byte actionByte = dataIn.readByte();
if (actionByte == ACTION_DOWNLOAD_USERS) {
log.info("Downloading users");
dataOut.writeByte(STATUS_SUCCESS);
writeUserList(dataOut);
} else if (actionByte == ACTION_DOWNLOAD_STUDY_LIST) {
log.info("Downloading study list");
dataOut.writeByte(STATUS_SUCCESS);
studyDefList.write(dataOut);
} else if (actionByte == ACTION_DOWNLOAD_USERS_AND_FORMS) {
log.info("Downloading users and forms");
dataOut.writeByte(STATUS_SUCCESS);
writeUserList(dataOut);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream mdos = new DataOutputStream(baos);
mdos.writeInt(studyDef.getId());
mdos.writeUTF(studyDef.getName());
mdos.writeUTF(studyDef.getVariableName());
mdos.writeShort(1);
List<Form> forms = (List<Form>) query.execute(studyPath);
if (!forms.isEmpty()) {
byte[] formContent = forms.get(0).getFormContent()
.getBytes();
mdos.write(formContent);
}
byte[] studyBytes = baos.toByteArray();
dataOut.writeInt(studyBytes.length);
dataOut.write(studyBytes);
} finally {
pm.close();
}
} else {
log.warning("Unknown action received. Action=" + actionByte);
}
} catch (Exception e) {
log.log(Level.WARNING,
"Failed to download form for path " + req.getPathInfo(), e);
} finally {
if (dataOut != null)
dataOut.flush();
if (zOut != null)
zOut.finish();
resp.flushBuffer();
}
} |
0bbd63f3-4b9d-4086-97b6-3b6b5e1f517b | 0 | public Account getBuyer(){ return buyerInt; } |
1f7f81b3-083e-4b7d-b28c-4f110d70aec6 | 1 | public boolean setProduct(Product product) {
if (product.getStock() == 0) return false;
this.product = product;
quantity = 1;
return true;
} |
86f23125-30fc-43f2-b6cc-38c988808564 | 5 | public int[] getOID(byte type) throws ASN1DecoderFail {
if(data[offset]!=type) throw new ASN1DecoderFail("OCTET STR: "+type+" != "+data[offset]);
byte[] b_value = new byte[contentLength()];
Encoder.copyBytes(b_value, 0, data, contentLength(),offset+typeLen()+lenLen());
int len=2;
for(int k=1;k<b_value.length; k++) if(b_value[k]>=0) len++;
int[] value = new int[len];
value[0] = get_u32(b_value[0])/40;
value[1] = get_u32(b_value[0])%40;
for(int k=2, crt=1; k<value.length; k++) {
value[k]=0;
while(b_value[crt]<0) {
value[k] <<= 7;
value[k] += b_value[crt++]+128;//get_u32(b_value[crt++])-128;
}
value[k] <<= 7;
value[k] += b_value[crt++];
continue;
}
return value;
} |
48f629b5-9cda-408a-9945-99fb70b7a64f | 4 | protected void updateDisplay() {
System.out.println("HELLO");
cover.repaint();
if (displayedToolIndex >= 1) {
this.startXPosition.setText("" + Math.round(cover.getStartPoint().getX()));
this.startYPosition.setText("" + Math.round(cover.getStartPoint().getY()));
if (displayedToolIndex > 1) {
this.stopXPosition.setText("" + Math.round(cover.getEndPoint().getX()));
this.stopYPosition.setText("" + Math.round(cover.getEndPoint().getY()));
if (displayedToolIndex == 2)
this.numPixels.setText("" + Math.round(cover.getEndPoint().distance(cover.getStartPoint())));
if (displayedToolIndex == 3)
this.numPixels.setText("" + Math.round((Math.abs(cover.getEndPoint().getX()-cover.getStartPoint().getX()) * Math.abs(cover.getEndPoint().getY() - cover.getStartPoint().getY()))));
}
}
this.handlePixelValue();
this.bringToFront(cover);
} |
4411442c-ed9e-486d-81ff-d4d57bf438da | 9 | public Node createNode(SVGGraphWriter writer, Document document,
GraphLayoutCache cache, CellView view, double dx, double dy) {
Rectangle2D bounds = view.getBounds();
Map attributes = view.getAllAttributes();
Element href = (Element) document.createElement("a");
String link = GraphConstants.getLink(attributes);
if (link != null) {
href.setAttribute("xlink:href", link);
}
// Specifies the shape geometry
int shapeType = SVGGraphConstants.getShape(attributes);
Color background = GraphConstants.getBackground(attributes);
String hexBackground = null;
if (background != null) {
hexBackground = SVGUtils.getHexEncoding(background);
}
Color gradient = GraphConstants.getGradientColor(attributes);
String hexGradient = null;
if (gradient != null) {
// TODO need proper definition for gradient colours
// For now put the gradient colour in the background
// In future need a proper definition for SVG
hexBackground = SVGUtils.getHexEncoding(gradient);
}
Color borderColor = GraphConstants.getBorderColor(attributes);
String hexLineColor = null;
if (borderColor != null) {
hexLineColor = SVGUtils.getHexEncoding(borderColor);
}
float lineWidth = GraphConstants.getLineWidth(attributes);
// Adds a drop shadow
boolean dropShadow = SVGGraphConstants.isShadow(attributes);
if (dropShadow) {
int dist = SHADOW_DISTANCE;
href.appendChild(writer.createShapeNode(document, shapeType,
bounds, dx - dist, dy - dist, HEXCOLOR_SHADOW, null,
"none", lineWidth, SHADOW_OPACITY, false));
}
href.appendChild(writer.createShapeNode(document, shapeType, bounds,
dx, dy, hexBackground, hexGradient, hexLineColor, lineWidth,
1.0, false));
// Adds the image
// This is currently not implemented due to bugs in all
// known SVG viewers, either ignoring the image at all
// or ignoring the individual sizes for the image (firefox)
// String imageURL = "http://www.jgraph.co.uk/images/logo.gif";
// if (imageURL != null) {
// Element image = (Element) document.createElement("image");
// image.setAttribute("x", String.valueOf(bounds.getX() - dx));
// image.setAttribute("y", String.valueOf(bounds.getY() - dy));
// image.setAttribute("w", String.valueOf(bounds.getWidth()));
// image.setAttribute("xlink:href", imageURL);
// image.setAttribute("h", String.valueOf(bounds.getHeight()));
// image.setAttribute("y", String.valueOf(bounds.getY() - dy));
// image.setAttribute("preserveAspectRatio", "none");
// href.appendChild(image);
// }
// Draws the labels stored in the user object
Object[] values = writer.getLabels(view);
int x = (int) (bounds.getX() - dx + bounds.getWidth() / 2);
Font font = GraphConstants.getFont(attributes);
int fontsize = (font != null) ? font.getSize() : 11;
int textHeight = (fontsize + SVGUtils.LINESPACING) * values.length;
int yOffset = (int) ((bounds.getHeight() - textHeight) / 2) + fontsize;
for (int i = 0; i < values.length; i++) {
Color fontColor = GraphConstants.getForeground(attributes);
String hexFontColor = null;
if (fontColor != null) {
hexFontColor = SVGUtils.getHexEncoding(fontColor);
}
if (values[i] instanceof Node) {
// Import the node since it comes from a different document
Node importedNode = document.importNode((Node)values[i], true);
// Create an empty text node
Node textNode = writer
.createTextNode(document, "", "middle", font,
hexFontColor, x,
(int) (bounds.getY() + yOffset - dy));
href.appendChild(textNode);
textNode.appendChild(importedNode);
} else {
String label = String.valueOf(values[i]);
href.appendChild(writer
.createTextNode(document, label, "middle", font,
hexFontColor, x,
(int) (bounds.getY() + yOffset - dy)));
}
yOffset += fontsize + SVGUtils.LINESPACING;
}
return href;
} |
fe3ae49a-6781-4bf7-a984-f23d815500f7 | 7 | public ProgressCheckRejectionPolicy(String rejection_policy) {
String policy = rejection_policy.toLowerCase();
if (!policy.startsWith(NAME)) {
throw new IllegalStateException(rejection_policy);
}
policy = policy.substring(NAME.length());
if (policy.startsWith("=")) {
String[] attributes = policy.substring(1).split(",", 0);
for (String attribute : attributes) {
String[] parts = attribute.split(":");
if (parts.length != 2) {
throw new IllegalArgumentException("Attribute '" + attribute + "' in " + rejection_policy);
}
String key = parts[0].trim();
String value = parts[1].trim();
if (key.equals("period")) {
try {
period = Long.parseLong(value);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Cannot parse period value in " + rejection_policy, e);
}
} else if (key.equals("fallback")) {
// in order to be able to define also different policy with attributes (use as the last attribute)
fallback = Util.parseRejectionPolicy(rejection_policy.substring(rejection_policy.indexOf("fallback:") + 9));
}
}
}
} |
1365ac69-5a31-4d59-9691-1e6b68d132c3 | 0 | public Serie(String nom) {
this.nom = nom;
} |
aaa533ee-3130-4a9b-821c-f43288affda2 | 5 | public static ArrayList<FullTicket> showAll(String status) {
ArrayList<FullTicket> fulltickets = new ArrayList<FullTicket>();
StringBuilder query = new StringBuilder();
Database db = dbconnect();
try {
query.append ("SELECT * FROM full_ticket ");
if ("Open".equals(status)) {
query.append("WHERE ticket_status = 'Open'");
db.prepare(query.toString());
} else if ("In process".equals(status)) {
query.append("WHERE ticket_status = 'In process'");
db.prepare(query.toString());
} else if ("Closed".equals(status)) {
query.append("WHERE ticket_status = 'Closed'");
db.prepare(query.toString());
} else {
query.append("ORDER BY TID");
db.prepare(query.toString());
}
ResultSet rs = db.executeQuery();
while(rs.next()) {
fulltickets.add(FullTicketObject(rs));
}
db.close();
} catch (SQLException e) {
Error_Frame.Error(e.toString());
}
return fulltickets;
} |
926f83af-c562-42f7-8158-0e24fe0e9d72 | 0 | private Session(String sessionId) {
this.recordActive();
this.sessionId = sessionId;
this.datas = new HashMap<String,Object>();
} |
3fdaa81c-7d26-461b-baf1-a9b0ce55ecf0 | 1 | private void acao102(Token token) throws SemanticError {
try {
String nomeConstante = token.getLexeme();
idAtual = new IdentificadorConstante(nomeConstante, null, null);
tabela.add(idAtual, nivelAtual);
} catch (IdentificadorJaDefinidoException e) {
throw new SemanticError(e.getMessage(), token.getPosition());
}
} |
2bbd1f3c-3ace-453b-b5e3-9e6c4f51268c | 8 | public static int[][] matrixMultiply(int[][] a, int[][] b) {
if (a == null || a.length == 0 || b == null || b.length == 0) {
throw new IllegalArgumentException("empty arrays");
}
if (b.length != a[0].length) {
throw new IllegalArgumentException("not compatible arrays");
}
int m = a.length;
int n = b.length;
int q = b[0].length;
int[][] c = new int[m][q];
for (int i = 0; i < m; i ++) {
for (int j = 0; j < q; j ++) {
for (int r = 0; r < n; r ++) {
c[i][j] += a[i][r] * b[r][j];
}
}
}
return c;
} |
99fdbd28-4b14-4729-8381-d67b333681ae | 6 | public void resizePanel(int w, int h) {
if (w == 0 && h == 0) {
//full screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
pWidth = dim.width;
pHeight = dim.height;
dbImage = null;
//resize the panel
this.setPreferredSize(new Dimension(pWidth, pHeight));
this.revalidate();
this.setFocusable(true);
this.requestFocus();
//resize the container
if (container != null) {
container.setPreferredSize(new Dimension(pWidth, pHeight));
container.validate();
}
} else {
pWidth = w;
pHeight = h;
dbImage = null;
game.setFullScreen(false);
//resize the panel
this.setPreferredSize(new Dimension(pWidth - 10, pHeight - 6));
this.revalidate();
this.setFocusable(true);
this.requestFocus();
//resize the container
if (container != null) {
container.setPreferredSize(new Dimension(pWidth - 10, pHeight - 6));
container.validate();
}
}
//resize the frame
game.pack();
game.setLocationRelativeTo(null);
if (w == 0 && h == 0) {
//full screen
game.setFullScreen(true);
}
} |
5b2d6b4e-5efb-433f-a9e8-8b7defa53b42 | 9 | synchronized void resizeMap(int x, int y)
{
int i,
i2,
X,
Y;
short newMap[][]= new short[x][y];
X = MapColumns;
if (x < MapColumns)
{
X = x;
}
Y = MapRows;
if (y < MapRows)
{
Y = y;
}
for (i=0;i<X;i++)
{
for (i2=0;i2<Y;i2++)
{
try
{
newMap[i][i2] = shrMap[i][i2];
}catch(Exception e)
{
}
}
}
shrMap = newMap;
DuskObject newEntities[][]= new DuskObject[x][y];
for (i=0;i<X;i++)
{
for (i2=0;i2<Y;i2++)
{
try
{
newEntities[i][i2] = objEntities[i][i2];
}catch(Exception e)
{
}
}
}
objEntities = newEntities;
MapColumns = x;
MapRows = y;
LivingThing thnStore;
for (i=0;i<vctSockets.size();i++)
{
thnStore = (LivingThing)vctSockets.elementAt(i);
thnStore.resizeMap();
}
blnMapHasChanged = true;
} |
c8e832f3-11de-4f14-90fe-0061545d0321 | 8 | @Override
public void keyReleased(final KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_UP:
isUP = false;
break;
case KeyEvent.VK_DOWN:
isDOWN = false;
break;
case KeyEvent.VK_LEFT:
isLEFT = false;
break;
case KeyEvent.VK_RIGHT:
isRIGHT = false;
break;
case KeyEvent.VK_CONTROL:
isCTRL = false;
break;
case KeyEvent.VK_SPACE:
space = 0;
break;
case KeyEvent.VK_S:
SoundEffect.muteSound();
break;
case KeyEvent.VK_M:
SoundEffect.muteMusic();
break;
}
} |
59de1a2f-d063-4a65-b7aa-cd07c92548a0 | 2 | @Override
public SqlSession getRequestSession() {
SqlSession session = thSession.get();
if (session == null) {
try {
session = MyBatisManager.getDataSessionFactory().openSession();
}catch (Exception ex) {
Logger.getLogger(ThreadLocalRequestDataSessionProvider.class.getName()).log(Level.SEVERE, null, ex);
}
thSession.set(session);
}
return session;
} |
50e42502-e12c-4c7f-a195-ca0df96cf23c | 4 | private void scheduleMatch()
{
clear();
try
{
int matchCount = matchmgr.showCount();
int teamCount = teammgr.showCount();
if (teamCount > 0)
{
int tm = teammgr.getById(1).getGroupId();
if (tm != 0)
{
/*
* If no matches, schedules group plays.
*/
if (matchCount < 1)
{
matchmgr.schedule(teammgr.listAll());
System.out.println("Group plays have been scheduled!");
}
else
{
System.out.println("Matches has already been scheduled!");
}
}
/*
* If groups is not assigned, returns an error.
*/
else
{
System.out.println("You need to assign to groups before scheduling matches!");
}
}
/*
* If no teams, returns an error.
*/
else
{
System.out.println("You need teams to schedule matches!");
}
}
catch (SQLException ex)
{
System.out.println("ERROR : " + ex.getMessage());
}
pause();
} |
9027d279-6abe-407c-9aa3-f4cb56e9fde5 | 0 | public Ginsu() {} |
1b7bacce-2605-4d93-ad78-78b5d7dcb269 | 5 | private Class<? extends GAttrib> attrclass(Class<? extends GAttrib> cl) {
while (true) {
Class<?> p = cl.getSuperclass();
if (p == GAttrib.class)
return (cl);
cl = p.asSubclass(GAttrib.class);
}
} |
e32d939f-1c43-4c08-a4f1-14a264b6bf4f | 3 | public static boolean isEmail(String email)
{
if ((email == null) || (email.length() < 1) || (email.length() > 256)) {
return false;
}
Pattern pattern = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
return pattern.matcher(email).matches();
} |
f2ac710b-243d-4d86-b765-6f83efddcf56 | 4 | public ArrayList<String> items(String string){
ArrayList<String> validItems = new ArrayList<>();
List<String> available = Utils.getItemsList();
if(!string.equals("")){
for(String item : available){
if(item.toLowerCase().startsWith(string)){
validItems.add(item);
}
}
}else {
for(String item : available){
validItems.add(item);
}
}
Collections.sort(validItems);
return validItems;
} |
a453d42a-dce4-4662-9722-5daa904b1c2f | 3 | private void RandomHeader() {
int a = 0;
String Path = null;
String[] PicturesArray = { "Ashe.jpg", "Fiddle.jpg", "Irelia.jpg",
"Jax.jpg", "Karthus.jpg", "Kayle.jpg", "Kayle2.jpg", "LB.jpg",
"Lux.jpg", "Maokai.jpg", "Morgana.jpg", "Morgana2.jpg",
"Noc.jpg", "Swain.jpg", "Vayne.jpg", "Xin.jpg", "Zyra.jpg",
"Nami.jpg", "Morgana3.jpg", "Nasus.jpg", "Riven.jpg",
"Shyvana.jpg", "Thresh.jpg", "TF.jpg", "Xin2.jpg",
"Anivia.jpg", "Draaaaaven.jpg" };
for (int index = 0; index < PicturesArray.length; index++) {
double i = Math.random() * PicturesArray.length;
a = (int) i;
Path = PicturesArray[a];
}
try {
BufferedImage image = ImageIO.read(Gui.class
.getResourceAsStream("/RADSSoundPatcher/Pictures/Header/"
+ Path));
headerLabel.setIcon(new ImageIcon(image));
Color c = Misc.getColor(image);
LookAndFeel(c);
} catch (IOException e) {
e.printStackTrace(); // To change body of catch statement use File |
// Settings | File Templates.
} catch (IllegalArgumentException e) {
logger.error("Error, image not found (" + Path + ")");
}
} |
3391d433-b392-4c68-9a9f-5b46454c9509 | 1 | private boolean jj_3_14() {
if (jj_3R_32()) return true;
return false;
} |
2ff2a019-a1f3-4352-a26d-41168bc542dc | 4 | public void paintButtons() {
buttonPane.removeAll();
buttonPane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
textField = new JTextField("port");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.5;
c.weighty = 0;
c.insets = MainGUI.defaultInsets;
textField.setPreferredSize(new Dimension(150, 50));
buttonPane.add(textField, c);
button = new JButton("Start Server");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
c.weightx = 0.5;
c.weighty = 0;
c.insets = MainGUI.defaultInsets;
button.setPreferredSize(new Dimension(150, 50));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ev) {
if (textField.getText() != null) {
try {
server = new Server(Integer.parseInt(textField.getText()));
} catch (IOException e) {
System.out.println("ERROR: Port already in use! Please enter a new " +
"port number.");
}
}
}
});
buttonPane.add(button, c);
button = new JButton("Main Menu");
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.SOUTH;
c.gridx = 0;
c.gridy = 3;
c.weightx = 0.5;
c.weighty = 1;
c.insets = MainGUI.defaultInsets;
button.setPreferredSize(new Dimension(150, 50));
button.addActionListener(new ActionListener() {
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.
* ActionEvent)
*/
public void actionPerformed(ActionEvent event) {
MainGUI.mainGUI.numberOfPlayers = "4";
MainGUI.mainGUI.startMainGUI();
frame.dispose();
try {
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
buttonPane.add(button, c);
button = new JButton("Quit");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 4;
c.weightx = 0.5;
c.weighty = 0;
c.insets = MainGUI.defaultInsets;
button.setPreferredSize(new Dimension(150, 50));
button.addActionListener(new ActionListener() {
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.
* ActionEvent)
*/
public void actionPerformed(ActionEvent event) {
frame.dispose();
try {
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
buttonPane.add(button, c);
} |
d002ec67-21ab-435e-b31b-02b910098be0 | 3 | public void calcTMmodeEffectiveRefractiveIndices(){
this.effectiveRefractiveIndicesTM = new double[this.numberOfTMmeasurementsPrism];
this.effectiveErrorsTM = new double[this.numberOfTMmeasurementsPrism];
if(this.setTMerrors){
ErrorProp alpha = new ErrorProp(this.prismAngleAlphaRad, 0.0D);
ErrorProp prismRI = new ErrorProp(super.prismRefractiveIndex, 0.0D);
ErrorProp airRI = new ErrorProp(RefractiveIndex.air(super.wavelength), 0.0D);
ErrorProp phi = new ErrorProp();
ErrorProp angle = new ErrorProp();
for(int i=0; i<this.numberOfTMmeasurementsPrism; i++){
angle.reset(this.anglesRadTM[i], this.errorsRadTM[i]);
phi = (angle.over(prismRI)).times(airRI);
phi = ErrorProp.asin(phi);
phi = alpha.plus(phi);
phi = prismRI.times(ErrorProp.sin(phi));
this.effectiveRefractiveIndicesTM[i] = phi.getValue();
this.effectiveErrorsTM[i] = phi.getError();
}
super.enterTMmodeData(this.thicknessesTM, this.effectiveRefractiveIndicesTM, this.effectiveErrorsTM, this.modeNumbersTM);
}
else{
for(int i=0; i<this.numberOfTMmeasurementsPrism; i++){
double phi = this.prismAngleAlphaRad + Math.asin(RefractiveIndex.air(super.wavelength)*this.anglesRadTM[i]/super.prismRefractiveIndex);
this.effectiveRefractiveIndicesTM[i] = super.prismRefractiveIndex*Math.sin(phi);
}
super.enterTMmodeData(this.thicknessesTM, this.effectiveRefractiveIndicesTM, this.modeNumbersTM);
}
} |
92894905-5053-40fc-b992-a0dfbe78aaab | 9 | public boolean containsValue (Object value, boolean identity) {
V[] valueTable = this.valueTable;
if (value == null) {
K[] keyTable = this.keyTable;
for (int i = capacity + stashSize; i-- > 0;)
if (keyTable[i] != null && valueTable[i] == null) return true;
} else if (identity) {
for (int i = capacity + stashSize; i-- > 0;)
if (valueTable[i] == value) return true;
} else {
for (int i = capacity + stashSize; i-- > 0;)
if (value.equals(valueTable[i])) return true;
}
return false;
} |
a2286cf3-20b0-4f6e-a3c5-7b715f6ca8c3 | 7 | @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
// Entering a sub-command without parameters is assumed to be a request
// for information. So display some detailed help.
if (args.length == 0) {
sender.sendMessage(plugin.translate(sender, "menu-edit-usage-extended", "/menu edit ([player]) [id] - Opens the menu with the given id for editing. This allows you to move menu items in and out of a menu. If a player is given, it will open the menu for the given player for editing, whether or not they have permission"));
return true;
}
// Expecting exactly one parameter, the id
if (args.length < 1 || args.length > 2) {
return false;
}
Player target;
String id;
if (args.length == 2) {
target = plugin.getServer().getPlayer(args[0]);
if (target == null) {
sender.sendMessage(plugin.translate(sender, "player-not-online", "{0} is not online", args[0]));
return true;
}
id = args[1];
} else {
id = args[0];
if (sender instanceof Player) {
target = (Player) sender;
} else {
sender.sendMessage(plugin.translate(sender, "console-no-target", "The console must specify a player"));
return false;
}
}
// Check the id is valid
Menu menu = plugin.getMenu(id);
if (menu == null) {
sender.sendMessage(plugin.translate(sender, "unknown-menu-id", "There is no menu with id {0}", id));
return true;
}
menu.edit(target);
return true;
} |
baf22003-cc4e-45a3-8190-137bf7b6ece0 | 9 | public void DrawBoard (){
for (int i = 0; i<9;i++){
if (i != 0 && i % 3 == 0){
System.out.println();
System.out.print("-----------");
System.out.println();
}
if (DrawnTTTBoard.isEmpty(i)){
System.out.print(" ");
}
if (DrawnTTTBoard.hasCross(i)){
System.out.print(" X ");
}
if (DrawnTTTBoard.hasNought(i)){
System.out.print(" O ");
}
if (i != 2 && i != 5 && i != 8){
System.out.print("|");
}
}
} |
df7309ff-ae35-43b2-a4b2-061231767c34 | 1 | public ShortAnswer(boolean needsAnswer){
prompt = InputHandler.getString("Enter the prompt for your Short Answer question:");
if (needsAnswer){
setCorrectAnswer();
}
} |
5a1491e6-7227-4640-ab76-7e331f2829ac | 9 | private static Stalk_Color_Below_Ring loadStalkColorBelow(String stalk_color_below)
{
if(stalk_color_below.equals("n"))
{
return Stalk_Color_Below_Ring.brown;
}
else if(stalk_color_below.equals("b"))
{
return Stalk_Color_Below_Ring.buff;
}
else if(stalk_color_below.equals("c"))
{
return Stalk_Color_Below_Ring.cinnamon;
}
else if(stalk_color_below.equals("g"))
{
return Stalk_Color_Below_Ring.gray;
}
else if(stalk_color_below.equals("o"))
{
return Stalk_Color_Below_Ring.orange;
}
else if(stalk_color_below.equals("p"))
{
return Stalk_Color_Below_Ring.pink;
}
else if(stalk_color_below.equals("e"))
{
return Stalk_Color_Below_Ring.red;
}
else if(stalk_color_below.equals("w"))
{
return Stalk_Color_Below_Ring.white;
}
else if(stalk_color_below.equals("y"))
{
return Stalk_Color_Below_Ring.yellow;
}
return null;
} |
eec976cd-5173-48b3-b311-43c6092f8f3a | 2 | @Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
item.setCurrentAnimation(1);
Thread.sleep(1000);
item.setCurrentAnimation(2);
Thread.sleep(1000);
item.setCurrentAnimation(0);
}
} catch (InterruptedException e) {
}
} |
7d37b748-9ab9-4e7b-9bbe-d9fea9f849b8 | 1 | public EncryptedDeck requestEncDeck(User reqUser, EncryptedDeck encDeck)
throws IOException, InterruptedException {
Notification not = new Notification();
encryptedDeck = null;
final Subscription encSub = elvin.subscribe(NOT_TYPE + " == '"
+ ENCRYPT_DECK_REPLY + "' && " + GAME_ID + " == '"
+ gameHost.getID() + "'");
encSub.addListener(new NotificationListener() {
public void notificationReceived(NotificationEvent e) {
byte[] tmpBytes = (byte[]) e.notification.get(ENCRYPTED_DECK);
try {
encryptedDeck = (EncryptedDeck) Passable
.readObject(tmpBytes);
} catch (Exception e1) {
shutdown();
System.exit(-2);
}
// notify the waiting thread that a message has arrived
synchronized (encSub) {
encSub.notify();
}
}
});
// construct the notification to send
not.set(NOT_TYPE, ENCRYPT_DECK_REQUEST);
not.set(GAME_ID, gameHost.getID());
not.set(REQ_USER, reqUser.getID());
not.set(ENCRYPTED_DECK, encDeck.writeObject());
synchronized (encSub) {
// send notification
elvin.send(not);
System.out.println("Sending encrypt deck request to user - "
+ reqUser.getID());
// wait until received reply
encSub.wait();
}
encSub.remove();
return encryptedDeck;
} |
7652b8cb-7e7a-4777-b1c4-49be0aaf3f45 | 3 | @Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 0) {
return sectionNameList.get(rowIndex);
}
if (columnIndex == 1) {
return sectionIdList.get(rowIndex);
}
if (columnIndex == 2) {
return sectionWordsAmount.get(rowIndex);
}
else {
return "0";
}
} |
3a66d8a8-755c-4065-ab96-3e1addfdf37b | 5 | public void Stop() throws InterruptedException, IOException {
if (!Running)
return;
Running = false;
Log("Stopping server...");
for(Player p : players)
{
p.sendMessage("Stopping server...");
}
for (Level l : this.getLevelHandler().getLevelList()) {
if (l != MainLevel)
l.Unload(this);
}
MainLevel.Save();
tick.join();
logger.Stop();
heartbeater.stop();
for(Player p : players) // Implementing this again because I want to stop everything first.
{ // The idea is that at the begining of the "stopping" session, the player receives that the server is stopping.
// Then after everything has stopped but the server itself, the player is kicked from the server before actually shutdown.
p.Kick("Server shut down. Thanks for playing!"); // Kicking so we can place a message that the server was stopped.
}
pm.StopReading();
} |
6914f3c0-2f27-423f-907a-450b4d835b2e | 9 | public Query handleInsertStatement(ZInsert s, TransactionId tId)
throws DbException, simpledb.ParsingException
{
int tableId;
try {
tableId = Database.getCatalog().getTableId(s.getTable()); // will
// fall
// through if
// table
// doesn't
// exist
} catch (NoSuchElementException e) {
throw new simpledb.ParsingException("Unknown table : " + s.getTable());
}
TupleDesc td = Database.getCatalog().getTupleDesc(tableId);
Tuple t = new Tuple(td);
int i = 0;
DbIterator newTups;
if (s.getValues() != null) {
@SuppressWarnings("unchecked")
Vector<ZExp> values = s.getValues();
if (td.numFields() != values.size()) {
throw new simpledb.ParsingException(
"INSERT statement does not contain same number of fields as table " + s.getTable());
}
for (ZExp e : values) {
if (!(e instanceof ZConstant))
throw new simpledb.ParsingException(
"Complex expressions not allowed in INSERT statements.");
ZConstant zc = (ZConstant) e;
if (zc.getType() == ZConstant.NUMBER) {
if (td.getFieldType(i) != Type.INT_TYPE) {
throw new simpledb.ParsingException("Value " + zc.getValue()
+ " is not an integer, expected a string.");
}
IntField f = new IntField(new Integer(zc.getValue()).intValue());
t.setField(i, f);
} else if (zc.getType() == ZConstant.STRING) {
if (td.getFieldType(i) != Type.STRING_TYPE) {
throw new simpledb.ParsingException("Value " + zc.getValue()
+ " is a string, expected an integer.");
}
StringField f = new StringField(zc.getValue(), Type.STRING_LEN);
t.setField(i, f);
} else {
throw new simpledb.ParsingException("Only string or int fields are supported.");
}
i++;
}
ArrayList<Tuple> tups = new ArrayList<Tuple>();
tups.add(t);
newTups = new TupleArrayIterator(tups);
} else {
ZQuery zq = s.getQuery();
LogicalPlan lp = parseQueryLogicalPlan(tId, zq);
newTups = lp.physicalPlan(tId, TableStats.getStatsMap(), explain);
}
Query insertQ = new Query(tId);
insertQ.setPhysicalPlan(new Insert(tId, newTups, tableId));
return insertQ;
} |
e40c6d97-0b92-4576-8afb-a5d245113592 | 5 | public long Problem3() {
long n=Long.parseLong("600851475143");
long maior=0;
while(n!=1) {
int i=2;
while (i<=n) {
if (Utility_J.isPrime(i) && n%i==0) {
if (i>maior) {
maior = i;
}
n/=i;
break;
}
i++;
}
}
return maior;
} |
ffd56958-c7de-4274-a491-30b910b00061 | 4 | public boolean checkStatus() {
for (final TextFile availableTextFile : AvailableTextFiles.getInstance().getAvailableTextFiles()) {
try {
final SVNStatus status =
this.svnClientManager.getStatusClient().doStatus(new File(availableTextFile.getAbsolutePath()), true);
if (status != null) {
final SVNStatusType contentsStatus = status.getContentsStatus();
final String svnStatus = this.defineSVNStatus(contentsStatus);
if (!availableTextFile.getSvnStatus().equals(svnStatus)) {
// Status was changed
availableTextFile.setSvnStatus(svnStatus);
}
}
}
catch (final SVNException e) {
e.printStackTrace();
}
}
return true;
} |
c11d7303-c6c3-4a1b-80ce-e0d6ccbf061d | 8 | private String [] fillArrayAtDo(String [] pullValues){
if(pullValues[2].equalsIgnoreCase("FORCE") && pullValues[3].equalsIgnoreCase("COORDINATES"))
return new String [] {"@DO", "FORCE_COORDINATES", pullValues[1], pullValues[4]};
else if(pullValues[2].equalsIgnoreCase("FORCE") && pullValues[3].equalsIgnoreCase("ALTITUDE"))
return new String [] {"@DO", "FORCE_ALTITUDE", pullValues[1], pullValues[4]};
else if(pullValues[2].equalsIgnoreCase("FORCE") && pullValues[3].equalsIgnoreCase("HEADING"))
return new String [] {"@DO", "FORCE_HEADING", pullValues[1], pullValues[4]};
else if(pullValues[2].equalsIgnoreCase("FORCE") && pullValues[3].equalsIgnoreCase("SPEED"))
return new String [] {"@DO", "FORCE_SPEED", pullValues[1], pullValues[4]};
return null;
} |
10dd8bf6-7f52-4fe6-b5bc-fce682007482 | 3 | public boolean enter(String s, SymtabEntry e) {
boolean isNew = true;
SymtabEntry value = lookup(s);
if (value != null)
if (value.getScope().equals(e.getScope()))
isNew = false;
m.put(s, e);
if (isNew)
l.add(s);
return isNew;
} |
a4a38cea-06ed-459f-a0de-56c4fd1a65ca | 8 | private void processType(String alias, String description)
{
// get type
Type type = this._typeManager.getType(alias);
// apply superclass
if (this._extendsTypes != null && this._extendsTypes.size() > 0)
{
// TODO: Only supporting single inheritance
Type superClass = this._extendsTypes.get(0);
type.setSuperClass(superClass);
}
// apply description
if (description != null && description.length() > 0)
{
type.setDescription(description);
}
// apply references
for (String reference : this._references)
{
type.addReference(reference);
}
// apply visibility
if (this._isAdvanced)
{
type.setVisibility(ADVANCED);
}
else if (this._isPrivate)
{
type.setVisibility(PRIVATE);
}
else if (this._isInternal)
{
type.setVisibility(INTERNAL);
}
} |
a204485f-2e5c-4454-b7a9-a6d5d919f932 | 0 | public static void main(String[] args) {
Base base = getBase(47);
base.f();
} |
71ef12df-aa7f-416b-9235-867afa168244 | 0 | public UserRemovalFinalized(User user)
{
this.user = user;
} |
65d99e56-d049-47d2-a0e7-590e48b28cbf | 9 | ArchiveLoader(int i, FileIndex class137, FileIndex class137_23_, OndemandWorker requester, FileIndexWorker class112, int i_24_, byte[] is, int i_25_, boolean bool) {
requestTable = new HashTable(16);
anInt6373 = 0;
requestsDeque = new Deque();
aLong6374 = 0L;
do {
try {
indexId = i;
fileIndex = class137;
if (fileIndex != null) {
aBoolean6368 = true;
aClass262_6372 = new Deque();
} else
aBoolean6368 = false;
checksum = i_24_;
src = is;
anInt6352 = i_25_;
aClass137_6364 = class137_23_;
aBoolean6375 = bool;
requestWorker = requester;
fileIndexWorker = class112;
if (aClass137_6364 == null)
break;
indexTableRequest = fileIndexWorker.createQuickReadRequest(aClass137_6364, indexId, (byte) -112);
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929
(runtimeexception,
("bja.<init>(" + i + ','
+ (class137 != null ? "{...}" : "null") + ','
+ (class137_23_ != null ? "{...}" : "null") + ','
+ (requester != null ? "{...}" : "null") + ','
+ (class112 != null ? "{...}" : "null") + ','
+ i_24_ + ',' + (is != null ? "{...}" : "null")
+ ',' + i_25_ + ',' + bool + ')'));
}
break;
} while (false);
} |
81af1f30-5bda-45f6-a9c1-b40bdadd1a70 | 4 | public void setGrid(Grid grid) {
this.grid = grid;
Slot[][] newCells = new Slot[grid.getNumRows()][grid.getNumColumns()];
for (int r = 0; r < grid.getNumRows(); r++) {
for (int c = 0; c < grid.getNumColumns(); c++) {
if (r < cells.length && c < cells[0].length) {
newCells[r][c] = cells[r][c];
}
else {
newCells[r][c] = new Slot();
}
}
}
cells = newCells;
needsAligned();
} |
9deee9d7-9a0c-4b39-9e40-b0fc38debb16 | 4 | public void save()
{
//W klasie docelowej należy sprawdzić, czy row.isEmpty()
//jeśli tak, to należy nadać nazwę tabeli, do ktrej zostanie wstawiony wiersz
//należy to zrobić za pomocą row.setTableName(<nazwa>);
//Dopiero potem należy wywołać save z klasy bazowej
if(row.isEmpty())
{
row.addAttribute("name", name);
row.addAttribute("description", description);
for(Parameter p : parameters)
{
row.addAttribute(p.getName(), p.getValue());
}
for(AbstractAttribute a : attributes)
{
row.addAttribute(a.getType(), a.getName());
}
DataVector.getInstance().dbManager.insert(row);
} else {
row.update("description", description);
DataRow param = new DataRow(row.getName());
param.setTableName(row.getTableName());
param.addAttribute("userName", DataVector.getInstance().dbManager.getUserName());
List<DataRow> res = DataVector.getInstance().dbManager.select(param);
if(!res.isEmpty())
{
DataVector.getInstance().dbManager.update(param, row);
} else {
DataVector.getInstance().dbManager.insert(row);
}
}
} |
c50f0994-2657-4c4d-8c69-d7f645e0e97d | 0 | public int getPerimeter() {
return 4 * side;
} |
9d61ecb6-97fa-4dba-923c-b712e09677b9 | 1 | public long getLong(String key) throws JSONException {
Object o = get(key);
return o instanceof Number ?
((Number)o).longValue() : (long)getDouble(key);
} |
59a5d298-67a0-443b-bf8a-81ddc29d908c | 2 | private long calcSSD (int[] org, int[] dec, int width, int height) {
long ssd = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int diff = org[y * width + x] - dec[y * width + x];
ssd += diff * diff;
}
}
return ssd;
} |
5e2f16f7-ca2b-4692-af2a-50a1e14c197a | 4 | private void handleCommon(HTMLComponent comp) {
currentPage.addChild(comp);
if (currentPage != currentContainer()) {
currentContainer().addChild(comp);
}
if (comp instanceof HTMLContainer) {
pushContainer((HTMLContainer)comp);
}
if (comp instanceof HTMLInput && currentForm != null) {
((HTMLFormImpl)currentForm).addInput((HTMLInput)comp);
}
} |
5a36eb62-7419-49e7-a359-7dc4173b3e31 | 2 | public void setPrismAngleAlpha(double angle){
this.prismAngleAlphaDeg = angle;
this.prismAngleAlphaRad = Math.toRadians(angle);
this.setPrismAlpha = true;
if(this.setMeasurementsPrism && this.setPrismRI)this.calcEffectiveRefractiveIndices();
} |
09cea4c2-e592-471b-811e-68e54c602a6a | 1 | private void compute_pcm_samples13(Obuffer buffer)
{
final float[] vp = actual_v;
//int inc = v_inc;
final float[] tmpOut = _tmpOut;
int dvp =0;
// fat chance of having this loop unroll
for( int i=0; i<32; i++)
{
final float[] dp = d16[i];
float pcm_sample;
pcm_sample = (float)(((vp[13 + dvp] * dp[0]) +
(vp[12 + dvp] * dp[1]) +
(vp[11 + dvp] * dp[2]) +
(vp[10 + dvp] * dp[3]) +
(vp[9 + dvp] * dp[4]) +
(vp[8 + dvp] * dp[5]) +
(vp[7 + dvp] * dp[6]) +
(vp[6 + dvp] * dp[7]) +
(vp[5 + dvp] * dp[8]) +
(vp[4 + dvp] * dp[9]) +
(vp[3 + dvp] * dp[10]) +
(vp[2 + dvp] * dp[11]) +
(vp[1 + dvp] * dp[12]) +
(vp[0 + dvp] * dp[13]) +
(vp[15 + dvp] * dp[14]) +
(vp[14 + dvp] * dp[15])
) * scalefactor);
tmpOut[i] = pcm_sample;
dvp += 16;
} // for
} |
73d41a07-a743-448e-9e76-3db8dc4af912 | 6 | public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
boolean[][] nabomatrise = new boolean[n][n];
String naboRad;
for(int i=0;i<n;i++){
naboRad=in.readLine();
for(int j=0;j<n;j++)
if(naboRad.charAt(j)=='1')nabomatrise[i][j]=true;
}
String linje = in.readLine();
StringBuilder sb = new StringBuilder();
int startnode= Integer.parseInt(linje);
sb.append((subgraftetthet(nabomatrise, startnode)));
linje=in.readLine();
while(linje!=null && linje.length()>0){
sb.append("\n");
startnode= Integer.parseInt(linje);
sb.append((subgraftetthet(nabomatrise, startnode)));
linje=in.readLine();
}
System.out.println(sb);
} catch (Exception e) {
e.printStackTrace();
}
} |
83b0ce0c-acfb-4d70-81fa-5f1313070971 | 6 | public GUIController(WorldFrame<T> parent, GridPanel disp,
DisplayMap displayMap, ResourceBundle res)
{
resources = res;
display = disp;
parentFrame = parent;
this.displayMap = displayMap;
makeControls();
occupantClasses = new TreeSet<Class>(new Comparator<Class>()
{
public int compare(Class a, Class b)
{
return a.getName().compareTo(b.getName());
}
});
World<T> world = parentFrame.getWorld();
Grid<T> gr = world.getGrid();
for (Location loc : gr.getOccupiedLocations())
addOccupant(gr.get(loc));
for (String name : world.getOccupantClasses())
try
{
occupantClasses.add(Class.forName(name));
}
catch (Exception ex)
{
ex.printStackTrace();
}
timer = new Timer(INITIAL_DELAY, new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
step();
}
});
display.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent evt)
{
Grid<T> gr = parentFrame.getWorld().getGrid();
Location loc = display.locationForPoint(evt.getPoint());
if (loc != null && gr.isValid(loc) && !isRunning())
{
//display.setCurrentLocation(loc);
//locationClicked();
}
}
});
stop();
} |
78aff74c-9cf5-4176-8c52-ed2eb7ace62c | 3 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Volume other = (Volume) obj;
if (this.value != other.value) {
return false;
}
return this.unit == other.unit;
} |
14a7ce16-1b88-42b5-8317-4a45b1e5af7d | 6 | public List<List<String>> getRecords(String fundCode) throws IOException {
if(records == null){
records = new HashMap<String, List<List<String>>>();
}
if(records.size() > RECORDCACHESIZE){
records.clear();
}
if(!records.containsKey(fundCode)){
List<List<String>> record = null;
try {
record = c.getRecords(fundCode);
records.put(fundCode, record);
FileDataBase.save(records.get(fundCode), root + "/" + fundCode + ".txt");
return records.get(fundCode);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String json = FileDataBase.readFromFile(root + "/" + fundCode + ".txt");
String[][] datas = gson.fromJson(json, String[][].class);
List<List<String>> lDatas = new ArrayList<List<String>>();
for(String[] data : datas){
List<String> llData = new ArrayList<String>();
llData.add(data[0]);
llData.add(data[1]);
llData.add(data[2]);
llData.add(data[3]);
llData.add(data[4]);
lDatas.add(llData);
}
records.put(fundCode, lDatas);
return records.get(fundCode);
}
return records.get(fundCode);
} |
d20ca966-0b4c-45df-8e07-9b64f8bbb1ac | 8 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ResourceHand other = (ResourceHand) obj;
if (brick != other.brick)
return false;
if (ore != other.ore)
return false;
if (sheep != other.sheep)
return false;
if (wheat != other.wheat)
return false;
if (wood != other.wood)
return false;
return true;
} |
5490bfe5-122f-4356-a634-72658b28e4f8 | 3 | public static void updateYellow() {
for (int i = 0; i < yOrgs.size(); i++) {
Organism g1 = yOrgs.get(i);
g1.move();
for (int j = i + 1; j < yOrgs.size(); j++) {
Organism g2 = yOrgs.get(j);
if (g1.getDist(g2) < 40) {
g1.closeTo(g2);
}
}
}
} |
d724dc60-fb38-4ba9-bf45-74bf283fcde3 | 9 | public static void main(String args[]) {
boolean[] isPrime = EulerMath.getSieve(1_000_000);
int total = 0;
for(int i = 10; i < isPrime.length; i++)
if( isPrime[i] ) {
boolean add = true;
int x = i;
int numDigits = 0;
// Removes least significant
while( add && x > 0 ) {
if( isPrime[x] ) {
numDigits++;
x /= 10;
}
else
add = false;
}
x = i;
// Removes most significant
while( add && numDigits > 0 ) {
if( isPrime[x] ) {
x = i%(int)(Math.pow(10, numDigits-1));
numDigits--;
}
else
add = false;
}
if(add)
total += i;
}
System.out.println("total = "+ total);
} |
5dc98af3-9e07-45ab-a5a6-68cedf05cc54 | 0 | public static void main(String[] args) {
Detergent x = new Detergent();
x.dilute();
x.apply();
x.scrub();
x.foam();
System.out.println(x);
System.out.println("Testing base class:");
Cleanser.main(args);
} |
67345692-cf60-4d55-a049-5f6035fce6f2 | 8 | public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0)
return "";
int num = strs.length;
if (num == 1)
return strs[0];
int len1 = strs[0].length();
String prefix = "";
for (int idx = 0; idx < len1; idx++) {
boolean flag = false;
char key = strs[0].charAt(idx);
for (int i = 1; i < num; i++) {
if (strs[i].length() <= idx || strs[i].charAt(idx) != key) {
flag = true;
break;
}
}
if (flag)
break;
else {
prefix += key;
}
}
return prefix;
} |
e0ad74db-bd70-4f37-84ef-106dd554f790 | 8 | public void warn(Event event) {
switch(event.getTypeEvent())
{
case SHUTDOWN :
stop();
break;
case PLAYMUSIC_END :
end = true;
break;
case GOFORWARD_END :
state = 1;
robotMoving = false;
break;
case GOBACKWARD_END :
state = 2;
robotMoving = false;
break;
case ROTATE_END :
state = 0;
robotMoving = false;
break;
case USECLAWS_END :
clawsMoving = false;
attente = true;
nextclawsOpenure = 1.0f - nextclawsOpenure;
break;
case WAIT_END :
if(event.getName().equals("end"))
end = true;
else
attente = false;
break;
default:
break;
}
} |
6e2a537e-d3f9-40a8-a784-a34ea5303477 | 7 | public int overlapEnd(int start, int end) {
if (start >= end) throw new IllegalArgumentException("The end " + end + " should be greater than start " + start);
IntervalNode intervalNode = root;
if (root == null || start >= root.maxEnd || end <= root.start)
return -1;
while (intervalNode != null) {
if (intersection(start, end, intervalNode.start, intervalNode.end))
return intervalNode.end;
if (goLeft(start, end, intervalNode.left)) {
intervalNode = intervalNode.left;
} else {
intervalNode = intervalNode.right;
}
}
return -1;
} |
74882d8e-9404-4e29-a75c-774bb78063b2 | 3 | public BufferedImage captureScreen()
{
File oDir = new File("");
String sDirectory = "";
String sPathSeparator = "";
if (!sDirectory.endsWith(File.separator))
{
sPathSeparator = File.separator;
}
try{
sDirectory = oDir.getCanonicalPath();
}
catch (IOException ex){
System.out.println(ex.getMessage());
}
final String sCurrentDateTime = getCurrentDataTime();
final String sFilename = sDirectory + sPathSeparator + "_" + sCurrentDateTime + ".png";
System.out.println("---");
try
{
// Determine current screen size
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension oScreenSize = toolkit.getScreenSize();
Rectangle oScreen = new Rectangle(oScreenSize);
// Create screen shot
Robot robot = new Robot();
BufferedImage oImage = robot.createScreenCapture(oScreen);
// Save captured image to PNG file
//ImageIO.write(oImage, "png", new File(sFilename));
// Display info of image saved.
//String sMsg = String.format("Screenshot(%s x %s pixels) is saved to %s.", oImage.getWidth(), oImage.getHeight(), sFilename);
//System.out.println(sMsg);
return oImage;
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
System.exit(0); // Shutdown the application completely. Need this because of the infinite loop.
}
return null;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.