method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
d735083d-e79a-4713-a7fc-4c4d1c68706d | 6 | public void run() {
if (logic.getEnemyState(0) == false && currente == 1) {
currente = 2;
}
if (logic.getEnemyState(1) == false && currente == 2) {
currente = 3;
}
if (logic.getEnemyState(2) == false && currente == 3) {
currente = 1;
}
repaint();
} |
4bdf1abc-33c8-41cc-8598-2bf0e3f58229 | 2 | public Roster getRosterByID (int id) {
for (Roster r: rosters)
if (r.getRosterID() == id)
return r;
return null;
} |
ca20e8e4-c3b5-4ce5-a8a4-5293d8a29383 | 6 | private void parse( String directory )
{
// Go through each directory and get the java source
// files for this dir.
log.debug( "Scanning " + directory );
DirectoryScanner directoryScanner = new DirectoryScanner();
File baseDir = new File( directory );
directoryScanner.setBasedir( baseDir );
directoryScanner.setExcludes( excludes );
directoryScanner.setIncludes( includes );
directoryScanner.scan();
String[] files = directoryScanner.getIncludedFiles();
for ( int j = 0; j < files.length; ++j )
{
log.debug( "parsing... " + files[j] );
//now parse out this file to get the packages/classname/etc
try
{
String fileName = new File( baseDir, files[j] ).getAbsolutePath();
JavaFile jfi = fileManager.getFile( fileName );
// now that we have this parsed out blend its information
// with the current package structure
PackageType jp = this.getPackageType( jfi.getPackageType().getName() );
if ( jp == null )
{
this.addPackageType( jfi.getPackageType() );
jp = jfi.getPackageType();
}
// Add the current file's class(es) to this global package.
if ( jfi.getClassTypes() != null && !jfi.getClassTypes().isEmpty() )
{
for ( Iterator iterator = jfi.getClassTypes().iterator(); iterator.hasNext(); )
{
jp.addClassType( (ClassType) iterator.next() );
}
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
} |
6e6a6114-5ce8-4961-a7b3-306747a9772c | 7 | public void recordContinueFrom(FlowContext innerFlowContext, FlowInfo flowInfo) {
if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) {
if ((initsOnContinue.tagBits & FlowInfo.UNREACHABLE) == 0) {
initsOnContinue = initsOnContinue.
mergedWith(flowInfo.unconditionalInitsWithoutSideEffect());
}
else {
initsOnContinue = flowInfo.unconditionalCopy();
}
FlowContext inner = innerFlowContext;
while (inner != this && !(inner instanceof LoopingFlowContext)) {
inner = inner.parent;
}
if (inner == this) {
this.upstreamNullFlowInfo.
addPotentialNullInfoFrom(
flowInfo.unconditionalInitsWithoutSideEffect());
}
else {
int length = 0;
if (this.innerFlowContexts == null) {
this.innerFlowContexts = new LoopingFlowContext[5];
this.innerFlowInfos = new UnconditionalFlowInfo[5];
}
else if (this.innerFlowContextsCount ==
(length = this.innerFlowContexts.length) - 1) {
System.arraycopy(this.innerFlowContexts, 0,
(this.innerFlowContexts = new LoopingFlowContext[length + 5]),
0, length);
System.arraycopy(this.innerFlowInfos, 0,
(this.innerFlowInfos= new UnconditionalFlowInfo[length + 5]),
0, length);
}
this.innerFlowContexts[this.innerFlowContextsCount] = (LoopingFlowContext) inner;
this.innerFlowInfos[this.innerFlowContextsCount++] =
flowInfo.unconditionalInitsWithoutSideEffect();
}
}
} |
1c4b1527-7b60-4818-be59-29caeeb1c254 | 6 | @Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnNewButton) {
String usernameText = usernameField.getText();
Staff user = null;
for (Person person : staffList) {
if (person.getName().equals(usernameText)) {
user = (Staff) person;
break;
}
}
if (user != null) {
char[] validate = passwordField.getPassword();
login = ((Staff) user).passwordValidation(validate);
if (login) {
gui = new MainGUI(user, driver);
driver.setGui(gui);
if (((Staff) user).getAccessLevel() == 2) {
gui.getSupplierTab().enableButtons(true);
gui.getCustomerTab().enableButtons(true);
gui.getStaffTab().enableButtons(true);
gui.getProductTab().enableButtons(true);
RetailSystemDriver.setPriviledged(true);
gui.setVisible(true);
setVisible(false);
}
else {
gui.getSupplierTab().enableButtons(false);
gui.getCustomerTab().enableButtons(false);
gui.getStaffTab().enableButtons(false);
gui.getProductTab().enableButtons(false);
RetailSystemDriver.setPriviledged(false);
gui.setVisible(true);
setVisible(false);
}
setVisible(false);
//JOptionPane.showMessageDialog(null, "Login successful!");
}
else
JOptionPane.showMessageDialog(null, "Wrong Password!");
}
else
JOptionPane.showMessageDialog(null, "Invalid username!");
}
} |
ffb16d7c-45ff-46ca-9f2d-e803dfd81282 | 7 | public static boolean LoadTest(Path p) {
try {
BufferedReader reader = Files.newBufferedReader(p, cSet);
String readL = "";
GlobalFuncs.loadMapCharacteristics(reader);
GlobalFuncs.scenMap.loadMap(reader);
GlobalFuncs.allCOAs = new Vector<COA>();
// Load units
while(readL != null) {
readL = reader.readLine();
// GUI_NB.GCO("String: >" + readL + "<");
if (readL.contentEquals("")) { }
else if (readL.startsWith("#")) {}
else if (readL.contains(">Last COA<")) {
break;
}
else if (readL.startsWith("COA")) {
COA newCOA = new COA(reader, readL);
GlobalFuncs.allCOAs.addElement(newCOA);
}
}
GlobalFuncs.curCOA = GlobalFuncs.allCOAs.firstElement();
GlobalFuncs.scenMap.UpdateExactDVNorm();
if (GlobalFuncs.maxSpottedDV == 1.0) GUI_NB.GCO("WARNING: Flow rate uninitialized for this scenario!");
GUI_NB.GCO("Test loaded successfully.");
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
} |
b5734ff5-755a-42ba-81c1-78d1b8b283b3 | 3 | private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed
if (jTable5.getSelectedRow() < 0) {
JOptionPane.showMessageDialog(this, "Please select contact to delete", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
int userSelection = JOptionPane.showConfirmDialog(this, "Are you sure you want to delete contact", "Delete Contact", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
System.out.println("userSelection:" + userSelection);
if (userSelection == 0) {
boolean status = false;
if (status) {
JOptionPane.showMessageDialog(this, "Contact deleted successfully", "Contact Deletion", JOptionPane.INFORMATION_MESSAGE);
//bbb
} else {
JOptionPane.showMessageDialog(this, "Contact cannot be deleted", "Contact deletion", JOptionPane.ERROR_MESSAGE);
}
}
}//GEN-LAST:event_jButton12ActionPerformed |
1bdcbe9b-906c-46b9-a57d-6ca5a40004cf | 9 | private static int getOpcode(int sort, int opcode) {
if (sort == TYPE.BOOLEAN.sort || sort == TYPE.CHAR.sort
|| sort == TYPE.BYTE.sort || sort == TYPE.SHORT.sort
|| sort == TYPE.INT.sort) {
opcode -= 4;
} else if (sort == TYPE.LONG.sort) {
opcode -= 3;
} else if (sort == TYPE.FLOAT.sort) {
opcode -= 2;
} else if (sort == TYPE.DOUBLE.sort) {
opcode -= 1;
} else if (sort == TYPE.VOID.sort) {
opcode++;
}
return opcode;
} |
2826da9d-72b8-4ec0-8e4c-82c82d1ecd57 | 4 | public static void main(String[] args) throws InterruptedException, RemoteException, UnknownHostException, NotBoundException {
try {
Parser.dataNodeConf();
if (Hdfs.Core.DEBUG) {
Parser.printConf(new ConfOpt[] {ConfOpt.HDFSCORE, ConfOpt.DATANODE});
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("The DataNode rountine cannot read configuration info.\n"
+ "Please confirm the hdfs.xml is placed as ./conf/hdfs.xml.\n"
+ "The DataNode routine is shutting down...");
System.exit(1);
}
if (args.length != 0) {
Hdfs.Core.DEBUG = true;
}
DataNode dataNode = new DataNode(Hdfs.Core.NAME_NODE_IP,
Hdfs.Core.NAME_NODE_REGISTRY_PORT,
Hdfs.DataNode.DATA_NODE_REGISTRY_PORT,
Hdfs.DataNode.DATA_NODE_SERVER_PORT);
try {
dataNode.init();
} catch (Exception e) {
e.printStackTrace();
}
Thread t1 = new Thread(dataNode);
t1.start();
} |
482aeba2-88ee-4389-b1dd-b8d2aaef415c | 0 | protected Icon getIcon() {
java.net.URL url = getClass().getResource("/ICON/de-expressionify.gif");
return new ImageIcon(url);
} |
052dae66-c008-414d-823c-e323649475dd | 2 | public List<Utr3prime> get3primeUtrs() {
ArrayList<Utr3prime> list = new ArrayList<Utr3prime>();
for (Utr utr : utrs)
if (utr instanceof Utr3prime) list.add((Utr3prime) utr);
return list;
} |
64b379b5-5cdc-493c-ada2-1e19f1404c12 | 7 | public void accept() {
PluginVars.removeRequest(this);
if(!this.requester.isOnline() || !this.requested.isOnline())
return;
if(PluginVars.isDueling(this.requester) || PluginVars.isDueling(this.requested)) {
this.requested.sendMessage(this.requester.getName() + " is in a duel.");
return;
}
try {
if(DeckGenerator.checkDeckInt(PluginVars.getDeckFor(this.requester)) && DeckGenerator.checkDeckInt(PluginVars.getDeckFor(this.requested))) {
Inventory i1 = Bukkit.getServer().createInventory(null, 54, "Duel Monsters");
Inventory i2 = Bukkit.getServer().createInventory(null, 54, "Duel Monsters");
Duel duel = PluginVars.createDuel(this.requester, i1, null, this.requested, i2, null);
this.requester.openInventory(i1);
this.requested.openInventory(i2);
duel.startDuel();
} else {
this.requester.sendMessage("Failed to start duel. Do you have a legal deck?");
this.requested.sendMessage("Failed to start duel. Do you have a legal deck?");
}
} catch (NoDeckException e) {
this.requester.sendMessage("Failed to start duel.");
this.requested.sendMessage("Failed to start duel.");
}
} |
9fa60a45-5d5f-4255-84e4-db3380a438c3 | 8 | private Set<Class<?>> add(final Class<?> cls, final Set<Class<?>> s) {
if (cls.isInterface()) {
s.add(cls);
}
for (final Class<?> iface : cls.getInterfaces()) {
add(iface, s);
}
final Class<?> superclass = cls.getSuperclass();
if (superclass != null) {
add(superclass, s);
}
return s;
} |
24d1c38f-5bc1-4a4e-b635-148ec72d3f33 | 5 | @Override
public void happens() {
Character character = Game.getInstance().getCurrentCharacter();
Character exp1 = null;
int index = 0;
ArrayList<Character> players = Game.getInstance().getCharacters();
search: for (int i = 0; i < players.size(); i++){
if(players.get(i).getItemHand().size() > 0){
ArrayList<ItemCard> items = players.get(i).getItemHand();
ResourceBundle messages = ResourceBundle.getBundle("ItemCardBundle", Game.getInstance().getLocale());
for (int j = 0; j < items.size(); j++){
if(items.get(j).getName() == messages.getString("titlePuzzleBox")){
exp1 = players.get(i);
index = j;
break search;
}
}
}
}
if (exp1 != null){
exp1.removeItemCard(exp1.getItemHand().get(index));
exp1.addItemCard(Game.getInstance().drawItem());
character.incrementSanity();
}
else
{
Trait chosenTrait = Game.getInstance().chooseAMentalTrait();
int damage = Game.getInstance().rollDice(1);
character.decrementTrait(chosenTrait, damage);
}
} |
47351873-8a8e-45e0-ab2b-9d28d5b4c881 | 7 | public int reductionColonne() {
int sommeRegret = 0;
int min;
for(int j = 0; j < this.getTaille(); j++) {
min = this.getValue(0, j);
if(j == 0) {
min = this.getValue(1, j);
}
for(int i = 0; i < this.getTaille(); i++) {
if(this.getValue(i, j) != -1) {
min = (this.getValue(i, j) < min)? this.getValue(i, j): min;
}
}
sommeRegret += min;
for(int i = 0; i < this.getTaille(); i++) {
if(this.getValue(i, j) != -1) {
this.setValue(i, j, this.getValue(i, j) - min);
}
}
}
return(sommeRegret);
} |
ad349c5b-ef2a-4ed1-9f07-b30a4e30a2d4 | 0 | public static void dehoist_all(Node currentNode) {
currentNode.getTree().getDocument().hoistStack.dehoistAll();
return;
} |
15dd8816-0a5f-4936-af46-1b2833039b1c | 2 | public synchronized void stop()
{
if (!running)
return;
running = false;
try
{
thread.join();
} catch (InterruptedException e)
{
e.printStackTrace();
}
} |
91dadf1b-0d93-411c-91e6-30b2676d9a24 | 2 | private static String compareFields(String texto, String[] fields) {
String fieldFound = "null";
for (String field : fields) {
if (texto.contains(field)) {
String linea = texto;
fieldFound = linea;
}
}
return fieldFound;
} |
ff3459ee-1759-4e75-8f44-6ffe09536b42 | 3 | private static void addEntry(Hashtable entries, String name) {
String dir = "";
int pathsep = name.lastIndexOf("/");
if (pathsep != -1) {
dir = name.substring(0, pathsep);
name = name.substring(pathsep + 1);
}
Vector dirContent = (Vector) entries.get(dir);
if (dirContent == null) {
dirContent = new Vector();
entries.put(dir, dirContent);
if (dir != "")
addEntry(entries, dir);
}
dirContent.addElement(name);
} |
fb0cf544-9a73-4d99-99b8-99997e04738b | 2 | void takeTour() throws TooHotException, TooColdException {
int temperature = (int) (Math.random() * 100);
System.out.println("temperature = " + temperature);
if (temperature > 60) {
throw new TooHotException("Too hot here");
} else if (temperature < 10) {
throw new TooColdException("Too cold here");
}
} |
f57ed256-721e-49a9-a131-ab5e77b24422 | 0 | public String getContent() {
return content;
} |
a04d53c6-3938-466c-be13-4eb1e0bf4b77 | 4 | public final Map<Integer, String> titles() {
synchronized (this) {
while ((this.lock > 0) || (this.lockRead > 0)) {
try {
wait();
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
return null;
}
}
++this.lockRead;
}
try {
parseIfNeeded();
return new HashMap<>(this.titles);
} catch (final FileNotFoundException e) {
this.io.printError("Selected midi does not exist", true);
return null;
} finally {
synchronized (this) {
--this.lockRead;
notifyAll();
}
}
} |
45337751-0144-45e9-975f-6ef495fe9317 | 9 | public static void main(String[] args) {
try {
if (args == null || args.length < 1 || args[0] == null) {
// If no arguments passed we exit. We need 1 parameter
// containing the path of the configuration file
System.out.println(ERROR_NO_CONF);
return;
}
// Read configuration file
File configFile = new File(args[0]);
Properties params = new Properties();
try {
params.load(new FileInputStream(configFile));
} catch (FileNotFoundException e) {
System.out.println(ERROR_NO_CONF);
return;
} catch (IOException e) {
System.out.println(ERROR_NO_CONF);
return;
}
// Configure a log4j logger
String logConf= getParam(params,"logConf", true, null);
if (logConf != null) {
try {
DOMConfigurator.configureAndWatch(logConf, 10000);
__log = Logger.getLogger(JmsStockListDemoService.class);
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
throw new IllegalStateException(ERROR_LOG_CONF);
}
} else {
System.out.println(ERROR_LOG_CONF);
throw new IllegalStateException(ERROR_LOG_CONF);
}
__log.info("StockList Demo service starting. Loading configuration...");
// Read parameters
String jmsUrl= getParam(params, "jmsUrl", true, null);
String initialContextFactory= getParam(params, "initialContextFactory", true, null);
String connectionFactory= getParam(params, "connectionFactory", true, null);
String stocksTopicName= getParam(params, "stocksTopicName", true, null);
// Create our service passing read parameters
new StockListService(__log, jmsUrl, initialContextFactory, connectionFactory, stocksTopicName);
__log.info("StockList Demo service ready.");
// Avoid termination
Object semaphore= new Object();
synchronized (semaphore) {
semaphore.wait();
}
} catch (Exception e) {
if (__log != null)
__log.error("Exception caught while starting StockList Demo service: " + e.getMessage(), e);
e.printStackTrace();
}
} |
8bec49f3-2e6f-4ab9-9487-64a1f3895714 | 4 | private void stats(Graphics g) {
Player player = game.getPlayer();
int rows = 5;
int width = per * 128;
int height = per * 16 * rows;
int x = (getWidth() - width) / 2;
int y = getHeight() - height;
g.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, per * 12));
for (int xx = x; xx < x + width; xx += 32) {
g.drawImage(ResourceManager.getImage("bdown"), xx, y - 10, null);
}
for (int yy = y; yy < y + height; yy += 32) {
g.drawImage(ResourceManager.getImage("bright"), x - 10, yy, null);
g.drawImage(ResourceManager.getImage("bleft"), x + width, yy, null);
}
g.drawImage(ResourceManager.getImage("cdr"), x - 10, y + height - 10, null);
g.drawImage(ResourceManager.getImage("cdl"), x + width - 10, y + height - 10, null);
g.drawImage(ResourceManager.getImage("cdro"), x - 12, y - 12, null);
g.drawImage(ResourceManager.getImage("cdlo"), x + width, y - 12, null);
g.setColor(Color.black);
g.fillRect(x, y, width, height);
int[] vals = new int[]{
(int) (((double) width / (double) player.maxhp()) * ((double) player.hp())),
(int) (((double) width / (double) player.maxXP()) * ((double) player.XP())),
(int) (((double) width) * (double) (1 - player.hunger())),
0, 0
};
Color[] cols = new Color[]{
Color.red,
Color.blue,
Color.yellow,
Color.white,
Color.white
};
for (int i = 0; i < vals.length; i++) {
g.setColor(new Color(1f, 1f, 1f, 0.25f));
g.fillRect(x, y + height / rows * i, width, height / rows);
g.setColor(cols[i]);
g.fillRect(x, y + height / rows * i, vals[i], height / rows);
g.setColor(new Color(1f, 1f, 1f, 0.5f));
g.fillRect(x, y + height / rows * i, vals[i], (height / rows) / 3);
g.setColor(Color.black);
g.drawRect(x, y + height / rows * i, width, height / rows);
}
String[] msgs = new String[]{
"HP " + player.hp() + "/" + player.maxhp(),
"(LVL " + player.level() + ") XP " + player.XP() + "/" + player.maxXP(),
String.format("Fullness %d%%", 100 - (int) (player.hunger() * 100)),
"DMG " + (player.dmg().min() + player.dmg().max()) / 2 + " ACC " + (int) (player.hitrate() * 100) + "%",
player.dungeon() + ". dungeon "
};
for (int i = 1; i <= msgs.length; i++) {
Rectangle2D r2d = g.getFontMetrics().getStringBounds(msgs[i - 1], g);
Rectangle drec = new Rectangle(getWidth() / 2 - (int) r2d.getWidth() / 2,
y + height / rows * i - (per * 4), 0, 0);
GraphicsUtils.drawTextOutlined(g, drec, msgs[i - 1], Color.WHITE, Color.BLACK);
}
} |
601332ac-7c05-455a-afaf-e24f7728ee89 | 5 | private void showSaveDialog() {
//TODO: Prevent saving (grey out this option) when the game is over.
if (matchFileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
try {
String filePath = matchFileChooser.getSelectedFile().getPath();
if (!filePath.endsWith("." + MatchSaveData.SAVE_FILE_EXTENSION)) {
filePath = filePath.concat("." + MatchSaveData.SAVE_FILE_EXTENSION); //Let users specify names without ".tcs", but add it anyway.
}
if (new File(filePath).exists()) { //Prompt for overwriting files, and be sure to check the file with ".tcs" at the end.
int chosenOption = JOptionPane.showConfirmDialog(this, "Really overwite the existing file?", "Overwrite file?",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (chosenOption == JOptionPane.YES_OPTION) {
new MatchSaveData(currentMatch).save(filePath);
} //Don't do anything if the user didn't hit "Yes" at the prompt.
} else {
new MatchSaveData(currentMatch).save(filePath); //Creating new files can be done without prompting.
}
} catch (IOException exception) {
exception.printStackTrace();
JOptionPane.showMessageDialog(this, "Error: Failed to save the game.");
}
}
} |
43feedf8-0526-4bdc-b360-adfeee30c72a | 7 | @Override
public void generate(Tile[][] tiles, Random random) throws ArrayIndexOutOfBoundsException {
Vec2D lt = Vec2D.get(8, 8);
for (int x = 0; x < tiles.length; x++) {
for (int y = 0; y < tiles.length; y++) {
tiles[x][y] = Tile.grass;
}
}
try {
for (int i = 0; i < 96; i++) {
tiles[lt.getX()][lt.getY()] = Tile.water;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
tiles[lt.getX() + x][lt.getY() + y] = Tile.water;
}
}
lt = lt.add(Vec2D.get(random.nextInt(2) - 1, random.nextInt(2) - 1));
if (random.nextInt(6) == 1) {
break;
}
}
} catch (ArrayIndexOutOfBoundsException e) {
}
} |
42a8ffc4-023c-4d9a-9efc-5f39e2effc59 | 6 | public void spread(){
if(direction != null && tailleRestante > 0){
switch(direction){
case N :
plateau.createFlamme(this.getHauteur(), this.getLargeur()-1, this.tailleRestante-1, this.direction, this.dateFin);
break;
case S :
plateau.createFlamme(this.getHauteur(), this.getLargeur()+1, this.tailleRestante-1, this.direction, this.dateFin);
break;
case E :
plateau.createFlamme(this.getHauteur()+1, (this.getLargeur()), this.tailleRestante-1, this.direction, this.dateFin);
break;
case O :
plateau.createFlamme(this.getHauteur()-1, (this.getLargeur()), this.tailleRestante-1, this.direction, this.dateFin);
break;
}
}
this.isSpread = true;
} |
0f6a3f28-cc57-42a3-a88c-142562e8d5af | 8 | private int computeSkyLightValue(int par1, int par2, int par3, int par4, int par5, int par6)
{
int var7 = 0;
if (this.canBlockSeeTheSky(par2, par3, par4))
{
var7 = 15;
}
else
{
if (par6 == 0)
{
par6 = 1;
}
int var8 = this.getSavedLightValue(EnumSkyBlock.Sky, par2 - 1, par3, par4) - par6;
int var9 = this.getSavedLightValue(EnumSkyBlock.Sky, par2 + 1, par3, par4) - par6;
int var10 = this.getSavedLightValue(EnumSkyBlock.Sky, par2, par3 - 1, par4) - par6;
int var11 = this.getSavedLightValue(EnumSkyBlock.Sky, par2, par3 + 1, par4) - par6;
int var12 = this.getSavedLightValue(EnumSkyBlock.Sky, par2, par3, par4 - 1) - par6;
int var13 = this.getSavedLightValue(EnumSkyBlock.Sky, par2, par3, par4 + 1) - par6;
if (var8 > var7)
{
var7 = var8;
}
if (var9 > var7)
{
var7 = var9;
}
if (var10 > var7)
{
var7 = var10;
}
if (var11 > var7)
{
var7 = var11;
}
if (var12 > var7)
{
var7 = var12;
}
if (var13 > var7)
{
var7 = var13;
}
}
return var7;
} |
5e53b25e-7f4b-4a3c-b4ba-4af805586093 | 6 | public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(UpdateNode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(UpdateNode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(UpdateNode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(UpdateNode.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new UpdateNode("").setVisible(true);
}
});
} |
d9b9d5de-3c9d-4e86-ab1f-d00739da0d28 | 2 | double[][] lhsu(double[] xmin, double[] xmax, int nsample) {
int nvar = xmin.length;
double s[][] = new double[nsample][nvar];
for (int j = 0; j < nvar; j++) {
int[] idx = randperm(nsample);
for (int i = 0; i < nsample; i++) {
double P = (idx[i] - random()) / (double) nsample;
s[i][j] = xmin[j] + P * (xmax[j] - xmin[j]);
}
}
return s;
} |
d9099cad-1fee-4b57-b4b0-7c09f5c628c6 | 4 | @EventHandler(ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
if (!event.getInventory().getType().equals(InventoryType.CRAFTING)) // Survival inventory
return;
Arena arena = OITG.instance.getArenaManager().getArena((Player) event.getWhoClicked());
if (arena != null && !arena.isItemDroppingAllowed() && event.getSlot() == -999)
event.setCancelled(true);
} |
d09459e0-82a0-4661-9d06-ed22bbaa28fb | 4 | public void moveWest() throws InterruptedException{
if (isDoor[3] && !isLocked[3]){
currentX--;
currentRoom = rooms[currentY][currentX];
currentRoom.playerVisits();
setAdjacentRooms();
Game.printMessage("You walk through the western door\n");
} else if (!isDoor[3])
Game.printMessage("There is no door in that direction\n");
else if (isLocked[3])
Game.printMessage("You try to continue, but the door is locked\n");
} |
e858c2c0-b690-443d-989e-1c4e76a3dca1 | 8 | public static Coordinates readMoveFromKeyboard() {
Coordinates result = null;
while (result == null) {
System.out.print(">");
String str = null;
int row = 0, column = 0;
BufferedReader d = new BufferedReader(new InputStreamReader(
System.in));
// String einlesen
try {
str = d.readLine();
} catch (IOException e) {
e.printStackTrace();
}
// gelesenen String sezieren
str.trim();
str = str.toLowerCase();
// falls der Zug "passen" bedeutet, beende Schleife (gib 'null'
// zurück)
if (str.equals(PASSEN)) {
System.out.println("Zug 'PASSEN' wurde ausgewaehlt.");
break;
}
if (str.length() != 2) {
System.out.println("Ungueltige Eingabe: mehr als 2 Zeichen.");
continue;
}
// ist das erste Zeichen eine Ziffer zwischen 0..8?
row = (int) (str.charAt(0)) - (int) '0';
// Zeilen 0 und 9 sind ungueltig
if (row < 1 || row > 8) {
System.out.println("Ungueltige Eingabe: die Zeilennummer muss "
+ "zwischen 1 und 8 liegen.");
continue;
}
// ist das zweite Zeichen ein Buchstabe zwischen a..h?
column = (int) (str.charAt(1)) - (int) 'a' + 1;
if (column < 1 || column > 8) {
System.out.println("Ungueltige Eingabe: die Spaltenummer muss "
+ "zwischen A und H liegen.");
continue;
}
result = new Coordinates(row, column);
}
return result;
} // end readMoveFromKeyboard() |
ad5b131a-ee4f-4156-8234-043ca0910ac3 | 7 | public boolean[] getSubDivideMask(CSVColumn sdi, Date start, Date end, File folder) {
if (sdi != null) {
try {
File fname = ObjFunc.resolve(sdi.getFile(), folder);
CSTable sdt = DataIO.table(fname, sdi.getTable());
String column = sdi.getColumn();
double[] retData = DataIO.getColumnDoubleValuesInterval(start, end, sdt, column, DataIO.DAILY, 0, null, null);
int[] subDivideData = new int[retData.length];
for (int i = 0; i < retData.length; i++) {
subDivideData[i] = (int) retData[i];
}
if ((subDivideMask == null) && (subDivideData != null)) {
this.subDivideMask = new boolean[subDivideData.length];
for (int i = 0; i < subDivideData.length; i++) {
this.subDivideMask[i] = ((subDivideData[i] == this.getSubDivideValue()) || (this.getSubDivideValue() == Integer.MIN_VALUE));
}
}
return this.subDivideMask;
} catch (IOException E) {
throw new RuntimeException(E);
}
} else {
return null;
}
} |
a78235a0-abf4-4462-8607-f3038113c6c8 | 8 | public void moveNoAnimate(int xa, int ya) {
if(xa != 0 && ya != 0) {
move(xa,0);
move(0,ya);
return;
}
xas = xa;
yas = ya;
LastDir = dir;
if (xa < 0) dir = 1; // 0 - north| 1- east | 2 - south | 3 - west |
if (xa > 0) dir = 3;
if (ya < 0) dir = 2;
if (ya > 0) dir = 0;
if(!collision(0,ya)) {
y += ya;
}
if(!collision(xa,0)) {
x += xa;
}
} |
5bdbfac7-9130-4e0a-a106-2aec3cf40159 | 1 | public boolean isEmpty() {
return (!this.player.isEmpty() && !this.reason.isEmpty());
} |
e07ec45e-d464-421b-91b0-9ae52f3a95df | 9 | private void addDirectoryToParentEntriesFile(final File CVSdir) throws IOException {
synchronized (ksEntries) {
final File parentCVSEntries = seekEntries(CVSdir.getParentFile().getParentFile());
// only update if the file exists. The file will not exist in the
// case where this is the top level of the module
if (parentCVSEntries != null) {
final File directory = parentCVSEntries.getParentFile();
final File tempFile = new File(directory, "Entries.Backup"); // NOI18N
tempFile.createNewFile();
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(parentCVSEntries));
writer = new BufferedWriter(new FileWriter(tempFile));
String line;
// As in the updateEntriesFile method the new Entry
// only may be written, if it does not exist
boolean written = false;
final Entry directoryEntry = new Entry();
directoryEntry.setName(CVSdir.getParentFile().getName());
directoryEntry.setDirectory(true);
while ((line = reader.readLine()) != null) {
if (line.trim().equals("D")) { // NOI18N
// do not write out this line
continue;
}
final Entry currentEntry = new Entry(line);
if ((currentEntry.getName() != null) && currentEntry.getName().equals(directoryEntry.getName())) {
writer.write(directoryEntry.toString());
written = true;
} else {
writer.write(line);
}
writer.newLine();
}
if (!written) {
writer.write(directoryEntry.toString());
writer.newLine();
}
} finally {
try {
if (writer != null) {
writer.close();
}
} finally {
if (reader != null) {
reader.close();
}
}
}
if (t9yBeforeRename != null) {
t9yBeforeRename.run();
}
FileUtils.renameFile(tempFile, parentCVSEntries);
}
}
} |
5203b9aa-0267-4cdc-b039-78c0a04a4756 | 7 | private void destroy(Map<K, List<ObjectTimestampPair<V>>> m, KeyedPoolableObjectFactory<K, V> factory) {
for (Iterator<Entry<K, List<ObjectTimestampPair<V>>>> entries = m.entrySet().iterator(); entries.hasNext();) {
Entry<K, List<ObjectTimestampPair<V>>> entry = entries.next();
K key = entry.getKey();
List<ObjectTimestampPair<V>> c = entry.getValue();
for (Iterator<ObjectTimestampPair<V>> it = c.iterator(); it.hasNext();) {
try {
factory.destroyObject(
key,it.next().value);
} catch(Exception e) {
// ignore error, keep destroying the rest
} finally {
synchronized(this) {
ObjectQueue objectQueue =
_poolMap.get(key);
if (objectQueue != null) {
objectQueue.decrementInternalProcessingCount();
if (objectQueue.internalProcessingCount == 0 &&
objectQueue.activeCount == 0 &&
objectQueue.queue.isEmpty()) {
_poolMap.remove(key);
_poolList.remove(key);
}
} else {
_totalInternalProcessing--;
}
}
allocate();
}
}
}
} |
e5ed5bf0-cafd-4511-872a-03969c4c2e5e | 5 | public boolean isResizable(Component c) {
boolean resizable = true;
if (c instanceof JDialog) {
JDialog dialog = (JDialog) c;
resizable = dialog.isResizable();
} else if (c instanceof JInternalFrame) {
JInternalFrame frame = (JInternalFrame) c;
resizable = frame.isResizable();
} else if (c instanceof JRootPane) {
JRootPane jp = (JRootPane) c;
if (jp.getParent() instanceof JFrame) {
JFrame frame = (JFrame) c.getParent();
resizable = frame.isResizable();
} else if (jp.getParent() instanceof JDialog) {
JDialog dialog = (JDialog) c.getParent();
resizable = dialog.isResizable();
}
}
return resizable;
} |
fd2e2e13-b768-4329-a844-679709def648 | 4 | private void sink(int i) {
while (2 * i + 1 <= N) {
int index = 2 * i + 1;
if (index + 1 <= N && pq[index].compareTo(pq[index + 1]) > 0) {
index = index + 1;
}
if (pq[i].compareTo(pq[index]) > 0) {
T temp = pq[index];
pq[index] = pq[i];
pq[i] = temp;
i = index;
} else {
break;
}
}
} |
bd477bd0-d505-4fb6-9b00-124c4f83253c | 4 | public static void cleanUpTable()
{
//Loop through every row in the table
for(int k = 0;k<=5;k++)
{
if(clientsTable.getModel().getValueAt(k, 0) == null)
{
System.out.println("Found Null Value at: " + k);
if(k != 5)
{
if(clientsTable.getModel().getValueAt(k+1, 0) != null)
{
System.out.println("Found Occupied Row at: " + (k+1));
String btName = clientsTable.getModel().getValueAt(k+1, 0).toString();
String btAddress = clientsTable.getModel().getValueAt(k+1, 1).toString();
clientsTable.getModel().setValueAt(btName, k, 0);
clientsTable.getModel().setValueAt(btAddress, k, 1);
clientsTable.getModel().setValueAt(null, k+1, 0);
clientsTable.getModel().setValueAt(null, k+1, 1);
}
}
}
}
} |
11144e42-1076-4f88-aa7b-785cea095399 | 2 | private void addLines(Document doc, Element linesElement, FileData fileData) {
int maxLines = fileData.getLines().size();
if (fileData.getBranchData().size() > 0)
maxLines = Math.max(fileData.getLines().size(), Collections.max(fileData.getBranchData().keySet())+1);
for (int i = 0; i < maxLines; i++) {
Element lineElement = null;
//Add line element
lineElement = addLineElement(doc, linesElement, fileData, i, lineElement);
//Add branch element
addBranchElement(doc, linesElement, fileData, i, lineElement);
}
} |
4264a565-8237-41a6-9d4f-6394c939f21c | 1 | public void destroyScreen() {
isRunning = false;
try {
gameThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// game.setScreen(null);
} |
c90bf58e-437f-46f1-9aee-214f3bd87a2b | 5 | public Net clone () {
Net newNet = new Net();
//clone all the nodes...
for (Node node : this._nodes) {
Node newNode = node.clone();
newNet.addNode(newNode);
// if it's an input or an output, put it in the right place
if (newNode instanceof InputNode) newNet.addInput((InputNode) newNode);
if (newNode instanceof OutputNode) newNet.addOutput((OutputNode) newNode);
}
// Clone the links, matching source and destination with corresponding IDs
for (Link link : this._links) {
if (link.getWeight() != 0) { //Dont' clone links with values of 0, I guess...
Node source = newNet.getNodeForId(link.getSource().getId());
Node dest = newNet.getNodeForId(link.getDestination().getId());
Link newLink = link.clone(source, dest);
newNet.addLink(newLink);
}
}
newNet.setTopId(this._topId);
newNet.sortNodes(); //Sort the nodes for more optimal access
return newNet;
} |
13b97516-6e0f-4aeb-8460-1137e9f8a48f | 4 | public static Promotion addPromotion(Promotion p) {
if (p == null)
return null;
// We check if the promotion doesn't still exist in the Professor List.
boolean exist = false;
int pos = 0;
for (int i = 0; i < FileReadService.pList.size(); i++) {
if (FileReadService.pList.get(i).equals(p)) {
exist = true;
pos = i;
}
}
if (!exist) {
FileReadService.pList.add(p);
return p;
}
return FileReadService.pList.get(pos);
} |
6cb34b26-1983-4ad6-94c0-31b2e4a51db8 | 3 | protected void finishModification() {
try {
courseModel.saveModelFile();
} catch (IOException e) {
JOptionPane.showMessageDialog(this,
"Cannot save static data file:\n" + e);
}
try {
courseModel.saveStatusFile();
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Cannot save status file:\n"
+ e);
}
List<? extends SortKey> skeys = table.getRowSorter().getSortKeys();
courseModel.fireModelReloaded();
table.tableChanged(null);
setColumnWidth();
table.getRowSorter().setSortKeys(skeys);
} |
190d3623-d3a6-4b0d-8989-076cfd806b60 | 8 | private boolean r_shortv() {
int v_1;
// (, line 49
// or, line 51
lab0: do {
v_1 = limit - cursor;
lab1: do {
// (, line 50
if (!(out_grouping_b(g_v_WXY, 89, 121))) {
break lab1;
}
if (!(in_grouping_b(g_v, 97, 121))) {
break lab1;
}
if (!(out_grouping_b(g_v, 97, 121))) {
break lab1;
}
break lab0;
} while (false);
cursor = limit - v_1;
// (, line 52
if (!(out_grouping_b(g_v, 97, 121))) {
return false;
}
if (!(in_grouping_b(g_v, 97, 121))) {
return false;
}
// atlimit, line 52
if (cursor > limit_backward) {
return false;
}
} while (false);
return true;
} |
adbba36e-9ea1-47c4-86d9-64bc76bd1ead | 2 | public void removeSelfFromGrid()
{
if (grid == null)
throw new IllegalStateException(
"This actor is not contained in a grid.");
if (grid.get(location) != this)
throw new IllegalStateException(
"The grid contains a different actor at location "
+ location + ".");
grid.remove(location);
grid = null;
location = null;
} |
06e9cfab-eff3-48c1-a7c9-be557e411fa5 | 5 | public boolean buildProduct(String productName){
for(ManufacturedProduct mfp : this.inventory.getManufacturedProductList()){
if(mfp.getProductName().equals(productName)){
for(String rm : mfp.getRawMaterialList()){
for(RawMaterial rm1 : this.inventory.getRawMaterialList()){
if(rm.equals(rm1.getProductName())){
rm1.setQuantity(rm1.getQuantity()-1);
}
}
}
}
}
return true;
} |
74dee449-dd81-4870-b17e-6e7c848a7f43 | 4 | public void addDownloadFromFileName(String fileName) {
try {
byte[] content = FileReader.readByteArray(fileName);
// TODO: Maybe, need real (but simple) check of file format
if (content.length < 3) {
throw new RuntimeException("Wrong file format");
}
if (fileName.toLowerCase().endsWith(".torrent"))
taskManager.addTorrent(content);
else if (fileName.toLowerCase().endsWith(".metalink"))
taskManager.addMetalink(content);
} catch (IOException e) {
Arietta.handleException(e);
}
} |
9878359c-f654-494e-b583-99153acefdff | 4 | private double addColumnsFromGeometry(RoadGeometry roadGeometry, int beginning, int end, double columns) {
if (geometryFitsInside(roadGeometry, beginning, end)) {
columns += roadGeometry.length() / (double) roadGeometry.getSmax();
} else if (geometryEndIsOutside(roadGeometry, beginning, end)) {
columns += (end - roadGeometry.getBeginning()) / (double) roadGeometry.getSmax();
} else if (geometryEndIsInside(roadGeometry, beginning, end)) {
columns += (roadGeometry.getEnd() - beginning) / (double) roadGeometry.getSmax();
} else if (geometryIsAround(roadGeometry, beginning, end)) {
columns += (end - beginning) / (double) roadGeometry.getSmax();
}
return columns;
} |
0923e5a2-43c4-40cc-a8f0-81547897f5f8 | 5 | public static void computePaths(Station source) {
source.setMinDistance(0.0);
System.out.println("source = " + source);
// Using PriorityQueue class with minDistance as a priority (see the comparator of Station)
PriorityQueue<Station> vertexQueue = new PriorityQueue<Station>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Station u = vertexQueue.poll();
// Visit each NEIGHBOR edge exiting u
for (Edge edge : u.getNeighborEdges()) {
Station v = edge.getTarget();
double weight = edge.getWeight();
// relax the edge (u, v) :
// if (u, v) is an edge and u is on the shortest path to v, then d(u) + w(u,v) = d(v).
double distanceThroughU = u.getMinDistance() + weight;
if (distanceThroughU < v.getMinDistance()) {
// The priority queue does not like when the ordering of its elements is changed, so
// when we change the minimum distance of any vertex, we need to remove it and re-insert
// it into the set.
vertexQueue.remove(v);
v.setMinDistance(distanceThroughU);
v.setPrevious(u);
vertexQueue.add(v);
}
}
// Visit each TRANSFER edge exiting u
for (Edge edge : u.getTransferEdges()) {
Station v = edge.getTarget();
double weight = edge.getWeight();
// relax the edge (u, v) :
// if (u, v) is an edge and u is on the shortest path to v, then d(u) + w(u,v) = d(v).
double distanceThroughU = u.getMinDistance() + weight;
if (distanceThroughU < v.getMinDistance()) {
// The priority queue does not like when the ordering of its elements is changed, so
// when we change the minimum distance of any vertex, we need to remove it and re-insert
// it into the set.
vertexQueue.remove(v);
v.setMinDistance(distanceThroughU);
v.setPrevious(u);
vertexQueue.add(v);
}
}
// // Visit each edge exiting u
// List<Edge> neighborEdges = u.getNeighborEdges();
// List<Edge> transferEdges = u.getTransferEdges();
// List<Edge> allEdges = new ArrayList<Edge>();
// allEdges.addAll(neighborEdges);
// allEdges.addAll(transferEdges);
// System.out.println("allEdges: " + allEdges.size());
// for (Edge edge : allEdges) {
// Station v = edge.getTarget();
// double weight = edge.getWeight();
//
// // relax the edge (u, v) :
// // if (u, v) is an edge and u is on the shortest path to v, then d(u) + w(u,v) = d(v).
// double distanceThroughU = u.getMinDistance() + weight;
//
// if (distanceThroughU < v.getMinDistance()) {
// // The priority queue does not like when the ordering of its elements is changed, so
// // when we change the minimum distance of any vertex, we need to remove it and re-insert
// // it into the set.
// vertexQueue.remove(v);
// v.setMinDistance(distanceThroughU);
// v.setPrevious(u);
// vertexQueue.add(v);
// }
// }
}
} |
e341ae44-3b08-442c-a785-da214f705bec | 4 | public int numDistinct(String S, String T) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
int ls = S.length();
int lt = T.length();
int[][] DP = new int[lt + 1][ls + 1];
for (int i = 0; i <= ls; ++i) {
DP[0][i] = 1;
}
DP[1][0] = 0;
for (int i = 1; i <= lt; ++i) {
for (int j = i; j <= ls; ++j) {
if (S.charAt(j-1) == T.charAt(i-1)) {
DP[i][j] = DP[i][j - 1] + DP[i - 1][j - 1];
} else {
DP[i][j] = DP[i][j - 1];
}
}
}
return DP[lt][ls];
} |
19e65e94-9e17-4344-b5db-9d029a4f79f8 | 7 | private void updateBoards(List<Clients> clientsList, Character[][] board, int playerNum){
Iterator itr = clientsList.iterator();
int i=0, j=0;
while(itr.hasNext()){
Clients client = (Clients) itr.next();
if(playerNum == PLAYER1){
//copy board of player1
for(i=0; i<4; i++){
for(j=0; j<5; j++){
client.board[i][j] = board[i][j];
}
}
}
else if(playerNum == PLAYER2){
//copy board of player2
for(i=0; i<4; i++){
for(j=5; j<10; j++){
client.board[i][j] = board[i][j];
}
}
}
}
} |
02382f41-0651-4384-8299-9b7f738e1845 | 8 | public static void main (String argv[]) {
// create scanner that reads from standard input
Scanner scanner = new Scanner(System.in);
if (argv.length > 2) {
System.err.println("Usage: java Main " + "[-d]");
System.exit(1);
}
// if commandline option -d is provided, debug the scanner
if (argv.length == 1 && argv[0].equals("-d")) {
// debug scanner
Token tok = scanner.getNextToken();
while (tok != null) {
int tt = tok.getType();
System.out.print(TokenName[tt]);
if (tt == Token.INT)
System.out.println(", intVal = " + tok.getIntVal());
else if (tt == Token.STRING)
System.out.println(", strVal = " + tok.getStrVal());
else if (tt == Token.IDENT)
System.out.println(", name = " + tok.getName());
else
System.out.println();
tok = scanner.getNextToken();
}
}
// Create parser
Parser parser = new Parser(scanner);
Node root;
// Parse and pretty-print each input expression
root = parser.parseExp();
while (root != null)
{
root.print(0);
root = parser.parseExp();
}
System.exit(0);
} |
0e85da9f-5163-488f-8c96-72271c894c42 | 2 | private void printResults(ChessGameConfiguration[] results){
String errorMsg;
if (results.length == 0){
errorMsg = messages.getString("noSolutionsFound");
System.out.println(errorMsg);
}else{
String msg = results.length + " "+ messages.getString("solutionsFound");
System.out.println(msg);
for(int i = 0; i < results.length; i++){
Cell[] cells = results[i].getCurrentBoard();
String alfabet = ChessConstants.CHESS_BOARD_REPRESENTATION_ALFABET;
BigInteger biRepresentationNumber = ChessTools.calculateRepresentationNumber(cells);
String strRepresentationString = ChessTools.convertToRepresentationString(biRepresentationNumber, alfabet.toCharArray());
msg = messages.getString("solution") +" ("+i+"): " + strRepresentationString;
System.out.println(msg);
}
msg = messages.getString("viewerAdvice");
System.out.println("\n" + msg);
}
} |
11590829-7aba-4559-a800-26bc8db1674e | 7 | private HttpHeader getHttpHeader(int length){
len = len + length;
splitbyte = findHeaderEnd(bytes, len);
if(splitbyte > 0){//find http header end
findHttpHeader = true;
httpHeader = new HttpHeader();
// Create a BufferedReader for parsing the header.
ByteArrayInputStream hbis = new ByteArrayInputStream(bytes, 0, splitbyte);
BufferedReader hin = new BufferedReader( new InputStreamReader(hbis));
Properties pre = new Properties();
Properties parms = new Properties();
Properties header = new Properties();
Properties files = new Properties();
// Decode the header into parms and header java properties
decodeHeader(hin, pre, parms, header);
httpHeader.setFiles(files);
httpHeader.setHeader(header);
httpHeader.setParms(parms);
httpHeader.setPre(pre);
String contentLength = httpHeader.getHeader().getProperty("content-length");
if (contentLength != null)
{
try { size = Integer.parseInt(contentLength); }
catch (NumberFormatException ex) {
//reject the request, is unlegal request
}
}
if (splitbyte < len){
f.write(bytes, splitbyte, len-splitbyte);
size = size - (len-splitbyte+1);
len = 0;//now can reuse bytes
}else if (splitbyte==0 || size == 0x7FFFFFFFFFFFFFFFl){ //contentLength = 0
size = 0;
}
return httpHeader;
}else{ //not find http header yet
//when len >= 8196 and not find http header yet ,the request is unlegal,reject
if(len > 8196){
isUnLegalRequest = true;
}
}
return null;
} |
aa101283-adb6-4330-b380-f0c2736d8d03 | 2 | private static Map<Character, Integer> addToMap(String text) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < text.length(); i++) {
char character = text.charAt(i);
if (map.get(character) == null) {
map.put(character, 0);
}
map.put(character, map.get(character) + 1);
}
return map;
} |
eea811c6-1b8e-4beb-ab6a-c4a56fdac4db | 4 | @Override
public void run()
{ System.out.println("Input run");
this.window.setEditable(true);
try
{
OutputStreamWriter os;
os = new OutputStreamWriter(out);
while (this.open) {
System.out.println("input loop");
if (this.inputRecieved) {
this.window.setForeground(Color.GREEN);
os.write(input);
os.flush();
out.flush();
this.inputRecieved=false;
this.input="";
//Thread.sleep(10);
}
}
System.out.println("Input Done!");
}
catch (AsynchronousCloseException e)
{
} catch (IOException e) {
System.out.println(e + " input");
} /*catch (InterruptedException ex) {
Logger.getLogger(InputGetter.class.getName()).log(Level.SEVERE, null, ex);
} /*catch (InterruptedException ex) {
Logger.getLogger(InputGetter.class.getName()).log(Level.SEVERE, null, ex);
}*/
} |
badd6dab-b9a6-477b-a1a7-7ea67451eb58 | 5 | public boolean checkDot(char c, boolean allowDot) {
return (c == '.' && allowDot) && (c == '.' && Utils.getCountOf(getText(), ".") < 1) && (c == '.' && !getText().isEmpty());
} |
93c1616f-5d4d-4dec-a8e4-970e7f41403c | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Campus)) {
return false;
}
Campus other = (Campus) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} |
06f71235-7dd1-484c-b563-b11111c5662d | 9 | final static Options createInstance( final Configuration configuration ) {
final Options instance = createDefaultInstance();
if ( configuration != null ) {
instance.setAntialiasScreen( configuration.isAntialiasScreen() );
instance.setShowScale( configuration.isShowScale() );
instance.setShowBranchLengthValues( configuration.isShowBranchLengthValues() );
instance.setShowOverview( configuration.isShowOverview() );
instance.setCladogramType( configuration.getCladogramType() );
instance.setOvPlacement( configuration.getOvPlacement() );
instance.setPrintLineWidth( configuration.getPrintLineWidth() );
instance.setNodeLabelDirection( configuration.getNodeLabelDirection() );
instance.setBackgroundColorGradient( configuration.isBackgroundColorGradient() );
if ( configuration.getNumberOfDigitsAfterCommaForBranchLengthValues() >= 0 ) {
instance.setNumberOfDigitsAfterCommaForBranchLength( configuration
.getNumberOfDigitsAfterCommaForBranchLengthValues() );
}
if ( configuration.getNumberOfDigitsAfterCommaForConfidenceValues() >= 0 ) {
instance.setNumberOfDigitsAfterCommaForConfidenceValues( configuration
.getNumberOfDigitsAfterCommaForConfidenceValues() );
}
instance.setExtractPfamTaxonomyCodesInNhParsing( configuration.isExtractPfamTaxonomyCodesInNhParsing() );
instance.setReplaceUnderscoresInNhParsing( configuration.isReplaceUnderscoresInNhParsing() );
instance.setInternalNumberAreConfidenceForNhParsing( configuration
.isInternalNumberAreConfidenceForNhParsing() );
instance.setNhParsingIgnoreQuotes( configuration.isNhParsingIgnoreQuotes() );
instance.setEditable( configuration.isEditable() );
if ( configuration.getMinConfidenceValue() != MIN_CONFIDENCE_DEFAULT ) {
instance.setMinConfidenceValue( configuration.getMinConfidenceValue() );
}
if ( configuration.getGraphicsExportX() > 0 ) {
instance.setPrintSizeX( configuration.getGraphicsExportX() );
}
if ( configuration.getGraphicsExportY() > 0 ) {
instance.setPrintSizeY( configuration.getGraphicsExportY() );
}
if ( configuration.getBaseFontSize() > 0 ) {
instance.setBaseFont( instance.getBaseFont().deriveFont( ( float ) configuration.getBaseFontSize() ) );
}
if ( !ForesterUtil.isEmpty( configuration.getBaseFontFamilyName() ) ) {
instance.setBaseFont( new Font( configuration.getBaseFontFamilyName(), Font.PLAIN, instance
.getBaseFont().getSize() ) );
}
if ( configuration.getPhylogenyGraphicsType() != null ) {
instance.setPhylogenyGraphicsType( configuration.getPhylogenyGraphicsType() );
}
}
return instance;
} |
c322a345-8060-492c-90c9-5657c7a2d6cc | 4 | private void mainLoop() {
screen = new ScreenSprites();
screen.init();
timer = new Timer(Constants.FPS_UPDATE);
fpsMeter = new FpsMeter();
while (!Display.isCloseRequested()) {
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
int j = timer.ticksMissed;
if (j > 1) fpsMeter.drop(j - 1);
timer.update();
for (int i = 0; i < j; i++) {
screen.update();
}
fpsMeter.frame();
float delta = timer.renderDeltaTime;
screen.render(delta);
Display.update();
try {
Display.sync(Constants.FPS_RENDER);
} catch (Throwable t) {
Log.e("Your graphics card driver does not support fullscreen properly.", t);
}
}
} |
e1ec2a03-2e13-45fc-abb1-4b19473acdc9 | 7 | public void dostuff(HashMap<Integer,GameData> g,Vector<Integer> index,CalculatingConsole c,HashMap<String,PlayerData> p)
{
game=g;
con=c;
players=p;
LinkedList<Moneys> tem=new LinkedList<Moneys>();
tem.add(new Moneys("Correct",TOURNY));
correction=new Player("Correct",25000,tem,this);
con.everyone.put("Correct", correction);
for(Integer i:index)
{
evaluateGame(g.get(i));
}
for(Player pi:everyone.values())
{
pi.writestack();
}
done = false;
while (!done)
{
System.out.print("#$?");
String command = in.nextLine();
if(con.everyone.containsKey(command))
{
Player play=(Player)(con.everyone.get(command));
System.out.println(play.name+": "+play.score);
System.out.println(play.money.toString());
for(String name:everyone.keySet())
{
int temp=0;
for(Moneys m:play.money)
{
if(m.owner.equals(name))
temp+=m.amount;
}
System.out.println(name+": "+temp);
}
}
}
} |
d2502d99-0390-4c67-8a64-dd4910b31087 | 7 | public Object nextValue() throws JSONException {
char c = this.nextClean();
String string;
switch (c) {
case '"':
case '\'':
return this.nextString(c);
case '{':
this.back();
return new JSONObject(this);
case '[':
this.back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuffer sb = new StringBuffer();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = this.next();
}
this.back();
string = sb.toString().trim();
if ("".equals(string)) {
throw this.syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
} |
e799fc1b-ce54-4b74-9655-fa7d1d0037b9 | 8 | public void compExecTime() {
double newExeTime;
double newCost;
dEval = 0;
dTime = 0;
dCost = 0;
for (int i = 0; i < iClass; i++) {
newExeTime = 0;
// System.out.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) {
// System.out.println("newExeTime - dDeadline="+ (newExeTime
// - dDeadline -1));
newCost = Double.MAX_VALUE;
} else {
newCost = dmDist[i][j] * dmPrediction[i][j]
* daPrice[j];
}
dTime += newExeTime;
dCost += newCost;
dEval += dmCost[i][j] - dCost;
dmExeTime[i][j] = newExeTime;
dmCost[i][j] = newCost;
// System.out.print(dmCost[i][j] + ", ");
}
// System.out.println();
}
for (int i = 0; i < iClass; i++) {
System.out.print("Time[" + i + "]");
for (int j = 0; j < iSite; j++) {
System.out.print(dmExeTime[i][j] + ", ");
}
System.out.println();
}
// System.out.println("AllTime = " + dTime + " AllCost = " + dCost);
// System.out.println();
} |
3434c637-c7cc-4501-b4ed-33106e218aeb | 0 | public String getId() {
return id;
} |
2cfdbabb-4a27-47c5-a741-d4cd5b55df57 | 3 | public void saveImage(ActionEvent e){
int returnVal = fc.showSaveDialog(Paintimator.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File savedPane = fc.getSelectedFile();
String ext = Utils.getExtension(savedPane);
ImageFilter imgfltr = new ImageFilter();
if (imgfltr.accept(savedPane)) {
try {
BufferedImage bi = layeredPanel.paneToBufferedImg();
ImageIO.write(bi, ext, savedPane);
} catch (IOException e1) {
JOptionPane.showMessageDialog(this, "Image could not be saved.",
"Image error", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(this, "Extension not accepted. Please choose a new one.",
"Extension error", JOptionPane.ERROR_MESSAGE);
saveImage(e);
}
}
} |
304954ba-4ee1-4a19-9378-049eb49b56b6 | 7 | public static void main(String args[]) throws IOException {
Scanner in = new Scanner(System.in);
String password = "star";
System.out.println(">Enter the database password:");
String passIn = in.nextLine();
if(passIn.equals(password)) {
System.out.println(">Enter menu selection:\n1 Create File\n2 Open File\n3 Edit File\n4 Delete File\n5 Exit");
menuLoop:
while (true) {
int menuChoice = in.nextInt();
switch (menuChoice) {
case 1:
FileCreator.createFile();
break;
case 2:
FileViewer.viewFile();
break;
case 3:
FileEditor.editFile();
break;
case 4:
FileDeleter.deleteFile();
break;
case 5:
break menuLoop;
}
System.out.println();
System.out.println(">Enter menu selection:\n1 Create File\n2 Open File\n3 Edit File\n4 Delete File\n5 Exit");
}
} else {
System.out.println(">Access Denied");
}
} |
fc046e1a-a3d4-4960-8335-c74106e7f5dd | 1 | public void writeData(final DataOutputStream out) throws IOException {
out.writeShort(locals.length);
for (int i = 0; i < locals.length; i++) {
out.writeShort(locals[i].startPC());
out.writeShort(locals[i].length());
out.writeShort(locals[i].nameIndex());
out.writeShort(locals[i].typeIndex());
out.writeShort(locals[i].index());
}
} |
baef7ded-4659-4796-a244-81690db7ac23 | 6 | public double evaluateState(StateObservationMulti stateObs, int playerID) {
boolean gameOver = stateObs.isGameOver();
Types.WINNER win = stateObs.getMultiGameWinner()[playerID];
Types.WINNER oppWin = stateObs.getMultiGameWinner()[(playerID + 1) % stateObs.getNoPlayers()];
double rawScore = stateObs.getGameScore(playerID);
if(gameOver && (win == Types.WINNER.PLAYER_LOSES || oppWin == Types.WINNER.PLAYER_WINS))
return HUGE_NEGATIVE;
if(gameOver && (win == Types.WINNER.PLAYER_WINS || oppWin == Types.WINNER.PLAYER_LOSES))
return HUGE_POSITIVE;
return rawScore;
} |
2b8e2951-dba4-4221-88bf-f2ce7b923e8e | 7 | public double obtenerMinimo(int columna, String csvFile){
String line = "";
String cvsSplitBy = ",";
BufferedReader br = null;
double minimo = 0;
boolean primera = true;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] patron = line.split(cvsSplitBy);
if(primera){
primera = false;
minimo = Double.valueOf(patron[columna]);
}
if(Double.valueOf(patron[columna]) < minimo){
minimo = Double.valueOf(patron[columna]);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException e) {
System.out.println("Error al obtener el maximo");
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return minimo;
} |
2f1bd22d-aed3-4945-b0d8-caeefe4c6707 | 6 | public BlockMap(int var1, int var2, int var3) {
this.width = var1 / 16;
this.depth = var2 / 16;
this.height = var3 / 16;
if(this.width == 0) {
this.width = 1;
}
if(this.depth == 0) {
this.depth = 1;
}
if(this.height == 0) {
this.height = 1;
}
this.entityGrid = new ArrayList[this.width * this.depth * this.height];
for(var1 = 0; var1 < this.width; ++var1) {
for(var2 = 0; var2 < this.depth; ++var2) {
for(var3 = 0; var3 < this.height; ++var3) {
this.entityGrid[(var3 * this.depth + var2) * this.width + var1] = new ArrayList();
}
}
}
} |
83126d01-5522-4465-a2b4-684d8bb61286 | 3 | public boolean cadastrar() {
EntityManager em = conexao();
try {
if (em != null) {
Paciente paciente = new Paciente();
paciente.setIdPaciente(null);
paciente.setNome(nome);
paciente.setDataNasc(dataNasc);
paciente.setLogradouro(logradouro);
paciente.setNumero(numero);
paciente.setBairro(bairro);
paciente.setCidade(cidade);
paciente.setUf(uf);
System.out.println(paciente.toString());
em.getTransaction().begin();
em.persist(paciente);
em.getTransaction().commit();
return true;
}
return false;
} catch (HibernateException e) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
return false;
}
} |
c44a87d0-cf5a-410c-b5b6-442de52dc3b4 | 1 | @Test
public void testGetAllCouriers()throws Exception{
List<Courier> couriers = connection.getAllCouriers();
//check first courier
Assert.assertEquals("First courier slug", firstCourier.get("slug"), couriers.get(0).getSlug());
Assert.assertEquals("First courier name", firstCourier.get("name"), couriers.get(0).getName());
Assert.assertEquals("First courier phone", firstCourier.get("phone"), couriers.get(0).getPhone());
Assert.assertEquals("First courier other_name", firstCourier.get("other_name"), couriers.get(0).getOther_name());
Assert.assertEquals("First courier web_url", firstCourier.get("web_url"), couriers.get(0).getWeb_url());
//total Couriers returned
assertEquals("It should return total couriers", TOTAL_COURIERS_API, couriers.size());
//try to acces with a bad API Key
ConnectionAPI connectionBadKey = new ConnectionAPI("badKey");
try{
connectionBadKey.getCouriers();
}catch (AftershipAPIException e){
Assert.assertEquals("{\"meta\":{\"code\":401,\"message\":\"Invalid API key.\",\"type\":\"Unauthorized\"},\"data\":{}}", e.getMessage());
}
} |
f08bf9e3-b974-4ef1-84ae-ff4d6878b625 | 3 | public static void main(String[] args) throws ClassNotFoundException {
int[] sched = {1,2};
DbHelper db = new DbHelper();
for(int schedule : sched)
{
List<Group> groups = fillRooms(db, schedule);
System.out.println("Schedule: " + schedule + "-------------");
for(Group g : groups) {
String teacher = "";
if(g.getTeacher() != null)
{
teacher = g.getTeacher();
}
System.out.println("Group: " + g.getName() + " Room: " + g.getRoom().getName() + " Teacher: " + teacher);
}
}
} |
e3c27946-6824-40d2-aed4-f33950e90810 | 9 | @Override
public Command createCommand(Context context, String... args) {
HttpCommand.Operation operation;
String path = null;
MediaType mediaType = null;
Map<String, String> parameters = new HashMap<String, String>();
Map<String, String> headers = new HashMap<String, String>();
try {
operation = HttpCommand.Operation.valueOf(args[0].toUpperCase());
} catch (IllegalArgumentException exc) {
return ErrorCommand.UNKNOWNCOMMAND_FACTORY.createCommand(context, args);
}
for (int i = 1; i < args.length; i++) {
String s = args[i];
if (isPath(s)) {
path = s;
} else if (isMediaType(s)) {
mediaType = MEDIA_TYPES.get(s);
if (mediaType == null) {
return new ErrorCommand("unknown mediatype [" + s + "]");
}
} else if (isParameter(s)) {
EnhancedStringTokenizer tok = new EnhancedStringTokenizer(s, "=", "\"");
final List<String> tokens = tok.getAllTokens();
final String key = tokens.get(0);
final String value = tokens.get(1);
parameters.put(key, value);
} else if (isHeader(s)) {
EnhancedStringTokenizer tok = new EnhancedStringTokenizer(s, ":", "\"");
final List<String> tokens = tok.getAllTokens();
final String key = tokens.get(0);
final String value = tokens.get(1);
headers.put(key, value);
} else {
return new ErrorCommand("unknown argument [" + s + "]");
}
}
if (path == null) {
return new ErrorCommand("missing path from command " + Arrays.toString(args));
}
if (mediaType == null) {
mediaType = context.getDefaultMediaType();
}
return new HttpCommand(context, operation, path, mediaType, parameters, headers);
} |
b76b0d1b-a5ad-4715-a88f-4a83c537056c | 0 | public static void question9b() {
/*
QUESTION PANEL SETUP
*/
questionLabel.setText("Which of these below do you like the most?");
questionNumberLabel.setText("9b");
/*
ANSWERS PANEL SETUP
*/
//resetting
radioButton1.setSelected(false);
radioButton2.setSelected(false);
radioButton3.setSelected(false);
radioButton4.setSelected(false);
radioButton5.setSelected(false);
radioButton6.setSelected(false);
radioButton7.setSelected(false);
radioButton8.setSelected(false);
radioButton9.setSelected(false);
radioButton10.setSelected(false);
radioButton11.setSelected(false);
radioButton12.setSelected(false);;
radioButton13.setSelected(false);
radioButton14.setSelected(false);
//enability
radioButton1.setEnabled(true);
radioButton2.setEnabled(true);
radioButton3.setEnabled(true);
radioButton4.setEnabled(true);
radioButton5.setEnabled(true);
radioButton6.setEnabled(true);
radioButton7.setEnabled(false);
radioButton8.setEnabled(false);
radioButton9.setEnabled(false);
radioButton10.setEnabled(false);
radioButton11.setEnabled(false);
radioButton12.setEnabled(false);
radioButton13.setEnabled(false);
radioButton14.setEnabled(false);
//setting the text
radioButton1.setText("Bowling.");
radioButton2.setText("I like going to gym.");
radioButton3.setText("Swimming.");
radioButton4.setText("Squash.");
radioButton5.setText("Carting.");
radioButton6.setText("Don't really care.");
radioButton7.setText("No used");
radioButton8.setText("No used");
radioButton9.setText("No used");
radioButton10.setText("No used");
radioButton11.setText("No used");
radioButton12.setText("No used");
radioButton13.setText("No used");
radioButton14.setText("No used");
// Calculating the best guesses and showing them.
Knowledge.calculateAndColorTheEvents();
} |
c8558004-4a00-4895-b7e2-db6e38c0781f | 8 | static public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[18];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 4; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
}
}
}
for (int i = 0; i < 18; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
} |
ad58ae56-1e02-4bea-b63d-6ef54cdb48a4 | 2 | public static List<Laureate> filterByDeathYear(
List<Laureate> inputList, List<String> ListOfTerms) {
List<Laureate> outputList = new ArrayList<Laureate>();
// parse input, keep what matchs the terms.
for (Laureate Awinner : inputList) {
if (ListOfTerms.contains(Awinner.getDeath())) {
outputList.add(Awinner);
}
}
return outputList;
} |
00e0345b-9c6d-4ef2-9d45-26a1fe8a0c6c | 6 | public void run()
{
boolean var27 = false;
label183:
{
label184:
{
label185:
{
label186:
{
label187:
{
try
{
var27 = true;
this.server.motd = "\u00a78Polling..";
long var1 = System.nanoTime();
GuiMultiplayer.pollServer(this.serverSlotContainer.parentGui, this.server);
long var3 = System.nanoTime();
this.server.lag = (var3 - var1) / 1000000L;
var27 = false;
break label183;
}
catch (UnknownHostException var35)
{
this.server.lag = -1L;
this.server.motd = "\u00a74Can\'t resolve hostname";
var27 = false;
}
catch (SocketTimeoutException var36)
{
this.server.lag = -1L;
this.server.motd = "\u00a74Can\'t reach server";
var27 = false;
break label187;
}
catch (ConnectException var37)
{
this.server.lag = -1L;
this.server.motd = "\u00a74Can\'t reach server";
var27 = false;
break label186;
}
catch (IOException var38)
{
this.server.lag = -1L;
this.server.motd = "\u00a74Communication error";
var27 = false;
break label185;
}
catch (Exception var39)
{
this.server.lag = -1L;
this.server.motd = "ERROR: " + var39.getClass();
var27 = false;
break label184;
}
finally
{
if (var27)
{
synchronized (GuiMultiplayer.getLock())
{
GuiMultiplayer.decrementThreadsPending();
}
}
}
synchronized (GuiMultiplayer.getLock())
{
GuiMultiplayer.decrementThreadsPending();
return;
}
}
synchronized (GuiMultiplayer.getLock())
{
GuiMultiplayer.decrementThreadsPending();
return;
}
}
synchronized (GuiMultiplayer.getLock())
{
GuiMultiplayer.decrementThreadsPending();
return;
}
}
synchronized (GuiMultiplayer.getLock())
{
GuiMultiplayer.decrementThreadsPending();
return;
}
}
synchronized (GuiMultiplayer.getLock())
{
GuiMultiplayer.decrementThreadsPending();
return;
}
}
synchronized (GuiMultiplayer.getLock())
{
GuiMultiplayer.decrementThreadsPending();
}
} |
e381ba2b-6055-4f3d-8570-5fb457beb4bd | 0 | public String toString()
{
return "x = " + this.x + ",y = " + this.y + ";";
} |
07ebb472-ea64-434f-aa51-a6bbdaabcdc3 | 9 | public FloorItem getGroundItem(int id, WorldTile tile, Player player) {
if (floorItems == null)
return null;
for (FloorItem item : floorItems) {
if ((item.isInvisible() || item.isGrave())
&& player != item.getOwner())
continue;
if (item.getId() == id && tile.getX() == item.getTile().getX()
&& tile.getY() == item.getTile().getY()
&& tile.getPlane() == item.getTile().getPlane())
return item;
}
return null;
} |
0d5234f9-3b4f-4cdd-8da0-d3cc8f4c7c43 | 7 | public byte[] populate(byte[] frameData) {
logger.debug("populate..");
boolean readingState=false;
int bytesRead=0;
//boolean frameCompleted=false;
ByteBuffer payloadBuffer = ByteBuffer.allocate(frameData.length);
for (byte newestByte:frameData){
bytesRead++;
if (newestByte == START_OF_FRAME && !readingState) {
logger.debug("frame start");
readingState=true;
}else if(newestByte == END_OF_FRAME && readingState){
logger.debug("frame end");
//frameCompleted=true;
readingState=false;
payloadData = payloadBuffer.array();
break;
}else if(readingState){
payloadBuffer.put(newestByte);
}
}
logger.debug(payloadData);
logger.debug("payload len: "+payloadData.length);
messageFrame = (payloadData.length>0);
byte[] unprocessedBytes = new byte[frameData.length-bytesRead];
int j=0;
for (int i=bytesRead;i<frameData.length;i++){
unprocessedBytes[j++]=frameData[i];
}
/*TODO: Handle case where frame data was not completely received*/
return unprocessedBytes;
} |
5b44db66-e993-4937-a17c-79379e76c901 | 2 | TreeNode rightNext(){
TreeNode head = queue.poll();
if (head.right != null)
queue.offer(head.right);
if (head.left != null)
queue.offer(head.left);
return head;
} |
db44aae7-27b2-4be9-b2e1-747c1c7dbd92 | 6 | @Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnSave) {
saveUpdateSubProcess();
closedByOk = false;
}
if (e.getSource() == btnClose) {
if (saveUpdateSubProcess()) {
closedByOk = true;
SubProcessCUDialog.this.setVisible(false);
}
}
if (e.getSource() == btnCancel) {
closedByOk = false;
SubProcessCUDialog.this.setVisible(false);
}
if (e.getSource() == btnAllToAssigned) {
Stock stock = (Stock) lstAllStocks.getSelectedValue();
Service.assignSubProcessToStock(stock, subProcess);
fillText(subProcess);
}
if (e.getSource() == btnAssignedToAll) {
Stock stock = (Stock) lstAssignedStocks.getSelectedValue();
Service.unsignSubProcessFromStock(stock, subProcess);
fillText(subProcess);
}
} |
a0d791d8-abfa-4cb5-b2b5-e6f0c5ea749a | 5 | private void insertAVL(TreeNode currentNode, TreeNode newNode) {
if (currentNode == null) {
this.root = newNode;
} else {
if (newNode.value.compareTo(currentNode.value) < 0) {
if (currentNode.left == null) {
currentNode.left = newNode;
newNode.parent = currentNode;
recursiveBalance(currentNode);
} else {
insertAVL(currentNode.left, newNode);
}
} else if (newNode.value.compareTo(currentNode.value) > 0) {
if (currentNode.right == null) {
currentNode.right = newNode;
newNode.parent = currentNode;
recursiveBalance(currentNode);
} else {
insertAVL(currentNode.right, newNode);
}
} else {
System.out.println("\nValue " + newNode.value + " already exists. Ignoring...");
}
}
} |
77f6872b-8b86-424e-9015-bf0376f789e9 | 6 | public double evaluate(Tree<Board> tree, boolean maxPlayer) {
Board b = tree.getRoot();
if (tree.getLeaves().isEmpty()) {
this.isFinished = true;
return getBoardValue(b);
} else {
double bestValue;
if (maxPlayer) {
bestValue = Integer.MIN_VALUE;
List<Tree<Board>> t = tree.getLeaves();
for(int i = 0; i < t.size(); i++) {
double value = evaluate(t.get(i), false);
bestValue = bestValue > value ? bestValue : value;
}
} else {
bestValue = Integer.MAX_VALUE;
List<Tree<Board>> t = tree.getLeaves();
for(int i = 0; i < t.size(); i++) {
double value = evaluate(t.get(i), true);
bestValue = bestValue < value ? bestValue : value;
}
}
tree.setScore(bestValue);
this.isFinished = true;
return bestValue;
}
} |
b9ed511e-6d4e-423f-921c-1b22d88980f3 | 3 | private static void executeCmd(String... cmd) {
System.out.println("spawning" + Arrays.toString(cmd));
try {
ProcessBuilder pb = new ProcessBuilder(cmd);
Process p = pb.start();
if (true) {
InputStream in = p.getInputStream();
BufferedInputStream buf = new BufferedInputStream(in);
InputStreamReader inread = new InputStreamReader(buf);
BufferedReader bufferedreader = new BufferedReader(inread);
String line;
while ((line = bufferedreader.readLine()) != null) {
System.err.println(line);
}
}
p.waitFor();
} catch (Exception e) {
System.err.println("could not execute <" + Arrays.toString(cmd) + ">");
}
} |
3695aa84-aaca-4b3a-b01f-f91dc5165ed7 | 6 | @Override
public void tick(MainGame game, Person person) {
if(person.storedWood.getAmount() >person. maxResource || person.storedFood.getAmount() > person.maxResource ||
person.storedMetal.getAmount() > person.maxResource || person.storedStone.getAmount() > person.maxResource) {
//Make the player go to the store point
person.setTargetPosition(game.village.x, game.village.y);
//if we are at the store point, unload our resources
if(person.getX() == game.village.x && person.getY() == game.village.y ) {
game.village.collectiveFood.add(person.storedFood);
game.village.collectiveMetal.add(person.storedMetal);
game.village.collectiveStone.add(person.storedStone);
game.village.collectiveWood.add(person.storedWood);
}
}else{
person.endTask();
}
} |
31990279-6f6d-4399-9e5a-2fef2db67b15 | 4 | public static Image loadImage(String name, int type)
{
switch(type)
{
case BMP:
return loadBMP(name);
case PNG:
return loadPNG(name);
case JPG:
return loadJPG(name);
case GIF:
return loadGIF(name);
default:
throw new UnsupportedOperationException("Not a supported image type. [" + type + "]");
}
} |
33965956-a23c-42f4-87f6-e73117e84648 | 9 | public int largestRectangleArea(int[] height) {
Stack<Integer> s = new Stack<Integer>();
int len = height.length;
int [] left = new int[len];
int [] right = new int[len];
int index =0;
for (int i=0;i<len;i++) {
while (!s.isEmpty() && height[s.peek()]>=height[i]) s.pop();
left[i]= i- (s.isEmpty()? -1: s.peek()) -1;
s.push(i);
}
s.clear();
for (int i=len-1;i>=0;i--) {
while (!s.isEmpty() && height[s.peek()]>=height[i]) s.pop();
right[i]= (s.isEmpty()? len : s.peek()) -i-1;
s.push(i);
}
int max = 0;
for (int i=0;i<len;i++) {
int total = height[i]*(left[i]+right[i]+1);
max = Math.max(total,max);
}
return max;
} |
73722b4c-a5a8-49a0-95fc-f9a8a03c5b4d | 3 | public static void caida() {
if (terminocaida){
terminocaida = false;
file = new File(".");
ruta = file.getAbsolutePath();
Thread hilo = new Thread() {
@Override
public void run() {
try {
Thread.sleep(500);
FileInputStream fis;
Player player;
try{
fis = new FileInputStream(ruta + "/src/sounds/caida.mp3");
}catch (FileNotFoundException e){
fis = new FileInputStream(ruta + "/complementos/caida.mp3");
}
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
player.play();
stop();
} catch (InterruptedException | JavaLayerException | FileNotFoundException e) {
}
}
};
hilo.start();
}
} |
ef87ab07-de93-4f8d-9472-4700a05e9668 | 3 | public static List<TrialGroup> createTrialGroups(List<Trial> trials) throws IncorrectNumberOfTrialsException {
List<TrialGroup> trialGroups = new ArrayList<TrialGroup>();
while (!trials.isEmpty()) {
List<Trial> trialsInThisGroup = new ArrayList<Trial>();
for (int iTrial = 0; iTrial < Options.TRIALS_PER_GROUP; iTrial++) { //0 to 4
if (!trials.isEmpty()) {
trialsInThisGroup.add(trials.remove(0));
} else {
//this should not occur: experimenter should make sure the number of trials is a multiple of TRIALS_PER_GROUP
throw new IncorrectNumberOfTrialsException("Not enough trials left to create group of "+ Options.TRIALS_PER_GROUP + " trials! " +
"Make sure the numer of trials in " + Options.STIM_FILE +" is a multiple of "+ Options.TRIALS_PER_GROUP +"!");
}
}
trialGroups.add(new TrialGroup(trialsInThisGroup, trialsInThisGroup.get(0).lowLoad));
}
return trialGroups;
} |
a4b1c696-62f5-4c5c-9e81-02dfc431ad8c | 9 | private static void merge(ConllSentence sen, ConllSentence mwe,
String[] originalpositions) {
ArrayList<Integer> op = new ArrayList<Integer>();
for(String s: originalpositions){
op.add(Integer.parseInt(s));
}
int orignalMWEHeadPostion = op.get(0);
int headOfMWE = Integer.parseInt(((sen.lines.get(orignalMWEHeadPostion-1)).split("\\t"))[6]);
ArrayList<Integer> afterReplace = new ArrayList<Integer>();
int MWEHeadNowInOriginal = -1;
int m_index = 0;
boolean flag = false;
for(String line : mwe.lines){
int h = Integer.parseInt((line.split("\\t"))[6]);
if(h==0 && !flag){
afterReplace.add(headOfMWE);
MWEHeadNowInOriginal = op.get(m_index);
flag = true;
}else{
if(h==0){
afterReplace.add(MWEHeadNowInOriginal);
}else{
afterReplace.add(op.get(h-1));
}
}
m_index++;
}
// Recover tokens inside the MWE
for(int i = 0; i < op.size(); i++){
String as = changeHeadField(sen.lines.get(op.get(i)-1), afterReplace.get(i));
sen.lines.set(op.get(i)-1, as);
}
// Recover tokens outside the MWE
for(int i = 0; i < sen.lines.size(); i++){
if(op.contains(i+1)) continue;
int oh = Integer.parseInt((sen.lines.get(i).split("\\t"))[6]);
if(oh == orignalMWEHeadPostion){
String as = changeHeadField(sen.lines.get(i), MWEHeadNowInOriginal);
sen.lines.set(i, as);
}
}
} |
e08c52d5-0e4b-4fd6-a41c-8255fe15303e | 9 | public void actionPerformed(ActionEvent evt) {
/** if save configuration button is clicked */
if (evt.getActionCommand().equals("Save Configurations")) {
/** copy new keys back to glocal variables */
for (int i = 0; i < 4; i++) for (int j = 0; j < 5; j++)
BomberKeyConfig.keys[i][j] = keys[i][j];
/** write the file */
BomberKeyConfig.writeFile();
/** destroy this dialog */
dispose();
}
/** if close button is clicked then destroy the dialog */
else if (evt.getActionCommand().equals("Close")) dispose();
/** if other buttons are clicked */
else {
/** find which key setup button is clicked */
int i = 0, j = 0;
boolean found = false;
for (i = 0; i < 4; ++i) {
for (j = 0; j < 5; ++j) {
/** if key found then exit the loop */
if (evt.getSource().equals(buttons[i][j])) found = true;
if (found) break;
}
if (found) break;
}
/** set keys being set indexes */
keysBeingSet[0] = i;
keysBeingSet[1] = j;
/** setup get key loop */
waitingForKey = true;
/** create the get key dialog */
new GetKeyDialog(this, "Press a key to be assigned...", true);
}
} |
6b2f1450-eda5-4b61-8527-05b61fa966be | 6 | public static boolean helpMostSpecificMethodP(Stella_Class renamed_Class, MethodSlot method) {
if (renamed_Class == null) {
return (true);
}
{ boolean testValue000 = false;
{ boolean foundP000 = false;
{ Slot slot = null;
Cons iter000 = renamed_Class.classLocalSlots.theConsList;
loop000 : for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
slot = ((Slot)(iter000.value));
if (slot.slotDirectEquivalent == method) {
foundP000 = true;
break loop000;
}
}
}
testValue000 = foundP000;
}
testValue000 = !testValue000;
if (testValue000) {
{ boolean alwaysP000 = true;
{ Surrogate sub = null;
Cons iter001 = renamed_Class.classDirectSubs.theConsList;
loop001 : for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) {
sub = ((Surrogate)(iter001.value));
if (!Stella_Class.helpMostSpecificMethodP(((Stella_Class)(sub.surrogateValue)), method)) {
alwaysP000 = false;
break loop001;
}
}
}
testValue000 = alwaysP000;
}
}
{ boolean value000 = testValue000;
return (value000);
}
}
} |
661fa881-14d1-4578-8e92-2f5eff87b837 | 9 | @Override
public List<ECollisionType> getCollisions(Long id, Long lecturerId,
List<Long> roomIds, List<Long> studentGroupIds,
int numberOfAppointments, Date startDate, Date endDate) {
if (id != null) {
return new ArrayList<ECollisionType>();
}
// The set with all found collionsTypes
Set<ECollisionType> collisionsSet = new HashSet<ECollisionType>();
// generate appointments
Set<Appointment> appointments = meetingService.createAppointments(
numberOfAppointments, startDate, endDate);
for (Appointment appointment : appointments) {
// set start and end date
Date start = appointment.getStart();
Date end = appointment.getEnd();
for (Long roomId : roomIds) {
// Check for RoomCollisions
if (this.roomService.isOccupied(roomId, start, end)) {
collisionsSet.add(ECollisionType.ROOM_OCCUPIED);
}
// Check for RoomSizeCollisions
for (Long studentGroupId : studentGroupIds) {
if (!this.roomService.hasEnoughSeats(roomId, studentGroupId)) {
collisionsSet.add(ECollisionType.ROOM_TOO_SMALL);
}
}
}
// Check for LecturerCollisions
if (lecturerService.isBusy(lecturerId, start, end)) {
collisionsSet.add(ECollisionType.LECTURER_BUSY);
}
// Check for StudentGroupCollisions
for (Long studentGroupId : studentGroupIds) {
if (studentGroupService.isBusy(studentGroupId, start, end)) {
collisionsSet.add(ECollisionType.STUDENTGROUP_BUSY);
}
}
}
// returns a List of all found collsionTypes
return new ArrayList<ECollisionType>(collisionsSet);
} |
f45839ff-87a5-4cf5-9d7c-f1c21d2bfba2 | 8 | public void move(boolean max, int m) {
int start = m;
int finish = m + this.board[m];
int loops = (finish - start) / 13;
if (max) {
if (finish == 13) { finish++; }
if (finish <= 12) {
fillBeans(start + 1, finish);
} else {
fillBeans(start + 1, 12);
while (loops > 0) {
fillBeans(0, 12);
loops--;
}
fillBeans(0, finish % 13);
}
} else {
if (finish % 13 == 6) { finish++; }
if (finish <= 13) {
fillBeans(start + 1, finish);
} else {
fillBeans(start + 1, 13);
while (loops > 0) {
fillBeans(0, 5);
fillBeans(7, 13);
loops--;
}
if (finish % 13 < 6) {
fillBeans(0, finish % 13);
} else {
fillBeans(0, 5);
fillBeans(7, finish % 13);
}
}
}
this.setBeans(start, 0);
} |
e992ec56-673e-49f7-8663-df7870b554f5 | 4 | public static void print(Collection<? extends Object> collection) {
Iterator<? extends Object> it = collection.iterator();
collection.getClass();
System.out.print(collection.getClass().getSimpleName() + ": " +
(it.hasNext() ? it.next() : null));
while(it.hasNext()) {
System.out.print(", " + it.next());
}
System.out.println("\n");
} |
Subsets and Splits