method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
92099848-8284-4afd-b1dd-c1574a393127 | 3 | @Override
public boolean equals(Object o){
if(o == null){
return false;
} else if (o.getClass() != this.getClass()){
return false;
} else if(this.word.equals(((Node)o).getWord())){
return true;
}
return false;
} |
b226f27f-11af-4364-a587-6b9bab936486 | 1 | public boolean isIDexist(int id)
{
String select="select count(*)from citedlist where paperid="+id;
int count=0;
count=sqLconnection.Count(select);
if(count!=0)
return true;
else
return false;
} |
e7a79300-5f43-4546-a432-44f7eae3e1db | 1 | public static void main(String[] args)
{
final Preferences prefs = Preferences.userRoot().node(Prefs.class.getName());
try
{
prefs.clear();
} catch (Exception e)
{
}
} |
9ba7ebd2-54a0-4d36-aa35-50e11fdacabd | 8 | public void actionPerformed(ActionEvent ae) {
if( ae.getSource() == this.searchQuery || ae.getSource() == this.search ) {
//displays results matching the query typed into the search box
ArrayList<Item> results = this.library.searchByTag( this.searchQuery.getText() );
this.currentListModel = new DefaultListModel<String>();
for( Item i : results ) {
this.currentListModel.addElement( i.getName() );
}
this.itemsDisplaying.setModel( this.currentListModel );
}
else if( ae.getSource() == this.cancel ) {
//clears out all searches, restores default list model
this.searchQuery.setText("");
this.detailedItemDisplay.setText("");
this.itemsDisplaying.setModel( this.defaultListModel );
this.currentListModel = this.defaultListModel;
}
else if( ae.getSource() == this.deleteSelectedItems ) {
int[] selected = this.itemsDisplaying.getSelectedIndices();
if( selected.length == 0 ) {
JOptionPane.showMessageDialog( this, "No items have been selected.", "No items selected.", JOptionPane.ERROR_MESSAGE );
}
else {
int confirmation = JOptionPane.showConfirmDialog( this, "Are you sure you wish to delete" + selected.length + " item(s) from the library?", "Confirm deletion.", JOptionPane.YES_NO_OPTION );
if( confirmation == JOptionPane.YES_OPTION ) {
for( int i : selected ) {
this.library.deleteItem( this.titlesToItems.get( this.currentListModel.get( i ) ) );
}
this.library.save();
this.library.load();
reloadLibraryEntries();
this.itemsDisplaying.setModel( this.defaultListModel );
}
}
}
} |
9205ef8b-5ed0-42e4-8220-8190613dde75 | 6 | public ListNode deleteDuplicates(ListNode head) {
if (head == null)
return null;
ListNode p = head;
ListNode t = new ListNode(0);
t.next = head;
head = t;
p = p.next;
while (p != null) {
if (t.next.val == p.val) {
p = p.next;
}
else {
if (t.next.next == p) {
t = t.next;
p = p.next;
}
else {
t.next = p;
p = p.next;
}
}
}
if (t.next.next == null)
return head.next;
if (t.next.val == t.next.next.val)
t.next = null;
return head.next;
} |
f523bc77-6d79-4939-a4e4-381fe377ee1b | 8 | static void setup_connection(FM_CH CH) {
IntSubArray carrier = new IntSubArray(out_ch, CH.PAN); /* NONE,LEFT,RIGHT or CENTER */
switch (CH.ALGO) {
case 0:
/* PG---S1---S2---S3---S4---OUT */
CH.connect1 = new IntSubArray(pg_in2);
CH.connect2 = new IntSubArray(pg_in3);
CH.connect3 = new IntSubArray(pg_in4);
break;
case 1:
/* PG---S1-+-S3---S4---OUT */
/* PG---S2-+ */
CH.connect1 = new IntSubArray(pg_in3);
CH.connect2 = new IntSubArray(pg_in3);
CH.connect3 = new IntSubArray(pg_in4);
break;
case 2:
/* PG---S1------+-S4---OUT */
/* PG---S2---S3-+ */
CH.connect1 = new IntSubArray(pg_in4);
CH.connect2 = new IntSubArray(pg_in3);
CH.connect3 = new IntSubArray(pg_in4);
break;
case 3:
/* PG---S1---S2-+-S4---OUT */
/* PG---S3------+ */
CH.connect1 = new IntSubArray(pg_in2);
CH.connect2 = new IntSubArray(pg_in4);
CH.connect3 = new IntSubArray(pg_in4);
break;
case 4:
/* PG---S1---S2-+--OUT */
/* PG---S3---S4-+ */
CH.connect1 = new IntSubArray(pg_in2);
CH.connect2 = carrier;
CH.connect3 = new IntSubArray(pg_in4);
break;
case 5:
/* +-S2-+ */
/* PG---S1-+-S3-+-OUT */
/* +-S4-+ */
CH.connect1 = null; /* special case */
CH.connect2 = carrier;
CH.connect3 = carrier;
break;
case 6:
/* PG---S1---S2-+ */
/* PG--------S3-+-OUT */
/* PG--------S4-+ */
CH.connect1 = new IntSubArray(pg_in2);
CH.connect2 = carrier;
CH.connect3 = carrier;
break;
case 7:
/* PG---S1-+ */
/* PG---S2-+-OUT */
/* PG---S3-+ */
/* PG---S4-+ */
CH.connect1 = carrier;
CH.connect2 = carrier;
CH.connect3 = carrier;
break;
}
CH.connect4 = carrier;
} |
afbe45e0-c913-4ae5-bc21-2b715d23fb04 | 3 | public boolean isInside(int mx, int my) {
return (mx > x && mx < x + width) && (my > y && my < y + height);
} |
854dc862-d278-414c-8d07-43015bde8ace | 8 | public Installation[] selectByActivity ( int activityId ) {
Connection con = null;
PreparedStatement statement = null;
ResultSet rs = null;
List<Installation> installations = new ArrayList<Installation>();
try {
con = ConnectionManager.getConnection();
String searchQuery = "SELECT * FROM installations WHERE activityId = ?";
statement = con.prepareStatement(searchQuery);
statement.setInt(1, activityId );
rs = statement.executeQuery();
while (rs.next()) {
Installation installation = new Installation();
installation.setActivityId(activityId);
installation.setWorkerId( rs.getInt("workerId") );
installation.setStatus( rs.getString("status") );
installation.setErrorDescription( rs.getString("errorDescription") );
installations.add(installation);
}
} catch (SQLException e) {
error = e.toString();
e.printStackTrace();
}
finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) { System.err.println(e); }
rs = null;
}
if (statement != null) {
try {
statement.close();
} catch (Exception e) { System.err.println(e); }
statement = null;
}
if (con != null) {
try {
con.close();
} catch (Exception e) { System.err.println(e); }
con = null;
}
}
return installations.toArray( new Installation [installations.size()] );
} |
ef1c6407-5954-4bb5-9195-87dbddde2f8e | 0 | public void setAuthor(Author author) {
this.author = author;
} |
1d28bb74-0639-4a4a-81a2-910186536f19 | 5 | private void isDogWithAllData(Dog dog) {
boolean hasError = false;
if(dog == null){
hasError = true;
}
if (dog.getName() == null || "".equals(dog.getName().trim())){
hasError = true;
}
if(dog.getWeight() <= 0){
hasError = true;
}
if (hasError){
throw new IllegalArgumentException("The dog is missing data. Check the name and weight, they should have value.");
}
} |
d2500db5-8ec8-47c2-ba74-93d3eb4707a0 | 0 | public static int hue(int color) {
double red = (color & RED_MASK) >> 16;
double green = (color & GREEN_MASK) >> 8;
double blue = (color & BLUE_MASK);
return (int)Math.atan2(Math.sqrt(3)*(green - blue), 2*red - green - blue);
} |
0a5d2dad-b707-4848-a741-dcd591d2fa8d | 6 | * @param y The y-coordinate.
* @param column The column the coordinates are currently over.
* @param row The row the coordinates are currently over.
* @return <code>true</code> if the coordinates are over a disclosure triangle.
*/
public boolean overDisclosureControl(int x, int y, Column column, Row row) {
if (showIndent() && column != null && row != null && row.canHaveChildren() && mModel.isFirstColumn(column)) {
StdImage image = getDisclosureControl(row);
int right = getInsets().left + mModel.getIndentWidth(row, column);
return x <= right && x >= right - image.getWidth();
}
return false;
} |
24660359-73f0-4179-9dc2-4bce35385eb5 | 3 | void updateInOut(FlowBlock successor, SuccessorInfo succInfo) {
/*
* First get the gen/kill sets of all jumps to successor and calculate
* the intersection.
*/
SlotSet kills = succInfo.kill;
VariableSet gens = succInfo.gen;
/*
* Merge the locals used in successing block with those written by this
* blocks.
*/
successor.in.merge(gens);
/*
* The ins of the successor that are not killed (i.e. unconditionally
* overwritten) by this block are new ins for this block.
*/
SlotSet newIn = (SlotSet) successor.in.clone();
newIn.removeAll(kills);
/*
* The gen/kill sets must be updated for every jump in the other block
*/
Iterator i = successor.successors.values().iterator();
while (i.hasNext()) {
SuccessorInfo succSuccInfo = (SuccessorInfo) i.next();
succSuccInfo.gen.mergeGenKill(gens, succSuccInfo.kill);
if (successor != this)
succSuccInfo.kill.mergeKill(kills);
}
this.in.addAll(newIn);
this.gen.addAll(successor.gen);
if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_INOUT) != 0) {
GlobalOptions.err.println("UpdateInOut: gens : " + gens);
GlobalOptions.err.println(" kills: " + kills);
GlobalOptions.err.println(" s.in : " + successor.in);
GlobalOptions.err.println(" in : " + in);
}
} |
c6fb7e30-8c3a-45e4-9d4e-bc76876b90bb | 7 | private void scale(final float m, final float[] a, int offa) {
final float norm = (float) (1.0 / m);
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (n >= ConcurrencyUtils.getThreadsBeginN_1D_FFT_2Threads())) {
nthreads = 2;
final int k = n / nthreads;
Future<?>[] futures = new Future[nthreads];
for (int i = 0; i < nthreads; i++) {
final int firstIdx = offa + i * k;
final int lastIdx = (i == (nthreads - 1)) ? offa + n : firstIdx + k;
futures[i] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int i = firstIdx; i < lastIdx; i++) {
a[i] *= norm;
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
int lastIdx = offa + n;
for (int i = offa; i < lastIdx; i++) {
a[i] *= norm;
}
}
} |
4b71df24-e1e9-4ffb-9420-056c711f0ae8 | 2 | public boolean equals(final Object value) {
if (!(value instanceof SourceValue)) {
return false;
}
SourceValue v = (SourceValue) value;
return size == v.size && insns.equals(v.insns);
} |
585041d8-1053-43f3-af17-db476e284e9c | 0 | public Integer getInhusa() {
return inhusa;
} |
709a4487-48a0-46ba-8aa0-78aaeeaa4474 | 8 | private void positionPlayerKickOff(int teamNumber) {
switch (teamNumber) {
case TEAM_1:{
Random generator = new Random();
int kickOffPlayerID = playmode.getTeams()[teamNumber].getUser()[generator.nextInt(playmode.getTeams()[teamNumber].getUser().length)].getID();
GameObject ball = gameObjects.get("BALL");
ball.setSpeed(0.0);
ball.setViewDegree(0);
ball.setLocation(103, 194);
ball.setCurrentAnimationType(animationStand);
GameObject kickOffPlayerArea = new GameObject(235, 56, new Dimension(251,295));
for (Team team : playmode.getTeams()) {
for (User user : team.getUser()) {
GameObject player = gameObjects.get("PLAYER" + user.getID());
player.setSpeed(0.0);
player.setCurrentAnimationType(animationStand);
if(user.getID() == kickOffPlayerID){
player.positionRelativeTo(ball, GameObject.X_OFFSET_LEFT, GameObject.Y_OFFSET_MIDDLE);
}else{
player.positionAnywhereIn(kickOffPlayerArea);
}
}
}
break;
}
case TEAM_2:
Random generator = new Random();
int kickOffPlayerID = playmode.getTeams()[teamNumber].getUser()[generator.nextInt(playmode.getTeams()[teamNumber].getUser().length)].getID();
GameObject ball = gameObjects.get("BALL");
ball.setSpeed(0.0);
ball.setViewDegree(180);
ball.setLocation(603, 194);
ball.setCurrentAnimationType(animationStand);
GameObject kickOffPlayerArea = new GameObject(235, 56, new Dimension(251,295));
for (Team team : playmode.getTeams()) {
for (User user : team.getUser()) {
GameObject player = gameObjects.get("PLAYER" + user.getID());
player.setSpeed(0.0);
player.setCurrentAnimationType(animationStand);
if(user.getID() == kickOffPlayerID){
player.positionRelativeTo(ball, GameObject.X_OFFSET_RIGHT, GameObject.Y_OFFSET_MIDDLE);
}else{
player.positionAnywhereIn(kickOffPlayerArea);
}
}
}
break;
default:
break;
}
} |
01105dd1-195f-42e6-ab51-84433aca90ba | 2 | private void validateContext() {
readyForExchange_ = localRoutingTable_.getLocalhost() != null
&& remoteRoutingTable_ != null
&& remoteRoutingTable_.getLocalhost() != null;
} |
1e880487-6bf2-48ce-abd4-f55be9d42f6b | 2 | public Entry getEntry(int index) {
for (int i = 0; i < entries.length; i++) {
if (entries[i].index == index) {
return entries[i];
}
}
return null;
} |
09b17289-8e5c-4b4e-bcd0-362597de2bbb | 6 | private void persist(PersistAction persistAction, String successMessage) {
if (selected != null) {
this.setEmbeddableKeys();
try {
if (persistAction != PersistAction.DELETE) {
this.ejbFacade.edit(selected);
} else {
this.ejbFacade.remove(selected);
}
JsfUtil.addSuccessMessage(successMessage);
} catch (EJBException ex) {
String msg = "";
Throwable cause = JsfUtil.getRootCause(ex.getCause());
if (cause != null) {
msg = cause.getLocalizedMessage();
}
if (msg.length() > 0) {
JsfUtil.addErrorMessage(msg);
} else {
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
} |
75e862e5-de95-4b5e-a0db-50a69e06399f | 6 | public void sentencesWithSameWords(String resultFilePath)
throws IOException{
if(text == null) return;
int maxNumberOfWords = 0;
ArrayList<Sentence> result = new ArrayList<Sentence>();
for(int i = 0; i < text.numberOfParagraphs(); i++){
Paragraph currParagraph = text.getParagraph(i);
for(int j = 0; j < currParagraph.numberOfSentences(); j++){
Sentence currSentence = currParagraph.getSentence(j);
int currMaxNumberOfSameWords = currSentence.getMaxNumberOfSameWords();
if(currMaxNumberOfSameWords > maxNumberOfWords){
maxNumberOfWords = currMaxNumberOfSameWords;
result.clear();
result.add(currSentence);
}
else if(currMaxNumberOfSameWords == maxNumberOfWords){
result.add(currSentence);
}
}
}
out = new BufferedWriter(new FileWriter(resultFilePath));
for(Sentence sentence : result){
writeSentence(sentence);
out.newLine();
}
out.flush();
} |
af4375cb-c0a9-48d4-ae2a-43d1ad753c8f | 8 | public String getAccessString() {
StringBuffer sb = new StringBuffer();
if (AccessFlags.isPublic(this.accessFlags))
sb.append("public ");
if (AccessFlags.isPrivate(this.accessFlags))
sb.append("private ");
if (AccessFlags.isProtected(this.accessFlags))
sb.append("protected ");
if (AccessFlags.isAbstract(this.accessFlags))
sb.append("abstract ");
if (AccessFlags.isStatic(this.accessFlags))
sb.append("static ");
if (AccessFlags.isSynchronized(this.accessFlags))
sb.append("synchronized ");
if (AccessFlags.isFinal(this.accessFlags))
sb.append("final ");
if (AccessFlags.isNative(this.accessFlags))
sb.append("native ");
return sb.toString().trim();
} |
a73dd9e3-a261-4a0d-907d-6b04c33e172c | 7 | private void actualizarTabla(){
if (a.getSizeArray() < 15) {
for (int i = 0; i < 15; i++) {
if (i < a.getSizeArray())
tabla.setValueAt(a.getProc(i).getNombre(), i, 0);
else
tabla.setValueAt("", i, 0);
}
for (int i = 0; i < 15; i++) {
if (i < a.getSizeArray())
tabla.setValueAt(a.getProc(i).getRafaga(), i, 1);
else
tabla.setValueAt("", i, 1);
}
}else{
for (int i = 0; i < 15; i++) {
tabla.setValueAt(a.getProc(i).getNombre(), i, 0);
}
for (int i = 0; i < 15; i++) {
tabla.setValueAt(a.getProc(i).getRafaga(), i, 1);
}
}
} |
c7e12207-75f6-4677-a739-4789fd181677 | 1 | public static void listProjectsEmployees(EntityManager entityManager) {
TypedQuery<Project> query = entityManager.createQuery(
"select distinct p from Project p join fetch p.employees",
Project.class);
List<Project> resultList = query.getResultList();
entityManager.close();
for (Project project : resultList) {
System.out.println(project.getName() + " - "
+ project.getEmployees());
}
} |
cb61fd2a-93f8-4546-a040-10ddbdc3c719 | 4 | @Override
public void draw(Graphics2D g) {
if (dead) return;
AffineTransform old = g.getTransform();
if (rotate) {
AffineTransform at = g.getTransform();
at.rotate(angle, pos.x, pos.y);
g.setTransform(at);
}
g.drawImage(image, (int) pos.x, (int) pos.y, Game.w);
g.setTransform(old);
if (canSetOnFire && onFire) Helper.drawImage(Game.getImage("anim/fire.png"), (int) pos.x - 12, (int) pos.y - 12, 24, 24, 32 * frame, 0, 32, 29, g);
} |
1a430bb2-49b8-4f54-905f-ce21c8b790eb | 7 | public boolean remove(Link<Integer> link)
{
Link<Integer> position = this.head;
if (link == null || this.head == null)
{
return false;
}
if (link.equals(this.head))
{
this.head = link.getNext();
if (this.head == null)
{
this.tail = null;
}
return true;
}
while (position != null)
{
if (position.getNext().equals(link))
{
position.setNext(link.getNext());
if (position.getNext() == null)
{
this.tail = position;
}
return true;
}
}
return false;
} |
49b79c35-a0ea-42c1-b39e-92b2665840ca | 0 | public Metadonnee getMetadonnee() {
return metadonnee;
} |
e4578375-42ed-415f-8eaa-6f821dccbd33 | 8 | public boolean batchFinished() throws Exception {
if (getInputFormat() == null)
throw new IllegalStateException("No input instance format defined");
Instances toFilter = getInputFormat();
if (!isFirstBatchDone()) {
// filter out attributes if necessary
Instances toFilterIgnoringAttributes = removeIgnored(toFilter);
// serialized model or build clusterer from scratch?
File file = getSerializedClustererFile();
if (!file.isDirectory()) {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
m_ActualClusterer = (Clusterer) ois.readObject();
Instances header = null;
// let's see whether there's an Instances header stored as well
try {
header = (Instances) ois.readObject();
}
catch (Exception e) {
// ignored
}
ois.close();
// same dataset format?
if ((header != null) && (!header.equalHeaders(toFilterIgnoringAttributes)))
throw new WekaException(
"Training header of clusterer and filter dataset don't match:\n"
+ header.equalHeadersMsg(toFilterIgnoringAttributes));
}
else {
m_ActualClusterer = AbstractClusterer.makeCopy(m_Clusterer);
m_ActualClusterer.buildClusterer(toFilterIgnoringAttributes);
}
// create output dataset with new attribute
Instances filtered = new Instances(toFilter, 0);
FastVector nominal_values = new FastVector(m_ActualClusterer.numberOfClusters());
for (int i = 0; i < m_ActualClusterer.numberOfClusters(); i++) {
nominal_values.addElement("cluster" + (i+1));
}
filtered.insertAttributeAt(new Attribute("cluster", nominal_values),
filtered.numAttributes());
setOutputFormat(filtered);
}
// build new dataset
for (int i=0; i<toFilter.numInstances(); i++) {
convertInstance(toFilter.instance(i));
}
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
} |
8fd125e1-a290-4059-8d5e-bd67ee94c1ed | 1 | private void assertExteriorRing()
{
if (coordinates.isEmpty())
{
throw new RuntimeException("No exterior ring defined");
}
} |
c77f8dc6-9ca9-476c-936d-3dc77edd09d2 | 3 | public static ServiceConditionEnumeration fromString(String v) {
if (v != null) {
for (ServiceConditionEnumeration c : ServiceConditionEnumeration.values()) {
if (v.equalsIgnoreCase(c.toString())) {
return c;
}
}
}
throw new IllegalArgumentException(v);
} |
be3c6330-de58-4c8d-af66-3de0fe0e0cdb | 1 | public JTextField getPassword(){
String pass=passT.getText();
String confirmedPass=confirmPassT.getText();
if(pass.equals(confirmedPass)){
return passT;
}else return null;
} |
15d45b82-c909-4624-a92a-cd780c05bedc | 4 | private void displayBoard(TicTacToeBoard state) {
for (int row = 0; row < TicTacToeBoard.SIZE; row++) {
for (int col = 0; col < TicTacToeBoard.SIZE; col++) {
if (state.getState(row, col) == TicTacToeBoard.X) {
cellLabel[row * TicTacToeBoard.SIZE + col].setText("X");
} else if (state.getState(row, col) == TicTacToeBoard.O) {
cellLabel[row * TicTacToeBoard.SIZE + col].setText("O");
} else {
cellLabel[row * TicTacToeBoard.SIZE + col].setText("");
}
}
}
} |
2bf77048-844e-429e-821a-55389fb112fa | 8 | public String[] someoneElse(boolean place)
{
try{
driver.get(baseUrl + "/content/lto/2013.html");
//global landing page
driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/div/div[3]/ul/li/a")).click();
//Brunei landing page - Order Now button
driver.findElement(By.xpath("/html/body/div[3]/div/div/div/div[3]/div/div[3]/div/div/a")).click();
//buyer select radio button
driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/form/div/div[2]/div/span")).click();
//buyer select continue button
driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/form/div/div[3]/div/div/div/p")).click();
//buyer page info
driver.findElement(By.id("zip_postalLookup")).clear();
driver.findElement(By.id("zip_postalLookup")).sendKeys("BM1326");
driver.findElement(By.id("distributorID")).clear();
driver.findElement(By.id("distributorID")).sendKeys("US8128558");
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys("[email protected]");
//driver.findElement(By.cssSelector("a.selector")).click();
//driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/div/div/form/div/div[2]/div/div[3]/div/div[2]/div/div/div/ul/li[2]")).click();
driver.findElement(By.id("user_phone_2")).clear();
driver.findElement(By.id("user_phone_2")).sendKeys("456");
driver.findElement(By.id("user_phone_3")).clear();
driver.findElement(By.id("user_phone_3")).sendKeys("456");
driver.findElement(By.id("buyerID")).clear();
driver.findElement(By.id("buyerID")).sendKeys("US8128558");
driver.findElement(By.id("buyerPhone_2")).clear();
driver.findElement(By.id("buyerPhone_2")).sendKeys("456");
driver.findElement(By.id("buyerPhone_3")).clear();
driver.findElement(By.id("buyerPhone_3")).sendKeys("4565");
driver.findElement(By.id("nameOfPerson")).clear();
driver.findElement(By.id("nameOfPerson")).sendKeys("Test User");
driver.findElement(By.id("address_address1")).clear();
driver.findElement(By.id("address_address1")).sendKeys("75 West Center Street");
driver.findElement(By.id("address_address2")).clear();
driver.findElement(By.id("address_address2")).sendKeys("Test Address");
try{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
Thread.currentThread().interrupt();
}
/*if (!driver.findElement(By.id("address_city")).getAttribute("value").equalsIgnoreCase("MUARA"))
return "Brunei: Failed: Someone Else \n" + "URL: " + driver.getCurrentUrl() + "\n" + "Error: Zipcode service call failure\n\n";
if (!driver.findElement(By.id("address_region")).getAttribute("value").equalsIgnoreCase("BM"))
return "Brunei: Failed: Someone Else \n" + "URL: " + driver.getCurrentUrl() + "\n" + "Error: Zipcode service call failure\n\n";*/
driver.findElement(By.xpath("/html/body/div[2]/div/div/div[2]/div/div/div/p/a")).click();
//Buyer validation page
driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/div/div/div/div/form/div/div/div/a")).click();
//product page
driver.findElement(By.id("checkout")).click();
if (isElementPresent(By.className("shopError")))
{
results[0] = "Brunei: Failed: Someone Else\n"+ "URL: " + driver.getCurrentUrl() + "\n" + "Error: " + driver.findElement(By.className("shopError")).getText();
return results;
}
//shop app
try{
Thread.sleep(100);
}
catch (InterruptedException ex)
{
Thread.currentThread().interrupt();
}
driver.findElement(By.cssSelector("option[value=\"addPaymentType0\"]")).click();
driver.findElement(By.id("paymentNumber_id")).clear();
driver.findElement(By.id("paymentNumber_id")).sendKeys("4111111111111111");
driver.findElement(By.id("paymentName_id")).clear();
driver.findElement(By.id("paymentName_id")).sendKeys("bob");
driver.findElement(By.id("paymentSecurityNumber")).clear();
driver.findElement(By.id("paymentSecurityNumber")).sendKeys("456");
driver.findElement(By.xpath("/html/body/form/div/div[7]/div/div[5]/div/div/div/div[6]/div[3]/div[2]/button")).click();
try{
Thread.sleep(5000);
}
catch (InterruptedException ex)
{
Thread.currentThread().interrupt();
}
if (place)
{
driver.findElement(By.xpath("/html/body/form/div/div[12]/div/button")).click();
if (isElementPresent(By.className("shopError")))
{
results[0] = "Brunei: Failed: Someone Else After Shop\n"+ "URL: " + driver.getCurrentUrl() + "\n" + "Error: " + driver.findElement(By.className("shopError")).getText();
return results;
}
if (!isElementPresent(By.id("productinformation-complete")))
{
results[0] = "Brunei: Failed: Order was not completed";
return results;
}
results[2] = driver.findElement(By.xpath("/html/body/form/div/div[2]/h2")).getText();
}
results[0] = "Brunei: Passed";
return results;
}
catch (Exception e)
{
results[0] = "Brunei: Someone Else\n"+ "URL: " + driver.getCurrentUrl() + "\n" + "Script Error: " + e;
return results;
}
} |
bd9f8cc2-5fd5-4341-b7a8-48de142d690b | 1 | public boolean fichierMove(File ancien_emplacement, File nouvelle_emplacement) {
if (ancien_emplacement.renameTo(nouvelle_emplacement))
return true;
else
return false;
} |
3cade567-ee12-4e7b-af80-bacbf7071a1e | 8 | public static boolean legalInput(int x1, int x2, int x3, int x4){
if ((x1 >= 0 && x1 <= 7) && (x2 >= 0 && x2 <= 7) && (x3 >= 0 && x3 <= 7) && (x4 >= 0 && x4 <= 7)){
return true;
}
return false;
} |
42476425-2b1b-4a81-893e-af177bf86a13 | 1 | private void action(final String input) {
System.out.println(MSG_INACTION+input);
for (int i = 0;i<input.length();i++) {
printADigit(input.substring(i,i+1));
}
} |
e5b0beaa-54bb-4514-9bd3-8b4d8a8dd945 | 1 | public RangeType(ReferenceType bottomType, ReferenceType topType) {
super(TC_RANGE);
if (bottomType == tNull)
throw new jode.AssertError("bottom is NULL");
this.bottomType = bottomType;
this.topType = topType;
} |
58cf79dd-14d1-4979-b8da-b9146a376d27 | 6 | public EmprestimoComboBox pesquisarTodosCodigoCidadaoEstoque() {
EmprestimoComboBox emprestimoComboBox = new EmprestimoComboBox();
Connection connection = conexao.getConnection();
try {
String valorDoComandoUm = comandos.get("pesquisarTodosCodigoCidadaoEstoque");
PreparedStatement preparedStatement = connection.prepareStatement(valorDoComandoUm);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String valor = resultSet.getString("valor");
Integer codigo = resultSet.getInt("codigo");
String tipo = resultSet.getString("tipo");
switch (tipo) {
case "emprestimo":
Emprestimo emprestimo = new Emprestimo();
emprestimo.setCodigo(codigo);
emprestimoComboBox.getEmprestimos().add(emprestimo);
break;
case "cidadao":
Cidadao cidadao = new Cidadao();
cidadao.setCodigo(codigo);
cidadao.setNomeCompleto(valor);
emprestimoComboBox.getCidadaos().add(cidadao);
break;
default:
Estoque estoque = new Estoque();
estoque.setMaterial(new Material());
estoque.getMaterial().setCodigo(codigo);
estoque.getMaterial().setDadoMaterial(new DadoMaterial());
estoque.getMaterial().getDadoMaterial().setTitulo(valor);
emprestimoComboBox.getEstoques().add(estoque);
break;
}
}
} catch (SQLException ex) {
try {
connection.rollback();
} catch (SQLException ex1) {
}
throw new RuntimeException(ex.getMessage());
} catch (NullPointerException ex) {
throw new RuntimeException(ex.getMessage());
} finally {
conexao.fecharConnection();
}
return emprestimoComboBox;
} |
4d9ca69a-9fcc-4c0d-8cf4-4151002ce523 | 3 | private JSONWriter end(char mode, char c) throws JSONException {
if (this.mode != mode) {
throw new JSONException(mode == 'a'
? "Misplaced endArray."
: "Misplaced endObject.");
}
this.pop(mode);
try {
this.writer.write(c);
} catch (IOException e) {
throw new JSONException(e);
}
this.comma = true;
return this;
} |
6f026829-be42-4545-a07c-e5bfbf94bcc8 | 2 | @Override
public Component getListCellRendererComponent(JList<? extends RiverComponent> list,
RiverComponent value, int index, boolean isSelected, boolean cellHasFocus) {
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
setTextColor (Color.BLUE);
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
setTextColor(Color.BLACK);
}
// setBackground(value.getRiver().getRiverColor(isSelected));
topPanel.setBackground(River.getRiverColor(value.getRiver().getWwTopLevel()));
riverNameLabel.setText(value.getRiver().getRiverName());
wwTopLevelLabel.setText ("\u02AC" + value.getRiver().getWwTopLevel());
tripFromToLabel.setText (" " + value.getRiver().getTripFrom() + " \u25BA " + value.getRiver().getTripTo());
return this;
} |
0a20b766-2f7a-4a76-b4c4-be09ae7715fe | 6 | private void saveFile(HashSet<String> words, String name)
{
File file;
FileWriter writer = null;
file = new File(this.getDataFolder(), name);
if(!file.exists())
{
try {
file.createNewFile();
} catch (IOException e) {
logger.severe("[" + pdfdescription + "] Unable to create login config file!");
logger.severe(e.getMessage());
}
}
try{
writer = new FileWriter(file);
for(String str: words)
{
writer.write(str + "\n");
}
writer.close();
}catch (IOException e){
logger.severe("[" + pdfdescription + "] Unable to create login config file!");
logger.severe(e.getMessage());
} finally {
if (writer != null) try {
writer.close();
} catch (IOException e2) {}
}
} |
21438812-580f-4ede-8831-6b33599d5db6 | 7 | public static boolean verifyNewPatient(NewPatientPage newPatient){
Patient patient = new Patient();
if(InputChecker.name(newPatient.getfName().getText())){
patient.setFirstName(newPatient.getfName().getText());
if(InputChecker.name(newPatient.getfName().getText())){
patient.setLastName(newPatient.getlName().getText());
if(InputChecker.fullName(newPatient.getDoctor().getText())){
patient.setPrimaryDoc(newPatient.getDoctor().getText());
if(InputChecker.phone(newPatient.getPhone().getText())){
patient.setPhone(newPatient.getPhone().getText());
if(newPatient.getAddress().getText()!=null){
patient.setAddress(newPatient.getAddress().getText());
if(newPatient.getDoB().getText()!=null){
if(InputChecker.dob(newPatient.getDoB().getText()))
return true;
else System.out.println("invalid format for Dob");
}else
System.out.println("wrong format for DoB");
}else
System.out.println("wrong format for address");
}else
System.out.println("wrong format for phone");
}else
System.out.println("wrong format for doc name");
}else
System.out.println("wrong format for last name");
}else
System.out.println("wrong format for first name");
return false;
} |
54a43260-25b1-4c96-b857-c82769986b31 | 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(LetterFlashcardFormViewController.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LetterFlashcardFormViewController.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LetterFlashcardFormViewController.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LetterFlashcardFormViewController.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 LetterFlashcardFormViewController().setVisible(true);
}
});
} |
14967f27-3b1b-4470-869c-9b034c4fdd44 | 5 | protected synchronized void storeContent() throws IOException, MediaWiki.MediaWikiException {
final Map<String, String> getParams = paramValuesToMap("action", "query", "format", "xml", "prop", "revisions", "rvprop", "content", "revids", Long.toString(revisionID));
final String url = createApiGetUrl(getParams);
networkLock.lock();
try {
final InputStream in = get(url);
final Document xml = parse(in);
checkError(xml);
final NodeList badrevidsTags = xml.getElementsByTagName("badrevids");
if (badrevidsTags.getLength() > 0)
throw new MediaWiki.MediaWikiException("Revision ID " + revisionID + " is now inexistent");
final NodeList pageTags = xml.getElementsByTagName("page");
if (pageTags.getLength() > 0) {
final Element pageTag = (Element) pageTags.item(0);
if (pageTag.hasAttribute("missing"))
throw new MediaWiki.MediaWikiException("Revision ID " + revisionID + " now belongs to no page");
final NodeList revTags = pageTag.getElementsByTagName("rev");
if (revTags.getLength() > 0) {
final Element revTag = (Element) revTags.item(0);
if (revTag.hasAttribute("texthidden")) {
contentHidden = true;
} else {
content = revTag.getTextContent();
}
contentStored = true;
} else
throw new MediaWiki.ResponseFormatException("expected <rev> tag not found");
} else
throw new MediaWiki.ResponseFormatException("expected <page> tag not found");
} finally {
networkLock.unlock();
}
} |
985af080-2850-46c1-9c40-f6599b4e977f | 3 | private String scanDirectiveName () {
int length = 0;
char ch = peek(length);
boolean zlen = true;
while (ALPHA.indexOf(ch) != -1) {
zlen = false;
length++;
ch = peek(length);
}
if (zlen)
throw new TokenizerException("While scanning for a directive name, expected an alpha or numeric character but found: "
+ ch(ch));
String value = prefixForward(length);
// forward(length);
if (NULL_BL_LINEBR.indexOf(peek()) == -1)
throw new TokenizerException("While scanning for a directive name, expected an alpha or numeric character but found: "
+ ch(ch));
return value;
} |
c9bef217-fd4a-4b24-a3db-d7bf2fdaf440 | 6 | public List getChangedComponents() {
ArrayList components = YUIToolkit.getViewComponents(controller.getView());
Iterator it = components.iterator();
ArrayList result = new ArrayList();
while (it.hasNext()) {
Object comp = it.next();
boolean changes = false;
if (comp instanceof YIModelComponent) {
YIModelComponent modelComp = (YIModelComponent) comp;
if (hasChanges(modelComp)) {
logger.debug("changes in " + modelComp.getYProperty().get(YIComponent.MVC_NAME));
result.add(modelComp);
changes = true;
}
}
if (!changes) {
// investigating extended field...
if (comp instanceof YIExtendedModelComponent) {
YIExtendedModelComponent extComp = (YIExtendedModelComponent) comp;
if (hasChanges(extComp)) {
result.add(extComp);
logger.debug("extended changes in " + extComp.getYProperty().get(YIComponent.MVC_NAME));
}
}
}
}
return result;
} |
c41bceb0-d059-4d0e-a6de-9e76362f9ca4 | 5 | public boolean hasChanged()
{
if ( parent != null && parent.hasChanged() )
return true;
if ( !pos.equals( oldPos ) )
return true;
if ( !rot.equals( oldRot ) )
return true;
if ( !scale.equals( oldScale ) )
return true;
return false;
} |
e9699751-9390-480e-8673-d9f02df84896 | 7 | protected int advQuoted(String s, StringBuffer sb, int i)
{
int j;
int len= s.length();
for (j=i; j<len; j++) {
if (s.charAt(j) == '"' && j+1 < len) {
if (s.charAt(j+1) == '"') {
j++; // skip escape char
} else if (s.charAt(j+1) == fieldSep) { //next delimeter
j++; // skip end quotes
break;
}
} else if (s.charAt(j) == '"' && j+1 == len) { // end quote @ line end
break; //done
}
sb.append(s.charAt(j)); // regular character.
}
return j;
} |
1847bb4e-a830-4065-bbeb-87a156aeff0d | 1 | public NewFactionEditor() {
setTitle("New Faction");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setBounds(100, 100, 300, 150);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
textField = new JTextField();
textField.setBounds(10, 36, 138, 20);
contentPanel.add(textField);
textField.setColumns(10);
JLabel lblFactionName = new JLabel("Faction name:");
lblFactionName.setBounds(10, 11, 68, 14);
contentPanel.add(lblFactionName);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("Save");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
save();
dispose();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
setModalityType(ModalityType.APPLICATION_MODAL);
setVisible(true);
} |
c85ce484-88d5-449e-ba27-00c6647c47c0 | 9 | @Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER)
actionPerformed(new ActionEvent(commandLineButton, 0, ""));
if (e.getKeyCode() == KeyEvent.VK_UP && commandLineHistoryPointer > -1
&& commandLineHistory.size() != 0) {
commandLineField
.setText(commandLineHistory
.get((commandLineHistoryPointer == 0 ? commandLineHistoryPointer
: commandLineHistoryPointer--)));
}
if (e.getKeyCode() == KeyEvent.VK_DOWN
&& commandLineHistoryPointer > -1
&& commandLineHistoryPointer < commandLineHistory.size()) {
commandLineField.setText(commandLineHistory
.get((commandLineHistoryPointer == commandLineHistory
.size() - 1 ? commandLineHistoryPointer
: commandLineHistoryPointer++)));
}
} |
d155e7aa-4a70-4f8c-b929-a58022063dae | 9 | private void calculate() {
if(model == null) return;
Double factor = jTextFieldFactor.getText().equals("") ? 0.0 : Double.parseDouble(jTextFieldFactor.getText());
Double fieldA = jTextFieldA.getText().equals("") ? 0.0 : Double.parseDouble(jTextFieldA.getText());
Double fieldB = jTextFieldB.getText().equals("") ? 0.0 : Double.parseDouble(jTextFieldB.getText());
Double partPrice = jTextFieldPartPrice.getText().equals("") ? 0.0 : Double.parseDouble(jTextFieldPartPrice.getText());
Map<String, Number> parameters = new HashMap<>();
parameters.put("factor", factor);
parameters.put("fieldA", fieldA);
parameters.put("fieldB", fieldB);
parameters.put("partPrice", partPrice);
Integer select = null;
if(jRadioButtonStandart.isSelected()) {
select = 0;
} else if (jRadioButtonStandart2.isSelected()) {
select = 1;
} else if (jRadioButtonPositionA.isSelected()) {
select = 2;
} else if (jRadioButtonGreatPositionA.isSelected()) {
select = 3;
} else {
select = 4;
}
parameters.put("select", select);
model.calculate(parameters);
fillResume();
} |
e74d8de1-316a-460d-9347-c461385ff428 | 4 | public void init() {
BmTestManager bmTestManager = BmTestManager.getInstance();
if (!JMeterUtils.getPropDefault(Constants.BLAZEMETER_TESTPANELGUI_INITIALIZED, false)) {
JMeterUtils.setProperty(Constants.BLAZEMETER_TESTPANELGUI_INITIALIZED, "true");
final IRunModeChangedNotification runModeChanged = new RunModeChangedNotification(runLocal,
runRemote,
cloudPanel,
advancedPropertiesPane);
BmTestManager.getInstance().runModeChangedNotificationListeners.add(runModeChanged);
RunModeListener runModeListener = new RunModeListener(runModeChanged);
runLocal.addActionListener(runModeListener);
runRemote.addActionListener(runModeListener);
signUpButton.setEnabled(bmTestManager.getUserKey() == null || bmTestManager.
getUserKey().
isEmpty());
TestIdComboBoxListener comboBoxListener = new TestIdComboBoxListener(testIdComboBox, cloudPanel);
testIdComboBox.addItemListener(comboBoxListener);
// init userKey
if (bmTestManager.isUserKeyFromProp()) {
String key = bmTestManager.getUserKey();
setUserKey(key);
userKeyTextField.setEnabled(false);
userKeyTextField.setToolTipText("User key found in jmeter.properties file");
signUpButton.setVisible(false);
new Thread(new Runnable() {
@Override
public void run() {
GuiUtils.getUserTests(testIdComboBox, mainPanel, cloudPanel, userKeyTextField.getText());
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
BmTestManager.getInstance().getUsers(true);
}
}).start();
} else {
String userKey = BmTestManager.getInstance().getUserKey();
if (!userKey.isEmpty()) {
signUpButton.setVisible(false);
userKeyTextField.setText(userKey);
GuiUtils.getUserTests(testIdComboBox, mainPanel, cloudPanel, userKeyTextField.getText());
}
UserKeyListener userKeyListener = new UserKeyListener(userKeyTextField,
signUpButton, testIdComboBox, mainPanel, cloudPanel);
userKeyTextField.getDocument().addDocumentListener(userKeyListener);
}
// init userKey
//Here should be all changes of TestInfo processed
ITestInfoNotification testInfoNotification = new TestInfoNotificationTP(runLocal, runRemote,
advancedPropertiesPane.getjMeterPropertyPanel());
bmTestManager.testInfoNotificationListeners.add(testInfoNotification);
//Processing serverStatusChangedNotification
ServerStatusController serverStatusController = ServerStatusController.getServerStatusController();
IServerStatusChangedNotification serverStatusChangedNotification = new ServerStatusChangedNotificationTP(this, cloudPanel,
(PropertyPanel) advancedPropertiesPane.getjMeterPropertyPanel());
serverStatusController.serverStatusChangedNotificationListeners.add(serverStatusChangedNotification);
}
} |
5df2ddd7-0ce7-439b-b5d7-0ebe01350eb2 | 0 | public void setIdCombinacion(int idCombinacion) {
this.idCombinacion = idCombinacion;
} |
7591879d-a3e2-4915-ba7e-b6bc4aaa1acb | 3 | public TreeNode buildTree(int[] inorder, int[] postorder) {
int length = inorder.length;
if(length ==0)
return null;
int pos = indexOf(inorder,postorder[length-1]);
TreeNode node = new TreeNode(postorder[length-1]);
if(pos >0)
node.left = buildTree(Arrays.copyOfRange(inorder,0,pos),
Arrays.copyOfRange(postorder,0,pos));
else
node.left = null;
if(pos < length)
node.right = buildTree(Arrays.copyOfRange(inorder,pos+1,length),
Arrays.copyOfRange(postorder,pos,length-1));
else
node.right = null;
return node;
} |
7acdc0cb-a0e9-43b1-a709-24c2ec58a73c | 1 | public java.security.cert.X509Certificate[] getAcceptedIssuers() {
java.security.cert.X509Certificate[] chain = null;
try {
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
KeyStore tks = KeyStore.getInstance("JKS");
tks.load(this.getClass().getClassLoader().getResourceAsStream("SSL/serverstore.jks"),
SERVER_KEY_STORE_PASSWORD.toCharArray());
tmf.init(tks);
chain = ((X509TrustManager) tmf.getTrustManagers()[0]).getAcceptedIssuers();
} catch (Exception e) {
throw new RuntimeException(e);
}
return chain;
} |
09d9b209-6191-4dad-90d0-6fa32c80757f | 4 | public static void saveLogs() {
if(logsBuffer.isEmpty()) return;
try {
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(logFile, true)));
String logStr = null;
while((logStr = logsBuffer.poll()) != null) {
pw.println(logStr);
}
pw.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
5192bce9-8a27-47a3-ab9d-d71af92ca5e6 | 2 | public static int search_type_by_name(Type_table type_table, String name) {
int num = type_table.type_name.size();
for (int i = 0; i < num; i++) {
if (type_table.type_name.get(i).toString().equals(name)) {
return i;
}
}
return -1;
} |
7a9b4789-72cf-43ba-a8a1-38de594f4377 | 4 | public void keyPressed(KeyEvent e) {
// react to pressing escape
if(e.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {
if(nodeToDrag != null) { // stop dragging a node, and undo
nodeToDrag.getPosition().assign(nodeToDragInitialPosition);
nodeToDragDrawCoordCube = null;
nodeToDrag = null;
parent.redrawGUI(); // node position has changed, full repaint
}
if(nodeToAddEdge != null) {
nodeToAddEdge = null;
targetNodeToAddEdge = null;
repaint(); // no need to redraw whole gui, just repaint layer
}
if(zoomRect != null) {
zoomRect = null;
repaint();
}
}
} |
2f005f38-b66a-47cb-a6af-c1cb9393c707 | 3 | protected void remove( TrieSequencer<S> sequencer )
{
// Decrement size if this node had a value
setValue( null );
int childCount = (children == null ? 0 : children.size());
// When there are no children, remove this node from it's parent.
if (childCount == 0)
{
parent.children.remove( sequencer.hashOf( sequence, start ) );
}
// With one child, become the child!
else if (childCount == 1)
{
TrieNode<S, T> child = children.valueAt( 0 );
children = child.children;
value = child.value;
sequence = child.sequence;
end = child.end;
child.children = null;
child.parent = null;
child.sequence = null;
child.value = null;
registerAsParent();
}
} |
99cf1945-cbd0-462d-8ea6-a06e0e1dcbed | 3 | public GuiLobby(boolean Op) {
host = Op;
compList.add(0, Leave);
if(host){
compList.add(1, Start);
compList.add(2, Kick);
Server.startServer();
}
try {
Rocket.getRocket().network.connect();
} catch (UnknownHostException e) {
System.err.println("Couldn't find host");
} catch (IOException e) {
System.err.println("Couldn't connect to host");
e.printStackTrace();
}
} |
7733fe2b-2664-4ed1-9b4a-597e4289399c | 5 | public LinkDigest putFile(final InputStream rawBytes, final LinkDigest prevChainHead) throws IOException {
if (mUpdates == null) {
IOUtil.silentlyClose(rawBytes);
throw new IllegalStateException("Not updating. Did you forget to call startUpdate?");
}
if (rawBytes == null) {
throw new IllegalArgumentException("rawBytes is null");
}
if (prevChainHead == null) {
throw new IllegalArgumentException("prevChainHead is null");
}
InputStream prevStream = null; // Leaving this null causes a full reinsert.
try {
if (!prevChainHead.isNullDigest() &&
mLinkMap.getChain(prevChainHead, true).size() < MAX_CHAIN_LENGTH) {
// Add to chain the existing chain.
prevStream = getFile(prevChainHead);
}
final HistoryLink link = mCoder.makeDelta(mLinkDataFactory,
prevChainHead,
prevStream,
rawBytes,
false);
mUpdates.append(link.mHash);
mLinkMap.addLink(link);
return link.mHash;
} finally {
IOUtil.silentlyClose(rawBytes);
IOUtil.silentlyClose(prevStream);
}
} |
1254256d-81c3-4cf9-9665-d6e056cd6f8c | 4 | public List<UserMaster>resContactInfo(String twitterID){
query = em.createNamedQuery("UserMaster.findByTwitterID").setParameter("twitterID", twitterID);//UserMasterからUser情報をすべてとってくるクエリを飛ばしている
if(!query.getResultList().isEmpty()){
um=(UserMaster)query.getSingleResult();
query = em.createNamedQuery("Contact.findByUserID").setParameter("receiveUID", um.getUserID());
if(!query.getResultList().isEmpty()){
contact=query.getResultList();
for(Contact cont : contact){
query = em.createNamedQuery("UserMaster.findByUserID").setParameter("userID", cont.getUserID());
if(!query.getResultList().isEmpty()){
um=(UserMaster)query.getSingleResult();
umList.add(um);
}
}
return umList;
}
}
return null;
} |
c20c34bf-822a-47fb-86ad-349dad91e316 | 6 | @Override
public void unsafe_set(int row, int col, double val) {
if( row != 0 && col != 0 )
throw new IllegalArgumentException("Row or column must be zero since this is a vector");
int w = Math.max(row,col);
if( w == 0 ) {
a1 = val;
} else if( w == 1 ) {
a2 = val;
} else if( w == 2 ) {
a3 = val;
} else if( w == 3 ) {
a4 = val;
} else {
throw new IllegalArgumentException("Out of range. "+w);
}
} |
0eda61aa-d4c9-4f66-ad8f-6558686e0d30 | 2 | private Texture loadTexture(String key){
try {
return TextureLoader.getTexture("PNG", new FileInputStream(new File("res/" + key + ".png")));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} |
8b52d225-4f61-49a7-9990-4e1145f38db7 | 5 | public ContentObject getObjectAt(int x, int y, ContentType type) {
if (type instanceof RegionType)
return getRegionAt(x, y);
else if (type instanceof LowLevelTextType) { //Text lines, word, glyph
for (ContentIterator it = this.iterator(RegionType.TextRegion); it.hasNext(); ) {
Region reg = (Region)it.next();
if (reg instanceof LowLevelTextContainer) {
ContentObject obj = getLowLevelTextObjectAt((LowLevelTextContainer)reg, x, y, (LowLevelTextType)type);
if (obj != null)
return obj;
}
}
}
return null;
} |
70d6126a-3eb3-41c0-9e8d-4a10defa6ea5 | 7 | public static void main(String[] args) {
Random randomNumbers = new Random();
int frequency1 = 0;
int frequency2 = 0;
int frequency3 = 0;
int frequency4 = 0;
int frequency5 = 0;
int frequency6 = 0;
int face;
for(int roll = 1; roll <= 6000000; roll++) {
face = 1 + randomNumbers.nextInt(6);
switch (face) {
case 1:
++frequency1;
break;
case 2:
++frequency2;
break;
case 3:
++frequency3;
break;
case 4:
++frequency4;
break;
case 5:
++frequency5;
break;
case 6:
++frequency6;
break;
}
}
System.out.println("Face\tFrequency");
System.out.printf("1\t%d\n2\t%d\n3\t%d\n4\t%d\n5\t%d\n6\t%d\n",
frequency1, frequency2, frequency3, frequency4, frequency5, frequency6);
} |
fe91add6-2fa8-4602-b8e0-a90184e317a1 | 2 | public static void paintRedN8(Image image, int x, int y) {
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
paintRed(image, x + i, y + j);
}
}
} |
c894869d-a20a-4a35-b0bf-33798f775162 | 1 | private boolean isAParameterRequest() throws IOException {
try {
String secondElement = requestArray[1];
String[] splitOnMark = secondElement.split("\\?");
String parameterString = splitOnMark[0];
return parameterString.equals("/parameters");
} catch (ArrayIndexOutOfBoundsException e) {
return false;
}
} |
6ba18620-131b-4dec-95b1-8c884bf0d56d | 7 | public void calculatePosition() {
double sigma1, tsig1, tu1, sa, ca, sa1, ca1, A, B, twosm;
double cu1, su1, uu;
double sigma;
int nIters = 0, nMaxIters = 10;
double c2sm, ssig, csig, dsig = 0.0, lastdsig;
double lambda, C;
double x, y;
double a = ellipsoid.getSemiMajorAxis();
double f = ellipsoid.getFlattening();
double b = a * (1.0 - f);
if (!havePositionA)
throw new IllegalStateException("positionA is not defined");
if (!haveAzimuthA)
throw new IllegalStateException("azimuthA is not defined");
if (!haveDistance)
throw new IllegalStateException("distance is not defined");
tu1 = (1.0 - f) * Math.tan(latitudeA);
cu1 = Math.cos(Math.atan(tu1));
su1 = Math.sin(Math.atan(tu1));
ca1 = Math.cos(azimuthA);
sa1 = Math.sin(azimuthA);
tsig1 = tu1 / ca1;
sa = cu1 * sa1;
ca = 1.0 - sa * sa;
uu = (1.0 - sa * sa) * (a * a - b * b) / (b * b);
A = 1.0 + (uu / 16384.0)
* (4096.0 + uu * (-768.0 + uu * (320.0 - 175.0 * uu)));
B = (uu / 1024.0) * (256.0 + uu * (-128.0 + uu * (74.0 - 47.0 * uu)));
sigma1 = Math.atan(tsig1);
if (tsig1 < 0.0)
sigma1 += Math.PI;
sigma = geodesicDistance / (b * A);
lastdsig = 0.0;
twosm = 2.0 * sigma1 + sigma;
do {
lastdsig = dsig;
c2sm = Math.cos(twosm);
ssig = Math.sin(sigma);
csig = Math.cos(sigma);
dsig = B
* ssig
* (c2sm + (B / 4.0)
* (csig * (-1.0 + 2.0 * c2sm * c2sm) - (B / 6.0)
* c2sm * (-3.0 + 4.0 * ssig * ssig)
* (-3.0 + 4.0 * c2sm * c2sm)));
sigma = geodesicDistance / (b * A) + dsig;
twosm = 2 * sigma1 + sigma;
nIters += 1;
} while ((Math.abs(dsig - lastdsig) > EPSILON) && (nIters <= nMaxIters));
if (nIters > nMaxIters)
throw new ArithmeticException("Exceeded iteration limit");
c2sm = Math.cos(twosm);
ssig = Math.sin(sigma);
csig = Math.cos(sigma);
y = su1 * csig + cu1 * ssig * ca1;
x = su1 * ssig - cu1 * csig * ca1;
x *= x;
x += sa * sa;
x = (1.0 - f) * Math.sqrt(x);
latitudeB = Math.atan2(y, x);
y = ssig * sa1;
x = cu1 * csig - su1 * ssig * ca1;
lambda = Math.atan2(y, x);
C = (f / 16.0) * ca * (4.0 + f * (4.0 - 3.0 * ca));
x = (1.0 - C)
* f
* sa
* (sigma + C * ssig
* (c2sm + (C * csig * (-1.0 + 2.0 * c2sm * c2sm))));
lambda -= x;
longitudeB = longitudeA + lambda;
havePositionB = true;
y = sa;
x = -su1 * ssig + cu1 * csig * ca1;
azimuthB = Math.atan2(-y, -x);
haveAzimuthB = true;
} |
f940c155-764c-4ee5-9d0b-042396539965 | 9 | private void checkAssignedValue(Identifier id, AssignedValue val)
throws SemanticsException {
int val_size = val.oidValue.size();
/* Has the oid value hierarchy?? */
if (val_size < 2) {
Message.error(id, "has no parent defined (need 2 oids at least)");
return;
}
/* Is the first oid value in the numerical range?? */
OidValue parent = (OidValue)val.oidValue.firstElement();
if (3 <= ((NumericValue)parent.getNumber()).getValue()) {
Message.error(id, "parent number " + parent.getNumber() + " not accepted");
}
/* Has the last oid value the same name as assignment when present?? */
/* Otherwise add the name. */
OidValue child = (OidValue)val.oidValue.lastElement();
if (child.hasName()) {
if (! id.equals(child.getName())) {
throw new SemanticsException("different name as the last Oid");
}
} else {
child.setName(id);
}
if (parent.hasName()) {
/* Check if all (except first and last) values have a name. */
for (int i = 0; i < val_size - 2 ; i++) {
parent = (OidValue)val.oidValue.elementAt(i);
child = (OidValue)val.oidValue.elementAt(i+1);
if (child.hasName() && ! child.hasNumber()) {
throw new SemanticsException("name only is not allowed");
}
if (! child.hasName()) {
String newname = new String(parent.getName() + "." + child.getNumber().getValue());
((OidValue)val.oidValue.elementAt(i+1)).setName(newname);
}
}
}
} |
3d13a752-4629-421f-8922-1d3bf6315a5e | 7 | public void renderTile(int xp, int yp, Tile tile) {
xp -= xOffset;
yp -= yOffset;
for (int y = 0; y < tile.getSpriteSize(); y++) {
int ya = y + yp;
for (int x = 0; x < tile.getSpriteSize(); x++) {
int xa = x + xp;
if (xa < -tile.getSpriteSize() || xa >= width || ya < 0 || ya >= height) break;
if (xa < 0) xa = 0;
pixels[xa + ya * width] = tile.sprite.pixels[x + y * tile.getSpriteSize()];
}
}
} |
26f28b41-b7fd-4299-a8ce-a044dd5da4ce | 3 | @SuppressWarnings("deprecation")
@Override
public boolean execute(AdrundaalGods plugin, CommandSender sender, String... args) {
if(args.length < 1)
return false;
final Shrine s = AGManager.getShrineHandler().getShrine(args[0]);
if(s == null)
Messenger.sendMessage(sender, "Shrine not found");
else if(showing.contains(s))
Messenger.sendMessage(sender, "Shrine already shown!");
else {
final Material maxMat = s.getMax().getBlock().getType();
final Material minMat = s.getMin().getBlock().getType();
final byte maxData = s.getMax().getBlock().getData();
final byte minData = s.getMax().getBlock().getData();
s.getMax().getBlock().setType(Material.WOOL);
s.getMin().getBlock().setType(Material.WOOL);
s.getMax().getBlock().setData((byte) 14);
s.getMin().getBlock().setData((byte) 14);
showing.add(s);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
s.getMax().getBlock().setType(maxMat);
s.getMin().getBlock().setType(minMat);
s.getMax().getBlock().setData(maxData);
s.getMin().getBlock().setData(minData);
showing.remove(s);
}
}, 200);
}
return true;
} |
3bcc5fe2-53ea-41bd-a475-d71d7f4f1a1c | 2 | @Override
public void run() {
super.run();
primeStatusIdCache();
for ( ;; ) {
try {
procTweets( searchForTweets() );
sleep( 8000l ); // Wait 8 seconds
} catch ( InterruptedException e ) { }
}
} |
f3363ba0-7be0-4c0b-b6e3-e1423b24444e | 1 | public static byte[] rByte(String packagestr){
byte[] tmp = new byte[packagestr.length()/2];
for (int i=0;i<packagestr.length()/2;i++){
tmp[i]=Byte.parseByte(packagestr.substring(i*2,i*2+2));
//int j = (String.valueOf(("0x"+packagestr.substring(i*2,i*2+2)).;
}
return tmp;
} |
6d45efec-9c8f-42de-a013-4f54f87d68c3 | 0 | @Test
public void test_maxGold(){
assertNotNull(board);
assertEquals(board.maxGold(), 0);
int maxGold = 3;
Pawn pawn = mock(Pawn.class);
when(pawn.getGold()).thenReturn(maxGold);
board.addPawn(pawn);
assertEquals(maxGold, board.maxGold());
} |
a355098b-4f0d-4731-9ea6-ad2fb366fbf8 | 9 | public void update() {
if (listAwardNames.getSelectedValue() == null) {
return;
}
clearErrors();
if (txtAwardName.isMessageDefault() || txtAwardName.getText().isEmpty()) {
Util.setError(lblNameError, "Award name cannot be left blank");
return;
}
for (int i = 0; i < listAwardNames.getModel().getSize(); ++i) {
String otherAwardName = (String) listAwardNames.getModel().getElementAt(i);
if (otherAwardName.equalsIgnoreCase(txtAwardName.getText()) && !txtAwardName.getText().equals(listAwardNames.getSelectedValue().toString())) {
Util.setError(lblNameError, "Award name already exists");
return;
}
}
OtherAward otherAward = LogicOtherAward.findByName(listAwardNames.getSelectedValue().toString());
if (otherAward == null) {
return;
}
if (txtImagePath.isMessageDefault()) {
otherAward.setImgPath("");
} else {
otherAward.setImgPath(txtImagePath.getText());
}
otherAward.setName(txtAwardName.getText());
List<Requirement> requirementList = validateRequirements(otherAward.getId());
if (requirementList == null) return;
Util.processBusy(pnlBadgeConf.getBtnUpdate(), true);
// when editing requirements may need to check who is using them
LogicRequirement.updateList(requirementList, otherAward.getId(), RequirementTypeConst.OTHER.getId());
LogicOtherAward.update(otherAward);
Util.processBusy(pnlBadgeConf.getBtnUpdate(), false);
reloadData();
} |
0ce8ffcb-a550-46fb-98fa-8dac36bcb255 | 3 | private void dfs(Digraph<?> G, Object v) {
this.marked.put(v, true);
this.reachable.add(v);
for (Object temp : G.getAdjacentVertices(v)) {
if (!marked.get(temp)) {
dfs(G, temp);
}
}
} |
b0e059ed-4092-4fcf-b035-89aee1f6ed51 | 9 | @Test
public void testIntWalkManager() throws IOException {
int nvertices = 33333;
IntWalkManager wmgr = new IntWalkManager(nvertices, 40000);
int tot = 0;
for(int j=877; j < 3898; j++) {
wmgr.addWalkBatch(j, (j % 100) + 10);
tot += (j % 100) + 10;
}
wmgr.initializeWalks();
assertEquals(tot, wmgr.getTotalWalks());
// Now get two snapshots
WalkSnapshot snapshot1 = wmgr.grabSnapshot(890, 1300);
for(int j=890; j <= 1300; j++) {
WalkArray vertexwalks = snapshot1.getWalksAtVertex(j, true);
assertEquals((j % 100) + 10, wmgr.getWalkLength(vertexwalks));
for(int w : ((IntWalkArray)vertexwalks).getArray()) {
if (w != -1)
assertEquals(false, wmgr.trackBit(w));
}
}
assertEquals(890, snapshot1.getFirstVertex());
assertEquals(1300, snapshot1.getLastVertex());
// Next snapshot should be empty
WalkSnapshot snapshot2 = wmgr.grabSnapshot(890, 1300);
for(int j=890; j <= 1300; j++) {
WalkArray vertexwalks = snapshot2.getWalksAtVertex(j, true);
assertNull(vertexwalks);
}
WalkSnapshot snapshot3 = wmgr.grabSnapshot(877, 889);
for(int j=877; j <= 889; j++) {
WalkArray vertexwalks = snapshot3.getWalksAtVertex(j, true);
assertEquals((j % 100) + 10, wmgr.getWalkLength(vertexwalks));
}
WalkSnapshot snapshot4 = wmgr.grabSnapshot(877, 889);
for(int j=877; j <= 889; j++) {
WalkArray vertexwalks = snapshot4.getWalksAtVertex(j, true);
assertNull(vertexwalks);
}
WalkSnapshot snapshot5 = wmgr.grabSnapshot(1301, 3898);
for(int j=1301; j < 3898; j++) {
WalkArray vertexwalks = snapshot5.getWalksAtVertex(j, true);
assertEquals((j % 100) + 10, wmgr.getWalkLength(vertexwalks));
}
// wmgr.dumpToFile(snapshot5, "tmp/snapshot5");
WalkSnapshot snapshot6 = wmgr.grabSnapshot(1301, 3898);
for(int j=1301; j < 3898; j++) {
WalkArray vertexwalks = snapshot6.getWalksAtVertex(j, true);
assertNull(vertexwalks);
}
/* Then update some walks */
int w = wmgr.encode(41, false, 0);
wmgr.moveWalk(w, 76, false);
w = wmgr.encode(88, false, 0);
wmgr.moveWalk(w, 22098, true);
WalkSnapshot snapshot7 = wmgr.grabSnapshot(76, 22098);
WalkArray w1 = snapshot7.getWalksAtVertex(76, true);
assertEquals(1, wmgr.getWalkLength(w1));
w = ((IntWalkArray)w1).getArray()[0];
assertEquals(41, wmgr.sourceIdx(w));
assertEquals(false, wmgr.trackBit(w));
WalkArray w2 = snapshot7.getWalksAtVertex(22098, true);
w = ((IntWalkArray)w2).getArray()[0];
assertEquals(88, wmgr.sourceIdx(w));
assertEquals(true, wmgr.trackBit(w));
} |
c5873263-6c10-42f3-b5e2-554e466b072e | 4 | public static List<Supplier> formatOutputs(JSONArray results) {
final List<Supplier> ret = new ArrayList<Supplier>();
for (int i = 0; i < results.length(); i++) {
JSONObject r = null;
if (results.get(i) instanceof JSONObject)
r = (JSONObject) results.get(i);
if (r != null) {
final Supplier c = new Supplier();
if (r.has("name"))
c.setName(r.get("name").toString());
c.setNumber(r.get("number").toString());
c.setUuid(r.get("uuid").toString());
c.setCustomerNumber(r.get("customerNumber").toString());
ret.add(c);
}
}
return ret;
} |
2c84bce3-10e1-4af9-a663-f1056d9dfa61 | 8 | public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("agrinet.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("agrinet.out")));
n = Integer.parseInt(f.readLine());
graph = new int[n][n];
for(int i=0; i<n; i++) {
String line = "";
int num = 0;
while(num < n) {
String tempLine = f.readLine();
line += " " + tempLine;
StringTokenizer testst = new StringTokenizer(tempLine);
num += testst.countTokens();
}
StringTokenizer st = new StringTokenizer(line);
for(int j=0; j<n; j++) {
graph[i][j] = Integer.parseInt(st.nextToken());
}
}
// run Prim's algorithm
mst.add(0);
int sum = 0;
// for each step (n-1) of them
for(int i=0; i<n-1; i++) {
int len = mst.size();
int min = 100001;
int newV = -1;
for(int j=0; j<len; j++) {
for(int k=0; k<n; k++) {
if(!mst.contains(k)) {
if(graph[mst.get(j)][k]<min) {
min = graph[mst.get(j)][k];
newV = k;
}
}
}
}
sum += min;
mst.add(newV);
}
System.out.println(sum);
out.write(sum + "\n");
out.close();
System.exit(0);
} |
cd7f3341-90ad-4489-a854-8fbc959a07bb | 3 | public void execute() {
int nThreads = Runtime.getRuntime().availableProcessors();
ArrayList<Thread> threads = new ArrayList<Thread>();
for(int i=0; i < nThreads; i++) {
Thread t = new Thread(new RMATGenerator(numEdges / nThreads));
t.start();
threads.add(t);
}
/* Wait */
try {
for(Thread t : threads) t.join();
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
} |
3b1b7daf-c3a2-4ea5-a241-7194f0df3243 | 9 | * @param getterName - Name of the getter method for the field name to sort by
* @param order Whether to sort in asc or desc order
*/
public <T> void sort(ArrayList<Course> list, String getterName, final int order){//help order makes no sense. please document how it works.
try {
final Method getter=Course.class.getMethod(getterName, (Class<?>[]) null);
if (getter == null){
//Do Nothing
} else{
Collections.sort(list, new Comparator<Course>(){
public int compare(Course c1, Course c2){
try {
if((Integer)getter.invoke(c1, (Object[]) null) == (Integer)getter.invoke(c2, (Object[]) null)){
return 0;
}
return ((Integer) getter.invoke(c1, (Object[]) null))<((Integer) getter.invoke(c2, (Object[]) null))?(-1*order):(1*order);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return -2;
}
});
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
} |
2d308c92-9fbd-4e10-b957-c589919a77a0 | 6 | public void move(int ax, int ay, int bx, int by) {
char t = this.b[ax][ay].toString().charAt(1);
boolean c = this.b[ax][ay].getColor();
this.b[ax][ay] = new Blank(true);
switch (t) {
case 'P':
this.b[bx][by] = new Pawn(c);
break;
case 'R':
this.b[bx][by] = new Rook(c);
break;
case 'N':
this.b[bx][by] = new Knight(c);
break;
case 'B':
this.b[bx][by] = new Bishop(c);
break;
case 'K':
this.b[bx][by] = new King(c);
break;
case 'Q':
this.b[bx][by] = new Queen(c);
break;
}
} |
76e0585c-ad0e-4cf3-ae52-50adfeb7daf4 | 8 | public static void caseG(){
//we have a double with the highest average
//need to iterate through the list of students and find the one who has that average.
boolean correct_input = false;
while(!correct_input){
if(students_in_courses.size() == 0){
correct_input = true;
JOptionPane.showMessageDialog(null, "No students have been registered", "Error", JOptionPane.INFORMATION_MESSAGE);
break;
}
//enter the course name and validate the input
String one_or_two = JOptionPane.showInputDialog(null, "Enter 1 - For Best Student Award. Enter 2 - For Highest Mark Award ", "Scholarships", JOptionPane.QUESTION_MESSAGE).toUpperCase();
//best average (student)
if (Integer.parseInt(one_or_two) == 1){
correct_input = true;
BestStudentAward best = new BestStudentAward();
double mark = best.getWinner(students_in_courses);
//create an interator for students currently in courses
//we want to check to see which student has the best average
java.util.Iterator<Student> iter = students_in_courses.iterator();
//create a reference to the student with the best average
Student top_student = null;
//while there are no more students in courses
while(iter.hasNext()){
//grab the first student
Student current_student = iter.next();
//get the student with the best average
if (current_student.average == mark) top_student = current_student;
}
JOptionPane.showMessageDialog(null, "The winner of the Best Student Award is " + top_student.getName() + " with an average of " + top_student.average + ".", "Highest Average", JOptionPane.INFORMATION_MESSAGE);
}
//highest mark in a course
else if (Integer.parseInt(one_or_two) == 2){
correct_input = true;
HighestMarkAward best = new HighestMarkAward();
double highest_mark = best.getWinner(students_in_courses);
//create an interator for students currently in courses
//we want to check to see which student has the best average
java.util.Iterator<Student> iter = students_in_courses.iterator();
//create a reference to the student with the best average
Student top_student = null;
//while there are no more students in courses
while(iter.hasNext()){
//grab the first student
Student current_student = iter.next();
//find who the top student is
if(current_student.highestMark() == highest_mark) top_student = current_student;
}
JOptionPane.showMessageDialog(null, "The winner of the Best Student Award is " + top_student.getName() + " with a Highest mark of " + top_student.highestMark() + ".", "Highest Mark", JOptionPane.INFORMATION_MESSAGE);
}
else{
correct_input = false;
JOptionPane.showMessageDialog(null, "Invalid entry!", "ERROR", JOptionPane.OK_OPTION);
}
}
} |
01b9a720-cc5e-4e07-8528-c15c53a62e3c | 0 | public void setFormattedLocation(String formattedLocation) {
this.formattedLocation = formattedLocation;
} |
0203d4ee-51ff-4ebc-a993-d6be5ed2c183 | 2 | public void modificarOtro(int id, ArrayList datos)
{
// Cambiamos todos los datos, que se puedan cambiar, a minúsculas
for(int i = 0 ; i < datos.size() ; i++)
{
try{datos.set(i, datos.get(i).toString().toLowerCase());}
catch(Exception e){}
}
biblioteca.modificarRegistros("otro", id, datos);
} |
1c94bad9-7653-4706-bbfa-3828d6cb0416 | 5 | public static void addClasspath(String component) {
if ((component != null) && (component.length() > 0)) {
try {
File f = new File(component);
if (f.exists()) {
URL key = f.getCanonicalFile().toURL();
if (!classPath.contains(key)) {
classPath.add(key);
}
}
} catch (IOException e) {
}
}
} |
d94e586c-90a0-4eb5-9602-bb8dd17d059e | 0 | public void setXAxisDeadZone(float zone) {
setDeadZone(xaxis,zone);
} |
daf8e0cb-89bf-4ef8-ba3a-456bd38254aa | 7 | public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean isRunning = true;
int c = 0;
while (c < 10 || c > 20) {
System.out.print("Choose the size of your cave (10-20): ");
while(!in.hasNextInt()) {
System.out.print("That's not a number! Please try again: ");
in.next();
}
c = in.nextInt();
if (c < 10 || c > 20) {
System.out.println("Error: Your input must be between 10 and 20.");
}
}
// choose cave size:
System.out.println();
Map map = new Map(c);
Player player = new Player(map.getEntranceX(), map.getEntranceY());
System.out.println();
System.out.println();
System.out.println("Welcome to the cave! Type N to go North, S to go South, E to go East, and W to go West.");
while (isRunning) {
Movement.displayArea(map.getGrid(), player.getLocationX(), player.getLocationY());
map.displayRoomInfo(player);
System.out.print("[" + player.getScore() + " points earned] ");
if (!player.weapon) {
System.out.println("You are weak and have no weapon.");
} else {
System.out.println("You're armed and dangerous.");
}
System.out.print("Enter Direction (? for help) > ");
String command = in.next().toLowerCase();
System.out.println();
Movement.processCommand(command, player, map.getGrid());
System.out.println();
System.out.println();
}
in.close();
} |
11ff199a-403c-4156-8558-8c6cac93bebc | 6 | private void LoadContent(int img) {
try {
if (img == 0) {
URL trackImgUrl0 = this.getClass().getResource("/raceresources/resources/images/track0.png");
trackImg = ImageIO.read(trackImgUrl0);
} else if (img == 1) {
URL trackImgUrl1 = this.getClass().getResource("/raceresources/resources/images/track1.png");
trackImg = ImageIO.read(trackImgUrl1);
} else if (img == 2) {
URL trackImgUrl2 = this.getClass().getResource("/raceresources/resources/images/track2.png");
trackImg = ImageIO.read(trackImgUrl2);
} else if (img == 3) {
URL trackImgUrl3 = this.getClass().getResource("/raceresources/resources/images/track3.png");
trackImg = ImageIO.read(trackImgUrl3);
} else if (img == 4){
URL trackImgUrlEnd = this.getClass().getResource("/raceresources/resources/images/track0end.png");
trackImg = ImageIO.read(trackImgUrlEnd);
}
//get widht of the track
//courseImgWidth = trackImg.getWidth();
} catch (IOException ex) {
Logger.getLogger(Course.class.getName()).log(Level.SEVERE, null, ex);
}
} |
73f7db41-bca7-49cb-bc26-e1f8a31388c0 | 4 | @Test
public void canGetAllCategories() {
CategoryDAO cd = new CategoryDAO();
List<CategoryModel> categories = null;
try {
categories = cd.getAllCategories();
} catch (WebshopAppException e) {
e.printStackTrace();
fail("Exception");
}
boolean findTestCategory = false;
for (CategoryModel cat : categories) {
if (categoryTest.equals(cat)) {
findTestCategory = true;
break;
}
}
assertTrue(findTestCategory && (countCategories() == categories.size()));
} |
220321b3-9a9e-4548-9bbe-5446d5a0fcdf | 8 | public ArrayList <Vehicle> DBvehicleRouter (Object sysObject,
String action){
//local container
ArrayList <Vehicle> temp;
try{
if (sysObject instanceof String && "VIEWALL".equals(action)
&& "MANAGER".equals(sysObject)){
temp = queryDB.VehiclesForFranchise(lIO.getfN());
return temp;
}
if (sysObject instanceof Vehicle && "VIEWITEM".equals(action)){
temp = queryDB.GetOneVehicle
(((Vehicle)sysObject).getVehicleID());
return temp;
}
}
catch(UnauthorizedUserException e){
Vehicle error = new Vehicle("", e.getMessage(),
"", "", "", "", "", "", "", "", "", "" );
temp = new ArrayList();
temp.add(error);
return temp;
}
catch(BadConnectionException e){
Vehicle error = new Vehicle("", e.getMessage(),
"", "", "", "", "", "", "", "", "", "" );
temp = new ArrayList();
temp.add(error);
return temp;
}
catch(DoubleEntryException e){
Vehicle error = new Vehicle("", e.getMessage(),
"", "", "", "", "", "", "", "", "", "" );
temp = new ArrayList();
temp.add(error);
return temp;
}
return null;
}//end DBvehicleRouter method |
bc1611b4-d6f6-4e33-b6ad-a06b9964fcc0 | 8 | public void enregistrerHouse(MemoryAction m ){
int drap=0;
int j =0;
while( j <20 && drap ==0 )
{
if(houseList[j] == null) drap = j;
else if(j == 19) drap =j;
j++;
}
for( int g = drap; g>=0 ;g-- ){
if (g != 19) houseList[g+1] =houseList[g];
else houseList[19] = houseList[18];
}
houseList[0] =m;
System.out.println(m.r.getTemperature());
System.out.println("**************");
for(int a = 19; a >=0 ;a-- ){
if (houseList[a] != null )
{
System.out.println("------------------");
System.out.println(houseList[a].r.getNom());
System.out.println(houseList[a].element);
System.out.println(houseList[a].lastValue);
System.out.println(houseList[a].newValue);
}
}
curr_pos =0;
} |
6637a49c-77c6-4282-af6e-c0f9cc4c7bec | 3 | @Override
public Object getValueAt(final int row, final int column) {
if (column == 0) {
return AvailableTextFiles.getInstance().getAvailableTextFiles().get(row).getName();
}
else if (column == 1) {
return AvailableTextFiles.getInstance().getAvailableTextFiles().get(row).getAbsolutePath();
}
else if (column == 2) {
return AvailableTextFiles.getInstance().getAvailableTextFiles().get(row).getSvnStatus();
}
return null;
} |
0a941db7-8d66-4e79-88e0-85a075bf7c6b | 1 | public void cancelMove() {
if(canCancelMove())
willCancelMove = true;
} |
19a47264-b63a-4a4d-8b18-aed785c5f689 | 2 | public Neuron getNeuron(Integer layer, Integer column) {
if (layer < neurons.size()) {
if (column < neurons.get(layer).size()) {
return neurons.get(layer).get(column);
}
}
throw new IllegalArgumentException(
"Error: The given Range is not within the Borders of this Perceptron!");
} |
20551652-f8cc-4a3f-96d6-c6cd24896501 | 0 | public static void msg(Object desc) {
JOptionPane.showMessageDialog(null, desc);
} |
3e719238-7209-4d1b-b148-0786dd437e5c | 0 | public Map() throws JAXBException {
JAXBContext context = JAXBContext.newInstance(Row.class);
this.unmarshaller = context.createUnmarshaller();
} |
45398cbe-aa96-44f8-86ee-9c9b41db900d | 1 | public void addNotes(String text)
{
String eol = System.getProperty("line.seperator");
if(this.meetingNotes==null)
{
this.meetingNotes = text;
}else{
this.meetingNotes = this.meetingNotes + eol + text;
}
} |
617e7844-4819-45a7-8af7-95115135c667 | 8 | public void initial() throws IOException {
double[] positions = null;
// initial pbest and particles
for (int i = 0; i < swarm_size; i++) {
positions = new double[dimension];
for (int j = 0; j < dimension; j++) {
positions[j] = (Math.random() * (range_max - range_min) + range_min)
* (Math.random() > 0.5 ? 1 : -1);
}
population[i] = new Particle(positions);
pbest[i] = new Particle(positions);
}
allweights_1+="generation:" + c_generation + "\n";
allweights_1+=pbest[0].generateText();
pbest[0].writeFile("pbest", allweights_1);
// initial gbest
gbest = new Particle(population[0].getPosition());
for (int i = 0; i < swarm_size; i++) {
if (fitness(population[i]) > fitness(gbest)) {
gbest = new Particle(population[i].getPosition());
}
}
allweights+="generation:" + c_generation + "\n";
allweights+=gbest.generateText();
gbest.writeFile("gbest", allweights);
// initial velocity of all particles
double[] temp = new double[dimension];
for (int i = 0; i < swarm_size; i++) {
for (int j = 0; j < dimension; j++) {
temp[j] = Math.random() * vmax * (Math.random() > 0.5 ? 1 : -1);
}
velocity[i] = temp;
temp = new double[dimension];
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.