text stringlengths 14 410k | label int32 0 9 |
|---|---|
protected void computeRect(Raster[] sources,
WritableRaster dest,
Rectangle destRect) {
// Retrieve format tags.
RasterFormatTag[] formatTags = getFormatTags();
RasterAccessor s1 = new RasterAccessor(sources[0], destRect,
formatTags[0],
getSource(0).getColorModel());
RasterAccessor s2 = new RasterAccessor(sources[1], destRect,
formatTags[1],
getSource(1).getColorModel());
RasterAccessor d = new RasterAccessor(dest, destRect,
formatTags[2], getColorModel());
if(d.isBinary()) {
byte[] src1Bits = s1.getBinaryDataArray();
byte[] src2Bits = s2.getBinaryDataArray();
byte[] dstBits = d.getBinaryDataArray();
int length = dstBits.length;
for(int i = 0; i < length; i++) {
// "Subtract" is equivalent to the following
// when -1 is clamped to 0.
dstBits[i] = (byte)(src1Bits[i] & (byte)(~(src2Bits[i])));
}
d.copyBinaryDataToRaster();
return;
}
switch (d.getDataType()) {
case DataBuffer.TYPE_BYTE:
computeRectByte(s1, s2, d);
break;
case DataBuffer.TYPE_USHORT:
computeRectUShort(s1, s2, d);
break;
case DataBuffer.TYPE_SHORT:
computeRectShort(s1, s2, d);
break;
case DataBuffer.TYPE_INT:
computeRectInt(s1, s2, d);
break;
case DataBuffer.TYPE_FLOAT:
computeRectFloat(s1, s2, d);
break;
case DataBuffer.TYPE_DOUBLE:
computeRectDouble(s1, s2, d);
break;
}
if (d.needsClamping()) {
d.clampDataArrays();
}
d.copyDataToRaster();
} | 9 |
static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
} else if (o instanceof Float) {
if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
}
}
} | 7 |
public void checkException () throws Exception {
if ( this.exception != null ) {
throw this.exception;
}
} | 1 |
public static void save(Document doc){
try (
OutputStream file = new FileOutputStream(SAVE_PATH+doc.getName());
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
){
output.writeObject(doc);
System.out.println("Document saved.");
}
catch(IOException ex){
ex.printStackTrace();
}
} | 1 |
public static Settings getInstance() {
return settings;
} | 0 |
public void setOptions(String[] options) throws Exception {
String tableString, inputString, tmpStr;
resetOptions();
tmpStr = Utils.getOption("url", options);
if (tmpStr.length() != 0)
setUrl(tmpStr);
tmpStr = Utils.getOption("user", options);
if (tmpStr.length() != 0)
setUser(tmpStr);
tmpStr = Utils.getOption("password", options);
if (tmpStr.length() != 0)
setPassword(tmpStr);
tableString = Utils.getOption('T', options);
inputString = Utils.getOption('i', options);
if(tableString.length() != 0){
m_tableName = tableString;
m_tabName = false;
}
m_id = Utils.getFlag('P', options);
if(inputString.length() != 0){
try{
m_inputFile = inputString;
ArffLoader al = new ArffLoader();
File inputFile = new File(inputString);
al.setSource(inputFile);
setInstances(al.getDataSet());
//System.out.println(getInstances());
if(tableString.length() == 0)
m_tableName = getInstances().relationName();
}catch(Exception ex) {
printException(ex);
ex.printStackTrace();
}
}
} | 7 |
public void disconnectRejectPart() {
rejectPartItems = new ShareableHashSet<Item>();
for (Item i : items) {
if (i.production.usedForReject) {
rejectPartItems.add(i);
}
}
items.removeAll(rejectPartItems);
rejectPartTransitions = new ShareableHashSet<Transition>();
rejectPartBridges = new ShareableHashSet<Transition>();
for (Transition t : transitions) {
if ((t.target.production != null && t.target.production.usedForReject) ||
(t.source.production != null && t.source.production.usedForReject)) {
if (reachableRejectBridge(t)) {
rejectPartBridges.add(t);
} else {
rejectPartTransitions.add(t);
}
}
}
transitions.removeAll(rejectPartTransitions);
removeTransitions(rejectPartBridges);
} | 8 |
public static int stringToInt (String st) {
int res = 0;
if (st.equals("integer") || st.equals("INTEGER")) res = INTEGER;
else if (st.equals("float") || st.equals("FLOAT")) res = DOUBLE;
else if (st.equals("text") || st.equals("VARCHAR") || st.equals("TEXT")) res = STRING;
else if (st.equals("bool") || st.equals("BOOL")) res = BOOLEAN;
return res;
} | 9 |
public void run() {
int counter = 0;
while (LazyHomer.noreply || counter<10) {
if (counter>4 && LazyHomer.noreply) LOG.info("Still looking for smithers on multicast port "+port+" ("+LazyHomer.noreply+")");
LazyHomer.send("INFO","/domain/internal/service/getname");
try {
sleep(500+(counter*100));
counter++;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
LOG.info("Stopped looking for new smithers");
} | 5 |
@Override
protected void channelRead0(final ChannelHandlerContext ctx, HttpRequest request) throws Exception {
QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
String decodedUri = decoder.path();
statCollector.addProcessedConnection(ctx.channel(), ConnectionParameter.URI, decodedUri);
// response Hello world
if(decodedUri.equals(HELLO_REQUEST)){
HttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
packString(ctx, HELLO_RESPONSE));
// ctx.write(response).addListener(ChannelFutureListener.CLOSE);
new DelayedResponse(ctx, response, 10000);
}
// redirect
else if(decodedUri.equals(REDIRECT_REQUEST)){
List<String> redirectUrlList = decoder.parameters().get("url");
String redirectUrl = null;
if(redirectUrlList != null && redirectUrlList.size() > 0){
redirectUrl = "http://" + redirectUrlList.get(0);
}
statCollector.addRedirect(redirectUrl);
HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.MOVED_PERMANENTLY);
HttpHeaders.setHeader(response, "Location", redirectUrl);
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
}
// status table
else if(decodedUri.equals(STAT_REQUEST)){
String statTableString = new StatFormatter().formatHTMLTable(statCollector);
HttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
packString(ctx, statTableString));
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
}
// default
else {
ctx.close();
}
} | 5 |
@SuppressWarnings("empty-statement")
@Override
public void run() {
while (true) {
try {
synchronized (guard) { };
if (sel.select() <= 0) {
continue;
}
} catch (IOException e) {
continue;
}
synchronized(guard) {
for (SelectionKey k : sel.selectedKeys()) {
if (k.isValid() && (k.attachment() != null)) {
final AbstractSelectableChannelConnection conn = (AbstractSelectableChannelConnection) k.attachment();
Event e;
if (k.isReadable()) {
e = new Event(Event.EVENT_READ, conn);
} else if (k.isWritable()) {
e = new Event(Event.EVENT_WRITE, conn);
} else {
continue;
}
removeConnection(conn);
conn.handleEvent(e);
}
}
}
sel.selectedKeys().clear();
}
} | 8 |
void computeBoardScale()
{
Dimension target = new Dimension(1500, 1500);
Dimension container = this.getSize();
Double s = 1.0;
if ( ( target.width <= container.width ) && ( target.height <= container.height ) )
{} // It already fits in container
else if ( (target.width > container.width) && (target.height <= container.height) )
s = (double)container.width / (double)target.width; // It does not fit horizontaly
else if ( (target.width <= container.width) && (target.height > container.height) )
s = (double)container.height / (double)target.height; // It does not fit verticaly
else if(target.width == target.height)
{
if(container.width <= container.height)
s = (double)container.width / (double)target.width;
else
s = (double)container.height / (double)target.height;
}
Dimension scaled = new Dimension((int)(target.width * s), (int)(target.height * s));
this.board.setPreferredSize(scaled);
this.boardScale = s;
this.origX = (container.width - scaled.width) / 2;
this.origY = (container.height - scaled.height) / 2;
Dimension ballSize = new Dimension((int)(100.0 * s), (int)(100.0 * s));
this.whiteBall.setPreferredSize(ballSize);
this.blackBall.setPreferredSize(ballSize);
this.selection.setPreferredSize(ballSize);
} | 8 |
private void quitChan(String user_name, CommandArgsIterator args_it)
throws IOException
{
if (args_it.hasNext()) {
String chan_arg = args_it.next();
if (!args_it.hasNext() && chan_arg.length() >= 2
&& chan_arg.charAt(0) == '#') {
String chan_name = chan_arg.substring(1);
boolean not_joined;
synchronized (this._server.getChans()) {
synchronized (this._chans) {
Chan chan = this._chans.get(chan_name);
if (chan != null) {
chan.quitChan(user_name, this);
not_joined = false;
} else
not_joined = true;
}
}
if (!not_joined) {
this.traceEvent("Quitte le salon #" + chan_name);
this.ack();
} else
this.writeCommand(Errors.ChanNotJoined);
} else
this.syntaxError();
} else
this.syntaxError();
} | 6 |
private void playGame() {
System.out.println("Game initialing.......");
this.initialGame();
System.out.println("Game starting...........");
System.out.println("> Select Game Mode :");
System.out.println(" > 1. Normal Mode");
System.out.println(" > 2. Intellligence Mode");
System.out.println(" > 3. Exit Game");
System.out.println("> Please chose mode :)");
while (true) {
this.scPress = new Scanner(System.in);
String input = this.scPress.next();
if (input.equals("1")) {
this.normalMode();
}
else if (input.equals("2")) {
this.intelligenceMode();
}
else if (input.equals("3")) {
System.out.println("Game Exit !");
break;
}
else {
System.out.println("Illegal choose, please try again!");
}
}
System.exit(0);
} | 4 |
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Rectangle clip = g2.getClipBounds();
rowRenderer.paintBackground(g, this);
for (int i=0; i<getModel().getRowCount(); i++) {
Rectangle2D bounds = getRowBounds(i);
if (bounds.intersects(clip)) {
rowRenderer.paintRow(g, this, i, bounds, false);
}
}
for (int i=0; i<model.getTaskCount(); i++) {
Object task = model.getTaskAt(i);
Rectangle2D bounds = getTaskBounds(task);
if (bounds.intersects(clip)) {
taskRenderer.paintTask(g, this, task, bounds, isTaskSelected(task));
}
}
if ((linkRenderer != null) && (linkModel != null)) {
for (int i=0; i<linkModel.getLinkCount(); i++) {
linkRenderer.paintLink(g, this, linkModel.getLinkAt(i));
}
}
} | 7 |
public static void main(String args[]) {
abTrajectory ar = new abTrajectory();
ImageSegFrame frame = null;
GameStateExtractor gameStateExtractor = new GameStateExtractor();
TrajectoryPlanner trajectory = new TrajectoryPlanner();
while (true) {
// capture image
BufferedImage screenshot = ar.doScreenShot();
final int nHeight = screenshot.getHeight();
final int nWidth = screenshot.getWidth();
System.out.println("captured image of size " + nWidth + "-by-" + nHeight);
// extract game state
GameStateExtractor.GameState state = gameStateExtractor.getGameState(screenshot);
if (state != GameStateExtractor.GameState.PLAYING) {
continue;
}
// process image
VisionMBR vision = new VisionMBR(screenshot);
List<Rectangle> pigs = vision.findPigsMBR();
List<Rectangle> redBirds = vision.findRedBirdsMBRs();
Rectangle sling = vision.findSlingshotMBR();
if (sling == null) {
System.out.println("...could not find the slingshot");
continue;
}
// System.out.println("...found " + pigs.size() + " pigs and " + redBirds.size() + " birds");
System.out.println("...found slingshot at " + sling.toString());
// convert screenshot to grey scale and draw bounding boxes
screenshot = VisionUtils.convert2grey(screenshot);
VisionUtils.drawBoundingBoxes(screenshot, pigs, Color.GREEN);
VisionUtils.drawBoundingBoxes(screenshot, redBirds, Color.PINK);
VisionUtils.drawBoundingBox(screenshot, sling, Color.ORANGE);
// find active bird
Rectangle activeBird = trajectory.findActiveBird(redBirds);
if (activeBird == null) {
System.out.println("...could not find active bird");
continue;
}
trajectory.plotTrajectory(screenshot, sling, activeBird);
// show image
if (frame == null) {
frame = new ImageSegFrame("trajectory", screenshot);
} else {
frame.refresh(screenshot);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
} | 6 |
private double calculateMantissa(int[] binaryNumber) {
double mantissa = 1;
int power = -1;
for(int i = 9; i < binaryNumber.length; i++){
mantissa = mantissa + binaryNumber[i] * Math.pow(2, power);
power--;
}
return mantissa;
} | 1 |
public void setMin(int min)
{
myMin = min;
refresh();
} | 0 |
@BeforeClass
public static void setUpClass() {
} | 0 |
private double calcY(final double TOP, final double TOTAL_HEIGHT ) {
switch (popupLocation) {
case TOP_LEFT : case TOP_CENTER : case TOP_RIGHT : return TOP + offsetY;
case CENTER_LEFT: case CENTER : case CENTER_RIGHT: return TOP + (TOTAL_HEIGHT- height)/2 - offsetY;
case BOTTOM_LEFT: case BOTTOM_CENTER: case BOTTOM_RIGHT: return TOP + TOTAL_HEIGHT - height - offsetY;
default: return 0.0;
}
} | 9 |
public int getWidth() {
return width;
} | 0 |
public boolean pickAndExecuteAnAction() {
// If there is a customer waiting
//synchronized(Customers) {
for (MyCustomer c : Customers) {
if (c.state.equals(MyCustomer.State.waiting)) {
// And an unoccupied table
for (Table t : Tables) {
if (! t.occupied) {
// And at least one waiter working
for (MyWaiter w : Waiters) {
if (w.state.equals(MyWaiter.State.working)) {
// Assign the customer to that table
AssignCustomer(c, t);
t.occupied = true;
return true;
}
}
}
else if (t.tableNum == Tables.size() - 1) {
TellRestaurantIsFull(c);
return true;
}
}
}
//}
}
return false;
} | 7 |
static final void method407(float f, int i, int i_1_, float f_2_, int i_3_, float[] fs, int i_4_, int i_5_, int i_6_, int i_7_, int i_8_, float f_9_, float[] fs_10_, int i_11_) {
i_4_ -= i_3_;
anInt577++;
i_1_ -= i_7_;
i_6_ -= i_8_;
float f_12_ = fs_10_[2] * (float) i_6_ + ((float) i_1_ * fs_10_[0] + fs_10_[1] * (float) i_4_);
float f_13_ = (float) i_6_ * fs_10_[5] + (fs_10_[3] * (float) i_1_ + fs_10_[4] * (float) i_4_);
if (i_5_ < 63) {
method408(-127, 7, -96, false, -54, null, false);
}
float f_14_ = fs_10_[8] * (float) i_6_ + ((float) i_4_ * fs_10_[7] + fs_10_[6] * (float) i_1_);
float f_15_;
float f_16_;
if (i != 0) {
if (i != 1) {
if ((i ^ 0xffffffff) != -3) {
if (i != 3) {
if ((i ^ 0xffffffff) != -5) {
f_15_ = f_2_ + -f_13_ + 0.5F;
f_16_ = 0.5F + (-f_14_ + f_9_);
} else {
f_16_ = f_9_ + f_14_ + 0.5F;
f_15_ = f_2_ + -f_13_ + 0.5F;
}
} else {
f_16_ = 0.5F + (f_12_ + f);
f_15_ = 0.5F + (-f_13_ + f_2_);
}
} else {
f_16_ = f + -f_12_ + 0.5F;
f_15_ = 0.5F + (-f_13_ + f_2_);
}
} else {
f_16_ = 0.5F + (f + f_12_);
f_15_ = 0.5F + (f_9_ + f_14_);
}
} else {
f_15_ = 0.5F + (-f_14_ + f_9_);
f_16_ = 0.5F + (f_12_ + f);
}
if ((i_11_ ^ 0xffffffff) != -2) {
if (i_11_ != 2) {
if ((i_11_ ^ 0xffffffff) == -4) {
float f_17_ = f_16_;
f_16_ = f_15_;
f_15_ = -f_17_;
}
} else {
f_15_ = -f_15_;
f_16_ = -f_16_;
}
} else {
float f_18_ = f_16_;
f_16_ = -f_15_;
f_15_ = f_18_;
}
fs[1] = f_15_;
fs[0] = f_16_;
} | 9 |
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
VMSMain vms = new VMSMain();
ReadErrorFile ref = new ReadErrorFile();
try {
if (vms.checkForUpdate()) {
Main frame = new Main();
frame.setVisible(true);
} else {
OldVersion frame = new OldVersion(ref.readErrorFile("versionOutOfDate", errorFilePath));
frame.setVisible(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
} | 2 |
public Pid searchByURI(String uri) throws IOException {
ClientResponse cr = wr.path(localPrefix)
.queryParam(Strings.PID_RECORD_KEY_URL, uri.toString())
.header(Strings.HEADER_ACCEPT, MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
if (cr.getStatus() / 100 != 2) {
throw new IOException("error when searching for URL: server returned: " + cr.getStatus());
}
Gson gson = new Gson();
String json = cr.getEntity(String.class);
if (json == null) {
throw new IOException("null json");
}
if (json.isEmpty()) {
throw new IOException("empty json");
}
Type listType = new TypeToken<ArrayList<String>>() {
}.getType();
List<String> jlist = gson.fromJson(json, listType);
if (jlist == null) {
throw new IOException("null json list");
}
if (jlist.isEmpty()) {
throw new IOException("empty json list");
}
String hdl = jlist.get(0);
if (hdl.startsWith(epicServer)) {
hdl = hdl.substring(epicServer.length());
} else if (hdl.startsWith(localPrefix)) {
// fine
} else {
hdl = localPrefix + hdl;
}
return new PidImpl(this, hdl);
} | 7 |
public void mostrarDatosDeIngreso(String campo, beansHistorial registro){
String descripcion = null, parametro = null;
switch(campo.trim()){
case "downline":
descripcion = "Nombre del downline nuevo ";
parametro = registro.getDownline().getNombre();
break;
case "upline":
descripcion = "Nombre del upline ";
parametro = registro.getUpline().getNombre();
break;
case "contacto":
descripcion = "Nombre del contacto ";
parametro = registro.getContacto().getNombre();
break;
case "fecha":
descripcion = "Fecha del ingreso del downline ";
parametro = ""+registro.getDate()+"";
break;
case "codigo":
descripcion = "Codigo de registro del downline ";
parametro = Integer.toString(registro.getId());
break;
default:
descripcion = "null";
parametro = "null";
break;
}
if(true != (descripcion.equals("null")) && true != (parametro.equals("null"))){
System.out.println(descripcion + parametro);
}
} | 7 |
private static boolean handleStaircases(Player player, WorldObject object,
int optionId) {
String option = object.getDefinitions().getOption(optionId);
if (option.equalsIgnoreCase("Climb-up")) {
if (player.getPlane() == 3)
return false;
player.useStairs(-1, new WorldTile(player.getX(), player.getY(),
player.getPlane() + 1), 0, 1);
} else if (option.equalsIgnoreCase("Climb-down")) {
if (player.getPlane() == 0)
return false;
player.useStairs(-1, new WorldTile(player.getX(), player.getY(),
player.getPlane() - 1), 0, 1);
} else if (option.equalsIgnoreCase("Climb")) {
if (player.getPlane() == 3 || player.getPlane() == 0)
return false;
player.getDialogueManager().startDialogue(
"ClimbNoEmoteStairs",
new WorldTile(player.getX(), player.getY(), player
.getPlane() + 1),
new WorldTile(player.getX(), player.getY(), player
.getPlane() - 1), "Go up the stairs.",
"Go down the stairs.");
} else
return false;
return false;
} | 7 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RecipeStepData other = (RecipeStepData) obj;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
return true;
} | 6 |
public boolean isAllowed(int patient_no, int test_id) {
String selectNotAllowedQuery = "SELECT * FROM NOT_ALLOWED WHERE health_care_no = "
+ patient_no + " AND test_id = " + test_id;
boolean isAllowed = true;
try {
rs = stmt.executeQuery(selectNotAllowedQuery);
if (rs.next()) {
isAllowed = false;
}
} catch (SQLException e) {
}
return isAllowed;
} | 2 |
public void setModifiers(int mod) {
ClassFile cf = getClassFile2();
if (Modifier.isStatic(mod)) {
int flags = cf.getInnerAccessFlags();
if (flags != -1 && (flags & AccessFlag.STATIC) != 0)
mod = mod & ~Modifier.STATIC;
else
throw new RuntimeException("cannot change " + getName() + " into a static class");
}
checkModify();
cf.setAccessFlags(AccessFlag.of(mod));
} | 3 |
@EventHandler
public void onPlayerQuit(PlayerQuitEvent e) {
Player p = e.getPlayer();
if (CTF.gm.isPlaying(p)) {
PlayerInventory inv = p.getInventory();
inv.setHelmet(new ItemStack(Material.AIR, 1));
inv.setChestplate(new ItemStack(Material.AIR, 1));
inv.setLeggings(new ItemStack(Material.AIR, 1));
inv.setBoots(new ItemStack(Material.AIR, 1));
inv.clear();
for (PotionEffect effect : p.getActivePotionEffects()) {
p.removePotionEffect(effect.getType());
}
if (CTF.fm.hasFlag(p)) {
Team flag = CTF.fm.getFlag(p);
if (flag == Team.RED) {
CTF.fm.getRedFlagSpawn().getBlock().setType(Material.WOOL);
CTF.fm.getRedFlagSpawn().getBlock().setData(DyeColor.RED.getData());
CTF.gm.broadcastMessageInGame(CTF.TAG_BLUE + CTF.tm.getPlayerNameInTeamColor(p) + " §2dropped the §cRed flag§2!");
} else if (flag == Team.BLUE) {
CTF.fm.getBlueFlagSpawn().getBlock().setType(Material.WOOL);
CTF.fm.getBlueFlagSpawn().getBlock().setData(DyeColor.BLUE.getData());
CTF.gm.broadcastMessageInGame(CTF.TAG_BLUE + CTF.tm.getPlayerNameInTeamColor(p) + " §2dropped the §9Blue flag§2!");
}
}
p.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());
e.setQuitMessage("");
CTF.gm.broadcastMessageInGame(CTF.TAG_RED + "§r" + CTF.tm.getPlayerNameInTeamColor(p) + " §cleft the game. ");
CTF.gm.removePlayerFromGame(p, CTF.tm.getTeam(p));
if (CTF.gm.getPlaying().size()==0) {
CTF.sm.setBlueCaptures(0);
CTF.sm.setRedCaptures(0);
CTF.sm.updateScoreboard();
}
}
} | 6 |
public void buildGui(Calculator calculator) {
this.calculator = calculator;
JFrame aFrame = new JFrame(TITLE);
// Create a the main panel, with 4 lines
JPanel mainPanel = new JPanel(new GridLayout(6, 1));
JPanel gridLines[] = { new JPanel(new GridLayout(1, 5)),
new JPanel(new GridLayout(1, 5)),
new JPanel(new GridLayout(1, 5)),
new JPanel(new GridLayout(1, 5)),
new JPanel(new GridLayout(1, 5)),
new JPanel(new GridLayout(1, 5)), };
aFrame.getContentPane().add(mainPanel);
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aFrame.setSize(FRAME_SIZE_X, FRAME_SIZE_Y);
aFrame.setResizable(false);
// Line 1
inputText.setFont(TEXT_FONT);
gridLines[0].add(inputText);
// Line 2
resultText.setHorizontalAlignment(JTextField.CENTER);
resultText.setFont(TEXT_FONT);
resultText.setFocusable(false);
resultText.setBackground(BUTTON_COLOR);
gridLines[1].add(resultText);
// Line 3, add the JButtons for the numbers 1 to 3 and "/"
for (int i = 1; i <= 3; ++i) {
createButton(gridLines[2], Integer.toString(i));
}
createButton(gridLines[2], "/");
// Line 4, add the JButtons for the numbers 4 to 6 and "*"
for (int i = 4; i <= 6; ++i) {
createButton(gridLines[3], Integer.toString(i));
}
createButton(gridLines[3], "*");
// Line 5, add the JButtons for the numbers 7 to 9 and "-"
for (int i = 7; i <= 9; ++i) {
createButton(gridLines[4], Integer.toString(i));
}
createButton(gridLines[4], "-");
// Line 6, add 2 empty JPanels and the JButtons for "=" and "+"
JPanel tempPanel = null;
for (int i = 1; i <= 2; ++i) {
tempPanel = new JPanel();
tempPanel.setBackground(BANANA);
gridLines[5].add(tempPanel);
}
JButton equalsButton = new JButton("=");
equalsButton.addActionListener(new MyEqualsListener());
styleAndAdd(gridLines[5], equalsButton);
createButton(gridLines[5], "+");
for (JPanel gridLine : gridLines) {
mainPanel.add(gridLine);
}
mainPanel.setBorder(MAIN_PANEL_BORDER);
mainPanel.setBackground(BANANA);
aFrame.pack();
aFrame.setLocationRelativeTo(null);
aFrame.setVisible(true);
} | 5 |
private void drawFields(Graphics g){
g.setColor(EMPTY_CIRCLE_COLOR);
// Zeiche Sekunden-Felder:
for (int a = 0; a < 2; a++){
for (int i = 0; i < Position.time_day[1].length; i++){
// x-Coorodinate y-Coordinate
g.drawOval(Position.time_day[a][i][0], Position.time_day[a][i][1], EMPTY_CIRCLE, EMPTY_CIRCLE);
}
}
for (int a = 0; a < 2; a++){
for (int i = 0; i < Position.time_month[1].length; i++){
// x-Coorodinate y-Coordinate
g.drawOval(Position.time_month[a][i][0], Position.time_month[a][i][1], EMPTY_CIRCLE, EMPTY_CIRCLE);
}
}
for (int a = 0; a < 4; a++){
for (int i = 0; i < Position.time_year[1].length; i++){
// x-Coorodinate y-Coordinate
g.drawOval(Position.time_year[a][i][0], Position.time_year[a][i][1], EMPTY_CIRCLE, EMPTY_CIRCLE);
}
}
} | 6 |
public void paintBorder(Component c, Graphics g, int x, int y, int width,
int height)
{
if (mDrawFocus)
{
x = 1;
y = height - 2;
while (x < width)
{
g.drawLine(x, 1, x, 1);
g.drawLine(x + 2, y, x + 2, y);
x += 2;
}
x = width - 2;
y = 1;
while (y < height)
{
g.drawLine(1, y, 1, y);
g.drawLine(x, y + 2, x, y + 2);
y += 2;
}
}
} | 3 |
public static void main(String[] args)
{
Song s1 = new Song("Yellow", "Cold Play", 2.4);
Song s2 = new Song("Clocks", "Cold Play", 3.56);
System.out.println(s2);
Playlist p = new Playlist("ColdPlayHits");
if(p.addSong(s1))System.out.println(s1+" added");;
if(p.addSong(s2))System.out.println(s2+" added");;
System.out.println( p.totalSongs());
System.out.println( p.playlistTime());
if(p.removeSong(s2))System.out.println(s2+" deleted");;
System.out.println( p.totalSongs());
p.addSong(s2);
if( p.isSongInPlaylist("clocks"))
System.out.println("clocks is in the playlist");
else
System.out.println("clocks is not in the playlist");
p.songsByArtist( "Cold Play"); // all info
p.songsByArtist("Grease Monkey");
Song s3 = new Song("Around the Sun", "REM", 4.30);
Playlist favorites = new Playlist("favorites");
if(favorites.addSong(s3))System.out.println(s3+" Added");;
if(favorites.addSong(s1))System.out.println(s1+" Added");;
if(favorites.addSongsFrom(p))System.out.println(p.getList()+" Added");;
System.out.println(favorites.getList()); //getList() returns List<Song> type and toString() in ArrayList class prints the list contents
Song s4 = new Song("Paranoid Android", "Radiohead",6.4);
favorites.addSong(s4);
System.out.println(s4 + " added");
favorites.removeSong(s3);
System.out.println(s3 + " removed");
System.out.println(favorites.getList());
System.out.println("My favorites playtime: " + favorites.playlistTime());
favorites.removeSong(s1);
System.out.println(s1 + " removed");
System.out.println("Will adding coldplay's playlist to favorites duplicate the already exisitng songs?");
favorites.addSongsFrom(p);
System.out.println(favorites.getList());
System.out.println("Nope!");
} | 7 |
private void createPlayer(){
CategoryType kat;
Track t;
ArrayList<Track> tracks = rep.getTracks();
for(int i = 0; i < tracks.size(); i++){
t = tracks.get(i);
kat = t.getKat();
switch(kat) {
case BASS:
bassPlayer.add(new Player(t));
break;
case BEATS:
beatsPlayer.add(new Player(t));
break;
case HARMONY:
harmonyPlayer.add(new Player(t));
break;
case MELODY:
melodyPlayer.add(new Player(t));
break;
case EFFECTS:
effectsPlayer.add(new Player(t));
break;
}
}
} | 6 |
private void checkCollision(PVector handAbsolute, DrumSingle myDrum, Player player, boolean left) {
PVector handAbsoluteNormalized = handAbsolute.get();
handAbsoluteNormalized.normalize();
PVector ov = myDrum.ov(true);
// Dot Product
float dotProduct = handAbsolute.dot(ov);
// Entfernung berechnen
float distance = handAbsolute.dist(myDrum.center());
float maxDistance = marginDrums / 2;
if (distance <= maxDistance) {
// Crap
float velocity = player.getVelocityLeft();
if (left) {
if (myDrum.dotProductLeft < 0 && dotProduct > 0) {
System.out.println("Down Left " + myDrum.id);
// midi.playMidi(myDrum.id, myDrum.id, true, velocity, 1);
midi.playMidiDrum(player.getVelocityLeft(), 1, myDrum.id);
} // else if (myDrum.dotProductLeft > 0 && dotProduct < 0) {
// }
} else {
if (myDrum.dotProductRight < 0 && dotProduct > 0) {
// System.out.println("Down Right " + myDrum.id);
// midi.playMidi(myDrum.id, myDrum.id, true);
} else if (myDrum.dotProductRight > 0 && dotProduct < 0) {
System.out.println("Down Right " + myDrum.id);
// midi.playMidi(myDrum.id, myDrum.id, true, velocity, 1);
midi.playMidiDrum(player.getVelocityLeft(), 1, myDrum.id);
}
}
}
// Neues Dot Product speichern
if (left) {
myDrum.dotProductLeft = dotProduct;
} else {
myDrum.dotProductRight = dotProduct;
}
} | 9 |
private static void prepareProfInfo(Player p, String prof, Professions plugin) {
ArrayList<ArrayList<ArrayList<String>>> j = getProfData(prof, plugin);
Integer i1;
Integer i2;
String temp;
for ( i1 = 0; i1 <j.size(); i1++ ) {
p.sendMessage(ChatColor.RED + "-- TIER" + (i1 + 1) + " --");
/*
* Send onBlockBreak rewards (if any):
*/
temp = "";
if ( j.get(i1).get(0).get(0) != null ) {
for ( i2 = 0; i2 < j.get(i1).get(0).size(); i2++ ) {
temp = j.get(i1).get(0).get(i2) + ", " + temp;
}
p.sendMessage(ChatColor.YELLOW + "BREAK: " + ChatColor.WHITE + temp);
}
/*
* Send onBlockPlace rewards (if any):
*/
temp = "";
if ( j.get(i1).get(1).get(0) != null ) {
for ( i2 = 0; i2 < j.get(i1).get(1).size(); i2++ ) {
temp = j.get(i1).get(1).get(i2) + ", " + temp;
}
p.sendMessage(ChatColor.YELLOW + "PLACE: " + ChatColor.WHITE + temp);
}
}
} | 5 |
public int getAlignment() {
checkWidget();
if ((style & SWT.ARROW) != 0) {
if ((style & SWT.UP) != 0)
return SWT.UP;
if ((style & SWT.DOWN) != 0)
return SWT.DOWN;
if ((style & SWT.LEFT) != 0)
return SWT.LEFT;
if ((style & SWT.RIGHT) != 0)
return SWT.RIGHT;
return SWT.UP;
}
if ((style & SWT.LEFT) != 0)
return SWT.LEFT;
if ((style & SWT.CENTER) != 0)
return SWT.CENTER;
if ((style & SWT.RIGHT) != 0)
return SWT.RIGHT;
return SWT.LEFT;
} | 8 |
public AlgReader(File file) throws FileNotFoundException {
if (!file.exists())
return;
map = new TreeMap<String, String>();
this.file = file;
String ext = file.getName().substring(file.getName().lastIndexOf('.'));
setValue("Program", "path", file.getParent() + "/");
setValue("Program", "name", file.getName());
if (ext.equals(".bin")) {
setValue("Program", "source", file.getName());
}
if (ext.equals(".cpp") || ext.equals(".cc")) {
readFromCpp();
setValue("Program", "source", file.getName());
}
if (ext.equals(".alg")) {
readFromAlg();
}
} | 5 |
public void setFamilienaam(String familienaam) {
this.familienaam = familienaam;
} | 0 |
public Class<?> lookupType(String name) throws ClassNotFoundException {
if (name == null) {
throw new IllegalArgumentException("name must not be null");
}
Class<?> type = typeRenames.get(name);
if (type == null) {
type = loadType(name);
}
return type;
} | 4 |
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List Querybooks(String authorid){
List list=new ArrayList();
ResultSet restl=null;
int i = 0;
double d = 0;
try{
contct=connector.getConnection();
Sttt=contct.prepareStatement("select * from bk where authorid= '"+authorid+"'");
restl=Sttt.executeQuery();
while(restl.next()){
databook bk = new databook();
bk.Sin(restl.getString("isbn"));
bk.Ste(restl.getString("title"));
bk.Sad(i);
bk.Spe(restl.getString("publishdate"));
bk.Spce(d);
bk.Spr(restl.getString("publisher"));
list.add(bk);
}
}catch(SQLException e){
list=null;
}if(restl!=null){
try{
restl.close();
}catch(SQLException e){}
}
connector.Close(contct, Sttt);
return list;
} | 4 |
void addCall(final MethodEditor callerMethod, final MemberRef callee) {
// Just maintain the calls mapping
final MemberRef caller = callerMethod.memberRef();
Set callees = (Set) this.calls.get(caller);
if (callees == null) {
callees = new HashSet();
this.calls.put(caller, callees);
}
callees.add(callee);
} | 1 |
public Reference getRef(int i) throws ClassFormatException {
if (i == 0)
return null;
if (tags[i] != FIELDREF && tags[i] != METHODREF
&& tags[i] != INTERFACEMETHODREF)
throw new ClassFormatException("Tag mismatch");
if (constants[i] == null) {
int classIndex = indices1[i];
int nameTypeIndex = indices2[i];
if (tags[nameTypeIndex] != NAMEANDTYPE)
throw new ClassFormatException("Tag mismatch");
String type = getUTF8(indices2[nameTypeIndex]);
try {
if (tags[i] == FIELDREF)
TypeSignature.checkTypeSig(type);
else
TypeSignature.checkMethodTypeSig(type);
} catch (IllegalArgumentException ex) {
throw new ClassFormatException(ex.getMessage());
}
String clName = getClassType(classIndex);
constants[i] = Reference.getReference(clName,
getUTF8(indices1[nameTypeIndex]), type);
}
return (Reference) constants[i];
} | 8 |
@Test
public void testStrings(){
System.out.println(System.getProperty("java.library.path"));
Strings strings = new Strings();
String s1 = "Hi";
String s2 = "Howdy";
String s3 = "Lollapalooza";
String s4 = "gg";
assertTrue(strings.allUniqueCharacters(s1));
assertTrue(strings.allUniqueCharacters(s2));
assertFalse(strings.allUniqueCharacters(s3));
assertFalse(strings.allUniqueCharacters(s4));
char[] cStyle = {'h', 'i', 'd', 'e', '/', 'n'};
char[] cStyleReverse = {'e', 'd', 'i', 'h', '/', 'n'};
char[] reversed = strings.reverseString(cStyle);
for(int i=0; i<cStyle.length; i++){
assertTrue(reversed[i] == cStyleReverse[i]);
}
s1 = strings.removeDuplicates(s3);
assertTrue(s1.equals("pz"));
String ana1 = "howy";
String ana2 = "yowh";
String ana3 = "abcd";
String ana4 = "yoowh";
assertTrue(strings.areAnagrams(ana1, ana2));
assertFalse(strings.areAnagrams(ana2, ana3));
assertFalse(strings.areAnagrams(ana2, ana4));
String stringWithSpaces = "Hi mom and dad";
String noSpaces = strings.needlessReplacement(stringWithSpaces);
assertTrue(noSpaces.equals("Hi%20mom%20and%20dad"));
int[][] matrix = new int[5][5];
for(int i=0; i<matrix.length; i++){
for(int j=0; j<matrix[0].length; j++){
matrix[i][j] = 1;
}
}
matrix[0][0] = 0;
matrix[4][4] = 0;
int[][] result = strings.findZerosInMatrix(matrix);
for(int i=0; i<result.length; i++){
assertTrue(result[0][i] == 0);
assertTrue(result[4][i] == 0);
assertTrue(result[i][0] == 0);
assertTrue(result[i][4] == 0);
}
for(int i=1; i<result.length-1; i++){
for(int j=1; j<result.length-1; j++){
assertTrue(result[i][j] == 1);
}
}
s1 = "howdy";
s2 = "yhowd";
s3 = "dyhow";
s4 = "dyhoww";
assertTrue(strings.isRotation(s1, s2));
assertTrue(strings.isRotation(s2, s3));
assertTrue(strings.isRotation(s1, s3));
assertFalse(strings.isRotation(s3, s4));
} | 6 |
public boolean mousedown(Coord c, int button) {
if (button != 1)
return (false);
a = true;
ui.grabmouse(this);
return (true);
} | 1 |
public int compareTo(WildcardString arg0) {
if(arg0==null)
throw new NullPointerException("cannot compare WildcardString to null");
return compareWildcardString(string,arg0.toString());
} | 1 |
public void update() {
glLoadIdentity(); //reset field of view to position = rotation = 0
float dt = Time.dt;
Vector3f velocity = new Vector3f();
//handle translation input
if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
velocity.z += speed*dt;
} if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
velocity.z -= speed*dt;
} if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
velocity.x += speed*dt;
} if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
velocity.x -= speed*dt;
} if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
velocity.y -= speed*dt;
} if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
velocity.y += speed*dt;
}
//handle rotation input
if (Keyboard.isKeyDown(Keyboard.KEY_Q)) {
rotation.y -= rotSpeed*dt;
} if (Keyboard.isKeyDown(Keyboard.KEY_E)) {
rotation.y += rotSpeed*dt;
}
//rotate the velocity based on the Y rotation
Vector3f vel = new Vector3f((float)(velocity.x*Math.cos(rotation.y*toRad) - velocity.z*Math.sin(rotation.y*toRad)),
velocity.y, (float)(velocity.x*Math.sin(rotation.y*toRad) + velocity.z*Math.cos(rotation.y*toRad)));
Vector3f.add(position, vel, position);
//translate world
GL11.glRotatef(rotation.y, 0, 1, 0);
GL11.glTranslatef(position.x, position.y, position.z);
} | 8 |
public static void main(String... args) throws Throwable {
final CountDownLatch connectLatch = new CountDownLatch(1);
final AtomicReference<ConnectReturnCode> connectReturnCode = new AtomicReference<ConnectReturnCode>();
AsyncClientListener listener = new AsyncClientListener() {
@Override
public void publishReceived(MqttClient client, PublishMessage message) {
log.warn("Received a message when no subscriptions were active. Check your broker ;)");
}
@Override
public void disconnected(MqttClient client, Throwable cause, boolean reconnecting) {
if (cause != null) {
log.error("Disconnected from the broker due to an exception.", cause);
} else {
log.info("Disconnected from the broker.");
}
if (reconnecting) {
log.info("Attempting to reconnect to the broker.");
}
}
@Override
public void connected(MqttClient client, ConnectReturnCode returnCode) {
connectReturnCode.set(returnCode);
connectLatch.countDown();
}
@Override
public void subscribed(MqttClient client, Subscription[] requestedSubscriptions, Subscription[] grantedSubscriptions, boolean requestsGranted) {
}
@Override
public void unsubscribed(MqttClient client, String[] topics) {
}
@Override
public void published(MqttClient client, PublishMessage message) {
}
};
// Build your client. This client is an asynchronous one so all interaction with the broker will be non-blocking.
MqttClient client = new AsyncMqttClient("tcp://mqtt-broker:1883", listener, 5);
try {
// Connect to the broker. We will await the return code so that we know whether or not we can even begin publishing.
client.connect("musicProducerAsync", false, "music-user", "music-pass");
connectLatch.await();
ConnectReturnCode returnCode = connectReturnCode.get();
if (returnCode == null || returnCode != ConnectReturnCode.ACCEPTED) {
// The broker bounced us. We are done.
log.error("The broker rejected our attempt to connect. Reason: " + returnCode);
return;
}
// Publish a musical catalog
client.publish(new PublishMessage("grand/funk/railroad", QoS.AT_MOST_ONCE, "On Time"));
client.publish(new PublishMessage("grand/funk/railroad", QoS.AT_MOST_ONCE, "E Pluribus Funk"));
client.publish(new PublishMessage("jefferson/airplane", QoS.AT_MOST_ONCE, "Surrealistic Pillow"));
client.publish(new PublishMessage("jefferson/airplane", QoS.AT_MOST_ONCE, "Crown of Creation"));
client.publish(new PublishMessage("seventies/prog/rush", QoS.AT_MOST_ONCE, "2112"));
client.publish(new PublishMessage("seventies/prog/rush", QoS.AT_MOST_ONCE, "A Farewell to Kings"));
client.publish(new PublishMessage("seventies/prog/rush", QoS.AT_MOST_ONCE, "Hemispheres"));
} catch (Exception ex) {
log.error("An exception prevented the publishing of the full catalog.", ex);
} finally {
// We are done. Disconnect.
if (!client.isClosed()) {
client.disconnect();
}
}
} | 6 |
public Object adjustParameterValueForEnumRefValue( Object aParameterValue, ParameterT aParameter, ControlT aControl )
{
logger.debug("aParameterValue: " + aParameterValue + " aParameter: " + aParameter + " aControl: " + aControl );
if ( ( aParameterValue != null ) && ( aParameter != null ) && ( aControl != null ) )
{
if ( aControl instanceof CheckBoxT )
{
CheckBoxT tempCheckBox = (CheckBoxT) aControl;
EnumPairT tempCheckedEnumPair = ParameterHelper.getEnumPairForEnumID( aParameter, tempCheckBox.getCheckedEnumRef() );
EnumPairT tempUncheckedEnumPair = ParameterHelper.getEnumPairForEnumID( aParameter, tempCheckBox.getUncheckedEnumRef() );
String tempParameterValueString = aParameterValue.toString();
logger.debug("tempParameterValueString: " + tempParameterValueString + " tempCheckedEnumPair: " + tempCheckedEnumPair + " tempUncheckedEnumPair: " + tempUncheckedEnumPair );
if ( ( tempCheckedEnumPair != null ) && ( tempParameterValueString.equals( tempCheckedEnumPair.getWireValue() ) ) )
{
return Boolean.TRUE.toString();
}
else if ( ( tempUncheckedEnumPair != null ) && ( tempParameterValueString.equals( tempUncheckedEnumPair.getWireValue() ) ) )
{
return Boolean.FALSE.toString();
}
}
}
return aParameterValue;
} | 8 |
@Override
public String getStylePref(String type) {
if(type.equals("doctype")) {
return DOCTYPE_COLOR;
}
if(type.equals("html")) {
return HTML_COLOR;
}
if(type.equals("string")) {
return STRING_COLOR;
}
if(type.equals("tag")) {
return TAG_COLOR;
}
if(type.equals("expression")) {
return EXPR_COLOR;
}
if(type.equals("action")) {
return ACTION_COLOR;
}
if(type.equals("skipped")) {
return SKIPPED_COLOR;
}
if(type.equals("keyword")) {
return KEYWORD_COLOR;
}
return DEFAULT_COLOR;
} | 8 |
@Override
public boolean saveLog(String name) {
// stringefy dataLog and save to file in readable
// xml format
String dump = "";
String ret = "\n";
dump += dataLog.size() + ret;
Iterator<DataItem> it=dataLog.iterator();
while(it.hasNext()){
DataItem i = it.next();
dump += i.dataName + ret;
dump += i.dataType + ret;
dump += i.receivedTime + ret;
dump += i.key + ret;
dump += i.sender + ret;
dump += i.dataPayload + ret;
}
PrintWriter writer = null;
try {
writer = new PrintWriter(name, "UTF-8");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
writer.println(dump);
writer.close();
return false;
} | 3 |
public static void updateAPList ()
{
for(int x = 0; x < chbxlist.size() ; x++)
{
String [] parse = chbxlist.get(x).getText().split("Sample Count: " );
chbxlist.get(x).setText(parse[0] + "Sample Count: " + PaintPane.Mac.get(x).getSampleCount() + "<br>" +
"</html>");
}
for(int x = chbxlist.size(); x < PaintPane.Mac.size(); x++)
{
String panelContents = "<html>" + (x+1) + "- ESSID: " + PaintPane.Mac.get(x).getESSID() + "<br>" +
"MAC: " + PaintPane.Mac.get(x).getMacAddress() + "<br>" +
"Channel: " + PaintPane.Mac.get(x).getChannel() + "<br>" +
"Position: (" + PaintPane.Mac.get(x).getApX() + "," + PaintPane.Mac.get(x).getApY() + ")" + "<br>" +
"Sample Count: " + PaintPane.Mac.get(x).getSampleCount() + "<br>" +
"</html>";
chbxlist.add(new JCheckBox(panelContents, PaintPane.Mac.get(x).isRepresented()));
chbxlist.get(x).setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
chbxlist.get(x).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
JCheckBox ch = (JCheckBox) e.getSource();
String [] s = ch.getText().split("<html>");
s = s[1].split("- ESSID");
PaintPane.Mac.get(Integer.parseInt(s[0])-1).setRepresented( (e.getStateChange() == ItemEvent.SELECTED? true:false) );
/*
if (PaintPane.Mac.get(Integer.parseInt(s[0])-1).isRepresented())
System.out.println("YES " + PaintPane.Mac.get(Integer.parseInt(s[0])-1).getMacAddress());
else if (!PaintPane.Mac.get(Integer.parseInt(s[0])-1).isRepresented())
System.out.println("NO " + PaintPane.Mac.get(Integer.parseInt(s[0])-1).getMacAddress());
/* for (int i = 0 ; i < PaintPane.mySamples.size(); i++)
{
PaintPane.mySamples.get(i).changeMaxRSSI();
}
*/
}
});
authAP_sp.add(chbxlist.get(x));
authAP_sp.validate();
authAP_sp.repaint();
}
} | 3 |
public Type getHint() {
if (ifaces.length == 0 || (clazz == null && ifaces.length == 1))
return this;
if (clazz != null)
return Type.tClass(clazz.getName());
else
return Type.tClass(ifaces[0].getName());
} | 4 |
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerMove(PlayerMoveEvent event) {
if (plugin.datacore.getBoolean("users." + event.getPlayer().getName() + ".frozen") == true){
Location from = event.getFrom();
double xfrom = event.getFrom().getX();
double yfrom = event.getFrom().getY();
double zfrom = event.getFrom().getZ();
double xto = event.getTo().getX();
double yto = event.getTo().getY();
double zto = event.getTo().getZ();
if (!(xfrom == xto && yfrom == yto && zfrom == zto)) {
event.getPlayer().teleport(from);
}
}
if (plugin.datacore.getBoolean("events.evac") == true && plugin.config.getBoolean("evacExempt." + event.getPlayer().getName()) == false){
Location from = event.getFrom();
double xfrom = event.getFrom().getX();
double yfrom = event.getFrom().getY();
double zfrom = event.getFrom().getZ();
double xto = event.getTo().getX();
double yto = event.getTo().getY();
double zto = event.getTo().getZ();
if (!(xfrom == xto && yfrom == yto && zfrom == zto)) {
event.getPlayer().teleport(from);
}
}
} | 9 |
@Override
public String perform(Company which) {
int n = Random.getInstance().randomInt(6);
String in = JOptionPane.showInputDialog(null, "You have landed on the Patents tile. "
+ "Enter 0-5 to try your luck!", "Patents Tile", JOptionPane.QUESTION_MESSAGE);
try {
int val = Integer.parseInt(in);
if (val == n) {
which.incrPatentCount();
return "You are in luck today. You have just acquired a new patent.";
}
} catch (NumberFormatException ex) {
}
return "hard Luck better try next time! (" + n + ")";
} | 7 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ScrollRestriction other = (ScrollRestriction) obj;
if (itemslots == null) {
if (other.itemslots != null)
return false;
} else if (!itemslots.equals(other.itemslots))
return false;
if (itemtype == null) {
if (other.itemtype != null)
return false;
} else if (!itemtype.equals(other.itemtype))
return false;
return true;
} | 9 |
private boolean r_un_accent() {
int v_3;
// (, line 215
// atleast, line 216
{
int v_1 = 1;
// atleast, line 216
replab0: while(true)
{
lab1: do {
if (!(out_grouping_b(g_v, 97, 251)))
{
break lab1;
}
v_1--;
continue replab0;
} while (false);
break replab0;
}
if (v_1 > 0)
{
return false;
}
}
// [, line 217
ket = cursor;
// or, line 217
lab2: do {
v_3 = limit - cursor;
lab3: do {
// literal, line 217
if (!(eq_s_b(1, "\u00E9")))
{
break lab3;
}
break lab2;
} while (false);
cursor = limit - v_3;
// literal, line 217
if (!(eq_s_b(1, "\u00E8")))
{
return false;
}
} while (false);
// ], line 217
bra = cursor;
// <-, line 217
slice_from("e");
return true;
} | 8 |
public JSONArray toJSONArray(JSONArray names) throws JSONException {
if (names == null || names.length() == 0) {
return null;
}
JSONArray ja = new JSONArray();
for (int i = 0; i < names.length(); i += 1) {
ja.put(this.opt(names.getString(i)));
}
return ja;
} | 3 |
protected ConfigurationSerializable deserializeViaMethod(Method method, Map<String, Object> args) {
try {
ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args);
if (result == null) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization: method returned null");
} else {
return result;
}
} catch (Throwable ex) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(
Level.SEVERE,
"Could not call method '" + method.toString() + "' of " + clazz + " for deserialization",
ex instanceof InvocationTargetException ? ex.getCause() : ex);
}
return null;
} | 3 |
public void updateReplicaState(Replica replica) {
switch (replica.getState()) {
case FAILED:
case CANCELLED:
case ABORTED:
boolean anyRunning = false;
for (Replica eachReplica : replica.getTask().getReplicas()) {
if (ExecutionState.RUNNING.equals(eachReplica.getState())) {
anyRunning = true;
break;
}
}
if (!anyRunning) {
unallocatedTasks.add(replica.getTask());
}
break;
default:
break;
}
} | 6 |
@EventHandler
public void EnderDragonJump(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getEnderDragonConfig().getDouble("EnderDragon.Jump.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getEnderDragonConfig().getBoolean("EnderDragon.Jump.Enabled", true) && damager instanceof EnderDragon && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, plugin.getEnderDragonConfig().getInt("EnderDragon.Jump.Time"), plugin.getEnderDragonConfig().getInt("EnderDragon.Jump.Power")));
}
} | 6 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Paciente other = (Paciente) obj;
if (!Objects.equals(this.idPessoa, other.idPessoa)) {
return false;
}
return true;
} | 3 |
public SortedMap<Long, Boolean> berechneZustandsWechselZustand(Long von, Long bis, int jahr)
{
// Die Abfrage besitzt eine eigene Zustandsliste
// ListeZustandsWechsel listeZustandsWechselAbfrage = new ListeZustandsWechsel();
listeZustandsWechsel = new ListeZustandsWechsel();
long time = 0;
long days = 0;
Calendar cal1 = new GregorianCalendar().getInstance();
Calendar cal2 = new GregorianCalendar();
Calendar tmp = new GregorianCalendar();
SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss,SSS");
Date dt = new Date();
int diff = jahr - cal1.get(Calendar.YEAR);
int temp = cal1.get(Calendar.YEAR) + diff;
try
{
cal1.setTimeInMillis(von);
cal2.setTimeInMillis(bis);
// cal1.set(Calendar.YEAR, temp);
// cal2.set(Calendar.YEAR, temp);
// Die Abfrage beginnt um...
cal1.set(Calendar.HOUR_OF_DAY, 0);
cal1.set(Calendar.MINUTE, 0);
cal1.set(Calendar.SECOND, 0);
cal1.set(Calendar.MILLISECOND, 0);
// Die Abfrage endet um...
cal2.set(Calendar.HOUR_OF_DAY, 23);
cal2.set(Calendar.MINUTE, 59);
cal2.set(Calendar.SECOND, 59);
cal2.set(Calendar.MILLISECOND, 999);
// Wie viele Tage hat das Jahr?
time = cal2.getTime().getTime() - cal1.getTime().getTime();
days = Math.round((double)time / (24. * 60. * 60. * 1000.));
// Der erste Tag der Abfrage endet um...
cal2.setTimeInMillis(von);
cal2.set(Calendar.YEAR, temp);
cal2.set(Calendar.HOUR_OF_DAY, 23);
cal2.set(Calendar.MINUTE, 59);
cal2.set(Calendar.SECOND, 59);
cal2.set(Calendar.MILLISECOND, 999);
if (definition.equalsIgnoreCase("ostersonntag"))
{
Ostern ostersonntag = new Ostern();
cal1 = ostersonntag.Ostersonntag(temp);
// Der Ostersonntag beginnt um...
dt = df.parse(cal1.get(Calendar.DATE) + "." + (cal1.get(Calendar.MONTH) + 1) + "." + temp + " 00:00:00,000");
cal1.setTime(dt);
// ...und endet um...
dt = df.parse(cal1.get(Calendar.DATE) + "." + (cal1.get(Calendar.MONTH) + 1) + "." + temp + " 23:59:59,999");
cal2.setTime(dt);
// ...er dauert natuerlich auch nur...
days = 1;
}
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
DateFormat df_ger = DateFormat.getDateInstance(DateFormat.FULL, Locale.GERMANY);
for (int i = 0; i < days; i++)
{
// Man spricht Deutsch!
String datum = df_ger.format(cal1.getTime()).toLowerCase();
// Wochentag ist hier...
String woTag = definition;
if (definition.equals("tag"))
{
// listeZustandsWechselAbfrage.getListeZustandsWechsel().put(cal1.getTimeInMillis(), true);
listeZustandsWechsel.getListeZustandsWechsel().put(cal1.getTimeInMillis(), true);
}
else if (definition.equals("ostersonntag"))
{
// listeZustandsWechselAbfrage.getListeZustandsWechsel().put(cal1.getTimeInMillis(), true);
listeZustandsWechsel.getListeZustandsWechsel().put(cal1.getTimeInMillis(), true);
}
else if (datum.contains(woTag))
{
// listeZustandsWechselAbfrage.getListeZustandsWechsel().put(cal1.getTimeInMillis(), true);
listeZustandsWechsel.getListeZustandsWechsel().put(cal1.getTimeInMillis(), true);
}
tmp = cal1;
tmp.add(Calendar.DATE, 1);
cal1 = tmp;
if (definition.equals("tag"))
{
// listeZustandsWechselAbfrage.getListeZustandsWechsel().put(cal2.getTimeInMillis(), false);
listeZustandsWechsel.getListeZustandsWechsel().put(cal2.getTimeInMillis(), false);
// listeZustandsWechselAbfrage.getListeZustandsWechsel().put(cal2.getTimeInMillis()+1, false);
}
else if (definition.equals("ostersonntag"))
{
// listeZustandsWechselAbfrage.getListeZustandsWechsel().put(cal2.getTimeInMillis(), false);
listeZustandsWechsel.getListeZustandsWechsel().put(cal2.getTimeInMillis(), false);
// listeZustandsWechselAbfrage.getListeZustandsWechsel().put(cal2.getTimeInMillis()+1, false);
}
else if (datum.contains(woTag))
{
// listeZustandsWechselAbfrage.getListeZustandsWechsel().put(cal2.getTimeInMillis(), false);
listeZustandsWechsel.getListeZustandsWechsel().put(cal2.getTimeInMillis(), false);
// listeZustandsWechselAbfrage.getListeZustandsWechsel().put(cal2.getTimeInMillis()+1, false);
}
tmp = cal2;
tmp.add(Calendar.DATE, 1);
cal2 = tmp;
}
// return listeZustandsWechselAbfrage.getListeZustandsWechsel();
return listeZustandsWechsel.getListeZustandsWechsel();
} | 9 |
protected static long getLong(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return -1;
}
return Long.parseLong(str);
} | 3 |
public boolean matches(Item item) {
if (item instanceof ToolItem) {
ToolItem other = (ToolItem) item;
if (other.type != type) return false;
if (other.level != level) return false;
return true;
}
return false;
} | 3 |
public List<String> getColumnTitles() {
List<String> titles = new ArrayList<String>();
for (HeaderCell cell : cells) {
titles.add(cell.getValue());
}
return titles;
} | 1 |
public static void main(String args[]){
//Creating a colour scheme to test the renderer with
int colourSize = 5;
Colour[] colours = new Colour[colourSize];
for (int i=0; i<colourSize; i++) {
switch (i) {
case 0: Colour black = new Colour("#000000");
colours[i] = black;
break;
case 1: Colour darkgrey = new Colour("#222222");
colours[i] = darkgrey;
break;
case 2: Colour grey = new Colour("#555555");
colours[i] = grey;
break;
case 3: Colour lightgrey = new Colour("#BBBBBB");
colours[i] = lightgrey;
break;
case 4: Colour white = new Colour("#EEEEEE");
colours[i] = white;
break;
}
}
ColourMap greyscale = new ColourMap(colours, "Greyscale");
CustomBubbleRenderer testRenderer =
new CustomBubbleRenderer(greyscale);
//Test GetMap method
System.out.println("CustomBubbleRenderer:: GetMap()");
testRenderer.GetMap();
System.out.println("CustomBubbleRenderer:: GetMap() - Test Passed");
//Test SetMap method
System.out.println("CustomBubbleRenderer:: SetMap()");
testRenderer.SetMap(greyscale);
System.out.println("CustomBubbleRenderer:: SetMap() - Test Passed");
} | 6 |
final void method3750(int i, Interface2 interface2) {
try {
if (i <= 39)
((OpenGlToolkit) this).anInt7782 = 120;
if (interface2 != anInterface2_7852) {
if (aBoolean7873)
OpenGL.glBindBufferARB(34962, interface2.method10(true));
anInterface2_7852 = interface2;
}
anInt7552++;
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("qo.D(" + i + ','
+ (interface2 != null ? "{...}"
: "null")
+ ')'));
}
} | 5 |
public synchronized String getMessage() throws InterruptedException {
notify();
while (messages.size() == 0)
wait();
String message = (String) messages.firstElement();
messages.removeElement(message);
return message;
} | 1 |
@Test
public void MinMaxWithMultipleInserts() {
l.insert(b);
for (int i = 0; i < 10; i++) {
l.insert(v);
}
l.insert(a);
assertEquals(a, l.min());
assertEquals(b, l.max());
} | 1 |
public void revalidatePieces()
{
int amountOfRemovedLooseSnakePieces = 0;
for (int i = 0; i < looseSnakePieces.size(); i++)
{
Piece piece = looseSnakePieces.get(i);
if (checkForOutOfBoundsForPiece(piece))
{
looseSnakePieces.remove(i);
amountOfRemovedLooseSnakePieces++;
}
}
for (int i = 0; i < amountOfRemovedLooseSnakePieces; i++)
{
createNewLooseSnakePiece();
controller.updateLooseSnakePiecesInView();
}
for (int i = 0; i < worldChangers.size(); i++)
{
Piece piece = (Piece) worldChangers.get(i);
if (checkForOutOfBoundsForPiece(piece))
{
worldChangers.remove(i);
}
}
for (int i = 0; i < currentBooster.size(); i++)
{
Piece piece = (Piece) currentBooster.get(i);
if (checkForOutOfBoundsForPiece(piece))
{
currentBooster.remove(i);
}
}
} | 7 |
public AbstractPlay nextPlay(){
Huffer huffer = new Huffer(this);
largestCapture = huffer.getLargestCapture();
FactoryOfPlaysForCpu factory = new FactoryOfPlaysForCpu(this,largestCapture);
AbstractPlay play = factory.getBest();
return play;
} | 0 |
public boolean addPiece(Tetromino piece, int x, int y, int orientation){
boolean[][] tiles = piece.getTiles();
int count = 0;
int width = piece.getTiles()[0].length == 9 ? 3 : 4; // get width (3 or 4) of piece
width = piece.getTiles()[0].length == 4 ? 2 : width;
for(int row = 0; row < width; ++row) {
for(int col = 0; col < width; ++col){
if(tiles[orientation][count++]){
if(screen[y+row][x+col].isEmpty()){
screen[row+y][col+x] = new Square(false, piece.getColor());
} else {
return false;
}
}
}
}
return true;
} | 6 |
public void insertFirst(int value)
{
if(isFull())
throw new ArrayIndexOutOfBoundsException();
for(int i = size; i > 0; i--)
ListArray[i] = ListArray[i-1];
ListArray[0] = value;
size++;
} | 2 |
public int getAnswerIndex() {
if(answer == null || options == null || isSurvey || style != DROP_DOWN_QUESTION){
return -1;
}
for(int i=0; i<options.length; i++){
if(answer.equals(options[i])){
return i;
}
}
return -1;
} | 6 |
protected static Class tryLoadMainClass(String jarFileName, String fileClassName) throws Exception {
try {
JarClassLoader loader;
try {
loader = new JarClassLoader(new URL("file:///" + jarFileName));
}
catch (MalformedURLException exc) {
throw new Exception("MalformedURLException: " + exc.getMessage());
}
String className = fileClassName;
String mainClassName = loader.getMainClassName();
//..
int pos = className.indexOf(".");
if (pos != -1) {
className = className.substring(0, pos);
}
else {
throw new Exception("Incorrect fullname class file (must be ex: packagename/classname.class)");
}
//..
className = className.replace("/", ".");
//..
Class clss = null;
if (className.equalsIgnoreCase(mainClassName))
clss = loader.loadClass(mainClassName);
return clss;
}
catch (Exception exc) {
throw new Exception("loadMainClass: " + exc.getMessage());
}
} | 4 |
public ListNode mergeKLists(ListNode[] lists)
{
if (lists.length == 0)
return null;
NavigableSet<ListNode> priorityQueue = new TreeSet<ListNode>(
new ListNodeComparator());
for (ListNode node : lists) {
if (node == null)
continue;
priorityQueue.add(node);
}
if (priorityQueue.isEmpty())
return null;
ListNode result = priorityQueue.pollFirst();
ListNode current = result;
if (result.next != null) {
priorityQueue.add(result.next);
}
while (!priorityQueue.isEmpty()) {
ListNode smallest = priorityQueue.pollFirst();
if (smallest.next != null) {
priorityQueue.add(smallest.next);
}
current.next = smallest;
current = smallest;
}
return result;
} | 7 |
@Override
public void out() throws Exception {
Object val = getFieldValue();
// Object val = access;
if (ens.shouldFire()) {
DataflowEvent e = new DataflowEvent(ens.getController(), this, val);
// DataflowEvent e = new DataflowEvent(ens.getController(), this, access.toObject());
ens.fireOut(e);
// the value might be altered
val = e.getValue();
}
// if data==null this unconsumed @Out, its OK but we do not want to set it.
if (data != null) {
data.setValue(val);
}
} | 2 |
public boolean savemoreinfo() {
BufferedWriter characterfile = null;
try {
characterfile = new BufferedWriter(new FileWriter("./moreinfo/"+playerName+".txt"));
characterfile.write("[MOREINFO]", 0, 10);
characterfile.newLine();
characterfile.write("character-clueid = ", 0, 19);
characterfile.write(Integer.toString(clueid), 0, Integer.toString(clueid).length());
characterfile.newLine();
characterfile.write("character-cluelevel = ", 0, 22);
characterfile.write(Integer.toString(cluelevel), 0, Integer.toString(cluelevel).length());
characterfile.newLine();
characterfile.write("character-cluestage = ", 0, 22);
characterfile.write(Integer.toString(cluestage), 0, Integer.toString(cluestage).length());
characterfile.newLine();
characterfile.write("character-lastlogin = ", 0, 22);
characterfile.write(connectedFrom, 0, connectedFrom.length());
characterfile.newLine();
characterfile.write("character-lastlogintime = ", 0, 26);
characterfile.write(Integer.toString(playerLastLogin), 0, Integer.toString(playerLastLogin).length());
characterfile.newLine();
characterfile.write("character-reputation = ", 0, 23);
characterfile.write(Integer.toString(reputation), 0, Integer.toString(reputation).length());
characterfile.newLine();
characterfile.write("character-ancients = ", 0, 21);
characterfile.write(Integer.toString(ancients), 0, Integer.toString(ancients).length());
characterfile.newLine();
characterfile.write("character-starter = ", 0, 20);
characterfile.write(Integer.toString(starter), 0, Integer.toString(starter).length());
characterfile.newLine();
characterfile.write("character-hasegg = ", 0, 19);
characterfile.write(Integer.toString(hasegg), 0, Integer.toString(hasegg).length());
characterfile.newLine();
characterfile.write("character-hasset = ", 0, 19);
characterfile.write(Integer.toString(hasset), 0, Integer.toString(hasset).length());
characterfile.newLine();
characterfile.write("character-pkpoints = ", 0, 21);
characterfile.write(Integer.toString(pkpoints), 0, Integer.toString(pkpoints).length());
characterfile.newLine();
characterfile.write("character-killcount = ", 0, 22);
characterfile.write(Integer.toString(killcount), 0, Integer.toString(killcount).length());
characterfile.newLine();
characterfile.write("character-deathcount = ", 0, 23);
characterfile.write(Integer.toString(deathcount), 0, Integer.toString(deathcount).length());
characterfile.newLine();
characterfile.write("character-mutedate = ", 0, 21);
characterfile.write(Integer.toString(mutedate), 0, Integer.toString(mutedate).length());
characterfile.newLine();
characterfile.write("character-height = ", 0, 19);
characterfile.write(Integer.toString(heightLevel), 0, Integer.toString(heightLevel).length());
characterfile.newLine();
characterfile.newLine();
characterfile.write("[QUESTS]", 0, 8);
characterfile.newLine();
characterfile.write("character-questpoints = ", 0, 24);
characterfile.write(Integer.toString(totalqp), 0, Integer.toString(totalqp).length());
characterfile.newLine();
characterfile.write("character-quest_1 = ", 0, 20);
characterfile.write(Integer.toString(q1stage), 0, Integer.toString(q1stage).length());
characterfile.newLine();
characterfile.write("character-quest_2 = ", 0, 20);
characterfile.write(Integer.toString(q2stage), 0, Integer.toString(q2stage).length());
characterfile.newLine();
characterfile.write("character-quest_3 = ", 0, 20);
characterfile.write(Integer.toString(q3stage), 0, Integer.toString(q3stage).length());
characterfile.newLine();
characterfile.newLine();
characterfile.write("[LOOK]", 0, 6);
characterfile.newLine();
for (int i = 0; i < playerLook.length; i++) {
characterfile.write("character-look = ", 0, 17);
characterfile.write(Integer.toString(i), 0, Integer.toString(i).length());
characterfile.write(" ", 0, 1);
characterfile.write(Integer.toString(playerLook[i]), 0, Integer.toString(playerLook[i]).length());
characterfile.newLine();
characterfile.write("character-head = ", 0, 17);
characterfile.write(Integer.toString(pHead), 0, Integer.toString(pHead).length());
characterfile.newLine();
characterfile.write("character-torso = ", 0, 18);
characterfile.write(Integer.toString(pTorso), 0, Integer.toString(pTorso).length());
characterfile.newLine();
characterfile.write("character-arms = ", 0, 17);
characterfile.write(Integer.toString(pArms), 0, Integer.toString(pArms).length());
characterfile.newLine();
characterfile.write("character-hands = ", 0, 18);
characterfile.write(Integer.toString(pHands), 0, Integer.toString(pHands).length());
characterfile.newLine();
characterfile.write("character-legs = ", 0, 17);
characterfile.write(Integer.toString(pLegs), 0, Integer.toString(pLegs).length());
characterfile.newLine();
characterfile.write("character-feet = ", 0, 17);
characterfile.write(Integer.toString(pFeet), 0, Integer.toString(pFeet).length());
characterfile.newLine();
characterfile.write("character-beard = ", 0, 18);
characterfile.write(Integer.toString(pBeard), 0, Integer.toString(pBeard).length());
characterfile.newLine();
characterfile.newLine();
}
characterfile.newLine();
characterfile.write("[FRIENDS]", 0, 9);
characterfile.newLine();
for (int i = 0; i < friends.length; i++) {
if (friends[i] > 0) {
characterfile.write("character-friend = ", 0, 19);
characterfile.write(Integer.toString(i), 0, Integer.toString(i).length());
characterfile.write(" ", 0, 1);
characterfile.write(Long.toString(friends[i]), 0, Long.toString(friends[i]).length());
characterfile.newLine();
}
}
characterfile.newLine();
characterfile.write("[IGNORES]", 0, 9);
characterfile.newLine();
for (int i = 0; i < ignores.length; i++) {
if (ignores[i] > 0) {
characterfile.write("character-ignore = ", 0, 19);
characterfile.write(Integer.toString(i), 0, Integer.toString(i).length());
characterfile.write(" ", 0, 1);
characterfile.write(Long.toString(ignores[i]), 0, Long.toString(ignores[i]).length());
characterfile.newLine();
}
}
characterfile.newLine();
characterfile.write("[HIDDEN]", 0, 8);
characterfile.newLine();
characterfile.write("character-points = ", 0, 19);
characterfile.write(Integer.toString(hiddenPoints), 0, Integer.toString(hiddenPoints).length());
characterfile.newLine();
characterfile.write("character-foundz[1] = ", 0, 22);
characterfile.write(Integer.toString(foundz[1]), 0, Integer.toString(foundz[1]).length());
characterfile.newLine();
characterfile.write("character-foundz[2] = ", 0, 22);
characterfile.write(Integer.toString(foundz[2]), 0, Integer.toString(foundz[2]).length());
characterfile.newLine();
characterfile.write("character-foundz[3] = ", 0, 22);
characterfile.write(Integer.toString(foundz[3]), 0, Integer.toString(foundz[3]).length());
characterfile.newLine();
characterfile.write("character-foundz[4] = ", 0, 22);
characterfile.write(Integer.toString(foundz[4]), 0, Integer.toString(foundz[4]).length());
characterfile.newLine();
characterfile.write("character-foundz[5] = ", 0, 22);
characterfile.write(Integer.toString(foundz[5]), 0, Integer.toString(foundz[5]).length());
characterfile.newLine();
characterfile.write("character-foundz[6] = ", 0, 22);
characterfile.write(Integer.toString(foundz[6]), 0, Integer.toString(foundz[6]).length());
characterfile.newLine();
characterfile.write("character-foundz[7] = ", 0, 22);
characterfile.write(Integer.toString(foundz[7]), 0, Integer.toString(foundz[7]).length());
characterfile.newLine();
characterfile.write("character-foundz[8] = ", 0, 22);
characterfile.write(Integer.toString(foundz[8]), 0, Integer.toString(foundz[8]).length());
characterfile.newLine();
characterfile.write("character-foundz[9] = ", 0, 22);
characterfile.write(Integer.toString(foundz[9]), 0, Integer.toString(foundz[9]).length());
characterfile.newLine();
characterfile.write("character-foundz[10] = ", 0, 23);
characterfile.write(Integer.toString(foundz[10]), 0, Integer.toString(foundz[10]).length());
characterfile.newLine();
characterfile.write("character-foundz[11] = ", 0, 23);
characterfile.write(Integer.toString(foundz[11]), 0, Integer.toString(foundz[11]).length());
characterfile.newLine();
characterfile.write("character-foundz[12] = ", 0, 23);
characterfile.write(Integer.toString(foundz[12]), 0, Integer.toString(foundz[12]).length());
characterfile.newLine();
characterfile.newLine();
characterfile.write("[EOF]", 0, 5);
characterfile.newLine();
characterfile.newLine();
characterfile.close();
} catch(IOException ioexception) {
misc.println(playerName+": error writing file.");
return false;
}
return true;
} | 6 |
private void jLabelUrlMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelUrlMousePressed
if (evt.getButton() == java.awt.event.MouseEvent.BUTTON1 && jLabelUrl.isEnabled()) {
if (java.awt.Desktop.isDesktopSupported()) {
java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
if(desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
String url = jLabelUrl.getToolTipText();
try {
java.net.URI uri = new java.net.URI(url);
desktop.browse(uri);
}
catch (URISyntaxException e) {
Logger.getLogger(JAboutDialog.class.getName()).log(Level.SEVERE, null, e);
}
catch (IOException e) {
Logger.getLogger(JAboutDialog.class.getName()).log(Level.SEVERE, null, e);
}
finally {
jLabelUrl.setEnabled(false);
}
}
}
}
}//GEN-LAST:event_jLabelUrlMousePressed | 6 |
public int nextSelectedIndex(int fromIndex) {
int index = mSelection.nextSetBit(fromIndex);
return index < mSize ? index : -1;
} | 1 |
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case boardPackage.BOARD__COUNTRIES:
return ((InternalEList<?>)getCountries()).basicRemove(otherEnd, msgs);
case boardPackage.BOARD__BORDERS:
return ((InternalEList<?>)getBorders()).basicRemove(otherEnd, msgs);
case boardPackage.BOARD__CONTINENTS:
return ((InternalEList<?>)getContinents()).basicRemove(otherEnd, msgs);
case boardPackage.BOARD__CARDS:
return ((InternalEList<?>)getCards()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
} | 8 |
private List<ReducerEstimatedJvmCost> estimateReducersMemory(List<Reducer> eReducers, InitialJvmCapacity gcCap) {
int fReducerNum = finishedConf.getMapred_reduce_tasks();
if(fReducerNum == 0)
return null;
List<ReducerEstimatedJvmCost> reducersJvmCostList = new ArrayList<ReducerEstimatedJvmCost>();
ReducerMemoryEstimator memoryEstimator = new ReducerMemoryEstimator(finishedConf, newConf, gcCap);
ReducerEstimatedJvmCost jvmCost;
//reducer number doesn't change
if(fReducerNum == newConf.getMapred_reduce_tasks()) {
for(int i = 0; i < fReducerNum; i++) {
//use the corresponding finished reducer to estimate the new reducer
//if input data is changed, this model needs modification
//currently, this model assumes the total input data is as same as the finished one
jvmCost = memoryEstimator.esimateJvmCost(job.getReducerList().get(i), eReducers.get(i));
reducersJvmCostList.add(jvmCost);
}
}
//reducer number changes
else {
for(int i = 0; i < newConf.getMapred_reduce_tasks(); i++) {
//use all the finished reducers' infos to estimate the new reducer
jvmCost = memoryEstimator.esimateJvmCost(job.getReducerList(), eReducers.get(i));
reducersJvmCostList.add(jvmCost);
}
}
return reducersJvmCostList;
} | 4 |
public int characterAt(int at) throws JSONException {
int c = get(at);
if ((c & 0x80) == 0) {
return c;
}
int character;
int c1 = get(at + 1);
if ((c1 & 0x80) == 0) {
character = ((c & 0x7F) << 7) | c1;
if (character > 0x7F) {
return character;
}
} else {
int c2 = get(at + 2);
character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2;
if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF
&& (character < 0xD800 || character > 0xDFFF)) {
return character;
}
}
throw new JSONException("Bad character at " + at);
} | 8 |
public ChatRoom(String text, Client Client) {
initComponents();
this.roomId = text;
this.setTitle(text);
this.client = Client;
int screen_width = Toolkit.getDefaultToolkit().getScreenSize().width;
int screen_height = Toolkit.getDefaultToolkit().getScreenSize().height;
this.setLocation((screen_width - this.getWidth()) / 2,
(screen_height - this.getHeight()) / 2);
myList.setModel(model);
usernames.add(client.frame.getTitle().toString());
model.addElement(client.frame.getTitle().toString() + " ");
for ( int i = client.onLineUsers.size() - 1; i >= 0; i-- )
{
invite.addItem(client.onLineUsers.get(i));
}
this.setVisible(true);
} | 1 |
@Override
public String onAttack(L2Npc npc, L2PcInstance attacker, int damage, boolean isPet)
{
if (npc.isScriptValue(0))
{
int npcId = npc.getNpcId();
if (npcId != 20767)
{
for (int val : MINIONS.get(npcId))
{
L2Attackable newNpc = (L2Attackable) addSpawn(val, npc.getX() + Rnd.get(-150, 150), npc.getY() + Rnd.get(-150, 150), npc.getZ(), 0, false, 0, false);
attack(newNpc, attacker);
}
}
else
{
for (int val : MINIONS.get(npcId))
addSpawn(val, (npc.getX() + Rnd.get(-100, 100)), (npc.getY() + Rnd.get(-100, 100)), npc.getZ(), 0, false, 0, false);
npc.broadcastNpcSay(ORCS_WORDS[Rnd.get(ORCS_WORDS.length)]);
}
npc.setScriptValue(1);
}
return super.onAttack(npc, attacker, damage, isPet);
} | 4 |
@EventHandler
public void onGrowEvent(BlockGrowEvent evt){//FIXME
if(evt.getBlock().getType().equals(Material.CROPS)){
if(((Crops)evt.getNewState().getData()).getState() == CropState.RIPE){
for(Farm farm : mainClass.farmList){
if(farm.containsBlock(evt.getBlock())){
evt.getNewState().update();
for(ItemStack e : evt.getNewState().getBlock().getDrops())
farm.getChest().getInventory().addItem(e);
farm.getChest().getInventory().addItem(new ItemStack(Material.SEEDS, new Random().nextInt(2)+1));
if(farm.getChest().getInventory().contains(Material.SEEDS)){
farm.getChest().getInventory().getItem(farm.getChest().getInventory().first(Material.SEEDS)).setAmount(
farm.getChest().getInventory().getItem(farm.getChest().getInventory().first(Material.SEEDS)).getAmount()-1);
((Crops)evt.getNewState().getData()).setState(CropState.GERMINATED);
}else
evt.getNewState().setType(Material.AIR);
return;
}
}
}
}
} | 6 |
@Override
public void show() {
System.out.println(name + ", here are your search results:");
Auction[] auctionResults = as.search(input);
if(auctionResults.length > 0){
System.out.println(String.format("%-20s%-100s%-15s%-15s%-20s%-18s", "ID:", "Name:", "Current Bid:", "Bid Count:", "Owner:", "Ends By:"));
}
ArrayList<Long> auctionIds = new ArrayList<Long>();
for(Auction auc : auctionResults){
System.out.println(auc.toString());
if(auc.getCreator().equals(name)){
FileBasedDatasource fbd = new FileBasedDatasource();
fbd.editing(auc);
}
auctionIds.add(auc.getId());
}
if(auctionResults.length == 0){
System.out.println(name + ", no results match the search criteria of '" + input + "'.");
System.out.println("Enter another search or hit 'enter' to go back to home page.");
}
else{
System.out.println("\n" + "Enter the item id to increase the bid by $1. Otherwise, enter another search: (hit enter to go back to home page)");
// boolean loop = false;
// do{
// for(Long id : auctionIds){
// if(input.equals(id.toString())){
// loop = true;
// }
// else{
// System.out.println("try again");
// loop = false;
// }
// }
// }
// while(loop = false);
}
} | 4 |
public int readPacketBytes( byte[] buf, int offset, int maxLength )
throws IOException
{
int b = read();
int i;
for( i=0; b != -1 && (byte)b != END && i < maxLength; ++i ) {
if( (byte)b == ESC ) {
b = read();
if( (byte)b == ESC_END ) b = END;
else if( (byte)b == ESC_ESC ) b = ESC;
}
buf[i] = (byte)b;
b = read();
}
unread(b);
return i;
} | 6 |
byte[] buildBrushSoft(byte[] brush, CPBrushInfo brushInfo) {
int intSize = (int) (brushInfo.curSize + .99f);
float center = intSize / 2.f;
float sqrRadius = (brushInfo.curSize / 2) * (brushInfo.curSize / 2);
float xFactor = 1f + brushInfo.curSqueeze * MAX_SQUEEZE;
float cosA = (float) Math.cos(brushInfo.curAngle);
float sinA = (float) Math.sin(brushInfo.curAngle);
// byte[] brush = new int[size * size];
int offset = 0;
for (int j = 0; j < intSize; j++) {
for (int i = 0; i < intSize; i++) {
float x = (i + .5f - center);
float y = (j + .5f - center);
float dx = (x * cosA - y * sinA) * xFactor;
float dy = (y * cosA + x * sinA);
float sqrDist = dx * dx + dy * dy;
if (sqrDist <= sqrRadius) {
brush[offset++] = (byte) (255 * (1 - (sqrDist / sqrRadius)));
} else {
brush[offset++] = 0;
}
}
}
return brush;
} | 3 |
public ListaSimpleProceso crearProceso(int cantProcesos) {
String listadoProceso = "";
String nombre;
int i = 1;
while (i <= cantProcesos) {
nombre = JOptionPane.showInputDialog("Nombre del proceso " + i);
if (nombre.isEmpty()) {
int j= cantProcesos;
JOptionPane.showMessageDialog(null,"Debe de ingresar un proceso","ERROR",JOptionPane.YES_NO_OPTION);
crearProceso(cantProcesos);
i=j+1;
}
else{
lstProcesos.InsertaFinal(nombre);
listadoProceso = listadoProceso + "\nProceso No: " + i + ": "+ nombre;
i++;
}
}
System.out.println("Lista de procesos");
lstProcesos.Imprimir();
return lstProcesos;
} | 2 |
private static Integer getNumber(String toBeFormatted) {
StringBuilder sb = new StringBuilder();
char[] characters = toBeFormatted.toCharArray();
for (int i = 0; i < characters.length; i++){
if (characters[i] == '_') continue;
else if (Character.isDigit(characters[i])){
sb.append(characters[i]);
} else{
System.out.println(characters[i]);
System.out.println("Invalid format for number");
System.exit(-1);
}
}
return Integer.parseInt(sb.toString());
} | 3 |
@Test
@Ignore
public void test_AssociationListBulkDelete()
{
int liNumOfRecs = 3;
// Setup
AssociationList laAssocListData = associationListPost(liNumOfRecs);
// End Setup
// Bulk Delete
DefaultResponse laResponse = laClient
.postBulkDeleteAssociationList(laAssocListData);
Assert.assertEquals(laResponse.getStatus(), "SUCCESS");
// Verify
for (Association laAssoc : laAssocListData.getAssociationList())
{
AssociationList laAssocList = laClient.getAssociation(laAssoc.getEpc(),
AllianceTechRestClient.ID_TYPE_EPC);
Assert.assertNotNull(laAssocList);
Assert.assertNotNull(laAssocList.getAssociationList());
Assert.assertTrue(laAssocList.getAssociationList().size() == 0);
}
// Nothing to clean up
} | 1 |
public static JulianDate jauTaiutc(double tai1, double tai2) throws JSOFAIllegalParameter, JSOFAInternalError
{
boolean big1;
int i;
double a1, a2,dats1, ddats, dats2, datd = 0.0, as1, as2, da, d1, d2, fd;
double utc1, utc2;
/* Put the two parts of the TAI into big-first order. */
big1 = ( tai1 >= tai2 );
if ( big1 ) {
a1 = tai1;
a2 = tai2;
} else {
a1 = tai2;
a2 = tai1;
}
/* See if the TAI can possibly be in a leap-second day. */
d1 = a1;
dats1 = 0.0;
for ( i = -1; i <= 3; i++ ) {
d2 = a2 + (double) i;
Calendar dt;
dt = jauJd2cal(d1, d2 );
dats2 = jauDat(dt.iy, dt.im, dt.id, 0.0);
//FIXME if ( js < 0 ) return -1;
if ( i == -1 ) dats1 = dats2;
ddats = dats2 - dats1;
datd = dats1 / DAYSEC;
if ( abs(ddats) >= 0.5 ) {
/* Yes. Get TAI for the start of the UTC day that */
/* ends in a leap. */
JulianDate jd = jauCal2jd(dt.iy, dt.im, dt.id );
d1 = jd.djm0; d2 = jd.djm1;
as1 = d1;
as2 = d2 - 1.0 + datd;
/* Is the TAI after this point? */
da = a1 - as1;
da = da + ( a2 - as2 );
if ( da > 0 ) {
/* Yes: fraction of the current UTC day that has elapsed. */
fd = da * DAYSEC / ( DAYSEC + ddats );
/* Ramp TAI-UTC to bring about SOFA's JD(UTC) convention. */
datd += ddats * ( fd <= 1.0 ? fd : 1.0 ) / DAYSEC;
}
/* Done. */
break;
}
dats1 = dats2;
}
/* Subtract the (possibly adjusted) TAI-UTC from TAI to give UTC. */
a2 -= datd;
/* Return the UTC result, preserving the TAI order. */
if ( big1 ) {
utc1 = a1;
utc2 = a2;
} else {
utc1 = a2;
utc2 = a1;
}
/* TODO Status */
return new JulianDate(utc1, utc2);
}; | 7 |
private void completeInPlaceRestore(FileDTO file, VersionDTO version)
throws DBException, IOException
{
Manager db = getDb();
Logger log = log();
ReplicaDTO replica = getCurrentReplica();
FileDAO fileDAO = db.findDAO(FileDAO.class);
LastSyncDAO lsDAO = db.findDAO(LastSyncDAO.class);
VersionDAO versionDAO = db.findDAO(VersionDAO.class);
Number nameId = version.getNameId();
if (null == nameId)
nameId = file.getNameId();
// use a transaction for undelete, rename (if needed) and sync record update
Transaction txn = db.beginTransaction();
try
{
// if the restored file needs renaming
if (file.getNameId() != nameId.longValue())
{
File originalPath = db.findDAO(NodeNameDAO.class).toLocalFile(file.getNameId(), replica.getPath());
VersionDTO current = versionDAO.findCurrentVersion(file);
if (!current.isDeletionMark() && originalPath.isFile() && !originalPath.delete())
log.warning("Cleanup failed for local file '" + originalPath + "'");
versionDAO.beforeFileNameChange(file);
lsDAO.beforeFileNameChange(file);
file.setNameId(nameId.longValue());
fileDAO.update(file);
}
// update the sync record when a file is being restored in-place
lsDAO.recordSync(replica, version);
txn.commit();
txn = null;
}
finally
{
if (null != txn)
try { txn.abort(); }
catch (DBException fail)
{
log.log(Level.WARNING, "Rollback failed after unsuccessful renaming of " + file, fail);
}
}
} | 7 |
public void setIsHostToZero(String hostName){
try {
cs = con.prepareCall("{call SET_ISHOST_TO_ZERO(?)}");
cs.setString(1, hostName);
cs.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} | 1 |
@Override
protected EntityManager getEntityManager() {
return em;
} | 0 |
private void test() {
final String title = "PushTraps - Prueba";
final String body = "Esto es una notificación de prueba de Pushtraps. Si puedes ver este mensaje,"
+ " la aplicación está funcionando";
BufferedReader bufferRead;
Service service;
int i;
int option;
try {
UI.printHeader();
System.out.println(services.size() + " servicios activos:");
System.out.println("");
for (i = 0; i < services.size(); i++) {
service = services.get(i);
System.out.println((i + 1) + ") Servicio: "
+ service.getType() + " Alias: "
+ service.getAlias());
}
System.out.println("");
System.out.print("Elige el servicio para probar: ");
bufferRead = new BufferedReader(new InputStreamReader(System.in));
option = Integer.parseInt(bufferRead.readLine());
service = services.get(option - 1);
service.pushMessage(title, body);
UI.setInfo("Enviado mensaje de prueba a " + service.getAlias());
} catch (IOException e) {
e.printStackTrace();
}
} | 2 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.