method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
52f2f267-4962-4e7d-8ff7-87e8016e068a | 6 | public void updateTask()
{
double var1 = 100.0D;
double var3 = this.entityHost.getDistanceSq(this.attackTarget.posX, this.attackTarget.boundingBox.minY, this.attackTarget.posZ);
boolean var5 = this.entityHost.getEntitySenses().canSee(this.attackTarget);
if (var5)
{
++this.field_48367_f;
}
else
{
this.field_48367_f = 0;
}
if (var3 <= var1 && this.field_48367_f >= 20)
{
this.entityHost.getNavigator().clearPathEntity();
}
else
{
this.entityHost.getNavigator().func_48667_a(this.attackTarget, this.field_48370_e);
}
this.entityHost.getLookHelper().setLookPositionWithEntity(this.attackTarget, 30.0F, 30.0F);
this.rangedAttackTime = Math.max(this.rangedAttackTime - 1, 0);
if (this.rangedAttackTime <= 0)
{
if (var3 <= var1 && var5)
{
this.doRangedAttack();
this.rangedAttackTime = this.maxRangedAttackTime;
}
}
} |
2f037ea0-6d16-4fc2-a355-9635826f15a0 | 6 | private void ComputeLCPMatrix(Vector<Contact> contacts, Matrixd A) {
for (int i = 0; i < contacts.size(); ++i)
{
Contact ci = contacts.get(i);
Vector3d tmp = new Vector3d(ci.contactPoint);
tmp.Substract(ci.body[0].position);
Vector3d rANi = tmp.CrossProduct(ci.contactNormal);
tmp = new Vector3d(ci.contactPoint);
tmp.Substract(ci.body[1].position);
Vector3d rBNi = tmp.CrossProduct(ci.contactNormal);
for (int j = 0; j < contacts.size(); ++j)
{
Contact cj = contacts.get(j);
tmp = new Vector3d(cj.contactPoint);
tmp.Substract(cj.body[0].position);
Vector3d rANj = tmp.CrossProduct(cj.contactNormal);
tmp = new Vector3d(cj.contactPoint);
tmp.Substract(cj.body[1].position);
Vector3d rBNj = tmp.CrossProduct(cj.contactNormal);
double a = 0.0d;
if (ci.body[0] == cj.body[0])
{
a += ci.body[0].inverseMass*(ci.contactNormal.ScalarProduct(cj.contactNormal));
a += rANi.ScalarProduct(ci.body[0].inverseInertiaTensor.Transform(rANj));
}
else if (ci.body[0] == cj.body[1])
{
a -= ci.body[0].inverseMass*(ci.contactNormal.ScalarProduct(cj.contactNormal));
a -= rANi.ScalarProduct(ci.body[0].inverseInertiaTensor.Transform(rANj));
}
if (ci.body[1] == cj.body[0])
{
a -= ci.body[1].inverseMass*(ci.contactNormal.ScalarProduct(cj.contactNormal));
a -= rBNi.ScalarProduct(ci.body[1].inverseInertiaTensor.Transform(rBNj));
}
else if (ci.body[1] == cj.body[1])
{
a += ci.body[1].inverseMass*(ci.contactNormal.ScalarProduct(cj.contactNormal));
a += rBNi.ScalarProduct(ci.body[1].inverseInertiaTensor.Transform(rBNj));
}
A.entry[i][j] = a;
}
}
} |
74b4225a-3180-4146-9980-732d8418e156 | 1 | @Override
public void updateUser(User user) {
User old = userDao.findById(user.getId());
if(old==null)
return ;
//cannot update so return null
old.setName(user.getName());
old.setSurname(user.getSurname());
userDao.saveOrUpdate(old);
} |
e9c7f1ff-f934-4de2-a27b-f02503c10a6f | 4 | public boolean hasSideEffects(Expression expr) {
if (expr instanceof MatchableOperator
&& expr.containsConflictingLoad((MatchableOperator) expr))
return true;
for (int i = 0; i < subExpressions.length; i++) {
if (subExpressions[i].hasSideEffects(expr))
return true;
}
return false;
} |
238240e9-d60d-44e8-b49f-ecf7d21933db | 6 | public static StateObject getStateObject(int objectX, int objectY, int objectHeight, int objectId)
{
for (StateObject so : stateChanges)
{
if(so == null)
continue;
if(so.getHeight() != objectHeight)
continue;
if(so.getStatedObject() == objectId && so.getX() == objectX && so.getY() == objectY)
return so;
}
return null;
} |
21e89387-283b-4b07-838b-3d19deb3c6af | 4 | private double[][] getHelperArray() {
double[][] helperArray = new double[combinedOutputs[0].length][combinedOutputs.length * (input[0].length + 1)];
int parameterCnt = input[0].length + 1;
for(int i = 0; i < combinedOutputs[0].length; i++) {
for(int j = 0; j < combinedOutputs.length; j++) {
for(int k = 0; k < input[0].length + 1; k++) {
if(k == input[0].length) {
helperArray[i][j * parameterCnt + k] = combinedOutputs[j][i];
} else {
helperArray[i][j * parameterCnt + k] = combinedOutputs[j][i] * input[i][k];
}
}
}
}
return helperArray;
} |
e674ae46-6594-4c1e-b47b-1cfcfcd43921 | 8 | public int romanToInt(String s) {
int res = 0;
for(int i =0; i<s.length();i++)
{
if(i<s.length()-1)
{
String x = s.substring(i, i+2);
switch (x){
case "CM": res += 900;i++; break;
case "CD": res += 400;i++;break;
case "XC": res += 90;i++;break;
case "XL": res += 40;i++;break;
case "IX": res += 9;i++;break;
case "IV": res += 4;i++;break;
default:
res += mapSingle(s.substring(i, i+1));
}
}else
res += mapSingle(s.substring(i, i+1));
}
return res;
} |
0beafa6b-f500-486f-ba6c-1d7adf5207da | 4 | String proteinFormat(String protein) {
if (protein.isEmpty()) return "";
// We use uppercase letters
protein = protein.toUpperCase();
// Stop codon is trimmed
int idxLast = protein.length() - 1;
char lastChar = protein.charAt(idxLast);
if ((lastChar == '*') || (lastChar == '?')) protein = protein.substring(0, idxLast);
// We use '?' as unknown protein
protein = protein.replace('X', '?');
// Remove staring '?' codons
if (protein.startsWith("?")) protein = protein.substring(1);
return protein;
} |
be82dd08-9306-4ec9-919c-bb9ef1e8deb7 | 1 | public String getSummary() {
LOGGER.log(Level.INFO, "Generating string summary for bag " + this.hashCode());
String output = "";
for (Disc disc : discs) {
output += "\n* -- " + disc.getName();
}
return output;
} |
08ce6a1b-512e-411e-b34e-6575e241e253 | 7 | public void buySkiPassMenu(Scanner scanner) {
// Delete old card
skiPassCard = null;
System.out.println("Choose ski-pass type from the list:");
System.out.println("1 - LIMITED:"
+ " limited number of passages, valid for 1 year");
System.out.println("2 - HOURLY:"
+ " unlimited number of passages, limited time");
System.out.println("3 - SEASON:"
+ " unlimited number of passages during the whole season");
int option;
option = scanner.nextInt();
switch (option) {
case 1:
System.out.println("Enter the number of passages: ");
int numPassages = scanner.nextInt();
skiPassCard = getLimitedSkiPass(numPassages);
break;
case 2:
System.out.println("1 - 1 day or more");
System.out.println("2 - first half of the day 9:00 - 13:00");
System.out.println("3 - second half of the day 13:00 - 17:00");
int hourlyCardType = scanner.nextInt();
switch (hourlyCardType) {
case 1:
System.out.println("Enter the number of days:");
int numDays = scanner.nextInt();
skiPassCard = getDaysSkiPass(numDays);
break;
case 2:
skiPassCard = getFirstHalfDaySkiPass(new Date());
break;
case 3:
skiPassCard = getSecondHalfDaySkiPass(new Date());
break;
default:
System.out.println("Wrong option! Please try again.");
break;
}
break;
case 3:
skiPassCard = getSeasonSkiPass();
break;
default:
System.out.println("Wrong option! Please try again.");
break;
}
if (skiPassCard == null) {
System.out.println("Cannot sell a ski-pass! Please try again.");
}
} |
926f3acd-a620-49ea-9e7b-8ed10a521a3d | 3 | public void setState(int state) {
this.state=state;
if (state==0) theApp.setStatusLabel("Setup");
else if (state==1) theApp.setStatusLabel("Signal Hunt");
else if (state==2) theApp.setStatusLabel("Msg Hunt");
} |
c5525d82-074a-4715-aab2-0554f3482598 | 8 | final int _readSymbol_(final int symbol) throws IllegalArgumentException {
switch (symbol) {
case '\\':
case '=':
case ';':
case ']':
case '[':
return symbol;
case 't':
return '\t';
case 'r':
return '\r';
case 'n':
return '\n';
}
throw new IllegalArgumentException();
} |
71580b2e-1f0b-4104-8cee-4bd4e8da1292 | 0 | public CollapseTool(AutomatonPane view, AutomatonDrawer drawer,
FSAToREController controller) {
super(view, drawer);
this.controller = controller;
} |
00625d1c-a4e4-4796-8ad3-36689d9e6694 | 3 | public void render(Graphics g)
{
for (int i = 0; i<tiles.length; i++)
{
for (int j = 0; j<tiles[i].length; j++)
{
if (tiles[i][j]!=null)
{
g.drawImage(tiles[i][j].getImage(),
i*tiles[i][j].getWidth()*Game.SCALE,
j*tiles[i][j].getHeight()*Game.SCALE,
16*Game.SCALE, 16*Game.SCALE, null);
g.drawImage(tiles[i][j].getEntity().getImage(),
i*tiles[i][j].getWidth()*Game.SCALE,
j*tiles[i][j].getHeight()*Game.SCALE,
16*Game.SCALE, 16*Game.SCALE, null);
}
}
}
} |
c64fc64c-a258-48c1-8e82-0edac550bf45 | 3 | public static void main(String[] args) {
Minesweeper m = new Minesweeper(2);
Scanner sc = new Scanner(System.in);
int x = 0 , y = 0;
while(true){
System.out.println(m);
// System.out.println(m.testString());
System.out.print("\nX coordinate\t");
x = sc.nextInt();
if(x == -1)
return;
System.out.print("\nY coordinate\t");
y = sc.nextInt();
if(y == -1)
continue;
m.open(x,y);
}
} |
b4821614-ff22-4281-b0ee-9ca94c8f55c5 | 2 | public static Car getInstance(String typeOfCar, RegistrationNumber registrationNumber, int fuelCapacity, int fuelInCar, boolean carRented){
String stringRepresentation = registrationNumber.toString() + fuelCapacity + fuelInCar + carRented;
Car c = CARS.get(stringRepresentation);
if (c != null) return c;
if (typeOfCar.equalsIgnoreCase("small car")){
c = new SmallCar(registrationNumber, fuelCapacity, fuelInCar, carRented);
}else{
c = new LargeCar(registrationNumber, fuelCapacity, fuelInCar, carRented);
}
CARS.put(stringRepresentation, c);
return c;
} |
b86dd49e-7282-468a-a4a5-1d697ef3c0e9 | 4 | public final static BruteParams<?> valueOf(final String s) {
for (final BruteParams<?> value : BruteParams.values) {
if (value.s.equalsIgnoreCase(s)) {
return value;
}
}
return null;
} |
8470acab-c8d9-4b07-8e5f-45edc80c937a | 0 | private Singleton(){
// Optional Code
} |
bff95edc-4da2-4fd7-927c-490ba92a0db4 | 0 | @Test
public void testNoTestLinkAnnotationSuccess() {
assertTrue(true);
} |
717d3e8e-89eb-4205-a7da-db71f7a6a167 | 7 | @Override
public void keyReleased(KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_F:
MainClass.getLevelManager().getPlayer().processFRelease();
break;
case KeyEvent.VK_D:
MainClass.getLevelManager().getPlayer().processDRelease();
break;
case KeyEvent.VK_LEFT:
arrowKeys[0] = false;
//MainClass.getMainClass.getLevelManager().getPlayer().arrowKeyReleased(0);
break;
case KeyEvent.VK_RIGHT:
arrowKeys[1] = false;
//MainClass.getMainClass.getLevelManager().getPlayer().arrowKeyReleased(1);
break;
case KeyEvent.VK_UP:
arrowKeys[2] = false;
//MainClass.getMainClass.getLevelManager().getPlayer().arrowKeyReleased(2);
break;
case KeyEvent.VK_DOWN:
arrowKeys[3] = false;
//MainClass.getMainClass.getLevelManager().getPlayer().arrowKeyReleased(3);
break;
case KeyEvent.VK_SPACE:
space = false;
break;
}
} |
945e445a-9522-4fd2-a58b-b2e599fd4ef8 | 8 | protected static Ptg calcDec2Oct( Ptg[] operands )
{
if( operands.length < 1 )
{
return new PtgErr( PtgErr.ERROR_NULL );
}
debugOperands( operands, "DEC2OCT" );
long dec = PtgCalculator.getLongValue( operands[0] );
int places = 0;
if( operands.length > 1 )
{
places = operands[1].getIntVal();
}
if( (dec < -536870912L) || (dec > 536870911L) || (places < 0) )
{
return new PtgErr( PtgErr.ERROR_NUM );
}
String oString = Long.toOctalString( dec );
if( dec < 0 )
{ // truncate to 10 digits automatically (should already be two's complement)
oString = oString.substring( Math.max( oString.length() - 10, 0 ) );
}
else if( places > 0 )
{
if( oString.length() > places )
{
return new PtgErr( PtgErr.ERROR_NUM );
}
oString = ("0000000000" + oString); // maximum= 10 places
oString = oString.substring( oString.length() - places );
}
PtgStr pstr = new PtgStr( oString );
log.debug( "Result from DEC2OCT= " + pstr.getString() );
return pstr;
} |
b54e208d-78e9-47ed-9b38-107106f16d23 | 4 | public void addButtons() {
if (save == null) {
save = new JButton("Save");
save.addActionListener(this);
}
if (cancel == null) {
cancel = new JButton("Cancel");
cancel.addActionListener(this);
}
if (!rebuilding) {
buttonPanel = new JPanel();
} else {
frame.remove(buttonPanel);
}
if (!rebuilding) {
buttonPanel.add(save);
buttonPanel.add(cancel);
}
frame.add(buttonPanel, RelativeLayout.BOTTOM_CENTER);
} |
bd908c34-f5bb-461e-a240-74acd5c16f7e | 0 | public String goToAdminProductsList() {
this.retrieveAllProducts();
return "adminProductsList";
} |
8bc195d2-249d-42e7-9bb5-0a38e73a8343 | 0 | public void load()throws IOException{
props.load(new FileInputStream(file));
} |
df2c666e-d734-48d0-bc66-d03c45578281 | 9 | public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
Stack<List<Integer>> stack = new Stack<>();
if(root == null) return result;
Queue<TreeNode> q1 = new LinkedList<>();
Queue<TreeNode> q2 = new LinkedList<>();
q1.offer(root);
while (!q1.isEmpty() || !q2.isEmpty()) {
List<Integer> tmp = new ArrayList<>();
Queue<TreeNode> noEmptyQ = q1.isEmpty()? q2 :q1;
Queue<TreeNode> emptyQ = q1.isEmpty()? q1 :q2;
while (!noEmptyQ.isEmpty()){
TreeNode cur = noEmptyQ.poll();
tmp.add(cur.val);
if (cur.left != null)
emptyQ.offer(cur.left);
if (cur.right != null)
emptyQ.offer(cur.right);
}
stack.push(tmp);
}
while (!stack.isEmpty())
result.add(stack.pop());
return result;
} |
2cb35621-83d7-483a-b6e3-8e3fae13c258 | 8 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
final boolean undead=CMLib.flags().isUndead(target);
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,(!undead?0:CMMsg.MASK_MALICIOUS)|verbalCastCode(mob,target,auto),auto?L("A bright white glow surrounds <T-NAME>."):L("^S<S-NAME> @x1, delivering a critical healing touch to <T-NAMESELF>.^?",prayWord(mob)));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
final int healing=CMLib.dice().roll(4,adjustedLevel(mob,asLevel),6);
final int oldHP=target.curState().getHitPoints();
CMLib.combat().postHealing(mob,target,this,healing,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,null);
if(target.curState().getHitPoints()>oldHP)
target.tell(L("You feel much better!"));
}
}
else
beneficialWordsFizzle(mob,target,auto?"":L("<S-NAME> @x1 for <T-NAMESELF>, but nothing happens.",prayWord(mob)));
// return whether it worked
return success;
} |
25192fd2-b885-4241-842f-55e21206a82c | 4 | public static BV4502 getInstance(I2CInterface device, char channel) {
BV4502.device = device;
switch (channel) {
case 'A' :
if (channel_A==null) channel_A=new BV4502('A');
return channel_A;
case 'B' :
if (channel_B==null) channel_B=new BV4502('B');
return channel_B;
}
throw new IllegalArgumentException();
} |
57928e34-193f-4e42-8549-4e0a8776f121 | 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(FormObras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FormObras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FormObras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FormObras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FormObras().setVisible(true);
}
});
} |
1ef5ba19-645e-4d39-8ee3-a3128242f285 | 5 | public JSONObject increment(String key) throws JSONException {
Object value = opt(key);
if (value == null) {
put(key, 1);
} else if (value instanceof Integer) {
put(key, ((Integer)value).intValue() + 1);
} else if (value instanceof Long) {
put(key, ((Long)value).longValue() + 1);
} else if (value instanceof Double) {
put(key, ((Double)value).doubleValue() + 1);
} else if (value instanceof Float) {
put(key, ((Float)value).floatValue() + 1);
} else {
throw new JSONException("Unable to increment [" + quote(key) + "].");
}
return this;
} |
5ba5e76f-a1a6-4dd2-b5fc-1b242a90fbe6 | 7 | public static boolean checkHashes(String... fileName) {
StringBuilder sb = new StringBuilder();
sb.append("SELECT `wadname`,`md5` FROM `").append(mysql_db).append("`.`wads` WHERE `wadname` IN (");
int i = 0;
for (; i < fileName.length; i++) {
if (i == fileName.length - 1)
sb.append("?");
else
sb.append("?, ");
}
sb.append(")");
String query = sb.toString();
try (Connection con = getConnection(); PreparedStatement pst = con.prepareStatement(query)){
for (int j = 1; j <= i; j++) {
pst.setString(j, fileName[j-1]);
}
ResultSet checkHashes = pst.executeQuery();
Statement stm = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet blacklistedHashes = stm.executeQuery("SELECT `name`,`md5` FROM `" + mysql_db + "`.`blacklist`;");
while (checkHashes.next()) {
blacklistedHashes.beforeFirst();
while (blacklistedHashes.next())
if (blacklistedHashes.getString("md5").equalsIgnoreCase(checkHashes.getString("md5"))) {
bot.sendMessage(bot.cfg_data.irc_channel, "Wad " + checkHashes.getString("wadname") +
" matches blacklist " + blacklistedHashes.getString("name") + " (hash: " + blacklistedHashes.getString("md5") + ")");
return false;
}
}
stm.close();
} catch (SQLException e) {
e.printStackTrace();
logMessage(LOGLEVEL_IMPORTANT, "Could not get hashes of file (SQL Error)");
return false;
}
return true;
} |
4c11bc64-96ee-46cc-9c2f-5931f7f19955 | 6 | public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
} |
e2c43e76-197a-4446-ba74-a03850f268be | 6 | private static void SwapStudents() {
int indexOfStu1 = -9;
int indexOfStu2 = -9;
String lName = new String();
String fName = new String();
boolean okStu1 = false;
boolean okStu2 = false;
boolean okToSwap = false;
int studentOn = 1;
while (!(okToSwap)) {
fName = JOptionPane
.showInputDialog("Please enter enter the student's first name.");
lName = JOptionPane.showInputDialog("Please enter the #"
+ studentOn + " student's last name.");
int indexOfStu = studentExists(fName, lName);
if (indexOfStu != -9999) // if student exists
{
JOptionPane.showMessageDialog(null, "Student #" + studentOn
+ " was found at index " + indexOfStu + ".");
if (studentOn == 1) // if we're on the first stu,
{
indexOfStu1 = indexOfStu; // student 1 exists.
okStu1 = true;
studentOn = 2;
}
else if (studentOn == 2) // if we're on the second stu,
{
indexOfStu2 = indexOfStu; // student 2 exists
okStu2 = true;
studentOn = 0;
}
}
else
JOptionPane.showMessageDialog(null,
"Sorry. Student not found. Please re-enter a name.");
if (okStu1 && okStu2) // if both students exist,
okToSwap = true; // OK to swap
}
Swap(indexOfStu1, indexOfStu2);
} |
8da173dc-a0b9-498a-998b-397c71d586fa | 5 | public static ArrayList<Fine> getAllUnpaidFines(){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<Fine> fineList = new ArrayList<Fine>();
try {
Statement stmnt = conn.createStatement();
String sql = "SELECT * FROM Fines where paid = 0";
ResultSet res = stmnt.executeQuery(sql);
while(res.next()) {
fine = new Fine(res.getInt("fine_id"), res.getInt("transaction_id"), res.getInt("member_id"), res.getFloat("fine_amount"), res.getBoolean("paid"));
fineList.add(fine);
}
}
catch(SQLException e) {
System.out.println(e);
}
return fineList;
} |
575ca1ad-8613-4fde-b306-e222efbee9e5 | 8 | public CalculationPeriodFrequency readCalculationPeriodFrequency(XMLStreamReader2 streamReader) throws XMLStreamException {
Integer periodMultiplier = null;
PeriodEnum period = null;
RollConventionEnum rollConvention = null;
int startingDepth = streamReader.getDepth();
while(streamReader.hasNext()) {
switch(streamReader.next()) {
case XMLEvent.START_ELEMENT:
if(streamReader.getDepth() == startingDepth + 1) {
String localName = streamReader.getLocalName();
if("periodMultiplier".equals(localName)) {
periodMultiplier = Integer.parseInt(FpmlParser.readText(streamReader));
}
if("period".equals(localName)) {
period = PeriodEnum.valueOf(FpmlParser.readText(streamReader));
}
if("rollConvention".equals(localName)) {
rollConvention = RollConventionEnum.fromValue(FpmlParser.readText(streamReader));
}
}
break;
case XMLEvent.END_ELEMENT:
if(streamReader.getDepth() == startingDepth) {
return new CalculationPeriodFrequency(periodMultiplier, period, rollConvention);
}
}
}
throw new PricerException("No more events before element finished");
} |
29815b5d-abe8-42c2-8970-13c423d1c219 | 9 | @Override
public Command planNextMove(Info info) {
if(info.getEnemies().isEmpty()==false)
{
int e_x = info.getEnemies().get(0).getX();
int e_y = info.getEnemies().get(0).getY();
int pomx,pomy,pomx1,pomy1;
int pos =0;
for(int i=1;i<info.getEnemies().size();i++){
pomx =(info.getEnemies().get(i).getX()-info.getX());
if(pomx<0)
pomx *=-1;
pomx1 = e_x -info.getX() ;
if(pomx1<0)
pomx1 *=-1;
pomy =(info.getEnemies().get(i).getY()-info.getY());
if(pomy<0)
pomy *=-1;
pomy1 = e_y -info.getY() ;
if(pomy1<0)
pomy1 *=-1;
if(pomx< pomx1 && pomy < pomy1)
{
e_x = info.getEnemies().get(i).getX();
e_y = info.getEnemies().get(i).getY();
pos = i;
}
}
int angle =0;
e_x = info.getEnemies().get(pos).getX();
e_y = info.getEnemies().get(pos).getY();
angle = getAngle(info,e_x,e_y);
if(Check(info))
{
// if(greenade(info, angle))
// {
return new Command(CommandType.MOVE_FORWARD, CommandType.TURN_RIGHT,angle , CommandType.SHOOT);
/* }
else
{
return new Command(CommandType.MOVE_FORWARD, CommandType.TURN_RIGHT, 5 , CommandType.SHOOT);
}*/
}
else
{
return new Command(CommandType.MOVE_FORWARD, CommandType.TURN_RIGHT, (angle+180) , CommandType.NONE);
}
}
else
{
return new Command(CommandType.NONE, CommandType.NONE, 0 , CommandType.NONE);
}
} |
40dc7b00-c410-41f9-8785-25bc5ca3c6b9 | 7 | public ArrayList<Plane> SearchPlanesAvailable(Date d){
ArrayList<Plane> foundPlanes = new ArrayList<Plane>();
for(Plane p : planes.values()){
boolean dontAdd = false;
for (Flight f : flights.values()) {
if (d.getYear() == f.getDate().getYear() && d.getMonth() == f.getDate().getMonth() && d.getDay() == f.getDate().getDay() && f.getPlane() == p) {
dontAdd = true;
}
}
if (!dontAdd) {
foundPlanes.add(p);
}
}
return foundPlanes;
} |
2b735bfa-5283-4ad1-8c45-12e62c77efa2 | 7 | @Override
public void mousePressed(MouseEvent me) {
this.requestFocus();
int x = me.getX() / scale;
int y = me.getY() / scale;
tp.setMouseClick(new Vector3f(x,y,0));
Color c = null;
if(SwingUtilities.isRightMouseButton(me)) {
c = bg;
} else if(SwingUtilities.isLeftMouseButton(me)) {
c = fg;
}
if(curTool == TOOL_PENCIL) {
tp.color(c.getRGB(), x, y);
} else if(curTool == TOOL_FILLER) {
tp.fill(c.getRGB(), x, y);
} else if(curTool == TOOL_CHOOSER) {
if(SwingUtilities.isRightMouseButton(me)) {
bg = tp.getColorAt(x, y);
} else if(SwingUtilities.isLeftMouseButton(me)) {
fg = tp.getColorAt(x, y);
}
tp.setColor(fg.getRGB());
this.setTool(lastTool);
}
view.updateTexture(tp.getTexture());
} |
78733181-f242-47c8-bd27-d6da6403b2c9 | 0 | public void actionPerformed(ActionEvent e) {
performAction((Component)e.getSource());
} |
c16a6cb8-a030-494c-b62a-9eee2c31d16e | 1 | private static String getStringFromDocument(Document doc) {
try {
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
} catch (TransformerException ex) {
ex.printStackTrace();
return null;
}
} |
de41b63b-b34d-4c9d-aaa2-6fc508b6fd8b | 9 | public void summary2(String label, Map<? extends Object, Stats1D> data, Integer norm, boolean average, FullResult reference)
throws Exception
{
if ( data == null ) return;
boolean allInt = true;
Object[] keys = new Object[data.size()];
int i = 0, sum = 0;
for(Object key : data.keySet()) {
keys[i++] = key;
sum += data.get(key).sum();
allInt &= (key instanceof Integer);
}
Arrays.sort(keys);
out.start(prefix(label));
String description = String.format("total=%d, norm=%d ", sum, norm);
out.description(description);
if ( allInt && average && sum > 1 ) {
double hsum = 0.0, hsum2 = 0.0;
for(Object key : keys) {
double w = data.get(key).sum();
hsum += w * ((Integer)key).intValue();
}
double avg = hsum/sum;
for(Object key : keys) {
double w = data.get(key).sum() - avg;
hsum2 += w * w * ((Integer)key).intValue();
}
out.value("_average", avg);
out.value("_sdev", Math.sqrt(hsum2/(sum-1)/sum));
}
DiscreteDistr distr = prepareDistr(label);
for(Object key : keys) {
out.item(key, data.get(key));
distr.inc(key, (int) data.get(key).sum());
}
addTest2Out(distr, label, reference);
out.finish(sum);
} |
cc452f99-fc93-43a6-b355-3c8323c75f72 | 8 | public void actualizarSensores() {
if ((int) robot1.getPuntoActual().getY() - 1 < 0)
robot1.setSensorArriba(false);
else if (DibujoEntorno[(int) robot1.getPuntoActual().getX()][(int) robot1
.getPuntoActual().getY() - 1] == 1)
robot1.setSensorArriba(false);
else
robot1.setSensorArriba(true);
if ((int) robot1.getPuntoActual().getY() + 1 > altoEntorno - 1)
robot1.setSensorAbajo(false);
else if (DibujoEntorno[(int) robot1.getPuntoActual().getX()][(int) robot1
.getPuntoActual().getY() + 1] == 1)
robot1.setSensorAbajo(false);
else
robot1.setSensorAbajo(true);
if ((int) robot1.getPuntoActual().getX() - 1 < 0)
robot1.setSensorIzquierda(false);
else if (DibujoEntorno[(int) robot1.getPuntoActual().getX() - 1][(int) robot1
.getPuntoActual().getY()] == 1) {
robot1.setSensorIzquierda(false);
} else
robot1.setSensorIzquierda(true);
if ((int) robot1.getPuntoActual().getX() + 1 > anchoEntorno - 1)
robot1.setSensorDerecha(false);
else if (DibujoEntorno[(int) robot1.getPuntoActual().getX() + 1][(int) robot1
.getPuntoActual().getY()] == 1)
robot1.setSensorDerecha(false);
else
robot1.setSensorDerecha(true);
} |
86b9fcdf-ba06-4e80-ad79-d5f34d2a7446 | 2 | public static void main(String[] args) {
if(args == null || args.length < 2){
printHelp();
return;
}
new Transfer().mysql2mongo(args[0],args[1]);
} |
12c7110e-d4e3-4c1e-bc68-92cae150374f | 1 | private void getNumCon() {
//Maintenance debug method, for getting all number of alive connections and connection pools - use to debug current state of the pool.
try {
System.out.println("Number of Connections: " + cpds.getNumConnections());
System.out.println("Number of Idle Connections: " + cpds.getNumIdleConnections());
System.out.println("Number of Busy Connections: " + cpds.getNumBusyConnections());
System.out.println("Number of Connection Pools: " + cpds.getNumUserPools());
System.out.println("");
} catch (SQLException ex) {
printSQLException(ex);
}
} |
d5d2f3bd-7b85-4df4-975d-fbaf89958665 | 4 | public void performClick() {
switch (cellType) {
case "F":
setColor(Colors.RED_LIGHT);
break;
case "T":
setColor(Colors.BLUE);
break;
case "0/0":
setColor(Colors.GREEN_LIGHT);
break;
default:
setColor(Colors.GREY);
}
setText(cellType);
if (!isFlipped())
reveal();
} |
d9b59d84-dfc3-4abc-95c1-cbeca8524af4 | 5 | public static Class decodeSolutionType(String encodedQuestion) throws DecodeException, ClassNotFoundException {
Class res;
int i=0;
int beginning = i;
while (encodedQuestion.charAt(i) != '>') {
i++;
}
String type = encodedQuestion.substring(beginning, i);
switch(type) {
case "int":
res = Class.forName("Integer");
break;
case "dbl":
res = Class.forName("Double");
break;
case "str":
res = Class.forName("String");
break;
case "chr":
res = Class.forName("Character");
break;
default:
throw new DecodeException("non recognized type");
}
return res;
} |
b654f411-c5e8-4d2f-8530-fb83ea6ecc5d | 7 | @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Block block = event.getClickedBlock();
if (block.getType() != Material.CHEST) {
return;
}
Location loc = block.getLocation();
Player player = event.getPlayer();
adminEnabled = cmds.getSwagAdminEnabled();
if (player.hasPermission("swagchest.admin") && adminEnabled.contains(player.getPlayerListName())) {
player.sendMessage(ChatColor.GREEN + "Chest coords: " + loc.getBlockX() + ", "
+ loc.getBlockY() + ", "
+ loc.getBlockZ() + " ("
+ loc.getWorld().getName() + ")");
if (isChestRegistered(loc)) {
player.sendMessage(ChatColor.GREEN + "This swag chest is registered as: " + chestObject.getId());
} else {
player.sendMessage(ChatColor.GREEN + "This chest is not a registered swag chest.");
}
} else {
if (isChestRegistered(loc)) {
if (!plugin.getChestTasks().containsKey(chestObject.getId())) {
PopulateChest chestTask = new PopulateChest(plugin, chestObject.getId(), false);
}
}
}
}
} |
b1367773-f112-4da5-a73f-35fce825f0e9 | 0 | public SortedSet<TVC> getConnectionsSortedUp() {
return connectionsSortedUp;
} |
250e1790-e2e0-4351-812a-1a072defff08 | 7 | @Override
public void update() {
if (Mouse.getX() > getX() && Mouse.getX() < getX() + getWidth()) {
int mousey = Display.getHeight() - Mouse.getY();
if (mousey > getY() && mousey < getY() + getHeight()) {
if (Mouse.isButtonDown(0)) {
if (!held) {
if (state == State.Checked) {
state = State.Unchecked;
setChanged();
notifyObservers(state);
} else {
state = State.Checked;
setChanged();
notifyObservers(state);
}
held = true;
}
} else {
held = false;
}
}
}
} |
539e5569-0eb9-4718-b304-12bfbc41665e | 8 | public void setup(Map attributes) {
// do we have a SecureRandom, or should we use our own?
rnd = (SecureRandom) attributes.get(SOURCE_OF_RANDOMNESS);
// are we given a set of Diffie-Hellman generation parameters or we shall
// use our own?
DHGenParameterSpec params =
(DHGenParameterSpec) attributes.get(DH_PARAMETERS);
// find out the desired sizes
if (params != null) {
l = params.getPrimeSize();
m = params.getExponentSize();
} else {
Integer bi = (Integer) attributes.get(PRIME_SIZE);
l = (bi == null ? DEFAULT_PRIME_SIZE : bi.intValue());
bi = (Integer) attributes.get(EXPONENT_SIZE);
m = (bi == null ? DEFAULT_EXPONENT_SIZE : bi.intValue());
}
// if ((L % 256) != 0 || L < 1024) {
if ((l % 256) != 0 || l < DEFAULT_PRIME_SIZE) {
throw new IllegalArgumentException("invalid modulus size");
}
if ((m % 8) != 0 || m < DEFAULT_EXPONENT_SIZE) {
throw new IllegalArgumentException("invalid exponent size");
}
if (m > l) {
throw new IllegalArgumentException("exponent size > modulus size");
}
} |
ddb8e06f-219a-414d-9e5c-977bb737a7a9 | 5 | public void dump(int x, int y, boolean fore){
try{
if(tiles[x][y] != null){
if(fore){
if(tiles[x][y].foreground != null){
tiles[x][y].foreground.dump();
tiles[x][y].foreground = null;
}
} else {
if(tiles[x][y].background != null){
tiles[x][y].background.dump();
tiles[x][y].background = null;
}
}
}
} catch(Exception e){
e.printStackTrace();
}
} |
446bf3e6-4231-4380-80e0-971b3b95c5b9 | 1 | public void testWithField2() {
TimeOfDay test = new TimeOfDay(10, 20, 30, 40);
try {
test.withField(null, 6);
fail();
} catch (IllegalArgumentException ex) {}
} |
d1db24e4-a27d-4368-bda1-4702ab25da5e | 5 | private static Integer randomPort() {
int retries = RANDOM_PORT_RETRIES;
Random random = new Random();
while (retries-- > 0) {
ServerSocket socket = null;
try {
Integer port = random.nextInt(50000) + 10000;
LOGGER.debug("Trying random port: " + port);
socket = new ServerSocket(port);
return port;
} catch (Exception e) {
LOGGER.warn("Port busy", e);
try {
Thread.sleep(random.nextInt(10) * 1000 + 1000);
} catch (InterruptedException e1) {
// Ignore
}
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// Ignore
}
}
}
}
throw new IllegalStateException("Could not find a suitable random port");
} |
45a39ad5-c1ba-456d-a437-33c90f68518b | 4 | private static String executeGetCommand(DataBaseManager dbManager, Command command) {
List<String> args = command.getArgs();
String tableName = args.get(0);
String key = args.get(1);
String msg = "";
try {
if ("*".equals(key)) {
Map<String, Row> result = dbManager.getAll(tableName);
msg = getResultSetAsStr(result);
} else {
List<String> result = dbManager.get(tableName, key);
msg = getResultSetAsStr(result);
}
} catch (DataBaseTableException e) {
msg = e.getMessage();
} catch (DBUnavailabilityException e) {
msg = e.getMessage();
} catch (DataBaseRequestException e) {
msg = e.getMessage();
}
return msg;
} |
6f10fa4c-33f3-42de-ac5f-d5549699fbca | 2 | public static String implode (List strings, String separator) {
StringBuilder sb = new StringBuilder();
Iterator ite = strings.iterator();
while(ite.hasNext()) {
sb.append(ite.next().toString());
if(ite.hasNext())
sb.append(separator);
}
return sb.toString();
} |
1230001f-9f15-4d1f-9443-e2f1e4348337 | 3 | public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>();
boolean[] visited = new boolean[n+1];
for(int i=0;i<=n;i++){
g.add(new ArrayList<Integer>());
visited[i]=false;
}
for(int j=0;j<m;j++){
int a = in.nextInt();
int b = in.nextInt();
g.get(a).add(b);
}
for(int i=1;i<=n;i++){
dfs(i, g, visited);
}
} |
5a68a761-a2ea-465d-81af-0279670f7654 | 5 | private String calculatePostfix(QueueInterface<T> postfix) throws DAIndexOutOfBoundsException, DAIllegalArgumentException, NumberFormatException, NotEnoughOperandsException
{
StackInterface<T> operandStack = new DynamicArray<T>();
DequeInterface<T> exprDeque = new DynamicArray<T>();
String result = "";
while(postfix.getSize() != 0)
{
String currentItem = (String) postfix.getFront();
if(currentItem.matches(OPERAND))
{
operandStack.addLast(postfix.removeFront());
}
else if(currentItem.matches(OPERATOR))
{
if(operandStack.getSize() >= 2)
{
exprDeque.addLast(operandStack.removeLast()); //adding last operand in expression
exprDeque.addFront(postfix.removeFront()); //adding the operator
exprDeque.addFront(operandStack.removeLast()); //adding first operand in expression
operandStack.addLast(calculateExpr(exprDeque)); //adding the result to the stack
}
else
{
throw new NotEnoughOperandsException();
}
}
}
if(operandStack.getSize() == 1)
result = (String) operandStack.removeLast();
return result;
} |
7de7d00e-7f25-450e-bf32-8ec2c3391d9b | 3 | private static void setOpaque(JComponent jc, boolean opaque) {
if (jc instanceof JTextField) {
return;
}
jc.setOpaque(false);
if (jc instanceof JSpinner) {
return;
}
for (int a = 0; a < jc.getComponentCount(); a++) {
JComponent child = (JComponent) jc.getComponent(a);
setOpaque(child, opaque);
}
} |
0bde6cc0-a718-4296-bb2d-5a20c5b836f2 | 3 | public static Company[] getCompanies() {
ArrayList<Company> companies = new ArrayList<Company>();
try {
Statement s1 = conn.createStatement();
ResultSet rs = s1
.executeQuery("Exec getCompanies");
if (rs != null) {
while (rs.next()) {
String name = rs.getString("name");
String hq = rs.getString("HQ");
int perks = rs.getInt("perks");
// System.out.println(name + " " + hq + " " + " " + perks);
companies.add(new Company(name, hq, perks));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return companies.toArray(new Company[companies.size()]);
} |
cb0f9cfc-7693-4a06-80ed-08465a6448da | 8 | public void FormEdit(CaseList caselist, ContactList contactlist, boolean createRow)
{
JPanel panel2 = new JPanel(new GridLayout(0,2));
panel2.setPreferredSize(new Dimension(400,200));
panel2.add(new JLabel("Case Add Form"));
panel2.add(new JLabel (""));
JTextField cf0 = new JTextField(this.getCaseNumber());
panel2.add(new JLabel("Case Number: "));
panel2.add(cf0);
JTextField cf1 = new JTextField(this.getCaseName());
panel2.add(new JLabel("Case Name: "));
panel2.add(cf1);
JTextField cf2 = new JTextField(this.getCaseDescription());
panel2.add(new JLabel("Case Description: "));
panel2.add(cf2);
Vector clientnames = new Vector();
Vector lawyernames = new Vector();
Vector paranames = new Vector();
clientnames.add("Select a Client");
lawyernames.add("Select an Attorney");
paranames.add("Select a Paralegel");
//Get names from the contact table
for (int i =0; i < contactlist.rowCount(); i++)
{
Contact contact = contactlist.getRowContact(i);
if (contact.getContactType().equals("Customer"))
clientnames.add(contact.getLastname() + ", " + contact.getFirstname());
else if (contact.getContactType().equals("Attorney"))
lawyernames.add(contact.getLastname() + ", " + contact.getFirstname());
else if (contact.getContactType().equals("Paralegal"))
paranames.add(contact.getLastname() + ", " + contact.getFirstname());
}
JComboBox cf3 = new JComboBox(clientnames);
cf3.setSelectedItem(this.getClientName());
panel2.add(new JLabel("Client: "));
panel2.add(cf3);
JComboBox cf4 = new JComboBox(lawyernames);
cf4.setSelectedItem(this.getLawyer());
panel2.add(new JLabel("Case Lawyer: "));
panel2.add(cf4);
JComboBox cf5 = new JComboBox(paranames);
cf5.setSelectedItem(this.getParalegal());
panel2.add(new JLabel("Case Paralegal: "));
panel2.add(cf5);
String[] items3 = {"Inactive", "Active"};
JComboBox cf6 = new JComboBox(items3);
cf6.setSelectedItem(this.getStatus());
panel2.add(new JLabel("Case Status: "));
panel2.add(cf6);
panel2.add(new JLabel (""));
panel2.add(new JLabel (""));
int result = JOptionPane.showConfirmDialog(null, panel2, "Case Module", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
//if ok then save the contents of the form
if (result == JOptionPane.OK_OPTION)
{
this.setCaseNumber(cf0.getText());
this.setCaseName(cf1.getText());
this.setCaseDescription(cf2.getText());
this.setClientName(cf3.getSelectedItem().toString());
this.setLawyer(cf4.getSelectedItem().toString());
this.setParalegal(cf5.getSelectedItem().toString());
if (cf6.getSelectedIndex()==0)
this.setStatus("Inactive");
else
this.setStatus("Active");
if(this.validateRecord())
{
this.setLoaded(true);
if (createRow)
{
this.saveRecord(caselist);
}
OutputBox.display(0, "Case Module", "Case has been added");
}
else
{
this.setLoaded(false);
this.FormEdit(caselist, contactlist, createRow);
}
}
else
{
this.initRecord();
this.setLoaded(false);
}
} |
f39e13aa-400d-4925-b620-2eaece3a666e | 5 | @MethodInformation(author="Alex", date="09.12.2012", description="Gives back a double that describes the minimum number of swords to plowshares of all DieselTraktor")
protected double minSwordsDiesel() {
MyIterator it = (MyIterator) traktoren.iterator();
double min = 0;
while(it.hasNext()) {
Traktor obj = (Traktor) it.next();
if(obj.getMaschine() instanceof DrillMaschine )
{
double anz = obj.getMaschine().getDetailOfMaschine();
if(obj instanceof DieselTraktor) {
if((anz < min) || (min == 0))
min = anz;
}
}
}
return min;
} |
769ad2a5-9a10-4da2-9d9e-2e1c30d6b1e2 | 7 | public void processEvent(Event event)
{
if (event.getType() != Event.OMM_ITEM_EVENT)
System.out.println("Received unhandled event: " + event);
OMMItemEvent ommItemEvent = (OMMItemEvent)event;
Handle itemHandle = event.getHandle();
String itemName = _handleMap.get(itemHandle);
OMMMsg msg = ommItemEvent.getMsg();
if (msg.getMsgType() == OMMMsg.MsgType.REFRESH_RESP)
{
if (msg.isSet(OMMMsg.Indication.REFRESH_COMPLETE))
{
System.out.println("Received refresh complete for: " + itemName);
}
else
{
System.out.println("Received refresh for: " + itemName);
}
}
else if (msg.getMsgType() == OMMMsg.MsgType.UPDATE_RESP)
{
System.out.println("Received update for: " + itemName);
}
else if (msg.getMsgType() == OMMMsg.MsgType.GENERIC)
{
System.out.println("Received generic message type, not supported. ");
}
else if (msg.getMsgType() == OMMMsg.MsgType.STATUS_RESP)
{
System.out.println("Received status response for: " + itemName);
GenericOMMParser.parse(msg);
}
else
{
System.out.println("ERROR: Received unexpected message type. " + msg.getMsgType());
}
if (msg.isFinal())
{
_nameMap.remove(itemName);
_handleMap.remove(itemHandle);
}
} |
be22c394-5801-4b51-8079-10c4665654a1 | 2 | @Override
public void put(String key, Value value) {
char[] array = key.toCharArray();
Node node = this.root;
for (char ch : array) {
int childIndex = this.keyMap.get(ch);
if (node.children[childIndex] == null) {
node.children[childIndex] = new Node();
node.numChildren++;
}
node = node.children[childIndex];
}
node.value = value;
} |
e6331fc2-8739-411a-a85e-0e64111aa6f7 | 4 | public static Handshake parse(ByteBuffer buffer)
throws ParseException, UnsupportedEncodingException {
if (buffer.remaining() < BASE_HANDSHAKE_LENGTH + 20) {
throw new ParseException("Incorrect handshake message length.", 0);
}
int pstrlen = new Byte(buffer.get()).intValue();
byte[] pstr = new byte[pstrlen==0x13 ? pstrlen : 0x13];
//byte[] pstr = new byte[0x13];
byte[] reserved = new byte[8];
byte[] infoHash = new byte[20];
byte[] peerID = new byte[20];
boolean isObfuscated = false;
buffer.get(pstr);
buffer.get(reserved);
buffer.get(infoHash);
buffer.get(peerID);
// if we have an ordinary bittorrent handshake
if (BITTORRENT_PROTOCOL_IDENTIFIER.equals(new String(pstr, Torrent.BYTE_ENCODING))) {
isObfuscated = false;
} /* else we might have an obfuscated handshake */
else if (Peer.isMagicPeerId(peerID)) {
isObfuscated = true;
}
return new Handshake(buffer, ByteBuffer.wrap(infoHash), ByteBuffer.wrap(peerID), isObfuscated);
} |
6a8e952b-9ff3-4297-91f3-d695c1333423 | 2 | private void shiftLeafAside(int fromIndex, int destIndex, Array<E> newArray, int level) {
if (Math.max(fromIndex, destIndex) > array.getSize()) {
return;
}
int sign = (fromIndex < destIndex) ? 1 : -1;
newArray.setElement(fromIndex + sign * level, array.getElement(fromIndex));
++level;
shiftLeafAside(getLeftChildIndex(fromIndex), getLeftChildIndex(destIndex), newArray, level);
shiftLeafAside(getRightChildIndex(fromIndex), getRightChildIndex(destIndex), newArray, level);
} |
7a57d63d-5bfe-4733-970c-ee392a5525fe | 1 | public final int getListeningPort() {
return myServerSocket == null ? -1 : myServerSocket.getLocalPort();
} |
28a49a46-3e2a-4678-a1b7-d4f94a44085c | 7 | @Override
public boolean activate() {
return (!Bank.isOpen()
&& (
!Inventory.contains(Settings.bar.getFirstId())
|| !Inventory.isFull()
)
&& (
Constants.FALADOR_BANK_AREA.contains(Players.getLocal())
|| Constants.EDGEVILLE_BANK_AREA.contains(Players.getLocal())
|| Constants.AL_KHARID_BANK_AREA.contains(Players.getLocal())
|| Constants.NEITIZNOT_BANK_AREA.contains(Players.getLocal())
)
&& !Widgets.get(13, 0).isOnScreen()
);
} |
c7eb22a8-5ea3-4cc6-9faf-878acea0a6b5 | 9 | public String largestNumber(int[] nums) {
if (nums.length <= 0) {
return "";
}
if (nums.length == 1) {
return nums[0] + "";
}
List<Num> lres = new LinkedList();
List l = getNums(nums);
bucketSort(l, -1, lres);
StringBuffer res = new StringBuffer();
StringBuffer res2 = null;
if(log)
res2=new StringBuffer();
int zeroidx = 0;
for(int i=zeroidx;i<lres.size();i++){
if(i==zeroidx && lres.get(i).val ==0 ){
zeroidx++;
continue;
}
res.append(lres.get(i).val);
if (log)
res2.append(lres.get(i).val+" ");
}
if(res.length()==0){
res.append("0");
}
if(log)
System.out.println(res2);
return res.toString();
} |
55177a1e-3dc8-4989-9284-5b8ed7556ba5 | 0 | private EventListJsonConverter() {
} |
e363c445-f3ee-4ab7-aed5-18127d3e511a | 6 | private static int[] exclusion(int[] itemIds1, int[] itemIds2) {
int[] exclusion = new int[itemIds1.length < itemIds2.length ? itemIds2.length : itemIds1.length];
int index1 = 0, index2 = 0, indexResult = 0;
while (index1 < itemIds1.length && index2 < itemIds2.length) {
if (itemIds1[index1] < itemIds2[index2]) {
index1++;
} else if (itemIds1[index1] > itemIds2[index2]) {
exclusion[indexResult++] = itemIds2[index2++];
} else {
index1++;
index2++;
}
}
while (index2 < itemIds2.length) {
exclusion[indexResult++] = itemIds2[index2++];
}
int[] result = new int[indexResult];
System.arraycopy(exclusion, 0, result, 0, indexResult);
return result;
} |
41db738d-5c3a-4bec-89cd-dbb5c050b3e9 | 7 | static Value determineTypedValue(final Token<?> valueToken, final String variableName) {
Validate.notNull(valueToken);
switch (valueToken.getType()) { // NOPMD
case NULL:
return Value.getNil();
case BOOLEAN:
if (((Token<Boolean>) valueToken).getValue()) {
return Value.getTrue();
} else {
return Value.getFalse();
}
case FLOAT:
return Value.valueOf(((Token<Float>) valueToken).getValue());
case INTEGER:
return Value.valueOf(((Token<Integer>) valueToken).getValue());
case STRING:
return Value.valueOf(((Token<String>) valueToken).getValue());
default:
throw new SyntaxException(String.format("Bad value '%s' assigned to varibale '%s'!",
valueToken.getValue(), variableName));
}
} |
e634adff-6fe2-413d-826a-9233340cec94 | 7 | @Override
public JsonElement serialize(Criteria criteria, Type type, JsonSerializationContext jsc) {
JsonObject json = new JsonObject();
json.addProperty("field", criteria.getField().ordinal()+1 ); // increase by 1
try {
String operator = criteria.getOperator().toString();
if ( operator.equals(Operators.StartWith.toString()) )
operator = "START%20WITH"; // add a space
else if ( operator.equals(Operators.Equals.toString()) )
operator = URLEncoder.encode("=", "UTF-8");
else if ( operator.equals(Operators.GreaterThan.toString()) )
operator = URLEncoder.encode(">", "UTF-8");
else if ( operator.equals(Operators.GreaterThanEqual.toString()) )
operator = URLEncoder.encode(">=", "UTF-8");
else if ( operator.equals(Operators.LessThan.toString()) )
operator = URLEncoder.encode("<", "UTF-8");
else if ( operator.equals(Operators.LessThanEqual.toString()) )
operator = URLEncoder.encode("<=", "UTF-8");
json.addProperty("operator", operator);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(CriteriaSerializer.class.getName()).log(Level.SEVERE, "Wrong encoding scheme!", ex);
}
json.addProperty("value", criteria.getValue() );
return json;
} |
c2ac8c64-392b-4acd-ae4b-87b654b1019c | 2 | private void acao132() throws SemanticError {
if (pilhaMetodosAtuais.peek().getTipo() == null)
throw new SemanticError(
"\"Retorne\" só pode ser utilizado em métodos com tipo");
if (!Tipo.isCompativel(pilhaMetodosAtuais.peek().getTipo(), tipoExpressao))
throw new SemanticError(
"Tipo da expressão diferente do tipo do método");
retornoDeclarado = true;
// Gerar código
} |
829a1311-d838-4703-8791-018451a76140 | 2 | public void toogleMaximized() {
final Screen screen = Screen.getScreensForRectangle(stage.getX(),
stage.getY(), 1, 1).get(0);
if (maximized) {
maximized = false;
if (backupWindowBounds != null) {
stage.setX(backupWindowBounds.getMinX());
stage.setY(backupWindowBounds.getMinY());
stage.setWidth(backupWindowBounds.getWidth());
stage.setHeight(backupWindowBounds.getHeight());
}
} else {
maximized = true;
backupWindowBounds = new Rectangle2D(stage.getX(), stage.getY(),
stage.getWidth(), stage.getHeight());
stage.setX(screen.getVisualBounds().getMinX());
stage.setY(screen.getVisualBounds().getMinY());
stage.setWidth(screen.getVisualBounds().getWidth());
stage.setHeight(screen.getVisualBounds().getHeight());
}
} |
dc3fb62b-2486-4891-9677-8531a0fd8018 | 5 | @Override
public void update(GameContainer gc, int i) throws SlickException
{
if (gc.getInput().isKeyDown(Keyboard.KEY_ESCAPE))
{
gc.exit();
Sound.kill();
System.exit(0);
}
if(gc.getInput().isKeyPressed(Keyboard.KEY_W))
{
cursor.moveUp(1);
}
if(gc.getInput().isKeyPressed(Keyboard.KEY_A))
{
cursor.moveLeft(1);
}
if(gc.getInput().isKeyPressed(Keyboard.KEY_S))
{
cursor.moveDown(1);
}
if(gc.getInput().isKeyPressed(Keyboard.KEY_D))
{
cursor.moveRight(1);
}
} |
631965c1-555f-4e86-9b64-a2dbfffd3723 | 5 | public boolean equals(Inventory other){
if(other == null){
return false;
}
else if(this.getClass() != other.getClass()){
return false;
}
else{
if(this.getSize() != other.getSize()){
return false;
}
for(int counter = 0; counter < this.getSize(); counter++){
if(this.getList().get(counter).getName().equals(other.getList().get(counter).getName())){
continue;
}
else{
return false;
}
}
}
return true;
} |
0161db11-3f93-4593-89c7-9d78259ecb15 | 3 | private void breakUpText(Element e, String s) {
String[] parts = s.split(LINEBREAK);
for (int i = 0; i < parts.length; i++) {
String t = parts[i].replaceAll("\\ +", " ").trim();
t = replaceReservedCharMarkers(t); // replace markers
if (!t.isEmpty())
e.appendChild(e.getOwnerDocument().createTextNode(t));
if (i < parts.length - 1) {
e.appendChild(e.getOwnerDocument().createElement("br"));
e.appendChild(e.getOwnerDocument().createElement("br"));
}
}
} |
6a50c838-bf1a-4f4e-a09c-0a05add23c9c | 1 | public Object clone() {
try {
SimpleSet other = (SimpleSet) super.clone();
other.elementObjects = (Object[]) elementObjects.clone();
return other;
} catch (CloneNotSupportedException ex) {
throw new jode.AssertError("Clone?");
}
} |
9a49be83-d6bb-4c8d-9bf2-1cf90c3e0e8c | 7 | @Override
public void paintComponent(Graphics g) {
try {
if (cases != null) {
for (int i = 0; i < controler.getLargeurTableau(); i++) {
for (int j = 0; j < controler.getHauteurTableau(); j++) {
final String elt = cases[i][j];
if (elt != null && !elt.isEmpty()) {
final File file = new File("images/" + elt);
if (file.exists()) {
final Image img = ImageIO.read(file);
g.drawImage(img, 34 * j, 34 * i + 20, this);
}
}
}
}
}
} catch (final IOException e) {
e.printStackTrace();
}
} |
8f2d0037-aa26-420c-9908-de9372e90db0 | 9 | public List<List<String>> getImages(String accessToken, String albumName) throws IOException, ServiceException {
if (StringUtil.isEmpty(albumName)) {
return null;
}
PicasawebService picasawebService = new PicasawebService("zigride");
picasawebService.setAuthSubToken(accessToken, null);
URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/default?kind=album");
AlbumEntry albumEntry = null;
UserFeed myUserFeed;
try {
myUserFeed = picasawebService.getFeed(feedUrl, UserFeed.class);
for (AlbumEntry myAlbum : myUserFeed.getAlbumEntries()) {
if (albumName.toLowerCase().equals(myAlbum.getTitle().getPlainText())) {
albumEntry = myAlbum;
}
}
} catch (ServiceException e) {
// TODO Auto-generated catch block
}
if (albumEntry == null) {
return null;
}
feedUrl = new URL(albumEntry.getFeedLink().getHref());
AlbumFeed feed = picasawebService.getFeed(feedUrl, AlbumFeed.class);
List<List<String>> images = new ArrayList<List<String>>();
for (PhotoEntry photoEntry : feed.getPhotoEntries()) {
List<String> image = new ArrayList<String>();
if (photoEntry.getMediaContents().size() > 0) {
image.add(photoEntry.getMediaContents().get(0).getUrl());
List<MediaThumbnail> thumbnails = photoEntry.getMediaThumbnails();
for (MediaThumbnail mediaThumbnail : thumbnails) {
image.add(mediaThumbnail.getUrl());
}
}
images.add(image);
}
if (images.size() == 0) {
return null;
}
return images;
} |
5b12b6aa-2b14-425f-a230-1c35db16723b | 0 | public String getName() {
return name;
} |
a7df3a8f-cdb6-4671-a52c-815cb6fbc4a3 | 1 | public int hashCode() {
return type == null ? 0 : type.hashCode();
} |
e9cd7a25-258d-407a-83b7-965a07dbec11 | 7 | public static Set<Class> listAnnotatedClasses(Class<? extends Annotation> annotation) {
Set<Class> classes = new HashSet<Class>();
try {
Enumeration<URL> e = ClassLoader.getSystemClassLoader().getResources("");
while (e.hasMoreElements()) {
URL url = e.nextElement();
for (String child : Classes.getChildren(url)) {
if (child.endsWith(".class")) {
String className = child.substring(0, child.length() - 6).replace("/", ".");
Class<?> clazz = Class.forName(className);
if (clazz.getAnnotation(annotation) != null) {
classes.add(Class.forName(clazz.getName()));
}
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return classes;
} |
9fe26c5b-5869-4007-af95-c91b2ae94c94 | 3 | public String getHealthText() {
double health = getHealth();
if (health > 0.75) {
return "excellently";
} else if (health > 0.50) {
return "well";
} else if (health > 0.25) {
return "decently";
} else {
return "poorly";
}
} |
03eb6b46-5b6c-4407-9603-7f56c252f32b | 7 | public static void massApplySimpleSprite(Environment envi){
synchronized(envi.lock_critter){
Iterator<Critter> iter = envi.getCritters().listIterator();
while(iter.hasNext()){
Critter crit = iter.next();
try {
crit.image = ImageIO.read(new FileInputStream("C:\\Users\\Daniel\\EclipseWorkspace\\Evo\\sprites\\Omnicrit.png"));
for(int i = 0; i < crit.image.getWidth(); i++){
for(int j = 0; j < crit.image.getHeight(); j++){
if(crit.image.getRGB(i, j) != Color.WHITE.getRGB()){
if(crit.food == 1){
crit.image.setRGB(i, j, Color.RED.getRGB());
}
else{
crit.image.setRGB(i, j, Color.GREEN.getRGB());
}
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} |
b142d7ab-751e-40eb-b7fa-fa3b25402dd1 | 6 | public boolean getBoolean(int index) throws JSONException {
Object object = get(index);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
} |
7485826a-635f-4d55-a813-4571f7661cb1 | 7 | public boolean isEligibleNode(DefaultMutableTreeNode node){
/*Eligible if:
- Is leaf and
- Is not repository/my apps (this covers the case when we have no apps) and
- Is not repository/my apps child (this cover second level hierarchy when no apps)
- Is not "by community" child (this covers third level - only necessary in communities)
*/
return node!=null && node.isLeaf() &&
!node.toString().contentEquals(this.model.getRepository_root_name()) &&
!node.toString().contentEquals(this.model.getMyApplications_root_name()) &&
!node.getParent().toString().contentEquals(this.model.getRepository_root_name()) &&
!node.getParent().toString().contentEquals(this.model.getMyApplications_root_name())&&
!node.getParent().toString().contentEquals(this.model.getCommunitiesRepositoryRoot())&&
!node.getParent().toString().contentEquals(this.model.getCommunitiesMyApplicationsRoot());
} |
23e2de6a-688f-42aa-a925-f4c3ce4d92e0 | 4 | public List<String> getCategories() {
if (categories == null) {
ArrayList<String> list = new ArrayList<>();
Iterator it = this.iterator();
while (it.hasNext()) {
Term term = (Term)it.next();
if (term.getCategory() != null &&
!list.contains(term.getCategory())) {
list.add(term.getCategory());
}
}
categories = list;
}
return categories;
} |
ba882732-bb40-4b18-ae14-e7dbe64f3ad9 | 1 | public RandomPermutation(int nums)
{
repeat = MAX_REPEATS;
random = new Random();
for (int i = 0; i != nums; ++i)
p[i] = i;
} |
79a07720-f16e-4647-b7d3-b0f3baa4d78d | 9 | @Override
public boolean pickAndExecuteAnAction() {
// If a new piece of glass has been received, load the workstation and
// process the glass
if (!glassToProcess.isEmpty()) {
MyGlass tempGlass = null;
synchronized (glassToProcess) {
for (MyGlass g : glassToProcess) {
if (g.status == GlassStatus.RECEIVED) {
tempGlass = g;
break;
}
}
}
if (tempGlass != null) {
loadGlass(tempGlass);
if (tempGlass.isBroken) {
removeBrokenGlass(tempGlass);
} else {
processGlass(tempGlass);
}
return true;
}
}
// If a piece of glass has been processed and the popup is ready for
// release, release the glass back to the popup
if (!glassToProcess.isEmpty()) {
MyGlass tempGlass = null;
synchronized (glassToProcess) {
for (MyGlass g : glassToProcess) {
if (g.status == GlassStatus.WAITING_FOR_RELEASE) {
tempGlass = g;
break;
}
}
}
if (tempGlass != null) {
releaseGlassToPopup(tempGlass);
return true;
}
}
// No scheduler rules match
return false;
} |
5ce2a5b6-0b6d-47ad-8899-e33071f710d2 | 8 | @Override
public Object getValueAt(int rowIndex, int columnIndex) {
String reply = "";
Item item = items.get(rowIndex);
switch (columnIndex) {
case 0:
reply = item.getId();
break;
case 1:
reply = item.getName();
break;
case 2:
reply = Integer.toString(item.getOfferAvailability());
break;
case 3:
reply = Integer.toString(item.getSaleAvailability());
break;
case 4:
reply = toString(item.getMaxOfferUnitPrice());
break;
case 5:
reply = toString(item.getMinSaleUnitPrice());
break;
case 6:
reply = String.format("%4.2fC", item.getMargin());
break;
case 7:
reply = "http://www.gw2spidy.com/item/" + item.getId();
break;
}
return reply;
} |
8ddfd762-bb59-47da-92b2-2ab93768b82b | 4 | public String identifierUtilisateurs() {
// on récupère les données du formulaire
String loginForm = user.getUserLogin();
if (loginForm != null && !loginForm.isEmpty()) {
String passwordForm = user.getUserPassword();
// on interroge le model
User u = ((UserDAOHibernate) userDAO).findUserByLogin(loginForm);
//si le user n'est pas null on continue
if (u != null) {
boolean identificationUser = ((UserDAOHibernate) userDAO).checkPassword(u, passwordForm);
// test métier si l'identification est ok
if (identificationUser) {
//recupération des infos du user
this.user = ((UserDAOHibernate) userDAO).getUser();
//on log le user
logUser(this.user);
return SUCCESS;
}
addActionError("Le mot de passe ne correspond pas");
return INPUT;
}
addActionError("L'utilisateur n'existe pas");
return INPUT;
}
addActionError("Vous devez saisir un nom d'utilisateur");
return INPUT;
} |
9138e462-f102-4667-8507-f59d0988e674 | 1 | @Override
public void execute() {
this.from.removePiece(this.piece);
if (this.to.hasPiece()) {
this.capturedPiece = this.to.getPiece();
this.to.removePiece(this.capturedPiece);
}
this.to.addPiece(this.promotionedPiece);
this.piece.increaseMoveCount();
} |
48dfc7e0-b4a8-4157-b4b0-4584a3fa3cb1 | 1 | public static String reverse(String code) {
char[] codeline = code.toCharArray();
String reversed = "";
for(int i = codeline.length - 1; i >= 0; i--) {
reversed += codeline[i];
}
return reversed;
} |
b210cf69-e8ae-49ab-bb99-ebe714b060c2 | 2 | public CheckboxMenuItem getAutoSizeCheckBox() {
if (autoSizeCheckBox == null) {
autoSizeCheckBox = new CheckboxMenuItem("Set auto size");
autoSizeCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
int autoSizeCheckBoxId = e.getStateChange();
if (autoSizeCheckBoxId == ItemEvent.SELECTED) {
trayIcon.setImageAutoSize(true);
} else {
trayIcon.setImageAutoSize(false);
}
}
});
autoSizeCheckBox.setState(true);
}
return autoSizeCheckBox;
} |
fb466650-b7f3-4022-8b52-dc0a40aba9a1 | 0 | public Author(String fName, String lName, Newspaper newspaper) {
this.firstName = fName;
this.lastName = lName;
this.newspaper = newspaper;
} |
256859e7-c88a-4816-994f-6fcc281504df | 2 | public synchronized void update(float increment){
currentTime += increment;
if(currentTime > totalDuration){
wrapAnimation();
}
while(currentTime > frameEndTimes[currentFrameIndex]){
currentFrameIndex++;
}
} |
65342e3d-3a2e-446b-8553-9520dc082e93 | 1 | @SuppressWarnings("unchecked")
public void addQustionToDB() {
String questionStr = getConcatedString((ArrayList<String>) question);
String answerStr = (String) answer;
// add to database
try {
String statement = new String("INSERT INTO " + DBTable
+ " (quizid, position, question, answer, score) VALUES (?, ?, ?, ?, ?)");
PreparedStatement stmt = DBConnection.con.prepareStatement(statement, new String[] {"questionid"});
stmt.setInt(1, quizID);
stmt.setInt(2, position);
stmt.setString(3, questionStr);
stmt.setString(4, answerStr);
stmt.setDouble(5, score);
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
questionID = rs.getInt("GENERATED_KEY");
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
} |
abbfc645-37bc-47ff-ba2b-8ace67d45ae1 | 3 | public CompanyEmployeeRelationship() {
super(null);
relationshipData = new String[2];
relationshiptxt = "fieldPlacement.txt";
model = new RelationshipTableModel();
fieldTable = new JTable(model);
fieldTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
sorter = new TableRowSorter<RelationshipTableModel>(model);
fieldTable.setRowSorter(sorter);
fieldTable.setFillsViewportHeight(true);
fieldTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
chooseFilter = new JComboBox(filterLabels);
filterText = new JTextField();
//Whenever filterText changes, invoke newFilter.
filterText.getDocument().addDocumentListener(
new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
System.out.println("Works");
newFilter();
}
public void insertUpdate(DocumentEvent e) {
System.out.println("Works2");
newFilter();
}
public void removeUpdate(DocumentEvent e) {
System.out.println("Works3");
newFilter();
}
});
// Initializes the JLabels and declares the foreground color as allColor
employeeLabel = new JLabel("Enter the Employee's ID : ");
employeeLabel.setForeground(allColor);
employeeLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
employerLabel = new JLabel("Enter the Company's ID : ");
employerLabel.setForeground(allColor);
employerLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
employeeName = new JLabel("");
employeeName.setForeground(allColor);
employeeName.setFont(new Font("Sans Serif",Font.PLAIN, fontSize));
employerName = new JLabel("");
employerName.setForeground(allColor);
employerName.setFont(new Font("Sans Serif",Font.PLAIN, fontSize));
// Looks for images in the database and uses them
try {
logo = ImageIO.read(new File("MMT_Logo.png"));
} catch (IOException e) {
e.printStackTrace();
}
try{
background = ImageIO.read(new File("DAPP_Background2.jpg"));
}catch(IOException e) {
e.printStackTrace();
}
// Declares the text fields
employeeField = new JTextField();
employeeField.getDocument().addDocumentListener(
new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
checkEmployeeID();
}
public void insertUpdate(DocumentEvent e) {
checkEmployeeID();
}
public void removeUpdate(DocumentEvent e) {
checkEmployeeID();
}
});
employerField = new JTextField();
employerField.getDocument().addDocumentListener(
new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
checkEmployerID();
}
public void insertUpdate(DocumentEvent e) {
checkEmployerID();
}
public void removeUpdate(DocumentEvent e) {
checkEmployerID();
}
});
// JButtons to employ (place in fields) or to cancel (restarts form)
employ = new JButton("Employ");
employ.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(checkTextFields()) {
getText();
clearTextFields();
enterToFile();
model.changeData();
model.fireTableDataChanged();
JOptionPane.showMessageDialog(null, "Your field placement has been submitted");
}
}
});
cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
clearTextFields();
}
});
// Adding all the fields and labels to the panel
this.add(employeeLabel);
this.add(employeeField);
this.add(employeeName);
this.add(employerLabel);
this.add(employerField);
this.add(employerName);
this.add(cancel);
this.add(employ);
employeeLabel.setBounds(50, 150, 200, 20);
employeeField.setBounds(260, 150, 250, 20);
employeeName.setBounds(260, 100, 200, 40);
TitledBorder employeeBorder = new TitledBorder("Employee Name");
employeeBorder.setTitleColor(allColor);
employeeName.setBorder(employeeBorder);
employerName.setBounds(260, 240, 200, 40);
TitledBorder employerBorder = new TitledBorder("Employer Name");
employerBorder.setTitleColor(allColor);
employerName.setBorder(employerBorder);
employerLabel.setBounds(50, 300, 200, 20);
employerField.setBounds(260, 300, 250, 20);
cancel.setBounds(50, 400, 70, 20);
employ.setBounds(150, 400, 70, 20);
this.add(chooseFilter);
chooseFilter.setBounds(tableX, 590, 150, 20);
this.add(filterText);
filterText.setBounds(tableX + 170, 590, 300, 20);
tablePane = new JScrollPane(fieldTable);
this.add(tablePane);
tablePane.setBounds(tableX, tableY, 500, 500);
} |
c543f934-3f52-4d91-816c-77fd7d5076e6 | 2 | private void createUser() {
panelUserAdd = new JPanel();
panelUserAdd.setBounds(10, 32, 614, 313);
getContentPane().add(panelUserAdd);
panelUserAdd.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(10, 11, 77, 14);
panelUserAdd.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 77, 14);
panelUserAdd.add(lblPassword);
JLabel lblPhone = new JLabel("Phone:");
lblPhone.setBounds(10, 61, 77, 14);
panelUserAdd.add(lblPhone);
rdbtnAdminCreate = new JRadioButton("Admin");
buttonGroup.add(rdbtnAdminCreate);
rdbtnAdminCreate.setBounds(10, 93, 109, 23);
rdbtnAdminCreate.setSelected(false);
panelUserAdd.add(rdbtnAdminCreate);
rdbtnEmployeeCreate = new JRadioButton("Employee");
buttonGroup.add(rdbtnEmployeeCreate);
rdbtnEmployeeCreate.setBounds(146, 93, 109, 23);
rdbtnEmployeeCreate.setSelected(true);
panelUserAdd.add(rdbtnEmployeeCreate);
userNameCreateField = new JTextField();
userNameCreateField.setBounds(136, 8, 86, 20);
panelUserAdd.add(userNameCreateField);
userNameCreateField.setColumns(10);
passwordCreateField = new JTextField();
passwordCreateField.setBounds(136, 33, 86, 20);
panelUserAdd.add(passwordCreateField);
passwordCreateField.setColumns(10);
phoneCreateField = new JTextField();
phoneCreateField.setBounds(136, 58, 86, 20);
panelUserAdd.add(phoneCreateField);
phoneCreateField.setColumns(10);
JButton btnAddUser = new JButton("Add User");
btnAddUser.setBounds(10, 140, 89, 23);
panelUserAdd.add(btnAddUser);
btnAddUser.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
AdminService admService = new AdminService();
int type = 1;
if (rdbtnAdminCreate.isSelected()) {
type = 0;
} else if (rdbtnEmployeeCreate.isSelected()) {
type = 1;
}
admService.createUser(userNameCreateField.getText(),
passwordCreateField.getText(),
phoneCreateField.getText(), type);
userNameCreateField.setText("");
passwordCreateField.setText("");
phoneCreateField.setText("");
rdbtnEmployeeCreate.setSelected(true);
rdbtnAdminCreate.setSelected(true);
}
});
} |
daad341f-be31-43ab-9605-a90bfc73077a | 1 | private boolean saveWorkspace(File saveFile){
WorkspaceData saveData = new WorkspaceData(Main.getStructureBase(),Main.getFileBase(),listDataOut);
try{
FileOutputStream outputStream = new FileOutputStream(saveFile);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(saveData);
objectOutputStream.close();
return true;
}catch(IOException ex){
return false;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.