method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
8f6b35fe-e35d-41de-a444-6ad75442f42e | 7 | public static void TH() throws IOException{
int timeblock = 5;
BufferedReader r = new BufferedReader (new InputStreamReader(System.in));
while (timeblock > 0){
System.out.println("What would you like to do right now?");
if (timeblock > 3)
{
System.out.println("1. Go to class (not likely)");
System.out.println("2. Go workout at the Gym");
System.out.println("3. Play games at home");
System.out.println("4. Sleep (what you always do anyways)");
System.out.println("Damon would like to choose option: ");
int choice = DamonTools.validInput(Integer.parseInt(r.readLine()), 4, 1);
if (choice == 1){
DamonStats.Knowledge ++;
DamonActions.CLASS();
}
else if (choice == 2)
DamonActions.Gym();
else if (choice == 3)
{
DamonActions.GAMING();
}
else {
System.out.println("Damon slept through the day. He did not get to do anything.");
timeblock = 0;
}
timeblock -= 1;
}
else
{
System.out.println("1. Go workout at the Gym");
System.out.println("2. Play games at home");
System.out.println("3. Sleep (what you always do anyways)");
int choice = DamonTools.validInput(Integer.parseInt(r.readLine()), 3, 1);
if (choice == 1)
{
DamonActions.Gym();
}
else if (choice == 2)
{
DamonActions.GAMING();
}
else {
System.out.println("Damon slept through the day. He did not get to do anything.");
timeblock = 0;
}
}
timeblock -= 1;
}
} |
0882bfee-fff5-4bbb-b0df-c9b38d1909f7 | 9 | public static CypherType arrayToType(double[] array)
{
CypherType type = null;
if (array[0] == 1 && array[1] == 0 && array[2] == 0)
type = CypherType.PLAIN_TEXT;
else if (array[0] == 0 && array[1] == 1 && array[2] == 0)
type = CypherType.MONO_ALPHABETIC;
else if (array[0] == 0 && array[1] == 0 && array[2] == 1)
type = CypherType.POLY_ALPHABETIC;
return type;
} |
7ea3b35f-fa25-4cb7-a14c-8fd91ebdd9e5 | 5 | public static List<Player> getOnlinePlayers() {
List<Player> onlinePlayers = new ArrayList<Player>();
try {
Method onlinePlayersMethod = Bukkit.class.getMethod("getOnlinePlayers");
if (onlinePlayersMethod.getReturnType().equals(Collection.class)) {
Collection<Player> playerCollection = (Collection<Player>) onlinePlayersMethod.invoke(null, new Object[0]);
if (playerCollection instanceof List) {
onlinePlayers = (List<Player>) playerCollection;
} else {
onlinePlayers = new ArrayList<Player>(playerCollection);
}
} else {
onlinePlayers = Arrays.asList((Player[]) onlinePlayersMethod.invoke(null, new Object[0]));
}
} catch (NoSuchMethodException ignored) {
} catch (InvocationTargetException ignored) {
} catch (IllegalAccessException ignored) {
}
return onlinePlayers;
} |
0f0aa129-7688-4ad9-92d8-f04cec4b3640 | 2 | @Override
public int getIndex(String name) {
for (int i=0;i<=attsList.size();i++)
if (name.equalsIgnoreCase(attsList.get(i).getName())) return i;
return -1;
} |
65c9b0d7-20bc-458e-9d02-7f4d67606b1b | 4 | @Override
public <T extends AggregateRoot<?>> T loadOneBy(final Class<T> aggregateRoot, final Specification<T> specification) {
@SuppressWarnings("unchecked")
final DomainRepositoryDriver<T, ?> driver = (DomainRepositoryDriver<T, ?>) drivers.get(aggregateRoot);
if (driver == null) {
throw new RuntimeException("Can't find any driver for the given aggregate: " + aggregateRoot);
}
return driver.loadOneBySpecification(specification);
} |
ff75674b-2d0e-4e17-b10f-fa3c0b771256 | 9 | public ArrayList<Integer> postorderTraversal(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<Integer> res = new ArrayList<Integer>();
if (root == null)
return res;
Stack<TreeNode> path = new Stack<TreeNode>();
TreeNode prev = null, cur;
path.push(root);
while (!path.isEmpty()) {
cur = path.peek();
if (prev == null || prev.left == cur || prev.right == cur) {
if (cur.left != null)
path.push(cur.left);
else if (cur.right != null)
path.push(cur.right);
} else if (cur.left == prev) {
if (cur.right != null)
path.push(cur.right);
} else {
res.add(cur.val);
path.pop();
}
prev = cur;
}
return res;
} |
cc0d2809-45b5-487e-bb28-1d8617ec63d0 | 0 | public Dimension getCurrentAvailableSpace() {
return new Dimension(getParent().getWidth(), getParent().getHeight());
} |
8de06340-0d18-4631-9a22-cd0c97423be4 | 4 | @Override
protected void leave() {
// Find north most door
final GameObject door = ctx.objects.select().select(ObjectDefinition.name(ctx, "Door")).within(15).sort(new Comparator<GameObject>() {
@Override
public int compare(GameObject o1, GameObject o2) {
return Integer.valueOf(o2.tile().y()).compareTo(o1.tile().y());
}
}).each(Interactive.doSetBounds(OSTutorialIsland.BOUNDS_DOOR_EW)).poll();
if (ctx.camera.prepare(door) && npc().valid() && door.click("Open")) {
Condition.sleep(1000);
if (Condition.wait(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return ctx.chat.visible("Now, how about showing some feelings?");
}
}, 200, 40)) {
Condition.sleep(500);
}
}
} |
711d1c6b-d9a5-4db7-a2e6-658071ebf3a3 | 1 | public static void printDocument(Document doc) {
OutputFormat format = OutputFormat.createPrettyPrint();
try {
XMLWriter writer = new XMLWriter(System.out, format);
writer.write(doc);
} catch (Exception e) {
System.err.println("Error while trying to print: " + e.getMessage());
e.printStackTrace();
}
} |
ab1b9ac1-db1b-449f-b644-e7e8c4ff903d | 4 | public void saveHistogram(String path) {
try {
if(path == null)
path = "histogram.csv";
File file = new File("histogram.csv");
file.createNewFile();
FileWriter fileW = new FileWriter(file);
BufferedWriter buffW = new BufferedWriter(fileW);
buffW.write("Grayscale");
for(int i = 0; i < histogram.length; ++i)
buffW.write(";" + i);
buffW.write("\n");
buffW.write("Intensity");
for(int i = 0; i < histogram.length; ++i)
buffW.write(";" + histogram[i]);
buffW.close();
fileW.close();
} catch (IOException e) {
e.printStackTrace();
}
} |
51db5433-9a34-4a9d-bd44-42bfe1c9be19 | 9 | public static void CheckServerMessages(String message){
newestreply = OtherStuff.LatestServerReply();
if(newestreply.startsWith("YouGotkickednr")){
OtherStuff.CloseAllWindows();
JOptionPane.showMessageDialog(null, "Kicked by Server");
System.exit(0);
}
else if(message.startsWith("YouGotkicked")){
String [] kickreason = message.split(" ");
OtherStuff.CloseAllWindows();
if(kickreason.length == 1){
JOptionPane.showMessageDialog(null, "Kicked by Server");
}else if(kickreason.length == 2){
JOptionPane.showMessageDialog(null, "Kicked by Server. Reason: " + kickreason[1]);
}else{
JOptionPane.showMessageDialog(null, "Kicked by Server");
}
System.exit(0);
}
else if(message.startsWith("ServerIsShuttingDown")){
try {
Client.socket.close();
} catch (IOException e){
e.printStackTrace();
}
reconnecting = true;
}
else if(message.startsWith("broadcast")){
if(ConsoleWindow.ircon == true){
String [] broadcaststring = message.split(" ");
ConsoleWindow.TextArea1.append(OtherStuff.TheNormalTime() + broadcaststring[1].replace("_", " ").replace("broadcast", "").toString() + "\n");
ConsoleWindow.TextArea1.setCaretPosition(ConsoleWindow.TextArea1.getDocument().getLength());
}
}
else if(message.contains("You are connected to the TFrame Server")){
reconnecting = false;
Client.IsConnectedToServer = true;
}
} |
936b0581-0e73-428c-a6d0-142b56c56567 | 0 | public AppTest(String testName) {
super(testName);
} |
bceea19e-44a6-4e2d-96a5-32cbd71721fe | 8 | protected boolean processOtherEvent(Sim_event ev)
{
boolean result = true;
switch ( ev.get_tag() )
{
//-----------REPLICA MANAGER REQUESTS--------
case DataGridTags.CTLG_ADD_MASTER:
processAddMaster(ev);
break;
case DataGridTags.CTLG_DELETE_MASTER:
processDeleteMaster(ev);
break;
case DataGridTags.CTLG_ADD_REPLICA:
processAddReplica(ev);
break;
case DataGridTags.CTLG_DELETE_REPLICA:
processDeleteReplica(ev);
break;
//-------USER REQUESTS---------------
case DataGridTags.CTLG_GET_FILE_ATTR:
processFileAttrRequest(ev);
break;
case DataGridTags.CTLG_GET_REPLICA:
processGetReplica(ev);
break;
case DataGridTags.CTLG_GET_REPLICA_LIST:
processGetReplicaList(ev);
break;
case DataGridTags.CTLG_FILTER:
processFilterFiles(ev);
break;
default:
System.out.println(super.get_name() +
".processOtherEvent(): Warning - unknown tag = "+ev.get_tag());
result = false;
break;
}
return result;
} |
1155f916-a9d1-45ea-96b9-65fd7bae42d8 | 3 | public int getLowestY()
{
int y = a[1];
if(b[1] < y)
{
y = b[1];
}
if(c[1] < y)
{
y = c[1];
}
if(d[1] < y)
{
y = d[1];
}
return(y);
} |
29782cf6-1aff-49ad-90d6-98ad74385a9f | 5 | public void run() {
if (ItemCount > 0) {
for (int i = 0; i < ItemCount; i++) {
try {
stack.push(temp.get(i));
} catch (InterruptedException ex) {
Logger.getLogger(TestingThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else {
try {
System.out.println("Thread " + ThreadID.get() + " : " + stack.pop().toString());
} catch (EmptyException ex) {
Logger.getLogger(TestingThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(TestingThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
} |
9c9ab1a9-6431-4f10-b647-0f39aa7382c4 | 1 | public void feedFood(int index)
{
FoodObject food = Food.getFood(index);
if (!canAfford(food.getPrice()))
return;
hunger += food.getAmount();
// money -= food.getMoney();
// "Purchased" + food.getName();
// TODO Add Food on the screen.
// TODO adding hunger is placeholder
} |
77c94dbc-7f02-4ead-86ea-2e1bcaabef34 | 2 | public int getInt(String key, int def) {
if(fconfig.contains(key)) {
return fconfig.getInt(key);
}
else {
fconfig.set(key, def);
try { fconfig.save(path); } catch (IOException e) { e.printStackTrace(); }
return def;
}
} |
70f3e95f-c7c6-4594-9972-ff10cca15866 | 7 | private boolean searchUpForNextSubsetNode( Node node, K key, Object[] ret ) {
if( node.mRight != null && mComp.compareMinToMax( node.mKey, key ) < 0 &&
mComp.compareMinToMax( key, node.mRight.mMaxStop.mKey ) < 0 )
{
// Request downard search on right subtree.
ret[0] = node.mRight;
return false;
}
while( node.mParent != null ) {
if( node == node.mParent.mRight ) {
node = node.mParent;
} else {
node = node.mParent;
// If we're coming from the left path, it means we haven't
// checked the
// current node or right subtree.
// We'd would never search to the left of a node that started
// before the mKey,
// so don't bother checking mins.
if( mComp.compareMaxes( key, node.mKey ) >= 0 ) {
ret[0] = node;
return true;
}
// Check if the right node might be contained.
if( node.mRight != null ) {
ret[0] = node.mRight;
return false;
}
}
}
// Search is complete.
ret[0] = null;
return true;
} |
b1c14ea1-d5ff-4e10-a78f-c4bcbfc82c7e | 2 | @Override
public void onDisable()
{
saveConfig();
if (thread != null && thread.isRunning())
{
//Disable thread
thread.setRunning(false);
}
else
{
}
} |
b6722369-978d-401b-995d-02e95ef122f7 | 5 | public static void main(String[] args) throws IOException {
AuthenticationServer server = null;
try {
Options options = new Options();
options.addOption("sp", true, "security package");
options.addOption("p", true, "server port");
options.addOption("h", false, "print this message");
CommandLine cmd = new PosixParser().parse(options, args);
if (cmd.hasOption("h") || !(cmd.hasOption("sp") && cmd.hasOption("p"))) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("server", options);
System.exit(0);
}
int port = Integer.parseInt(cmd.getOptionValue("p"));
server = new AuthenticationServer(port, cmd.getOptionValue("sp"));
server.bootstrap();
System.in.read();
} catch (ParseException e) {
e.printStackTrace();
} finally {
if (server != null) {
server.shutdown();
}
}
} |
e9a6eea7-7877-4ffe-8ae1-3a7d82284267 | 9 | private int findDirectionOfSquare(int x, int y, int[][] path) { // grid system
int sq2 = path[x][y] + 1;
try {
if (y > 0) if (sq2 == path[x][y - 1]) return NORTH;
if (x < getColumns() - 1) if (sq2 == path[x + 1][y]) return EAST;
if (y < getRows() - 1) if (sq2 == path[x][y + 1]) return SOUTH;
if (x > 0) if (sq2 == path[x - 1][y]) return WEST;
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
return -1;
} |
99d0486f-8ff4-424d-a62a-c5351ec111ba | 6 | public void multiSpellEffectNPC(int npcId, int damage) {
switch(c.MAGIC_SPELLS[c.oldSpellId][0]) {
case 12919: // blood spells
case 12929:
int heal = (int)(damage / 4);
if(c.constitution + heal >= c.maxConstitution)
c.constitution = c.maxConstitution;
else
c.constitution += heal;
break;
case 12891:
case 12881:
if (Server.npcHandler.npcs[npcId].freezeTimer == 0) {
Server.npcHandler.npcs[npcId].freezeTimer = getFreezeTime();
}
break;
}
} |
83633602-7bd1-4501-8d43-91fe663eac33 | 3 | public synchronized void stop() {
if (thread == null) {
return;
}
running = false;
if (server != null) {
try {
server.close();
} catch (Exception e) { }
}
thread = null;
} |
fc9e0e3d-6225-43dc-9cf7-e0cd07215541 | 0 | @Override
public boolean supportsEditability() {return true;} |
c9349e61-cb75-4e37-8329-cd73a76c05b8 | 2 | public static boolean howHardCanItBe(){
for (final String word : words) {
if( wordValidator.wordContainsLettersInOrder(letGen, word) ) {
return true;
}
}
return false;
} |
381b3c15-524b-4857-a832-3953325cd14e | 1 | public void processRequest(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
FrontCommand command;
try {
command = getCommand(req);
command.init(getServletContext(), req, res);
command.process();
} catch (Exception e) {
e.printStackTrace();
}
} |
fd504161-8727-4cd2-961c-2fe5716dd007 | 9 | private static char ConvertToChar(int num)
{
char letter = '0';
switch(num)
{
case 1:
letter = '1';
break;
case 2:
letter = '2';
break;
case 3:
letter = '3';
break;
case 4:
letter = '4';
break;
case 5:
letter = '5';
break;
case 6:
letter = '6';
break;
case 7:
letter = '7';
break;
case 8:
letter = '8';
break;
case 9:
letter = '9';
break;
}
return letter;
} |
965f6d18-84e8-40af-b5a8-bf4cb448bfaf | 1 | public boolean changeUserName(String oldName, String newName){
if (users.get(newName.toLowerCase())!=null) return false;
UserAccount account = users.remove(oldName.toLowerCase());
account.setName(newName);
users.put(newName.toLowerCase(), account);
return true;
} |
52d4245f-6469-486e-bfcb-c397c04bb688 | 4 | public void upload(UploadedFile uploadedFile, String fileName) throws IOException, NotCreatedDirException {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
// save file on disk
inputStream = uploadedFile.getInputStream();
File newFile = new File(path + "poms/" + fileName + ".xml");
if (!newFile.exists()) {
newFile.createNewFile();
}
outputStream = new FileOutputStream(newFile);
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} |
77a6c2ce-1622-4d6e-b132-7e2f90a2737b | 6 | public void keyTyped(KeyEvent e) {
if(open) {
switch(e.getKeyCode()) {
case KeyEvent.VK_ESCAPE:
case KeyEvent.VK_ENTER:
break;
case KeyEvent.VK_BACK_SPACE:
if(typing.length() > 0)
typing = typing.substring(0, typing.length()-1);
break;
default:
if(typing.length() < MAX_INPUT_LENGTH)
typing += e.getKeyChar();
break;
}
}
} |
2def5cc2-608a-4452-8419-9f602bdb5d9c | 7 | public void deleteComponent(Component com) {
if(com == null) {
return;
}
((ContactItem)com).deleteContactItem();
Component cm = hd;
while(cm != null) {
if(cm == com) {
if(com == hd) {
hd = hd.next;
if(hd == null) {
selected = null;
break;
}
hd.prev = com.prev;
break;
}
if(cm.prev != null) {
cm.prev.next = cm.next;
}
if(cm.next != null) {
cm.next.prev = cm.prev;
}
else {
hd.prev = cm.prev;
}
break;
}
cm = cm.next;
}
yaxisAssigned = false;
scrollBarAttached = false;
} |
e9ac477b-a418-4d42-9eb4-ff1e41f5e4ef | 9 | private void processResp(OMMItemEvent event)
{
OMMMsg msg = event.getMsg();
Token token = (Token)event.getClosure();
// we need to set dictionary in case we reencode FieldList
Handle handle = (Handle)_reqMap.get(token);
// this can happen, when the dictionary stream is close or dictionary
// has been changed
// we have still have response msgs in the queue, we will discard this
// response
if (handle == null)
return;
HandleEntry he = _itemGroupManager.getHandleEntry(handle);
// item is not in the watchlist
if (he == null)
return;
FieldDictionary dictionary = _parent.getDictionaryManager().getDictionary(he.serviceName);
OMMMsgReencoder.setLocalDictionary(dictionary);
// Refresh will always provide group id
// Status response can contain group id
if ((msg.getMsgType() == OMMMsg.MsgType.REFRESH_RESP)
|| (msg.getMsgType() == OMMMsg.MsgType.STATUS_RESP && msg
.has(OMMMsg.HAS_ITEM_GROUP)))
{
OMMItemGroup group = msg.getItemGroup();
Handle itemHandle = event.getHandle();
_itemGroupManager.applyGroup(itemHandle, group);
}
else if (msg.getMsgType() == OMMMsg.MsgType.GENERIC)
{
System.out.println("Received generic message type, not supported. ");
}
if (msg.isFinal())
{
_itemGroupManager.removeItem(handle);
System.out.println(_instanceName + " Received stream closed. Remove " + handle);
}
boolean growEncoderFlag = false;
int encoderSize = msg.getEncodedLength() + 100;
do
{
try
{
_providerServer.submitResp(msg, token, encoderSize);
growEncoderFlag = false;
}
catch (IndexOutOfBoundsException e)
{
// Not enough room, need to grow the encoderSize and try submit
// again.
growEncoderFlag = true;
encoderSize = (int)(encoderSize * 1.1);
}
}
while (growEncoderFlag);
} |
1e439fcf-6237-4add-90e2-64f75061064d | 3 | private int[] getAround(int[][] temp, int x, int y) {
int[] around = new int[9];
int i = 0;
for(int xLoop = x-1; xLoop <= x+1; xLoop++) {
for(int yLoop = y-1; yLoop <= y+1; yLoop++) {
around[i] = validPosition(temp, xLoop, yLoop) ? temp[xLoop][yLoop] : USED;
i++;
}
}
return around;
} |
36057014-7542-4a5c-8590-c82baba2ff8a | 1 | @Test
public void testSecondUp()
{
Model model = new Model();
Time realTime, expectedTime;
realTime = new Time(0,1,53);
expectedTime = new Time(0,2,3);
model.setTime(realTime);
for (int i=0;i<10;i++)
{
model.secondUp();
}
assertEquals(expectedTime, model.getTime());
} |
77b9208e-cf37-4eac-8bcc-e6d5eff4fa5b | 9 | public String toString() {
StringBuilderOutputSource sb = new StringBuilderOutputSource(new StringBuilder());
for (int i = 0; i < path.length; i+=2) {
Object key = path[i];
if (key == null) {
sb.append("[null]");
} else if (key instanceof Number) {
sb.append('[');
sb.append(key.toString());
sb.append(']');
} else if (key instanceof Character) {
sb.append(key.toString());
} else {
String str = key.toString();
boolean escape = false;
for (int j = 0; j < str.length(); j++) {
if (j == 0) {
escape = !Character.isJavaIdentifierStart(str.charAt(j));
} else {
escape = !Character.isJavaIdentifierPart(str.charAt(j));
}
if (escape) break;
}
if (escape) {
sb.append('[');
try {
StringFormatter.serialize(this, str, sb);
} catch (Exception e) {
// no handle
}
sb.append(']');
} else {
sb.append('.');
sb.append(str);
}
}
}
return sb.toString();
} |
d36883fa-22cc-40c1-bed3-4571254d3923 | 5 | private void putRequest(HttpExchange he) throws IOException {
try {
InputStreamReader isr = new InputStreamReader(he.getRequestBody(), "UTF-8");
BufferedReader br = new BufferedReader(isr);
String jsonInput = br.readLine();
long roleId = parseRoleId(jsonInput);
String path = he.getRequestURI().getPath();
int lastIndex = path.lastIndexOf("/");
if (lastIndex > 0 && jsonInput.toLowerCase().contains("unassign")) { // unassigning happens here
int id = Integer.parseInt(path.substring(lastIndex + 1));
Course editedCourse = facade.unassignRoleSchoolFromCourse(roleId, id);
response = trans.toJson(editedCourse);
status = 200;
} else if (lastIndex > 0 && jsonInput.toLowerCase().contains("assign")) { // assigning happens here
int id = Integer.parseInt(path.substring(lastIndex + 1));
Course editedCourse = facade.assignRoleSchoolToCourse(roleId, id);
response = trans.toJson(editedCourse);
status = 200;
} else {
status = 400;
response = "no id";
}
} catch (NumberFormatException nfe) {
response = "id is not a number";
status = 404;
}
} |
bdd6aa62-5a9b-49a8-bebe-2f02a5f0d329 | 2 | public void setModel(PlotModel model) {
surfacePanel.setModel(model.getModel());
setLayout(new BorderLayout());
task = model.getModel().plot();
surfacePanel.setBackground(Color.white);
surfacePanel.setConfigurationVisible(true);
add(surfacePanel, BorderLayout.CENTER);
final Projector projector = surfacePanel.getSurface().getModel().getProjector();
surfacePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK), "Save");
surfacePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "Up");
surfacePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "Down");
surfacePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "Right");
surfacePanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "Left");
surfacePanel.getActionMap().put("Save",
new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
try {
File file = OpenFileHelper.open(null);
if (file.exists()) {
file = new File(file.getAbsolutePath());
}
surfacePanel.getSurface().doExportPNG(file);
} catch (IOException | NullPointerException ex) {
logger.error(ex);
}
}
});
surfacePanel.getActionMap().put("Up",
new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
float newAngle = projector.getElevationAngle() + DEFAULT_ANGLE_STEP;
projector.setElevationAngle(newAngle);
repaint();
}
});
surfacePanel.getActionMap().put("Down",
new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
float newAngle = projector.getElevationAngle() - DEFAULT_ANGLE_STEP;
projector.setElevationAngle(newAngle);
repaint();
}
});
surfacePanel.getActionMap().put("Right",
new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
float newAngle = projector.getRotationAngle() + DEFAULT_ANGLE_STEP;
projector.setRotationAngle(newAngle);
repaint();
}
});
surfacePanel.getActionMap().put("Left",
new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
float newAngle = projector.getRotationAngle() - DEFAULT_ANGLE_STEP;
projector.setRotationAngle(newAngle);
repaint();
}
});
} |
3df09aa8-cd2f-490c-b3cc-94a78685103d | 5 | @Override
public void run() {
try {
serversocket = new ServerSocket(port);
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "Failed to run serversocket.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
while (breakflag == false) {
try {
client = serversocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter writer = new PrintWriter(client.getOutputStream(), true);
//String line = reader.readLine();
//textField.append(line + "\r\n");
String line = reader.readLine();
while(line != null) {
textField.append(line + "\r\n");
line = reader.readLine();
}
writer.close();
reader.close();
client.close();
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "Server closed.", "Alert", JOptionPane.WARNING_MESSAGE);
return;
}
}
breakflag = false;
try {
serversocket.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Failed to stop serversocket.", "Error", JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(null, "Break.", "Alert", JOptionPane.WARNING_MESSAGE);
return;
} |
6002a9bd-c38a-4987-8cff-3bf16b55bc6e | 0 | public String getSno() {
return this.sno;
} |
b18ea7b0-0fb8-4b2c-b78a-4322f184ae50 | 8 | public Humain rencontre(Humain h) {
Humain b;
loterie = new Random();
if (h instanceof Homme)
return null;
if (h.age > 15 && h.age < 50 && age > 15) {
if (poids > 150 || h.poids > 150) {
return null;
} else {
int f = loterie.nextInt(100);
if (f > ((Femme) h).getFertilite())
return null;
int p = loterie.nextInt(100);
if (p < 50)
b = new Homme("toto");
else
b = new Femme("titi");
int g = loterie.nextInt(20) - 10;
grossir(g);
((Femme) h).setNbBebe(1);
}
} else
return null;
return b;
} |
dbf0c133-4f3a-4d37-a335-f01513212044 | 5 | public static Iterable<Direction> solve(State state)
{
State boxToGoal;
int px = state.player.x;
int py = state.player.y;
ArrayList<Position> possiblePlayerPositions = possibleStartPositions(state);
for (Position player : possiblePlayerPositions)
{
boxToGoal = Search.findBoxPath(state, player.x, player.y);
if (boxToGoal != null){
Search.Result result = Search.bfs(boxToGoal, new IsAtPosition(px, py), boxToGoal.player.x, boxToGoal.player.y);
if(result != null){
Collections.reverse(result.path);
ArrayList<Direction> toReturn = Search.getPlayerPath(boxToGoal);
toReturn.addAll(result.path);
Collections.reverse(toReturn);
return toReturn;
}
else
{
if (Main.DEBUG)
{
System.err.println("No path back");
}
}
}
else
{
if (Main.DEBUG)
{
System.err.println("No solution" + state.playerEndPos);
}
}
}
return null;
} |
7cedb517-10ec-43ae-a329-9ffb1f6e7647 | 6 | public boolean isFinished() {
boolean retBoo = false;
for (int i = 0; i < 6; i++) {
if (board.get(i) > 0)
break;
else if (i == 5)
retBoo = true;
}
for (int x = 7; x < 13; x++) {
if (board.get(x) > 0)
break;
else if (x == 12)
retBoo = true;
}
return retBoo;
} |
e90e53c1-3d9e-49c7-9d68-96a354639fc1 | 9 | @Override public void paintComponent(Graphics g2) {
Graphics2D g = (Graphics2D) g2; // Create Graphics Object
super.paintComponent(g); // Paint Background
// Get the size of the x path vectors
int size_of_xpath = xPath.size();
// Create array of integers
int[] xPoints = new int[size_of_xpath];
int[] yPoints = new int[size_of_xpath];
// Add Vector Elements to the Array
for (int j = 0; j < size_of_xpath; j++)
{
xPoints[j] = xPath.elementAt(j);
yPoints[j] = yPath.elementAt(j);
}
//create polygon
Polygon poly = new Polygon(xPoints, yPoints, size_of_xpath);
//move polygon to centre of JPanel
poly.translate(thickness/2, thickness/2);
if (fill==true)
{
if(fill_type<=0 || fill_type>=3)//if fill is not range
{
fill_type = 1;
}
else
{
if(fill_type==1)
{
Color fillC = new Color(fillColor);
g.setPaint(fillC);//Colour main body
}
else if(fill_type==2)
{
Color grad_color1 = new Color(color1);
Color grad_color2 = new Color(color2);
//gradient
GradientPaint fillcol = new GradientPaint(x_at_color1, y_at_color1,
grad_color1, x_at_color2, y_at_color2,
grad_color2, is_cyclic);
g.setPaint(fillcol);//Gradient main body
}
if(alpha>=0 & alpha<=1)
{
g.setComposite(AlphaComposite.getInstance
(AlphaComposite.SRC_OVER, (float)alpha));
}
g.fill(poly); //create main body
}
}
if(thickness!=0)
{
Color lineC = new Color(lineColor);
//set edge thickness
BasicStroke edgeThickness = new BasicStroke(thickness,
BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND);
g.setStroke(edgeThickness); //set line thickness
g.setPaint(lineC); //Colour line
if(alpha>=0 & alpha<=1)
{
g.setComposite(AlphaComposite.getInstance
(AlphaComposite.SRC_OVER, (float)alpha));
}
g.drawPolygon(poly); //create line round shape
}
} |
ae8d2a88-ba92-470b-8291-dac1e13fad16 | 0 | public boolean isProgressive()
{
return progressive;
} |
179f9f84-3712-48ba-8751-31d57aacea31 | 7 | private String startSetToString() {
StringBuffer FString = new StringBuffer();
boolean didPrint;
if (m_starting == null) {
return getStartSet();
}
for (int i = 0; i < m_starting.length; i++) {
didPrint = false;
if ((m_hasClass == false) ||
(m_hasClass == true && i != m_classIndex)) {
FString.append((m_starting[i] + 1));
didPrint = true;
}
if (i == (m_starting.length - 1)) {
FString.append("");
}
else {
if (didPrint) {
FString.append(",");
}
}
}
return FString.toString();
} |
7765354f-78ce-4bd9-add1-f4c8a10a1847 | 0 | public String getToolTip() {
return "Transition Creator";
} |
5802b96c-c7fe-4b0c-8a9e-9b4d380339c3 | 4 | public List<TestResultData> process() {
List<TestResultData> testResults = new ArrayList<TestResultData>();
try {
TestNgResultParser resultParser = new TestNgResultParser(resultFile);
Map<String, String> testResultMap = resultParser.getTestResultMap();
Iterator<Entry<String, String>> testResultSet = testResultMap.entrySet().iterator();
while (testResultSet.hasNext()) {
TestResultData resultData = new TestResultData();
Entry<String, String> entry = testResultSet.next();
resultData.setTestName(entry.getKey());
resultData.setTestSetName("");
resultData.setTestStatus(toTestStatus(entry.getValue()));
testResults.add(resultData);
}
} catch (FileNotFoundException fnfe) {
log.error("File is not found :" + resultFile);
} catch (IOException ioe) {
log.error("Got an exception while reading file :", ioe);
} catch (Exception e) {
log.error("Got an exception while reading file :", e);
e.printStackTrace();
}
return testResults;
} |
7e90769e-e704-4ced-9f84-0caa1971c583 | 8 | private void drawDebug() {
debugRenderer.begin(ShapeType.Line);
for (MapLayer ml : world.getMap().getLayers()) {
for (Tile t : ml.getTiles()) {
debugRenderer.setColor(Color.WHITE);
float startX = t.getPosition().x * ppuX, startY = t
.getPosition().y * ppuY;
debugRenderer.rect(startX, startY, ppuX, ppuY);
spriteBatch.begin();
font.setColor(Color.WHITE);
font.draw(
spriteBatch,
(int) t.getPosition().x + "," + (int) t.getPosition().y,
startX + ppuX / 4, startY + ppuY / 4);
spriteBatch.end();
if (t.getProperties().isObstacle()) {
debugRenderer.setColor(Color.BLACK);
debugRenderer.rect(startX + ppuX / 4, startY + ppuY / 4,
ppuX / 2, ppuY / 2);
}
}
}
for (Iterator<Entry<Boolean, Joueur>> it = this.world.getJoueurs()
.entrySet().iterator(); it.hasNext();) {
Joueur b = it.next().getValue();
debugRenderer.setColor(Color.GREEN);
debugRenderer.rect(b.getPosition().x * ppuX, b.getPosition().y
* ppuY, Joueur.SIZE * ppuX, Joueur.SIZE * ppuY);
spriteBatch.begin();
font.setColor(Color.GREEN);
font.draw(this.spriteBatch, String.valueOf(b.getVie()),
(b.getPosition().x + 0.5f) * ppuX,
(b.getPosition().y + 0.5f) * ppuY);
spriteBatch.end();
debugRenderer.setColor(Color.WHITE);
debugRenderer.circle((b.getBounds().x) * ppuX, (b.getBounds().y)
* ppuY, 3, 3);
for (Tile t : b.rechercheTileCollisionPossible()) {
if (t == null)
continue;
debugRenderer
.rect(t.getPosition().x * ppuX + ppuX / 4,
t.getPosition().y * ppuY + ppuY / 4, ppuX / 2,
ppuY / 2);
}
}
for (Projectile b : world.getProjectiles()) {
debugRenderer.setColor(Color.GREEN);
debugRenderer.rect(b.getPosition().x * ppuX, b.getPosition().y
* ppuY, b.SIZE * ppuX, b.SIZE * ppuY);
}
Vector2 t = lifeBar.getBarSize();
debugRenderer.rect(lifeBar.getPosition().x * ppuX ,lifeBar.getPosition().y * ppuY, t.x * ppuX,t.y * ppuY);
if(ennemyLifeBar!= null){
t = ennemyLifeBar.getBarSize();
debugRenderer.rect(ennemyLifeBar.getPosition().x * ppuX,ennemyLifeBar.getPosition().y * ppuY, t.x * ppuX,t.y * ppuY);
}
debugRenderer.end();
} |
b22ab1c2-46cd-4529-a08c-729799552449 | 3 | @Test
public void enqueuesAtTheEnd()
{
for (int i = 0; i < 3; i++) queue.dequeue();
queue.enqueue("nice shoes");
assertTrue(queue.dequeue().equals("tommytoes") &&
queue.dequeue().equals("nice shoes") &&
queue.dequeue() == null);
} |
0d6b9557-db93-4875-a98b-c47b4aab153b | 4 | public void fire(char tankDirection,int bulletx,int bullety){
x=bulletx;
y=bullety;
if(tankDirection=='u'){setXSpeed(0);setYSpeed(-16);}
if(tankDirection=='d'){setXSpeed(0);setYSpeed(16);}
if(tankDirection=='r'){setXSpeed(16);setYSpeed(0);}
if(tankDirection=='l'){setXSpeed(-16);setYSpeed(0);}
isFired=true;
} |
96d92c1c-57df-4ba2-a177-125a74142b79 | 1 | @Override
public void mouseExited(MouseEvent event) {
//When hovering off the board, only display data for the selected tile.
if (event.getSource() instanceof Tile) {
Tile selectedTile = match.getSelectedTile();
match.getPanel().setTile(null, selectedTile, null, match.getTileOwner(selectedTile), true);
}
} |
5a1cda2c-7c3c-4ac7-983c-0ab68c93329b | 7 | private Object instantiate(Class<?> clazz) {
try {
Object instance = clazz.newInstance();
for (ExtendedField field : DaoUtils.getAllFieldsWithSuperclasses(clazz)) {
if (field.hasEntityMapping() && field.isCascadingLoad()) {
switch (field.getEntityMapping()) {
case MANY_TO_MANY:
case MANY_TO_ONE:
field.setValue(instance, new ArrayList<Object>());
break;
default:
// Nothing to do here
break;
}
}
}
return instance;
} catch (Exception e) {
throw new DBException("could not create instance of class '"
+ clazz + "'", e);
}
} |
63d40aa7-56e8-4c6d-8d87-7639d4d0c0c9 | 4 | public Connector read(int bytes, Consumer<byte[]> consumer) {
updateActionIfNotNull();
byte[] data = new byte[bytes];
if (in != null) {
try {
int r = -1;
synchronized (in) {
r = in.read(data);
}
if (r != -1) {
if (r < bytes) {
byte[] n = new byte[r];
System.arraycopy(data, 0, n, 0, r);
data = n;
}
consumer.accept(data);
}
} catch (IOException e) {
error.addSuppressed(e);
destroy();
} finally {
updateActionIfNotNull();
}
}
return this;
} |
4a961ea1-34fe-4a56-9905-37cf4490373a | 8 | @Test
public void combine() {
SimpleMatrix A = new SimpleMatrix(6,4);
SimpleMatrix B = SimpleMatrix.random(3,4, 0, 1, rand);
SimpleMatrix C = A.combine(2,2,B);
assertEquals(6,C.numRows());
assertEquals(6,C.numCols());
for( int i = 0; i < 6; i++ ) {
for( int j = 0; j < 6; j++ ) {
if( i >= 2 && i < 5 && j >= 2 && j < 6 ) {
// check to see if B was overlayed
assertTrue( B.get(i-2,j-2) == C.get(i,j));
} else if( i >= 5 || j >= 4 ) {
// check zero padding
assertTrue( C.get(i,j) == 0 );
} else {
// see if the parts of A remain there
assertTrue( A.get(i,j) == C.get(i,j));
}
}
}
} |
0a30a346-d34e-45a6-97aa-a716efe60358 | 9 | public boolean expandAtdl4jWidgetParentStrategyPanel( Atdl4jWidget<?> aWidget )
{
boolean tempAdjustedFlag = false;
if ( ( aWidget.getParent() != null ) && ( aWidget.getParent() instanceof Composite ) )
{
Composite tempParent = (Composite) aWidget.getParent();
while ( tempParent != null )
{
// -- Expand if necessary --
if ( tempParent instanceof ExpandBar )
{
ExpandBar tempExpandBar = (ExpandBar) tempParent;
for ( ExpandItem tempExpandItem : tempExpandBar.getItems() )
{
if ( ! tempExpandItem.getExpanded() )
{
tempExpandItem.setExpanded( true );
// -- (relayoutParents=false) --
relayoutExpandBar( tempExpandBar, false );
tempAdjustedFlag = true;
}
}
}
// -- Iterate to next parent --
if ( ( tempParent.getParent() != null ) && ( ( tempParent.getParent() instanceof Composite ) ) )
{
tempParent = (Composite) tempParent.getParent();
}
else
{
break;
}
}
}
return tempAdjustedFlag;
} |
87f88f3f-a3f7-43f7-8b26-b8fd425c7d2e | 9 | @Override
public AnnotationVisitor visitInsnAnnotation(final int typeRef,
final TypePath typePath, final String desc, final boolean visible) {
checkStartCode();
checkEndCode();
int sort = typeRef >>> 24;
if (sort != TypeReference.INSTANCEOF && sort != TypeReference.NEW
&& sort != TypeReference.CONSTRUCTOR_REFERENCE
&& sort != TypeReference.METHOD_REFERENCE
&& sort != TypeReference.CAST
&& sort != TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT
&& sort != TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT
&& sort != TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT
&& sort != TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT) {
throw new IllegalArgumentException("Invalid type reference sort 0x"
+ Integer.toHexString(sort));
}
CheckClassAdapter.checkTypeRefAndPath(typeRef, typePath);
CheckMethodAdapter.checkDesc(desc, false);
return new CheckAnnotationAdapter(super.visitInsnAnnotation(typeRef,
typePath, desc, visible));
} |
b19a035f-1b80-41a1-915a-341603223160 | 5 | @Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Entry<? extends K,? extends V> p : m.entrySet())
this.put(p.getKey(),p.getValue());
} |
d73ad882-13a3-4448-a8fc-9977e576dd82 | 8 | public boolean realizarTransacoesPossiveis() {
for (int indiceCompra = 0; indiceCompra < compras.getTamanhoLista(); indiceCompra++) {
for (int indiceVenda = 0; indiceVenda < vendas.getTamanhoLista(); indiceVenda++) {
Interesse compra = compras.getInteresse(indiceCompra);
Interesse venda = vendas.getInteresse(indiceVenda);
if (!compra.getCliente().equals(venda.getCliente())) {
if (compra.getAcao().getEmpresa().equals(venda.getAcao().getEmpresa())
&& compra.getPreco() >= venda.getPreco()) {
double precoFinal = (compra.getPreco() + venda.getPreco()) / 2;
try {
if (compra.getAcao().getQuantidade() < venda.getAcao().getQuantidade()) {
venda.getAcao().setQuantidade(venda.getAcao().getQuantidade() - compra.getAcao().getQuantidade());
compras.remover(compra);
compra.getCliente().comunicarCompraEfetuada(compra.getAcao().getEmpresa(), compra.getAcao().getQuantidade(), precoFinal);
venda.getCliente().comunicarVendaEfetuada(compra.getAcao().getEmpresa(), compra.getAcao().getQuantidade(), precoFinal);
return true;
} else if (compra.getAcao().getQuantidade() > venda.getAcao().getQuantidade()) {
compra.getAcao().setQuantidade(compra.getAcao().getQuantidade() - venda.getAcao().getQuantidade());
vendas.remover(venda);
compra.getCliente().comunicarCompraEfetuada(compra.getAcao().getEmpresa(), venda.getAcao().getQuantidade(), precoFinal);
venda.getCliente().comunicarVendaEfetuada(compra.getAcao().getEmpresa(), venda.getAcao().getQuantidade(), precoFinal);
return true;
} else {
compras.remover(compra);
vendas.remover(venda);
compra.getCliente().comunicarCompraEfetuada(compra.getAcao().getEmpresa(), compra.getAcao().getQuantidade(), precoFinal);
venda.getCliente().comunicarVendaEfetuada(compra.getAcao().getEmpresa(), venda.getAcao().getQuantidade(), precoFinal);
return true;
}
} catch (RemoteException ex) {
Logger.getLogger(SalaTransacoes.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
return false;
} |
2c619e7a-4396-4793-a6f5-250bc87364b6 | 2 | public static OpCode parseOpCode(String op, boolean throwError) throws AssemblyException {
OpCode code = OpCode.parseOpCode(op);
if (code == null && throwError)
throw new AssemblyException(op + " is not a valid op code!");
return code;
} |
5d6c42b9-1e0e-423b-876d-a6dfa748c458 | 3 | public void run() {
try {
correct = check();
} catch (ModelingException e) {
e.printStackTrace();
}
if(correct) {
try {
simulate();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
d4737413-8775-47f6-bc64-a739748b72dd | 1 | private void setLogger(ILogger logger) {
if (logger == null) {
throw new IllegalArgumentException("aLogger is null");
}
this.logger = logger;
} |
fe9b3fde-0cc7-47f3-8ca6-bfe659aad1f2 | 9 | private void copyValue(Value val) {
descriptor_ = new ValueDescriptor(val.getDescriptor());
Object obj = val.getData();
switch (getType()) {
case FLOAT:
data_ = new Float((Float) obj);
break;
case DOUBLE:
data_ = new Double((Double) obj);
break;
case INTEGER:
data_ = new Integer((Integer) obj);
break;
case LONG:
data_ = new Long((Long) obj);
break;
case SHORT:
data_ = new Short((Short) obj);
break;
case BYTE:
data_ = new Byte((Byte) obj);
break;
case STRING:
data_ = obj.toString();
break;
case BOOLEAN:
data_ = new Boolean((Boolean) obj);
break;
case ARRAY:
copyArray(obj);
break;
default:
data_ = obj;
break;
}
} |
caa12338-7fa7-4b59-8012-99c545c66917 | 6 | public static Object getProperty(Object obj, String propertyName)
{
if (obj == null)
return null;
try
{
BeanInfo info = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
for (int i = 0; i < descriptors.length; i++)
{
if (descriptors[i].getName().equals(propertyName))
{
Method getter = descriptors[i].getReadMethod();
if (getter == null)
return null;
try {
return getter.invoke(obj);
} catch (Exception ex) {
System.out.println(descriptors[i].getName());
return null;
}
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
} |
9d850ca7-3f75-4056-a597-b49c1870e098 | 3 | private static void writeProperties(Properties props, XMLWriter w) throws
IOException
{
if (!props.isEmpty()) {
final SortedSet<Object> propertyKeys = new TreeSet<Object>();
propertyKeys.addAll(props.keySet());
w.startElement("properties");
for (Object propertyKey : propertyKeys) {
final String key = (String) propertyKey;
final String property = props.getProperty(key);
w.startElement("property");
w.writeAttribute("name", key);
if (property.indexOf('\n') == -1) {
w.writeAttribute("value", property);
} else {
// Save multiline values as character data
w.writeCDATA(property);
}
w.endElement();
}
w.endElement();
}
} |
4994f29f-6e08-43bc-96ff-966c471c09e4 | 7 | private void getAllActors(){
Document doc = getXmlFile();
NodeList nList = doc.getElementsByTagName("Actor");
if(debugConsole){
System.out.println("Actors in XML-File");
System.out.println("-------------------");
System.out.println("");
System.out.println("Number : "+nList.getLength());
}
System.out.println("");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
Element eElement = (Element) nNode;
Actor actor = new Actor(Integer.parseInt(eElement.getElementsByTagName("Value").item(12).getTextContent()));
if(debugConsole){
System.out.println("ActorID: " + eElement.getAttribute("ID"));
System.out.println("--------");
}
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
actor.setName(eElement.getElementsByTagName("Value").item(0).getTextContent());
actor.setPicturePath(eElement.getElementsByTagName("Value").item(1).getTextContent());
actor.setDescription(eElement.getElementsByTagName("Value").item(2).getTextContent());
if(eElement.getElementsByTagName("Value").item(3).getTextContent().equalsIgnoreCase("True")){
actor.setPlayer(true);
}
else actor.setPlayer(false);
actor.setAge(Integer.parseInt(eElement.getElementsByTagName("Value").item(4).getTextContent()));
actor.setGender(eElement.getElementsByTagName("Value").item(5).getTextContent());
actor.setOccupation(eElement.getElementsByTagName("Value").item(6).getTextContent());
actor.setRank(eElement.getElementsByTagName("Value").item(7).getTextContent());
actor.setFaction(eElement.getElementsByTagName("Value").item(8).getTextContent());
actor.setAbilities(eElement.getElementsByTagName("Value").item(9).getTextContent());
if(eElement.getElementsByTagName("Value").item(10).getTextContent().equalsIgnoreCase("True")){
actor.setFixedLocation(true);
}
else actor.setFixedLocation(false);
actor.setLocation(eElement.getElementsByTagName("Value").item(11).getTextContent());
actor.setActorClass(eElement.getElementsByTagName("Value").item(13).getTextContent());
actor.setActorSubClass(eElement.getElementsByTagName("Value").item(14).getTextContent());
actor.setFiles2dPath(eElement.getElementsByTagName("Value").item(15).getTextContent());
actor.setFiles3dPath(eElement.getElementsByTagName("Value").item(16).getTextContent());
if(debugConsole){
System.out.println("Name : " + eElement.getElementsByTagName("Value").item(0).getTextContent());
System.out.println("Picture path (?) : " + eElement.getElementsByTagName("Value").item(1).getTextContent());
System.out.println("Description : " + eElement.getElementsByTagName("Value").item(2).getTextContent());
System.out.println("Is Player : " + eElement.getElementsByTagName("Value").item(3).getTextContent());
System.out.println("Age : " + eElement.getElementsByTagName("Value").item(4).getTextContent());
System.out.println("Gender: " + eElement.getElementsByTagName("Value").item(5).getTextContent());
System.out.println("Occupation : " + eElement.getElementsByTagName("Value").item(6).getTextContent());
System.out.println("Rank : " + eElement.getElementsByTagName("Value").item(7).getTextContent());
System.out.println("Faction : " + eElement.getElementsByTagName("Value").item(8).getTextContent());
System.out.println("Ability : " + eElement.getElementsByTagName("Value").item(9).getTextContent());
System.out.println("Fixed Location : " + eElement.getElementsByTagName("Value").item(10).getTextContent());
System.out.println("Location : " + eElement.getElementsByTagName("Value").item(11).getTextContent());
System.out.println("NPC Id : " + eElement.getElementsByTagName("Value").item(12).getTextContent());
System.out.println("Class : " + eElement.getElementsByTagName("Value").item(13).getTextContent());
System.out.println("Subclass : " + eElement.getElementsByTagName("Value").item(14).getTextContent());
System.out.println("Texture Files (2D) : " + eElement.getElementsByTagName("Value").item(15).getTextContent());
System.out.println("Texture Files (3D) : " + eElement.getElementsByTagName("Value").item(16).getTextContent());
System.out.println("");
}
}
listActors.add(actor);
}
} |
ec108b71-72d1-4851-a2b1-3c18b582b724 | 7 | private static String createRealUser(String string) {
Connection conn = ConnectionFactory.getConnection();
PreparedStatement pst = null;
ResultSet rs = null;
User user = JsonUtils.getUserByJson(string);
String sql = null;
int i = 0;// 判断是否创建了用户信息
// 判断是否输入了info
String infoString = ",u_info";
String haveInfo = "?";
String comma = ",";
if (user.getInfo().equals("")) {
infoString = "";
haveInfo = "";
comma = "";
}
// 判断用户是创建还是修改
try {
// 创建用户
if (user.getIsCreate()) {
// 判断用户名是否存在
pst = conn
.prepareStatement("SELECT u_name FROM user_info WHERE u_name = ?");
pst.setString(1, user.getName());
rs = pst.executeQuery();
// 若用户名不存在
if (!rs.next()) {
sql = "insert into user_info (u_name,u_password,u_school,u_address"
+ infoString
+ ") values (?,?,?,?"
+ comma
+ haveInfo
+ ");";
pst = conn.prepareStatement(sql);
pst.setString(1, user.getName());
pst.setString(2, user.getPassword());
pst.setString(3, user.getSchool());
pst.setString(4, user.getAddress());
// 判断在需不需要输入info
if (!haveInfo.equals("")) {
pst.setString(5, user.getInfo());
}
i = pst.executeUpdate();
}
else{
return "saved";
}
}
// 修改用户
else {
sql = "update user_info set u_password = ? , u_school = ? , u_address = ? , u_info= ? where u_name = ?;";
pst = conn.prepareStatement(sql);
pst.setString(1, user.getPassword());
pst.setString(2, user.getSchool());
pst.setString(3, user.getAddress());
pst.setString(5, user.getName());
if (haveInfo.equals("")){
haveInfo = " ";
pst.setString(4, haveInfo);
}else {
pst.setString(4, user.getInfo());
}
i = pst.executeUpdate();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
ConnectionFactory.close(rs, pst, conn);
}
return i == 0 ? "false" : "true";
} |
1e89788f-5df1-4d81-a846-db855c73665d | 7 | public String decode(String codeWord) {
if (codeWord != null) {
decode = new StringBuilder();
StringBuilder sum = new StringBuilder();
String c;
char l;
int count = 0;
for (int i = 0; i < codeWord.length()-1; i++) {
switch (l=codeWord.charAt(i)) {
case 'A':
for (int j = 0; j < count; j++) {
decode.append(alphabet[0]);
}
sum.setLength(0);
break;
case 'B':
for (int j = 0; j < count; j++) {
decode.append(alphabet[1]);
}
sum.setLength(0);
break;
default:
c = "" + l;
if(!c.isEmpty()){
sum.append(c);
count = Integer.parseInt(sum.toString());
}
break;
}
}
return decode.toString();
} else {
throw new IllegalArgumentException("Codeword must not be null");
}
} |
278a4b80-08ef-4ef7-a29e-e784a9e1584f | 5 | private Expression primary() {
Expression e = null;
// variable or function call
if (currentToken.type() == Token.Type.Identifier) {
Variable v = new Variable(currentToken.value());
match(Token.Type.Identifier);
// function call
if(currentToken.type() == Token.Type.LeftParen)
e = callStatement(v);
// variable
else
e = v;
// literal
} else if (isLiteral()) {
e = literal();
// expression
} else if (currentToken.type().equals(Token.Type.LeftParen)) {
currentToken = lexer.next();
e = expression();
match(Token.Type.RightParen);
// type cast
} else if (isType()) {
Operator op = new Operator(currentToken.value());
match(currentToken.type());
match(Token.Type.LeftParen);
Expression term = expression();
match(Token.Type.RightParen);
e = new Unary(op, term);
} else
error("Identifier | Literal | ( | Type");
return e;
} |
866ca8fc-600b-4229-afa0-6f1bca3acc35 | 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(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.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 Main().setVisible(true);
}
});
} |
a3fffe73-aa98-4eb4-bd29-c30b3185a341 | 9 | private void setLookAndFeel(final String laf) {
try {
final int lafNum = Integer.parseInt(laf);
switch(lafNum){
default:
case -2: //Nimbus
boolean isLAFFound = false;
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
isLAFFound = true;
break;
}
}
if( isLAFFound ){
break;
}
case 0: //Java LAF
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());
break;
case 1: //System LAF
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
break;
case 2:
javax.swing.UIManager.setLookAndFeel( recursosConfig.getString("LAFClass") );
break;
}
} catch (Exception e) {
System.err.println("Error setting Look and Feel: " + e.getMessage());
try{
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());
}catch(Exception e2){
System.err.println("Error setting Look and Feel (1st and only retry): " + e2.getMessage());
}
}
JFrame.setDefaultLookAndFeelDecorated(true);
} |
246e4360-dc80-4263-94fa-15d6864a3480 | 8 | private void jButtonGuardarNovaEntradaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarNovaEntradaActionPerformed
// BOTAO GUARDAR -> JANELA ENTRADAS
//FAZER AS VALIDAÇÕES, SE OS CAMPOS ESTAO TODOS PREENCHIDOS
String nomeFuncionarioResponsavelEntrada = jComboBoxFuncionarioResponsavelEntrada.getSelectedItem().toString();
String nomeFornecedorEntrada = jComboBoxFornecedorEntrada.getSelectedItem().toString();
String nomeMateriaPrimaEntrada = jComboBoxMateriaPrimaEntrada.getSelectedItem().toString();
float qantidadeMatPrimaEntrada = Float.parseFloat(jTextFieldQuantidadeEntrada.getText().toString());
String conformidadeTemperatura = jComboBoxTemperaturaEntrada.getSelectedItem().toString();
String conformidadeDtaValidade = jComboBoxDataValidadeEntrada.getSelectedItem().toString();
String conformidadeCaratOrgono = jComboBoxCaraOrgonolepticasEntradas.getSelectedItem().toString();
String conformidadeEmbalagem = jComboBoxEmbalagemEntradas.getSelectedItem().toString();
if(nomeFuncionarioResponsavelEntrada.equals("--Funcionario--")){
JOptionPane.showMessageDialog(jDialogNovaEntrada, "Por Favor !\nSelecciona um Funcionario!");
}else if (nomeFornecedorEntrada.equals("--Fornecedor--")){
JOptionPane.showMessageDialog(jDialogNovaEntrada, "Por Favor !\nSelecciona um Fornecedor!");
}else if (nomeMateriaPrimaEntrada.equals("--Materia Prima--")){
JOptionPane.showMessageDialog(jDialogNovaEntrada, "Por Favor !\nSelecciona uma Matéria-Prima!");
}else if(qantidadeMatPrimaEntrada == 0.0){
JOptionPane.showMessageDialog(jDialogNovaEntrada, "Por Favor !\nQuantidade não pode ser Zero!");
}else if(conformidadeTemperatura.equals("--Opção--")){
JOptionPane.showMessageDialog(jDialogNovaEntrada, "Por Favor !\nSelecciona a Conformidade da Temperatura!");
}else if (conformidadeDtaValidade.equals("--Opção--")){
JOptionPane.showMessageDialog(jDialogNovaEntrada, "Por Favor !\nSelecciona a Conformidade da Data de Validade!");
}else if (conformidadeCaratOrgono.equals("--Opção--")){
JOptionPane.showMessageDialog(jDialogNovaEntrada, "Por Favor !\nSelecciona a Conformidade das Caract. Orgonolepticas!");
}else if (conformidadeEmbalagem.equals("--Opção--")){
JOptionPane.showMessageDialog(jDialogNovaEntrada, "Por Favor !\nSelecciona a Conformidade da Embalagem/Transporte!");
}else{
InserirNovaEntrada();
}
} |
850c9d2e-09d9-4f63-a124-3e7ac25d200e | 2 | public static boolean userExist(String email){
SQLiteJDBC db = new SQLiteJDBC();
String sql = String.format("SELECT user_id FROM users WHERE email='%s'", email);
ResultSet resultSet = db.query(sql);
try {
if(resultSet.next())
return true;
db.close();
}catch(Exception e) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
return false;
} |
4ffa3315-05bc-4c93-b443-db4efaddc331 | 2 | private void buttonSendInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSendInfoActionPerformed
//Создаем нового клиента по заполненным полям
Client client = new Client();
try {
client.setFio(textFieldFio.getText());
client.setAddress(textFieldAdr.getText());
client.setPassport(textFieldPas.getText());
client.setIdCod(textFieldIdCod.getText());
client.setTel(textFieldTel.getText());
client.setLevel(Long.parseLong(textFieldLevel.getText()));
client.setWorkInfo(textAreaWorkInfo.getText());
client.setUsersId(curUserId);
//Временное значение для поручителя
//client.setSuretyId(1);
} catch (NumberFormatException exc) {
JOptionPane.showMessageDialog(this, "Неверный формат данных!");
return;
}
//Обновляем или добавляем нового клиента
if (clientDAO.update(client) != true) {
clientDAO.add(client);
}
JOptionPane.showMessageDialog(this, "Данные успешно сохранены");
}//GEN-LAST:event_buttonSendInfoActionPerformed |
81497bce-02e2-4a88-9334-38e5d409af49 | 7 | private void setMenu() {
boolean isNumeric;
boolean hasColumns;
boolean hasRows;
boolean attSelected;
ArffSortedTableModel model;
boolean isNull;
model = (ArffSortedTableModel) m_TableArff.getModel();
isNull = (model.getInstances() == null);
hasColumns = !isNull && (model.getInstances().numAttributes() > 0);
hasRows = !isNull && (model.getInstances().numInstances() > 0);
attSelected = hasColumns && (m_CurrentCol > 0);
isNumeric = attSelected && (model.getAttributeAt(m_CurrentCol).isNumeric());
menuItemUndo.setEnabled(canUndo());
menuItemCopy.setEnabled(true);
menuItemSearch.setEnabled(true);
menuItemClearSearch.setEnabled(true);
menuItemMean.setEnabled(isNumeric);
menuItemSetAllValues.setEnabled(attSelected);
menuItemSetMissingValues.setEnabled(attSelected);
menuItemReplaceValues.setEnabled(attSelected);
menuItemRenameAttribute.setEnabled(attSelected);
menuItemDeleteAttribute.setEnabled(attSelected);
menuItemDeleteAttributes.setEnabled(attSelected);
menuItemSortInstances.setEnabled(hasRows && attSelected);
menuItemDeleteSelectedInstance.setEnabled(hasRows && m_TableArff.getSelectedRow() > -1);
menuItemDeleteAllSelectedInstances.setEnabled(hasRows && (m_TableArff.getSelectedRows().length > 0));
} |
f6515e7d-170c-4525-b053-c64a67ea0052 | 6 | public static LinkedListNode unionLL(LinkedListNode head1,
LinkedListNode head2)
{
if (head1 == null || head2 == null)
{
return null;
}
LinkedListNode result = null;
LinkedListNode temp = head1;
LinkedListNode temp2 = head2;
HashSet<Integer> hs = new HashSet();
while (temp != null && temp2 != null)
{
LinkedListNode nn = temp.getNext();
LinkedListNode nn2 = temp2.getNext();
if (hs.add((int)temp.getData()))
{
LinkedListNode n = temp;
temp.setNext(result);
result = n;
}
if (hs.add((int)temp2.getData()))
{
LinkedListNode n = temp2;
temp2.setNext(result);
result = n;
}
temp = nn;
temp2 = nn2;
}
return result;
} |
66f2bdbc-616c-4a1b-b1d4-04f765b57573 | 0 | public Transition(Integer n, Character c, Integer lc, Integer rc){
node = n;
character = c;
leftChildren = lc;
rightChildren = rc;
} |
a375bc1c-d86f-4f13-91c6-21e374243bfa | 9 | protected Proxy getNextProxy() {
if (this.proxies.isEmpty()) {
System.out.println(">>> GET NEW PROXIES: ");
try {
if (useLocalProxyFile) { // Local Proxy List
if (proxyFile == null)
return null;
File in = new File(proxyFile);
if (!in.isFile())
throw new IllegalArgumentException("input must be a file");
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(in), "UTF-8"));
// Parse proxies
String line = null;
String host = null;
int port;
Type type = null;
while ((line = reader.readLine()) != null) {
host = line.substring(0, line.indexOf(':') - 1);
port = Integer.parseInt(line.substring(line
.indexOf(':') + 1));
type = Type.HTTP;
Proxy proxy = new Proxy(host, port, type);
System.out.println("host: "+host+" port: "+port);
proxies.add(proxy);
}
proxyFile = null;
} finally {
if (reader != null)
reader.close();
}
} else { // Get Proxies from HideMyAss
HideMyAssProxyRequest request = new HideMyAssProxyRequest(
this.first ? 1000
: HideMyAssProxyRequest.PAGE_PROXY_LIMIT);
this.first = false;
this.proxies.addAll(request.submit());
}
} catch (IOException e) {
System.out.println(">>> EXCEPTION : " + e.getMessage());
}
}
if (this.proxies.isEmpty())
return null;
Proxy proxy = this.proxies.remove(0);
System.out.println(">>> USE PROXY : " + proxy);
return proxy;
} |
402af9ec-2136-471d-8eea-ef28bfbe982d | 7 | public mst(Graph G) {
graphSize = G.getSize();
mst1 = new Graph(graphSize); //size of graph initialized to number of Vertices
parent = new int[graphSize]; //stores the parent values corresponding to every vertice. Used to decide whic edges lie in the graph
key = new int[graphSize]; //stores the value of the weight a particular vertex belongs to
/* keys are initially set to +infinity which is 1001 > max(cost) and parents are set to -2*/
for(int index = 0; index < graphSize; index++) {
parent[index] = -2;
key[index] = 1001;
}
/*The priority queue is initialized and the root element is deleted from linked list
*Parent of root set to -1 because this will help in checking the condition when the root is removed from linkedList
So that we dont end up adding another edge
* */
parent[root] = -1;
LinkedList<Integer>[] Q = initializeWeightArray(G);
key[root] = 0;
deleteFromLinkedList(Q[weightSize - 1], linkedListPointer[root], root);
keyMinSimple = 0;
/*stores the position of a vertice in the linked list . Initially all are pushed to the array element max(cost) + 1 in initializeWeightArray*/
linkedListPointer[root] = pushIntoLinkedList(Q[keyMinSimple], root);
/*keyMinSimple is the loop condition. if all keys are greater than max(cost) means that there are no edges left with lesser costs*/
/* In this whileLoop iteratively extractMin is done and the edge with least cost from the minimum spanning tree
* is added. At the end of this loop all n-1 edges of the mst are added to the result and returned
* */
while(keyMinSimple <= wMaximumSimple) {
Integer u = extractMin(Q);
if(u != -1){
LinkedList<Integer> adjacencyList = G.getAdjacencyList(u);
for(Integer i = 0; i < adjacencyList.size(); i++) {
Integer adjacentVertex = adjacencyList.get(i);
int edgeWeight = G.getCost(u, adjacentVertex);
if(linkedListPointer[adjacentVertex] != -1 && edgeWeight < key[adjacentVertex]) {
parent[adjacentVertex] = u;
deleteFromLinkedList(Q[key[adjacentVertex]], linkedListPointer[adjacentVertex] ,
adjacentVertex);
key[adjacentVertex] = edgeWeight;
linkedListPointer[adjacentVertex] = pushIntoLinkedList(Q[key[adjacentVertex]], adjacentVertex);
}
}
if(parent[u] != -1) {
mst1.addEdge(parent[u], u, G.getCost(u, parent[u]));
}
}
}
} |
9b9df9a4-32a3-4a9b-9149-f7ef7ce76fc1 | 7 | public void descend(){
eraseCenter();
for(int col = 0; col < board.getWidth(); col++){
int[] values = new int[board.getLength()];
for(int i = 0; i < values.length; i++){
values[i] = -2;
}
for(int row = board.getLength()-1; row >= 0;row--){
if(board.getValue(row, col) != -2){
if(board.isValid(row+2, col)){
values[row+2] = board.getValue(row, col);
}
else if(board.isValid(row+1,col)){
values[0] = board.getValue(row, col);
}
else{
values[1] = board.getValue(row,col);
}
}
}
for(int i = 0; i < values.length; i++){
board.setValue(i, col, values[i]);
}
}
markCenter();
} |
318e593a-3cd5-4a28-885a-2712fe65a040 | 6 | @Override
public void hyperlinkUpdate(HyperlinkEvent event) {
if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
String url = event.getDescription();
if (url != null) {
if (url.indexOf("jfchat;jsessionid=") != -1) {
if (url.indexOf("say=") != -1) {
String tmp = url.substring(url.indexOf("say=")+"say=".length());
client.sendToChat(tmp);
} else {
client.openJFChatLink(url);
}
} else if (url.indexOf("jfchat?refout=") != -1) {
String tmp = url.substring(url.indexOf("refout=")+"refout=".length());
client.openInBrowser(tmp);
} else {
client.openInBrowser(url);
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
} |
f6d93cf5-7bc6-4e36-ae54-287099d531cb | 2 | public static SwingAppenderUI getInstance() {
if (instance == null) {
synchronized(SwingAppenderUI.class) {
if(instance == null) {
instance = new SwingAppenderUI();
}
}
}
return instance;
} |
5f5dc039-8183-4483-b776-8ac893fe9ce6 | 7 | public static void main(String[] args) {
// TODO code application logic here
ArchivoDeTexto nuevo = new ArchivoDeTexto();
int[] lista = new int[2000];
lista = nuevo.lectura();
String menu = "1. Mostrar arreglo inicial\n2. Ordenar por BubbleSort\n3. Ordenar por InsertionSort\n4. Ordenar por MergeSort\n5. Ordenar por QuickSort\n6. Salir";
Scanner scan = new Scanner(System.in);
int opc = 0;
Random rnd = new Random();
int originaldata[] = new int[2000], temp[] = new int[2000], bsortdata[] = new int[2000], isortdata[] = new int[2000], qsortdata[] = new int[2000], msortdata[] = new int[2000];
for(int i=0;i<2000;i++){
originaldata[i] = lista[i];
bsortdata[i] = lista[i];
isortdata[i] = lista[i];
qsortdata[i] = lista[i];
msortdata[i] = lista[i];
}
while (opc != 6){
System.out.println(menu + "\nOpción: ");
opc = scan.nextInt();
switch (opc){
case 1:
System.out.print("Arreglo inicial: " + Arrays.toString(originaldata));
break;
case 2: //BubbleSort
BubbleSort orden = new BubbleSort();
System.out.print(Arrays.toString(orden.Sort(bsortdata,2000)) + "\n");
System.out.println("Se ha ordenado por medio del BubbleSort");
break;
case 3:
InsertionSort orden1 = new InsertionSort();
System.out.print(Arrays.toString(orden1.Sort(isortdata,2000)) + "\n");
System.out.println("Se ha ordenado por medio del InsertionSort");
break;
case 4:
MergeSort orden2 =new MergeSort();
System.out.print(Arrays.toString(orden2.Sort(msortdata,2000)) + "\n");
System.out.println("Se ha ordenado por medio del MergeSort");
break;
case 5:
QuickSort orden3 =new QuickSort();
System.out.print(Arrays.toString(orden3.Sort(msortdata, 2000)) + "\n");
System.out.println("Se ha ordenado por medio del QuickSort");
break;
}
}
System.out.println("Ha salido del programa correctamente");
} |
09ef6941-1f4f-4579-aff2-578b34206e3a | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Period other = (Period) obj;
if (cost != other.cost)
return false;
if (date_hour == null) {
if (other.date_hour != null)
return false;
} else if (!date_hour.equals(other.date_hour))
return false;
if (duration != other.duration)
return false;
if (id != other.id)
return false;
return true;
} |
89b7c616-2be6-46da-95d1-b6bfdccd5c52 | 3 | @Override
public void mouseDragged(MouseEvent e) {
float y = e.getY();
if(scrolling) {
scrollPerc = (y - startScrolling)/this.height + startScrollingPerc;
scroll = (int) (scrollPerc * totalHeight);
if(scrollPerc < 0)
scrollPerc = scroll = 0;
else
if(scroll > totalHeight - this.height) {
scroll = totalHeight - this.height;
scrollPerc = (float)scroll/(float)totalHeight;
}
}
} |
3319f496-4a90-40f1-85e1-f781c7f6943d | 3 | public void draw(Graphics2D g){
switch(size){
case 0:
g.setColor(new Color(0xFF4545));
break;
case 1:
g.setColor(new Color(0xaa5555));
break;
case 2:
g.setColor(Color.red);
break;
default:
g.setColor(Color.yellow);
break;
}
int[] px = {x , x + width, x + width };
int[] py = {y , y - height / 2, y + height / 2 };
g.fillPolygon(px,py,3);
g.setColor(Color.black);
} |
26872b86-fc2f-4e10-98d8-5e04265a52f5 | 4 | private static Class findUnderlyingClass(Type t)
{
if (t instanceof Class) {
return (Class) t;
}
else if (t instanceof ParameterizedType) {
ParameterizedType paramType = (ParameterizedType) t;
return findUnderlyingClass(paramType.getRawType());
}
else if (t instanceof WildcardType) {
WildcardType wt = (WildcardType) t;
Type[] upperBounds = wt.getUpperBounds();
// TODO: Handle null and length > 1
return findUnderlyingClass(upperBounds[0]);
}
else if (t instanceof TypeVariable) {
TypeVariable tv = (TypeVariable) t;
// TODO: Handle null and length > 1
return findUnderlyingClass(tv.getBounds()[0]);
}
return null;
} |
b8366e22-26a7-464f-8a21-7b6e5d68dc4f | 5 | public static boolean estDate(String source){
if(source.length() != 10){
return false ;
}
else {
try {
int jour = Integer.parseInt(source.substring(0,2)) ;
int mois = Integer.parseInt(source.substring(3,5)) - 1 ;
int annee = Integer.parseInt(source.substring(6)) ;
if(jour >= 1 && mois >= 0 && annee >= 1){
new GregorianCalendar(annee,mois,jour) ;
return true ;
}
else {
return false ;
}
}
catch(Exception e){
return false ;
}
}
} |
26f16d0c-406d-4fe9-b888-3898ec1c9fdd | 8 | @Override
public List<SpaceObject> getSpaceObjectsWithin(final SpaceObject ofObj, long minDistance, long maxDistance)
{
final List<SpaceObject> within=new ArrayList<SpaceObject>(1);
if(ofObj==null)
return within;
synchronized(space)
{
space.query(within, new BoundedObject.BoundedCube(ofObj.coordinates(), maxDistance));
}
for (final Iterator<SpaceObject> o=within.iterator();o.hasNext();)
{
SpaceObject O=o.next();
if(O!=ofObj)
{
final long dist=Math.round(Math.abs(getDistanceFrom(O,ofObj) - O.radius() - ofObj.radius()));
if((dist<minDistance)||(dist>maxDistance))
o.remove();
}
}
if(within.size()<=1)
return within;
Collections.sort(within, new Comparator<SpaceObject>()
{
@Override public int compare(SpaceObject o1, SpaceObject o2)
{
final long distTo1=getDistanceFrom(o1,ofObj);
final long distTo2=getDistanceFrom(o2,ofObj);
if(distTo1==distTo2)
return 0;
return distTo1>distTo2?1:-1;
}
});
return within;
} |
1f2dafca-f3ed-4594-8eb7-eff577a5266c | 0 | public void setEncryptionMethod(EncryptionMethodType value) {
this.encryptionMethod = value;
} |
8e9b5aac-c5d2-4b98-83d5-f7c743f5a6b7 | 4 | public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, UnknownHostException {
tempRxList = new ArrayList<Medicine>();
Date EditDate = new Date();
ArrayList<String> tempPrescriptionID;
// Prepare Morphia Framework
Mongo mongo = new Mongo("localhost", 27017);
Morphia morphia = new Morphia();
morphia.mapPackage("com.j3ltd.server.entities");
Datastore ds = morphia.createDatastore(mongo, "dotc");
Query<Record> qr = ds.createQuery(Record.class).field("RecordID")
.equal(request.getParameter("RecordID").toString());
record = qr.get();
prescription = new Prescription();
// prescription.setPatientID(request.getParameter("PatientID").toString());
prescription.setDoctorID(request.getParameter("DoctorID").toString());
String PostRx = request.getParameter("RxList").toString();
String[] rawRxList = PostRx.split(";");
int i = 1;
temp = "";
for (String rawRx : rawRxList) {
Rx = new Medicine();
String[] RxAttribute = rawRx.split(",");
Rx.setId(String.valueOf(i));
Rx.setType(RxAttribute[0].trim());
Rx.setName(RxAttribute[1].trim());
Rx.setDose(RxAttribute[2].trim());
Rx.setAmount(Integer.parseInt(RxAttribute[3].trim()));
Rx.setUsageDirection(RxAttribute[4].trim());
Rx.setRawString(notePrescription(Rx));
tempRxList.add(Rx);
if (i == 1)
temp += Rx.getRawString();
else
temp += "\n" + Rx.getRawString();
i++;
}
prescription.setMedicineList(tempRxList);
prescription.setRawStringList(temp);
Query<Person> qp = ds.createQuery(Person.class).field("citizenid")
.equal(record.getPatientCitizenID());
Person patient = qp.get();
prescription.setPatientID(patient.getCitizenid());
prescription.setPatientFirstName(patient.getFirstName());
prescription.setPatientLastName(patient.getLastName());
Query<Doctor> qd = ds.createQuery(Doctor.class).field("citizenid")
.equal(prescription.getDoctorID());
Doctor doctor = qd.get();
prescription.setDoctorFirstName(doctor.getFirstName());
prescription.setDoctorLastName(doctor.getLastName());
// Generating Prescription ID
if (ds.createQuery(Prescription.class).countAll() == 0)
prescription.setPrescriptionID("1");
else {
Query<Prescription> q = ds.createQuery(Prescription.class).order(
"-PrescriptionID");
Prescription temp = q.get();
long l = Long.parseLong(temp.getPrescriptionID()) + 1;
prescription.setPrescriptionID(String.valueOf(l));
}
// Generating Prescription ID List to Record
tempP = "";
if (record.getPrescriptionID() == null) {
tempPrescriptionID = new ArrayList<String>();
tempP = prescription.getPrescriptionID().trim();
} else {
tempPrescriptionID = record.getPrescriptionID();
tempP = record.getRawPrescriptionIDList().concat(",")
.concat(prescription.getPrescriptionID()).trim();
}
tempPrescriptionID.add(prescription.getPrescriptionID());
UpdateOperations<Record> ops = ds.createUpdateOperations(Record.class)
.set("PrescriptionID", tempPrescriptionID)
.set("rawPrescriptionIDList", tempP).set("DiagDate", EditDate)
.set("timestamp", EditDate);
ds.findAndModify(qr, ops);
System.out.println("Sent POST request to backBean");
insertPrescription();
System.out.println("Finish inserting to MongoDB");
} |
88548930-9ac3-446c-846b-fc0a9b491c15 | 7 | @Override
public TypeInfo TypeCheck(CompilationContext cont) throws Exception {
TypeInfo eval_leftTypeInfo = leftExpr.TypeCheck(cont);
TypeInfo eval_rightTypeInfo = rightExpr.TypeCheck(cont);
if (eval_leftTypeInfo != eval_rightTypeInfo) {
throw new Exception("Wrong Type in expression");
}
if (eval_leftTypeInfo == TypeInfo.TYPE_STRING
&& (!(m_op == RelationalOperators.TOK_EQ
|| m_op == RelationalOperators.TOK_NEQ))) {
throw new Exception("Only == and != supported for string type ");
}
if (eval_leftTypeInfo == TypeInfo.TYPE_BOOL
&& (!(m_op == RelationalOperators.TOK_EQ
|| m_op == RelationalOperators.TOK_NEQ))) {
throw new Exception("Only == and != supported for boolean type ");
}
// store the operand type as well
_opType = eval_leftTypeInfo;
_type = TypeInfo.TYPE_BOOL;
return _type;
} |
b34d1e23-1301-48c8-8774-306d60cd000c | 8 | @Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnSauvegarder){
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");
int userSelection = fileChooser.showSaveDialog(this);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if(!file.getAbsolutePath().toLowerCase().endsWith(".txt"))
{
file= new File(file.getAbsolutePath() + ".txt");
}
System.out.println("Save as file: " + file.getAbsolutePath());
controleur.SauvegarderModele(file);
}
}
else if(e.getSource()==btnSauvegarder_1){
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");
int userSelection = fileChooser.showSaveDialog(this);
if (userSelection == JFileChooser.APPROVE_OPTION) {
file = fileChooser.getSelectedFile();
System.out.println("Save as file: " + file.getAbsolutePath());
if(!file.getAbsolutePath().toLowerCase().endsWith(".gexf"))
{
file= new File(file.getAbsolutePath() + ".gexf");
}
new Thread(new Runnable() {
public void run() {
controleur.SauvegarderGrapheChaines(file);
}
}).start();
}
}
else if(e.getSource()==btnFichiers){
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");
int userSelection = fileChooser.showSaveDialog(this);
if (userSelection == JFileChooser.APPROVE_OPTION) {
file = fileChooser.getSelectedFile();
System.out.println("Save as file: " + file.getAbsolutePath());
String chemin=file.getAbsolutePath();
file= new File(chemin + ".gexf");
file2= new File(chemin + ".txt");
new Thread(new Runnable() {
public void run() {
controleur.SauvegarderGrapheChaines(file);
controleur.SauvegarderModele(file2);
}
}).start();
}
}
} |
9accffed-f179-414e-8a1f-67df47f99586 | 0 | public String getUserId() {
return userId;
} |
7d063e6b-d1cf-4418-ac0b-a8cd2a2c1ff7 | 3 | public void start() {
activeScreen = new CreateScreen(this);;
while (true) {
Draw();
if (gotchi != null) {
gotchi.Update();
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} |
cae56348-2508-4df9-9ff0-dd7f604a9303 | 6 | @Override
public Hashtable<String, LinkedList<Triple<String, String, String>>> relations_extraction() throws IOException{
// Start by building dictionaries
build_dicos();
// st is the next sentence tree to be built
Tuple<Sentence_tree,String> st = build_next_sentence_tree();
if(st == null){
st = build_next_sentence_tree();
}
// If st is null, then we reached the end of the file
Hashtable<String, LinkedList<Triple<String,String,String>>> relations = new Hashtable<String,LinkedList<Triple<String,String,String>>>();
while(st != null){
for(int index = 0; index < st.get_x().get_children().length; index++){
Sentence_tree current_root = st.get_x().get_children()[index];
current_root.set_parent(null); // Remove the reference to the super root.
// Retrieve the interesting subtrees
LinkedList<Tuple<Sentence_tree,Tuple<String,String>>> good_subs = current_root.interesting_subtree(voc, subvoc);
while(!good_subs.isEmpty()){
// For each interesting subtree
Tuple<Sentence_tree,Tuple<String,String>> current = good_subs.pop();
String keyword1 = current.get_y().get_x();
String keyword2 = current.get_y().get_y();
Hashtable<String, String> result = current.get_x().find_relation(keyword1, keyword2);
if(result != null){
LinkedList<Triple<String,String,String>> list;
if(!relations.containsKey(result.get("rel"))){
list = new LinkedList<Triple<String,String,String>>();
list.add(new Triple<String,String,String>(result.get("suj"),result.get("obj"),st.get_y()));
}
else{
list = relations.get(result.get("rel"));
list.add(new Triple<String,String,String>(result.get("suj"),result.get("obj"),st.get_y()));
}
relations.put(result.get("rel"),list);
}
}
}
st = build_next_sentence_tree();
}
return relations;
} |
d81706d2-c2d0-4fab-a812-680fa27e7e58 | 5 | private Map<Integer, Integer> buildLoopIndex(List<Token> tokens) {
Map<Integer, Integer> loopIndex = new HashMap<>();
Stack<Integer> startIndices = new Stack<>();
for (int i = 0; i < tokens.size(); i++) {
switch (tokens.get(i).getType()) {
case LOOP_START:
startIndices.push(i);
break;
case LOOP_END:
if (startIndices.isEmpty()) {
throw new UnbalancedLoopException(i);
}
loopIndex.put(startIndices.pop(), i);
break;
}
}
if (startIndices.size() > 0) {
throw new UnbalancedLoopException(startIndices.pop());
}
return loopIndex;
} |
e771be98-4d04-4fca-bc9f-c4847ee15400 | 5 | @Test
public void testServerSetQueueTimeoutErrorIndividualInvalidEx() {
LOGGER.log(Level.INFO, "----- STARTING TEST testServerSetQueueTimeoutErrorIndividualInvalidEx -----");
boolean exception_other = false;
String client_hash = "";
try {
server2.setUseMessageQueues(true);
} catch (TimeoutException e) {
exception_other = true;
}
try {
server1.startThread();
} catch (IOException | ServerSocketCloseException | FeatureNotUsedException e) {
exception_other = true;
}
waitListenThreadStart(server1);
try {
client_hash = server2.addSocket("127.0.0.1", port);
} catch (IOException | TimeoutException e) {
exception_other = true;
}
waitSocketThreadAddNotEmpty(server2);
waitSocketThreadState(server2, client_hash, SocketThread.CONFIRMED);
waitMessageQueueAddNotEmpty(server2);
waitMessageQueueState(server2, client_hash, MessageQueue.RUNNING);
try {
server2.setQueueTimeoutErrorIndividual(client_hash, -1);
} catch (InvalidArgumentException e) {
exception = true;
} catch (FeatureNotUsedException | NullException | HashNotFoundException e) {
exception_other = true;
}
Assert.assertFalse(exception_other, "Caught an unexpected exception");
Assert.assertTrue(exception, "Successfully ran setQueueTimeoutErrorIndividual on server, should have received an exception");
LOGGER.log(Level.INFO, "----- TEST testServerSetQueueTimeoutErrorIndividualInvalidEx COMPLETED -----");
} |
e1404e6c-4783-4974-bec6-271a321675a6 | 1 | public void visitExpr(final Expr expr) {
if (checkValueNumbers) {
Assert.isTrue(expr.valueNumber() != -1, expr
+ ".valueNumber() = -1");
}
visitNode(expr);
} |
6db677c6-277a-4522-bec1-3b004932e85f | 2 | public void processInput(Deque<KeyEvent> events) {
int eventNumber = events.size();
for (int i = 0; i < eventNumber; i++) {
KeyEvent event = events.pollFirst();
Point direction = keyMapping.get(event.getKeyCode());
if (direction != null) {
schlange.setDirection(direction);
}
}
} |
70bfbb42-5bb8-4fc3-9133-0d9d6f7b3970 | 9 | private boolean r_verb_suffix() {
int among_var;
int v_1;
int v_2;
int v_3;
// setlimit, line 174
v_1 = limit - cursor;
// tomark, line 174
if (cursor < I_pV)
{
return false;
}
cursor = I_pV;
v_2 = limit_backward;
limit_backward = cursor;
cursor = limit - v_1;
// (, line 174
// [, line 175
ket = cursor;
// substring, line 175
among_var = find_among_b(a_6, 38);
if (among_var == 0)
{
limit_backward = v_2;
return false;
}
// ], line 175
bra = cursor;
switch(among_var) {
case 0:
limit_backward = v_2;
return false;
case 1:
// (, line 177
// call R2, line 177
if (!r_R2())
{
limit_backward = v_2;
return false;
}
// delete, line 177
slice_del();
break;
case 2:
// (, line 185
// delete, line 185
slice_del();
break;
case 3:
// (, line 190
// delete, line 190
slice_del();
// try, line 191
v_3 = limit - cursor;
lab0: do {
// (, line 191
// [, line 191
ket = cursor;
// literal, line 191
if (!(eq_s_b(1, "e")))
{
cursor = limit - v_3;
break lab0;
}
// ], line 191
bra = cursor;
// delete, line 191
slice_del();
} while (false);
break;
}
limit_backward = v_2;
return true;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.