method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
2540d819-307b-4321-be43-c88046ca9905 | 9 | private void processLine(String line, int lineNumber) {
if (line.startsWith("//") || line.trim().length() == 0) return;
DeconstructedStringScroller sd = new DeconstructedStringScroller(line, " ");
if (type == null) {
if (sd.next().toLowerCase().equals("class")) try {
String className = sd.next();
type = Class.forName(className);
if (sd.hasNext())
throw new RuntimeException("Trailing content at line " + lineNumber + ": " + line);
return;
} catch (ClassNotFoundException e) {
throw new RuntimeException("Unable to parse line " + lineNumber + ": " + line, e);
}
} else {
String action = sd.next();
for(String key: actions.keySet()) {
if (key.equals(action)) {
line = line.substring(key.length() + 1);
String fieldName = sd.next();
FieldSpec fieldSpec = newInstance(actions.get(key), fieldName);
currentVersion().addFieldSpec(fieldSpec); //w00!
if (!sd.hasNext())
return;
//more here...
}
}
}
throw new RuntimeException("Unable to parse line " + lineNumber + ": " + line);
} |
6be74c97-b437-4408-8df6-9af4d4295657 | 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 Truck)) {
return false;
}
Truck other = (Truck) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} |
ba9eb422-b279-43de-b05e-7b98acdf248d | 0 | public void setId(Integer id) {
this.id = id;
} |
7b2636ba-8ce3-4def-b2c8-a9120cd16e7c | 9 | public void stealDeadEquipment(Player pgive, Player pget){
String head = pgive.playerTag + "'s inventory";
String textBlock = "Enter a number to take an item from " + pgive.playerTag + " : ";
ArrayList<String> strList = new ArrayList<String>();
ArrayList<Card> eqInv = new ArrayList<Card>();
for(Card card: pgive.inventory){
if(card.equipment && !card.ultimate){
eqInv.add(card);
}
}
int n = -1;
for(int j = 0; j < eqInv.size(); j++){
strList.add(j + " : " + eqInv.get(j).name);
}
pget.displayRender(head, textBlock, strList);
drawEvent(pget, pget);
do{
n = playerInput(pget);
}while(n <= -1 || n >= eqInv.size());
pgive.inventory.remove(eqInv.get(n));
pget.inventory.add(eqInv.get(n));
updateActionFeed(eqInv.get(n).name + " was stolen from " + pgive.playerTag +"!");
eqInv.remove(eqInv.get(n));
if(!eqInv.isEmpty() && (pget.inventory.contains(Card.reliquary)|| pget.inventory.contains(Card.reliquaryii))){
stealDeadEquipment(pgive, pget);
}
} |
f173b4e6-1cdf-47b2-99f5-a13295c6b44e | 5 | private Boolean checkOfFieldsOk() {
if ("".equals(txtDatabaseSettingName.getText())) {
txtDatabaseSettingName.setForeground(Color.red);
return false;
} else {
txtDatabaseSettingName.setBackground(Color.white);
}
if ("".equals(txtDatabaseAddressingLocation.getText())) {
txtDatabaseAddressingLocation.setBackground(Color.red);
return false;
} else {
txtDatabaseAddressingLocation.setBackground(Color.white);
}
if ("".equals(txtDatabaseAddressingPort.getText())) {
txtDatabaseAddressingPort.setBackground(Color.red);
return false;
} else {
txtDatabaseAddressingPort.setBackground(Color.white);
}
if ("".equals(txtDatabaseNamingDatabaseName.getText())) {
txtDatabaseNamingDatabaseName.setBackground(Color.red);
return false;
} else {
txtDatabaseNamingDatabaseName.setBackground(Color.white);
}
if ("".equals(txtDatabaseNamingTablePrefix.getText())) {
txtDatabaseNamingTablePrefix.setBackground(Color.red);
return false;
} else {
txtDatabaseNamingTablePrefix.setBackground(Color.white);
}
return true;
} |
ef463b02-3173-4f12-be4d-76ac45ec311b | 5 | private int parseLine(String line)
{
//preprocessing: remove extra whitespace, comments, lowercase
int commentPos = line.indexOf('#');
if (commentPos >= 0)
line = line.substring(0, commentPos);
line = line.trim().toUpperCase();
int i = 0; // Current position in the string
//If the line contains no code just skip it
if (line.length() == 0)
return 0; // empty string
//Verbose output for the user if requested
if (m_verbose)
{
System.out.print(line);
for(int j = 0; j < (25 - line.length()); j++)
System.out.print(" ");
}
//Check for a label and parse it if found
if (line.charAt(i) == ':')
return parseLabel(line, i);
//Otherwise it must be an instruction
return parseInstruction(line, i);
}//parse |
77bf119c-80f3-40fc-9d2f-5890494a35c5 | 5 | public void bulkPut1( ByteChunk[] keys, ByteChunk[] values, int offset, int count ) {
long[] indexPos = new long[count];
for( int i=0; i<count; ++i ) {
indexPos[i] = indexPos(keys[i]);
}
FileLock fl = null;
synchronized( this ) {
try {
try {
if( fileChannel != null ) fl = fileChannel.lock(0, Long.MAX_VALUE, false);
for( int i=0; i<count; ++i ) {
_putWithoutLocking( indexPos[i], keys[i], values[i] );
}
} finally {
if( fl != null ) fl.release();
}
} catch( IOException e ) {
throw new RuntimeException(e);
}
}
} |
c9208c13-93a8-4125-8934-df9ffccc63e2 | 8 | private void optimiseSelectorsAndHuffmanTables (final boolean storeSelectors) {
final char[] mtfBlock = this.mtfBlock;
final byte[] selectors = this.selectors;
final int[][] huffmanCodeLengths = this.huffmanCodeLengths;
final int mtfLength = this.mtfLength;
final int mtfAlphabetSize = this.mtfAlphabetSize;
final int totalTables = huffmanCodeLengths.length;
final int[][] tableFrequencies = new int[totalTables][mtfAlphabetSize];
int selectorIndex = 0;
// Find the best table for each group of 50 block bytes based on the current Huffman code lengths
for (int groupStart = 0; groupStart < mtfLength;) {
final int groupEnd = Math.min (groupStart + BZip2Constants.HUFFMAN_GROUP_RUN_LENGTH, mtfLength) - 1;
// Calculate the cost of this group when encoded by each table
short[] cost = new short[totalTables];
for (int i = groupStart; i <= groupEnd; i++) {
final int value = mtfBlock[i];
for (int j = 0; j < totalTables; j++) {
cost[j] += huffmanCodeLengths[j][value];
}
}
// Find the table with the least cost for this group
byte bestTable = 0;
int bestCost = cost[0];
for (byte i = 1 ; i < totalTables; i++) {
final int tableCost = cost[i];
if (tableCost < bestCost) {
bestCost = tableCost;
bestTable = i;
}
}
// Accumulate symbol frequencies for the table chosen for this block
final int[] bestGroupFrequencies = tableFrequencies[bestTable];
for (int i = groupStart; i <= groupEnd; i++) {
bestGroupFrequencies[mtfBlock[i]]++;
}
// Store a selector indicating the table chosen for this block
if (storeSelectors) {
selectors[selectorIndex++] = bestTable;
}
groupStart = groupEnd + 1;
}
// Generate new Huffman code lengths based on the frequencies for each table accumulated in this iteration
for (int i = 0; i < totalTables; i++) {
generateHuffmanCodeLengths (mtfAlphabetSize, tableFrequencies[i], huffmanCodeLengths[i]);
}
} |
1882c74d-747b-41e6-ab2b-50889b2dde28 | 5 | public boolean isNeighbour(GraphPoint p1, GraphPoint p2)
{
if (p1 == p2)
return false;
for (Point point : points)
{
if (point != p1 && point != p2 &&
p1.euclideanDistance2(p2) >
Math.max(p1.euclideanDistance2(point), p2.euclideanDistance2(point)))
{
return false;
}
}
return true;
} |
a4312e0f-a82c-4561-9793-ede22d351556 | 6 | public static void act(Unit facility) {
if (facility == null) {
return;
}
int[] buildingQueueDetails = Constructing.shouldBuildAnyBuilding();
int freeMinerals = xvr.getMinerals();
int freeGas = xvr.getGas();
if (buildingQueueDetails != null) {
freeMinerals -= buildingQueueDetails[0];
freeGas -= buildingQueueDetails[1];
}
if (buildingQueueDetails == null || (freeMinerals >= 200 && freeGas >= 400)) {
if (facility.getTrainingQueueSize() == 0) {
xvr.buildUnit(facility, defineUnitToBuild(freeMinerals, freeGas));
}
}
} |
fd5a7a5a-d49d-4029-8c70-9ac10bfe0ed7 | 0 | public void setPassengers(List<Participant> passengers) {
this.passengers = passengers;
} |
d1d62c08-0b05-46e9-9226-3505882b9907 | 7 | @Override
public void collision(Engine engine, Entity v,boolean b) {
if(type==6)
{
boolean entitythere = false;
for(Entity q:engine.getWorld().getEntityList()){
if(entitythere)
continue;
if(q != null && (q.doesDamage()&&q.canDie()))
entitythere = true;
}
if(!entitythere){
engine.playSound(this.getLocation().getX(),this.getLocation().getY(),"portal");
((TestEngine)engine).curmission++;
((TestEngine)engine).setWorld(((TestEngine)engine).getNextWorld());
}
}
} |
8c180689-b56f-4a55-88fb-80a4219efbaf | 3 | public double readDouble(String pSection, String pKey, double pDefault)
{
//if the ini file was never loaded from memory, return the default
if (buffer == null) {return pDefault;}
Parameters params = new Parameters();
//get the value associated with pSection and PKey
String valueText = getValue(pSection, pKey, params);
//if Section/Key not found, return the default
if (valueText.equals("")) {return(pDefault);}
double value;
//try to convert the remainder of the string after the '=' symbol to a
//double if an error occurs, return the default value
try{
value = Double.parseDouble(valueText);
}
catch(NumberFormatException e){return(pDefault);}
return(value);
}//end of IniFile::readDouble |
38cf944d-16a3-4715-b3cc-c36de72d80b8 | 1 | public void ancestorResized(HierarchyEvent e) {
if (GamePanel.getThis() != null) {
GamePanel.getThis().resizePanel();
}
} |
cc66ca5a-09c7-4932-88ba-2422dd941e43 | 5 | public void insert(E e)
{
int newPlace = heapSize;
while (newPlace > 0 &&
comparator.compare(e, array[getParent(newPlace)]) < 0)
{
array[newPlace] = array[getParent(newPlace)];
if (indexes != null)
indexes.put((E)array[newPlace], newPlace);
newPlace = getParent(newPlace);
}
array[newPlace] = e;
if (indexes != null)
indexes.put(e, newPlace);
heapSize++;
if (heapSize >= array.length)
increaseArray();
} |
bd0ec2ef-7904-4dae-b022-5dc3f63c6cc4 | 8 | public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int N = sc.nextInt();
if (N == 0) {
break;
}
Queue<Integer> q = new ArrayDeque<Integer>();
for (int i = 1; i <= N; i++) {
q.add(i);
}
Queue<Integer> q2 = new ArrayDeque<Integer>();
int last = 0;
while (!q.isEmpty()) {
int x = q.poll();
if (q.isEmpty()) {
last = x;
} else {
q2.offer(x);
x = q.poll();
q.add(x);
}
}
System.out.print("Discarded cards:");
boolean first = true;
while (!q2.isEmpty()) {
if (first) {
System.out.print(" ");
first = false;
}
int x = q2.poll();
System.out.print(x);
if (!q2.isEmpty()) {
System.out.print(", ");
}
}
System.out.println("\nRemaining card: " + last);
}
} |
c5f11666-0177-4f06-bd6c-50a3c978610f | 7 | public void write(int bits, int width) throws IOException {
if (bits == 0 && width == 0) {
return;
}
if (width <= 0 || width > 32) {
throw new IOException("Bad write width.");
}
while (width > 0) {
int actual = width;
if (actual > this.vacant) {
actual = this.vacant;
}
this.unwritten |= ((bits >>> (width - actual)) &
((1 << actual) - 1)) << (this.vacant - actual);
width -= actual;
nrBits += actual;
this.vacant -= actual;
if (this.vacant == 0) {
this.out.write(this.unwritten);
this.unwritten = 0;
this.vacant = 8;
}
}
} |
e1dddb27-8295-4cb0-8ef1-05d3a1711909 | 5 | public String getCellSymbol() {
if (rock) {
return "#";
} else if (ant != null) {
return "a";
} else if (food != 0) {
return food + "";
} else {
switch (anthill) {
case "red":
return "+";
case "black":
return "-";
default:
return ".";
}
}
} |
e7443692-8d7d-487d-a370-e453dc5d4fa3 | 4 | public static byte[] readBytesFromFile(File file) throws IOException {
byte[] bytes;
try (InputStream is = new FileInputStream(file)) {
long length = file.length();
if (length > Integer.MAX_VALUE) {
throw new IOException("Could not completely read file " + file.getName() + " as it is too long (" + length + " bytes, max supported " + Integer.MAX_VALUE + ")");
}
bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
}
}
return bytes;
} |
1e1c26d9-290a-4513-84fa-9c4f7214c9f7 | 7 | @Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
String data;
try {
ArrayList<FilterBean> alFilter = new ArrayList<>();
if (request.getParameter("filter") != null) {
if (request.getParameter("filteroperator") != null) {
if (request.getParameter("filtervalue") != null) {
FilterBean oFilterBean = new FilterBean();
oFilterBean.setFilter(request.getParameter("filter"));
oFilterBean.setFilterOperator(request.getParameter("filteroperator"));
oFilterBean.setFilterValue(request.getParameter("filtervalue"));
oFilterBean.setFilterOrigin("user");
alFilter.add(oFilterBean);
}
}
}
if (request.getParameter("systemfilter") != null) {
if (request.getParameter("systemfilteroperator") != null) {
if (request.getParameter("systemfiltervalue") != null) {
FilterBean oFilterBean = new FilterBean();
oFilterBean.setFilter(request.getParameter("systemfilter"));
oFilterBean.setFilterOperator(request.getParameter("systemfilteroperator"));
oFilterBean.setFilterValue(request.getParameter("systemfiltervalue"));
oFilterBean.setFilterOrigin("system");
alFilter.add(oFilterBean);
}
}
}
ProductoDao oProductoDAO = new ProductoDao();
int pages = oProductoDAO.getCount(alFilter);
data = "{\"data\":\"" + Integer.toString(pages) + "\"}";
return data;
} catch (Exception e) {
throw new ServletException("ProductoGetregistersJson: View Error: " + e.getMessage());
}
} |
ccd920db-be7d-4802-9879-90ac1fe642d9 | 3 | public static final boolean AABB_point(Box b, Point p) {
return p.x >= b.x
&& p.x <= b.getMaxX()
&& p.y >= b.y
&& p.y <= b.getMaxY();
} |
35ba667c-3770-4ee9-8ed2-fea3549845c6 | 7 | private boolean isValidBlock(int[][] game, int x, int y, int testNumber) {
//declare variables referencing 3x3 block location in 9x9 grid
int blockX, blockY;
//determine row of 3x3 block being tested
if (x < 3)
blockX = 0; //rows 0, 1, 2
else if (x < 6)
blockX = 3; //rows 3, 4, 5
else
blockX = 6; //rows 6, 7, 8
//determine column of 3x3 block being tested
if (y < 3)
blockY = 0; //columns 0, 1, 2
else if (y < 6)
blockY = 3; //columns 3, 4, 5
else
blockY = 6; //columns 6, 7, 8
while (y < blockY + 3) {
while (x < blockX + 3) {
if (game[blockY][blockX] == testNumber)
return false; //testNumber exists in 3x3 block
x++;
}
y++;
}
return true; //testNumber does not exist in 3x3 block
} |
db5ebadc-a260-4106-ae16-4c599e4fa5a5 | 2 | public void goToImage(int index){
if(index < 0 || index >= history.size()) return;
historyIndex = index;
imagePanel.updatePanel(history.get(historyIndex));
imagePanel.update(imagePanel.getGraphics());
} |
1a1353ba-f9a5-4b6f-8b18-115e1f7db2f5 | 9 | static private void load() {
Timestamp startDay = Timestamp.valueOf("2011-01-01 00:00:00.0");
Timestamp nextDay = new Timestamp(startDay.getTime() + oneDayLong);
//final Timestamp endDay = Timestamp.valueOf("2011-09-01 00:00:00.0"); // !!!!!!! the first 8 months
final Timestamp endDay = Timestamp.valueOf("2012-05-01 00:00:00.0");
while (startDay.before(endDay)) {
System.out.println(startDay); // print info
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
String sqlTxt = "select * from stream2 where t >= \'"
+ startDay + "\' and t < \'" + nextDay + "\'";
if (stmt.execute(sqlTxt)) {
rs = stmt.getResultSet();
while (rs.next()) {
Tweet tweet = new Tweet(rs.getString("user_ID"),
rs.getString("status_ID"),
rs.getString("tweet"), rs.getTimestamp("t"));
users.add(tweet.user_ID);
}
}
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) {
} // ignore
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) {
} // ignore
stmt = null;
}
}
int count = users.size();
saveUsersCount(startDay, count);
System.out.println("" + startDay + ":\t" + count);
startDay = nextDay;
nextDay = new Timestamp(startDay.getTime() + oneDayLong);
}
System.out.println("Number of users: " + users.size());
for(String user : users){
save(user);
}
} |
8e997fe8-e714-4f4d-b994-87298fc5422f | 7 | private void dragDivider(MouseEvent event) {
if (mDividerDragLayout != null) {
if (!mDividerDragIsValid) {
mDividerDragIsValid = Math.abs(mDividerDragStartX - event.getX()) > DRAG_THRESHOLD || Math.abs(mDividerDragStartY - event.getY()) > DRAG_THRESHOLD || event.getWhen() - mDividerDragStartedAt > DRAG_DELAY;
}
if (mDividerDragIsValid) {
int pos = mDividerDragInitialDividerPosition - (mDividerDragInitialEventPosition - (mDividerDragLayout.isHorizontal() ? event.getX() : event.getY()));
mDividerDragLayout.setDividerPosition(pos < 0 ? 0 : pos);
}
}
} |
ea1523fb-b4d7-4d7b-960a-0cf7940e3fff | 8 | public static boolean computeCell(boolean[][] world, int col, int row)
{
// liveCell is true if the cell at position (col,row) in world is live
boolean liveCell = getCell(world, col, row);
// neighbours is the number of live neighbours to cell (col,row)
int neighbours = countNeighbours(world, col, row);
// we will return this value at the end of the method to indicate whether
// cell (col,row) should be live in the next generation
boolean nextCell = false;
// A live cell with less than two neighbours dies (underpopulation)
if (neighbours < 2) nextCell = false;
// A live cell with two or three neighbours lives (a balanced population)
if (liveCell && (neighbours == 2 || neighbours == 3)) nextCell = true;
// A live cell with more than three neighbours dies (overcrowding)
if (liveCell && neighbours > 3) nextCell = false;
// A dead cell with exactly three live neighbours comes alive
if (!liveCell && neighbours == 3) nextCell = true;
return nextCell;
} |
70e1c7c6-c02e-4387-bdb2-d9cb9959a9b8 | 9 | @Override
public void run() {
if (state == GameState.Running) {
while (true) {
bg1.update();
bg2.update();
robot.update();
hb.update();
hb2.update();
if (robot.isJumped()) {
currentSprite = characterJumped;
}
else if (robot.isJumped() == false && robot.isDucked() == false) {
currentSprite = anim.getImage();
}
ArrayList projectiles = robot.getProjectiles();
for (int i = 0; i < projectiles.size(); i++) {
Projectiles p = (Projectiles) projectiles.get(i);
if (p.isVisible() == true) {
p.update();
}
else {
projectiles.remove(i);
}
}
updateTiles();
hb.update();
hb2.update();
bg1.update();
bg2.update();
animate();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (robot.getCenterY() > 500) {
state = GameState.Dead;
}
}
}
} |
5f84005b-b62f-4fb7-897d-30adab7e04ef | 3 | public static List<AstronomicalObject> sortByMass(List stm, int factor) {
List<AstronomicalObject> sorted = stm;
if (stm.size() > 0) {
if (factor < 0) {
Collections.sort(sorted, (B, A) -> MASS_COMPARATOR.compare(A, B));
log.info("SortedByMass descending :{}");
}
if (factor >= 0) {
Collections.sort(sorted, MASS_COMPARATOR::compare);
log.info("SortedByMass ascending :{}");
}
}
return sorted;
} |
05f92ab5-87cd-464a-904f-98341b6aa140 | 8 | private boolean await0(long timeoutMillis, boolean interruptable) throws InterruptedException {
long startTime = timeoutMillis <= 0 ? 0 : System.currentTimeMillis();
long waitTime = timeoutMillis;
synchronized (lock) {
if (ready) {
return ready;
} else if (waitTime <= 0) {
return ready;
}
waiters++;
try {
for (;;) {
try {
lock.wait(waitTime);
} catch (InterruptedException e) {
if (interruptable) {
throw e;
}
}
if (ready) {
return true;
} else {
waitTime = timeoutMillis
- (System.currentTimeMillis() - startTime);
if (waitTime <= 0) {
return ready;
}
}
}
} finally {
waiters--;
}
}
} |
87027ea2-5a6e-43c3-9018-ea8a603cfd2d | 6 | public void removeEffects(Character character) {
if (!character.getBuffs().isEmpty()) {
for (SkillEffect effect : character.getBuffs()) {
effect.endEffect();
}
character.getBuffs().clear();
}
if (!character.getDebuffs().isEmpty()) {
for (SkillEffect effect : character.getDebuffs()) {
effect.endEffect();
}
character.getDebuffs().clear();
}
for (Skill skill : character.getSkills()) {
if (skill.isUsed()) {
skill.actionPerformed(null);
}
}
} |
998087a8-609d-49fb-a2bd-a08afdd56e66 | 5 | public byte[] pack() throws IOException {
byte[] footer = new byte[activeEntries * 10 + cSize + 2];
footer[0] = (byte) (activeEntries >> 8);
footer[1] = (byte) activeEntries;
int informationOffset = 2;
for(int i = 0; i < amountEntries; i++) {
if(archivePayloads[i] != null) {
footer[informationOffset++] = (byte) (nameHashes[i] >> 24);
footer[informationOffset++] = (byte) (nameHashes[i] >> 16);
footer[informationOffset++] = (byte) (nameHashes[i] >> 8);
footer[informationOffset++] = (byte) nameHashes[i];
footer[informationOffset++] = (byte) (uSizes[i] >> 16);
footer[informationOffset++] = (byte) (uSizes[i] >> 8);
footer[informationOffset++] = (byte) uSizes[i];
footer[informationOffset++] = (byte) (cSizes[i] >> 16);
footer[informationOffset++] = (byte) (cSizes[i] >> 8);
footer[informationOffset++] = (byte) cSizes[i];
}
}
for(int i = 0; i < amountEntries; i++) {
if(archivePayloads[i] != null) {
System.arraycopy(archivePayloads[i], 0, footer, informationOffset, cSizes[i]);
informationOffset += cSizes[i];
}
}
byte[] header = new byte[3 + 3];
int usize = footer.length;
header[0] = (byte) (usize >> 16);
header[1] = (byte) (usize >> 8);
header[2] = (byte) usize;
if(isCompressed) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
BZip2CompressorOutputStream bz2os = new BZip2CompressorOutputStream(os);
bz2os.write(footer);
footer = os.toByteArray();
}
int csize = footer.length;
header[3] = (byte) (csize >> 16);
header[4] = (byte) (csize >> 8);
header[5] = (byte) csize;
byte[] payload = new byte[header.length + csize];
System.arraycopy(header, 0, payload, 0, payload.length);
System.arraycopy(footer, 0, payload, header.length, footer.length);
return payload;
} |
67a46c2a-e585-4d77-9125-1e55a5fdcf43 | 9 | public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
do {
line = in.readLine();
if (line == null || line.length() == 0)
break;
int[] nn = retInts(line);
SegTree[] st = new SegTree[nn[0]];
String[] d;
for (int i = 0; i < nn[0]; i++) {
d = in.readLine().trim().split(" ");
st[i] = new SegTree(1, nn[1]);
for (int j = 0; j < d.length; j++)
st[i].set(j+1, Integer.parseInt(d[j]));
}
int q = Integer.parseInt(in.readLine());
for (int i = 0; i < q; i++) {
d = in.readLine().trim().split(" ");
if(d[0].equals("q")){
int x0 = Integer.parseInt(d[1]);
int y0 = Integer.parseInt(d[2]);
int x1 = Integer.parseInt(d[3]);
int y1 = Integer.parseInt(d[4]);
long max = Long.MIN_VALUE;
long min = Long.MAX_VALUE;
for (int j = x0; j <= x1; j++) {
max = Math.max(max, st[j-1].getMax(y0, y1));
min = Math.min(min, st[j-1].getMin(y0, y1));
}
out.append(max+" "+min+"\n");
}else{
int x = Integer.parseInt(d[1]);
int y = Integer.parseInt(d[2]);
int v = Integer.parseInt(d[3]);
st[x-1].set(y, v);
}
}
} while (line != null && line.length() != 0);
System.out.print(out);
} |
dd105c22-e032-4afa-a2a5-891f11a3a1f2 | 3 | public int getTeamSearchResult(String search){
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = dbconn.getConnection();
st = conn.prepareStatement("SELECT * FROM match_record_2013 where event_id = ? AND team_id = ?");
st.setInt(1, getSelectedEvent());
st.setInt(2, Integer.parseInt(search));
rs = st.executeQuery();
if (rs.next()) {
return rs.getInt("team_id");
} else {
return -1;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try{
conn.close();
st.close();
rs.close();
}catch (SQLException e) {
System.out.println("Error closing query");
}
}
return -1;
} |
ed9f13fd-8de2-40d0-8213-4e9c67da73a0 | 5 | public static String removePrefix(String listenHostname, String hostname, boolean forward) {
if(hostname == null || listenHostname == null) {
return null;
}
listenHostname = listenHostname.trim();
hostname = hostname.trim();
if(hostname.startsWith(listenHostname)) {
hostname = hostname.substring(listenHostname.length());
hostname = hostname.trim();
} else {
return forward?null:hostname;
}
if(hostname.startsWith(",")) {
hostname = hostname.substring(1);
hostname = hostname.trim();
} else {
return null;
}
return hostname;
} |
e793d238-4fb9-40cc-afbe-359a2b6ac4ea | 0 | @Override
public IRemoteCallObjectData getDataObject() {
return data;
} |
94facffa-d345-429b-a25e-e00892a31875 | 1 | @GET
@Path("/v2.0/ports/{portId}")
@Produces({MediaType.APPLICATION_JSON, OpenstackNetProxyConstants.TYPE_RDF})
public Response showPort(@PathParam("portId") String portId, @HeaderParam("Accept") String accept) throws MalformedURLException, IOException{
if (accept.equals(OpenstackNetProxyConstants.TYPE_RDF)){
System.out.println(accept);
String dataFromKB=PortOntology.showPort(portId);
System.out.println(dataFromKB);
// XmlTester t=new XmlTester();
return Response.status(200).header("Access-Control-Allow-Origin", "*").entity(dataFromKB).build();
}
else{
//Send HTTP request and receive a single Json content identified by an ID
HttpURLConnection conn=HTTPConnector.HTTPConnect(new URL(this.URLpath+"/"+portId), OpenstackNetProxyConstants.HTTP_METHOD_GET, null);
String response=HTTPConnector.printStream(conn);
Object result;
result=(ExtendedPort) JsonUtility.fromResponseStringToObject(response, ExtendedPort.class);
int responseCode=conn.getResponseCode();
HTTPConnector.HTTPDisconnect(conn);
return Response.status(responseCode).header("Access-Control-Allow-Origin", "*").entity(result).build();
}
} |
2add0c87-7e66-401a-801e-3f89444eed48 | 6 | private String getActiveModels() {
String s = "";
int modelNumber = 0;
int num = 0;
while (modelNumber < models.size()) {
if (models.get(modelNumber).getIsComplex()) {
ComplexModel c = (ComplexModel) models.get(modelNumber);
for (int i = 0; i < c.getSize(); i++) {
if (c.getModel(i).getIsActive())
s += num + ",";
num++;
}
modelNumber++;
} else {
if (models.get(modelNumber).getIsActive())
s += num + ",";
num++;
modelNumber++;
}
}
if (s.length() > 0)
s = s.substring(0, s.length() - 1);
return s;
} |
ff433606-963b-4d31-89f9-58e12d9bd8b5 | 1 | public int getPixelSize(int boardWidth, int boardHeight) {
Dimension maxCanvas = getMaxCanvas();
int pixelWidth = maxCanvas.width / boardWidth;
int pixelHeight = maxCanvas.height / boardHeight;
int pixelSize;
if (pixelWidth <= pixelHeight) {
pixelSize = pixelWidth;
} else {
pixelSize = pixelHeight;
}
return pixelSize;
} |
ff6cdb09-f838-4d50-870d-aac3f14b3635 | 3 | public SingleTreeNode treePolicy(StateObservationMulti state) {
SingleTreeNode cur = this;
while (!state.isGameOver() && cur.m_depth < ROLLOUT_DEPTH)
{
if (cur.notFullyExpanded()) {
return cur.expand(state);
} else {
SingleTreeNode next = cur.uct(state);
cur = next;
}
}
return cur;
} |
4886a725-8ecf-4199-8969-e9e9028b668d | 8 | public static boolean isHydrophicChar( char inChar )
{
if ( inChar == 'A' || inChar == 'V' || inChar == 'L'
|| inChar == 'I' || inChar =='F' || inChar =='W'
|| inChar == 'M' || inChar == 'P')
return true;
return false;
} |
1ca54e88-0dc4-4fcf-9af8-43554272ae56 | 5 | public static int getIntLE(final byte[] array, final int index, final int size) {
switch (size) {
case 0:
return 0;
case 1:
return Bytes.getInt1(array, index);
case 2:
return Bytes.getInt2LE(array, index);
case 3:
return Bytes.getInt3LE(array, index);
case 4:
return Bytes.getInt4LE(array, index);
default:
throw new IllegalArgumentException();
}
} |
354eb344-77e7-49cf-bc2b-5b8eacc0dc8a | 1 | public static List<String> cloneList(List<String> list) {
List<String> clone = new ArrayList<String>(list.size());
for(String item: list) clone.add(item);
return clone;
} |
091218fa-d409-4e23-b9e9-331f8cf6be5d | 8 | public List<Tuple<Integer,Integer>> aStar ( Tuple<Integer,Integer> start, Tuple<Integer,Integer> goal) {
// Set closedSet = empty set
HashSet<Tuple<Integer,Integer>> closedSet = new HashSet<Tuple<Integer,Integer>>();
// The set of tentative nodes to be evaluated
HashSet<Tuple<Integer,Integer>> openSet = new HashSet<Tuple<Integer,Integer>>();
// initially containing the start node
openSet.add(start);
// The map of navigated nodes.
// Initially set to empty map
HashMap<Tuple<Integer,Integer>,Tuple<Integer,Integer>> cameFrom = new HashMap<Tuple<Integer,Integer>,Tuple<Integer,Integer>>();
HashMap<Tuple<Integer,Integer>,Integer> g_score = new HashMap<Tuple<Integer,Integer>,Integer>();
g_score.put(start,0); // Cost from start along best known path.
// Estimated total cost from start to goal through y.
HashMap<Tuple<Integer,Integer>,Integer> f_score = new HashMap<Tuple<Integer,Integer>,Integer>();
f_score.put(start, g_score.get(start) + heuristicCostEstimate(start, goal));
while ( !openSet.isEmpty() ) {
// current := the node in openset having the lowest f_score[] value
int lowestF = Integer.MAX_VALUE;
Tuple<Integer,Integer> current = null;
for ( Tuple<Integer,Integer> node : openSet ) {
if ( f_score.get(node) < lowestF ) {
lowestF = f_score.get(node);
current = node;
}
}
if ( current.equals(goal) ) {
return reconstructPath(cameFrom, goal);
}
//remove current from openset
openSet.remove(current);
//add current to closedset
closedSet.add(current);
HashSet<Tuple<Integer,Integer>> neighbor_nodes = getNeighborNodes(current);
// log.trace("Neighboring nodes: " + neighbor_nodes.size());
// for each neighbor in neighbor_nodes(current)
for ( Tuple<Integer,Integer> neighbor : neighbor_nodes ) {
// if neighbor in closedset
if ( closedSet.contains(neighbor) )
continue;
int tentative_g_score = g_score.get(current) + 1;
// log.trace("Open set size:" + openSet.size());
if ( !openSet.contains(neighbor) || tentative_g_score < g_score.get(neighbor) ) {
// add neighbor to openset
// log.trace("adding a neighbor to openSet with tentative_g_score" + tentative_g_score);
openSet.add(neighbor);
cameFrom.put(neighbor, current);
g_score.put(neighbor, tentative_g_score);
f_score.put(neighbor, g_score.get(neighbor) + heuristicCostEstimate(neighbor, goal));
}
}
}
// Failure
log.error("A* is returning null! This should never happen!");
return null;
} |
02996435-fbaf-46c1-acc0-bdcc7f996805 | 6 | public Production[] getProductionsToAddForProduction(Production production,
Set lambdaSet) {
// Stupid...
/*
* ProductionChecker pc = new ProductionChecker(); String[] variables =
* production.getVariablesOnRHS(); ArrayList list = new ArrayList();
* for(int k = 0; k < variables.length; k++) {
* if(isInLambdaSet(variables[k],lambdaSet)) list.add(variables[k]); }
* String[] lambdaVar = (String[]) list.toArray(new String[0]); String[]
* combs = getCombinations(lambdaVar); ArrayList productions = new
* ArrayList(); for(int k = 0; k < combs.length; k++) { Production p =
* getProductionForCombination(production,combs[k]);
* if(!pc.isLambdaProduction(p)) productions.add(p); } return
* (Production[]) productions.toArray(new Production[0]);
*/
String[] start = new String[] { "" };
String rhs = production.getRHS();
for (int i = 0; i < rhs.length(); i++) {
String v = rhs.substring(i, i + 1);
if (lambdaSet.contains(v)) {
String s[] = new String[start.length * 2];
for (int j = 0; j < start.length; j++) {
s[j] = start[j] + v;
s[j + start.length] = start[j];
}
start = s;
} else {
for (int j = 0; j < start.length; j++)
start[j] += v;
}
}
Arrays.sort(start);
ArrayList list = new ArrayList();
String lhs = production.getLHS();
for (int i = (start[0].length() == 0) ? 1 : 0; i < start.length; i++)
list.add(new Production(lhs, start[i]));
return (Production[]) list.toArray(new Production[0]);
} |
5eac313b-0e27-483f-9de5-2a87ca18c9ad | 1 | public long evaluate_long(Object[] dl) throws Throwable {
if (Debug.enabled)
Debug.println("Wrong evaluateXXXX() method called,"+
" check value of getType().");
return 0L;
}; |
5b6e3803-143f-4723-a06e-f11926039c83 | 1 | public void updateTitle(Dockable dockable) {
int index = mDockables.indexOf(dockable);
if (index != -1) {
mHeader.updateTitle(index);
}
} |
cb55c41b-49fe-4b21-9fab-75c5dd3a50fe | 0 | public PRFAlgorithmIdentifierType getPRF() {
return prf;
} |
347f0d41-ec81-47b6-9e68-6796e94519dd | 5 | private void writeFin(String user, int glID, String resName,
double cost, double cpu, double clock,
boolean header)
{
if (trace_flag == false) {
return;
}
// Write into a results file
FileWriter fwriter = null;
try
{
fwriter = new FileWriter(user, true);
} catch (Exception ex)
{
ex.printStackTrace();
System.out.println(
"Unwanted errors while opening file " + user);
}
try
{
if (header == true) {
fwriter.write(
"\n\nGridletID \t Resource \t Cost \t CPU time \t Latency\n");
}
fwriter.write(glID + "\t" + resName + "\t" + cost + "\t"+ cpu +
"\t" + + clock + "\n");
} catch (Exception ex)
{
ex.printStackTrace();
System.out.println(
"Unwanted errors while writing on file " + user);
}
try
{
fwriter.close();
} catch (Exception ex)
{
ex.printStackTrace();
System.out.println(
"Unwanted errors while closing file " + user);
}
} |
a1fda48c-eabd-44d2-8e8b-f67c78e56097 | 1 | protected Class loadClass(final String className) throws ClassNotFoundException {
try {
return (Class)AccessController.doPrivileged(new PrivilegedExceptionAction(){
public Object run() throws Exception{
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return Class.forName(className, true, cl);
}
});
}
catch (PrivilegedActionException pae) {
throw new RuntimeException("cannot load the class: " + className, pae.getException());
}
} |
d8c27cb5-ec43-4b8e-bf6e-aed87dad405a | 6 | * @param colony The <code>Colony</code> to pillage.
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csPillageColony(Unit attacker, Colony colony,
Random random, ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerNation = attacker.getApparentOwnerName();
ServerPlayer colonyPlayer = (ServerPlayer) colony.getOwner();
StringTemplate colonyNation = colonyPlayer.getNationName();
// Collect the damagable buildings, ships, movable goods.
List<Building> buildingList = colony.getBurnableBuildingList();
List<Unit> shipList = colony.getShipList();
List<Goods> goodsList = colony.getLootableGoodsList();
// Pick one, with one extra choice for stealing gold.
int pillage = Utils.randomInt(logger, "Pillage choice", random,
buildingList.size() + shipList.size() + goodsList.size()
+ ((colony.canBePlundered()) ? 1 : 0));
if (pillage < buildingList.size()) {
Building building = buildingList.get(pillage);
csDamageBuilding(building, cs);
cs.addMessage(See.only(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.buildingDamaged", colony)
.add("%building%", building.getNameKey())
.addName("%colony%", colony.getName())
.addStringTemplate("%enemyNation%", attackerNation)
.addStringTemplate("%enemyUnit%", attacker.getLabel()));
} else if (pillage < buildingList.size() + shipList.size()) {
Unit ship = shipList.get(pillage - buildingList.size());
if (ship.getRepairLocation() == null) {
csSinkShipAttack(attacker, ship, cs);
} else {
csDamageShipAttack(attacker, ship, cs);
}
} else if (pillage < buildingList.size() + shipList.size()
+ goodsList.size()) {
Goods goods = goodsList.get(pillage - buildingList.size()
- shipList.size());
goods.setAmount(Math.min(goods.getAmount() / 2, 50));
colony.removeGoods(goods);
if (attacker.canAdd(goods)) attacker.add(goods);
cs.addMessage(See.only(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.goodsStolen", colony, goods)
.addAmount("%amount%", goods.getAmount())
.add("%goods%", goods.getType().getNameKey())
.addName("%colony%", colony.getName())
.addStringTemplate("%enemyNation%", attackerNation)
.addStringTemplate("%enemyUnit%", attacker.getLabel()));
} else {
int plunder = Math.max(1, colony.getPlunder(attacker, random) / 5);
colonyPlayer.modifyGold(-plunder);
attackerPlayer.modifyGold(plunder);
cs.addPartial(See.only(colonyPlayer), colonyPlayer, "gold");
cs.addMessage(See.only(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.indianPlunder", colony)
.addAmount("%amount%", plunder)
.addName("%colony%", colony.getName())
.addStringTemplate("%enemyNation%", attackerNation)
.addStringTemplate("%enemyUnit%", attacker.getLabel()));
}
cs.addMessage(See.all().except(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.indianRaid", colonyPlayer)
.addStringTemplate("%nation%", attackerNation)
.addName("%colony%", colony.getName())
.addStringTemplate("%colonyNation%", colonyNation));
} |
4ae0a73d-379c-4e99-a281-c9cbc040f0b4 | 4 | private ActionListener createInviteROListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PeerStatus status = LocalInfo.getPeerStatus();
if (!(status == PeerStatus.STARTER || status == PeerStatus.INVITEE)) {
JOptionPane.showMessageDialog(frame, "You have no authority to do that");
return;
}
// send invitation to specific ip and port
// send invitation to specific ip and port
String ipPort = JOptionPane.showInputDialog("Please input ip:port");
String[] strs = ipPort.split(":");
if (strs.length != 2)
JOptionPane.showMessageDialog(null, "Invalid Format of Ip and Port",
"Error!", JOptionPane.ERROR_MESSAGE);
try {
LocalSender.sendInvitationMsg(strs[0], Integer.parseInt(strs[1]),
Event.INVITATION_RO);
System.out.println("Invite server to network: " + strs[0] + ":" + strs[1]);
} catch (Exception exception) {
exception.printStackTrace();
}
}
};
} |
406758e7-6e33-4bba-bdc9-8e3ab81e8016 | 6 | public static void method335(int i, int j, int k, int l, int i1, int k1)
{
if(k1 < topX)
{
k -= topX - k1;
k1 = topX;
}
if(j < topY)
{
l -= topY - j;
j = topY;
}
if(k1 + k > bottomX)
k = bottomX - k1;
if(j + l > bottomY)
l = bottomY - j;
int l1 = 256 - i1;
int i2 = (i >> 16 & 0xff) * i1;
int j2 = (i >> 8 & 0xff) * i1;
int k2 = (i & 0xff) * i1;
int k3 = width - k;
int l3 = k1 + j * width;
for(int i4 = 0; i4 < l; i4++)
{
for(int j4 = -k; j4 < 0; j4++)
{
int l2 = (pixels[l3] >> 16 & 0xff) * l1;
int i3 = (pixels[l3] >> 8 & 0xff) * l1;
int j3 = (pixels[l3] & 0xff) * l1;
int k4 = ((i2 + l2 >> 8) << 16) + ((j2 + i3 >> 8) << 8) + (k2 + j3 >> 8);
pixels[l3++] = k4;
}
l3 += k3;
}
} |
5adf89a8-6742-429e-8f8f-bab8167a3e19 | 0 | public String getLabel() {
return this.label;
} |
119276a1-6ce7-47ec-8461-8f2059601e87 | 3 | @Override
public boolean equals(Object object) {
if (object instanceof SearchTerm) {
SearchTerm test = (SearchTerm) object;
return test.isCaseSensitive() == caseSensitive &&
test.isWholeWord() == wholeWord &&
test.getTerm().equals(term);
} else {
return false;
}
} |
0f2b7802-8762-4b23-8cc2-e6022eaa23eb | 6 | public static void loadScriptsFile(String name)
{
try {
File f = new File(name);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(f);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("action");
for (int temp = 0; temp < nList.getLength(); temp++) {
LuaActionScript scr = new LuaActionScript();
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if(eElement.hasAttribute("itemid"))
scr.itemid = Integer.parseInt(eElement.getAttribute("itemid"));
if(eElement.hasAttribute("actionid"))
scr.actionid = Integer.parseInt(eElement.getAttribute("actionid"));
if(eElement.hasAttribute("uniqueid"))
scr.uniqueid = Integer.parseInt(eElement.getAttribute("uniqueid"));
scr.type = TYPE.find(eElement.getAttribute("type"));
scr.name = eElement.getAttribute("name");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} |
54b8c8e5-3b5a-4312-902a-935cda55241a | 3 | public static String decimalToBinary(int decimal) {
String binary = "";
while (decimal != 0) {
if (decimal % 2 == 0)
binary = "0" + binary;
else
binary = "1" + binary;
decimal = decimal / 2;
}
for (int i = binary.length(); i < 16; i++) {
binary = "0" + binary;
}
return binary;
} |
eddc9261-9528-4609-9d3f-8b3f351750f8 | 0 | public void close() throws IOException
{
target.close();
listener.done();
} |
fad265f9-ae65-4da7-9261-2a13ab615259 | 0 | public String getCode(final K symbol) {
return this.symbols.get(symbol);
} |
e0f4582d-841b-48a9-8fc6-e4cd0be5204f | 2 | public static byte menu(){
byte op=-1;
System.out.println("1.- Feu un programa en Java que demani el nombre de dades amb les quals es vol treballar (n), que les carregui en un array unidimensional real x i que:a) un cop introduïdes les dades les visualitzi per pantalla.b) calculi la mitjana, el valor més gran i el valor més petit de l’array.c) digui quins elements es troben per sobre i per sota de la mitjana.");
System.out.println("2.- Feu un programa en Java que demani el nombre de valors que té l’array unidimensional, que carregui aquest array amb nombres enters i que demani una certa posició i un valor. Després que inserti aquest valor en la posició donada i que mostri de nou l’array per pantalla.");
System.out.println("3.- Feu un programa en Java que demani el nombre de valors que té l’array unidimensional, que carregui l’array (double), que demani una posició i que esborri (elimini) l’element que es troba en aquesta posició. Després que mostri de nou array per pantalla.");
System.out.println("4.- Feu un programa en Java que carregui un array unidimensional amb enters, que demani un valor i que escrigui la posició en la qual es troba aquest valor a dins d’aquest array i en cas que no hi sigui el valor que ho digui.");
System.out.println("5.- Feu un programa en Java que demani la longitud de dos arrays unidimensionals llista1 llista2, que carregui els dos arrays el primer amb números parells i el segon amb imparells, que uneixi els dos arrays en un de sol anomenat llista i que el mostri per pantalla.");
System.out.println("6.- Feu un programa en Java que carregui dos arrays reals unidimensionals i una posició i que faci un nou array on inserti tot el segon array en la posició indicada del primer array i, a continuació d’aquest, acabi d’escriure el primer array.");
System.out.println("7.- Feu un programa en Java que carregui un array unidimensional amb números reals i que digui si està ordenat en forma creixent (de més petit a més gran) o en forma decreixent (de més gran a més petit). En cas contrari que també ho digui.");
System.out.println("8.- Feu un programa en Java que carregui un array unidimensional amb números enters. Després que ens demani si el volem ordenar en forma creixent o decreixent i que ho faci.");
System.out.println("9.- Suposeu que teniu les qualificacions de dos crèdits A i B que els fan els mateixos alumnes. Feu un programa en Java que demani les notes dels dos crèdits i que digui quin o quins alumnes tenen la mateixa nota del crèdit A i del B.");
System.out.println("10.- Feu un programa en Java que demani el número de files i de columnes d’una taula i que la carregui amb números parells consecutius. Després que:a) Mostri la taula per pantalla.b) Demani un valor de la taula, que canviï aquest valor per un 0 i que torni a mostrar la taula. c) Demani una fila i una columna i que canviï el valor que està en aquella fila i columna per un 0 i que torni a mostrar la taula.");
System.out.println("11.- Feu un programa en Java que:a) carregui una taula n x n de números enters positius.b) sumi per separat els elements situats a cada fila.c) multipliqui per separat els elements situats a cada columna.");
System.out.println("12.- Feu un programa en Java que prengui una taula n x m plena de caràcters i que canvií les files per les columnes.");
System.out.println("13.- Feu un programa en Java que carregui un tauler d’escacs amb els caràcters blanc B o negre N. Després que:a) Demani una posició del tauler i que digui si hi ha un quadre blanc o un de negre.b)Si al primer quadre posen una moneda d’un cèntim d’euro, al segon dues, al tercer quatre i així successivament, quants diners tindrem en total?");
System.out.println("14.- Feu un programa en Java que demani una taula n x n amb nombres reals i que calculi: La suma de tots els elements que es troben per sobre de cada diagonal. La suma de tots els elements que es troben per sota de cada diagonal.");
System.out.println("15.- En un cert crèdit de CFGS tenim una llista numerada de 25 persones amb el número de llista, les qualificacions de conceptes (60%), les qualificacions de procediments (30%) i les qualificacions d’actituds (10%).Feu un programa en Java que carregui de cada alumne/a les qualificacions i que doni la qualificació final en forma quantitativa (amb dos decimals) i qualitativa (E, N, B, S, I) i que mostri totes les dades per pantalla.");
boolean entra=true;
do{
try{
System.out.print("Exercici => ");
op=Byte.parseByte(stdin.readLine());
entra=true;
}catch(Exception e){
System.out.println("No has introducido un valor válido");
entra=false;
}
}while(entra==false);
return op;
} |
5576ef7e-e425-454b-a7d3-271062940f7b | 9 | private boolean backupStorage() {
new Thread() {
@Override
public void run() {
ProcessBuilder process = null;
Process pr = null;
BufferedReader reader = null;
List<String> args = null;
String line = null;
try {
workingLabel.setText(workingLabel2);
File f = new File(backupDir + "/" + backupTitleLabel1.getText() + backupTitleText.getText() + "/storage/internal");
f.mkdirs();
process = new ProcessBuilder();
args = new ArrayList<>();
args.add(adbController.getADB().getAbsolutePath());
args.add("-s");
args.add(device.toString());
args.add("pull");
args.add("/mnt/sdcard");
process.command(args);
process.directory(f);
process.redirectErrorStream(true);
pr = process.start();
reader = new BufferedReader(new InputStreamReader(pr.getInputStream()));
while ((line = reader.readLine()) != null) {
if (debug)
logger.log(Level.DEBUG, "ADB Output: " + line);
if (line.contains("files pulled.")) {
workingLabel.setText(line);
break;
}
}
pr.destroy();
reader.close();
args.clear();
for (int i = 0; i < 2000; i++) {
} // Display result to user before continuing work.
workingLabel.setText(workingLabel2);
f = new File(backupDir + "/" + backupTitleLabel1.getText() + backupTitleText.getText() + "/storage/sd_card");
f.mkdirs();
process = new ProcessBuilder();
args = new ArrayList<>();
args.add(adbController.getADB().getAbsolutePath());
args.add("-s");
args.add(device.toString());
args.add("pull");
args.add("/mnt/extsdcard");
process.command(args);
process.directory(f);
process.redirectErrorStream(true);
pr = process.start();
reader = new BufferedReader(new InputStreamReader(pr.getInputStream()));
while ((line = reader.readLine()) != null) {
if (debug)
logger.log(Level.DEBUG, "ADB Output: " + line);
if (line.contains("files pulled.")) {
workingLabel.setText(line);
break;
}
}
pr.destroy();
reader.close();
args.clear();
for (int i = 0; i < 2000; i++) {
} // Display result to user before continuing work.
} catch (IOException ex) {
logger.log(Level.ERROR, "An error occurred while backing up storage devices: " + ex.toString() + "\nThe error stack trace will be printed to the console...");
ex.printStackTrace(System.err);
}
interrupt();
}
}.start();
return true;
} |
12f3dbd6-d5dd-483e-8610-ecd430af1e7d | 2 | public static void main(String[] args) {
MessageConfig messageConfig=MessageConfig.parse(
XmlTest.class.getClassLoader().getResourceAsStream("demo.xml"));
System.out.println(messageConfig.toString());
for(Client client : messageConfig.getClient()){
System.out.println("----client----");
System.out.println(client.getUrl());
System.out.println(client.getUser());
System.out.println(client.getPwd());
}
for(Destination destination:messageConfig.getDestination()){
System.out.println("----destination---");
System.out.println(destination.getClient());
System.out.println(destination.getName());
System.out.println(destination.getType());
System.out.println("params thread:"+destination.getParams().getThreads());
System.out.println("params autostart:"+destination.getParams().getAutostart());
}
} |
3fd86f65-ddd0-4fe1-b25a-5c1998e1ffc4 | 4 | public void alert(PrepareItemEnchantEvent e) {
if (Settings.logging) {
writeLog(e.getEnchanter().getDisplayName() + " tried to enchant a "
+ e.getItem().getType().toString().toLowerCase());
}
if (Settings.alertz) {
for (Player p : e.getEnchanter().getServer().getOnlinePlayers()) {
if (PermissionHandler.has(p, PermissionNode.ADMIN)) {
p.sendMessage(ChatColor.GREEN + "[EM] "
+ ChatColor.DARK_RED
+ e.getEnchanter().getDisplayName()
+ " tried to enchant a " + ChatColor.GOLD
+ e.getItem().getType().toString().toLowerCase()
+ ".");
}
}
}
} |
d4444768-a91b-4c31-93f0-a1d8c1d8880b | 7 | Instantiation(final Instantiation prev, final BitSet sub) {
previous = prev;
subroutine = sub;
for (Instantiation p = prev; p != null; p = p.previous) {
if (p.subroutine == sub) {
throw new RuntimeException("Recursive invocation of " + sub);
}
}
// Determine the label to return to when this subroutine terminates
// via RET: note that the main subroutine never terminates via RET.
if (prev != null) {
returnLabel = new LabelNode();
} else {
returnLabel = null;
}
// Each instantiation will remap the labels from the code above to
// refer to its particular copy of its own instructions. Note that
// we collapse labels which point at the same instruction into one:
// this is fairly common as we are often ignoring large chunks of
// instructions, so what were previously distinct labels become
// duplicates.
LabelNode duplbl = null;
for (int i = 0, c = instructions.size(); i < c; i++) {
AbstractInsnNode insn = instructions.get(i);
if (insn.getType() == AbstractInsnNode.LABEL) {
LabelNode ilbl = (LabelNode) insn;
if (duplbl == null) {
// if we already have a label pointing at this spot,
// don't recreate it.
duplbl = new LabelNode();
}
// Add an entry in the rangeTable for every label
// in the original code which points at the next
// instruction of our own to be emitted.
rangeTable.put(ilbl, duplbl);
} else if (findOwner(i) == this) {
// We will emit this instruction, so clear the 'duplbl' flag
// since the next Label will refer to a distinct
// instruction.
duplbl = null;
}
}
} |
673b440c-3718-4b51-b3c1-9a15a71647c9 | 8 | public ExtDecimal ln(int scale, RoundingMode rm) {
if (type == Type.NUMBER) {
if (compareTo(ZERO) < 0) {
throw new ArithmeticException("Logarithm of a negative number in a real context");
} else if (compareTo(ZERO) == 0) {
throw new ArithmeticException("Logarithm of 0");
} else if (compareTo(ONE) == 0) {
return ZERO;
} else if (compareTo(E) == 0) {
return ONE;
} else {
ExtDecimal sum = ExtDecimal.ZERO;
int limit = scale;
for (int i = 0; i <= limit; i++) {
ExtDecimal augend = this.dec().divide(this.inc(), scale + 2, RoundingMode.HALF_DOWN).pow(2 * i + 1).divide(ExtDecimal.valueOf(2 * i + 1), scale + 2, RoundingMode.HALF_UP);
//System.out.println(augend);
sum = sum.add(augend);
}
return sum.multiply(ExtDecimal.TWO).setScale(scale, RoundingMode.DOWN);
}
} else if (type == Type.POSITIVEZERO) {
return NEGATIVEINFINITY;
} else if (type == Type.INFINITY) {
return INFINITY;
} else {
throw new UnsupportedOperationException("exp of ".toString());
}
} |
1ceecbdb-ab79-4ac5-942e-a4f0c5f1131d | 6 | private String generateFirstScan()
{
String tmp = new String();
for(int i = 0; i != lstInfoSchemaPair.size(); i++)
{
String name = lstInfoSchemaPair.get(i).getFirst();
String type = lstInfoSchemaPair.get(i).getSecond();
String typeGetMethod = type.substring(0, 1).toUpperCase() + type.substring(1);
tmp = tmp + "\t\t\t\t" + type + " " + name + "Tmp" + " = rs.get" + typeGetMethod + "(\""
+ name + "\");\n";
}
//Follow code is to print all data. SELECT * FROM <TABLE>
//tmp = this.myPrintAll(lstInfoSchemaPair, tmp);
for(int i = 0; i != this.mfstructOrig.num_Grouping_Vari; i++)
{
tmp += "\t\t\t\t//#" + new Integer(i+1) + " Selection Conditions.\n";
tmp += "\t\t\t\tif(" + this.mySCVConverter.lstJavaCodeConditions.get(i).getSecond() + ")\n";
tmp += "\t\t\t\t{\n";
tmp += "\t\t\t\t\tif(lstMFStruct.size() == 0)\n";
tmp += "\t\t\t\t\t{\n";
tmp += "\t\t\t\t\t\tMFStruct mfStructTmp = new MFStruct();\n";
tmp += "\t\t\t\t\t\tmfStructTmp.initialization_" + new Integer(i+1) + "(";
tmp += this.genMFStructcode.getInitFunctionString();
tmp += "\t\t\t\t\t\tlstMFStruct.add(mfStructTmp);\n";
// tmp += "//\t\t\t\t\t\tcontinue;\n";
tmp += "\t\t\t\t\t}\n";
tmp += "\t\t\t\t\telse\n";
tmp += "\t\t\t\t\t{\n";
tmp += "\t\t\t\t\t\tfor(int i = 0; i != lstMFStruct.size(); i++)\n";
tmp += "\t\t\t\t\t\t{\n";
tmp += "\t\t\t\t\t\t\tif(lstMFStruct.get(i).equals(";
for(int i0 = 0; i0 != this.genMFStructcode.getGroupingTypeNameList().size(); i0++)
{
tmp += this.genMFStructcode.getGroupingTypeNameList().get(i0).getSecond() + "Tmp";
if(i0 != this.genMFStructcode.getGroupingTypeNameList().size() - 1)
{
tmp += ",";
}
}
tmp += ") == true)\n";
tmp += "\t\t\t\t\t\t\t{\n";
//Add count_* functions
tmp += "\t\t\t\t\t\t\t\tlstMFStruct.get(i).set_count_" + new Integer(i+1)+ "();\n";
ArrayList<Pair<Integer, String>> tmpList = new ArrayList<Pair<Integer, String>>(
this.genMFStructcode.getFuncitonList());
for(int j = 0; j != tmpList.size(); j++)
{
if(tmpList.get(j).getFirst().equals(i+1))
{
tmp += "\t\t\t\t\t\t\t\tlstMFStruct.get(i).";
tmp += tmpList.get(j).getSecond() + "(" +
this.myInitSubString(tmpList.get(j).getSecond()) + "Tmp" + ");\n";
}
}
tmp += "\t\t\t\t\t\t\t\tbreak;\n";
tmp += "\t\t\t\t\t\t\t}\n";
tmp += "\t\t\t\t\t\t\tif(i == lstMFStruct.size() - 1)\n";
tmp += "\t\t\t\t\t\t\t{\n";
tmp += "\t\t\t\t\t\t\t\tMFStruct mfStructTmp = new MFStruct();\n";
tmp += "\t\t\t\t\t\t\t\tmfStructTmp.initialization_" + new Integer(i+1) + "("
+ this.genMFStructcode.getInitFunctionString();
tmp += "\t\t\t\t\t\t\t\tlstMFStruct.add(mfStructTmp);\n";
tmp += "\t\t\t\t\t\t\t\tbreak;\n";
tmp += "\t\t\t\t\t\t\t}\n";
tmp += "\t\t\t\t\t\t}\n";
tmp += "\t\t\t\t\t}\n";
tmp += "\t\t\t\t}\n";
}
tmp += "\t\t\t}\n";
return tmp;
} |
ec09b8d2-e6c8-427a-a209-8152e74a5e21 | 1 | @Override
public final ArrayList<Short> get(final Integer... a) {
final ArrayList<Short> r = new ArrayList<Short>();
for (final Integer i : a) { r.add(filter[i]); }
return r;
} |
70e0423a-50f8-4dd9-820d-22bd562b530e | 0 | public ImageIconCellEditor(JCheckBox checkBox, ImageIcon onIcon, ImageIcon offIcon) {
super(checkBox);
button = new JButton(offIcon);
button.setOpaque(true);
button.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
}
);
rendererButton = new JButton(onIcon);
rendererButton.setOpaque(true);
rendererButton.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
}
);
} |
e158d01a-6a4c-41db-81cc-4c038fbfae5e | 3 | @EventHandler
public void onInteract(PlayerInteractEvent e) {
if(e.getPlayer().getItemInHand().getType() == Material.FEATHER) {
if(e.getAction() == Action.LEFT_CLICK_BLOCK) {
PlayerSelections.pos1.put(e.getPlayer().getName(), e.getClickedBlock().getLocation());
e.getPlayer().sendMessage("Position 1 set!");
e.setCancelled(true);
} else if (e.getAction() == Action.RIGHT_CLICK_BLOCK) {
PlayerSelections.pos2.put(e.getPlayer().getName(), e.getClickedBlock().getLocation());
e.getPlayer().sendMessage("Position 2 set!");
e.setCancelled(true);
}
}
} |
0954017f-b9fc-4e78-993c-8449068709fc | 0 | public void setFunFormaPago(String funFormaPago) {
this.funFormaPago = funFormaPago;
} |
6126050d-f516-477f-9264-80022aa23248 | 2 | public MethodInfo getMethod(String name) {
ArrayList list = methods;
int n = list.size();
for (int i = 0; i < n; ++i) {
MethodInfo minfo = (MethodInfo)list.get(i);
if (minfo.getName().equals(name))
return minfo;
}
return null;
} |
01db1a17-c805-40c3-8179-2116fe92cf9a | 4 | public void update(double tDelta) {
if (!stopped) {
double xUnclamped = curPos.getX() + tDelta * vX;
double yUnclamped = curPos.getY() + tDelta * vY;
curPos.setLocation(
vX > 0 ?
Math.min(xUnclamped, finalPos.getX())
:
Math.max(xUnclamped, finalPos.getX()),
vY > 0 ?
Math.min(yUnclamped, finalPos.getY())
:
Math.max(yUnclamped, finalPos.getY())
);
if (curPos.equals(finalPos)) {
curRot = finalRot;
curScale = finalScale;
stop();
} else {
double curDistance = curPos.distance(initPos);
double finalDistance = finalPos.distance(initPos);
double progress = curDistance / finalDistance;
curRot = (finalRot - initRot) * progress + initRot;
curScale = (finalScale - initScale) * progress + initScale;
}
}
} |
84de1f7f-92fc-447f-8ce5-4b6596b2f5cb | 4 | @Override
protected void paintComponent(Graphics oldG) {
super.paintComponent(oldG);
if (fullBoard == null) {
return;
}
//Calculate necessary cell width and height to fill panel
cellWidth = getWidth() / (fullBoard.getColumns() - (zoomFactor * 2));
cellHeight = getHeight() / (fullBoard.getColumns() - (zoomFactor * 2));
Graphics2D g = (Graphics2D) oldG;
//Skip rows and columns that aren't within view after zooming
for (int r = zoomFactor; r < fullBoard.getRows() - zoomFactor; r++) {
for (int c = zoomFactor; c < fullBoard.getColumns() - zoomFactor; c++) {
//Get the contents of the square that corresponds with this cell
Square square = fullBoard.getCell(r, c);
//Perform whatever operations you want, give the square's info
//For my example I only fill in the cell if it is not null
if (square != null) {
//Build cell outline
Rectangle outline = new Rectangle(
(c - zoomFactor) * cellWidth, (r - zoomFactor) * cellHeight, cellWidth, cellHeight);
//Set cell outline color
g.setColor(java.awt.Color.black);
//Draw the cell outline
g.draw(outline);
//Build cell shape (the 1 offsets allow for the outline to be visible)
//Subtracting the zoom ofset makes sure the cells render properly
Rectangle cell = new Rectangle(
(c - zoomFactor) * cellWidth + 1, (r - zoomFactor) * cellHeight + 1, cellWidth - 1, cellHeight - 1);
//Set the color for the inside of the cell
g.setColor(java.awt.Color.white);
//Fill the square
g.fill(cell);
}
}
}
} |
c3e84617-4a11-43ed-8265-a2d8f6010d50 | 5 | public static String getDataReport(Table<Integer, String, Double> input) {
// check preconditions
Preconditions.checkNotNull(input);
Preconditions.checkArgument(input.column("N1").size() > 0, "expect a column N1 with data");
// header of the table
final StringBuilder result = new StringBuilder(1000);
final Set<String> cols = input.columnKeySet();
for (int i = 1; i < cols.size(); i++) {
result.append("N" + i + "\t");
}
result.append("TIME").append(NL);
// values of the table
final SortedSet<Double> rows = new TreeSet<Double>();
rows.addAll(input.column("N1").values());
for (final Double value : rows) {
// find row for the value (sorted by the value of N1)
Integer row = 0;
for (final Integer index : input.column("N1").keySet()) {
if (value.equals(input.get(index, "N1"))) {
row = index;
break;
}
}
// add values to result
for (int col = 1; col < cols.size(); col++) {
result.append(String.format(Locale.US,"%.0f", input.get(row, "N" + col)) + "\t");
}
result.append(String.format(Locale.US,"%.0f", input.get(row, "TIME"))).append(NL);
}
return result.toString();
} |
20f3ec34-f21a-4126-b8f6-70f73e92c98c | 7 | private void ATTACK(Vector3f direction, float distance)
{
double time = (double)Time.getTime()/(double)(Time.SECOND);
double timeDecimals = time - (double)((int)time);
if(timeDecimals < 0.25)
{
material.setTexture(textures.get(4));
}
else if(timeDecimals < 0.5)
material.setTexture(textures.get(5));
else if(timeDecimals < 0.75)
{
material.setTexture(textures.get(6));
if(canShoot){
Vector2f lineStart = new Vector2f(transform.getTranslation().getX(), transform.getTranslation().getZ());
Vector2f castDirection = new Vector2f(direction.getX(),direction.getZ()).rotate((random.nextFloat() - 0.5f) * SHOT_ANGLE);
Vector2f lineEnd = lineStart.add(castDirection.mul(1000.0f));
Vector2f colVector = Game.getLevel().checkIntersection(lineStart, lineEnd, false);
Vector2f playerIntersectVector = Game.getLevel().lineInterSectRect(lineStart,lineEnd, new Vector2f(Transform.getCamera().getPos().getX(), Transform.getCamera().getPos().getZ()), new Vector2f(Player.PLAYER_SIZE, Player.PLAYER_SIZE));
if(playerIntersectVector != null && (colVector == null ||
playerIntersectVector.sub(lineStart).length() < colVector.sub(lineStart).length()))
{
Game.getLevel().getPlayer().damage(random.nextInt(DAMAGE_MAX - DAMAGE_MIN) + DAMAGE_MIN);
}
state = STATE_CHASE;
canShoot = false;
}}else
{
material.setTexture(textures.get(5));
canShoot = true;
}
} |
955e8606-5b13-45b7-aabc-1928732a4655 | 9 | public static void main(String[] args) {
Watch.start();
int[] q = new int[N + 1];
for (int i = 0; i <= N; i++)
q[i] = i;
boolean[] primes = new boolean[N + 1];
Arrays.fill(primes, true);
primes[0] = primes[1] = false;
for (int i = 2; i <= N; i++)
if (primes[i]) {
q[i] = i - 1;
for (int j = 2; i * j <= N; j++) {
primes[i * j] = false;
q[i * j] = (q[i * j] / i) * q[i];//phi(mn) = phi(n)phi(m) if m and n are co-prime
}
}
long sum = 0;
for (int i = 0; i < N; i++)
if (primes[i]) {
int chain = 1, number = i;
while (number != 1) {
number = q[number];
chain++;
if (chain > 25) break;
}
if (chain == 25) sum += i;
}
System.out.println(sum);
Watch.stop();
} |
8d61bbe1-0c54-4ed6-adc1-7461833a66f4 | 3 | public CheckStatus() {
byte[] byteArray = new byte[100];
int msgSize;
loadNativeLibrary();
// eZioLib.openport("6");
byte[] usbId = new byte[100];
eZioLib.FindFirstUSB(usbId);
eZioLib.OpenUSB(usbId);
eZioLib.sendcommand("^XSET,ACTIVERESPONSE,1");
eZioLib.sendcommand("~S,CHECK");
for (int i = 0; i < 5; i++) {
msgSize = eZioLib.RcvBuf(byteArray, byteArray.length);
if (msgSize > 0) {
break;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(new String(byteArray));
eZioLib.closeport();
} |
4df7f45c-06a6-4a4f-9c06-cb0032f37f82 | 5 | private void checkWinCondition()
{
boolean allCellsFlagged = true;
for (int x = 0; x<boardSize; x++) { //iterate through board
for (int y = 0; y<boardSize; y++) {
if (cells[x][y].getMined() && !cells[x][y].getFlagged()) { //if a cell with a mine hasn't been flagged, then the game can't have been won
allCellsFlagged = false;
}
}
}
if (allCellsFlagged) {
gameWon = true; //if we get here, all cells have been flagged
}
} |
30f20962-b21b-4e72-8090-dde9f27edc94 | 3 | public void openLink(final String url) {
if (!java.awt.Desktop.isDesktopSupported()) {
System.err.println("Desktop is not supported (Can't open link)");
return;
}
java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
if (!desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
System.err.println("Desktop (BROWSE) is not supported (Can't open link)");
return;
}
try {
java.net.URI uri = new java.net.URI(url);
desktop.browse(uri);
} catch (Exception e) {
e.printStackTrace();
}
} |
e60c000a-b0ef-40a4-885a-6474b4258601 | 8 | public void buildClusterer(Instances instances) throws Exception {
// can clusterer handle the data?
getCapabilities().testWithFail(instances);
resultVector = new FastVector();
long time_1 = System.currentTimeMillis();
numberOfGeneratedClusters = 0;
replaceMissingValues_Filter = new ReplaceMissingValues();
replaceMissingValues_Filter.setInputFormat(instances);
Instances filteredInstances = Filter.useFilter(instances, replaceMissingValues_Filter);
database = databaseForName(getDatabase_Type(), filteredInstances);
for (int i = 0; i < database.getInstances().numInstances(); i++) {
DataObject dataObject = dataObjectForName(getDatabase_distanceType(),
database.getInstances().instance(i),
Integer.toString(i),
database);
database.insert(dataObject);
}
database.setMinMaxValues();
UpdateQueue seeds = new UpdateQueue();
/** OPTICS-Begin */
Iterator iterator = database.dataObjectIterator();
while (iterator.hasNext()) {
DataObject dataObject = (DataObject) iterator.next();
if (!dataObject.isProcessed()) {
expandClusterOrder(dataObject, seeds);
}
}
long time_2 = System.currentTimeMillis();
elapsedTime = (double) (time_2 - time_1) / 1000.0;
if (writeOPTICSresults) {
String fileName = "";
GregorianCalendar gregorianCalendar = new GregorianCalendar();
String timeStamp = gregorianCalendar.get(Calendar.DAY_OF_MONTH) + "-" +
(gregorianCalendar.get(Calendar.MONTH) + 1) +
"-" + gregorianCalendar.get(Calendar.YEAR) +
"--" + gregorianCalendar.get(Calendar.HOUR_OF_DAY) +
"-" + gregorianCalendar.get(Calendar.MINUTE) +
"-" + gregorianCalendar.get(Calendar.SECOND);
fileName = "OPTICS_" + timeStamp + ".TXT";
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedOPTICSWriter = new BufferedWriter(fileWriter);
for (int i = 0; i < resultVector.size(); i++) {
bufferedOPTICSWriter.write(format_dataObject((DataObject) resultVector.elementAt(i)));
}
bufferedOPTICSWriter.flush();
bufferedOPTICSWriter.close();
}
// explicit file provided to write the generated database to?
if (!databaseOutput.isDirectory()) {
try {
FileOutputStream fos = new FileOutputStream(databaseOutput);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(getSERObject());
oos.flush();
oos.close();
fos.close();
}
catch (Exception e) {
System.err.println(
"Error writing generated database to file '" + getDatabaseOutput() + "': "
+ e);
e.printStackTrace();
}
}
if (showGUI)
new OPTICS_Visualizer(getSERObject(), "OPTICS Visualizer - Main Window");
} |
af61aae1-eeb5-4a3a-829f-ebbda4c7643d | 2 | public synchronized void put(T el) {
while (elements.size() == capacity){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
elements.add(el);
notify();
} |
9c441719-9c36-477f-9fc2-86664127fb35 | 9 | public int getCloseRandomPlayer(int i) {
ArrayList<Integer> players = new ArrayList<Integer>();
for (int j = 0; j < Server.playerHandler.players.length; j++) {
if (Server.playerHandler.players[j] != null) {
if (goodDistance(Server.playerHandler.players[j].absX, Server.playerHandler.players[j].absY, npcs[i].absX, npcs[i].absY, 2 + distanceRequired(i) + followDistance(i)) || isFightCaveNpc(i)) {
if ((Server.playerHandler.players[j].underAttackBy <= 0 && Server.playerHandler.players[j].underAttackBy2 <= 0) || Server.playerHandler.players[j].inMulti())
if (Server.playerHandler.players[j].heightLevel == npcs[i].heightLevel)
players.add(j);
}
}
}
if (players.size() > 0)
return players.get(Misc.random(players.size() -1));
else
return 0;
} |
e37fb151-c4b8-4ffe-b8c8-2e5083fa1527 | 9 | public int synthesis(Packet op){
Info vi=vd.vi;
// first things first. Make sure decode is ready
opb.readinit(op.packet_base, op.packet, op.bytes);
// Check the packet type
if(opb.read(1)!=0){
// Oops. This is not an audio data packet
return (-1);
}
// read our mode and pre/post windowsize
int _mode=opb.read(vd.modebits);
if(_mode==-1)
return (-1);
mode=_mode;
W=vi.mode_param[mode].blockflag;
if(W!=0){
lW=opb.read(1);
nW=opb.read(1);
if(nW==-1)
return (-1);
}
else{
lW=0;
nW=0;
}
// more setup
granulepos=op.granulepos;
sequence=op.packetno-3; // first block is third packet
eofflag=op.e_o_s;
// alloc pcm passback storage
pcmend=vi.blocksizes[W];
if(pcm.length<vi.channels){
pcm=new float[vi.channels][];
}
for(int i=0; i<vi.channels; i++){
if(pcm[i]==null||pcm[i].length<pcmend){
pcm[i]=new float[pcmend];
}
else{
for(int j=0; j<pcmend; j++){
pcm[i][j]=0;
}
}
}
// unpack_header enforces range checking
int type=vi.map_type[vi.mode_param[mode].mapping];
return (FuncMapping.mapping_P[type].inverse(this, vd.mode[mode]));
} |
cff14744-11ab-4d4c-9dee-3adcce06ab97 | 6 | public static int populateObjects(byte[] data, int offset, List dsftBinSpriteSetList, int entryCount, Class dsftBinSpriteClass)
{
Number recordSizeNumber = null;
try
{
Method getStaticRecordSizeMethod = dsftBinSpriteClass.getMethod("getStaticRecordSize", null);
recordSizeNumber = (Number)getStaticRecordSizeMethod.invoke(dsftBinSpriteClass, null);
}
catch (SecurityException exception)
{
throw new RuntimeException(exception);
}
catch (NoSuchMethodException exception)
{
throw new RuntimeException(exception);
}
catch (IllegalArgumentException exception)
{
throw new RuntimeException(exception);
}
catch (IllegalAccessException exception)
{
throw new RuntimeException(exception);
}
catch (InvocationTargetException exception)
{
throw new RuntimeException(exception);
}
int dsftEntryCount = 0;
int endOfData = (8 + (entryCount * recordSizeNumber.intValue()));
while(offset < endOfData)
{
DsftBinSpriteSet dsftBinSpriteSet = new DsftBinSpriteSet(dsftBinSpriteClass);
offset = dsftBinSpriteSet.initialize(data, offset);
dsftBinSpriteSetList.add(dsftBinSpriteSet);
dsftEntryCount += dsftBinSpriteSet.getDsftBinSpriteArray().length;
}
return offset;
} |
44d868e0-2eae-4842-b265-d094cb3d6eae | 6 | private void drawGridlines(Graphics2D g2)
{
Rectangle curClip = g2.getClip().getBounds();
int top = getInsets().top, left = getInsets().left;
int miny = Math.max(0, (curClip.y - top) / (cellSize + 1)) * (cellSize + 1) + top;
int minx = Math.max(0, (curClip.x - left) / (cellSize + 1)) * (cellSize + 1) + left;
int maxy = Math.min(numRows,
(curClip.y + curClip.height - top + cellSize) / (cellSize + 1))
* (cellSize + 1) + top;
int maxx = Math.min(numCols,
(curClip.x + curClip.width - left + cellSize) / (cellSize + 1))
* (cellSize + 1) + left;
g2.setColor(Color.GRAY);
for (int y = miny; y <= maxy; y += cellSize + 1)
for (int x = minx; x <= maxx; x += cellSize + 1)
{
Location loc = locationForPoint(
new Point(x + cellSize / 2, y + cellSize / 2));
if (loc != null && !grid.isValid(loc))
g2.fillRect(x + 1, y + 1, cellSize, cellSize);
}
g2.setColor(Color.BLACK);
for (int y = miny; y <= maxy; y += cellSize + 1)
// draw horizontal lines
g2.drawLine(minx, y, maxx, y);
for (int x = minx; x <= maxx; x += cellSize + 1)
// draw vertical lines
g2.drawLine(x, miny, x, maxy);
} |
42da27ed-41aa-4ebe-905b-2da12c5438fe | 3 | public static void checkJMeterVersion() {
String[] currentVersion = StringUtils.split(Utils.getJmeterVersion(), ".");
String[] baseVersion = StringUtils.split("2.5", ".");
if (currentVersion[0].equals(baseVersion[0])) {
if (Integer.valueOf(currentVersion[1]) < Integer.valueOf(baseVersion[1])) {
if (JMeter.isNonGUI()) {
BmLog.error("Blazemeter Listener won't work with " + Utils.getJmeterVersion() + " version of JMeter. Please, update Jmeter to 2.5 or later.");
} else {
JMeterUtils.reportErrorToUser("Blazemeter Listener won't work with " + Utils.getJmeterVersion() + " version of JMeter. Please, update Jmeter to 2.5 or later.",
"Invalid JMeter version");
}
}
}
} |
1204e05c-6002-4d91-9454-43985e1ec8af | 2 | public void ignoreRecord(GedcomRecord rootRecord, GedcomReader reader)
throws IOException, GedcomReaderException {
int rootLevel = rootRecord.getLevel();
for (GedcomRecord record = reader.nextRecord(); record != null; record = reader
.nextRecord()) {
int level = record.getLevel();
if (level <= rootLevel) {
reader.pushback();
return;
}
}
} |
dc0ae0b4-10f9-40a0-8f62-5f53d1188d60 | 8 | protected void func_72612_a(boolean par1)
{
int i = 0;
Iterator iterator = field_72616_e.iterator();
do
{
if (!iterator.hasNext())
{
break;
}
DatagramSocket datagramsocket = (DatagramSocket)iterator.next();
if (func_72604_a(datagramsocket, false))
{
i++;
}
}
while (true);
field_72616_e.clear();
iterator = field_72614_f.iterator();
do
{
if (!iterator.hasNext())
{
break;
}
ServerSocket serversocket = (ServerSocket)iterator.next();
if (func_72605_a(serversocket, false))
{
i++;
}
}
while (true);
field_72614_f.clear();
if (par1 && 0 < i)
{
func_72606_c((new StringBuilder()).append("Force closed ").append(i).append(" sockets").toString());
}
} |
3fd5e82e-e545-44dc-a472-f355bd8c6ce6 | 4 | public void update(Level level, int x, int y, int z, Random rand) {
if(!level.growTrees) {
int var6 = level.getTile(x, y - 1, z);
if(!level.isLit(x, y, z) || var6 != Block.DIRT.id && var6 != Block.GRASS.id) {
level.setTile(x, y, z, 0);
}
}
} |
9f487a09-0579-44bd-be12-34f9219d5c84 | 0 | public void remove()
{
q.clear();
} |
872e59de-9d6e-4972-b142-0e1d0b7f4405 | 8 | private boolean isModifierKey(int key) {
switch(key) {
case Keyboard.KEY_LSHIFT:
case Keyboard.KEY_RSHIFT:
case Keyboard.KEY_RIGHT:
case Keyboard.KEY_LEFT:
case Keyboard.KEY_DOWN:
case Keyboard.KEY_UP:
case Keyboard.KEY_LCONTROL:
case Keyboard.KEY_RCONTROL:
return true;
default:
return false;
}
} |
c5c00b6f-e8fa-47d8-9815-a44d32a69e06 | 9 | public ArrayList<Query> getQueries(String queryFileName) {
ArrayList<Query> queryList = new ArrayList<Query>();
Query query = new Query();
FileReader fileReader;
try {
fileReader = new FileReader(queryFileName);
BufferedReader reader = new BufferedReader(fileReader);
String line;
try {
while ((line = reader.readLine()) != null) {
StringTokenizer tokenizer = new StringTokenizer(line);
long featureId = Long.parseLong(tokenizer.nextToken());
int weight = Integer.parseInt(tokenizer.nextToken());
if (!(featureId == 0 && weight == 0)) {
if (dictionary.map.containsKey(featureId))
query.addTerm(featureId, weight);
} else {
queryList.add(query);
query = new Query();
}
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
ArrayList<Query> returnList;
if (SORT_QUERIES) {
// Send back the shortest queries
Collections.sort(queryList);
returnList = new ArrayList<Query>(queryList.subList(0, NUM_QUERIES));
} else if (REVERSE_SORT_QUERIES) {
// Send back the longest queries
Collections.sort(queryList, Collections.reverseOrder());
returnList = new ArrayList<Query>(queryList.subList(0, NUM_QUERIES));
} else {
// Send back random queries
returnList = new ArrayList<Query>();
for (int i = 0; i < queryIndices.length; i++) {
returnList.add(queryList.get(queryIndices[i]));
}
}
return returnList;
} |
a9a76e93-c5a4-4380-aac1-c5eef530cc4d | 4 | public JSONWriter key(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null key.");
}
if (this.mode == 'k') {
try {
stack[top - 1].putOnce(string, Boolean.TRUE);
if (this.comma) {
this.writer.write(',');
}
this.writer.write(JSONObject.quote(string));
this.writer.write(':');
this.comma = false;
this.mode = 'o';
return this;
} catch (IOException e) {
throw new JSONException(e);
}
}
throw new JSONException("Misplaced key.");
} |
1fd3dc67-57eb-4bec-8f29-71b90414b5a9 | 0 | public void setY2Coordinate(double y)
{
y2Coordinate=y;
} |
4e6a9b6e-5992-404e-b78b-d4cd230b7474 | 4 | public JSONWriter key(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null key.");
}
if (this.mode == 'k') {
try {
this.stack[this.top - 1].putOnce(string, Boolean.TRUE);
if (this.comma) {
this.writer.write(',');
}
this.writer.write(JSONObject.quote(string));
this.writer.write(':');
this.comma = false;
this.mode = 'o';
return this;
} catch (IOException e) {
throw new JSONException(e);
}
}
throw new JSONException("Misplaced key.");
} |
bb84728f-aa61-4bc0-a5ac-2f2f20efccd8 | 7 | private void initDataLayout(File file) throws IOException {
if (file.exists()) { // Load the data formats from the file
byte[] buffer = new byte[32];
mappedByteBuffer.get(buffer);
ByteBuffer bbuffer = ByteBuffer.wrap(buffer);
int index;
if ((index = indexOf(FLOAT_COOKIE_BIG_ENDIAN, buffer)) != -1) {
order = ByteOrder.BIG_ENDIAN;
}
else if ((index = indexOf(FLOAT_COOKIE_LITTLE_ENDIAN, buffer))
!= -1) {
order = ByteOrder.LITTLE_ENDIAN;
}
else {
throw new IOException("Invalid RRD file");
}
mappedByteBuffer.order(order);
bbuffer.order(order);
switch (index) {
case 12:
alignment = 4;
break;
case 16:
alignment = 8;
break;
default:
throw new RuntimeException("Unsupported architecture");
}
bbuffer.position(index + 8);
//We cannot have dsCount && rracount == 0
//If one is 0, it's a 64 bits rrd
int int1 = bbuffer.getInt(); //Should be dsCount in ILP32
int int2 = bbuffer.getInt(); //Should be rraCount in ILP32
if(int1 == 0 || int2 ==0) {
longSize = 8;
}
}
else { // Default to data formats for this hardware architecture
}
// Reset file pointer to start of file
mappedByteBuffer.rewind();
} |
2bcfde19-d528-4032-b5d6-6f0304d07b7d | 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(DaftarBuku.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DaftarBuku.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DaftarBuku.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DaftarBuku.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the dialog
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
DaftarBuku dialog = new DaftarBuku(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} |
ed72fe62-732e-44e1-9c31-8c439009e587 | 1 | @Override
public void actionPerformed(ActionEvent event) {
Duplicatable duplicatable = getTarget(Duplicatable.class);
if (duplicatable != null) {
duplicatable.duplicateSelection();
}
} |
7e1092f9-29c3-45d9-938c-b1ca3e861e44 | 2 | @Override
public void startElement( String uri, String localName, String name,
Attributes attributes ) throws SAXException {
XElement element = new XElement( name );
if( this.element == null ){
this.element = element;
}
else{
stack.getFirst().addElement( element );
}
stack.addFirst( element );
// read the attributes
for( int i = 0, n = attributes.getLength(); i<n; i++ ){
XAttribute attr = new XAttribute( attributes.getQName( i ));
attr.setString( attributes.getValue( i ));
element.addAttribute( attr );
}
} |
aeb69a8a-90bd-4cba-9b8b-91f87edf156f | 4 | public ConfigurationHolder getExactRegion(String world, String name) {
for (ConfigurationHolder holder : this) {
if (holder.getType() == ConfigurationType.REGION)
if (holder.getWorld().equalsIgnoreCase(world))
if (holder.getName().equalsIgnoreCase(name))
return holder;
}
return null;
} |
2d117476-7dbf-4d5b-884f-7c1020747d39 | 9 | private static List<List<Livraison>> kmeans(List<Livraison> livraisons, int k)
{
List<List<Livraison>> clusters = new ArrayList<List<Livraison>>();
for(int i = 0 ; i < k ; i++)
{
clusters.add(new ArrayList<Livraison>());
}
List<Double> centroidX = new ArrayList<Double>();
List<Double> centroidY = new ArrayList<Double>();
Double eps = Double.POSITIVE_INFINITY;
List<Livraison> tempLiv = new ArrayList<Livraison>(livraisons);
for(int i = 0 ; i < k ; i++)
{
int index = (int)(Math.random()*tempLiv.size());
Livraison l = tempLiv.get(index);
centroidX.add((double)l.getAdresse().getX());
centroidY.add((double)l.getAdresse().getY());
tempLiv.remove(index);
}
while(eps > 1.0)
{
for(int i = 0 ; i < k ; i++)
{
clusters.get(i).clear();
}
Double delta = 0.0;
//Clusters
for(Livraison l : livraisons)
{
Double lowestDistance = Double.POSITIVE_INFINITY;
int closestCentroid = -1;
for(int i = 0 ; i < k ; i++)
{
Double x = l.getAdresse().getX() - centroidX.get(i);
Double y = l.getAdresse().getY() - centroidY.get(i);
Double distance = Math.sqrt(x*x + y*y);
if(distance < lowestDistance)
{
lowestDistance = distance;
closestCentroid = i;
}
}
clusters.get(closestCentroid).add(l);
}
//Recompute centroid
for(int i = 0 ; i < k ; i++)
{
Double averageX = 0.0;
Double averageY = 0.0;
for(Livraison l : clusters.get(i))
{
averageX += l.getAdresse().getX();
averageY += l.getAdresse().getY();
}
averageX /= clusters.get(i).size();
averageY /= clusters.get(i).size();
delta += averageX-centroidX.get(i) + averageY-centroidY.get(i);
centroidX.set(i, averageX);
centroidY.set(i,averageY);
}
eps = delta;
}
return clusters;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.