method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
0629db93-613c-4fec-b356-2e315768808c | 1 | public static void main(String args[]) {
initialize();
while (true) {
// resets the board to the screen
Interperet.reset();
// moves the best move
Calculate.move(Calculate.bestMove());
}
} |
a9332a89-82ba-4b3a-89ee-1ca780ac6ca5 | 5 | protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = null;
try {
// get the action class to be called
// to do this, we grab the URL and take the ".action" off of it
String servletpath = request.getServletPath().substring(1);
int dot = servletpath.lastIndexOf(".action");
if (dot <= 0) {
throw new ServletException("Invalid action. No method specified");
}
String className = servletpath.substring(0, dot);
// get an instance of the action
Class klass = Class.forName(className);
Action action = (Action)klass.newInstance();
// call the action
String viewPath = action.process(request, response);
// get a dispatcher to the view (if the action returned something besides null)
if (viewPath != null) {
dispatcher = request.getRequestDispatcher(viewPath);
}
}catch (Exception e) {
// this is wierd. from a servlet, tomcat seems to inspect the embedded
// exception, not the main exception. so i'm embedding a WebException
// inside a regular ServletException. this makes tomcat (per web.xml)
// call the /error.jsp page.
if (e instanceof WebException) { // already a WebException
throw new ServletException(e);
}else{ // wrap it in one
throw new ServletException(new WebException("Error in controller: " + e.getMessage(), e));
}//if
}
// forward to the JSP page
if (dispatcher != null) {
dispatcher.forward(request, response);
}
} |
e14035e5-04e9-4692-aa6b-2125d8eb1481 | 4 | public static String getSqlWhereWithValues(Map<String, Object> sqlWhereMap) throws SQLException {
if (sqlWhereMap.size() < 1)
return null;
StringBuffer sqlWhere = new StringBuffer();//SQL语句
Set<Entry<String, Object>> entrySets = sqlWhereMap.entrySet();
for (Iterator<Entry<String, Object>> iteraotr = entrySets.iterator(); iteraotr.hasNext();) {
Entry<String, Object> entrySet = iteraotr.next();
Object value = entrySet.getValue();
if (value.getClass() == String.class) {
sqlWhere.append(entrySet.getKey()).append(" like ").append(StringPool.APOSTROPHE+entrySet.getValue()+StringPool.APOSTROPHE).append(" and ");
}else if(value.getClass() == Date.class){
sqlWhere.append(entrySet.getKey()).append(" = ").append(StringPool.APOSTROPHE + entrySet.getValue() + StringPool.APOSTROPHE).append(" and ");
}
else {
sqlWhere.append(entrySet.getKey()).append(" = ").append(entrySet.getValue()).append(" and ");
}
}
sqlWhere.delete(sqlWhere.lastIndexOf("and"), sqlWhere.length());
return sqlWhere.toString();
} |
a9e113d8-ad72-4c30-93c3-2028f053378a | 2 | public void run() {
if (progressBar != null) {
progressBar.setMinimum(0);
progressBar.setMaximum(countClasses(0, ""));
}
readPackage(0, new HashMap(), "", 0);
TreeModelListener[] ls;
synchronized (listeners) {
ls = (TreeModelListener[]) listeners
.toArray(new TreeModelListener[listeners.size()]);
}
TreeModelEvent ev = new TreeModelEvent(this, new Object[] { root });
for (int i = 0; i < ls.length; i++)
ls[i].treeStructureChanged(ev);
main.reselect();
} |
32e3f306-6a09-4400-a494-6157556d563e | 8 | public JSONObject parseUserAnimeListXML(InputStream inputXML) throws MALException, IOException {
// My storage variables
final ArrayList<Anime> myAnime = new ArrayList<Anime>();
final JSONObject animeListData = new JSONObject();
final Anime currentAnime = new Anime();
final User currentUser = new User();
// XML nodes to detect
RootElement root = new RootElement(MYANIMELIST);
Element anime = root.getChild(ANIME);
Element user = root.getChild(MYINFO);
// Set parse events for myinfo node
user.getChild(USER_ID).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentUser.setId(Integer.parseInt(body));
}
});
user.getChild(USER_NAME).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentUser.setName(body);
}
});
user.getChild(USER_WATCHING).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentUser.setAnimeWatching(Integer.parseInt(body));
}
});
user.getChild(USER_COMPLETED).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentUser.setAnimeCompleted(Integer.parseInt(body));
}
});
user.getChild(USER_ONHOLD).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentUser.setAnimeOnhold(Integer.parseInt(body));
}
});
user.getChild(USER_DROPPED).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentUser.setAnimeDropped(Integer.parseInt(body));
}
});
user.getChild(USER_PLANTOWATCH).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentUser.setAnimePlanToWatch(Integer.parseInt(body));
}
});
user.getChild(USER_DAYS_SPENT_WATCHING).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentUser.setAnimeDaysSpentWatching(Double.parseDouble(body));
}
});
// Set parse events for anime node
anime.setEndElementListener(new EndElementListener() {
public void end() {
myAnime.add(currentAnime.copy());
}
});
anime.getChild(SERIES_ANIMEDB_ID).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentAnime.setId(Integer.parseInt(body));
}
});
anime.getChild(SERIES_TITLE).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentAnime.setTitle(body);
}
});
anime.getChild(SERIES_SYNONYMS).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
if(body.equals("")) {
currentAnime.setSynonyms(new String[0]);
} else {
currentAnime.setSynonyms(body.split(";\\s"));
}
}
});
anime.getChild(SERIES_TYPE).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentAnime.setType(Integer.parseInt(body));
}
});
anime.getChild(SERIES_EPISODES).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentAnime.setEpisodes(Integer.parseInt(body));
}
});
anime.getChild(SERIES_STATUS).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentAnime.setStatus(Integer.parseInt(body));
}
});
anime.getChild(SERIES_START).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
if(body.equals("0000-00-00") == false) {
currentAnime.setStart(Date.valueOf(body));
}
}
});
anime.getChild(SERIES_END).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
if(body.equals("0000-00-00") == false) {
currentAnime.setEnd(Date.valueOf(body));
}
}
});
anime.getChild(SERIES_IMAGE).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentAnime.setImageUrl(body);
}
});
anime.getChild(MY_ID).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentAnime.setUserListId(Integer.parseInt(body));
}
});
anime.getChild(MY_WATCHED_EPISODES).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentAnime.setUserEpisodesWatched(Integer.parseInt(body));
}
});
anime.getChild(MY_START_DATE).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
if(body.equals("0000-00-00") == false) {
currentAnime.setUserStart(Date.valueOf(body));
}
}
});
anime.getChild(MY_FINISH_DATE).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
if(body.equals("0000-00-00") == false) {
currentAnime.setUserFinish(Date.valueOf(body));
}
}
});
anime.getChild(MY_SCORE).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentAnime.setUserScore(Integer.parseInt(body));
}
});
anime.getChild(MY_STATUS).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
final int userStatus = Integer.parseInt(body);
currentAnime.setPreviousUserStatus(userStatus);
currentAnime.setUserStatus(userStatus);
}
});
anime.getChild(MY_REWATCHING).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
if(body.equals("1")) {
currentAnime.setUserEnableRewatching(true);
} else {
currentAnime.setUserEnableRewatching(false);
}
}
});
anime.getChild(MY_LAST_UPDATED).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentAnime.setUserLastUpdated(body);
}
});
anime.getChild(MY_TAGS).setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentAnime.setUserTags(body);
}
});
try {
Xml.parse(inputXML, Xml.Encoding.UTF_8, root.getContentHandler());
animeListData.put("user", currentUser);
animeListData.put("anime", myAnime);
} catch (Exception e) {
throw new MALException(e);
} finally {
if(inputXML != null)
inputXML.close();
}
return animeListData;
} |
331043c2-8524-40dc-b909-86d6078ef512 | 6 | @Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof UnitsValue<?>) {
UnitsValue<?> uv = (UnitsValue<?>) obj;
return mUnits == uv.mUnits && mValue == uv.mValue;
}
return false;
} |
df235c50-3a3c-4efb-a138-2ec272ff7276 | 3 | public void export(Exporter ex) throws SQLException, IOException {
ex.start(settings.getName());
String query = "SELECT entry_id FROM entry";
EnumSet<ExporterSettings> expSetting = ex.getSettings();
if (expSetting == null) {
expSetting = EnumSet.noneOf(ExporterSettings.class);
}
if (expSetting.contains(ExporterSettings.ALPHABETICAL)) {
query = query + " ORDER BY LOWER(word)";
}
query = query + ";";
ResultSet res = connection.createStatement().executeQuery(query);
while (res.next()) {
ex.addEntry(getEntry(res.getLong("entry_id")));
}
ex.finish();
} |
06e2c493-4763-4cb6-9bbb-839b09ecad8f | 9 | /* @ pure */ public Coordinate recursiveCheck(int x, int y, Mark mark, int xOffset,
int yOffset, boolean seenSomething) {
if (x < 0 || y < 0 || x > DIM - 1 || y > DIM - 1) {
return null;
} else if (fields[index(x, y)] == Mark.EMPTY) {
return null;
} else if (fields[index(x, y)] == mark && seenSomething) {
return coordinates[index(x, y)];
} else if (fields[index(x, y)] == mark && !seenSomething) {
return null;
} else {
return recursiveCheck(x + xOffset, y + yOffset, mark, xOffset,
yOffset, true);
}
} |
73c7a784-5728-4adf-8eb0-5547b68e0f55 | 6 | public final void encode(final IAMCodec codec, final IAMIndex source) throws IOException, IllegalArgumentException {
final int mappingCount = source.mappingCount();
final int listingCount = source.listingCount();
final IAMINDEXTYPE xmlIndex = new IAMINDEXTYPE();
xmlIndex.byteOrder = codec.getByteOrder().toString();
xmlIndex.mappingCount = Integer.toString(mappingCount);
xmlIndex.listingCount = Integer.toString(listingCount);
for (int index = 0; index < mappingCount; index++) {
final IAMMapping mapping = source.mapping(index);
final int entryCount = mapping.entryCount();
if (entryCount != 0) {
final IAMMAPPINGTYPE xmlMapping = new IAMMAPPINGTYPE();
xmlIndex.mappingOrListing.add(xmlMapping);
xmlMapping.index = Integer.toString(index);
for (int i = 0; i < entryCount; i++) {
final IAMENTRYTYPE xmlEntry = new IAMENTRYTYPE();
xmlMapping.entry.add(xmlEntry);
xmlEntry.key = IAMArrayFormat.ARRAY.format(mapping.key(i).toArray());
xmlEntry.value = IAMArrayFormat.ARRAY.format(mapping.value(i).toArray());
}
}
}
for (int index = 0; index < listingCount; index++) {
final IAMListing listing = source.listing(index);
final int itemCount = listing.itemCount();
if (itemCount != 0) {
final IAMLISTINGTYPE xmlListing = new IAMLISTINGTYPE();
xmlIndex.mappingOrListing.add(xmlListing);
xmlListing.index = Integer.toString(index);
for (int i = 0; i < itemCount; i++) {
final IAMITEMTYPE xmlItem = new IAMITEMTYPE();
xmlListing.item.add(xmlItem);
xmlItem.data = IAMArrayFormat.ARRAY.format(listing.item(i).toArray());
}
}
}
JAXB.marshal(xmlIndex, IO.outputWriterFrom(codec.getTargetData()));
} |
3986ceb8-4080-4447-8769-cf91c047e89e | 4 | public static void main(String[] args) {
try {
initParameters(args);
File file = new File(filePath);
Input input = InputReader.readInput(file);
List<Cluster> clusters = DBScan.run(input.getTimeSeries(), eps, minNrOfNeighbours);
runPlotPrintingThread(input, clusters);
runClusterPlotScriptBuilderThread(input, clusters);
runErrorbarsPrintingThread(input, clusters);
runClusterErrorbarsScriptBuilderThread(input, clusters);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (InputException e) {
System.out.println(e.getMessage());
} catch (InputMismatchException e) {
printHelpMessage();
} catch (ExecutionException e) {
printErrorMessage();
}
} |
98a2ee5b-8696-4df2-b8cf-4c73f320cb9b | 9 | public void update( final double ct ) {
// get the array of entities
final Entity[] entities = getEntities();
// update all entities
for( final Entity entity : entities ) {
entity.update( ct );
}
// check for collisions
for( final Entity entityA : entities ) {
for( final Entity entityB : entities ) {
if( ( entityA != entityB ) && entityA.isAlive() && entityB.isAlive() ) {
if( entityA.intersects( entityB ) ) {
// allow each entity to handle the collision
entityA.handleCollsion( entityB );
entityB.handleCollsion( entityA );
// did entity A die?
if( !entityA.isAlive() ) {
remove( entityA );
}
// did entity B die?
if( !entityB.isAlive() ) {
remove( entityB );
}
}
}
}
}
} |
88eedeee-b81f-43c1-925f-1e175c7cd2e0 | 1 | public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Ventana window = new Ventana();
window.frmClienteChat.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} |
06d2dcd0-b8ea-4c7d-af16-84970cdca8cc | 9 | private String prettyPrinterDados(List<Object> dados) {
int cont = 0;
StringBuilder pretty = new StringBuilder();
for (Object o : dados){
if (o instanceof EData1)
pretty.append((cont > 0) ? " e Temperatura" : "Temperatura");
else if (o instanceof EData2)
pretty.append((cont > 0) ? " e Hemoglobina" : "Hemoglobina");
else if (o instanceof EData3)
pretty.append((cont > 0) ? " e Bilirrubina" : "Bilirrubina");
else if (o instanceof EData4)
pretty.append((cont > 0) ? " e Pressao Arterial" : "Pressao Arterial");
cont++;
}
return pretty.toString();
} |
321abb5e-38a6-41a0-9602-4284c0b108d2 | 0 | private String classNameToZipEntryName(String className) {
return className.replace('.', '/')
+ ".class";
} |
7f8f63f8-568e-44c4-bf1b-0db32d8e9ed5 | 2 | public static void checkNotNull(Object o, Class<?> c) {
if (o == null) {
throw new PrecondictionException("");
}
} |
b1f8e8c4-bc25-4733-ba1c-d72931df702f | 4 | public void selectPreviousStream() {
int selectedRow = table.getSelectedRow();
int numberOfStreams = controlStreams.getStreamVector().size();
//no stream is selected
if(selectedRow == -1 && numberOfStreams > 0) {
selectedRow = numberOfStreams-1;
} else if (selectedRow >= (numberOfStreams-1)) {
selectedRow = numberOfStreams-1;
} else {
selectedRow--;
}
try {
table.getSelectionModel().setSelectionInterval(selectedRow, selectedRow);
} catch (IllegalArgumentException e) {
SRSOutput.getInstance().logE("Gui_TablePanel: Unable to select an row");
}
} |
b2d8d4bd-9e0e-4850-b5c8-3644477656b2 | 3 | public void setNumeroInt(TNumeroInt node)
{
if(this._numeroInt_ != null)
{
this._numeroInt_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._numeroInt_ = node;
} |
60dd738e-8da4-4700-9e32-e7facca613a8 | 0 | public String getRegion() {
return region;
} |
4361cc34-d374-436d-90c6-ce7db27930d7 | 4 | private static Token matchIdentifier(String word, int line, int position){
StringBuilder token = new StringBuilder();
int i=0;
for (; i<word.length(); i++){
char current = word.charAt(i);
if (!Character.isLetterOrDigit(current)){
break;
}
token.append(current);
}
if (i != 0) {
Keyword key = testForKeyword(token.toString());
if (key != null)
return new Token(key, line, position);
else
return new Token(TokenType.IDENTIFIER, token.toString(), line, position);
}
return null;
} |
08829e14-c740-4a14-af8a-5dd53d33433f | 0 | private void printScore() {
aiTimer.stop();
playerTimer = new Timer(SCORE_SHOW_DELAY, this); // TODO: 300
playerTimer.start();
ballMovement = false;
} |
2632192d-ef77-4dfb-b336-44050a1bda52 | 4 | public void run(){
try {
_serverSocket = new ServerSocket(_listenPort);
System.out.println("Listening...");
} catch (IOException e) {
System.out.println("Cannot listen on port " + _listenPort);
}
UserDatabase.getUsers();
Statistics statistics= Statistics.getStatisticsObject();
while (!_serverStop.getValue()){
try {
ConnectionHandler<T> newConnection = new ConnectionHandler<T>(_tokenizerFactory.create(), _serverSocket.accept(), _protocolFactory.create(), _serverStop, this);
_allConnections.add(newConnection);
new Thread(newConnection).start();
} catch (IOException e){
if (!_serverStop.getValue())
System.out.println("Failed to accept on port " + _listenPort);
else
System.out.println("Server recieved shutdown command");
}
}
statistics.shutDown();
} |
95e51e1c-fc5c-4f48-bb08-6cb70fe8b4c8 | 4 | private boolean checkForObjectRestore(int i, float days, String root) {
// float[][] data = new float[dbSet.length][];
float[][] data = DataUtil.restore2D(root + File.separator + "OBJECTS"
+ File.separator + "DATA_" + days);
if (data == null)
return false;
// float[][][] pdata = new float[dbSet.length][10][7];
float[][][] pdata = DataUtil.restore3D(root + File.separator
+ "OBJECTS" + File.separator + "TECHNICAL_" + days);
if (pdata == null)
return false;
// float[] weeksPrices = new float[dbSet.length];
float[] weeksPrices = DataUtil.restore1D(root + File.separator
+ "OBJECTS" + File.separator + "PRICES_" + days);
if (weeksPrices == null)
return false;
// float marketSum = sum(weeksPrices);
Float marketSum = DataUtil.restoreFloat(root + File.separator
+ "OBJECTS" + File.separator + "SUM_" + days);
if (marketSum == null)
return false;
// add data to fundamental series
DB_ARRAY.put(days, data);
// add data to technical series
DB_PRICES.put(days, pdata);
// add weeks prices to prices - actual prices of stocks for that
PRICES.put(days, weeksPrices);
// complete value of market each week
MARKET.put(days, marketSum);
return true;
} |
7b69c638-86c1-4c82-b5f7-320982ad6ea8 | 3 | @Override
public String toString() {
return "IkszorBinaryObject " +
"[encodedValue=" + IkszorManager.booleanArray2BinaryString(encodedValue) + "["+(encodedValue != null ? encodedValue.length : "null")+"]" +
", symmetricKey=" + IkszorManager.booleanArray2BinaryString(symmetricKey) + "["+(symmetricKey != null ? symmetricKey.length : "null")+"]" +
", decodedValue=" + IkszorManager.booleanArray2BinaryString(decodedValue) + "["+(decodedValue != null ? decodedValue.length : "null")+"]" +
", isEncoded=" + isEncoded +
", isDecoded=" + isDecoded + "]";
} |
638a724a-651c-4578-b41d-a767ba258ead | 5 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Port other = (Port) obj;
if (this.numberOfBerthes != other.numberOfBerthes) {
return false;
}
if (this.capacity != other.capacity) {
return false;
}
if (this.loading != other.loading) {
return false;
}
return true;
} |
e5240fee-674b-433b-9ca7-3f91d9a0ab02 | 2 | private List<Teleporter> getTeleportersOfGrid(Grid grid) {
final List<Teleporter> teleporters = new ArrayList<Teleporter>();
for (Element e : grid.getElementsOnGrid())
if (e instanceof Teleporter)
teleporters.add((Teleporter) e);
return teleporters;
} |
f309cbf6-d837-4f91-8969-94562f13de07 | 0 | public void setLine(int line) {this.line = line;} |
e208e42c-b513-4557-8e8b-31d8b2c56708 | 1 | public static void testFindFieldsbyXpath() throws Exception {
try{
getDriver().get("http://www.google.com/webhp?complete=1&hl=en");
// assertEquals("Google", getDriver().getTitle());
// Find the text input element by its Xpath
WebElement element = getDriver().findElement(By.xpath("//input[@class='gbqfif']"));
// Enter something to search for
element.sendKeys("Henry Chan");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the Url address
String actual="http://www.google.com/webhp?complete=1&hl=en#complete=1&hl=en&output=search&sclient=psy-ab&q=Henry+Chan&oq=&gs_l=&pbx=1&bav=on.2,or.r_qf.&bvm=bv.47883778,d.cGE&fp=d320cc8f6176a3c&biw=980&bih=602";
assertEquals(actual, getDriver().getCurrentUrl());
} catch (Exception e) {
// Take screenshots on error in jpg format
Common.TakesScreenshot(getDriver(),"Err_testFindFieldsbyXpath");
}
} |
3490c1b6-6c15-47c3-9131-66502ad2fc2b | 4 | @Override
public void setFloat(long i, float value)
{
if (value != 0.0 && value != 1.0) {
throw new IllegalArgumentException("The value has to be 0 or 1.");
}
if (ptr != 0) {
Utilities.UNSAFE.putByte(ptr + i, (byte) value);
} else {
if (isConstant()) {
throw new IllegalAccessError("Constant arrays cannot be modified.");
}
data[(int) i] = (byte) value;
}
} |
7ec1b24c-80d1-4bb8-b0c6-7fd70cf09946 | 2 | public void deductCost(Player player) {
for (int i = 0; i < costs.size(); i++) {
Item item = costs.get(i);
if (item instanceof ResourceItem) {
ResourceItem ri = (ResourceItem) item;
player.inventory.removeResource(ri.resource, ri.count);
}
}
} |
f5e04885-2a82-42a0-becc-abee74f1840d | 6 | public void update() {
player.update();
player.checkAttack(enemies);
player.checkCoins(coins);
finish.update();
finish.checkGrab(player);
bg.setPosition(tileMap.getx(), tileMap.gety());
if(player.isDead()){
player.setPosition(100, 400);
player.revive();
player.reset();
restart();
}
tileMap.setPosition(
GamePanel.WIDTH / 2 - player.getx(),
GamePanel.HEIGHT / 2 - player.gety());
for(int i = 0; i < enemies.size(); i++){
Enemy e = enemies.get(i);
e.update();
if(player.isDrunk()){
e.kill();
}
if(e.isDead()){
enemies.remove(i);
e.addScore(Level2State.score);
i--;
}
}
for(int i = 0; i < coins.size(); i++){
Coin c = coins.get(i);
c.update();
if(c.shouldRemove()){
c.addScore();
coins.remove(i);
i--;
}
}
bg.setPosition(tileMap.getx(), tileMap.gety());
} |
aea40c9a-2197-4df8-94ac-6f4aabeb3bca | 9 | public static Map<String, String> simpleCommandLineParser(String[] args) {
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i <= args.length; i++) {
String key = (i > 0 ? args[i - 1] : null);
String value = (i < args.length ? args[i] : null);
if (key == null || key.startsWith("-")) {
if (value != null && value.startsWith("-"))
value = null;
if (key != null || value != null)
map.put(key, value);
}
}
return map;
} |
72947150-3a0f-4b7b-87e3-c5e123e8627a | 8 | public void connect() {
// STEP 1 - CONNECT ALL UNCONNECTED
// NEIGHBOURS------------------------------------------------
// picks random room based on index from 0 to times*times(nb. of rooms)
Random rand = new Random();
int currentRoom = rand.nextInt(roomBase * roomBase);
// the starting room for the player
setStartRoom(currentRoom);
rooms.get(currentRoom).setConnected(true);
boolean found = false;
int index = 0;
boolean allC = checkConnected(rooms);
// find and check the room's neighbours
ArrayList<Room> neighbours = findNs(currentRoom); // could just store ID
// less memory -
// search needed,
// lazy and not much
// difference
boolean nC = checkConnected(neighbours);
// while there are unconnected neighbours
while (!nC) {
System.out.println("Current room: " + currentRoom);
index = 0;
// while no unconnected neighbour at index
while (found == false) {
// pick random neighbour
index = rand.nextInt(neighbours.size());
if (!neighbours.get(index).isConnected()) {
System.out.println("Neighbor to connect: "
+ neighbours.get(index).getID());
found = true;
}
}
System.out.println("\n" + nC);
rooms.get(currentRoom).addConnection(neighbours.get(index)); // connect
// the
// random
// unconnected
// neighbor
// to
// this
// room
currentRoom = neighbours.get(index).getID();
rooms.get(currentRoom).setConnected(true);
found = false;
neighbours = findNs(currentRoom);
nC = checkConnected(neighbours);
}
System.out
.println("\n" + nC + " - all unconnected neighbors connected");
// STEP 1
// FINISHED--------------------------------------------------------------------------------
// STEP 2 CONNECT ALL UNCONNECTED ROOMS TO A RANDOM CONNECTED
// NEIGHBOUR---------------------------
// reset for second search
found = false;
index = 0;
allC = checkConnected(rooms);
while (!allC) {
// find a random unconnected room
do {
// System.out.println("Checking for unconnected room");
currentRoom = rand.nextInt(rooms.size());
} while (rooms.get(currentRoom).isConnected() == true
|| hasConnectedNs(findNs(currentRoom)) == false);
// and find its neighbours
neighbours = findNs(currentRoom);
System.out.println("Current room: " + currentRoom);
index = 0;
// FIXME Perhaps is possible for no neighbours to be connected -
// method that checks this and keeps cycling to others if false
// FIXED! added check for connected neighbours, else it got stuck on
// trying to find a connected neighbour when there was none, very
// rare but annoying as hell
// keep searching for a connected neighbour
while (found == false) {
index = rand.nextInt(neighbours.size());
// System.out.println("We are stuck");
System.out.println(index);
if (neighbours.get(index).isConnected()) {
System.out.println("Neighbor to connect: "
+ neighbours.get(index).getID());
found = true;
}
}
rooms.get(currentRoom).addConnection(rooms.get(index)); // connect
// the
// random
// connected
// neighbor
// to this
// room
rooms.get(currentRoom).setConnected(true);
found = false;
allC = checkConnected(rooms);
System.out.println("\n" + allC);
}
endRoom = currentRoom;
System.out.println("\n" + allC + " - all rooms connected");
} |
75253238-2c1e-4c54-a356-46433c9c5cd9 | 7 | @Override
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "This command is not supported from console.");
return true;
}
if (!sender.hasPermission("timebasic.adweather") && (!sender.isOp())) {
sender.sendMessage(ChatColor.RED + "You don't have permission to use this command.");
return true;
}
Player p = (Player) sender;
if (args.length == 0) {
p.sendMessage("---------------- " + ChatColor.GOLD + "Admin Weather Menu " + ChatColor.WHITE + "----------------");
p.sendMessage(ChatColor.GOLD + "/" + ChatColor.GREEN + "adweather clear " + ChatColor.GRAY + " - set the weather to clear in your world.");
p.sendMessage(ChatColor.GOLD + "/" + ChatColor.GREEN + "adweather downfall " + ChatColor.GRAY + " - set the weather to downfall in your world.");
return true;
} else if (args.length == 1) {
switch (args[0].toLowerCase()) {
case "clear":
p.setPlayerWeather(WeatherType.CLEAR);
p.sendMessage(ChatColor.GOLD + "Weather was set to clear in your world.");
break;
case "downfall":
p.setPlayerWeather(WeatherType.DOWNFALL);
p.sendMessage(ChatColor.GOLD + "Weather was set to downfall in your world.");
break;
default:
p.sendMessage(ChatColor.RED + "Unknown argument, sending you to the menu.");
p.performCommand("weather");
break;
}
return true;
} else {
p.sendMessage(ChatColor.RED + "Unknown argument, sending you to the menu.");
p.performCommand("weather");
return true;
}
} |
4fc85d32-4caf-4d38-9f50-1d1b48ac14fb | 9 | public String arabToRome(int arabNum, int digits){
String romeNum = "";
String[] digits1 = new String[]{"I","X","C","M"};
String[] digits2 = new String[]{"II","XX","CC","MM"};
String[] digits3 = new String[]{"III","XXX","CCC","MMM"};
String[] digits4 = new String[]{"IV","XL","CD"};
String[] digits5 = new String[]{"V","L","D"};
String[] digits6 = new String[]{"VI","LX","DC"};
String[] digits7 = new String[]{"VII","LXX","DCC"};
String[] digits8 = new String[]{"VIII","LXXX","DCCC"};
String[] digits9 = new String[]{"IX","XC","CM"};
if (arabNum == 1){romeNum = digits1[digits];
}else if (arabNum == 2){romeNum = digits2[digits-1];
}else if (arabNum == 3){romeNum = digits3[digits-1];
}else if (arabNum == 4){romeNum = digits4[digits-1];
}else if (arabNum == 5){romeNum = digits5[digits-1];
}else if (arabNum == 6){romeNum = digits6[digits-1];
}else if (arabNum == 7){romeNum = digits7[digits-1];
}else if (arabNum == 8){romeNum = digits8[digits-1];
}else if (arabNum == 9){romeNum = digits9[digits-1];
}
return romeNum;
} |
2d201255-7a22-4515-90c7-34bf2c8a1ee3 | 7 | public void affichePacman(Graphics pacman, GestionGraphismes g)
{
String img = "pacman_"+mvmt;
if (ferme > 15)
img = img+"_ferme";
if (invincible && (timer > 100 || timer%10<5))
img = img+"_invincible";
if (!invisible || (invisible && timer % 15 < 10))
pacman.drawImage(g.getPacman(img), positionX, positionY);
} |
f1c9fd84-f6a1-49e9-b81e-f44ef4f16fe8 | 7 | public static void UpdateImportFile(String profile, String genername, String importfile)
{
File file = new File(profile);
if (file.exists())
{
try
{
// Create a factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Use the factory to create a builder
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);
doc.normalize();
NodeList nodelist = doc.getElementsByTagName(GENERATOR);
if (nodelist.getLength() != 0)
{
Element elem;
for (int i = 0; i < nodelist.getLength(); i++)
{
elem = (Element)nodelist.item(i);
//find the generator
if (elem.getAttribute("name").equals(genername))
{
//find import file node
nodelist = elem.getElementsByTagName(IMPORTFILE);
if (nodelist.getLength() == 1)
{
elem = (Element)nodelist.item(0);
if (elem.getFirstChild() != null)
elem.getFirstChild().setNodeValue(importfile);
doc2XmlFile(doc, profile);
}
}
}
}
}
catch (Exception e)
{
System.out.println(e.toString());
e.getStackTrace();
}
}
} |
155511c8-c93b-4d3a-967d-a39e162289dc | 3 | public void handle(Packet packet) {
if (packet instanceof ConnectPacket) {
// do nothing, already handled elsewhere
} else if (packet instanceof ShootPacket) {
shoot();
} else if (packet instanceof AdjustShooterAnglePacket) {
System.out.println("recv");
double angle = ((AdjustShooterAnglePacket)packet).angle;
setShooterAngle(angle);
PlayerAdjustShooterAnglePacket broadcastPacket = new PlayerAdjustShooterAnglePacket();
broadcastPacket.name = getName();
broadcastPacket.angle = angle;
game.broadcast(broadcastPacket);
} else {
System.out.println("[Server] Unknown packet class: " + packet.getClass().getSimpleName());
}
} |
720e174e-cff2-489b-b3c3-779659ccebfe | 0 | public boolean hasMatchedWord(String wordnum) {
return dictionary.containsKey(wordnum);
} |
4fcac1fa-f76d-4b91-9158-7fda6b50007e | 3 | @Override
public String execute() throws Exception {
try {
Map session = ActionContext.getContext().getSession();
Campaign camp = (Campaign) session.get("campa");
CampaignDevice campdev = new CampaignDevice(camp, getPlatform());
getMyDao().getDbsession().save(campdev);
CampaignLocation camploc = new CampaignLocation(camp, getLocation());
getMyDao().getDbsession().save(camploc);
CampaignOs campos = new CampaignOs(camp, getIphone());
getMyDao().getDbsession().save(campos);
CampaignDemography campdemo = new CampaignDemography();
campdemo.setCampaign(camp);
campdemo.setSex(gender);
campdemo.setAge(getAge());
getMyDao().getDbsession().save(campdemo);
return "success";
} catch (HibernateException e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
} catch (NullPointerException ne) {
addActionError("Server Error Please Recheck All Fields ");
ne.printStackTrace();
return "error";
} catch (Exception e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
}
} |
cb1180df-e221-4f2d-a31c-15777a39c16e | 9 | @Override
public String toString() {
if (type == NUM) {
return "NUM: " + value;
} else if (type == CMD) {
return "CMD: " + name;
} else if (type == UNK) {
return "UNK";
} else if (type == EOF) {
return "EOF";
} else if (type == NAME) {
return "NAME: " + name;
} else if (type == CMD) {
return "CMD: " + name;
} else if (type == STR) {
return "STR: (" + name;
} else if (type == ARYB) {
return "ARY [";
} else if (type == ARYE) {
return "ARY ]";
} else {
return "some kind of brace (" + type + ")";
}
} |
8f539d96-2eae-47f2-9fd6-d987d58dfa7d | 5 | @Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
Player p = Bukkit.getPlayer(sender.getName());
if(cmd.getName().equalsIgnoreCase("hub")){
Bukkit.dispatchCommand(p, "warp hub");
return true;
}
if(cmd.getName().equalsIgnoreCase("kits")){
KitPvP.kit(p, args);
return true;
}
if(cmd.getName().equalsIgnoreCase("rank")){
if(!p.getName().equals("Freelix2000")){
p.sendMessage(ChatColor.RED + "Only Freelix2000 can use this command.");
return true;
}
if(args.length < 2){
p.sendMessage(ChatColor.RED + "Too few arguments.");
p.sendMessage(ChatColor.RED + "/rank <player> <group>");
return true;
}
Bukkit.dispatchCommand(p, "manuadd " + args[0] + " " + args[1] + " kitpvp");
Bukkit.dispatchCommand(p, "manuadd " + args[0] + " " + args[1] + " freebuild");
Bukkit.dispatchCommand(p, "manuadd " + args[0] + " " + args[1] + " Survival");
Bukkit.dispatchCommand(p, "manuadd " + args[0] + " " + args[1] + " skyworld");
Bukkit.dispatchCommand(p, "manuadd " + args[0] + " " + args[1] + " world");
p.sendMessage(ChatColor.GOLD + "Promoted " + ChatColor.YELLOW + args[0] + ChatColor.GOLD + " to " + ChatColor.YELLOW + args[1] + ChatColor.GOLD + " in all worlds.");
return true;
}
return false;
} |
6d6d6161-51df-483c-ae93-d93b0cc35bcb | 9 | public void mouseInput(){
int mouseX = Mouse.getX();
int mouseY = Mouse.getY();
if (!justRequested){
distributePoints(mouseX, mouseY);
justRequested = true;
}
for (int x = 0; x < windowslist.size(); x ++){
if (windowslist.get(x).recieveMouseEvent(mouseX, mouseY)){
break;
}
}
panesselector.recieveInput(mouseX, mouseY);
activePane.__recieveMouseEvent(mouseX, mouseY);
if (!Mouse.isButtonDown(0) && justRequested){
justRequested = false;
}
if (Mouse.isButtonDown(0) && activePane.doesAllowMapInteraction() && !gotWorldInput){
worldInput(mouseX, mouseY);
gotWorldInput = true;
}
ticksPassed++;
if (ticksPassed > 20){
gotWorldInput = false;
ticksPassed = 0;
}
} |
e7cb73c5-7694-4efc-b417-f66b7d32bf78 | 9 | public final LogoParser.sum_return sum() throws RecognitionException {
LogoParser.sum_return retval = new LogoParser.sum_return();
retval.start = input.LT(1);
Object root_0 = null;
Token PLUS43=null;
Token MINUS44=null;
LogoParser.mult_return o1 =null;
LogoParser.mult_return o2 =null;
Object PLUS43_tree=null;
Object MINUS44_tree=null;
try {
// /home/carlos/Proyectos/logojava/Logo.g:114:2: (o1= mult ( PLUS o2= mult | MINUS o2= mult )* )
// /home/carlos/Proyectos/logojava/Logo.g:114:4: o1= mult ( PLUS o2= mult | MINUS o2= mult )*
{
root_0 = (Object)adaptor.nil();
AdditiveOperation operation = new AdditiveOperation();
pushFollow(FOLLOW_mult_in_sum654);
o1=mult();
state._fsp--;
adaptor.addChild(root_0, o1.getTree());
operation.sum((o1!=null?o1.value:null));
// /home/carlos/Proyectos/logojava/Logo.g:116:3: ( PLUS o2= mult | MINUS o2= mult )*
loop15:
do {
int alt15=3;
int LA15_0 = input.LA(1);
if ( (LA15_0==PLUS) ) {
alt15=1;
}
else if ( (LA15_0==MINUS) ) {
alt15=2;
}
switch (alt15) {
case 1 :
// /home/carlos/Proyectos/logojava/Logo.g:117:5: PLUS o2= mult
{
PLUS43=(Token)match(input,PLUS,FOLLOW_PLUS_in_sum669);
PLUS43_tree =
(Object)adaptor.create(PLUS43)
;
adaptor.addChild(root_0, PLUS43_tree);
pushFollow(FOLLOW_mult_in_sum673);
o2=mult();
state._fsp--;
adaptor.addChild(root_0, o2.getTree());
operation.sum((o2!=null?o2.value:null));
}
break;
case 2 :
// /home/carlos/Proyectos/logojava/Logo.g:118:5: MINUS o2= mult
{
MINUS44=(Token)match(input,MINUS,FOLLOW_MINUS_in_sum684);
MINUS44_tree =
(Object)adaptor.create(MINUS44)
;
adaptor.addChild(root_0, MINUS44_tree);
pushFollow(FOLLOW_mult_in_sum688);
o2=mult();
state._fsp--;
adaptor.addChild(root_0, o2.getTree());
operation.sub((o2!=null?o2.value:null));
}
break;
default :
break loop15;
}
} while (true);
retval.value = operation;
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
} |
519f35f7-78d5-425a-919f-d18d4b8ca6cc | 3 | public InstructionStack(final MethodEditor method) {
this.method = method;
this.stacks = new HashMap();
this.preexists = new HashMap();
// Initially only the parameters to the method prexist
final Type[] paramTypes = method.paramTypes();
this.currPreexists = new HashMap();
for (int i = 0; i < paramTypes.length; i++) {
// We only care about the preexistence of objects (not arrays)
if ((paramTypes[i] != null) && paramTypes[i].isObject()) {
this.currPreexists.put(method.paramAt(i), new HashSet());
}
}
} |
ee97bceb-708c-4b87-9da3-19f170a35b55 | 2 | private boolean canNotPassWall(double x, double dx, double y, double dy){
for (Wall wall: walls){
if (wall.crossedWall(x, dx, y, dy)){
return true;
}
}
return false;
} |
a9e8c635-af43-4a7d-8370-42900bf53215 | 7 | protected String startSetToString() {
StringBuffer FString = new StringBuffer();
boolean didPrint;
if (m_starting == null) {
return getStartSet();
}
for (int i = 0; i < m_starting.length; i++) {
didPrint = false;
if ((m_hasClass == false) ||
(m_hasClass == true && i != m_classIndex)) {
FString.append((m_starting[i] + 1));
didPrint = true;
}
if (i == (m_starting.length - 1)) {
FString.append("");
}
else {
if (didPrint) {
FString.append(",");
}
}
}
return FString.toString();
} |
3732f1b7-08fc-4f2a-a979-087751ea4d38 | 0 | @Override
public void deconnecter() throws SQLException {
getConnexion().close();
} |
5edf8583-95ce-4cf6-bf68-78bd04fe68d8 | 1 | public boolean estTerminee(){
if(this.etat == TERMINEE){
return true ;
}
else {
return false ;
}
} |
28059ed6-5e44-4774-a725-a779bfb2be48 | 6 | public void run(){
try {
while(true){
Thread.sleep(MS_PER_SHRINK); // milliseconds
synchronized(vTrapped){
for(SpaceObject uObj : vTrapped){
if(uObj.getRad() > 0){
double x = uObj.getCenterX();
double y = uObj.getCenterY();
uObj.setRad(uObj.getRad() - 1); //decrease radius
uObj.setCenterX(x); //ensure the center stays the same
uObj.setCenterY(y);
uObj.setCenterX(0.1*(this.getCenterX() - uObj.getCenterX()) + uObj.getCenterX());//move towards the center of the black hole
uObj.setCenterY(0.1*(this.getCenterY() - uObj.getCenterY()) + uObj.getCenterY());
}
else if(uObj instanceof Player){
vTrapped.remove(uObj);
//This is a while loop to ensure the player is not generated over the black hole
//which would cause points to be subtracted more than once
uObj.setRad(Player.RAD); //reset the radius of the player
uObj.setVelX(0); //make sure the velocity is zero
uObj.setVelY(0);
while(SpaceObjectManager.collision(uObj, this)) { //if randomly generated over the black hole, try again
uObj.setCenterX(GameUI.randInt(uObj.getRad(), uPanel.getWidth()-uObj.getRad()));
uObj.setCenterY(GameUI.randInt(uObj.getRad(), uPanel.getHeight()-uObj.getRad()));
}
vObjs.add(uObj); //add the player back into the vector of objects
break;
}
else{
vTrapped.remove(uObj);
uPanel.remove(uObj);
break;
}
}
}
}
} catch (InterruptedException ex) {
System.out.print(ex.getMessage());
}
} |
d26fe3b0-189f-4f69-a4c3-54c389bca185 | 5 | private void merge(int[] left, int[] right)
{
int leftIndex = 0; // current left index
int rightIndex = 0; // current right index
int i = 0; // current index in a
// merge the left and right arrays into a
while (leftIndex < left.length &&
rightIndex < right.length)
{
if (left[leftIndex] < right[rightIndex])
{
a[i] = left[leftIndex];
leftIndex++;
}
else
{
a[i] = right[rightIndex];
rightIndex++;
}
i++;
}
// copy any remaining in left
for (int j = leftIndex; j < left.length; j++)
{
a[i] = left[j];
i++;
}
// copy any remaining in right
for (int j = rightIndex; j < right.length; j++)
{
a[i] = right[j];
i++;
}
} |
081bfdd0-3221-4cf9-b2d5-4ecf01b6f1bd | 4 | public HashMap<String, Integer> calculateDocumentOccuriences(
List<String> unique, List<List<String>> documents)
throws InvalidFormatException, IOException {
HashMap<String, Integer> map = new HashMap<>();
for (String uniqueToken : unique) {
map.put(uniqueToken, 0);
for (List<String> list : documents) {
primaryLoop: for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(uniqueToken)) {
int occ = map.get(uniqueToken);
occ++;
map.put(uniqueToken, occ); //
break primaryLoop;
}
}
}
}
return map;
} |
38bd48a7-5cfd-46ab-a902-9ba01bc8bcff | 2 | @Override
public void doLoopAction()
{
if (hit)
{
doHit();
}
if (changeAni)
{
setAnimation();
changeAni = false;
}
} |
1b354845-e140-4b1a-b485-965ca909a939 | 6 | public void act(){
//if it gone past the start menu
if (start){
MouseInfo mouse = Greenfoot.getMouseInfo();
uiAct();
s.run();
//if the level started, increase the time and prepare the spawn
if (levelStart){
prepareSpawn();
time++;
}
/**Terence's Stuff**/
checkInput(mouse);
if (mouse != null){
trackButtons(mouse);
if (place) // used to place tower when onto the field
trackMouse(mouse);
}
}
else if (init){
initCounter++;
intalize();
loadScreen.update();
}
else{
//if the user presses a when they are on the start screen, start the actual game
//temp fix, add buttons later
if (startScreen.gameStart()){
removeObjects (getObjects (SSButtons.class));
removeObject (startScreen);
loadScreen = new LoadScreen(6);
addObject (loadScreen, 512, 384);
init = true;
}
}
} |
dea4dd2f-9674-480e-a878-40faef8d104a | 7 | private void tryMove() {
for(BB bb : level.collidables) {
if(bb.intersects(this.x + this.xa, this.y, width, height)) {
if(this.xa > 0) {
this.x = bb.getX() - width;
} else if(this.xa < 0) {
this.x = bb.getX() + bb.getWidth();
}
this.xa = -xa;
}
if(bb.intersects(this.x, this.y + this.ya, width, height)) {
if(this.ya > 0) {
this.y = bb.getY() - height;
} else if(this.ya < 0) {
this.y = bb.getY() + bb.getHeight() + 1;
}
this.ya = -ya;
}
}
this.x += this.xa;
this.y += this.ya;
} |
54058910-5800-401c-974c-1ae4aade0c74 | 5 | public synchronized byte[] sendMutualAuth(byte[] rndIFD, byte[] rndICC,
byte[] kIFD, SecretKey kEnc, SecretKey kMac)
throws CardServiceException {
try {
ResponseAPDU rapdu = transmit(createMutualAuthAPDU(rndIFD, rndICC,
kIFD, kEnc, kMac));
byte[] rapduBytes = rapdu.getBytes();
if (rapduBytes == null) {
throw new CardServiceException("Mutual authentication failed");
}
String errorCode = Hex.shortToHexString((short) rapdu.getSW());
if (rapduBytes.length == 2) {
throw new CardServiceException(
"Mutual authentication failed: error code: "
+ errorCode);
}
if (rapduBytes.length != 42) {
throw new CardServiceException(
"Mutual authentication failed: expected length: 42, actual length: "
+ rapduBytes.length + ", error code: "
+ errorCode);
}
/* Decrypt the response. */
cipher.init(Cipher.DECRYPT_MODE, kEnc, ZERO_IV_PARAM_SPEC);
byte[] result = cipher.doFinal(rapduBytes, 0,
rapduBytes.length - 8 - 2);
if (result.length != 32) {
throw new IllegalStateException("Cryptogram wrong length "
+ result.length);
}
return result;
} catch (GeneralSecurityException gse) {
throw new CardServiceException(gse.toString());
}
} |
d8a5f60a-489a-4a73-97ae-13fd27fb9288 | 3 | @Override
public void updateUser(UserDTO user) throws SQLException {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.update(user);
session.getTransaction().commit();
}
catch (Exception e) {
System.err.println("Error while adding an user!");
}
finally {
if (session != null && session.isOpen())
session.close();
}
} |
b03350f8-e7a0-4cac-8c57-a256e50ab61d | 8 | static String makeRgbaData(int width, int height, int bpp, boolean has_alpha) {
final int CHECK_SIZE = 20;
assert (bpp == 4);
assert (has_alpha);
int rowstride = width * bpp;
char[] pixels = new char[height * rowstride];
for (int y = 0; y < height; y++) {
int i = 0;
for (int x = 0; x < width; x++) {
pixels[0 + y * rowstride + x * bpp] = pixels[1 + y * rowstride
+ x * bpp] = pixels[2 + y * rowstride + x * bpp] = 0;
pixels[3 + y * rowstride + x * bpp] = 0xff;
// TODO
if ((x % 2 == 1) && (y % 2 == 1) && (y % CHECK_SIZE == 1)
&& (x % CHECK_SIZE == 1)) {
if (x % CHECK_SIZE == 1) {
if (++i > 3)
i = 0;
}
pixels[i + y * rowstride + x * bpp] = 0xff;
}
}
}
return new String(pixels);
} |
02066883-0ffc-46af-b9ea-fcce2c848e79 | 2 | public double variance_of_ComplexRealParts() {
boolean hold = Stat.nFactorOptionS;
if (nFactorReset) {
if (nFactorOptionI) {
Stat.nFactorOptionS = true;
} else {
Stat.nFactorOptionS = false;
}
}
double[] re = this.array_as_real_part_of_Complex();
double variance = Stat.variance(re);
Stat.nFactorOptionS = hold;
return variance;
} |
433ebd91-40a0-48f2-a699-f164d87ca9aa | 8 | public void unDeplacement(){
this.flackBoy.avancer();
/*System.out.println("ANGLE = "+this.flackBoy.getTrajectoire().angleActuelle());
System.out.println("VITESSE = "+this.flackBoy.getTrajectoire().vitesseActuelle());
System.out.println("X = "+this.flackBoy.getX());
System.out.println("Y = "+this.flackBoy.getY());*/
// TODO : replacement de FB sur le terrain
/*if (this.flackBoy.getX()<5) {
this.flackBoy.setX(2);
} else if(this.flackBoy.getX()+this.flackBoy.getLargeur()>this.dimensionTerrain.getLargeur()){
this.flackBoy.setX(this.dimensionTerrain.getLargeur()-2);
}
if (this.flackBoy.getY()<5+32) {
this.flackBoy.setY(2+32);
} else if(this.flackBoy.getY()+this.flackBoy.getHauteur()>this.dimensionTerrain.getHauteur()){
this.flackBoy.setY(this.dimensionTerrain.getHauteur()-2-32);
}*/
// test avec la liste les armes
/*for (int j=0 ; j<this.listeArmes.size();j++) {
if (this.listeArmes.get(j).utilisable()) {
if (this.listeArmes.get(j).enCollision(this.flackBoy)) {
System.out.println("\nARME : BOUM !");
System.out.println("ANGLE ARME = "+this.flackBoy.getTrajectoire().angleActuelle());
System.out.println("VITESSE ARME = "+this.flackBoy.getTrajectoire().vitesseActuelle());
System.out.println("X ARME = "+this.flackBoy.getX());
System.out.println("Y ARME = "+this.flackBoy.getY());
this.listeArmes.get(j).collision(this.flackBoy, this.listeArmes.get(j).getBord());
}
else {
if(this.listeArmes.get(j) instanceof ArmeDeclenchable){
ArmeDeclenchable armeD=(ArmeDeclenchable)this.listeArmes.get(j);
if(armeD.sousPortee(this.flackBoy)){
System.out.println("\n$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
armeD.grossirForme();
}
}
}
}
}*/
for (int j=0 ; j<this.listeArmes.size();j++) {
if (this.listeArmes.get(j).utilisable()) {
if(this.listeArmes.get(j) instanceof ArmeDeclenchable){
ArmeDeclenchable armeD=(ArmeDeclenchable)this.listeArmes.get(j);
if(armeD.sousPortee(this.flackBoy)){
armeD.grossirForme();
if(armeD.enCollision(this.flackBoy)){
armeD.collision(this.flackBoy, armeD.getBord());
armeD.utiliser();
}
}
else{
armeD.degrossirForme();
}
}
else{
if (this.listeArmes.get(j).enCollision(this.flackBoy)) {
System.out.println("\nARME : BOUM !");
System.out.println("ANGLE ARME = "+this.flackBoy.getTrajectoire().angleActuelle());
System.out.println("VITESSE ARME = "+this.flackBoy.getTrajectoire().vitesseActuelle());
System.out.println("X ARME = "+this.flackBoy.getX());
System.out.println("Y ARME = "+this.flackBoy.getY());
this.listeArmes.get(j).collision(this.flackBoy, this.listeArmes.get(j).getBord());
this.listeArmes.get(j).utiliser();
}
}
}
else{
this.listeArmes.remove(this.listeArmes.get(j));
}
}
// test avec la liste des murs
for (int i=0 ; i<this.limites.size();i++) {
if (this.limites.get(i).enCollision(this.flackBoy)) {
System.out.println("\nMUR : BOUM !");
System.out.println("ANGLE = "+this.flackBoy.getTrajectoire().angleActuelle());
System.out.println("VITESSE = "+this.flackBoy.getTrajectoire().vitesseActuelle());
System.out.println("X = "+this.flackBoy.getX());
System.out.println("Y = "+this.flackBoy.getY());
this.limites.get(i).collision(this.flackBoy, this.limites.get(i).getBord());
}
}
} |
68ce765e-8116-465e-853f-ee4763516a91 | 9 | public int getStringWidth(String par1Str)
{
if (par1Str == null)
{
return 0;
}
int i = 0;
boolean flag = false;
for (int j = 0; j < par1Str.length(); j++)
{
char c = par1Str.charAt(j);
int k = getCharWidth(c);
if (k < 0 && j < par1Str.length() - 1)
{
char c1 = par1Str.charAt(++j);
if (c1 == 'l' || c1 == 'L')
{
flag = true;
}
else if (c1 == 'r' || c1 == 'R')
{
flag = false;
}
k = getCharWidth(c1);
}
i += k;
if (flag)
{
i++;
}
}
return i;
} |
c051cf0c-e958-481e-bc35-37defedf6dd2 | 9 | public static void main(String[] args) {
Scanner tecla=new Scanner(System.in);
String opcion=" ";
System.out.println("ELECCIONES");
do{
System.out.println("Elige una opcion (a-e), o teclea 'X' para terminar:");
opcion=tecla.next();
switch (opcion){
case "a":
String nombre=" ";
String apellido1=" ";
String apellido2=" ";
String dni=" ";
int edad=0;
boolean mayor=false;
String genero=" ";
String direccion=" ";
long fijo=0;
long movil=0;
System.out.println("DATOS DEL HABITANTE");
System.out.println(" ");
System.out.println("Ingresa tus datos");
System.out.print("Nombre: ");
nombre=tecla.next();
System.out.print("Primer apellido: ");
apellido1=tecla.next();
System.out.print("Segundo apellido: ");
apellido2=tecla.next();
System.out.print("DNI: ");
dni=tecla.next();
System.out.print("Edad: ");
edad=tecla.nextInt();
System.out.print("Genero: ");
genero=tecla.next();
System.out.print("Direccion: ");
direccion=tecla.next();
System.out.print("Telefono fijo: ");
fijo=tecla.nextLong();
System.out.print("Telefono movil: ");
movil=tecla.nextLong();
Habitante h1=new Habitante();
h1.setNombre(nombre);
h1.setApellido1(apellido1);
h1.setApellido2(apellido2);
h1.setDni(dni);
h1.setEdad(edad);
h1.setSexo(genero);
h1.setDireccion(direccion);
h1.setFijo(fijo);
h1.setMovil(movil);
System.out.println("Datos introducidos del habitante");
System.out.println("Nombre: "+h1.getNombre());
System.out.println("Apellido 1: "+h1.getApellido1());
System.out.println("Apellido 2: "+h1.getApellido2());
System.out.println("DNI: "+h1.getDni());
System.out.println("Edad: "+h1.getEdad());
if (h1.getMayor()){
System.out.println("El habitante es mayor de edad. ");
}else{
System.out.println("El habitante es menor.");
}
System.out.println("Genero: "+h1.getSexo());
System.out.println("Direccion: "+h1.getDireccion());
System.out.println("Fijo: "+h1.getFijo());
System.out.println("Movil: "+h1.getMovil());
break;
case "b":
System.out.println("Ayuntamiento");
String pueblo=" ";
String tipo=" ";
int habitatantes=0;
int votantes=0;
double area=0;
String alcalde=" ";
int codPost=0;
String provincia=" ";
System.out.println("DATOS DEL AYUNTAMIENTO");
System.out.println(" ");
System.out.println("Ingresa los datos");
System.out.print("Pueblo: ");
pueblo=tecla.next();
System.out.print("Tipo de localidad( ciudad, villa, etc): ");
tipo=tecla.next();
System.out.print("Numero de habitatantes: ");
habitatantes=tecla.nextInt();
System.out.print("Numero de votantes: ");
votantes=tecla.nextInt();
System.out.print("Extension en km2: ");
area=tecla.nextDouble();
System.out.print("Nombre del alcalde: ");
alcalde=tecla.next();
System.out.print("Codigo Postal: ");
codPost=tecla.nextInt();
System.out.print("Provincia: ");
provincia=tecla.next();
Ayuntamiento a1=new Ayuntamiento();
a1.setNombre(pueblo);
a1.setTipo(tipo);
a1.setPopulacion(habitatantes);
a1.setCenso(votantes);
a1.setExtension(area);
a1.setAlcalde(alcalde);
a1.setCp(codPost);
a1.setProvincia(provincia);
System.out.println("Datos del ayuntamiento");
System.out.println("Pueblo: "+a1.getNombre());
System.out.println("Tipo de pueblo: "+a1.getTipo());
System.out.println("Habitantes: "+a1.getPopulacion());
System.out.println("Censo: "+a1.getCenso());
System.out.println("Area: "+a1.getExtension());
System.out.println("Alcalde: "+a1.getAlcalde());
System.out.println("Codigo Postal: "+a1.getCp());
System.out.println("Provincia: "+a1.getProvincia());
break;
case "c":
System.out.println("Partido");
/*atributos
private String nombre;
private String siglas;
private String ideologia;
private int miembros;
private String candidato;*/
String nomPartido=" ";
String siglas=" ";
String idea=" ";
int miembros=0;
String candidato=" ";
System.out.println("DATOS DEL PARTIDO");
System.out.println(" ");
System.out.println("Ingresa los datos");
System.out.print("Nombre del partido: ");
nomPartido=tecla.next();
System.out.print("Siglas: ");
siglas=tecla.next();
System.out.print("Ideologia: ");
idea=tecla.next();
System.out.print("Numero de afiliados: ");
miembros=tecla.nextInt();
System.out.print("Nombre del candidato: ");
candidato=tecla.next();
Partido p1=new Partido();
p1.setNombre(nomPartido);
p1.setSiglas(siglas);
p1.setIdeologia(idea);
p1.setMiembros(miembros);
p1.setCandidato(candidato);
System.out.println("Datos introducidos del partido");
System.out.println("Partido: "+p1.getNombre());
System.out.println("Siglas: "+p1.getSiglas());
System.out.println("Ideologia: "+p1.getIdeologia());
System.out.println("Numero de afiliados: "+p1.getMiembros());
System.out.println("Candidato: "+p1.getCandidato());
break;
case "d":
System.out.println("Inmueble");
/*
private String pueblo;
private String calle;
private int numPortal;
private int piso;
private String puerta;
private boolean habitable;
private String tipoLocal;
private double metros;
*/
String nomPueblo=" ";
String calle=" ";
int portal=0;
int piso=0;
String puerta=" ";
String habitable=" ";
String tipoLocal=" ";
double metros2=0;
System.out.println("DATOS DEL INMUEBLE");
System.out.println(" ");
System.out.println("Ingresa los datos");
System.out.print("Pueblo: ");
nomPueblo=tecla.next();
System.out.print("Calle o Barrio: ");
calle=tecla.next();
System.out.print("Nº de portal: ");
portal=tecla.nextInt();
System.out.print("Piso: ");
piso=tecla.nextInt();
System.out.print("Puerta: ");
puerta=tecla.next();
System.out.print("Es habitable?(si/no) ");
habitable=tecla.next();
System.out.print("Tipo de local(piso,apartamento,villa,garaje...): ");
tipoLocal=tecla.next();
System.out.print("Cuantos metros cuadrados tiene? ");
metros2=tecla.nextDouble();
Inmueble i1=new Inmueble();
i1.setPueblo(nomPueblo);
i1.setCalle(calle);
i1.setNumPortal(portal);
i1.setPiso(piso);
i1.setPuerta(puerta);
i1.setHabitable(habitable);
i1.setTipoLocal(tipoLocal);
i1.setMetros(metros2);
System.out.println("Datos introducidos del Inmueble");
System.out.println("Pueblo: "+i1.getPueblo());
System.out.println("Barrio o calle: "+i1.getCalle());
System.out.println("Portal: "+i1.getNumPortal());
System.out.println("Piso: "+i1.getPiso());
System.out.println("Puerta: "+i1.getPuerta());
System.out.println("Es habitable: ");
if (i1.getHabitable()){
System.out.println("SI");
}else{
System.out.println("NO ");
}
System.out.println("Tipo de local: "+i1.getTipoLocal());
System.out.println("Metros cuadrados: "+i1.getMetros());
break;
case "e":
System.out.println("Espacio Publico");
/*private String tipo;//tipo de espacio, escuela, playa, parque, ...
private String municipio;
private String direccion;
private double extension;//m2*/
String tipoEspacio=" ";
String municipio=" ";
String donde=" ";
double extension=0;
System.out.println("DATOS DEL ESPACIO PUBLICO");
System.out.println(" ");
System.out.println("Ingresa los datos");
System.out.print("Tipo: ");
tipoEspacio=tecla.next();
System.out.print("Pueblo: ");
municipio=tecla.next();
System.out.print("Direccion: ");
donde=tecla.next();
System.out.print("Extension en metros2: ");
extension=tecla.nextDouble();
EspacioPublico e1=new EspacioPublico();
e1.setTipo(tipoEspacio);
e1.setMunicipio(municipio);
e1.setDireccion(donde);
e1.setExtension(extension);
System.out.println("Datos introducidos del espacio publico");
System.out.println("Tipo de espacio: "+e1.getTipo());
System.out.println("Pueblo: "+e1.getMunicipio());
System.out.println("Direccion: "+e1.getDireccion());
System.out.println("Extension: "+e1.getExtension());
break;
case "x":
System.out.println("Salir");
break;
default:
System.out.println("Opcion incorrecta, teclea otra opcion");
break;
}
}while(!opcion.equalsIgnoreCase("x"));
System.out.println("Programa terminado");
tecla.close();
} |
5aa3adfc-7fa0-4ff8-89b3-9909ebed6ced | 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(RedesSociais.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RedesSociais.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RedesSociais.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RedesSociais.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 RedesSociais().setVisible(true);
}
});
} |
b730872f-7d17-4403-b3e7-05958c31c82f | 3 | public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
int h = getHeight();
int w = getWidth();
int pct=2;
float tran = 0.1f + pct * 0.9f;
GradientPaint GP = new GradientPaint(0, 0, COLOR1, 0, h, COLOR2, true);
g2d.setPaint(GP);
ButtonModel model = getModel();
if (!model.isEnabled()) {
GP = new GradientPaint(0, 0, COLOR1, 0, h, COLOR2, true);
} else if (model.isRollover()) {
GP = new GradientPaint(0, 0, COLOR1, 0, h, COLOR2, true);
}
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
GradientPaint p1;
GradientPaint p2;
//If is pressed ,orange
if (getModel().isPressed()) {
p1 = new GradientPaint(0, 0, new Color(0, 0, 0), 0, h - 1,
new Color(100, 100, 100));
p2 = new GradientPaint(0, 1, new Color(0, 0, 0, 50), 0, h - 3,
new Color(255, 255, 255, 100));
} else {
p1 = new GradientPaint(0, 0, new Color(100, 100, 100), 0, h - 1,
new Color(0, 0, 0));
p2 = new GradientPaint(0, 1, new Color(255, 255, 255, 100), 0,
h - 3, new Color(0, 0, 0, 50));
}
// g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, tran));
RoundRectangle2D.Float r2d = new RoundRectangle2D.Float(0, 0, w - 1,
h - 1, outerRoundRectSize, outerRoundRectSize);
Shape clip = g2d.getClip();
g2d.clip(r2d);
g2d.fillRect(0, 0, w, h);
g2d.setClip(clip);
g2d.setPaint(p1);
g2d.drawRoundRect(0, 0, w - 1, h - 1, outerRoundRectSize,
outerRoundRectSize);
g2d.setPaint(p2);
g2d.drawRoundRect(1, 1, w - 3, h - 3, innerRoundRectSize,
innerRoundRectSize);
// g2d.dispose();
_drawRect(g2d, 0, w, unselectedHigh, unselectedMid, unselectedLow);
g2d.setPaint(null);
super.paintComponent(g);
} |
9c15974c-d862-441f-9d25-af25712284d4 | 9 | private void loadGame(BasicGame rps) {
Util.initialPromtVersion(rps);
// get all the available items for this verison of game
Set<Item> itemSet = rps.getItems();
while (true) {
currentLine = scanner.nextLine();
try {
//your current picked item. Populates on valid index selection
youPicked = null;
// select an item from the menu
selectedIndex = Integer.parseInt(currentLine);
// computer picks a random item
computerPicked = rps.getRandomOpponent();
// denies any invalid range of item displayed in the menu
if (selectedIndex < 1 || selectedIndex > rps.getItems().size()) {
youPicked = null;
if (selectedIndex == -1) {
return; //return to main menu
} else
System.out.println(Util.wrongInputTypeGameItem());
} else {
// look for an item in the game
// TODO needs further rafactoring ??
int iteratorIndex = 1;
Iterator iterator = itemSet.iterator();
while (iterator.hasNext()) {
if (iteratorIndex == selectedIndex)
youPicked = (Item) iterator.next();
else
iterator.next();
iteratorIndex++;
}
}
if (youPicked != null) {
play(rps, youPicked, computerPicked);
if (Util.playAgainPromt(scanner)) {
Util.initialPromtVersion(rps);
} else {
Util.initialPromt();
scanner.reset();
return;
}
}
} catch (NumberFormatException ex) {
System.out.println(Util.wrongInputTypeGameItem());
}
}
} |
baad786e-b9f9-4195-9d53-207c1cf44a61 | 0 | private void jButtonNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNextActionPerformed
ctrlP.suivant();
}//GEN-LAST:event_jButtonNextActionPerformed |
dc429881-c330-4aeb-8008-73547fd55a6b | 8 | public ComparableNode getLeftmostProperDescendant() throws MaltChainedException {
NonTerminalNode node = this;
ComparableNode candidate = null;
while (node != null) {
candidate = node.getLeftChild();
if (candidate == null || candidate instanceof TokenNode) {
break;
}
node = (NonTerminalNode)candidate;
}
if (candidate == null && candidate instanceof NonTerminalNode) {
candidate = null;
DependencyNode dep = null;
for (int index : ((TokenStructure)getBelongsToGraph()).getTokenIndices()) {
dep = ((TokenStructure)getBelongsToGraph()).getTokenNode(index);
while (dep != null) {
if (dep == this ) {
return dep;
}
dep = dep.getHead();
}
}
}
return candidate;
} |
b543d7da-3a19-4fc3-9530-b861ee24558d | 9 | static final public void metodos() throws ParseException {
if (jj_2_4(2147483647)) {
metodos_com_parametros();
} else {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case DOUBLE:
case FLOAT:
case LONG:
case CHAR:
case INT:
case VISIBILITY:
case IDENTIFIER:
metodos_sem_parametros();
break;
default:
jj_la1[10] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
} |
4c45aca7-6265-460d-a0d1-b12f7c05a267 | 4 | @Override
public void free_result() throws SQLException {
// no need to close a stmt which doesn't exist
if(this.stmt != null && !this.stmt.isClosed()) {
this.stmt.close();
this.stmt = null;
this.last_prepare = "";
}
if(this.res != null && !this.res.isClosed()) {
this.res.close();
this.res = null;
}
} |
cabc7f0e-6324-4780-9b99-1350d022a2d6 | 5 | private void dissipate() {
float flowRate = Globals.getSetting("Dissipation strength", "Water");
for(int x = 0; x < Globals.width; x++){
for(int y = 0; y < Globals.height; y++){
for(int[] neighbor : HexagonUtils.neighborTiles(x, y, false)){
if(groundWaterLevel[neighbor[0]][neighbor[1]] < groundWaterLevel[x][y]){
float flow = (groundWaterLevel[x][y]-groundWaterLevel[neighbor[0]][neighbor[1]])*flowRate;
if(groundWaterLevel[x][y] >= flow){
groundWaterLevel[x][y] -= flow;
groundWaterLevel[neighbor[0]][neighbor[1]] += flow;
}
}
}
}
}
} |
c6d5df21-1d84-42d4-aabd-6716b1caab47 | 8 | public static void parseArguments(final String[] args) {
for (int i = 0; i < args.length; i++) {
final String element = args[i];
if (element.equalsIgnoreCase("-h") || element.equalsIgnoreCase("--h") || element.equalsIgnoreCase("--help") || element.equalsIgnoreCase("-help") || element.equalsIgnoreCase("help")) {
System.out.println("--help, -help, help: this help printout");
System.out.println("-h (host), --host (host): set the hostname to bind to");
System.out.println("-p (port), --port (port): set the port to use to");
System.out.println("-p (dir), --port (dir): set the root directory");
System.out.println("-i (file deliminated by ';'), --index (files deliminated by ';'): set the default file");
System.exit(0);
} else if (element.equalsIgnoreCase("-p") || element.equalsIgnoreCase("--port")) {
}
}
} |
b81af191-b303-46b3-ad1a-022c136c3b67 | 1 | public static void main(String[] args)
{
HashSet set1 = new HashSet();
set1.add("a");
set1.add("b");
set1.add("c");
set1.add("d");
// Iterator iter = set1.iterator();
// while(iter.hasNext()){
//
// String value = (String)iter.next();
//
// System.out.println(value);
// }
for(Iterator iter = set1.iterator();iter.hasNext();)
{
String value = (String)iter.next();
System.out.println(value);
}
} |
9191e3ec-d745-4a64-8c44-0b4ef1769049 | 5 | private void writeToFile(String strRep, String path) {
FileOutputStream fos = null;
File file;
try {
//Get all current text into temp
String temp = "";
Scanner sc = new Scanner(new File(path));
while(sc.hasNextLine()) {
temp += sc.nextLine() + '\n';
}
sc.close();
file = new File(path);
fos = new FileOutputStream(file);
//Todo new file creation
// if file does not exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
temp = temp + strRep;
byte[] contentInBytes = temp.getBytes();
fos.write(contentInBytes);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} |
7ae76b01-ca66-4a3d-87da-b0c2f64b9a20 | 3 | static double[][] multiply(double[][] A, double[][] B){
double[][] AB = new double[A.length][B[0].length];
for(int i = 0; i < A.length; i++){
for(int j = 0; j < B[i].length; j++){
for(int k = 0; k < B.length ; k++){
AB[i][j] += A[i][k]*B[k][j];
}
}
}
return AB;
} |
d0fc548e-db31-4230-b48d-84a2f6626eda | 3 | private void initEnemies() {
for(int i = 0; i < 12; i++) {
Mho newEnemy = initRandMho();
if(!(grid[newEnemy.getX()][newEnemy.getY()] instanceof Fence) && !(grid[newEnemy.getX()][newEnemy.getY()].contains(Mho.class))) {
grid[newEnemy.getX()][newEnemy.getY()].occupy(newEnemy);
}
else i--;
}
} |
5cf24108-9654-473f-b026-ff64ea071233 | 6 | public Double[][] sum(Double[][] a, Double[][] b) {
Double[][] ans = new Double[2][a[0].length+b[0].length];
boolean flag = false;
for(int i=0; i<a[0].length; i++){
ans[0][i] = a[0][i];
ans[1][i] = a[1][i];
}
if(a[0].length < b[0].length){
Double[][] t = a;
a = b;
b = t;
}
for(int i=0;i<b[0].length; i++){
for(int j=0;j < a[0].length; j++){
if(a[1][j].doubleValue() == b[1][i].doubleValue()){
ans[0][j] += b[0][i];
flag = true;
}
}
if(!flag){
ans[0][a[0].length+i] = b[0][i];
ans[1][a[1].length+i] = b[1][i];
}
flag = false;
}
return ArrayVerifier.removeZeroCoefs(ans);
} |
62707562-8069-4382-819c-7a9074917f9f | 3 | @Override
public void delete(Match obj) {
PreparedStatement pst = null;
try {
pst = this.connect().prepareStatement("DELETE FROM Matches where id=?;");
pst.setInt(1, obj.getId());
pst.executeUpdate();
System.out.println("suppression effectuer");
} catch (SQLException ex) {
Logger.getLogger(MatchDao.class.getName()).log(Level.SEVERE, "suppression echoué", ex);
}finally{
try {
if(pst != null)
pst.close();
} catch (SQLException ex) {
Logger.getLogger(MatchDao.class.getName()).log(Level.SEVERE, "liberation preparedstatement echoué", ex);
}
}
} |
27839fa8-8f67-4dad-8fa4-7ac16706bfc3 | 5 | public static void flatten3(TreeNode root) {
if (root == null || (root.left == null && root.right == null)) return;
if (root.left != null) {
TreeNode tmp = root.right;
root.right = root.left;
root.left = null;
TreeNode rightMost = findRightMostNode(root.right);
rightMost.right = tmp;
flatten3(root.right);
} else if (root.right != null) {
flatten3(root.right);
}
} |
47086476-2244-43db-b3aa-89b6bee9e076 | 0 | public void clear(){
wrncnt=0;
errcnt=0;
messagequeue.clear();
} |
85085369-e2ce-44db-9c3a-ff39e8b69344 | 1 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((val == null) ? 0 : val.hashCode());
return result;
} |
b6360478-96aa-4d4d-b39e-c49bfe360ed5 | 2 | public void delete(int index){
if(index >= size || index < 0){
System.out.println("Invalid index");
}else{
maxHeap[index] = maxHeap[size - 1];
size --;
MaxHeap.maxHeaplify(maxHeap, index, size);
}
} |
8ec69478-7410-481a-9f16-0baca5ed284d | 4 | private List<Reducer> estimateReducers(List<Mapper> newMapperList) {
int fReducerNum = finishedConf.getMapred_reduce_tasks();
if(fReducerNum == 0)
return null;
ReducerEstimator reducerEstimator = new ReducerEstimator(finishedConf, newConf, newMapperList, false);
List<Reducer> newReducerList = new ArrayList<Reducer>();
//reducer number doesn't change
//reducerIndex means which partition of mappers' output will be received by the new reducer
if(fReducerNum == newConf.getMapred_reduce_tasks()) {
for(int i = 0; i < fReducerNum; i++) {
//use the corresponding finished reducer to estimate the new reducer
Reducer newReducer = reducerEstimator.estimateNewReducer(job.getReducerList().get(i), i);
newReducerList.add(newReducer);
}
}
//reducer number changes
else {
for(int i = 0; i < newConf.getMapred_reduce_tasks(); i++) {
//use all the finished reducers' infos to estimate the new reducer
Reducer newReducer = reducerEstimator.estimateNewReducer(job.getReducerList(), i);
newReducerList.add(newReducer);
}
}
return newReducerList;
} |
4598608a-fd30-4f98-8008-fd711ace62c2 | 7 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final Item target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_ANY);
if(target==null)
return false;
if(!(target instanceof Armor))
{
mob.tell(mob,target,null,L("You can't enchant <T-NAME> with an Enchant Armor spell!"));
return false;
}
if(target.phyStats().ability()>2)
{
mob.tell(L("@x1 cannot be enchanted further.",target.name(mob)));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final int experienceToLose=getXPCOSTAdjustment(mob,50);
CMLib.leveler().postExperience(mob,null,null,-experienceToLose,false);
mob.tell(L("The effort causes you to lose @x1 experience.",""+experienceToLose));
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> hold(s) <T-NAMESELF> and cast(s) a spell.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
mob.location().show(mob,target,CMMsg.MSG_OK_VISUAL,L("<T-NAME> glows!"));
target.basePhyStats().setAbility(target.basePhyStats().ability()+1);
target.basePhyStats().setLevel(target.basePhyStats().level()+3);
target.recoverPhyStats();
mob.recoverPhyStats();
}
}
else
beneficialWordsFizzle(mob,target,L("<S-NAME> hold(s) <T-NAMESELF> tightly and whisper(s), but fail(s) to cast a spell."));
// return whether it worked
return success;
} |
a98c3f28-7235-407c-ba23-0e1e2af28209 | 6 | public boolean canShiftLeft(){
if(loc1.getColumn() == 0 || loc2.getColumn() == 0|| loc3.getColumn() == 0
|| loc4.getColumn() == 0){
return false;
}
//gets all of the rightmost locations of the piece
ArrayList<Location> leftLocs = getLeftLocs();
for(int i = 0; i < leftLocs.size(); i++){
if(board.getValue(leftLocs.get(i).getRow(), leftLocs.get(i).getColumn() - 1) !=0){
return false;
}
}
return true;
} |
edee296b-b1f2-4565-acac-9acd1aa3147f | 4 | public boolean onCommand(CommandSender cs, Command cmd, String string,
String[] args) {
if(!(cs instanceof Player)){
cs.sendMessage("This is not a console command!");
return false;
}
if(string.equalsIgnoreCase("tp")){
Teleport teleportObj = new Teleport(MainClass);
teleportObj.teleport(cs, cmd, string, args);
}
else if(string.equalsIgnoreCase("tphere")){
TeleportHere teleporthereObj = new TeleportHere(MainClass);
teleporthereObj.teleport(cs, cmd, string, args);
}
else if(string.equalsIgnoreCase("tpall")){
TeleportAll tpAll = new TeleportAll(MainClass);
tpAll.teleport(cs, cmd, string, args);
}
return false;
} |
0909eae2-a304-4dd3-aa53-ba68853f5fb9 | 4 | public void linearInterpolation(){
if(this.nAnalyteConcns<2)throw new IllegalArgumentException("Method cubicInterpolation requres at least 2 data points; only " + this.nAnalyteConcns + " were supplied");
this.methodUsed = 14;
this.sampleErrorFlag = false;
this.titleOne = "Linear interpolation ";
if(!this.setDataOneDone)this.setDataOne();
this.li = new LinearInterpolation(this.analyteConcns, this.responses);
for(int i=0; i<this.nInterp; i++)this.calculatedResponses[i] = li.interpolate(this.interpolationConcns[i]);
if(!this.supressPlot)this.plott();
this.curveCheck(this.methodIndices[this.methodUsed]);
} |
386f1a2f-a926-491d-8ca1-56ab6adefc43 | 2 | @Override
@Command
public MessageResponse setUserPublicKey(String userName) throws IOException {
if(initRMI()) {
String pathToPublicKey = keysDir+"/"+userName+".pub.pem";
PEMReader in;
try {
in = new PEMReader(new FileReader(pathToPublicKey));
PublicKey publicKey = (PublicKey) in.readObject();
in.close();
return proxyRMI.setUserPublicKey(userName, publicKey);
} catch (FileNotFoundException e) {
return new MessageResponse("Key for user "+userName+" not found");
}
}
else return new MessageResponse("Cannot connect to Proxy via RMI");
} |
5d83334b-91fd-4e28-9d13-951bad61ec27 | 7 | public GameData getData() {
// creating a new gamedata object
GameData gd = new GameData();
// setting the MP and gem
gd.setMP(MagicPower.getMP());
gd.setGem(gem);
gd.setCounter(counter);
// adding the enemies
List<Enemy> enemyList = new ArrayList<Enemy>();
for (Tile t : map) {
if (t instanceof Road) {
Road r = (Road) t;
for (Enemy e : r.getEnemies()) {
enemyList.add(e);
}
}
}
for (Enemy e : enemyList) {
int[] pos = new int[2];
pos[0] = map.indexOf(e.getRoad()) / size;
pos[1] = map.indexOf(e.getRoad()) % size;
gd.addEnemy(pos, e);
}
// adding the towers
for (Tower t : towers) {
int[] pos = new int[2];
pos[0] = map.indexOf(t.getField()) / size;
pos[1] = map.indexOf(t.getField()) % size;
gd.addTower(pos, t);
}
// adding swamps
for (Tile t : map) {
if (t instanceof Swamp) {
int[] pos = new int[2];
pos[0] = map.indexOf(t) / size;
pos[1] = map.indexOf(t) % size;
gd.addSwamp(pos, (Swamp) t);
}
}
return gd;
} |
4b54a3c9-6560-46db-96ad-e636385d9e0f | 5 | @Override
public boolean export(final File target, HistorySorter sorter) {
boolean result = false;
if (sorter == null) {
throw new IllegalArgumentException("Null sorter not allowed");
}
try {
final Document doc = prepareDocument();
final Element rootElement = doc.createElement("History");
doc.appendChild(rootElement);
final List<Element> data = sorter.sortHistory(records, doc);
for (Element e : data) {
rootElement.appendChild(e);
}
exportDocumentToXML(target, doc);
result = true;
LOG.log(Level.FINE, "History successfully exported to {0}, sorted using {1}", new Object[]{target.getAbsolutePath(), sorter.getClass().getCanonicalName()});
} catch (TransformerConfigurationException ex) {
LOG.log(Level.WARNING, "Failed to create Transformer, export failed.");
LOG.log(Level.FINE, "Failed to create Transformer.", ex);
} catch (TransformerException ex) {
LOG.log(Level.WARNING, "Failed to transform history into XML, export failed.");
LOG.log(Level.FINE, "Failed to transform history into XML.", ex);
} catch (ParserConfigurationException ex) {
LOG.log(Level.WARNING, "Failed to create DocumentBuilder, export failed.");
LOG.log(Level.FINE, "Failed to create DocumentBuilder.", ex);
}
return result;
} |
78cc8981-a002-44fb-9c15-1c47851d065f | 2 | private void printImplementors(final Type iType, final PrintWriter out,
final boolean recurse, final int indent) {
final Iterator implementors = this.implementors(iType).iterator();
while (implementors.hasNext()) {
final Type implementor = (Type) implementors.next();
indent(out, indent);
out.println(implementor);
if (recurse) {
printImplementors(implementor, out, recurse, indent + 2);
}
}
} |
374b2104-14cd-4a27-916f-9b2ce0ce76d7 | 3 | @Override
Shape getShape(String shapeName) {
// Java 8 can use Strings in switch.
switch (shapeName) {
case "CIRCLE":
return new Circle();
case "RECTANGLE":
return new Rectangle();
case "SQUARE":
return new Square();
default:
return null;
}
} |
c9cd0d9f-f370-4346-9c35-059473b9772f | 7 | private boolean catchEntryRefs(E entry) {
strongRefs.clear();
if (entry == null) {
return true;
}
final List<? extends Reference<?>> refs = entry.getReferences();
if (refs == null) {
return true;
}
for (Reference<?> ref: refs) {
final Object obj = ref.get();
if (obj == null) {
strongRefs.clear();
return false;
}
strongRefs.add(obj);
}
return true;
} |
64f4bf4e-c631-4193-bcde-884802e13759 | 6 | public void check() throws IllegalStateException {
Run currentRun = getFirst();
int curLength = 0;
int totalLength = width * height;
while(hasNext(currentRun)) {
if((currentRun.getRunType() == currentRun.getNext().getRunType())
&&(currentRun.getHungerVal() == currentRun.getNext().getHungerVal())) {
currentRun = currentRun.getNext();
break;
}
curLength += currentRun.getRunLength();
currentRun = currentRun.getNext();
}
if(curLength != totalLength)
throw new IllegalStateException("Sum of Run lengths not equal to RunLengthEncoding length ");
else if(currentRun.getRunType() == currentRun.getPrev().getRunType()
&& currentRun.getHungerVal() == currentRun.getPrev().getHungerVal())
throw new IllegalStateException("RunLengthEncoding contains consecutive runs of same runType and hungerVal");
} |
3e25fb8b-ffa9-4cdc-b13e-25eaf6dc55f6 | 9 | Object createPrimitiveFor(Class<?> primitiveT) {
if (primitiveT == Boolean.TYPE) {
return arbBoolean();
} else if (primitiveT == Character.TYPE) {
return arbChar();
} else if (primitiveT == Byte.TYPE) {
return arbByte();
} else if (primitiveT == Short.TYPE) {
return arbShort();
} else if (primitiveT == Integer.TYPE) {
return arbInt();
} else if (primitiveT == Long.TYPE) {
return arbLong();
} else if (primitiveT == Float.TYPE) {
return arbFloat();
} else if (primitiveT == Double.TYPE) {
return arbDouble();
} else { /* Void.TYPE */
return null;
}
} |
f453be3b-2b2c-4ebe-979a-1da4009e3550 | 5 | final void method1716(boolean bool) {
anInt5931++;
if (bool != false)
aClass351_5929 = null;
if (((Class239) this).aClass348_Sub51_3136.method3422(674)
!= Class10.aClass230_186)
((Class239) this).anInt3138 = 1;
else if (((Class239) this).aClass348_Sub51_3136.method3425(-125))
((Class239) this).anInt3138 = 0;
if (((Class239) this).anInt3138 != 0
&& ((Class239) this).anInt3138 != 1)
((Class239) this).anInt3138 = method1710(20014);
} |
87f6f023-c7f7-41e6-8aa7-affdb7bf701f | 4 | public void drawStringMoveY(int waveSpeed, String string, int waveAmount, int y, int x, int color) {
if (string == null) {
return;
}
double speed = 7D - (double) waveSpeed / 8D;
if (speed < 0.0D) {
speed = 0.0D;
}
x -= getTextWidth(string) / 2;
y -= baseHeight;
for (int index = 0; index < string.length(); index++) {
char c = string.charAt(index);
if (c != ' ') {
drawCharacter(characterPixels[c], x + characterOffsetX[c], y + characterOffsetY[c] + (int) (Math.sin((double) index / 1.5D + (double) waveAmount) * speed), characterWidth[c], characterHeight[c], color);
}
x += characterScreenWidth[c];
}
} |
5781cdff-a0c9-4ad0-98f0-ad07f1238d65 | 3 | @Override
public void reset () {
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (field[i][j] instanceof EmptyCell) {
field[i][j] = new EmptyCell();
}
}
}
openedCells.clear();
isProcess = false;
isPathFind = false;
path.clear();
pathLength = 0;
} |
a95f3b4b-aac8-4b09-b93b-a85dd53c981b | 7 | private void hitEnemy(Player player, Enemy[][] enemys){
for(int i = 0; i < enemys.length; i++) {
for(int j = 0; j < enemys[i].length; j++) {
for(int k = 0; k < player.getProjectiles().length; k++) {
if(player.getProjectiles()[k].getCollider() != null) {
if(enemys[i][j].getCollider().overlaps(player.getProjectiles()[k].getCollider()) &&
enemys[i][j].isAlive() &&
player.getProjectiles()[k].isAlive()) {
enemys[i][j].toggleAlive();
player.getProjectiles()[k].toggleAlive();
score += enemys[i][j].getScore();
}
}
}
}
}
} |
62322b15-103c-473c-89f8-ff573149774b | 7 | private void setUpValueSelection(Instances format) {
if (format.classIndex() < 0 || format.classAttribute().isNumeric()) {
// cant do anything in this case
return;
}
if (m_displayValNames == false) {
remove(m_messageLabel);
}
int existingClassVal = m_classValuePicker.getClassValueIndex();
String [] attribValNames = new String [format.classAttribute().numValues()];
for (int i = 0; i < attribValNames.length; i++) {
attribValNames[i] = format.classAttribute().value(i);
}
m_ClassValueCombo.setModel(new DefaultComboBoxModel(attribValNames));
if (attribValNames.length > 0) {
if (existingClassVal < attribValNames.length) {
m_ClassValueCombo.setSelectedIndex(existingClassVal);
}
}
if (m_displayValNames == false) {
add(m_holderP, BorderLayout.CENTER);
m_displayValNames = true;
}
validate(); repaint();
} |
6b75ee12-d3eb-445a-9434-30d109bca6cd | 3 | @EventHandler
public void onPlayerJoin(PlayerJoinEvent e)
{
IrcClient client = Parent.Manager.getCurrentClient();
for(String s : client.getMcEcho_ActiveChannels())
{
try{ client.PrivMsg(s, IrcColor.formatMCMessage(ChatManagerUtils.ParseDisplayName(e.getPlayer())) + IrcColor.NORMAL.getIRCColor() + " has joined.", false); }
catch(NoClassDefFoundError ex){ ex.printStackTrace(); }
catch(Exception ex){ }
}
} |
89cdeaca-8671-4569-a061-131737865798 | 9 | public void createStockArff(String stockName, ArrayList<Integer> years) {
String result = "";
int instances = 0;
result += "@RELATION " + stockName + "\r\n";
result += "@ATTRIBUTE day NUMERIC " + "\r\n";
result += "@ATTRIBUTE price NUMERIC " + "\r\n";
result += "@DATA " + "\r\n";
for (Integer i : years) {
try {
File f = new File("src/datas/" + stockName + "/" + stockName + "_" + i.toString() + ".csv");
Scanner sc = new Scanner(f);
String line = "";
String ld = "";
while (sc.hasNext()) {
line = sc.nextLine();
// System.out.println(f);
// System.out.println(line);
String date = line.split(";")[0];
if (!date.equals(ld)) {
instances++;
// System.out.println(line);
String attr = line.split(";")[1].equals("N/A") ? "?" : line.split(";")[1];
String toSave = instances + "," + attr + "\r\n";
result += toSave;
switch (stockName) {
case "djia":
djiaData[instances - 1] = attr;
case "nasdaq":
nasdaqData[instances - 1] = attr;
case "eurostoxx":
eurostoxxData[instances - 1] = attr;
}
}
ld = date;
}
} catch (FileNotFoundException ex) {
System.out.println("Cannot find specified path: " + stockName + " " + i);
}
}
result = "%" + instances + "\r\n" + result;
try {
File f = new File("src/datas/" + stockName + "/" + stockName + ".arff");
f.delete();
f.createNewFile();
PrintWriter out = null;
out = new PrintWriter(new BufferedWriter(new FileWriter("src/datas/" + stockName + "/" + stockName + ".arff", true)));
out.print(result);
out.close();
} catch (IOException ex) {
Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.