method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
78966d37-91ae-4e0e-92a8-d75e803c103a | 7 | public static void renderAllTiles(int z, int x, int y, int z_start, int z_stop) throws IOException {
// find the projected bounds of this tile in osm projection
double[] tile = TileToMercBounds.tileToMercBounds(z, x, y);
// convert the bounds to a jts geometry
Envelope envolope = new Envelope(tile[0], tile[2], tile[1], tile[3]);
Geometry bbox = gf.toGeometry(envolope);
// see if our tile intersects with any of the polygons for the regions to render
boolean intersects = false;
if (imageryBoundaries == null) {
intersects = true;
}else{
for (Geometry i : imageryBoundaries) {
intersects = intersects || i.intersects(bbox);
if (intersects)
break; // no need to check the rest of the candidates if we already have a match
}
}
if (intersects) {
if (z >= z_start) {
tileListWriter.write(z + "/" + x + "/" + y + "\n");
tileCount++;
}
// move on to a higher zoom level
if (z < z_stop) {
renderAllTiles(z + 1, x*2, y*2, z_start, z_stop);
renderAllTiles(z + 1, x*2 + 1, y*2, z_start, z_stop);
renderAllTiles(z + 1, x*2, y*2 + 1, z_start, z_stop);
renderAllTiles(z + 1, x*2 + 1, y*2 + 1, z_start, z_stop);
}
}
return;
} |
c5f0d699-35de-4345-a49e-4b38eb504a37 | 0 | public void setFecha(GregorianCalendar fecha) {
this.fecha = fecha;
} |
6b08ed38-1f0a-49f7-8e20-37e5418c8521 | 6 | public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
} |
893b830e-4af0-42e7-aa96-1db6676a49e5 | 4 | @Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()){
case(KeyEvent.VK_W) : rocket.player.buttom[0] = true; break;
case(KeyEvent.VK_A) : rocket.player.buttom[1] = true; break;
case(KeyEvent.VK_S) : rocket.player.buttom[2] = true; break;
case(KeyEvent.VK_D) : rocket.player.buttom[3] = true; break;
}
} |
1d73001a-de52-44dd-9843-45e074ac969a | 8 | public void calculateExecTime() {
double newExeTime;
double newCost;
dEval = 0;
dTime = 0;
dCost = 0;
for (int i = 0; i < iClass; i++) {
newExeTime = 0;
print("Cost[" + i + "]");
for (int j = 0; j < iSite; j++) {
if (dmAlloc[i][j] != -1) {
if (dmAlloc[i][j] < 1) {
newExeTime = 0;
} else {
newExeTime = (dmDist[i][j] * dmPrediction[i][j]) / dmAlloc[i][j];
if (newExeTime > dDeadline + 1) {
newExeTime = Double.MAX_VALUE;
}
}
}
if (newExeTime > dDeadline + 1) {
newCost = Double.MAX_VALUE;
} else {
newCost = dmDist[i][j] * dmPrediction[i][j] * daPrice[j];
}
dTime += dmDist[i][j] * dmPrediction[i][j];
dCost += newCost;
dEval += dmCost[i][j] - newCost;
dmExeTime[i][j] = newExeTime;
dmCost[i][j] = newCost;
print(Math.round(dmCost[i][j]) + ", ");
}
println();
}
for (int i = 0; i < iClass; i++) {
print("Time[" + i + "]");
for (int j = 0; j < iSite; j++) {
print(Math.round(dmExeTime[i][j]) + ", ");
}
println();
}
dFinalMakespan = dDeadline;
println("My Time = " + dTime);
println("My Cost = " + dCost);
} |
a3d179cc-3d37-49ad-bc15-62d9db68c030 | 4 | private void checkAvailabilityButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkAvailabilityButtonActionPerformed
Date checkInDate = checkIn.getDate();
Date checkOutDate = checkOut.getDate();
if (checkInDate != null && checkOutDate != null && !checkInDate.equals(checkOutDate) && checkOutDate.after(checkInDate)) { // checker at begge datoer er valgt, og at checkOut dato er efter checkIn dato.
refreshRoomTable(roomTableModel, checkInDate, checkOutDate);
}
else {
jOptionPane.showMessageDialog(this, "You must choose a check-in and a check-out date. Check-in date must be before check-out date.", "Invalid dates!", jOptionPane.WARNING_MESSAGE);
}
}//GEN-LAST:event_checkAvailabilityButtonActionPerformed |
4485aa58-6f4d-49cb-b1e1-d0ae0b306d26 | 2 | private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
try {
List<Pays> pp1 = RequetesPays.selectPays();
for (Pays pays : pp1) {
jComboBoxPays.addItem(pays);
}
} catch (SQLException ex) {
Logger.getLogger(VueVille.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_formWindowOpened |
601e954c-12d3-4022-96d6-7f19646b1cc2 | 5 | public Bullet handleInput(Camera camera) {
Bullet bullet = null;
if (Gdx.input.isKeyPressed(scheme.Left)) {
player.moveLeft();
}
else if (Gdx.input.isKeyPressed(scheme.Right)) {
player.moveRight();
}
else {
player.stopMoving();
}
if (Gdx.input.isKeyPressed(scheme.Jump)) {
player.jump();
}
debugFiringLine = null;
if (Gdx.input.isTouched()) {
Vector3 touchPos = new Vector3();
touchPos.set(
Gdx.input.getX(),
camera.height - Gdx.input.getY(),
0);
debugFiringLine = new Vector2[2];
debugFiringLine[0] = player.getPosition();
debugFiringLine[1] = new Vector2(touchPos.x, touchPos.y);
if (player.canFire()) {
bullet = player.fire(new Vector2(touchPos.x, touchPos.y));
}
}
return bullet;
} |
10e0dafe-bfa1-4d9a-82ea-c85a8d99ea04 | 1 | private void checkForUpdates_settingsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkForUpdates_settingsButtonActionPerformed
if (debug)
logger.log(Level.DEBUG, "Setting preference \"checkForUpdates\" from " + settings.checkForUpdatesOnStartup() + " to " + checkForUpdates_settingsButton.isSelected());
settings.setCheckForUpdatesOnStartup(checkForUpdates_settingsButton.isSelected());
}//GEN-LAST:event_checkForUpdates_settingsButtonActionPerformed |
333ff17f-6bee-4b39-8019-bb014f4408de | 5 | @SuppressWarnings("deprecation")
void listen(Function<String> listener) {
if (socket == null) {
println("Cannot operate with a null socket");
return;
} else if (listener == null) {
println("The listener needs to be set");
return;
}
DataInputStream input;
String tmp;
try {
input = new DataInputStream(socket.getInputStream());
while ((tmp = input.readLine()) != null) {
if (listener.apply(tmp))
break;
}
} catch (IOException e) {
println("An exception has occured while reading from the socket");
}
} |
1bb86b98-f314-45d8-82f6-08e980b2c634 | 2 | @Test
public void insertAndDeleteTest(){
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++){
heap.insert(i);
}
for (int i = 0; i < 1000000; i++){
assertEquals(heap.extract_min().value, i);
}
long end = System.currentTimeMillis();
System.out.println("Time spent adding and deleteting 1000000: " + (end-start*1.0) + "ms");
} |
10912b67-9a2a-46c4-ab3f-fca3219aed25 | 0 | public Collection<BookingEntity> getBooking() {
return booking;
} |
5eee64b4-3654-4456-aacf-bb196c637b23 | 7 | public static boolean isPutChessmen(final ChessBoardEntity b, final ChessmenEntity c, final PositionEntity p) {
boolean result = false;
do {
if (null == c || null == p) {
break;
}
if (!c.isPlayer()) {
// ̋łȂłB
break;
}
if (c.isBoard()) {
// Տ̋łB
break;
}
if (isChessmen(b, p)) {
// ɋ݂܂B
break;
}
if (is2Pawn(b, c, p)) {
// 2
break;
}
result = true;
} while (false);
return result;
} |
72958e04-30e8-4946-821c-1c0036380944 | 7 | public static void memberOfEvaluator(Proposition self) {
{ Stella_Object member = Logic.valueOf((self.arguments.theArray)[0]);
Stella_Object collection = Logic.valueOf((self.arguments.theArray)[1]);
if (Proposition.trueP(self)) {
if (Stella_Object.isaP(collection, Logic.SGT_LOGIC_DESCRIPTION) &&
(Stella_Object.isaP(member, Logic.SGT_LOGIC_LOGIC_OBJECT) &&
(!Description.namedDescriptionP(((Description)(collection)))))) {
Logic.inheritUnnamedDescription(((LogicObject)(member)), ((Description)(collection)), Proposition.defaultTrueP(self));
}
if (Logic.logicalCollectionP(collection)) {
{ Object old$ReversepolarityP$000 = Logic.$REVERSEPOLARITYp$.get();
try {
Native.setBooleanSpecial(Logic.$REVERSEPOLARITYp$, true);
if (Logic.memberOfCollectionP(member, collection) &&
(!Logic.skolemP(member))) {
Proposition.signalTruthValueClash(self);
}
} finally {
Logic.$REVERSEPOLARITYp$.set(old$ReversepolarityP$000);
}
}
}
}
}
} |
ae616e58-6b26-4dfd-aca8-dc9c7577dc70 | 3 | @Test
public void resolve() {
int days = daysOfYear(1900);
int count = 0;
for (int year = 1901; year <= 2000; year++) {
for (int mon = 1; mon <= 12; mon++) {
if (days % 7 == 0) {
count++;
}
days += getDaysOfMonth(year, mon);
}
}
print(count);
} |
077e08f3-b5c6-4845-b54d-c285250e465f | 4 | @SuppressWarnings("static-access")
public void read(Buffer buf) throws IOException {
// Check if we've finished all the frames.
if (nextImage >= images.size()) {
// We are done. Set EndOfMedia.
System.err.println("Done reading all images.");
buf.setEOM(true);
buf.setOffset(0);
buf.setLength(0);
ended = true;
return;
}
String imageFile = (String)images.get(nextImage);
nextImage++;
//System.err.println(" - reading image file: " + imageFile);
// Open a random access file for the next image.
RandomAccessFile raFile;
raFile = new RandomAccessFile(imageFile, "r");
byte data[] = null;
// Check the input buffer type & size.
if (buf.getData() instanceof byte[])
data = (byte[])buf.getData();
// Check to see the given buffer is big enough for the frame.
if (data == null || data.length < raFile.length()) {
data = new byte[(int)raFile.length()];
buf.setData(data);
}
// Read the entire JPEG image from the file.
raFile.readFully(data, 0, (int)raFile.length());
//System.err.println(" read " + raFile.length() + " bytes.");
buf.setOffset(0);
buf.setLength((int)raFile.length());
buf.setFormat(format);
buf.setFlags(buf.getFlags() | buf.FLAG_KEY_FRAME);
buf.setTimeStamp(frame++ * Time.ONE_SECOND/fRate); /*AVI*/
// Close the random access file.
raFile.close();
} |
f10af4e1-a259-4529-a26d-031287563206 | 0 | public static void main(String[] args) {
SpaceShipDelegation protector = new SpaceShipDelegation("NSEA Protector");
protector.forward(100);
} |
3868b661-5f50-4c4f-b399-839a53d9de22 | 8 | public String toString() {
StringBuilder sb = new StringBuilder();
long ms = this.millis;
int ns = this.nanos;
if (ms < 0 || (ms == 0 && ns < 0)) {
sb.append("-");
ms *= -1;
ns *= -1;
}
if (ms > Duration.DAY) {
ms = extract(ms, Duration.DAY, "d", sb);
}
if (ms > Duration.HOUR) {
ms = extract(ms, Duration.HOUR, "h", sb);
}
if (ms > Duration.MINUTE) {
ms = extract(ms, Duration.MINUTE, "m", sb);
}
if (ms > Duration.SECOND) {
// Findbugs complains of "dead store" if assigned to ms here
extract(ms, Duration.SECOND, "s", sb);
}
if (ns > 0) {
sb.append(ns);
sb.append("n");
}
return sb.toString();
} |
b0195af0-821c-4514-a0ac-09d95fc070a7 | 4 | public void recruitHero()
{
if (castle.getHero() != null && castle.getHero().isInCastle(castle)) {
QMessageBox.warning(this, "Nie można wynająć bohatera", "W tym zamku znajduje się już inny bohater");
} else if (player.getResource(core.ResourceType.GOLD) < 2500) {
QMessageBox.warning(this, "Nie można wynająć bohatera", "Wynajęcie bohatera kosztuje 2500 złota");
} else {
if (QMessageBox.question(this, "Wynajęcie bohatera", "Czy chcesz wynająć bohatera za 2500 złota?",
new StandardButtons(StandardButton.Yes, StandardButton.No)) != StandardButton.Yes) {
return;
}
Hero hero = new Hero(Names.name(), castle.getType());
addNewHero(hero);
player.addResource(core.ResourceType.GOLD, -2500);
updateResources();
//QMessageBox.warning(this, "Wynajęto bohatera", "Wynajęto bohatera");
}
} |
dc4ead83-be26-42b7-9f45-3f00dd41782a | 0 | public Forme getForme() {
return forme;
} |
33565c77-e124-48b4-a57c-8c763b9f04cc | 7 | final int[] method3042(int i, int i_13_) {
anInt9457++;
int[] is = ((Class348_Sub40) this).aClass191_7032.method1433(0, i);
if (i_13_ != 255)
method3148(true);
if (((Class191) ((Class348_Sub40) this).aClass191_7032).aBoolean2570) {
int i_14_ = 1 + (anInt9463 + anInt9463);
int i_15_ = 65536 / i_14_;
int i_16_ = 1 + anInt9466 + anInt9466;
int i_17_ = 65536 / i_16_;
int[][] is_18_ = new int[i_14_][];
for (int i_19_ = -anInt9463 + i; i - -anInt9463 >= i_19_;
i_19_++) {
int[] is_20_ = this.method3048(Class299_Sub2.anInt6325 & i_19_,
633706337, 0);
int[] is_21_ = new int[Class348_Sub40_Sub6.anInt9139];
int i_22_ = 0;
for (int i_23_ = -anInt9466; anInt9466 >= i_23_; i_23_++)
i_22_ += is_20_[i_23_ & Class239_Sub22.anInt6076];
int i_24_ = 0;
while (i_24_ < Class348_Sub40_Sub6.anInt9139) {
is_21_[i_24_] = i_17_ * i_22_ >> 1257667792;
i_22_ -= (is_20_
[-anInt9466 + i_24_ & Class239_Sub22.anInt6076]);
i_24_++;
i_22_ += (is_20_
[i_24_ + anInt9466 & Class239_Sub22.anInt6076]);
}
is_18_[-i + (i_19_ + anInt9463)] = is_21_;
}
for (int i_25_ = 0; Class348_Sub40_Sub6.anInt9139 > i_25_;
i_25_++) {
int i_26_ = 0;
for (int i_27_ = 0;
(i_27_ ^ 0xffffffff) > (i_14_ ^ 0xffffffff); i_27_++)
i_26_ += is_18_[i_27_][i_25_];
is[i_25_] = i_26_ * i_15_ >> 408717616;
}
}
return is;
} |
8a8fd034-c3e5-4cfa-88b5-3a1a378d5509 | 4 | public void rotate(boolean clockwise) {
int turns;
if (clockwise)
turns = 1;
else
turns = 3;
for (int k = 1; k <= turns; k++) {
boolean sec[][] = new boolean[getHeight()][getWidth()];
for (int i = 0; i < getHeight(); i++) {
for (int j = getWidth() - 1; j >= 0; j--) {
sec[i][getWidth() - 1 - j] = matrix[j][i];
}
}
matrix = sec;
}
} |
0e085490-d318-41c0-a741-05adeb3f3713 | 6 | private void reduceUnits(){
newTimeSecond = totalSeconds;
if ((newTimeSecond <= 60) || (newTimeSecond >= 60)){
newTimeMinute = newTimeSecond / 60;
newTimeSecond = newTimeSecond % 60;
}
if ((newTimeMinute <= 60) || (newTimeMinute >= 60)){
newTimeHour = newTimeMinute / 60;
newTimeMinute = newTimeMinute % 60;
}
if ((newTimeHour <= 24) || (newTimeHour >= 24)){
newTimeDay = newTimeHour / 24;
newTimeHour = newTimeHour % 24;
}
} |
bf97e8a7-a104-4eb6-9118-9fe0704b7332 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
User other = (User) obj;
if (groups == null) {
if (other.groups != null) {
return false;
}
} else if (!groups.equals(other.groups)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
} |
f57ddf42-2b3c-4a0c-bc43-7173ccc3f3f5 | 4 | protected static void mult_INT_PACK_Data(WritableRaster wr) {
// System.out.println("Multiply Int: " + wr);
SinglePixelPackedSampleModel sppsm;
sppsm = (SinglePixelPackedSampleModel) wr.getSampleModel();
final int width = wr.getWidth();
final int scanStride = sppsm.getScanlineStride();
DataBufferInt db = (DataBufferInt) wr.getDataBuffer();
final int base
= (db.getOffset() +
sppsm.getOffset(wr.getMinX() - wr.getSampleModelTranslateX(),
wr.getMinY() - wr.getSampleModelTranslateY()));
// Access the pixel data array
final int[] pixels = db.getBankData()[0];
for (int y = 0; y < wr.getHeight(); y++) {
int sp = base + y * scanStride;
final int end = sp + width;
while (sp < end) {
int pixel = pixels[sp];
int a = pixel >>> 24;
if ((a >= 0) && (a < 255)) { // this does NOT include a == 255 (0xff) !
pixels[sp] = ((a << 24) |
((((pixel & 0xFF0000) * a) >> 8) & 0xFF0000) |
((((pixel & 0x00FF00) * a) >> 8) & 0x00FF00) |
((((pixel & 0x0000FF) * a) >> 8) & 0x0000FF));
}
sp++;
}
}
} |
b436de13-14c2-47f1-9231-8769d7ab6db6 | 3 | void test() throws InterruptedException,
ExecutionException{
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<Future<String>>(); //Future 相当于是用来存放Executor执行的结果的一种容器
for (int i = 0; i < 10; i++) {
results.add(exec.submit(new TaskWithResult(i)));
}
for (Future<String> fs : results) {
if (fs.isDone()) {
System.out.println(fs.get());
} else {
System.out.println("Future result is not yet complete");
}
}
exec.shutdown();
} |
7f6e9f25-1a99-45cc-b0b6-30dc92ecb97f | 7 | public void annuler() throws InvalidArgumentException {
if (prixReserveAtteint() && etatEnchere == EtatEnchere.PUBLIEE)
throw new InvalidArgumentException(
"Prix de réserve atteint. Annulation impossible.");
else if (etatEnchere == EtatEnchere.TERMINEE)
throw new InvalidArgumentException(
"Enchère terminée. Annulation impossible.");
else if (!prixReserveAtteint() && etatEnchere == EtatEnchere.PUBLIEE){
etatEnchere = EtatEnchere.ANNULEE;
alerteTous("Le vendeur vient d'annuler l'enchère : "+this.objet.getNom());
}
else if (etatEnchere != EtatEnchere.PUBLIEE
&& etatEnchere != EtatEnchere.TERMINEE){
etatEnchere = EtatEnchere.ANNULEE;
alerteTous("Le vendeur vient d'annuler l'enchère : "+this.objet.getNom());
}
else
throw new InvalidArgumentException(
"Enchère terminée. Annulation impossible.");
} |
078a30ab-7b60-4c0b-b5f9-96484cb779a8 | 2 | public void run() {
try {
File f = new File ( filename );
MediaLocator locator = new MediaLocator ( f.toURI().toURL());
player = Manager.createPlayer ( locator );
player.addControllerListener(new ControllerListener() {
public void controllerUpdate(ControllerEvent event) {
if (event instanceof EndOfMediaEvent) {
player.setMediaTime(Player.RESET);
player.realize();
player.start();
}
}
});
player.realize();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
} |
729b9139-9616-40bc-87f9-6d13f4a32ff6 | 0 | public T getFirst() { return first; } |
12b69f10-4a24-4338-99b2-0dcda1659144 | 0 | public void enterEnvironmentRecord(String identifier, int offset) {
environmentStack.peek().putSymbolTable(identifier, offset);
} |
7484c375-a523-4aab-ae87-898a4a0e8b0a | 3 | private boolean isControlWord(String line) {
return line != null && (line.length() >= 2 && (line.charAt(0) == '#' && line.charAt(1) != ' '));
} |
610c7c49-1726-4bfe-9c44-936b474d59f1 | 1 | public static void main(String[] args) throws FileNotFoundException {
File videoOut = new File("data/video1_out.mp4");
File videoIn = new File("data/video1.mp4");
// Vytvorim si testovacie video
// List<VideoSection> louderSections = new ArrayList<>();
// louderSections.add(new VideoSection(45L, 120L, TimeUnit.SECONDS));
// louderSections.add(new VideoSection(160L, 200L, TimeUnit.SECONDS));
// new VolumeRandomizer(louderSections, 0.2).randomize(videoIn, videoOut);
// System.out.println("LouderSections:");
// for (VideoSection videoSection : louderSections) {
// System.out.println("Start: " + videoSection.getStart() + " End:" + videoSection.getEnd());
// }
//
// // Vykreslim grafy
//new AmplitudeGraph(videoOut).show();
//new AmplitudeMaxesGraph(videoOut, 5).show();
// Detekcia hlasnejsich casti
VolumeAdDetector volumeAdDetector = new VolumeAdDetector(videoOut);
List<VideoSection> louderSectionsFound = volumeAdDetector.run();
System.out.println("Video sections found:");
for (VideoSection videoSection : louderSectionsFound) {
System.out.println(videoSection.toString());
}
} |
1e1cfcb7-444e-4509-ba98-44ee9f319bdb | 3 | public void printCombs(ArrayList<ArrayList<Integer>> comb) {
System.out.println("[");
for (int i = 0; i < comb.size(); i++) {
ArrayList<Integer> curComb = comb.get(i);
System.out.print("[");
for (int j = 0; j < curComb.size(); j++) {
if (j == curComb.size() - 1)
System.out.print(curComb.get(j));
else
System.out.print(curComb.get(j) + ",");
}
System.out.println("]");
}
System.out.println("]");
} |
b2d057be-427d-44fc-9fc5-f422f5849d47 | 5 | public int addEntry(Score newScore) {
lastIndex++; //update the index of the last entry in the list
//System.out.println("lastIndex: "+lastIndex);
// check if list's size needs to be increase
if (isFull())
doubleArraySize();
boolean isHighest = false;
boolean done = false;
int currentIndex = lastIndex - 1;
while(!done && currentIndex >= 0) {
//System.out.println("curentIndex: " + currentIndex);
if (scoreList[currentIndex].compareTo(newScore) < 0)
scoreList[currentIndex + 1] = scoreList[currentIndex];
else {
scoreList[currentIndex + 1] = newScore;
lastScoreIndex = currentIndex + 1;
done = true;
}
currentIndex--;
}
// the new score has not been added to the list: it's a new record!
if (!done) {
scoreList[0] = newScore;
lastScoreIndex = 0;
}
return lastScoreIndex;
} |
858255e3-f403-4dc6-b8e7-15a12b6f1f8f | 7 | public AbstractMainframe(Controlador controlador) {
super(controlador);
panel.setLayout(new FlowLayout(FlowLayout.LEADING));
desconectar.setEnabled(false);
frame.setResizable(false);
/* False para iconified, True para o resto */
frame.addWindowStateListener(e -> frame.setVisible(e.getNewState() != JFrame.ICONIFIED));
icone.addActionListener(e -> exibir.doClick());
exibir.addActionListener(e -> {
frame.setVisible(true);
frame.setExtendedState(JFrame.NORMAL);
});
icone.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.setLocation(e.getPoint());
popup.setInvoker(popup);
popup.setVisible(true);
}
}
});
sair.addActionListener(e -> {
destroy();
terminate();
});
desconectar.addActionListener(e -> {
SwingUtilities.invokeLater(() -> {
SocketInformation info = lista.getSelectedValue();
if (info == null) return;
if (desconectar.getText().equals(AbstractMainframe.REMOVE)) {
controlador.removerSocket(info);
try {
modelo.removeElement(info);
} catch (NullPointerException e1) {
/* Erro no Swing? Não fazer nada */
}
desconectar.setEnabled(false);
} else {
controlador.fecharSocket(info);
}
});
});
lista.addListSelectionListener(e -> {
if (!e.getValueIsAdjusting()) {
SocketInformation info = lista.getSelectedValue();
boolean fechado = info == null ? true : info.isClosed();
changeActions(fechado);
}
});
try {
tray.add(icone);
popup.add(exibir);
popup.addSeparator();
popup.add(sair);
} catch (AWTException e1) {
e1.printStackTrace();
}
} |
a598a375-5ccb-4fc5-a9f8-27a159129654 | 1 | public void fillDeclarables(Collection used) {
for (int i = 0; i < subExpressions.length; i++)
subExpressions[i].fillDeclarables(used);
} |
da4f51cf-06a2-4cc9-b9a0-1ad17454868c | 7 | public boolean setNext(Unit unit) {
if (predicate.obtains(unit)) { // Of course, it has to be valid...
Unit first = (units.isEmpty()) ? null : units.get(0);
while (!units.isEmpty()) {
if (units.get(0) == unit) return true;
units.remove(0);
}
reset();
while (!units.isEmpty() && units.get(0) != first) {
if (units.get(0) == unit) return true;
units.remove(0);
}
}
return false;
} |
6f782743-0b94-459d-a3fa-7e6225d49bfe | 9 | private void addDiagonalCell (java.util.List<Point> adjoiningCells, Point adjoiningCell, Point parentCell) {
if (isCellOutOfField(adjoiningCell) || isCellWall(adjoiningCell) || isCellClosed(adjoiningCell) || isCellOpened(adjoiningCell)) {
return;
}
java.util.List<Point> checkCells = new ArrayList<>();
int dx;
int dy;
if (adjoiningCell.x > parentCell.x) {
dx = 1;
} else {
dx = -1;
}
if (adjoiningCell.y > parentCell.y) {
dy = 1;
} else {
dy = -1;
}
checkCells.add(new Point(parentCell.x + dx, parentCell.y));
checkCells.add(new Point(parentCell.x, parentCell.y + dy));
int wallsCount = 0;
for (Point checkCell : checkCells) {
if (field[checkCell.x][checkCell.y] instanceof Wall) {
wallsCount++;
}
}
if (wallsCount > 0) {
return;
}
adjoiningCells.add(adjoiningCell);
field[adjoiningCell.x][adjoiningCell.y].setParent(parentCell);
} |
9caec7b6-e046-496a-b82c-a88dab740b20 | 8 | private static Object processFunctionResults(final Object binaryOperatorKey,
final Object functionResult)
{
if (binaryOperatorKey.equals(Syntax.OPERATOR_GREATER))
{
return ((Number) functionResult).intValue() == 1 ? Boolean.TRUE
: Boolean.FALSE;
} else if (binaryOperatorKey.equals(Syntax.OPERATOR_GREATER_OR_EQUAL))
{
return ((Number) functionResult).intValue() == -1 ? Boolean.FALSE
: Boolean.TRUE;
} else if (binaryOperatorKey.equals(Syntax.OPERATOR_LESS))
{
return ((Number) functionResult).intValue() == -1 ? Boolean.TRUE
: Boolean.FALSE;
} else if (binaryOperatorKey.equals(Syntax.OPERATOR_LESS_OR_EQUAL))
{
return ((Number) functionResult).intValue() == 1 ? Boolean.FALSE
: Boolean.TRUE;
} else
{
return functionResult;
}
} |
b2b887d9-8144-4cfd-8cfc-d3f08f126d66 | 6 | public boolean canEquip(int slotId, int itemId) {
if (slotId == Equipment.SLOT_CAPE || slotId == Equipment.SLOT_HAT) {
player.getPackets().sendGameMessage(
"You can't remove your team's colours.");
return false;
}
if (slotId == Equipment.SLOT_WEAPON || slotId == Equipment.SLOT_SHIELD) {
int weaponId = player.getEquipment().getWeaponId();
if (weaponId == 4037 || weaponId == 4039) {
player.getPackets().sendGameMessage(
"You can't remove enemy's flag.");
return false;
}
}
return true;
} |
6e73ec31-f352-4da3-8a9a-e9dbf264d66c | 7 | public boolean concatenateAligned(BitOutputStream src) {
int bitsToAdd = src.totalBits - src.totalConsumedBits;
if (bitsToAdd == 0) return true;
if (outBits != src.consumedBits) return false;
if (!ensureSize(bitsToAdd)) return false;
if (outBits == 0) {
System.arraycopy(src.buffer, src.consumedBlurbs, buffer, outBlurbs,
(src.outBlurbs - src.consumedBlurbs + ((src.outBits != 0) ? 1 : 0)));
} else if (outBits + bitsToAdd > BITS_PER_BLURB) {
buffer[outBlurbs] <<= (BITS_PER_BLURB - outBits);
buffer[outBlurbs] |= (src.buffer[src.consumedBlurbs] & ((1 << (BITS_PER_BLURB - outBits)) - 1));
System.arraycopy(src.buffer, src.consumedBlurbs + 1, buffer, outBlurbs + 11,
(src.outBlurbs - src.consumedBlurbs - 1 + ((src.outBits != 0) ? 1 : 0)));
} else {
buffer[outBlurbs] <<= bitsToAdd;
buffer[outBlurbs] |= (src.buffer[src.consumedBlurbs] & ((1 << bitsToAdd) - 1));
}
outBits = src.outBits;
totalBits += bitsToAdd;
outBlurbs = totalBits / BITS_PER_BLURB;
return true;
} |
83322c73-5223-46b1-b340-5e04fe81ccc4 | 8 | private void processCommand(String unprocessedCommand)
{
unprocessedCommand = unprocessedCommand.replaceAll("\\s+", " "); //take out all extra spaces. ("Hello world!" -> "Hello world")
if(unprocessedCommand.length() == 0 || (unprocessedCommand.charAt(0) == ' ' && unprocessedCommand.length() == 1)) //avoid exceptions when nothing (excluding spaces) is entered
return;
if(unprocessedCommand.charAt(0) == ' ') //If first char is a space, eliminate it (fixes annoying bad commands where the rest of the command is correct)
unprocessedCommand = unprocessedCommand.substring(1);
if(!(unprocessedCommand.charAt(unprocessedCommand.length()-1) == ' '))
unprocessedCommand = unprocessedCommand + " ";
char[] charCmds = unprocessedCommand.toCharArray();
String currentArg = "";
for(char c : charCmds)
{
if(!(c == ' '))
{
currentArg = currentArg + c; //keep appending to currentArg until next value is not a space
if(!(unprocessedCommand.indexOf(c) == charCmds.length-1)) //Without this, the last argument is not processed.
{
continue; //re-loop with next character
}
}
args.add(currentArg); //add newly processed argument
currentArg = ""; //reset current argument
}
command = getCommandFromAlias(args.get(0)); //command is first argument
args.remove(0); //remove command from arguments
} |
f8c14642-371d-4e08-b046-7d004ac247aa | 4 | public synchronized void gridletSubmit(Gridlet gridlet, boolean ack) {
int reqPE = gridlet.getNumPE();
try {
// reject the Gridlet if it requires more PEs than the maximum
if(reqPE > super.totalPE_) {
String userName = GridSim.getEntityName( gridlet.getUserID() );
logger.warning("Gridlet #" + gridlet.getGridletID() + " from " +
userName + " user requires " + gridlet.getNumPE() + " PEs." +
"\n--> The resource has only " + super.totalPE_ + " PEs.");
gridlet.setGridletStatus(Gridlet.FAILED);
super.sendFinishGridlet(gridlet);
return;
}
} catch(Exception ex) {
logger.log(Level.WARNING, "Exception on submission of a Gridlet", ex);
}
// Creates a server side job
SSGridlet sgl = new SSGridlet(gridlet);
//-------------- FOR DEBUGGING PURPOSES ONLY --------------
visualizer.notifyListeners(super.get_id(), ActionType.ITEM_ARRIVED, true, sgl);
//----------------------------------------------------------
// if job cannot be scheduled immediately, then enqueue it
if(!startGridlet(sgl)) {
enqueueGridlet(sgl);
waitingJobs.add(sgl);
}
if (ack) {
// sends back an ack
super.sendAck(GridSimTags.GRIDLET_SUBMIT_ACK, true,
gridlet.getGridletID(), gridlet.getUserID());
}
//------------------ FOR DEBUGGING PURPOSES ONLY ----------------
visualizer.notifyListeners(super.get_id(), ActionType.ITEM_SCHEDULED, true, sgl);
//---------------------------------------------------------------
} |
c872ca43-1252-4539-86bb-fc6e31e711b3 | 7 | public void actionPerformed(ActionEvent e) {
if(e.getSource() == buttonStop){
serial.write(125);
MainWindow mainWindow = new MainWindow(serial, laser1, laser2);
dispose();
timer.stop();
}
if(e.getSource() == buttonIncreaseL1){
serial.write(108);
}
if(e.getSource() == buttonReduceL1){
serial.write(110);
}
if(e.getSource() == buttonIncreaseL2){
serial.write(109);
}
if(e.getSource() == buttonReduceL2){
serial.write(111);
}
if(e.getSource() == timer){
if(serial.getDataAvailable()){
System.out.println(serial.getTest());
serial.setDataAvailable(false);
labelPower.setText("Current power : " + serial.read() + "mW.");
}
}
} |
d9d94881-d8a2-4cbe-904a-0902412fb5f8 | 3 | private void createMenuBar() {
menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("Menu");
JMenuItem scoresMenuItem = new JMenuItem("Najlepsze wyniki");
JMenuItem loginMenuItem = new JMenuItem("Zaloguj");
JMenuItem registerMenuItem = new JMenuItem("Rejestruj");
JMenuItem exitItem = new JMenuItem("Exit");
JMenu showMenu = new JMenu("Rozmiar planszy");
final JCheckBoxMenuItem smallSize = new JCheckBoxMenuItem("8 kart");
final JCheckBoxMenuItem mediumSize = new JCheckBoxMenuItem("12 kart");
final JCheckBoxMenuItem bigSize = new JCheckBoxMenuItem("16 kart");
smallSize.setSelected(true);
showMenu.add(smallSize);
showMenu.add(mediumSize);
showMenu.add(bigSize);
fileMenu.add(showMenu);
fileMenu.add(scoresMenuItem);
fileMenu.add(loginMenuItem);
fileMenu.add(registerMenuItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
smallSize.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JCheckBoxMenuItem item = (JCheckBoxMenuItem) e.getSource();
recreateBoard(8);
mediumSize.setSelected(false);
bigSize.setSelected(false);
}
});
mediumSize.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JCheckBoxMenuItem item = (JCheckBoxMenuItem) e.getSource();
recreateBoard(12);
smallSize.setSelected(false);
bigSize.setSelected(false);
}
});
bigSize.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JCheckBoxMenuItem item = (JCheckBoxMenuItem) e.getSource();
recreateBoard(16);
smallSize.setSelected(false);
mediumSize.setSelected(false);
}
});
// logowanie
loginMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(loginDialog.isVisible()) {
loginDialog.setVisible(false);
} else {
loginDialog.setVisible(true);
}
}
});
// rejestracja
registerMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(registerDialog.isVisible()) {
registerDialog.setVisible(false);
} else {
registerDialog.setVisible(true);
}
}
});
//najlepsze wyniki
ArrayList<String> users = new ArrayList<String>();
users.add("pgol");
users.add("mysiaczkaa");
users.add("marcin");
ArrayList<Integer> scores = new ArrayList<Integer>();
scores.add(1);
scores.add(2);
scores.add(3);
ArrayList<String> topScores = new ArrayList<String>();
topScores = scoresDialog.buildScores(users, scores);
scoresDialog.addScores(topScores);
scoresMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
scoresDialog.setVisible(true);
}
});
exitItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int action = JOptionPane.showConfirmDialog(gameBoard, "Czy napewno chcesz wyjsc z tej niesamowitej gry", "Wyjdz", JOptionPane.OK_CANCEL_OPTION);
if(action == JOptionPane.OK_OPTION) {
System.exit(0);
}
}
});
menuBar.add(fileMenu);
add(menuBar, BorderLayout.NORTH); // TODO check this
} |
8aedded9-5165-4984-9ce9-1b159ec41649 | 0 | public void setName(String name)
{
this.name = name;
} |
031dff08-35f8-415e-a4a2-abfdcfc34c2f | 0 | public String getVersion() {
return version;
} |
44df2dfc-3986-44c1-9060-c27ccbebd6d9 | 6 | public static void main(String[] args){
//made a linked list of integers
LinkedList<Integer> myList = new LinkedList();
myList.add(2);
myList.add(3);
for(int i = 5; i<Integer.MAX_VALUE; i=i+2){
int ALSize = myList.size();
boolean isPrime = true;
//while the number is not proved to not be a prime, go through the list and see if it has any divisors in the list, if not, it is prime
for(int j = 0; (isPrime == true) && (j<ALSize); j++){
int temp = myList.get(j);
if(i%temp == 0){//not prime
isPrime = false;
}
}
if(isPrime){//if it is prime, add it to the list
myList.add(i);
System.out.println("added: " + i + " size: " + myList.size());
}
if(myList.size() == 10001){ //size we want
System.out.println(myList.get(10000)); //number we want, 10001st prime
return;
}
}
return;
} |
d2ed5bd2-c78e-4408-a78e-4bd68e967911 | 5 | final int method2426(int i) {
anInt10504++;
if (i != 200)
return 115;
if ((((NpcDefinition) ((Npc) this).definition)
.anIntArray1377)
!= null) {
NpcDefinition class79
= ((Npc) this).definition
.method794(Mob.varbitHandler, -1);
if (class79 != null && ((NpcDefinition) class79).anInt1390 != -1)
return ((NpcDefinition) class79).anInt1390;
}
if ((((NpcDefinition) ((Npc) this).definition)
.anInt1390)
== -1)
return super.method2426(200);
return (((NpcDefinition)
((Npc) this).definition)
.anInt1390);
} |
9f784bb9-de44-423d-b4a8-e00c350f5409 | 0 | private String aboutText() {
return
"Small World Agents [1.0] has been produced by the\nMulti Agents " +
"Systems and Simulation (MASS) Group at the University of Leeds, UK. \n\n" +
"It is a working framework for Agent based systems " +
"in which Agents can have a geographical location, and a location on a graph of " +
"connections between themselves and other Agents.\n\n" +
"The graphs can be developed into " +
"Small World Networks, using the algorithms published in Duncan J. Watt's 1999 paper " +
"'Networks, Dynamics, and Small World Phenomenon', AJS, 105(2), 493-527. " +
"Similar algorithms can be found in his book 'Small Worlds'.\n\n" +
"The application should not be used for commercial or military purposes. For details " +
"of the licensing of the source code, please contact the MASS group.\n\n" +
"http://www.geog.leeds.ac.uk/groups/mass/";
} |
e2eb0fac-f35c-4e32-b172-9f697f71352c | 7 | private void setSettingsPanel() {
if (square) {
playersNumber = new JComboBox<String>(new String[]{"1 Player", "2 Players", "3 Players", "4 Players"});
} else {
playersNumber = new JComboBox<String>(new String[]{"1 Player", "2 Players", "3 Players", "4 Players", "5 Players", "6 Players"});
}
playersNumber.setFocusable(false);
playersNumber.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
for (int i = 1; i < playersTypes.size(); i++){
playersTypes.get(i).setEnabled(i < playersNumber.getSelectedIndex() + 1);
}
}
});
boardSize = new JComboBox<String>(new String[]{"7 x 7", "9 x 9", "11 x 11", "13 x 13", "15 x 15"});
boardSize.setFocusable(false);
numberOfOpenings = new JComboBox<String>(new String[]{"1 Opening", "2 Openings", "3 Openings", "4 Openings"});
numberOfOpenings.setFocusable(false);
tileShape = new JComboBox<String>(new String[]{"Hexagon", "Square"});
tileShape.setSelectedIndex((square)? 1 : 0);
tileShape.setFocusable(false);
tileShape.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (isVisible()) {
setVisible(false);
square = tileShape.getSelectedIndex() == 1;
mainPanel.remove(settingsPanel);
setSettingsPanel();
mainPanel.add(settingsPanel);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
});
JPanel p1 = new JPanel(new GridLayout(4, 2, 5, 5));
p1.setOpaque(false);
p1.add(new JLabel("Shape"));
p1.add(tileShape);
p1.add(new JLabel("Size"));
p1.add(boardSize);
p1.add(new JLabel("Openings"));
p1.add(numberOfOpenings);
p1.add(new JLabel("Players"));
p1.add(playersNumber);
int r = (square)? 4 : 6;
JPanel p2 = new JPanel(new GridLayout(r, 2, 5, 5));
p2.setOpaque(false);
JLabel[] labels = new JLabel[r];
playersTypes = new ArrayList<JComboBox<String>>();
for (int i = 0; i < labels.length; i++) {
labels[i] = new JLabel("Player " + (i + 1));
labels[i].setForeground(PlayPanel.getColor(i));
JComboBox<String> playerType = new JComboBox<String>(new String[]{"Human"});
if (i != 0) {
playerType.addItem("Computer");
playerType.setEnabled(false);
}
playerType.setFocusable(false);
p2.add(labels[i]);
p2.add(playerType);
playersTypes.add(playerType);
}
JPanel p3 = new JPanel();
p3.setOpaque(false);
p3.add(p1);
p3.add(Box.createRigidArea(new Dimension(30, 0)));
p3.add(p2);
settingsPanel = new JPanel();
settingsPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
settingsPanel.setOpaque(false);
settingsPanel.add(p3);
} |
6d0ccd11-b726-40ed-b433-491e38bf31cd | 9 | public void buildDB(){
Console.line("Building Database\n**********************\n");
for (CorpusSource source : sources){
if (!source.wasRead()){
Console.text(".");
if (source.open()){
while (source.hasNext()){
String sentence = source.readSentence();
//sentence = sentence.replaceAll("[\\W\\d]+", " ").trim(); //^a-zA-Z
sentence = sentence.replaceAll("\\d+?", " ").replaceAll("(\\s+?\\W+?)", " ")
.replaceAll("(\\W+?\\s+?)"," ").replaceAll("[-/\\[\\]\\(\\)]", " " );
if (sentence.length()!=0){
String[] words = toWords(sentence);
for (String word : words){
vocab.add(word);
}
for (int i=0;i<words.length;i++) {
//Make the right context for the word
VocabularyContext cont = new VocabularyContext(
vocab.getIndex(i==0 ? "$START" : words[i-1]),
vocab.getIndex(i==(words.length-1) ? "$END" : words[i+1])
);
//add it to the word
vocab.getWord(vocab.getIndex(words[i])).addContext(cont);
//add 1 to the token count (absolute corpus size, with repititions)
tokenCount++;
}
}
}
} else {
Console.line("");
Console.error("Can't open "+source.name, name);
}
source.close();
}
source.markAsRead();
}
Console.line("Done building database\n");
sources.clear();
} |
62a3eeb0-4965-42cb-980c-826981b54aa8 | 9 | public Move move(boolean[] foodpresent, int[] neighbors, int foodleft, int energyleft) {
MoveInfo moveData = new MoveInfo(foodpresent, neighbors, foodleft, energyleft, lastMove);
preMoveTrack(moveData);
Move move; // placeholder for return value
move = reproduce(moveData);
if (move == null) {
move = makeMove(moveData);
}
if (move == null) {
move = new Move(STAYPUT);
}
if (move.type() < 5 && move.type() > 0) {
if (neighbors[move.type()] != -1) {
move = new Move(STAYPUT);
}
}
if(move.type() == REPRODUCE && move.childpos() > 0 && neighbors[move.childpos()] != -1) {
move = new Move(STAYPUT);
}
if (move.type() == 0) {
turnsSinceLastMove++;
} else {
turnsSinceLastMove = 0;
}
postMoveTrack(move, moveData);
lastMove = move.type();
return move;
} |
c25fd2f4-261f-47c9-92ec-31a8f4e32d96 | 3 | public boolean locationCheck(Locale newLocale) {
if (newLocale == null) {
return false;
} else {
currentLocale = newLocale;
try {
myStack.push(currentLocale);
} catch (Exception ex) {
System.out.println("Stack is full");
}
try {
myQueue.enqueue(currentLocale);
} catch (Exception ex) {
System.out.println("Queue is full");
}
}
return true;
} |
dfb20243-7ef9-483e-bb21-00bc777c3a23 | 8 | private double desiredDirection() {
if (directions.contains(Direction.UP)) {
if (directions.contains(Direction.RIGHT)) {
return 45;
}
if (directions.contains(Direction.LEFT)) {
return 315;
}
return 0;
}
if (directions.contains(Direction.DOWN)) {
if (directions.contains(Direction.RIGHT)) {
return 135;
}
if (directions.contains(Direction.LEFT)) {
return 225;
}
return 180;
}
if (directions.contains(Direction.RIGHT)) {
return 90;
}
if (directions.contains(Direction.LEFT)) {
return 270;
}
return 0;
} |
dc548eec-efc9-48e9-a738-aef93d9f74c9 | 9 | public boolean fGuiCheckObjectNonExistence(String strDesc){
//Delimiters
String[] delimiters = new String[] {":="};
String[] arrFindByValues = strDesc.split(delimiters[0]);
//Get Findby and Value
String FindBy = arrFindByValues[0];
String val = arrFindByValues[1];
//WebElement Collection
List<WebElement> lst;
try
{
//Handle all FindBy cases
String strElement = FindBy.toLowerCase();
if (strElement.equalsIgnoreCase("linktext"))
{
lst = driver.findElements(By.linkText(val));
}
else if (strElement.equalsIgnoreCase("xpath"))
{
lst = driver.findElements(By.xpath(val));
}
else if (strElement.equalsIgnoreCase("name"))
{
lst = driver.findElements(By.name(val));
}
else if (strElement.equalsIgnoreCase("id"))
{
lst = driver.findElements(By.id(val));
}
else if (strElement.equalsIgnoreCase("classname"))
{
lst = driver.findElements(By.className(val));
}
else if (strElement.equalsIgnoreCase("cssselector"))
{
lst = driver.findElements(By.cssSelector(val));
}
else if (strElement.equalsIgnoreCase("tagname"))
{
lst = driver.findElements(By.tagName(val));
}
else
{
Reporter.fnWriteToHtmlOutput("Check object Non Existence for object " + strDesc, "Object should not exist", "Property " + FindBy + " specified for object is invalid", "Fail");
System.out.println("Property name " + FindBy + " specified for object " + strDesc + " is invalid");
return false;
}
if(lst.size() == 0)
{
Reporter.fnWriteToHtmlOutput("Check Non Existence of object " + strDesc, "Object Should not exist", "Object does not exist", "Pass");
return true;
}
else
{
Reporter.fnWriteToHtmlOutput("Check Non Existence of object " + strDesc, "Object Should not exist", "Object exist", "Fail");
return false;
}
}
//Catch Block
catch(Exception e)
{
Reporter.fnWriteToHtmlOutput("Check Non Existence of object " + strDesc, "Object should not exist", "Exception occured while checking existence", "Fail");
System.out.println("Exception " + e.toString() + " occured while checking object non existence");
return false;
}
} |
ec59b315-d2e7-4ed5-a875-2b8eb22eeb7f | 5 | private int countMapFiles()
{
int counter = 0;
CodeSource src = this.getClass().getProtectionDomain().getCodeSource();
if( src != null ) {
URL jar = src.getLocation();
ZipInputStream zip;
try {
zip = new ZipInputStream( jar.openStream());
ZipEntry ze = null;
while((ze = zip.getNextEntry()) != null)
{
if(ze.getName().contains(worldPath))
{
String sub = ze.getName().substring(worldPath.length());
if(sub.length() > 3)
{
counter++;
}
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return counter;
} |
f123a972-8658-46a4-9817-60550f69d788 | 8 | private void notifyListeners(ProcessState event) {
for (IProcessComponentListener listener : this.listeners) {
switch (event) {
case EXECUTING:
listener.onExecuting(new ProcessEventArgs(this));
break;
case ROLLBACKING:
listener.onRollbacking(new ProcessEventArgs(this));
break;
case PAUSED:
listener.onPaused(new ProcessEventArgs(this));
break;
case EXECUTION_SUCCEEDED:
listener.onExecutionSucceeded(new ProcessEventArgs(this));
break;
case EXECUTION_FAILED:
listener.onExecutionFailed(new ProcessEventArgs(this));
break;
case ROLLBACK_SUCCEEDED:
listener.onRollbackSucceeded(new ProcessEventArgs(this));
break;
case ROLLBACK_FAILED:
listener.onRollbackFailed(new ProcessEventArgs(this));
break;
default:
break;
}
}
} |
a4cfc75b-7369-4420-b254-323c9c4549f9 | 0 | public PeanutButterSandwich() {
this.setName("PeanutButterSandwich");
this.setPrice(new BigDecimal(30));
} |
9ad29e5a-036d-455d-b5e4-da7bc8d4ccf9 | 0 | public TransformType createTransformType() {
return new TransformType();
} |
3e1c35dd-4bbb-4d11-80d2-6c72a7dfb238 | 3 | public static boolean equals( double[] vec1, double[] vec2 )
{
if ( vec1.length != vec2.length )
return(false);
for ( int i = 0; i < vec1.length; ++i )
if ( vec1[i] != vec2[i] )
return(false);
return(true);
} |
4dec91d5-6433-4eb5-9672-6e691c56007b | 8 | public static String[] substringsBetween(String str, String open,
String close) {
if (str == null || isEmpty(open) || isEmpty(close)) {
return null;
}
int strLen = str.length();
if (strLen == 0) {
return new String[0];
}
int closeLen = close.length();
int openLen = open.length();
List<String> list = new ArrayList<String>();
int pos = 0;
while (pos < strLen - closeLen) {
int start = str.indexOf(open, pos);
if (start < 0) {
break;
}
start += openLen;
int end = str.indexOf(close, start);
if (end < 0) {
break;
}
list.add(str.substring(start, end));
pos = end + closeLen;
}
if (list.isEmpty()) {
return null;
}
return list.toArray(new String[list.size()]);
} |
e0fe3f30-f61c-470d-bd96-995ee8422898 | 9 | public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt(),
k = in.nextInt();
if (k == 0) {
out.println(n == 1 ? 1 : -1);
}
else if (n < 2 || n / 2 > k) {
out.println(-1);
}
else {
int nadds = n / 2 - 1;
int core = k - nadds;
if (core == 1) {
for (int i = 1; i <= n; i++)
out.print(i + " ");
}
else {
HashSet<Integer> hs = new HashSet<>();
int other = 2*core;
hs.add(other);
out.print(core + " " + other);
for (int i = 0; i < nadds; i++) {
core++;
while(hs.contains(core)) core++;
other = 2*core + 1;
hs.add(other);
out.print(" " + core + " " + other);
}
if (n % 2 > 0) out.print(" 1");
}
}
out.flush();
} |
288d7c5d-8d3b-4e37-a443-3fc24e16ee90 | 7 | private void init() {
// default values
props.put(REPRODUCIBLE_PRNG, new Boolean(reproducible).toString());
props.put(CHECK_WEAK_KEYS, new Boolean(checkForWeakKeys).toString());
props.put(DO_RSA_BLINDING, new Boolean(doRSABlinding).toString());
// 1. allow site-wide override by reading a properties file
String propFile = null;
try {
propFile = (String) AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
return System.getProperty(PROPERTIES_FILE);
}
}
);
} catch (SecurityException se) {
if (DEBUG) debug("Reading property "+PROPERTIES_FILE+" not allowed. Ignored.");
}
if (propFile != null) {
try {
final java.util.Properties temp = new java.util.Properties();
final FileInputStream fin = new FileInputStream(propFile);
temp.load(fin);
temp.list(System.out);
props.putAll(temp);
} catch (IOException ioe) {
if (DEBUG) debug("IO error reading "+propFile+": "+ioe.getMessage());
} catch (SecurityException se) {
if (DEBUG) debug("Security error reading "+propFile+": "+se.getMessage());
}
}
// 2. allow vm-specific override by allowing -D options in launcher
handleBooleanProperty(REPRODUCIBLE_PRNG);
handleBooleanProperty(CHECK_WEAK_KEYS);
handleBooleanProperty(DO_RSA_BLINDING);
// re-sync the 'known' properties
reproducible = new Boolean((String) props.get(REPRODUCIBLE_PRNG)).booleanValue();
checkForWeakKeys = new Boolean((String) props.get(CHECK_WEAK_KEYS)).booleanValue();
doRSABlinding = new Boolean((String) props.get(DO_RSA_BLINDING)).booleanValue();
} |
79ea18a9-8760-4938-a5d9-0aba61b2f3ed | 6 | @Override
public void render(Screen screen) {
switch (dir) {
case NONE:
sprite = Sprite.player;
break;
case UP:
sprite = Sprite.playerUp;
break;
case RIGHT:
sprite = Sprite.playerRight;
break;
case DOWN:
sprite = Sprite.playerDown;
break;
case LEFT:
sprite = Sprite.playerLeft;
break;
}
if (damaged) sprite = sprite.tinted(0xffff2222);
int halfSprite = sprite.size / 2;
int yp = location.getY() - halfSprite;
screen.renderText(location.getX(), yp - sprite.size / 3, name, TextAlign.CENTER);
screen.render(location.getX() - halfSprite, yp, sprite);
} |
b4b1e5eb-ddb5-4e40-a692-74afd5041b70 | 2 | public GraphPoint[] getSelectedPoints() {
ArrayList<GraphPoint> buffer = new ArrayList();
Iterator<Map.Entry<Integer, GraphPoint>> it = points.entrySet().iterator();
GraphPoint bgp;
while (it.hasNext()) {
bgp = it.next().getValue();
if (bgp.getComponent().getSelect()) {
buffer.add(bgp);
}
}
GraphPoint[] gps = buffer.toArray(new GraphPoint[0]);
return gps;
} |
09c7bc5f-ba48-4c25-a467-7850c844e3de | 3 | public HashSet<ymlReward> getymlRewardsFromHashMap(int questNumber, HashMap<String,Object> map){
//Since there can be different types of the same reward as well as an undefined amount of them... iterate
HashSet<ymlReward> returnMe = new HashSet<ymlReward>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
//Should be a string if their list is setup correctly
String key = (String) entry.getKey();
Object value = entry.getValue();
if(key.equalsIgnoreCase("Money")){
//Money Type
returnMe.add( new ymlReward( Integer.toString((Integer) value), plugin.getMoneyName() ) );
}else
if(key.equalsIgnoreCase("Item")){
//Item Type
//public ymlReward( String Item_ID, String Display, String Amount, String Durability){
HashMap<String,Object> itemInfo = (HashMap<String, Object>) value;
returnMe.add(getymlItemFromHashMap(itemInfo));
}else{
questLoadError(questNumber, "Unknown reward format:\n Key:" + key + " | Value:" + value);
}
}
return returnMe;
} |
15e2c2eb-89a0-4471-9d2f-ac62c06c58c8 | 2 | private void goToTest(GenericLittleMan<?> littleMan) {
final boolean isComplete = littleMan.goToComputerLocation(littleManTest.getComputerLocation());
if (isComplete) {
incrementConditionalActionStep();
}
} |
cb467662-04af-402a-b109-ec57bdc145a8 | 0 | public void setApplicationName(String name) {
this.applicationName = name;
} |
db94c4b2-702f-40a0-bbd3-2d25890cfc71 | 3 | public void visit_iinc(final Instruction inst) {
final IncOperand operand = (IncOperand) inst.operand();
final int index = operand.var().index();
if (index + 1 > maxLocals) {
maxLocals = index + 1;
}
final int incr = operand.incr();
if ((index < 256) && ((byte) incr == incr)) {
addOpcode(Opcode.opc_iinc);
addByte(index);
addByte(incr);
} else {
addOpcode(Opcode.opc_wide);
addByte(Opcode.opc_iinc);
addShort(index);
addShort(incr);
}
stackHeight += 0;
} |
6820b676-e021-4be5-abf9-d9d6453a5345 | 9 | protected void execute() {
processPendingRequests();
Loadable task = null;
try { // it probably won't hurt much not to synchronize this iterator
for (Iterator it = taskPool.iterator(); it.hasNext();) {
if (off || isStopped())
return;
task = (AbstractLoadable) it.next();
if (task == null || !task.isEnabled())
continue;
if (task.isCompleted()) {
remove(task);
}
if (task.getInterval() <= 1) {
task.execute();
}
else {
if (indexOfStep % task.getInterval() == 0)
task.execute();
}
}
}
catch (Throwable t) {
t.printStackTrace();
}
} |
03ec15df-9c7a-4fb3-9831-094f581ebb2f | 3 | public void addDownServices() {
LinkedList<Integer> list = new LinkedList<Integer>();
//conn.query("select service_id from esri.services si where si.service_id not in " +
// "(select service_id from esri.service_date_uptime where date_trunc('day', localtimestamp) = time);");
conn.query("select service_id from esri.service_date_uptime where date_trunc('day', localtimestamp) = runtime;");
ResultSet rs = conn.getQueryResult();
try {
while( rs.next() ) {
list.add(rs.getInt("service_id"));
}
} catch (SQLException e) {
e.printStackTrace();
}
for( int i: list ) addTestResult(i, false);
} |
908360a8-0d19-4f28-8d45-96c08a09dfe2 | 2 | public void FecharConexao(){
try{
if (!conbco.isClosed() )
{
conbco.close();
}
}
catch(Exception ex){
}
} |
e207e942-3505-4410-b618-4061371022c1 | 7 | @Override
public void train(final Matrix matrix) {
List<List<Double>> data = matrix.getData();
for (int colIndex = 0; colIndex < data.get(0).size(); colIndex++){
if (matrix.getColumnAttributes(colIndex).getColumnType()== ColumnAttributes.ColumnType.CATEGORICAL){
Counter<Double> counter = new Counter<Double>();
for (int rowIndex = 0; rowIndex < data.size(); rowIndex++){
Double value = data.get(rowIndex).get(colIndex);
if(!value.equals(Matrix.UNKNOWN_VALUE)){
counter.increment(data.get(rowIndex).get(colIndex));
}
}
columnCentroids.add(colIndex, counter.getMax());
}
else if (matrix.getColumnAttributes(colIndex).getColumnType()== ColumnAttributes.ColumnType.CONTINUOUS){
Double total = 0.0;
for (int rowIndex = 0; rowIndex < data.size(); rowIndex++){
Double value = data.get(rowIndex).get(colIndex);
if(!value.equals(Matrix.UNKNOWN_VALUE)){
total+=data.get(rowIndex).get(colIndex);
}
}
Double average = total/data.size();
columnCentroids.add(colIndex, average);
}
}
} |
9d98b7ab-4dea-42f5-a6af-7fd6bbbd20d4 | 9 | private static final String clean(final String desc) {
final StringBuilder result = new StringBuilder();
int pos = 0;
for (int i = 0; i < desc.length(); i++) {
final char c = desc.charAt(i);
if (c == '\\') {
result.append(desc.substring(pos, i));
pos = i += 2;
} else if (c == '"') {
result.append(desc.substring(pos, i));
result.append("\\\"");
pos = i + 1;
} else if (((c >= ' ') && (c <= ']' /*
* including uppercased chars
* and digits
*/))
|| ((c >= 'a') && (c <= 'z'))
|| ((c > (char) 127) && (c < (char) 256))) {
continue;
} else {
result.append(desc.substring(pos, i));
pos = i + 1;
}
}
result.append(desc.substring(pos));
return result.toString();
} |
3352637a-85d7-4150-a145-78a372c89d19 | 2 | public void savePatient(Patient patient,String action)throws Exception{
log.debug("savePatient Service method called...");
PatientDAO patientDao=new PatientDAOJDBCImpl();
if(action.equals("Save")){
patientDao.addPatient(patient);
}else if(action.equals("Update")){
patientDao.updatePatient(patient);
}
} |
6f71be80-4375-49ea-ba07-2058c4aceab1 | 7 | private CompilerToken makeToken(final String token, final String state) throws LexicalException {
if (state.equalsIgnoreCase("identifier")) {
return processIdentifier(token);
} else if (state.equalsIgnoreCase("integer")) {
return processInteger(token);
} else if (state.equalsIgnoreCase("realexponent")) {
return processFloat(token, state);
} else if (state.equalsIgnoreCase("real")) {
return processFloat(token, state);
} else if (state.equalsIgnoreCase("realexponentzero")) {
return processFloat(token, state);
} else if (state.equalsIgnoreCase("zerointeger")) {
return processInteger(token);
} else if (state.equalsIgnoreCase("bang")) {
throw new LexicalException("Invalid modifier ! found.");
} else {
return new CompilerToken(tokenStateMap.get(state), token);
}
} |
4ca03e89-5e5d-4238-8c94-895275aac178 | 9 | @Override
public double[] calculateFractal3DWithoutPeriodicity(Complex pixel) {
iterations = 0;
Complex tempz = new Complex(pertur_val.getPixel(init_val.getPixel(pixel)));
Complex tempz2 = new Complex(init_val2.getPixel(pixel));
Complex[] complex = new Complex[3];
complex[0] = tempz;//z
complex[1] = new Complex(pixel);//c
complex[2] = tempz2;//z2
Complex zold = new Complex();
if(parser.foundS()) {
parser.setSvalue(new Complex(complex[0]));
}
if(parser2.foundS()) {
parser2.setSvalue(new Complex(complex[0]));
}
if(parser.foundP()) {
parser.setPvalue(new Complex());
}
if(parser2.foundP()) {
parser2.setPvalue(new Complex());
}
double temp;
for(; iterations < max_iterations; iterations++) {
if(bailout_algorithm.escaped(complex[0], zold)) {
Object[] object = {iterations, complex[0], zold};
temp = out_color_algorithm.getResult(object);
double[] array = {Math.abs(temp) - 100800, temp};
return array;
}
zold.assign(complex[0]);
function(complex);
if(parser.foundP()) {
parser.setPvalue(new Complex(zold));
}
if(parser2.foundP()) {
parser2.setPvalue(new Complex(zold));
}
}
Object[] object = {complex[0], zold};
temp = in_color_algorithm.getResult(object);
double result = temp == max_iterations ? max_iterations : max_iterations + Math.abs(temp) - 100820;
double[] array = {result, temp};
return array;
} |
a80af227-1eca-4ebc-8f81-de4d6a59bd86 | 2 | public int testGetState(){
if(bomb) return Spot.BOMB;
if(flag) return Spot.FLAG;
return getBombCount();
} |
23c0fdc0-f8de-4f13-acfc-4c49a70fc1a4 | 4 | private void loadShapes(String[] files, final HashMap<Integer, GMTShape> shapes) {
GMTParser gmtpBuildings = new GMTParser() {
@Override
public void processShape(GMTShape shape) {
shapes.put(shape.getID(), shape);
}
};
try {
for (String file : files) {
gmtpBuildings.load(file);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(DataLoader.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(DataLoader.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(DataLoader.class.getName()).log(Level.SEVERE, null, ex);
}
} |
80ed5f05-787d-47bd-b5b5-3b1d399f9317 | 0 | public Worker () {
//initial settings
this.iFrom=IFROM;
this.iTo=ITO;
System.out.println(MSG_WELCOME);
//start
this.lifeCycle();
} |
2dd487dc-e43a-45a0-a727-684130e93c80 | 0 | @Test
public void getConnectedComponentsTestZero() {
City_Graph city_graph2 = new City_Graph();
city_graph2.loadMap("res/singleCity.mp");
City testCity = city_graph2.getCity(0);
VertexSet emptySet = new VertexSet();
assertTrue(city_graph2.getNeighbourhood(testCity).equals(emptySet));
} |
16ce789c-932f-4cdd-af1f-d28d02262d95 | 8 | public double f_to_minimize(double x[]) {
double f,sq1,sq2,sq3,f1,f2,f3,f4,fac,c1,c2,s1,s2;
double theta,x1,x2,x3,x4;
if (id_f_to_min == 0) {
f = x[1]*x[1];
} else if (id_f_to_min == 1) {
sq1 = (x[1] - c)*(x[1] - c);
sq2 = (x[2] - d)*(x[2] - d);
f = sq1 + sq2;
} else if (id_f_to_min == 2) {
sq1 = (x[1] - c)*(x[1] - c);
sq2 = (x[2] - d)*(x[2] - d);
sq3 = (x[3] - e)*(x[3] - e);
f = sq1 + sq2 + sq3;
} else if (id_f_to_min == 3) {
f1 = 10.0*(x[2] - x[1]*x[1]);
f2 = 1.0 - x[1];
f3 = 10.0*(x[4] - x[3]*x[3]);
f4 = 1.0 - x[3];
f = f1*f1 + f2*f2 + f3*f3 + f4*f4;
} else if (id_f_to_min == 4) {
f1 = x[1] + 10.0*x[2];
f2 = Math.sqrt(5.0)*(x[3] - x[4]);
fac = x[2] - 2.0*x[3];
f3 = fac*fac;
fac = x[1] - x[4];
f4 = Math.sqrt(10.0)*fac*fac;
f = f1*f1 + f2*f2 + f3*f3 + f4*f4;
} else if (id_f_to_min == 5) {
c1 = Math.cos(x[1]);
c2 = Math.cos(x[2]);
s1 = Math.sin(x[1]);
s2 = Math.sin(x[2]);
f1 = 1.0 - (c1 + (1.0 - c1) - s1);
f2 = 2.0 - ((c1 + 2.0*(1 - c2) - s2) +
(c2 + 2.0*(1 - c2) - s2));
f = f1*f1 + f2*f2;
} else if (id_f_to_min == 6) {
if (x[1] > 0.0) {
theta = one_d_twopi*Math.atan(x[2]/x[1]);
} else {
theta = one_d_twopi*Math.atan(x[2]/x[1]) + .5;
}
f1 = 10.0*(x[3] - 10.0*theta);
f2 = 10.0*(Math.sqrt(x[1]*x[1] + x[2]*x[2]) - 1.0);
f3 = x[3];
f = f1*f1 + f2*f2 + f3*f3;
} else {
x1 = x[1];
x2 = x[2];
x3 = x[3];
x4 = x[4];
f = 100.0*(x1*x1 - x2)*(x1*x1 - x2) + (1.0 - x1)*(1.0 - x1) +
90.0*(x3*x3 - x4)*(x3*x3 - x4) + (1.0 - x3)*(1.0 - x3) +
10.1*((1.0 - x2)*(1.0 - x2) + (1.0 - x4)*(1.0 - x4)) +
19.8*(1.0 - x2)*(1.0 - x4);
}
return f;
} |
4088c531-7ab0-4015-92cb-8a4401aa7420 | 0 | public MealyLambdaTransitionChecker()
{
super();
} |
c09b4ec3-df78-4e57-ae7e-48e3c56c7d5d | 5 | public RrdDef getRrdDef() throws RrdException {
if (!root.getTagName().equals("rrd_def")) {
throw new RrdException("XML definition must start with <rrd_def>");
}
validateTagsOnlyOnce(root, new String[] {
"path", "start", "step", "datasource*", "archive*"
});
// PATH must be supplied or exception is thrown
String path = getChildValue(root, "path");
RrdDef rrdDef = new RrdDef(path);
try {
String startStr = getChildValue(root, "start");
GregorianCalendar startGc = Util.getGregorianCalendar(startStr);
rrdDef.setStartTime(startGc);
} catch (RrdException e) {
// START is not mandatory
}
try {
long step = getChildValueAsLong(root, "step");
rrdDef.setStep(step);
} catch (RrdException e) {
// STEP is not mandatory
}
// datsources
Node[] dsNodes = getChildNodes(root, "datasource");
for (int i = 0; i < dsNodes.length; i++) {
validateTagsOnlyOnce(dsNodes[i], new String[] {
"name", "type", "heartbeat", "min", "max"
});
String name = getChildValue(dsNodes[i], "name");
String type = getChildValue(dsNodes[i], "type");
long heartbeat = getChildValueAsLong(dsNodes[i], "heartbeat");
double min = getChildValueAsDouble(dsNodes[i], "min");
double max = getChildValueAsDouble(dsNodes[i], "max");
rrdDef.addDatasource(name, type, heartbeat, min, max);
}
// archives
Node[] arcNodes = getChildNodes(root, "archive");
for (int i = 0; i < arcNodes.length; i++) {
validateTagsOnlyOnce(arcNodes[i], new String[] {
"cf", "xff", "steps", "rows"
});
String consolFun = getChildValue(arcNodes[i], "cf");
double xff = getChildValueAsDouble(arcNodes[i], "xff");
int steps = getChildValueAsInt(arcNodes[i], "steps");
int rows = getChildValueAsInt(arcNodes[i], "rows");
rrdDef.addArchive(consolFun, xff, steps, rows);
}
return rrdDef;
} |
d7998c0e-7ed7-45ce-8f3e-42db7ea79ea0 | 7 | public static Color getColor ( byte multiplier, byte type ) {
switch ( type ) {
case 0:
switch ( multiplier ) {
case 1:
return new Color ( 170, 100, 0 ) ;
case 2:
return Color.CYAN ;
case 3:
return Color.BLUE ;
default:
return null ;
}
case 2:
return Color.PINK ;
case 3:
return Color.MAGENTA ;
case 4:
return Color.PINK ;
default:
return null ;
}
} |
10deb57d-bf38-4550-b5e7-b17a9cf4c766 | 0 | public PhaseId getPhaseId()
{
return PhaseId.RENDER_RESPONSE;
} |
74f2eb7f-4955-4a9d-9577-bd653ad146b8 | 3 | @Override
public int hashCode() {
int result = parentCategoryId;
result = 31 * result + accountId;
result = 31 * result + id;
result = 31 * result + (headLine != null ? headLine.hashCode() : 0);
result = 31 * result + (text != null ? text.hashCode() : 0);
result = 31 * result + (time != null ? time.hashCode() : 0);
return result;
} |
f9e05e34-0fbb-4948-9bda-b167535249e9 | 8 | public void setFreeColGameObject(String id, FreeColGameObject fcgo) {
if (aiObjects.containsKey(id)) return;
if (!id.equals(fcgo.getId())) {
throw new IllegalArgumentException("!id.equals(fcgo.getId())");
}
if (fcgo instanceof Colony) {
new AIColony(this, (Colony)fcgo);
} else if (fcgo instanceof ServerPlayer) {
ServerPlayer p = (ServerPlayer)fcgo;
if (p.isIndian()) {
new NativeAIPlayer(this, p);
} else if (p.isREF()) {
new REFAIPlayer(this, p);
} else if (p.isEuropean()) {
new EuropeanAIPlayer(this, p);
}
} else if (fcgo instanceof Unit) {
new AIUnit(this, (Unit)fcgo);
}
} |
3007b65b-5af8-4d1f-8f4b-4e79644a9fd1 | 6 | @SuppressWarnings("unchecked")
public static Class<?> getClass(Type type) {
if (type instanceof Class) {
return (Class) type;
} else if (type instanceof ParameterizedType) {
return getClass(((ParameterizedType) type).getRawType());
} else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
Class<?> componentClass = getClass(componentType);
if (componentClass != null) {
return Array.newInstance(componentClass, 0).getClass();
} else {
return null;
}
} else {
return null;
}
} |
3680b337-2ed1-4675-8e13-a9032d63616a | 6 | @Override
public double distribute(TVC newCon) {
int id1 = newCon.getFirewallId1();
int id2 = newCon.getFirewallId2();
List<TVC> conns = new LinkedList<>();
for (TVC c : environment.getConnectionsSortedDown()) {
if ( c.mightBeManagedBy(id1) && c.mightBeManagedBy(id2)) {
conns.add(c);
if ( !c.equals(newCon)) {
environment.getFirewalls()[c.getManagerFirewallId()].removeManagedConnection(c);
}
}
}
Firewall fw1 = environment.getFirewalls()[id1];
Firewall fw2 = environment.getFirewalls()[id2];
for (TVC c : conns) {
Firewall fw = (fw2.getManagedIntencity() < fw1.getManagedIntencity()) ? fw2 : fw1;
fw.manageConnection(c);
}
return environment.dispersion();
} |
606f5906-a0f1-4d0a-afe4-3300e2460313 | 9 | public static StringBuffer expertiseList(MOB E, HTTPRequest httpReq, java.util.Map<String,String> parms)
{
final StringBuffer str=new StringBuffer("");
if(parms.containsKey("EXPERTISELIST"))
{
final ArrayList<String> theclasses=new ArrayList<String>();
if(httpReq.isUrlParameter("EXPER1"))
{
int num=1;
String behav=httpReq.getUrlParameter("EXPER"+num);
while(behav!=null)
{
if(behav.length()>0)
theclasses.add(behav);
num++;
behav=httpReq.getUrlParameter("EXPER"+num);
}
}
else
for(final Enumeration<String> x=E.expertises();x.hasMoreElements();)
{
final String ID=x.nextElement();
final ExpertiseLibrary.ExpertiseDefinition X=CMLib.expertises().getDefinition(ID);
if(X!=null)
theclasses.add(ID);
}
for(int i=0;i<theclasses.size();i++)
{
final String theclass=theclasses.get(i);
str.append("<SELECT ONCHANGE=\"EditAffect(this);\" NAME=EXPER"+(i+1)+">");
str.append("<OPTION VALUE=\"\">Delete!");
final ExpertiseLibrary.ExpertiseDefinition X=CMLib.expertises().getDefinition(theclass);
if(X==null)
str.append("<OPTION VALUE=\""+theclass+"\" SELECTED>"+theclass);
else
str.append("<OPTION VALUE=\""+X.ID()+"\" SELECTED>"+X.name());
str.append("</SELECT>, ");
}
str.append("<SELECT ONCHANGE=\"AddAffect(this);\" NAME=EXPER"+(theclasses.size()+1)+">");
str.append("<OPTION SELECTED VALUE=\"\">Select an Expertise");
for(final Enumeration<ExpertiseLibrary.ExpertiseDefinition> e=CMLib.expertises().definitions();e.hasMoreElements();)
{
final ExpertiseLibrary.ExpertiseDefinition X=e.nextElement();
str.append("<OPTION VALUE=\""+X.ID()+"\">"+X.name());
}
str.append("</SELECT>");
}
return str;
} |
ba6a505a-987f-4e59-bfb5-2ebf198744c1 | 4 | public void testLongLargeArrayArraycopy()
{
long[] data = new long[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int startPos = 2;
int length = 8;
LargeArray.setMaxSizeOf32bitArray(1073741824);
LongLargeArray a = new LongLargeArray(data);
LongLargeArray b = new LongLargeArray(2 * data.length);
Utilities.arraycopy(a, startPos, b, 0, length);
for (int i = 0; i < length; i++) {
assertEquals(data[startPos + i], b.getLong(i));
}
b = new LongLargeArray(2 * data.length);
Utilities.arraycopy(data, startPos, b, 0, length);
for (int i = 0; i < length; i++) {
assertEquals(data[startPos + i], b.getLong(i));
}
LargeArray.setMaxSizeOf32bitArray(data.length - 1);
a = new LongLargeArray(data);
b = new LongLargeArray(2 * data.length);
Utilities.arraycopy(a, startPos, b, 0, length);
for (int i = 0; i < length; i++) {
assertEquals(data[startPos + i], b.getLong(i));
}
b = new LongLargeArray(2 * data.length);
Utilities.arraycopy(data, startPos, b, 0, length);
for (int i = 0; i < length; i++) {
assertEquals(data[startPos + i], b.getLong(i));
}
} |
df502110-b0e3-42f8-a02c-43250357875b | 2 | private void initBoutons() {
// Création des boutons
for (int i = 0; i < this.animaux.size(); i++) {
this.boutons.add(i, new JButton() );
this.boutons.get(i).setBackground(java.awt.Color.white);
this.boutons.get(i).setText(this.animaux.get(i).getNom());
this.boutons.get(i).setMaximumSize(new java.awt.Dimension(190, 23));
this.boutons.get(i).setMinimumSize(new java.awt.Dimension(190, 23));
this.boutons.get(i).setPreferredSize(new java.awt.Dimension(190, 23));
this.boutons.get(i).addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
boutonActionPerformed(evt);
}
});
}
// Affichage des boutons
JPanel conteneur = new JPanel();
conteneur.setLayout( new GridLayout(this.animaux.size() / 2, 2, 10, 10));
for (int i = 0; i < this.boutons.size(); i++)
conteneur.add(this.boutons.get(i));
conteneur.setPreferredSize( new Dimension(370, 33 * this.boutons.size() / 2) );
JPanel createurMarges = new JPanel();
createurMarges.setLayout( new FlowLayout(FlowLayout.CENTER, 10, 10) );
createurMarges.add(conteneur);
JScrollPane scrollChoixAnimal = new JScrollPane(createurMarges);
containChoixAnimal.setLayout( new BoxLayout(containChoixAnimal, 1));
// containChoixAnimal.setLayout( new FlowLayout(FlowLayout.CENTER, 10, 5) );
containChoixAnimal.add(scrollChoixAnimal);
} |
dcf3c7bf-129d-4107-93a8-2b31dbf39e09 | 2 | public void draw(Graphics2D g) {
int offsetX = 0;
for (int i = 0; i < playerLives; i++){
g.drawImage(playerHeadImage, playerLivesX + offsetX, playerLivesY, null);
offsetX += 15;
}
g.drawImage(healthBarImage,healthBarX,healthBarY,null );
offsetX = 0;
for (int i = 0; i < playerHealth; i++){
g.drawImage(healthBar1PercentImage,healthBarX + offsetX,healthBarY,null );
offsetX += 1;
}
g.setColor(Color.BLACK);
g.setFont(new Font("Century Gothic", Font.BOLD, 18));
String st = Integer.toString(playerScore);
g.drawString(st, scoreX, scoreY);
} |
c1190647-b303-4423-b2d1-bee511c43044 | 1 | public static void compareAndChangeId(int comparedId)
{
if(id<comparedId)
id=comparedId+1;
} |
3f6326f7-bdf7-40f5-8b6b-305d42015b69 | 0 | public static synchronized HashMap<String, Integer> getUserStock(String uid) {
UserStorageAccess xmlAccessor = new UserStorageAccess();
stocks = xmlAccessor.getUserStocks(uid);
//System.out.println("size of Hashmap : " + stocks.size());
//System.out.println(stocks.containsKey("CCR"));
return stocks;
} |
e14f4d4a-c9e2-4ec9-ae0e-cd8e4e5df297 | 7 | private TreeNode SimpleExpresion() {
TreeNode tmp = AdditiveExpression();
switch (t.id) {
case Constants.EQ:
case Constants.LEQ:
case Constants.LS:
case Constants.GEQ:
case Constants.GT:
case Constants.NEQ:
TreeNode tmp2 = Relop();
tmp2.C1 = tmp;
tmp = tmp2;
tmp.C2 = AdditiveExpression();
break;
case Constants.SEMI:
return tmp;
// default: throw new
// IllegalStateException("Unexpected Token in Simple Expresion Found Token = "+t.toString());
}
return tmp;
} |
76b3e334-e390-429b-9919-ebd432c0cc74 | 9 | static byte HopperFix(byte data, String kierunek)
{
if (kierunek.equals("right"))
{
if (data == 2) {
return 5;
}
if (data == 4) {
return 2;
}
if (data == 5) {
return 3;
}
if (data == 3) {
return 4;
}
}
else
{
if (data == 5) {
return 2;
}
if (data == 2) {
return 4;
}
if (data == 3) {
return 5;
}
if (data == 4) {
return 3;
}
}
return data;
} |
5baabfe3-3d7b-4f1c-9b10-1518fe6be908 | 1 | private static Key toKey(byte[] key, String algorithm)
throws InvalidKeyException, NoSuchAlgorithmException,
InvalidKeySpecException {
DESKeySpec spec = new DESKeySpec(key);
SecretKey secretKey = new SecretKeySpec(key, algorithm);
if (algorithm.equals(DES)) {
SecretKeyFactory factory = SecretKeyFactory.getInstance(DES);
secretKey = factory.generateSecret(spec);
}
return secretKey;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.