method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
f51e4298-03d0-4e34-bad9-054ebdc819b4 | 2 | public void start() {
if (driving)
return;
(new Thread() {
public void run() {
driving = true;
while (driving) {
move();
yield(); // prevent consuming all CPU resources
}
}
}).start();
} |
66634799-da43-4f2b-a39d-d20cd7f4db6d | 8 | public String getEncoded() {
if (padding == PaddingType.Number && StringUtils.isBlank(original)) {
return StringUtils.leftPad(StringUtils.EMPTY, size).substring(0, size);
}
if (padding == PaddingType.Number) {
return StringUtils.leftPad(original, size, "0").substring(0, size);
}
if (padding == PaddingType.NumberFollowedByAlpha && StringUtils.isBlank(original)) {
return StringUtils.leftPad(StringUtils.EMPTY, size - 1, "0").substring(0, size - 1) + " ";
}
if (padding == PaddingType.NumberFollowedByAlpha) {
final int lastPosition = original.length() - 1;
if (StringUtils.isAlpha(original.substring(lastPosition))) {
final String number = original.substring(0, lastPosition);
return StringUtils.leftPad(number, size - 1, "0").substring(0, size - 1)
+ original.substring(lastPosition);
} else {
return StringUtils.leftPad(original, size - 1, "0").substring(0, size - 1) + " ";
}
}
if (padding == PaddingType.String) {
return StringUtils.rightPad(original, size).substring(0, size);
}
return StringUtils.EMPTY;
} |
ba829784-9273-4b56-a173-0d10adaeec59 | 4 | public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<3;i++)
{
String s1=sc.next();
int x=sc.nextInt();
int length = String.valueOf(x).length();
String val="";
if(length==3)
val= Integer.toString(x);
else if(length==2)
val="0" + Integer.toString(x);
else if(length==1)
val="00"+Integer.toString(x);
System.out.printf("%-10s %-3s %s\n", s1,"",val );
//String.format(s1,"%-10s", "test")
//Complete this line
}
System.out.println("================================");
} |
1b902771-0fe5-4faf-afda-bac4098e735e | 9 | private void idNotificationCompletnessTest(){
List<String> notificationIdListFromNotificationSys = new ArrayList<String>();
List<String> notificationIdListFromNetezza = new ArrayList<String>();
this.IdType = this.reader.getIdType();
this.MessageType = this.reader.getMessageType();
String nodeName = "Id";
String attrName = "Type";
//Get id list from netezza
try {
notificationIdListFromNetezza = executeSql();
if(!notificationIdListFromNetezza.isEmpty()){
print("[INFO]Success to get ["+notificationIdListFromNetezza.size()+"] PerformanceId in Netezza");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for(String getIdUrl:this.realUriList){
List<String> tempList = new ArrayList<String>();
tempList = NotificationCatcherHelper.getDataListWithNodenameAttrNameAttrValue(getIdUrl, nodeName, attrName, this.IdType);
notificationIdListFromNotificationSys.addAll(tempList);
print("[INFO]Call url=["+getIdUrl+"] to get PerformanceId");
print("[INFO]"+tempList.size()+" in "+notificationIdListFromNotificationSys.size());
}
if(!notificationIdListFromNotificationSys.isEmpty()){
print("[INFO]Success to get ["+notificationIdListFromNotificationSys.size()+"] PerformanceId in Notification System");
}
if(notificationIdListFromNotificationSys.size() >= notificationIdListFromNetezza.size()){
boolean isRemoved = notificationIdListFromNotificationSys.removeAll(notificationIdListFromNetezza);
if(isRemoved == true){
print("[INFO]Got different ids... ...");
for(String diffIds:notificationIdListFromNotificationSys){
System.out.println("[DIFF]PerformanceId="+diffIds+" only in notification system!");
}
}
}else{
boolean isRemoved = notificationIdListFromNetezza.removeAll(notificationIdListFromNotificationSys);
if(isRemoved == true){
print("[INFO]Got different ids... ...");
for(String diffIds:notificationIdListFromNetezza){
System.out.println("[DIFF]PerformanceId="+diffIds+" only in netezza trigger table!");
}
}
}
} |
fcbe8ada-28b3-493a-a452-d89664a6164b | 7 | public Wave36(){
super();
MobBuilder m = super.mobBuilder;
for(int i = 0; i < 1200; i++){
if(i % 17 == 0)
add(m.buildMob(MobID.TENTACRUEL));
else if(i % 6 == 0)
add(m.buildMob(MobID.HORSEA));
else if(i % 5 == 0)
add(m.buildMob(MobID.TENTACOOL));
else if(i % 4 == 0)
add(m.buildMob(MobID.SHELLDER));
else if(i % 3 == 0)
add(m.buildMob(MobID.GOLDEEN));
else if(i % 2 == 0)
add(m.buildMob(MobID.POLIWAG));
else
add(m.buildMob(MobID.STARYU));
}
add(m.buildMob(MobID.ZAPDOS));
} |
d31be3ed-89ac-4a91-a2c2-cefe3676b518 | 7 | private void agendaItemMenu(int itemid, int meetingId) throws IOException, ClassNotFoundException {
String opt = "";
while (!("0".equals(opt))) {
System.out.println("You are now in the item " + itemid + " room\n");
System.out.println("You may now receive messages from other members of the item at anytime " + itemid + " room\n");
System.out.println("Please select one of the following options (0 to quit):\n");
System.out.println("1-Add Message\n" +
"2-Add key decision\n" +
"3-Assign task to user\n\n");
System.out.println(":::Chat log:::\n");
Message listChat = new Message(username_logged, null, null, "checkchatmessages");
listChat.dataint = itemid;
sendOut(listChat);
listChat = (Message) in.readObject();
System.out.println(listChat.data);
System.out.println("::::::::::::::\n");
//TODO colocar um metodo para conseguir ver o chat log todo
opt = scs.nextLine();
switch (opt) {
//add message
case "1":
System.out.println("Insert your message to add to the discussion:\n");
Message chatMsg = new Message(username_logged, null, null, "addchatmessage");
chatMsg.data = scs.nextLine();
chatMsg.dataint = itemJoined;
chatMsg.dataint2 = meetingId;
sendOut(chatMsg);
chatMsg = (Message) in.readObject();
if (chatMsg.result) {
System.out.println("::posted::");
} else {
System.out.println("An error occured. Please try again");
}
break;
//add key decision
case "2":
System.out.println("Add a key decision to this item:\n");
Message keyMsg = new Message(username_logged, null, null, "addkeydecision");
keyMsg.keydecision = scs.nextLine();
keyMsg.dataint = itemJoined;
sendOut(keyMsg);
keyMsg = (Message) in.readObject();
if (keyMsg.result) {
System.out.println("::Added::");
} else {
System.out.println("An error occured. Please try again");
}
break;
//assign action
case "3":
Message members = new Message(username_logged, null, null, "listmembers");
sendOut(members);
members = (Message) in.readObject();
System.out.println(members.data);
Message assignAction = new Message(username_logged, null, null, "assignaction");
assignAction.dataint = meetingId;
System.out.println("User (ID):");
assignAction.dataint2 = sci.nextInt();
System.out.println("Task:");
assignAction.data = scs.nextLine();
sendOut(assignAction);
assignAction = (Message) in.readObject();
if (assignAction.result) {
System.out.println("\nTask assigned to the selected user!\n");
} else {
System.out.println("An error occured. Please try again");
}
break;
}
}
} |
e5c08731-634f-47c6-a957-e9d8c9e91113 | 8 | public void testMixed() throws IOException {
System.out.println("testMixed");
RecordManager recman = newRecordManager();
HashDirectory dir = new HashDirectory((byte)0);
long recid = recman.insert(dir,HashNode.SERIALIZER);
dir.setPersistenceContext(recman, recid);
Hashtable hash = new Hashtable(); // use to compare results
int max = 30; // must be even
// insert & check values
for (int i=0; i<max; i++) {
dir.put("key"+i, "value"+i);
hash.put("key"+i, "value"+i);
}
recman.commit();
for (int i=0; i<max; i++) {
String s = (String)dir.get("key"+i);
assertEquals("value"+i, s);
}
recman.commit();
// replace only even values
for (int i=0; i<max; i+=2) {
dir.put("key"+i, "value"+(i*2+1));
hash.put("key"+i, "value"+(i*2+1));
}
recman.commit();
for (int i=0; i<max; i++) {
if ((i%2) == 1) {
// odd
String s = (String)dir.get("key"+i);
assertEquals("value"+i, s);
} else {
// even
String s = (String)dir.get("key"+i);
assertEquals("value"+(i*2+1), s);
}
}
recman.commit();
// remove odd numbers
for (int i=1; i<max; i+=2) {
dir.remove("key"+i);
hash.remove("key"+i);
}
recman.commit();
for (int i=0; i<max; i++) {
if ((i%2) == 1) {
// odd
String s = (String)dir.get("key"+i);
assertEquals(null, s);
} else {
// even
String s = (String)dir.get("key"+i);
assertEquals("value"+(i*2+1), s);
}
}
recman.commit();
recman.close();
recman = null;
} |
28c938db-1ee5-4848-8172-c8557640f6a7 | 2 | TreeNode next() {
TreeNode head = queue.poll();
if (head.left != null)
queue.offer(head.left);
if (head.right != null)
queue.offer(head.right);
return head;
} |
18f16509-f1ff-482a-a967-e438a4c93323 | 4 | public void turnSymbol() {
Random generator = new Random();
int x = generator.nextInt(100);
if (x < 10) // 10% chance will get 7
{
this.setID(1);
this.setIcon(new ImageIcon(getClass().getResource(
"resources/Seven2.png")));
value = 10;
} else if (x < 25) // 15% chance will get Bar
{
this.setID(2);
this.setIcon(new ImageIcon(getClass().getResource(
"resources/BAR.png")));
value = 7;
} else if (x < 45) // 20% chance will get Orange
{
this.setID(3);
this.setIcon(new ImageIcon(getClass().getResource(
"resources/orange.png")));
value = 5;
} else if (x < 70) // 25% chance will get Cherry
{
this.setID(4);
this.setIcon(new ImageIcon(getClass().getResource(
"resources/cherry.png")));
value = 3;
} else // 30% chance will get Lemon
{
this.setID(5);
this.setIcon(new ImageIcon(getClass().getResource(
"resources/lemon.png")));
value = 1;
}
} |
641b4d4a-24b4-45af-bc29-035286d6c3da | 5 | public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = "";
diffWays(30002);
d: do {
line = br.readLine();
if (line == null || line.length() == 0)
break d;
double amount = Double.parseDouble(line);
int ra = (int) ((amount * 100)+0.5);
if (amount == 0)
break;
System.out.printf(Locale.US, "%6.2f", amount);
System.out.printf(Locale.US, "%17d\n", dp2[ra]);
} while (line != null && line.length() != 0);
} |
cdda696d-74ca-4f2f-88d8-4c3946324cc5 | 0 | public LambdaProductionRemover() {
} |
32310d7f-e858-42ff-9efc-084c219a62ab | 0 | @Override
public String toString() {
return "fleming.entity.Paciente[ inhusa=" + inhusa + " ]";
} |
d449c4aa-057b-4acd-8216-7a9a90a73cde | 2 | @SuppressWarnings("unchecked")
public void setSortingStatus(int column, int status)
{
Directive directive = getDirective(column);
if (directive != EMPTY_DIRECTIVE)
{
sortingColumns.remove(directive);
}
if (status != NOT_SORTED)
{
sortingColumns.add(new Directive(column, status));
}
sortingStatusChanged();
} |
a9fb606f-ec85-48d7-9c67-f35b3b608323 | 0 | public String toString() {
return Thread.currentThread() + ": " + countDown;
} |
ea4d4614-2e3b-4da5-a8ed-ec8fe925bc2c | 4 | public void run() {
try {
while(!stop) {
if(control.shouldUpdate()) {
int selRow = sM.getSelectedRowNumber();
sM.updateTable();
//if a Row was selected select it again
if(selRow > -1) {
sM.setSelectedRow(selRow);
}
control.setUpdateView(false);
}
Thread.sleep(250);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} |
a6684dfa-5029-419f-ab0e-6902840bedd6 | 0 | public static void main(String[] args) {
System.out.println(s.replaceFirst("f\\w+", "located"));
System.out.println(s.replaceAll("shrubbery|tree|herring", "banana"));
} |
85f9d145-7f1d-48ec-bb9e-5a311c0b50d8 | 3 | public List<Claim> getClaimList() {
List<Claim> claimList = new ArrayList<Claim>();
Element claimE;
Claim claim;
for (Iterator i = root.elementIterator("claim"); i.hasNext();) {
claimE = (Element)i.next();
if (claimE.element("isDelete").getText().equals("false")) {
String id = claimE.element("id").getText()
, title = claimE.element("title").getText()
, description = claimE.element("description").getText()
, type = claimE.element("type").getText()
, timeAdded = claimE.element("timeAdded").getText()
, name = claimE.element("name").getText()
, debateId = claimE.element("debateId").getText()
, dialogState = claimE.elementText("dialogState");
claim = new Claim(id, title, description, type
, timeAdded, null, name, debateId, dialogState);
if (claimE.attributeValue("teamType").equals("A")) {
claim.setTeamType("A");
} else {
claim.setTeamType("B");
}
claimList.add(claim);
}
}
return claimList;
} |
98dfe861-b494-4595-a3bd-b18edadf6cae | 0 | public AbstractOutlineIndicator(OutlinerCellRendererImpl renderer, String toolTipText) {
this.renderer = renderer;
setVerticalAlignment(SwingConstants.TOP);
setOpaque(true);
setVisible(false);
setToolTipText(toolTipText);
updateIcon();
} |
d76ecffa-5cfd-4090-a63e-1836acf6171a | 0 | public String publicMethod()
{
return "public";
} |
7e43f8d9-9232-430d-ab7e-0fbb461e24f7 | 4 | public static char randBase(Random random) {
switch (random.nextInt(4)) {
case 0:
return 'A';
case 1:
return 'C';
case 2:
return 'G';
case 3:
return 'T';
default:
throw new RuntimeException("This should never happen!");
}
} |
705a2efc-97a2-47c0-a9e3-e1287358b409 | 4 | public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<Future<String>>();
for (int i = 0; i < 10; i++)
results.add(exec.submit(new TaskWithResult(i)));
for (Future<String> fs : results)
try {
// get() blocks until completion:
System.out.println(fs.get());
} catch (InterruptedException e) {
System.out.println(e);
return;
} catch (ExecutionException e) {
System.out.println(e);
} finally {
exec.shutdown();
}
} |
a143bed5-4f06-4c4b-83b1-38ac0ad5a1e5 | 3 | public void run() {
long nextFrameTicks = System.currentTimeMillis();
int framesSkipped;
float interpol;
while (running) {
framesSkipped = 0;
// Profiler.start();
while ((System.currentTimeMillis() > nextFrameTicks) && (framesSkipped < MAX_FRAMESKIP)) {
updateTime = System.nanoTime();
update();
updateTime = System.nanoTime() - updateTime;
addUpdateEntry(updateTime);
nextFrameTicks += TICKS_PER_FRAME;
framesSkipped++;
}
// Profiler.lapRestart("Update");
long systemMil = System.currentTimeMillis();
long num = systemMil + TICKS_PER_FRAME - nextFrameTicks;
interpol= ((float)(num))/((float)(TICKS_PER_FRAME));
tempRenderTime = System.nanoTime();
render(interpol);
renderTime = System.nanoTime() - tempRenderTime;
addRenderEntry(renderTime);
// Profiler.lap("Draw");
}
} |
df62c643-cf80-4790-94df-7fdf81d5af0c | 2 | public static int countInstances(String s, char c){
int count=0;
for (int i=0; i<s.length(); i++)
if (s.charAt(i) == c)
count++;
return count;
} |
7b3b1409-00c7-4a1b-a9f3-db8efdfdfb24 | 1 | public void addOrigin(ISO3Country origin) {
if (this.origin == null) {
this.origin = new ArrayList<ISO3Country>();
this.origin.add(origin);
} else {
this.origin.add(origin);
}
} |
8c0f1c35-4ca9-4c28-b37a-c83ba85a8035 | 7 | public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Servidor servidor;
try {
servidor = em.getReference(Servidor.class, id);
servidor.getIdServidor();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The servidor with id " + id + " no longer exists.", enfe);
}
List<String> illegalOrphanMessages = null;
Collection<Computadora> computadoraCollectionOrphanCheck = servidor.getComputadoraCollection();
for (Computadora computadoraCollectionOrphanCheckComputadora : computadoraCollectionOrphanCheck) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("This Servidor (" + servidor + ") cannot be destroyed since the Computadora " + computadoraCollectionOrphanCheckComputadora + " in its computadoraCollection field has a non-nullable servidoridServidor field.");
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
em.remove(servidor);
em.getTransaction().commit();
} catch (Exception ex) {
try {
em.getTransaction().rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
} |
3341f387-0df7-443f-b8dc-ac48b958d9ba | 4 | @Override
public void takeInfo(InfoPacket info) throws Exception {
super.takeSuperInfo(info);
Iterator<Pair<?>> i = info.namedValues.iterator();
Pair<?> pair = null;
Label label = null;
while(i.hasNext()){
pair = i.next();
label = pair.getLabel();
switch (label){
case elec:
electrisityGenerated = (Double) pair.second();
default:
break;
}
}
} |
afd4351c-353f-45c4-81e9-e0d9208d66f3 | 8 | public final static void main(String[] args) {
for (int i = 0; i < 20; i++) {
try {
Control.current = new Instance(args);
current.run();
} catch (FatalError e) {
Output.println(e.getMessage() + "\n", 0);
System.exit(1);
} catch (RestartLater e) {
if (e.getMessage() == null || e.getMessage().equals("")) {
i--;
Output
.println(
"Es ist ein Fehler aufgetreten, der nicht zugeordnet werden konnte.\n"
+ "Versuchen Sie den Fehler direkt über die Webseite zu finden. "
+ "Vermutlich hängt der Spieler irgendwo fest, wann der Bot nicht erkennen kann. "
+ "Oftmals scheitert es, wenn man manuell in den Ablauf eingegriffen hat oder wenn "
+ "Account beim Starten nicht im Ausgangszustand ist.\n"
+ "Der Bot wird sich in 3 min neu starten.",
0);
if (Config.getDebug()) {
e.printStackTrace();
}
Control.sleep(3 * 600);
} else {
Output.println("Geplanter Neustart: " + e.getMessage(), 2);
Control.current.logout();
}
} catch (Exception e) {
e.printStackTrace();
if (current.lastResponse != null) {
SimpleFile.write("debug-info.html", current.lastResponse);
Output.println("Bitte den Fehlerbericht »debug-info.html« melden", Output.ERROR);
}
Control.sleep(6000, Output.ERROR);
}
}
} |
6ddb228e-2b7d-4511-80b9-114e49092666 | 0 | @SuppressWarnings({"unchecked","deprecation"})
public static void main(String[] args)
{
Map map = new TreeMap();
Date date = new Date();
map.put("1", date);
System.out.println(date.toLocaleString());
} |
4b64739b-e21f-4064-bd48-6903f214f8dd | 9 | private String action(String[] messageList, String address, String message) throws SQLException {
String msg0 = messageList[0].toLowerCase();
String msg1 = messageList[1].toLowerCase();
String reply = "";
if (msg0.equals("reg")) {
DBServices.findUser("SELECT * from automart where usersId='" + address + "'");
if (!DBServices.result.next()) {
DBServices.insertUser("insert into `thescore`.`automart` (`usersId`) values ('" + address + "');");
reply = "Welcome to AutoMart..., you will recieve the adds soon, Thank you";
System.out.println("User registed : [" + address + "]");
} else {
reply = "You have already registered";
}
} else if (msg0.equals("unreg")) {
DBServices.findUser("SELECT * from automart where usersId='" + address + "'");
if (DBServices.result.next()) {
DBServices.insertUser("delete from `thescore`.`users` where `usersId`='" + address + "';");
reply = "You have successfully unregistered with AutoMart";
System.out.println("User unregisted : [" + address + "]");
} else {
reply = "You are not available at AutoMart";
}
} else if (msg1.equals("@")) {
String news = "";
if (messageList.length > 2) {
news = message.replace("@", "");
news = news.replaceFirst(" ", "");
news = news.replace("&", "n");
news = news.replaceFirst("automart", "AutoMart:");
sendBulkSms(news);
reply = "Successfully sent the news to subscribers";
} else {
reply = "Fail to send the news, type automart<space>@<space><news>";
}
} else if (msg1.equals("users")) {
if (messageList.length > 1) {
DBServices.findUser("select count(usersId) from thescore.automart;");
if (DBServices.result.next()) {
reply = "Subscribers count : " + DBServices.result.getInt("count(usersId)");
} else {
reply = "There no users registered yet.";
}
} else {
reply = "Fail to find the count of subscribers. Try again later";
}
} else {
reply = "Invalide message recieved, recheck the message again,Thank you";
}
DBServices.DbConnectionClose();
return reply;
} |
402eba18-76de-4d9d-9b41-307fe6628ed2 | 3 | public static void main(String[] args) {
HashMap<String, Integer> comptadors = new HashMap<String, Integer>();
String[] arrayParaules = { "Algu", "Pop", "Pilotilla", "Pilota",
"Romba", "Toyota", "Swag", "Meme", "Java", "Rom", "Majordom",
"Xavier", "Oli", "Algu", "Pop", "Java", "Java" };
for (String aux : arrayParaules) {
if (comptadors.containsKey(aux)) {
comptadors.put(aux, comptadors.get(aux) + 1);
} else {
comptadors.put(aux, 1);
}
}
//Ordenem el Hasmap, convertint-lo amb Treempa(que te l'ordena automaticament)
TreeMap ordenat = new TreeMap(comptadors);
Set<Entry<String, Integer>> entrades = ordenat.entrySet();
Iterator<Entry<String, Integer>> llistat = entrades.iterator();
Entry<String, Integer> entrada;
while (llistat.hasNext()) {
entrada = llistat.next();
System.out.println(entrada.getKey() + " :: " + entrada.getValue());
}
} |
72562440-a831-414b-955b-dcbb30d467df | 1 | public void LogOut(String userName) {
try {
print("User Log-out from the system.");
driver.findElement(By.partialLinkText(userName)).click();
waitTillElementLoad(By.linkText("Logout"));
driver.findElement(By.linkText("Logout")).click();
print("Successfully logged-out from the system.");
} catch (Exception ex) {
print("Logout failed.");
}
} |
7e8727d7-2dad-4844-bb5a-2a0f7b379785 | 5 | public static void PlayerPerksInventory(Player player) {
// get a list of all perks
List<?> PerkList = GChub.getPlugin().getMainConfig().getList("PerkList");
// get player name
String PlayerName = player.getName().toString();
// get player rank
String AllPlayerRanks = "";
String PlayerRank = null;
String[] playerGroups = GChub.getPlugin().permission.getPlayerGroups(player);
List<?> RankLevel = GChub.getPlugin().getMainConfig().getList("RankLevel");
for(int i = 0; i < playerGroups.length; i++) {
AllPlayerRanks = AllPlayerRanks + ", " + playerGroups[i];
}
for (int i = 0; i < RankLevel.size(); i++) {
String gName = RankLevel.get(i).toString().toLowerCase();
// test if current group is the highest one
if(AllPlayerRanks.toString().toLowerCase().contains(gName)) {
PlayerRank = RankLevel.get(i).toString();
break;
}
}
// clear player inventory before generating a new random one
player.getInventory().clear();
// create random inventory for player
PlayerCreateRandomInventory(player, PlayerName, PlayerRank, PerkList);
} |
f2045b20-eed6-4b59-9544-fb003f41580b | 5 | public static List<Game> getGamesList() {
List<Game> gamesList = new ArrayList<Game>();
boolean isLetPointEnabled = false;
for (int i = 1; i <= HOW_MANY_GAMES_YOU_WANT_TO_SET_UP; i++) {
String gameIdString = "game" + i;
// 设置这场比赛的赔率
List<Rate> ratesList = new ArrayList<Rate>();
for (int j = 1; j <= (isLetPointEnabled ? 6 : 3); j++) {
Rate rate = new Rate(gameIdString, isLetPointEnabled ? "让球" : "不让球", j % 3, j);
ratesList.add(rate);
}
Game game = new Game(gameIdString, "主队" + i, "客队" + i, isLetPointEnabled);
game.setRateList(ratesList);
if (i==2) {
game.setSure(true);
}
gamesList.add(game);
isLetPointEnabled = !isLetPointEnabled;
}
return gamesList;
} |
bd96459b-901b-4c3c-b9a6-766f41dd8ac1 | 4 | public List<Challenge> getPublicChallengeList(String parentId) {
List<Challenge> challengeList = new ArrayList<Challenge>();
Element challengeE;
Challenge challenge;
for (Iterator i = root.elementIterator("challenge"); i.hasNext();) {
challengeE = (Element)i.next();
if (challengeE.element("isDelete").getText().equals("false")
&& challengeE.element("parent").getText().equals(parentId)) {
String id = challengeE.element("id").getText()
, title = challengeE.element("title").getText()
, type = challengeE.element("type").getText();
challenge = new Challenge(id, parentId, title, type);
if (challengeE.attributeValue("teamType").equals("A")) {
challenge.setTeamType("A");
} else {
challenge.setTeamType("B");
}
challengeList.add(challenge);
}
}
return challengeList;
} |
0fdf7a02-a7cd-4151-9d2d-8483e18d1c97 | 5 | @FXML
private void deleteUplan() {
this.mainApp.confirmMeldung("Soll wirklich gelöscht werden?");
if (this.detailsUmlaufTable.getSelectionModel().getSelectedItem() != null) {
Umlaufplan umlaufplan = this.detailsUmlaufTable.getSelectionModel()
.getSelectedItem();
this.dbm.deleteUmlaufplan(umlaufplan);
for (int i = 0; i < this.umlaufplanliste.size(); i++) {
if (this.umlaufplanliste.get(i).equals(umlaufplan)) {
for (int j = 0; j < this.dienstplanliste.size(); j++) {
if (this.umlaufplanliste.get(i).getId() == this.dienstplanliste
.get(j).getUmlaufplanID()) {
this.dienstplanliste.remove(j);
--j;
}
}
this.umlaufplanliste.remove(i);
}
}
// Aktualisieren der Listen und Anzeigen
refreshUmlaufplan();
refreshDienstplan();
} else {
String fehlerA = "Es wurde noch Element ausgewählt";
String fehlerB = "Was soll gelöscht werden ?";
String fehlerC = "Fehler";
this.mainApp.fehlerMeldung(fehlerA, fehlerB, fehlerC);
}
} |
562e3bdb-5b9a-4c2e-9357-ebfdb53f6275 | 0 | public int handSize() {
return size;
} |
3f8d80dd-76c2-4558-b167-c7ad9a1ff398 | 0 | public int getPort() {
return port;
} |
a58033c0-19f9-4c90-af8b-bc902bb3c494 | 6 | private LinkedList processStorm(NOAAHurricaneData noaa, String stormName)
throws Exception
{
if(log.isDebugEnabled())
log.debug("Storm:" + stormName);
LinkedList centers = null;
try {
centers = noaa.getStormCenters(stormName);
} catch (MalformedURLException e) {
e.printStackTrace();
throw new Exception("Error reading NOAA coordinates:" + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new Exception("Error reading NOAA coordinates:" + e.getMessage());
} catch(ParseException e) {
e.printStackTrace();
throw new Exception("Error reading NOAA coordinates:" + e.getMessage());
}
if(log.isDebugEnabled())
log.debug("Retrieved " + centers.size() + " coordinates for " + stormName);
if(centers == null){
log.error("Failed to retrieve coordinates for " + stormName);
throw new Exception("Failed to retrieve coordinates for " + stormName);
}
return centers;
} |
d9779d51-a2ca-4712-82e4-27bc6e1f5778 | 8 | private String findServiceForDictionary(String dictionaryName)
{
for (Iterator<ServiceInfo> iter = _services.values().iterator(); iter.hasNext();)
{
ServiceInfo service = iter.next();
// stop, if serviceState is DOWN (0) or not available
Object oServiceState = service.get(RDMService.SvcState.ServiceState);
if(oServiceState == null)
continue;
int serviceState = Integer.parseInt((String) oServiceState);
if( serviceState == 0 )
continue;
// stop, if acceptRequests is false (0) or not available
Object oAcceptingRequests = service.get(RDMService.SvcState.ServiceState);
if(oAcceptingRequests == null)
continue;
int acceptingRequests = Integer.parseInt((String) oAcceptingRequests);
if( acceptingRequests == 0 )
continue;
String[] dictionariesProvided = (String[])service
.get(RDMService.Info.DictionariesProvided);
if (dictionariesProvided == null)
continue;
for (int i = 0; i < dictionariesProvided.length; i++)
{
if (dictionariesProvided[i].equals(dictionaryName))
return service.getServiceName();
}
}
return null;
} |
df0a7c90-e504-419f-9b03-3b17d3bf604c | 2 | public boolean set(int i, T pData) {
if (i >= this.length)
return false;
Node<T> ele = _head;
for (int x = 0; x < i; x++)
ele = ele.getNext();
ele.setData(pData);
return true;
} |
5047864f-8843-4cde-8b8e-bced81f03eaa | 4 | public void check(Sorter sorter) {
int[] a = {4,7,1,8,5}, a0 = {1,4,5,7,8};
int[] b = {1,2,3,4}, b0 = {1,2,3,4};
int[] c = {6,6,0,9,1,7}, c0 = {0,1,6,6,7,9};
int[] d = {1}, d0 = {1};
a = sorter.sort(a);
b = sorter.sort(b);
c = sorter.sort(c);
d = sorter.sort(d);
System.out.println(sorter.getClass().getSimpleName() + ":");
if(
Arrays.equals(a, a0) &&
Arrays.equals(b, b0) &&
Arrays.equals(c, c0) &&
Arrays.equals(d, d0) ) {
println("True");
} else {
println(Arrays.toString(a));
println(Arrays.toString(b));
println(Arrays.toString(c));
println(Arrays.toString(d));
}
} |
6a3d67f5-4bec-46bf-abc8-d365f8090b33 | 4 | @Override
public void mousePressed(MouseEvent me) {
if (me.getPoint().x < 800 && me.getPoint().y < 800) {
if (this.echiquier.getPieceCase(((ChessFrame) this.fenetre).getCoord(me.getPoint())) != null) {
if (this.echiquier.getPieceCase(((ChessFrame) this.fenetre).getCoord(me.getPoint())).getCouleur() == this.echiquier.getJoueurCourant().getCouleurJeu()) {
pInit = ((ChessFrame) this.fenetre).getCoord(me.getPoint());
deplacementsAutorises(pInit);
((ChessFrame) this.fenetre).moveIcon(me.getPoint());
}
}
}
} |
decb7696-9123-4a45-9847-d2c6cd78af83 | 4 | public static boolean chkCol(char[][] arr,int col){
boolean res = true;
Set<Character> set = new HashSet<>();
for(int i=0;i<arr.length;i++){
if(arr[i][col]!='.') {
if (set.contains(arr[i][col])) {
if(log){
prints(set);
System.out.println("i "+i+",col "+col+","+arr[i][col]);
}
res = false;
break;
} else {
set.add(arr[i][col]);
}
}
}
return res;
} |
5fb6d236-1359-451d-af34-fbb46710d45f | 4 | @Override
public void execute() {
String msg = Widgets.get(13, 28).getText();
if (msg.contains("FIRST")) {
Widgets.get(13, Character.getNumericValue(Settings.pin[0]) + 6).click(true);
Task.sleep(750, 1200);
}
if (msg.contains("SECOND")) {
Widgets.get(13, Character.getNumericValue(Settings.pin[1]) + 6).click(true);
Task.sleep(750, 1200);
}
if (msg.contains("THIRD")) {
Widgets.get(13, Character.getNumericValue(Settings.pin[2]) + 6).click(true);
Task.sleep(750, 1200);
}
if (msg.contains("FOURTH")) {
Widgets.get(13, Character.getNumericValue(Settings.pin[3]) + 6).click(true);
Task.sleep(750, 1200);
}
} |
b177f2c5-7f14-4cb6-8c45-8380c5638cb7 | 5 | @Override
public void insertString(FilterBypass fb, int offset, String string,
AttributeSet attr) throws BadLocationException {
StringBuilder builder = new StringBuilder(string);
for (int i = builder.length() - 1; i >= 0; i--) {
int cp = builder.codePointAt(i);
if (!Character.isDigit(cp) && cp != '.' && cp != '-') {
builder.deleteCharAt(i);
if (Character.isSupplementaryCodePoint(cp)) {
i--;
builder.deleteCharAt(i);
}
}
}
super.insertString(fb, offset, string, attr);
} |
4173764c-4ed3-4718-9e78-5b146d5e5983 | 9 | public SequenceIterator getTypedValue() throws XPathException {
switch (getNodeKind()) {
case Type.COMMENT:
case Type.PROCESSING_INSTRUCTION:
return SingletonIterator.makeIterator(new StringValue(stringValue));
case Type.TEXT:
case Type.DOCUMENT:
case Type.NAMESPACE:
return SingletonIterator.makeIterator(new UntypedAtomicValue(stringValue));
default:
if (typeAnnotation == -1 || typeAnnotation == StandardNames.XS_UNTYPED ||
typeAnnotation == StandardNames.XS_UNTYPED_ATOMIC) {
return SingletonIterator.makeIterator(new UntypedAtomicValue(stringValue));
} else {
SchemaType stype = config.getSchemaType(typeAnnotation);
if (stype == null) {
String typeName = config.getNamePool().getDisplayName(typeAnnotation);
throw new IllegalStateException("Unknown type annotation " +
Err.wrap(typeName) + " in standalone node");
} else {
return stype.getTypedValue(this);
}
}
}
} |
b31b829b-4822-4a4b-849f-39b15f5a121a | 4 | public static <T> Iterable<T> filter(Iterable<? extends T> c, Predicate<? super T> p) {
List<T> result = new ArrayList<T>();
for (T e : c) {
if (p.apply(e)) {
result.add(e);
}
}
return result;
} |
1ffea9c6-5a9e-44d5-b212-aaa8fac98759 | 6 | private String inverseLetters(String str){
String returnValue = new String(), c = new String();
if(str.length()>0){
for(int i=0;i<str.length();i++){
c = str.substring(i,i+1);
if(c.equalsIgnoreCase("A")){
returnValue+="T";
}//END IF
if(c.equalsIgnoreCase("T")){
returnValue+="A";
}//END IF
if(c.equalsIgnoreCase("C")){
returnValue+="G";
}//END IF
if(c.equalsIgnoreCase("G")){
returnValue+="C";
}//END IF
}//END FOR
}//END IF
return this.inverseLettersOrder(returnValue);
}//END FUNCTION |
f116dc9f-84ce-42de-a93b-8ba1e26a074c | 9 | public int setPage(int page) {
if (select == null) {
return -1;
}
int nbpage = getPageCount();
if (nbpage > 0) {
if (page > 0 && page < getPageCount()) {
currentPage = page - 1;
currentRows = getNbRow();
try {
this.curRows = this.database.getRows(select, currentPage * rowperpage, currentRows);
fieldsArray = this.curRows.remove(0);
currentRows = this.curRows.size();
} catch (WaarpDatabaseSqlException e) {
this.curRows = null;
}
fireTableStructureChanged();
}
} else {
if (page > 0) {
List<String[]> temp = null;
try {
temp = this.database.getRows(select, currentPage * rowperpage, currentRows);
} catch (WaarpDatabaseSqlException e) {
}
if (temp == null || temp.size() == 0) {
} else {
currentPage = page - 1;
fieldsArray = temp.remove(0);
currentRows = temp.size();
this.curRows = temp;
}
fireTableStructureChanged();
}
}
return currentPage + 1;
} |
4aabf848-543f-40cd-82f8-5a7a8693f011 | 2 | public Unit(int x, int y, Sprite sprite, int MOV, int TEAM)
{
this.x = this.pX = x;
this.y = this.pY = y;
this.dX = x * Game.TILESIZE;
this.dY = y * Game.TILESIZE;
this.sprite = sprite;
this.mov = MOV != -1 ? MOV : 5; //Defaults to 5
this.team = TEAM;
this.inventory = new Inventory(5);
classID = 0;
this.exp = 15;
this.maxHP = 50;
this.hp = 40;
this.maxMP = 20;
this.mp = 15;
this.atk = 25-10*team;
this.def = 5;
btList.put(0, "Attack " + x);
//btList.put(5, "Cancel " + y);
//btList.put(6, "Done " + dX);
if(TEAM == 1)
{
btList.put(7, "Reset Moves " + dY);
}
} |
9749c6b1-e84c-4dcb-83d1-3961aee95ac2 | 9 | private int getType(Object a) {
while (a.getClass().isArray()) {
a = Array.get(a, 0);
}
if (a instanceof Byte) {
return 1;
}
if (a instanceof Boolean) {
return 2;
}
if (a instanceof Short) {
return 3;
}
if (a instanceof Integer) {
return 5;
}
if (a instanceof Long) {
return 7;
}
if (a instanceof Float) {
return 9;
}
if (a instanceof Double) {
return 10;
}
if (a instanceof String) {
return 11;
}
return -1;
} |
65e87696-7bb4-4187-a166-7bb39976b173 | 3 | @Override
public List<Livro> listAll() {
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
List<Livro> livros = new ArrayList<>();
try{
conn = ConnectionFactory.getConnection();
pstm = conn.prepareStatement(LIST);
rs = pstm.executeQuery();
while (rs.next()){
Livro l = new Livro();
l.setId_livro(rs.getInt("livro.id_livro"));
l.setTitulo(rs.getString("livro.titulo_lv"));
l.setSubtitulo(rs.getString("livro.subtitulo_lv"));
l.setPalavrasChave(rs.getString("livro.palavraChave_lv"));
l.setPreco(rs.getDouble("livro.preco_lv"));
l.setRoyalty(rs.getDouble("livro.royalty_lv"));
l.setResumo(rs.getString("livro.resumo_lv"));
l.setEdicao(rs.getInt("livro.nEdi_lv"));
l.setVolume(rs.getDouble("livro.volume_lv"));
l.setQtEstoque(rs.getInt("livro.qtEstoque_lv"));
l.setIsbn(rs.getInt("livro.isbn"));
Editor ed = new Editor();
ed.setId_editor(rs.getInt("Editora.id_editora"));
l.setEditor(ed);
Loja lj = new Loja();
lj.setId_loja(rs.getInt("Loja.id_loja"));
//Autor
//l.setAutor(rs.getInt("id_autor"));
//livros.add(l);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Erro ao listar livros " + e);
}finally{
try{
ConnectionFactory.closeConnection(conn, pstm, rs);
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Erro ao desconectar com o banco " + e);
}
}
return livros;
} |
f53d71a6-6287-4fac-a297-b8aec5b400a2 | 7 | @Override
public void unInvoke()
{
// undo the affects of this spell
if(!(affected instanceof MOB))
return;
final MOB mob=(MOB)affected;
if((mob.isMonster())&&(mob.amDead())&&(!canBeUninvoked()))
super.canBeUninvoked=true;
super.unInvoke();
if(canBeUninvoked())
if((mob.location()!=null)&&(!mob.amDead()))
mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-YOUPOSS> broken limbs have been healed."));
} |
e42f12ad-5964-43d7-9a63-8cf293419a05 | 4 | public void nestPartInScene(String viewName)
{
Resource resView = this.applicationContext.getResource(MessageFormat.format("views/modules/{0}.fxml", viewName));
Resource resLang = this.applicationContext.getResource(MessageFormat.format("views/modules/{0}.properties", viewName));
try
{
FXMLLoader loader = new FXMLLoader(resView.getURL());
loader.setResources(new PropertyResourceBundle(resLang.getInputStream()));
loader.setControllerFactory((Class<?> clazz) -> this.applicationContext.getBean(clazz) );
ObservableList<Node> children = this.lookup.getChildren();
if(children.size() > 0)
{
children.remove(children.size() - 1);
}
children.add((Node) loader.load());
SceneManagerShowable ctrl = loader.getController();
if(ctrl != null)
{
ctrl.showed();
}
}
catch (IOException ex)
{
System.err.println(" Part view don't exist: " + resView.toString() + " \n" + ex.getLocalizedMessage() );
}
} |
8b4f505c-1c63-4f58-9571-e5faf204cfbd | 5 | public void checkName(Draggable d) { //Checks the name of the Draggable and creates a new one of that type of Draggable
if (d.name == "Lake") {
createLake();
} if (d.name == "Crater") {
createCrater();
} if (d.name == "Archer") {
createArcher();
} if (d.name == "Warrior") {
createWarrior();
} if (d.name == "Wall") {
createWall();
}
} |
f4eb6217-aae3-4e68-9f82-9be8e6854f52 | 1 | public void paint(Graphics g) {
// This test is necessary because the swing thread may call this
// method before the simulation calls SwingAnimator.update()
if (_painter != null ) {
// The clearRect is necessary, since JPanel is lightweight
g.clearRect(0, 0, _width, _height);
_painter.paint(g);
}
} |
63c44549-91bb-40b7-81c5-1639d853bb8c | 5 | public void tick(World world, int delta) {
if (this.alive) {
// Update the equipped weapon (if there is a weapon equipped)
if (this.weapon != null) this.weapon.tick(this, world, delta);
// Shoot if the player is detected
if (this.detect()) this.weapon.shot(world, this.weapon.getDelay().getDuration() + Util.getRandomIntBetween(3500, 0));
// Set to the correct animation
if (this.running) this.animation = Resources.similiRunning;
else this.animation = Resources.similiStatic;
if (this.getAngleWithPlayer() < 0)
this.animation.setReverse(true);
else
this.animation.setReverse(false);
}
} |
ac9d311b-5e48-4be8-9795-eb0aae44ff50 | 1 | private void notifyListeners()
{
for (QuestionListener listener : listeners)
listener.onQuestionChange(question);
} |
6faed899-4117-45c7-bcf6-1a4bfe0f2bad | 6 | public static int search3(int[] a, int p, int r) {
int x = a[p];
int i = p + 1;
int j = r;
while (true) {
while (j >= p && a[j] > x) {
j--;
}
while (i <= r && a[i] < x) {
i++;
}
if (i < j) {
swap(a, i, j);
} else {
swap(a, p, j);
return j;
}
}
} |
c6aba156-16f9-4598-8eeb-85111cda1f89 | 4 | public static ProtocolChatMessage getProtocolChatMessage(String inString)
throws TagFormatException, JDOMException, IOException {
SAXBuilder mSAXBuilder = new SAXBuilder();
Document mDocument = mSAXBuilder.build(new StringReader(inString));
Element rootNode = mDocument.getRootElement();
String protType = rootNode.getName();
int type = -1;
String content = "";
if (protType.equals(Tags.CHAT_MSG)) {
type = ProtocolChatMessage.CHAT_MESSAGE;
content = rootNode.getText();
} else if (protType.equals(Tags.FILE_REQ)) {
type = ProtocolChatMessage.FILE_MESSAGE;
content = rootNode.getText();
} else if (protType.equals(Tags.FILE_REQ_NOACK_S)) {
type = ProtocolChatMessage.FILE_NOACK;
} else if (protType.equals(Tags.FILE_REQ_ACK)) {
type = ProtocolChatMessage.FILE_ACK;
content = rootNode.getChildText(Tags.PORT);
} else {
TagFormatException tfe = new TagFormatException(
"It's not a chat message protocol");
throw tfe;
}
return new ProtocolChatMessage(type, content);
} |
c5e45978-cb71-45cb-8dcf-04f64d1334d7 | 2 | @BeforeClass
public static void setUpBeforeClass() throws Exception {
testImage = new BufferedImage(9, 9, BufferedImage.TYPE_INT_RGB);
for(int x = 3; x < 6; ++x) {
for(int y = 3; y < 6; ++y) {
testImage.setRGB(x, y, 0xFFFFFF);
}
}
} |
1a8e5a15-687d-4f22-b385-de4709e31f91 | 2 | private void db(final String s) {
if (FlowGraph.DEBUG || FlowGraph.DB_GRAPHS) {
System.out.println(s);
}
} |
a9749fd0-e236-4473-91f2-bbe1ed4afe24 | 2 | public Tree(HuntField field) {
boolean searchPosition = true;
Position position;
while (searchPosition){
position = new Position(new Random().nextInt(field.getXLength()), new Random().nextInt(field.getYLength()));
if(field.setItem(this,position)){
searchPosition = false;
}
}
} |
e71fb7f3-7b89-4c74-997c-a25fb2429931 | 1 | public static boolean purgeDB()
{
boolean a, b;
a = db.Query("DROP TABLE `database`");
b = db.Query("CREATE TABLE IF NOT EXISTS `database` (signurl varchar(20), url varchar(164))");
CustomFunction.addLink("Author Site", "http://www.willhastings.net", true);
if(a == b) return true;
else return false;
} |
bd6ecbd1-9a17-4f0e-a225-23cf8d03dc5f | 4 | protected void moveLeft() {
if (this.posX > 0 && !(this.posY == this.enemyPosY && (this.posX-1) == this.enemyPosX) && !(BattleBotsGUI.instance.obstacles[this.posX-1][this.posY])) {
this.posX--;
}
} |
1259c5d5-a27e-4cb7-a5ed-ba7bf452072c | 8 | public void move(Input input, Rectangle[] walls, int delta){
Rectangle attempt = container;
if (input.isKeyDown(Input.KEY_UP))
{
sprite = up;
attempt.setLocation(absolutex,absolutey - delta * 0.1f);
if (!collision(attempt,walls)){
absolutey -= delta * 0.1f;
//move(0,-delta * 0.1f);
container.setLocation(absolutex , absolutey);
sprite.update(delta);
}
}
else if (input.isKeyDown(Input.KEY_DOWN))
{
sprite = down;
attempt.setLocation(absolutex,absolutey + delta * 0.1f);
if (!collision(attempt,walls)){
absolutey += delta * 0.1f;
//move(0,delta * 0.1f);
container.setLocation(absolutex, absolutey);
sprite.update(delta);
}
}
else if (input.isKeyDown(Input.KEY_LEFT))
{
sprite = left;
attempt.setLocation(absolutex - delta * 0.1f,absolutey);
if (!collision(attempt,walls)){
absolutex -= delta * 0.1f;
//move(-delta * 0.1f,0);
container.setLocation(absolutex, absolutey);
sprite.update(delta);
}
}
else if (input.isKeyDown(Input.KEY_RIGHT))
{
sprite = right;
attempt.setLocation(absolutex + delta * 0.1f,absolutey);
if (!collision(attempt,walls)){
absolutex += delta * 0.1f;
//move(delta * 0.1f,0);
container.setLocation(absolutex, absolutey);
sprite.update(delta);
}
}
} |
e952ec69-b35f-4e43-b871-ada9e4fc06f4 | 6 | @Test
public void layerIteratorTest() {
int traversed = 0;
int backtracked = 0;
LayerIterator iter = new LayerIterator(networkLinear);
while (iter.hasNext()) {
List<? extends Neuron> layer = iter.next();
assertNotNull(layer);
if (iter.hasPrevious()) {
iter.previous();
assertEquals(layer, iter.next());
backtracked++;
}
traversed++;
}
assertEquals(3, traversed);
assertEquals(2, backtracked);
iter = new LayerIterator(networkLinear);
traversed = 0;
backtracked = 0;
while (iter.hasPrevious()) {
List<? extends Neuron> layer = iter.previous();
assertNotNull(layer);
if (iter.hasNext()) {
iter.next();
assertEquals(layer, iter.previous());
backtracked++;
}
traversed++;
}
assertEquals(3, traversed);
assertEquals(2, backtracked);
} |
4c48c6b1-9328-4238-8232-890b13b29940 | 9 | public List<Meeting> xmlToList() throws Exception {
List<Meeting> meetingList = new ArrayList<Meeting>();
try{
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
InputStream in = new FileInputStream("meetings.xml");
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
// Read the XML document
Meeting aMeeting = null;
Calendar meetingDate = Calendar.getInstance();
int meetingId = 0;
Set<Contact> meetingContacts = new HashSet<Contact>();
while (eventReader.hasNext()) { //iterate down the xmlevents
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) { //if there is a < then set the event to be < event
StartElement startElement = event.asStartElement();
// If we have a item element we create a new item
if (startElement.getName().getLocalPart() == (MEETING)) {
if (event.isStartElement()) {
if (event.asStartElement().getName().getLocalPart().equals(DATE)) {
event = eventReader.nextEvent();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
meetingDate.setTime(sdf.parse(event.asCharacters().getData()));// Jigar Joshi; Mar 14 '11 (StackOverflow.com)
continue;
}
if (event.asStartElement().getName().getLocalPart().equals(ID)) {
event = eventReader.nextEvent();
meetingId = Integer.parseInt(event.asCharacters().getData());
continue;
}
if (event.asStartElement().getName().getLocalPart().equals(CONTACT)){
event = eventReader.nextEvent();
//do something to create a set of contacts
Contact person = new ContactImpl(event.asCharacters().getData());
meetingContacts.add(person);
continue;
}
if(meetingDate.before(Calendar.getInstance())){
aMeeting = new PastMeetingImpl(meetingDate, meetingId, meetingContacts);
}
else{
aMeeting = new FutureMeetingImpl(meetingDate, meetingId, meetingContacts);
}
meetingList.add(aMeeting);
}
}
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return meetingList;
} |
6fba700d-da2f-414b-b99c-de57bd809a8f | 3 | private PrintWriter getPrintWriter()
{
if(this.currentLogFile == null && this.filePath != null)
{
try {
return new PrintWriter(this.filePath);
} catch (Exception e) {
e.printStackTrace();
}
}
return this.currentLogFile;
} |
8ec93798-d871-41e6-86fe-8377b8ae8ade | 5 | public void initMenu()
{
comps.add(new UILabel("Connecting to server: "+serverIP, w/2, h/2, LabelAlignment.CENTERED).setColor(0xFFFFFF));
backButton = new UIButton(this, w/2-75, h/2-30, 150, 30,"Cancel");
comps.add(backButton);
if(!connecting)
new Thread(new Runnable()
{
public void run()
{
if(serverIP == null || serverIP.trim().length() == 0)
return;
String serverAddress = "";
int serverPort = 35565;
if(serverIP.contains(":"))
{
serverAddress = serverIP.split(":")[0];
serverPort = Integer.parseInt(serverIP.split(":")[1]);
}
else
{
serverAddress = serverIP;
}
try
{
client = new Client(6556500, 6556500);
client.start();
NetworkCommons.registerClassesFor(client);
ClientNetworkListener listener = new ClientNetworkListener(client);
BlockyMain.instance.setClientNetwork(listener);
client.addListener(listener);
client.connect(8001, serverAddress, serverPort);
}
catch (Exception e)
{
UI.displayMenu(new UIErrorMenu(new UIMainMenu(), UIConnectingToServer.this, e));
e.printStackTrace();
}
}
}).start();
connecting = true;
} |
91cb4ff5-a0c0-4250-800b-036053094b9f | 0 | protected void interrupted() {
end();
} |
f1580831-6cbc-457e-803d-7fe85f3271c7 | 4 | public boolean doesThreaten(Point p) {
char c = aiarr[(int) p.getX()][(int) p.getY()].toString().charAt(0);
if (c == 'B')
c = 'W';
else
c = 'B';
checkThreats(gameBoard, c);
for (int i = 0; i < numThreatening; i++) {
if (locThreatening[i].getX() == p.getX() && locThreatening[i].getY() == p.getY()) {
return true;
}
}
return false;
} |
683ba19d-e22e-4c84-90da-fb42867872b8 | 0 | private ConfigValues(String key, Object def) {
this.key = key;
this.def = def;
} |
7592d780-0e53-40ee-801d-eca47bdc0656 | 4 | @Override
public Line getNextFromTextIntro() {
if (this.getIndex() < ((TextIntroImp) this.getParent()).getLineNb() - 1) {
return ((TextIntroImp) this.getParent())
.getLine(this.getIndex() + 1);
} else {
if (((TextIntroImp) this.getParent()).getParent() instanceof DocumentImp) {
Document doc = ((Document) ((TextIntroImp) this.getParent())
.getParent());
if(doc.getSubSectionNb() > 0)
return doc.getSubSection(0).getTitle().getLine();
else return doc.getTextIntro().getLastLine();
} else if (((SectionImp) ((TextIntroImp) this.getParent())
.getParent()).getNextSection() != null) {
return ((SectionImp) ((TextIntroImp) this.getParent())
.getParent()).getNextSection().getFirstLine();
} else {
return this;
}
}
} |
b635fe15-5f9a-4da8-83cf-1de9bf052cd2 | 7 | public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
try {
if (method.getName().equalsIgnoreCase("setService")) {
this.setService(args[0]);
return null;
} else if (method.getName().equalsIgnoreCase("unsetService")) {
this.unsetService(args[0]);
return null;
}
if (service == null && hasStartStop)
throw new RuntimeException("need set real service first");
if (method.getName().equalsIgnoreCase(startMethodName)
|| method.getName().equalsIgnoreCase(stopMethodName))
{
return callStartOrStop(proxy, method, args);
}
else
return method.invoke(service, args);
} catch (Exception e) {
throw new RuntimeException("error ", e);
}
} |
b4054d2f-c795-47ff-8cc5-b2c2b9aae6db | 3 | public void stop() {
try {
mServerSocket.close();
} catch (IOException e) {
}
for (Messenger messenger : mConnectedClients) {
messenger.stop();
}
mConnectedClients.clear();
try {
mServerThread.join();
} catch (InterruptedException e) {
}
} |
00884caf-3c74-435e-9e63-3269edce1784 | 2 | public ParseTree addChild(ParseTree parseTree) {
ParseTree[] newChildren = new ParseTree[children.length + 1];
for(int i = 0; i < children.length; i++)
newChildren[i] = children[i];
newChildren[newChildren.length - 1] = parseTree;
children = new ParseTree[newChildren.length];
for(int i = 0; i < children.length; i++)
children[i] = newChildren[i];
return parseTree;
} |
02d84ab7-c971-45e7-865a-fc3a0394ace2 | 0 | public void setModeleJComboBoxVisiteur(DefaultComboBoxModel modeleJComboBoxVisiteur) {
this.modeleJComboBoxVisiteur = modeleJComboBoxVisiteur;
} |
5854351b-3539-4b86-a9da-d9f35f566352 | 3 | @Override
public void ParseIn(Connection Main, Server Environment)
{
Environment.InitPacket(620, Main.ClientMessage);
Environment.Append(true, Main.ClientMessage); // gift wrapping Enabled?
Environment.Append(1, Main.ClientMessage); // gift wrapping Cost
Environment.Append(10, Main.ClientMessage);
for(int i = 0;i<10;i++)
Environment.Append(i+3372, Main.ClientMessage);
Environment.Append(7, Main.ClientMessage);
for(int i = 0;i<7;i++)
Environment.Append(i, Main.ClientMessage);
Environment.Append(11, Main.ClientMessage);
for(int i = 0;i<11;i++)
Environment.Append(i, Main.ClientMessage);
Environment.EndPacket(Main.Socket, Main.ClientMessage);
} |
2d719888-0ed8-46db-ad9a-bbf24da6cc16 | 8 | public void release(HGPersistentHandle handle)
{
if (slots.isEmpty() || graph.getHandleFactory().nullHandle().equals(handle))
return;
HGPersistentHandle [] layout = graph.getStore().getLink(handle);
if (layout == null)
// this is fishy, a sys print out like this, next line will throw an NPE anyway
System.out.println("oops, no data for : " + handle);
if (layout.length != slots.size() * 2)
throw new HGException("RecordType.remove: Record value of handle " +
handle +
" does not match record type number of slots.");
for (int i = 0; i < slots.size(); i++)
{
HGHandle slotHandle = (HGHandle)getAt(i);
HGAtomType type;
if (getReferenceMode(slotHandle) == null)
type = graph.getTypeSystem().getType(layout[2*i]);
else
type = graph.getTypeSystem().getAtomType(HGAtomRef.class);
int j = 2*i + 1;
if (!layout[j].equals(graph.getHandleFactory().nullHandle()))
if (!TypeUtils.isValueReleased(graph, layout[j]))
{
TypeUtils.releaseValue(graph, type, layout[j]);
}
}
graph.getStore().removeLink(handle);
} |
3c841ef7-0fbe-4fd2-9573-7783cfa6e323 | 7 | @Override
public boolean execute(MOB mob, List<String> commands, int metaFlags)
throws java.io.IOException
{
if(mob.findTattoo("SYSTEM_MPRUNDOWN")!=null)
return CMLib.commands().handleUnknownCommand(mob, commands);
MOB checkMOB=mob;
if(commands.size()>1)
{
final String firstParm=commands.get(1);
final int x=firstParm.indexOf(':');
if(x>0)
{
checkMOB=CMLib.players().getLoadPlayer(firstParm.substring(0,x));
if(checkMOB==null)
{
mob.addTattoo("SYSTEM_MPRUNDOWN",(int)CMProps.getTicksPerMinute());
return CMLib.commands().handleUnknownCommand(mob, commands);
}
final String pw=firstParm.substring(x+1);
if(!checkMOB.playerStats().matchesPassword(pw))
{
mob.addTattoo("SYSTEM_MPRUNDOWN",(int)(2 * CMProps.getTicksPerMinute()));
return CMLib.commands().handleUnknownCommand(mob, commands);
}
commands.remove(1);
}
}
if(!CMSecurity.isAllowed(checkMOB,mob.location(),CMSecurity.SecFlag.JSCRIPTS))
return CMLib.commands().handleUnknownCommand(mob, commands);
if(commands.size()<2)
{
mob.tell(L("mprun (user:password) [script]"));
return false;
}
commands.remove(0);
final String cmd = CMParms.combineQuoted(commands, 0);
executeScript(mob, cmd);
mob.tell(L("Completed."));
return false;
} |
008a19b6-9ee8-405c-a0e7-20a37fa360fa | 9 | public static void main(String[] args) {
// TODO code application logic here
boolean validar = true;
double valor1 = 0;
double valor2 = 0;
double resultado;
char continuar;
int opcion = 0;
Scanner teclado = new Scanner(System.in);
Operaciones_ aOperaciones_=new Operaciones_();
do {
System.out.println("Digite la operacion a evaluar ");
System.out.println("1.Suma ");
System.out.println("2.Resta ");
System.out.println("3.Division ");
System.out.println("4.Multiplicacion ");
System.out.println("5.Raiz ");
System.out.println("6.Potencia ");
opcion=Integer.parseInt(teclado.nextLine());
switch(opcion)
{ case 1:
System.out.println("Digite el valor del primer digito");
valor1=Double.parseDouble(teclado.nextLine());
System.out.println("Digite el valor del segundo digito");
valor2=Double.parseDouble(teclado.nextLine());
resultado=aOperaciones_.Sumar(valor1, valor2);
System.out.println(resultado);
break;
case 2:
System.out.println("Digite el valor del primer digito");
valor1=Double.parseDouble(teclado.nextLine());
System.out.println("Digite el valor del segundo digito");
valor2=Double.parseDouble(teclado.nextLine());
resultado=aOperaciones_.Resta(valor1,valor2);
System.out.println(resultado);
break;
case 3:
System.out.println("Digite el valor del primer digito");
valor1=Double.parseDouble(teclado.nextLine());
System.out.println("Digite el valor del segundo digito");
valor2=Double.parseDouble(teclado.nextLine());
resultado=aOperaciones_.divicion(valor1,valor2);
System.out.println(resultado);
break;
case 4:
System.out.println("Digite el valor del primer digito");
valor1=Double.parseDouble(teclado.nextLine());
System.out.println("Digite el valor del segundo digito");
valor2=Double.parseDouble(teclado.nextLine());
resultado=aOperaciones_.Multiplcacion(valor1,valor2);
System.out.println(resultado);
break;
case 5:
System.out.println("Digite el valor del primer digito");
valor1=Double.parseDouble(teclado.nextLine());
resultado=aOperaciones_.Raiz(valor1,valor2);
System.out.println(resultado);
break;
case 6:
System.out.println("Digite el valor del primer digito");
valor1=Double.parseDouble(teclado.nextLine());
System.out.println("Digite el valor del segundo digito");
valor2=Double.parseDouble(teclado.nextLine());
resultado=aOperaciones_.Potencia(valor1,valor2);
System.out.println(resultado);
break;
}
System.out.println("Desea continuar con otra operacion S/N ");
continuar = teclado.nextLine().charAt(0);
if ((continuar == 'S') || (continuar == 's')) {
validar = true;
} else {
validar = false;
}
} while (validar);
} |
cb0ca975-ce25-4465-b2ae-fcfdd9bc7296 | 5 | private boolean updateTime(Time oldTime, Time newTime) {
boolean saved = false;
try {
Connection conn = Dao.getConnection();
// Check that the fields are not null and that the duration is greater than 1 minute.
if (newTime.isFullFilled() && newTime.getDuration() >= MINIMUM_TIME_DURATION) {
int updateTime = timeDao.updateTime(conn, oldTime, newTime);
if (updateTime > 0) saved = true;
} else {
checkTimeFields(newTime);
}
} catch (SQLException ex) {
ErrorMessages.sqlExceptionError("updateTime()", ex);
} catch (ClassNotFoundException ex) {
ErrorMessages.classNotFoundError("updateTime()", ex);
}
return saved;
} |
2a5f382e-9d74-4f30-854e-107d568ab05d | 2 | public final static double roundIt(double number, double tick)
{
final String rounded = roundItAsString(number, tick);
try
{
if (rounded != null)
{
return Double.parseDouble(rounded);
}
else
{
// LOGGER.warn("roundItAsString returned null for {} and {}", number, tick);
}
}
catch (NumberFormatException e)
{
// LOGGER.warn("Failed to parse rounded value {} for number {} and tick {}: {}", new Object[] { rounded, number, tick, e });
}
return Double.NaN;
} |
79f51271-7746-4d32-ab3b-940bf311dc97 | 2 | Node findCycle() {
Node tortoise = this.next;
Node hare = this.next.next;
while(tortoise != hare) {
tortoise = tortoise.next;
hare = hare.next.next;
}
tortoise = this;
while(tortoise != hare) {
tortoise = tortoise.next;
hare = hare.next;
}
return tortoise;
} |
88d5e257-2ad4-4f98-9155-b6912be1d071 | 0 | @Test
public void testMain() throws Exception {
} |
b92fed2e-6d90-4f6e-a261-dbecba84dc60 | 4 | @Override
public boolean onCommand(CommandSender sender, Command cmd, String lable, String[] arg) {
if (cmd.getName().equalsIgnoreCase("hotstreak") || cmd.getName().equalsIgnoreCase("hs")) {
//If command sent from console
if (!(sender instanceof Player)) {
//Notify how to use console command
if (arg.length != 1) {
sender.sendMessage("Console usage: /"+cmd.getName()+" <username>");
}
//Get & Display hot streak streak
else {
int streak = HotStreakManager.get(arg[0]);
sender.sendMessage(prefix+arg[0]+" is on a hot streak of "+streak);
}
return true;
}
//Send hotstreak info to player.
int streak = HotStreakManager.get(sender.getName());
sender.sendMessage(prefix+"Your hot streak is "+streak);
}
return true;
} |
86d21946-2a0b-4fda-90b3-afb71376fdef | 4 | public void panic() {
for (int x = 0; x < width; x++) {
if (random.nextBoolean()) {
for (int y = 1; y < height; y++) {
if (get(x, y)) {
set(x, y - 1, true);
}
}
}
}
} |
b3da2e48-bff9-4186-8472-8f0e1d8f4dac | 2 | private Element getStockByIdentifier(String identifier) {
NodeList nl = doc.getDocumentElement().getElementsByTagName("stock");
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
if (e.getAttribute("identifier").equals(identifier)) {
return e;
}
}
return null;
} |
5678f2b5-792c-4a85-99eb-7118b7d250ad | 1 | public static void addSingleItemCentered(JComponent component, Container container) {
LayoutManager layout = container.getLayout();
component.setMaximumSize(component.getPreferredSize());
if (layout instanceof GridBagLayout) {
GridBagLayout gridbag = (GridBagLayout) layout;
c.weighty = 0;
c.weightx = 1;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
gridbag.setConstraints(component, c);
container.add(component);
} else {
Box box = Box.createHorizontalBox();
box.add(Box.createHorizontalGlue());
box.add(component);
box.add(Box.createHorizontalGlue());
container.add(box);
container.add(component);
}
} |
bb3fef40-36a7-4b81-a1f2-52369a252523 | 7 | public List<String> completeBrokenLimbNameSet(Environmental E)
{
final Vector<String> V=new Vector<String>();
if(!(E instanceof MOB))
return V;
final MOB M=(MOB)E;
final int[] limbs=M.charStats().getMyRace().bodyMask();
for(int i=0;i<limbs.length;i++)
{
if((limbs[i]>0)&&(validBrokens[i]))
{
if(limbs[i]==1)
V.addElement(Race.BODYPARTSTR[i].toLowerCase());
else
if(limbs[i]==2)
{
V.addElement("left "+Race.BODYPARTSTR[i].toLowerCase());
V.addElement("right "+Race.BODYPARTSTR[i].toLowerCase());
}
else
for(int ii=0;ii<limbs[i];ii++)
V.addElement(Race.BODYPARTSTR[i].toLowerCase());
}
}
return V;
} |
2baa8463-d08d-4114-ac67-f98efcc89b0d | 6 | @Override
public boolean createDataConnectionToInputPort(final String portName, LockPolicy lockPolicy, Object client) throws WrongPortTypeException{
OrocosDataPort port = getPort(portName);
if(port.getPortType() == PortType.OUTPUT_PORT){
throw new WrongPortTypeException(port.getPortType());
}
if(inputPortConnectionsMap.containsKey(portName) &&
inputPortConnectionsMap.get(portName).containsKey(client)){
return true;
}else{
try {
AbstractOrocosConnection connection = CorbaOrocosConnection.createDataConnection(port, lockPolicy);
// Store the connection into the hashmap
HashMap<Object, AbstractOrocosConnection> map;
// if a connection to the same port already exist extract the map,
// hotherwise create a new map
if(inputPortConnectionsMap.containsKey(portName)){
map = inputPortConnectionsMap.get(portName);
inputPortConnectionsMap.remove(portName);
}else{
map = new HashMap<Object, AbstractOrocosConnection>();
}
// add to the map the couple client/connection
map.put(client, connection);
// store the map in the input port connections map
inputPortConnectionsMap.put(portName, map);
return true;
} catch (CNoCorbaTransport e) {
logger.error("Error on the Corba Transport. See the exception stack trace.");
e.printStackTrace();
return false;
} catch (CNoSuchPortException e) {
logger.error("The port you required does not exist");
e.printStackTrace();
return false;
}
}
} |
b930c47c-b2e4-412c-901d-f92b1bec8073 | 9 | protected void send(RoomEvent event) {
if(event instanceof JoinEvent) {
if(((JoinEvent)event).getType()==JoinEvent.EVENT_JOIN) {
// we need to send a "Joined..." messahge to IRC and to the channel.
processEvent(new JoinEvent(this,JoinEvent.EVENT_JOIN,23,((JoinEvent)event).getName()));
processEvent(new ChatEvent(this,-1,"","*" + ((JoinEvent)event).getName() + " enters the room"));
if(_bJoined)
sendJoinInfo(((JoinEvent)event).getName());
} else {
// we need to send a "Joined..." messahge to IRC and to the channel.
//processEvent(new JoinEvent(this,JoinEvent.EVENT_LEAVE,22,((JoinEvent)event).getName()));
processEvent(new ChatEvent(this,-1,"","*" + ((JoinEvent)event).getName() + " leaves the room"));
if(_bJoined)
sendIRCCommand(new MessageCommand(_sChannel,"Left QRoom: " + ((JoinEvent)event).getName()));
}
} else if(event instanceof ChatEvent) {
processEvent((ChatEvent)event);
if(_bJoined) {
String name=((ChatEvent)event).getName();
if(name==null || name.equals(""))
sendIRCCommand(new MessageCommand(_sChannel,((ChatEvent)event).getText()));
else
sendIRCCommand(new MessageCommand(_sChannel,"{" + name + "} " + ((ChatEvent)event).getText()));
}
} else if(event instanceof SystemMessageEvent)
// these will always go back to users on QLink.
processEvent(event);
} |
75889c4c-b7d4-40c1-97e3-0311b04c0c42 | 3 | protected void write(String str)
{
if (!record_) {
return;
}
if (num_ == null || history_ == null)
{
// Creates the history or transactions of this Gridlet
newline_ = System.getProperty("line.separator");
num_ = new DecimalFormat("#0.00#"); // with 3 decimal spaces
history_ = new StringBuffer(1000);
history_.append("Time below denotes the simulation time.");
history_.append( System.getProperty("line.separator") );
history_.append("Time (sec) Description Gridlet #"+gridletID_);
history_.append( System.getProperty("line.separator") );
history_.append("------------------------------------------");
history_.append( System.getProperty("line.separator") );
history_.append( num_.format(GridSim.clock()) );
history_.append(" Creates Gridlet ID #" + gridletID_);
history_.append( System.getProperty("line.separator") );
}
history_.append( num_.format(GridSim.clock()) );
history_.append( " " + str + newline_);
} |
d202b19b-214a-4c7e-ab49-a40cfba028ae | 7 | private void createThreeSliders() {
if (triSliderPanel != null)
return;
triSliderPanel = new JPanel(new SpringLayout());
String s = MolecularContainer.getInternationalText("XComponent");
xSlider = createSlider(originalVector == null ? 0 : originalVector.x, s != null ? s : "x-component");
triSliderPanel.add(createSliderButtonPanel(xSlider));
s = MolecularContainer.getInternationalText("YComponent");
ySlider = createSlider(originalVector == null ? 0 : originalVector.y, s != null ? s : "y-component");
triSliderPanel.add(createSliderButtonPanel(ySlider));
s = MolecularContainer.getInternationalText("ZComponent");
zSlider = createSlider(originalVector == null ? 0 : originalVector.z, s != null ? s : "z-component");
triSliderPanel.add(createSliderButtonPanel(zSlider));
ModelerUtilities.makeCompactGrid(triSliderPanel, 3, 1, 5, 5, 10, 2);
} |
18024fe2-07da-4317-9895-0b2a8e848c7c | 3 | public static Configuration fromFile(String filename) {
Configuration c = null;
InputStream i = null;
try {
Properties prop = new Properties();
i = new FileInputStream(filename);
prop.load(i);
String picname = prop.getProperty("picname");
int xSteps = Integer.parseInt(prop.getProperty("xsteps"));
int ySteps = Integer.parseInt(prop.getProperty("ysteps"));
int colorSteps = Integer.parseInt(prop.getProperty("colorsteps"));
int alphaSteps = Integer.parseInt(prop.getProperty("alphasteps"));
int maxTriangles = Integer.parseInt(prop.getProperty("maxtriangles"));
c = new Configuration(picname, xSteps, ySteps, colorSteps, alphaSteps, maxTriangles);
} catch (Exception ex) {
Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (i != null) {
try {
i.close();
} catch (IOException e) {
Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, e);
}
}
}
return c;
} |
e10fcb63-fcb9-4101-8162-6fc3e18b6cfe | 2 | @POST
@Path("/v2.0/networks")
@Produces(MediaType.APPLICATION_JSON)
public Response createNetwork(final String request) throws MalformedURLException, IOException{
//Convert input object NetworkData into a String like a Json text
Object net;
net = JsonUtility.fromResponseStringToObject(request,ExtendedNetwork.class);
String input = JsonUtility.toJsonString(net);
System.out.println(input);
//Connect to a REST service
HttpURLConnection conn=HTTPConnector.HTTPConnect(new URL(this.URLpath), OpenstackNetProxyConstants.HTTP_METHOD_POST, input);
//Get the response text from the REST service
String response=HTTPConnector.printStream(conn);
Object result;
if(response.equals("Multiple created")) result=response;
else result=(ExtendedNetwork) JsonUtility.fromResponseStringToObject(response, ExtendedNetwork.class);
int responseCode=conn.getResponseCode();
HTTPConnector.HTTPDisconnect(conn);
//Insert data into the Knowledge Base
if (responseCode==201){
// ExtendedNetwork n=(ExtendedNetwork)result;
// if(n.getNetworks()==null)NetworkOntology.insertExtendedNetwork(n, null);
// else NetworkOntology.insertMultipleExtendedNetworks(n);
}
//Build the response
return Response.ok().status(responseCode).header("Access-Control-Allow-Origin", "*").entity(result).build();
} |
7e548e44-e1fa-4a94-8cf9-91542bfa0b86 | 0 | public boolean isAce() {
return value == 1;
} |
5c28f46f-1a1c-4ec8-ad96-5bff0f402d22 | 7 | public static void main(String args[]){
BufferedReader br = null;
try{
String cLine[];
br = new BufferedReader(new FileReader("graph.txt"));
int nodeNum = Integer.parseInt(br.readLine());
int edgeNum = Integer.parseInt(br.readLine());
//Initialize the vertices
for(int i = 0;i < nodeNum;i++){
edges.add(new ArrayList<Integer>());
reversedEdges.add(new ArrayList<Integer>());
}
//Verify our amounts are correct
System.out.println("We have " + nodeNum + " vertices and " + edgeNum + " edges");
//Read in the edges and put them into the array
for(int i = 0;i < edgeNum;i++){
String line = br.readLine();
//line = line.substring(1);
//System.out.println(line);
cLine = line.split("\\s+");
int n1 = Integer.parseInt(cLine[0]);
int n2 = Integer.parseInt(cLine[1]);
//Add the newly created edge to edges and reversedEdges
edges.get(n1).add(n2);
reversedEdges.get(n2).add(n1);
//System.out.println("Reading in line "+i);
}
//Run Depth First Order in numerical order on the reversed digraph
for(int i = 0;i < nodeNum;i++){
depthFirstOrder(i);
}
//Reverse the node ordering ArrayList Obtained
Collections.reverse(nodeOrdering);
//for(int i:nodeOrdering){System.out.print(i+" ");}
System.out.println("");
//Clear visited since it will be used again for DFS
visitedNodes.clear();
int count = 1;
//Now we can DFS based on the Reverse Post Order of the Reversed Di-Graph
for(int i:nodeOrdering){
//Don't want to redo a kernel that we've already visited so we need to make sure that
//anything already visited won't be visited again
if(!visitedNodes.contains(i)){
//Call DFS from the next unchecked node in the reverse Post Order node list
depthFirstSearch(i);
System.out.print("Kernel #"+count+" contains nodes: ");
for(int j:kernel){System.out.print(j+" ");}
System.out.print("\n");
count++;
//Clear the kernel so we can build it again in the next iteration
kernel.clear();
}
}
}catch (IOException e){
System.out.println("IO ERROR: Check Input and Program");
}
} |
cc9e9c1d-af90-4aaa-a764-cd60d9a3901e | 7 | public static void makeCompactGrid(Container parent,
int rows, int cols,
int initialX, int initialY,
int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout)parent.getLayout();
} catch (ClassCastException exc) {
System.err.println("The first argument to makeCompactGrid must use SpringLayout.");
return;
}
//Align all cells in each column and make them the same width.
Spring x = Spring.constant(initialX);
for (int c = 0; c < cols; c++) {
Spring width = Spring.constant(0);
for (int r = 0; r < rows; r++) {
width = Spring.max(width,
getConstraintsForCell(r, c, parent, cols).
getWidth());
}
for (int r = 0; r < rows; r++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setX(x);
constraints.setWidth(width);
}
x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
}
//Align all cells in each row and make them the same height.
Spring y = Spring.constant(initialY);
for (int r = 0; r < rows; r++) {
Spring height = Spring.constant(0);
for (int c = 0; c < cols; c++) {
height = Spring.max(height,
getConstraintsForCell(r, c, parent, cols).
getHeight());
}
for (int c = 0; c < cols; c++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setY(y);
constraints.setHeight(height);
}
y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
}
//Set the parent's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH, y);
pCons.setConstraint(SpringLayout.EAST, x);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.