method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
6cd060f1-80f5-40c9-8d16-5a9b42948169 | 3 | public AnnotationVisitor visitAnnotation(
final String name,
final String desc)
{
if (values == null) {
values = new ArrayList(this.desc != null ? 2 : 1);
}
if (this.desc != null) {
values.add(name);
}
AnnotationNode annotation = new AnnotationNode(desc);
values.add(annotation);
return annotation;
} |
c5524b52-2b67-4aff-8728-5488c3b0d153 | 9 | private void CreateListeners() {
addMouseListener(
new MouseListener(){
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){
if (seeTrainPoints){
if (displayImage != null){
Point local=adjustPoint(e.getPoint());
if (local != null){
//fire all train click listeners
switch (e.getButton()){
case MouseEvent.BUTTON2: //ie middle click
for (TrainClickListener l:trainClickListeners)
l.DeletePoint(displayImage.getFilename(), local);
break;
case MouseEvent.BUTTON3: //ie right click
for (TrainClickListener l:trainClickListeners)
l.NewNonPoint(displayImage.getFilename(), local);
break;
default: //ie left click or any other click in OS's that don't recognize the constants above
for (TrainClickListener l:trainClickListeners)
l.NewPoint(displayImage.getFilename(), local);
}
}
}
}
repaint();
}
public void mouseReleased(final MouseEvent e){
if (seeTrainPoints)
UpdateMagnifierMouseEvent(e);
}
}
);
addMouseMotionListener(
new MouseMotionListener(){
public void mouseDragged(MouseEvent e){}
public void mouseMoved(MouseEvent e){
trainPanel.UpdateLocationLabel(adjustPoint(e.getPoint()));
}
}
);
} |
992ffc46-76db-4991-841a-9121d0afbd78 | 6 | public int compareTo(Date date) {
if (this._y == date.getYear()) {
if (this._m == date.getMonth()) {
if (this._d == date.getDay()) {
return 0; // =
}
else if (this._d > date.getDay()) {
return 1; // >
}
else { // this._d < date.getDay()
return -1; // <
}
}
else if (this._m > date.getMonth()) {
return 1; // >
}
else { // this._m < date.getMonth()
return -1; // <
}
}
else if (this._y > date.getYear()) {
return 1; // >
}
else { // this._y < date.getYear()
return -1; // <
}
} |
125981a7-c82b-4e19-82e0-ab17acc1fd67 | 9 | public String toString(){
int i;
String tmp = "";
tmp += this.clr==ChessBoard.RED?"RED":"BLUE";
switch(this.direction){
case Chessline.LEFT:
for(i=this.chess_num-1;i>=0;i--){
tmp+="("+(this.start_x-i)+","+this.start_y+")";
}
break;
case Chessline.DOWN:
for(i=this.chess_num-1;i>=0;i--)
{
tmp+="("+this.start_x+","+(this.start_y-i)+")";
}
break;
case Chessline.DOWNLEFT:
for(i=this.chess_num-1;i>=0;i--)
{
tmp+="("+(this.start_x-i)+","+(this.start_y-i)+")";
}
break;
case Chessline.DOWNRIGHT:
for(i=this.chess_num-1;i>=0;i--)
{
tmp+="("+(this.start_x+i)+","+(this.start_y-i)+")";
}
break;
default:
throw new java.lang.RuntimeException("The direction is illegal!");
}
return tmp;
} |
5e9d3339-16e7-42c7-95d7-cd1af576abce | 2 | @Override
public void onEnable(){
spawn = LocationParser.stringToLoc(PKSQLd.getUnparsedData("MAPSPAWN"));
new Damage(this);
new FireProjectile(this);
new Interaction(this);
new InventoryCancel(this);
new MapElementInteractions(this);
new PlayerSpawn(this);
CommandManager.loadAllCommands();
if(!ConfigMain.hasBeenLoaded()){
ConfigMain.loaded();
Broadcast.general("The server has just booted up.");
Broadcast.general("Lobby will start in 30 seconds.");
SchedulerManager.registerSingle(10, new Runnable(){
public void run(){
Broadcast.general("The server has just booted up.");
Broadcast.general("Lobby will start in 20 seconds.");
}
});
SchedulerManager.registerSingle(20, new Runnable(){
public void run(){
Broadcast.general("The server has just booted up.");
Broadcast.general("Lobby will start in 10 seconds.");
}
}); startGameLoad(30);
}else startGameLoad(5);
for(Player p : Bukkit.getOnlinePlayers()){
Bukkit.getPluginManager().callEvent(new PlayerJoinEvent(p, "has remained connected."));
}RealmsMain.setServerMode(ServerMode.PREVOTE);
} |
7c4ac234-4b2d-49cb-8871-26d87296bb00 | 6 | @SuppressWarnings("rawtypes")
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
AbstractEntity other = (AbstractEntity) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
} |
14c372b8-8ec9-4043-ac99-89f570c43491 | 8 | public String getHtml(WikiContext context) throws ChildContainerException {
try {
if (context.getAction().equals("confirm")) {
mPath = context.getPath();
mContainerPrefix = context.getString("container_prefix", null);
if (mContainerPrefix == null) {
throw new RuntimeException("Assertion Failure: mContainerPrefix == null");
}
startTask();
sendRedirect(context, context.getPath());
return "unreachable code";
}
boolean showBuffer = false;
String confirmTitle = null;
String cancelTitle = null;
String title = null;
switch (getState()) {
case STATE_WORKING:
showBuffer = true;
title = "Loading Change Log";
cancelTitle = "Cancel";
break;
case STATE_WAITING:
// Shouldn't hit this state.
showBuffer = false;
title = "Loading Change Log";
confirmTitle = "Load";
cancelTitle = "Cancel";
break;
case STATE_SUCCEEDED:
showBuffer = true;
title = "Read Full Change Log";
confirmTitle = null;
cancelTitle = "Done";
break;
case STATE_FAILED:
showBuffer = true;
title = "Full Read of Change Log Failed";
confirmTitle = "Reload";
cancelTitle = "Done";
break;
}
setTitle(title);
StringWriter buffer = new StringWriter();
PrintWriter body = new PrintWriter(buffer);
body.println("<h3>" + escapeHTML(title) + "</h3>");
if (showBuffer) {
body.println(getListHtml());
body.println("<hr>");
body.println("<pre>");
body.print(escapeHTML(getOutput()));
body.println("</pre>");
}
body.println("<hr>");
addButtonsHtml(context, body, confirmTitle, cancelTitle);
body.close();
return buffer.toString();
} catch (IOException ioe) {
context.logError("Submitting", ioe);
context.raiseServerError("LoadingChangeLog.handle coding error. Sorry :-(");
return "unreachable code";
}
} |
43784f95-88e4-4f45-a9fc-6d7541aaeacd | 6 | final Interface8 method3733(int i, int i_14_, int i_15_, byte[] is,
boolean bool) {
try {
anInt7565++;
if (i_14_ >= -2)
method3644();
if (aBoolean7873 && (!bool || aBoolean7869))
return new Class135_Sub2(this, i, is, i_15_, bool);
return new Class119_Sub2(this, i, is, i_15_);
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("qo.G(" + i + ',' + i_14_ + ','
+ i_15_ + ','
+ (is != null ? "{...}" : "null")
+ ',' + bool + ')'));
}
} |
611ab16e-9098-46d7-a24b-6a4c6929c806 | 6 | public static int[][] lenghtLCS(char[] x, char[] y){
// TODO Auto-generated method stub
int m = x.length;
int n = y.length;
int[][] c = new int[m + 1][n + 1];//保存LCS(Xi,Yj)的长度
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(x[i] == y[j]){
c[i + 1][j + 1] = c[i][j] + 1;
}else{
if(c[i][j + 1] > c[i + 1][j]){
c[i + 1][j + 1] = c[i][j + 1];
}else{
c[i + 1][j + 1] = c[i + 1][j];
}
}
}
}
for(int i=0; i<=m; i++){
for(int j=0; j<=n; j++){
System.out.print(c[i][j] + " ");
}
System.out.println();
}
return c;
} |
dccfcde5-e18a-4b08-bb9b-f88183e688c3 | 2 | protected void assinarGravar() throws IOException, KeyStoreException{
int index = gCrlv.getTableGerenciarCrlvs().getSelectionModel().getLeadSelectionIndex();
if(index > -1){
XStream xstream = new XStream();
ModelCRLV c = gCrlv.getCrlv().get(index);
String xml = xstream.toXML(c);
File f = new File("xmls/", c.getCodRenavam()+".xml");
if(f.exists())
f.delete();
f.createNewFile();
FileWriter x = new FileWriter(f, true);
x.write("<?xml version = \"1.0\" encoding=\"UTF-8\"?>\n" +xml);
x.close();
ModelSigner model = new ModelSigner();
ViewSigner vs = new ViewSigner(model);
ControllerSigner cs = new ControllerSigner(vs, c.getCodRenavam(), true);
mw.getDesktop().add(vs);
vs.setVisible(true);
}
else
JOptionPane.showMessageDialog(mw, "Selecione um documento para ser assinado!");
} |
2c2d8b32-a71f-4a96-91de-727c70557be0 | 0 | public void clearAll() {
undoStack.clear();
redoStack.clear();
} |
bb54b963-5309-4692-be3f-ee34e339b995 | 6 | static int fseek(InputStream fis, long off, int whence) {
if (fis instanceof SeekableInputStream) {
SeekableInputStream sis = (SeekableInputStream) fis;
try {
if (whence == SEEK_SET) {
sis.seek(off);
} else if (whence == SEEK_END) {
sis.seek(sis.getLength() - off);
} else {
}
} catch (Exception e) {
}
return 0;
}
try {
if (whence == 0) {
fis.reset();
}
fis.skip(off);
} catch (Exception e) {
return -1;
}
return 0;
} |
068d60cf-9ea7-4623-a54a-69769aaf5b88 | 3 | public void mainMenu() {
System.out.println("Do you want to save a profile or start a test? SaP = Save StT = Start");
String choice = "";
try {
choice = cache.readLine();
} catch (IOException ex) {
System.out.println(ex.getMessage());
System.exit(-1);
}
choice = choice.toLowerCase();
switch (choice) {
case "sap":
this.saveGame();
break;
case "stt":
this.startGame();
break;
}
} |
f98dd2a1-3516-4b91-b439-5618adeaf776 | 0 | public listByMonth()
{
this.requireLogin = true;
this.info = "list all appointments in a given month";
this.addParamConstraint("timestamp", ParamCons.INTEGER);
} |
fd14f536-e9bf-4cae-bcd3-da9d4a2a0da4 | 1 | public static void decode(String inputImagePath, String outputFilePath) {
//foto ophalen van disk
BufferedImage selectedImage = getImage(inputImagePath);
//kopie maken van geselecteerde foto zodat de foto aangepast kan worden in Java (userspace)
BufferedImage img = cloneImage(selectedImage);
//retrieve message from image
byte[] decodedFile = decodeImage(img);
try {
//Scrijft message naar een file
final File outputFile = new File(outputFilePath);
final OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
outputStream.write(decodedFile);
outputStream.close();
} catch (Exception ex) {
ConsoleHelper.appendError(ex.getMessage());
}
} |
d95f5912-783b-48f9-a9e9-34665cc129eb | 4 | void getDirection(Position dir)
{
dir.x = dir.y = 0;
switch (this)
{
case LEFT:
dir.x = -1;
break;
case RIGHT:
dir.x = 1;
break;
case UP:
dir.y = -1;
break;
case DOWN:
dir.y = 1;
break;
}
} |
f2fd0aff-2e5d-4d0f-ab53-638bc2f5bdc4 | 6 | public void move(Point startMove, Point endMove, int canvasWidth, int canvasHeight)
{
if(((x1 + endMove.getX()-startMove.getX()) >= 0)
&& ((y1 + endMove.getY()-startMove.getY()) >= 0)
&& ((x2 + endMove.getX()-startMove.getX()) < canvasWidth)
&& ((y2 + endMove.getY()-startMove.getY()) < canvasHeight))
{
updateOuterPoints(startMove, endMove);
for(GeometricObject go : geometricObjects)
{
go.move(startMove, endMove, canvasWidth, canvasHeight);
}
for(Connector c : connectors)
{
c.move(startMove, endMove, canvasWidth, canvasHeight);
}
}
} |
9501a1f3-16ee-4a7c-9183-01ee21afda47 | 0 | public void restoreAttempts(){ ReconnectAttempts = 3; } |
17e9c24e-004e-4c75-b38a-77ba615ffbcc | 6 | public void paint(Graphics g) {
super.paint(g);
//Make the square objects
DrawSquareWithColour redSquare = new DrawSquareWithColour();
DrawSquareWithColour blueSquare = new DrawSquareWithColour();
DrawSquareWithColour greenSquare = new DrawSquareWithColour();
DrawSquareWithColour yellowSquare = new DrawSquareWithColour();
//Draw the squares
redSquare.DrawSquare (g, false, Color.red, 450, 100);
blueSquare.DrawSquare (g, false, Color.blue, 700, 100);
greenSquare.DrawSquare (g, false, Color.green, 450, 350);
yellowSquare.DrawSquare(g, false, Color.yellow, 700, 350);
//Stops the thread long enough so if the same colour is shown twice there is a noticeable gap
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
switch (shapeToColour) {
case 0:
redSquare.DrawSquare(g, true, Color.red, 450, 100);
gameInput.add(0);//Add the number corresponding to the colour to the array
break;
case 1:
blueSquare.DrawSquare(g, true, Color.blue, 700, 100);
gameInput.add(1);
break;
case 2:
greenSquare.DrawSquare(g, true, Color.green, 450, 350);
gameInput.add(2);
break;
case 3:
yellowSquare.DrawSquare(g, true, Color.yellow, 700, 350);
gameInput.add(3);
break;
}
if (win) {
new FinishGameImage(g, 50, 350);
}
} |
9411146a-b579-44c1-9d8a-012ba70fb31e | 8 | @Override
int transition(int absState, int position, int vector) {
// null absState should never be passed in
assert absState != -1;
// decode absState -> state, offset
int state = absState/(w+1);
int offset = absState%(w+1);
assert offset >= 0;
if (position == w) {
if (state < 2) {
final int loc = vector * 2 + state;
offset += unpack(offsetIncrs0, loc, 1);
state = unpack(toStates0, loc, 2)-1;
}
} else if (position == w-1) {
if (state < 3) {
final int loc = vector * 3 + state;
offset += unpack(offsetIncrs1, loc, 1);
state = unpack(toStates1, loc, 2)-1;
}
} else if (position == w-2) {
if (state < 6) {
final int loc = vector * 6 + state;
offset += unpack(offsetIncrs2, loc, 2);
state = unpack(toStates2, loc, 3)-1;
}
} else {
if (state < 6) {
final int loc = vector * 6 + state;
offset += unpack(offsetIncrs3, loc, 2);
state = unpack(toStates3, loc, 3)-1;
}
}
if (state == -1) {
// null state
return -1;
} else {
// translate back to abs
return state*(w+1)+offset;
}
} |
e01cdf43-c5a1-47e7-83fd-045bcdfaf2a4 | 4 | public String getUrlFormat(String wikiName) {
String url = this.wikis.get(wikiName);
if (url == null) {
return null;
}
else if (!(url.startsWith("http://") || url.startsWith("https://"))) {
return this.getUrlFormat(url);
}
else {
if (url.contains("%%SEARCHTERMS%%")) {
return url;
}
else {
return url + mediawikiUrlAppend;
}
}
} |
ce5fadd1-a89f-4775-b552-998c408b29cf | 5 | private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
String searchNum = txtSearchPartNo.getText();
if (searchNum != null && searchNum.length() > 0) {
for (int i = 0; i < this.partNums.length; i++) {
if (searchNum.equalsIgnoreCase(partNums[i])) {
foundIndex = i;
break;
}
}
if (foundIndex == NOT_FOUND) {
JOptionPane.showMessageDialog(this,
"Part Number not found. Please try again.",
"Not Found", JOptionPane.WARNING_MESSAGE);
} else {
txtCurProdNo.setText(partNums[foundIndex]);
txtCurDesc.setText(partDescs[foundIndex]);
txtCurPrice.setText("" + partPrices[foundIndex]);
}
} else {
JOptionPane.showMessageDialog(this,
"Please enter a Part No. to search",
"Entry Missing", JOptionPane.WARNING_MESSAGE);
}
}//GEN-LAST:event_btnSearchActionPerformed |
22374b16-d871-4ba9-af77-5638a1b6e172 | 2 | @Override
public List<LinkDirectionCity> load(Criteria criteria, GenericLoadQuery loadGeneric, Connection conn) throws DaoQueryException {
int pageSize = 10;
List paramList = new ArrayList<>();
StringBuilder sb = new StringBuilder(WHERE);
String queryStr = new QueryMapper() {
@Override
public String mapQuery() {
Appender.append(DAO_ID_DIRECTION, DB_DIRCITY_ID_DIRECTION, criteria, paramList, sb, AND);
Appender.append(DAO_ID_CITY, DB_DIRCITY_ID_CITY, criteria, paramList, sb, AND);
if (paramList.isEmpty()) {
return LOAD_QUERY;
} else {
return sb.insert(0, LOAD_QUERY).toString();
}
}
}.mapQuery();
try {
return loadGeneric.sendQuery(queryStr, paramList.toArray(), pageSize, conn, (ResultSet rs, int rowNum) -> {
LinkDirectionCity bean = new LinkDirectionCity();
bean.setIdCity(rs.getInt(DB_DIRCITY_ID_CITY));
bean.setIdDirection(rs.getInt(DB_DIRCITY_ID_DIRECTION));
return bean;
});
} catch (DaoException ex) {
throw new DaoQueryException(ERR_DIR_CITY_LOAD, ex);
}
} |
6a7b85a9-4f05-472f-aa3d-031eb993a2de | 0 | protected void initDefaultCommand() {} |
d798ee82-8f6b-41a9-87ed-32254eb6d547 | 7 | public void plot(int x, int y, int val, boolean isMonochrome, boolean intensifyRed, boolean intensifyGreen, boolean intensifyBlue) {
if (isMonochrome) {
pix[y * SCREEN_WIDTH + x] = PPUConstants.NES_PALETTE[(val & 0x30)].getRGB();
} else if (intensifyRed || intensifyGreen || intensifyBlue) {
// http://wiki.nesdev.com/w/index.php/NTSC_video
// relative = relative * 0.746
// normalized = normalized * 0.746 - 0.0912
float scaleRed = 0.7f;
float scaleGreen = 0.7f;
float scaleBlue = 0.7f;
if (intensifyRed) {
scaleRed = 1.3f;
} else if (intensifyGreen) {
scaleGreen = 1.3f;
} else if (intensifyBlue) {
scaleBlue = 1.3f;
}
pix[y * SCREEN_WIDTH + x] = intensifyColor(PPUConstants.NES_PALETTE[val], scaleRed, scaleGreen, scaleBlue);
} else {
pix[y * SCREEN_WIDTH + x] = PPUConstants.NES_PALETTE[val].getRGB();
}
} |
09e01912-bc5c-47a4-afd0-bac684d86512 | 4 | private Object iceMethodCall(String methodName, Object[] args) {
// Figure the Class of each element of args[]:
Class[] parameterTypes = new Class[args.length];
for (int i = 0; i < args.length; i++) {
parameterTypes[i] = args[i].getClass();
}
try {
Method method = iceClass.getMethod(methodName, parameterTypes);
return (method.invoke(iceBrowser, args));
}
catch (NoSuchMethodException e) {
JOptionPane.showMessageDialog(null,
"No such method in ice.iblite.Browser: " + methodName, "Warning",
JOptionPane.WARNING_MESSAGE);
}
catch (InvocationTargetException e) {
JOptionPane.showMessageDialog(null,
"InvocationTargetException in call to: " + methodName, "Warning",
JOptionPane.WARNING_MESSAGE);
}
catch (IllegalAccessException e) {
JOptionPane.showMessageDialog(null, "IllegalAccessException in call to: "
+ methodName, "Warning", JOptionPane.WARNING_MESSAGE);
}
return null;
} |
b44717f4-489c-4a5c-bb1f-5c61ab99f36e | 0 | public static void main(String[] args) {
boolean t = true, f = false;
System.out.println(t & f); // false
System.out.println(t | f); // true
System.out.println(t ^ f); // true
System.out.println(!t); // false
} |
fb825ab2-5ff7-4fe2-b30d-faabaca43e74 | 9 | static public void main(String[] argv)
{
try {
Blocker blocker = (Blocker)Class.forName(BLOCKER_PACKAGE+argv[0]).newInstance();
StringDistanceLearner learner = DistanceLearnerFactory.build( argv[1] );
MatchData data = new MatchData(argv[2]);
MatchExpt expt = new MatchExpt(data,learner,blocker);
for (int i=3; i<argv.length; ) {
String c = argv[i++];
if (c.equals("-display")) {
expt.displayResults(true,System.out);
} else if (c.equals("-dump")) {
expt.dumpResultsAsStrings(System.out);
} else if (c.equals("-dumpIds")) {
expt.dumpResultsAsIds(System.out);
} else if (c.equals("-shortDisplay")) {
expt.displayResults(false,System.out);
} else if (c.equals("-graph")) {
expt.graphPrecisionRecall(System.out);
} else if (c.equals("-summarize")) {
System.out.println("maxF1:\t" + expt.maxF1());
System.out.println("avgPrec:\t" + expt.averagePrecision());
} else {
throw new RuntimeException("illegal command "+c);
}
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("\nusage: <blocker> <distanceClass> <matchDataFile> [commands]\n");
System.err.println("\nAvailable commands: \n");
for (String s : "display dump dumpIds shortDisplay graph summarize".split(" ")) {
System.err.println("\t"+s);
}
}
} |
a7b741cb-d3d5-4286-ac0a-1eab82b01593 | 2 | private void connect() throws ClassNotFoundException, SQLException
{
try
{
_connection = null;
_statement = null;
// Laedt den MySQL Treiber
Class.forName(DBDRIVER);
// Verbindung mit DB herstellen
String strPassword = this.readPassword();
_connection = DriverManager.getConnection(SERVERNAME, USER, strPassword);
// Statements erlauben SQL Abfragen
_statement = _connection.createStatement();
}
catch (ClassNotFoundException e)
{
_logger.fatal(e.getMessage(), e);
e.printStackTrace();
}
catch (SQLException e)
{
_logger.fatal(e.getMessage(), e);
e.printStackTrace();
}
} |
9080fcdf-8639-49d9-b356-8fc5fe8f13ce | 6 | public void specials(int xSpot, int ySpot, Entity e) {
if (xSpot == 1 && ySpot == 4) {
// level = new LongHall("/maps/longhall.png", screen);
// screen.setScreen(new GameScreen(level));
}
if (xSpot == 1 && ySpot == 4) {
GameScreen.DownStairs.xSpawn = 2;
GameScreen.DownStairs.ySpawn = 4;
Level newlevel = GameScreen.DownStairs;
screen.levelswap(newlevel);
}
if (xSpot == 11 && ySpot == 3) {
e.msg = new String[] {" Use the Aarow keys to move."};
e.special = false;
e.level.popup(e);
}
} |
2cae6a07-a1aa-4a0c-b6f2-68e7ddee2c1a | 6 | private static int Modification(int choosenMenu) {
switch (choosenMenu) {
case 1:
String oldLeagueName;
for (Iterator<String> it = listLeague.keySet().iterator(); it.hasNext();) {
String keyListLeague = it.next();
System.out.println(keyListLeague);
}
System.out.println("Entrez le nom de la ligue à modifier.");
keyboard.nextLine();
do {
oldLeagueName = keyboard.nextLine();
if (listLeague.containsKey(oldLeagueName)) {
break;
} else {
System.out.println("Erreur : Ce nom de ligue n'existe pas, veuillez saisir un nom de ligue valide.");
}
} while (true);
League currentLeague = listLeague.get(oldLeagueName);
System.out.println("Veuillez saisir les nouvelles valeurs (pour ne pas modifier une valeur laisser le champ vide.");
System.out.print("Nom de ligue : ");
String newLeagueName = keyboard.nextLine();
listLeague.remove(oldLeagueName);
currentLeague.setName(newLeagueName);
listLeague.put(newLeagueName, currentLeague);
// System.out.println("1 - Modifier une ligue");
// System.out.println("2 - Modifier une équipe");
// System.out.println("3 - Modifier un match");
// System.out.println("4 - Précédent");
break;
case 2:
break;
case 3:
break;
}
return choosenMenu;
} |
be2b9c13-11dd-4cbe-9a47-88cede75ca62 | 3 | @Override
public Product readObject() throws IOException {
if(receivedProducts == null){
try{
// receivedProducts = jdbcCon.getProductsfromDB(10);
receivedProducts = jdbcCon.getProductsFromIdRange(10,14);
} catch (SQLException e){
e.printStackTrace();
}
}
if(!receivedProducts.isEmpty()){
Product receivedProduct = receivedProducts.get(0);
System.out.println(receivedProduct.getId());
receivedProducts.remove(0);
return receivedProduct;
} else receivedProducts = null;
return null;
} |
cb6a5144-e44a-4165-be50-4058d25e4abe | 0 | public List<String> getSearchedSites() {
return null;
} |
cc82ccd7-0b96-4e00-bf93-bd7fdc03a232 | 8 | private void unfilterPaeth(byte[] curLine, byte[] prevLine) {
final int bpp = this.bytesPerPixel;
final int lineSize = width*bpp;
int i;
for(i=1 ; i<=bpp ; ++i) {
curLine[i] += prevLine[i];
}
for(; i<=lineSize ; ++i) {
int a = curLine[i - bpp] & 255;
int b = prevLine[i] & 255;
int c = prevLine[i - bpp] & 255;
int p = a + b - c;
int pa = p - a; if(pa < 0) pa = -pa;
int pb = p - b; if(pb < 0) pb = -pb;
int pc = p - c; if(pc < 0) pc = -pc;
if(pa<=pb && pa<=pc)
c = a;
else if(pb<=pc)
c = b;
curLine[i] += (byte)c;
}
} |
b78ca302-4b64-45fb-84e5-88aafcc5a922 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Attendee other = (Attendee) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equalsIgnoreCase(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equalsIgnoreCase(other.lastName))
return false;
return true;
} |
0bbf74ff-c2f5-4518-bcc2-1fd4840315f2 | 5 | public void removePlayer(Location loc, Player play, Boolean isBreak){
if(isBreak){
if(this.hPlayerBreakBlock.containsKey(loc))
if(this.hPlayerBreakBlock.get(loc).contains(play))
this.hPlayerBreakBlock.get(loc).remove(play);
}
else{
if(this.hPlayerPlaceBlock.containsKey(loc))
if(this.hPlayerPlaceBlock.get(loc).contains(play))
this.hPlayerPlaceBlock.get(loc).remove(play);
}
} |
50dc113f-c39d-419a-8afd-5bf23c838f40 | 1 | public void prettyPrintJSON(JSONObject oldJSON){
try {
JSONTokener tokener = new JSONTokener(oldJSON.toString()); //tokenize the ugly JSON string
JSONObject finalResult = new JSONObject(tokener); // convert it to JSON object
System.out.println(finalResult.toString(4)); // To string method prints it with specified indentation.
}catch( Exception e){
System.out.println("exception printing pretty JSON: "+e.getMessage() );
}
} |
4b92130b-a77f-4e41-8259-f48614e0ef60 | 1 | @Override
public void mouseEntered(MouseEvent e) {
try {
setImg(ImageIO.read(new File("img/button/button.focus.png")));
} catch (IOException ex) {
ex.printStackTrace();
}
} |
6c20e586-990e-4281-935e-6ab81e8926ab | 9 | public String runMain(String className, String[] args, String stdin) {
Class<?> target;
try {
target = ByteClassLoader.publicFindClass(className);
} catch (ClassNotFoundException e) {
return "Internal error: main class "+className+" not found";
}
Method main;
try {
main = target.getMethod("main", new Class[]{String[].class});
} catch (NoSuchMethodException e) {
return "Class "+className+" needs public static void main(String[] args)";
}
if (stdin != null)
try {
System.setIn(new java.io.ByteArrayInputStream(stdin.getBytes("UTF-8")));
}
catch (SecurityException | java.io.UnsupportedEncodingException e) {
return "Internal error: can't setIn";
}
int modifiers = main.getModifiers();
if (modifiers != (Modifier.PUBLIC | Modifier.STATIC))
return "Class "+className+" needs public static void main(String[] args)";
try {
// first is null since it is a static method
main.invoke(null, new Object[]{args});
return null;
}
catch (IllegalAccessException e) {
return "Internal error invoking main";
}
catch (InvocationTargetException e) {
if (e.getTargetException() instanceof RuntimeException)
throw (RuntimeException)(e.getTargetException());
java.io.StringWriter sw = new java.io.StringWriter();
java.io.PrintWriter pw = new java.io.PrintWriter(sw);
e.getTargetException().printStackTrace(pw);
return "Internal error handling error " + e.getTargetException() + sw.toString();
//if (e.getTargetException() instanceof Error)
// throw (Error)(e.getTargetException());
}
} |
1f0cfa0a-6c1d-48de-b63d-c5950b6cf561 | 5 | private Program applyMutations(Program offspring) throws InvalidProgramException {
int numberOfMutationOps = mutationsOps.size();
for (Mutation m : mutationsOps) {
if (m instanceof KineticRateAlterationForProgram1 || m instanceof InsertionForProgramImpl ||
m instanceof DeletionForProgramImpl ||
randomizer.nextDouble() < mutationProbability) {
offspring = m.mutate(offspring);
}
}
return offspring;
} |
530880e3-8fe9-4f7e-9e93-25f825284389 | 8 | @Test
public void testBogusFile() throws IOException {
final String filename = "test.wav";
final File file = File.createTempFile("testBogusFile", filename);
FileOutputStream out = new FileOutputStream(file);
final Random random = new Random();
for (int i=0; i<8*1024; i++) {
out.write(random.nextInt());
}
out.close();
FFURLInputStream in = null;
try {
in = new FFURLInputStream(file.toURI().toURL());
in.read(new byte[1024]);
fail("Expected UnsupportedAudioFileException");
} catch (UnsupportedAudioFileException e) {
// expected this
e.printStackTrace();
assertTrue(e.toString().endsWith("(Operation not permitted)")
|| e.toString().endsWith("(Invalid data found when processing input)")
|| e.toString().endsWith("(End of file)")
|| e.toString().endsWith("(Invalid data found when processing input)")
|| e.toString().contains("Probe score too low")
);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
file.delete();
}
} |
2a194397-3c1b-4904-bef1-55139a4a26c6 | 4 | private void waitIncomingRequest() throws ShutdownRequestException {
try {
incomingSocket = welcomeServer.accept();
if(shutdownRequested)
throw new ShutdownRequestException();
fromClient = new BufferedReader(
new InputStreamReader(incomingSocket.getInputStream()));
String cmd = fromClient.readLine();
if(cmd.equals(USER_CMD)) {
activeTalk.add(new UserThread(incomingSocket));
activeTalk.lastElement().start();
} else if(cmd.equals(ADMIN_CMD)) {
activeTalk.add(new AdminThread(incomingSocket));
activeTalk.lastElement().start();
} else {
toLog("Incorrect incoming request format. '" + cmd + "'");
}
} catch (IOException e) {
toLog("ERROR: " + e.getMessage());
}
} |
c3be61a2-83cb-4d3e-8aa7-d33839f04c54 | 9 | @Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
char[] source = str.toCharArray();
char[] result = new char[source.length];
int j = 0;
String currentText = this.getText(0, this.getLength());
currentText.toCharArray();
for (int i = 0; i < result.length; i++) {
if (this.type == "Hex") {
if (Character.isDigit(source[i]) || source[i] >= 'A' && source[i] <= 'F' || source[i] >= 'a' && source[i] <= 'f') {
result[j++] = source[i];
} else {
ByteTextField.this.toolkit.beep();
System.err.println("insertString: " + source[i]);
}
} else if (this.type == "Decimal") {
if (Character.isDigit(source[i])) {
result[j++] = source[i];
} else {
ByteTextField.this.toolkit.beep();
System.err.println("insertString: " + source[i]);
}
}
}
super.insertString(offs, new String(result, 0, j), a);
} |
e412c1f0-4fbd-4b81-a214-c876d2573e5f | 0 | protected void doDestroy() {
writeLocks.clear();
readLocks.clear();
logger.info("Sync.destroy");
} |
3553c40b-d357-4679-bd58-9578c3584c06 | 2 | public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (isOptOut()) {
configuration.set("opt-out", false);
configuration.save(configurationFile);
}
// Enable Task, if it is not running
if (task == null) {
start();
}
}
} |
86719c32-6a06-409e-ad5a-46841941fc1d | 9 | private void initPreview(Component parent, ReportState state) {
//
// Save the report state
//
this.state = state;
//
// Create the report view
//
reportView = new ReportView();
reportView.setOpaque(true);
//
// Create the scroll pane containing the report view
//
JScrollPane scrollPane = new JScrollPane(reportView);
//
// Create the dialog tool bar using both icons and text descriptions
//
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
URL imageURL;
JButton button;
imageURL = ReportPreview.class.getResource("/images/Back24.gif");
button = new JButton("Back");
button.setActionCommand("back");
button.addActionListener(this);
if (imageURL != null)
button.setIcon(new ImageIcon(imageURL));
toolBar.add(button);
imageURL = ReportPreview.class.getResource("/images/Forward24.gif");
button = new JButton("Forward");
button.setActionCommand("forward");
button.addActionListener(this);
if (imageURL != null)
button.setIcon(new ImageIcon(imageURL));
toolBar.add(button);
toolBar.addSeparator();
imageURL = ReportPreview.class.getResource("/images/ZoomIn24.gif");
button = new JButton("Zoom In");
button.setActionCommand("zoom in");
button.addActionListener(this);
if (imageURL != null)
button.setIcon(new ImageIcon(imageURL));
toolBar.add(button);
imageURL = ReportPreview.class.getResource("/images/ZoomOut24.gif");
button = new JButton("Zoom Out");
button.setActionCommand("zoom out");
button.addActionListener(this);
if (imageURL != null)
button.setIcon(new ImageIcon(imageURL));
toolBar.add(button);
toolBar.addSeparator();
imageURL = ReportPreview.class.getResource("/images/Print24.gif");
button = new JButton("Print");
button.setActionCommand("print");
button.addActionListener(this);
if (imageURL != null)
button.setIcon(new ImageIcon(imageURL));
toolBar.add(button);
toolBar.addSeparator();
//
// Get the display configuration
//
Toolkit toolkit = Toolkit.getDefaultToolkit();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
Dimension screenSize = toolkit.getScreenSize();
int baseX = 0;
int baseY = 0;
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
screenResolution = toolkit.getScreenResolution();
screenAdjustment = (double)screenResolution/72.0;
Insets screenInsets = toolkit.getScreenInsets(gc);
if (screenInsets != null) {
baseX = screenInsets.left;
baseY = screenInsets.top;
screenWidth -= screenInsets.left+screenInsets.right;
screenHeight -= screenInsets.top+screenInsets.bottom;
}
//
// Size the report view based on the page format and the
// screen resolution
//
PageFormat pageFormat = state.getPageFormat();
viewSize.setSize(pageFormat.getWidth()*screenAdjustment,
pageFormat.getHeight()*screenAdjustment);
zoomSize.setSize(viewSize);
reportView.setPreferredSize(viewSize);
reportView.setMinimumSize(viewSize);
//
// Set the viewport size based on the screen size
//
JViewport viewPort = scrollPane.getViewport();
Dimension scrollSize = viewPort.getPreferredSize();
scrollSize.setSize(Math.min(scrollSize.width, screenWidth-75),
Math.min(scrollSize.height, screenHeight-75));
viewPort.setPreferredSize(scrollSize);
//
// Create the content pane containing the tool bar and the scroll pane
//
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
contentPane.add(toolBar, BorderLayout.NORTH);
contentPane.add(scrollPane, BorderLayout.CENTER);
setContentPane(contentPane);
//
// Position the dialog window relative to the parent and ensure that
// it will fit within the screen insets
//
pack();
setLocationRelativeTo(parent);
Rectangle bounds = getBounds();
if (bounds.x-baseX+bounds.width > screenWidth)
bounds.setLocation(baseX, bounds.y);
if (bounds.y-baseY+bounds.height > screenHeight)
bounds.setLocation(bounds.x, baseY);
setBounds(bounds);
//
// Build the report
//
reportPage = new ReportPage(state);
numPages = reportPage.paginate();
//
// Display the first page
//
if (numPages != 0) {
displayPage();
setTitle(state.getReportTitle()+" - Page 1 of "+numPages);
}
} |
7365a3c7-8f20-4dd3-9a23-8812118ebdd8 | 5 | void setSortDirection (int value) {
if (value == sort) return;
boolean widthChange = value == SWT.NONE || sort == SWT.NONE;
sort = value;
if (widthChange) {
/*
* adding/removing the sort arrow decreases/increases the width that is
* available for the column's header text, so recompute the display text
*/
GC gc = new GC (parent);
computeDisplayText (gc);
gc.dispose ();
}
if (parent.drawCount <= 0 && parent.getHeaderVisible ()) {
/* don't damage the header's drawn borders */
parent.header.redraw (getX (), 1, width - 2, parent.getHeaderHeight () - 3, false);
}
} |
461299b6-8462-45eb-9300-0cb68e057642 | 7 | public void run() {
try {
this.server = new ServerSocket(sconf.getPort());
while (true) {
this.socket = server.accept();
try {
Packet p = Packet.readSocket(socket);
PacketReader pr = p.getByteBufferReader();
PacketType ptype = GamePacketType.valueOf(p.getTypeID());
switch ((GamePacketType) ptype) {
case PACKET_CLIENT_COMPANY_INFO:
procClientCompanyInfo(p);
break;
case PACKET_CLIENT_QUIT:
procClientQuit();
break;
case PACKET_CLIENT_JOIN:
break;
default:
System.out.println("Rcvd "+GamePacketType.valueOf(p.getTypeID()));
break;
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} |
cf3ef1be-3b92-45a6-9163-48befbc790d5 | 6 | public void letterGuessedByUser(String letter, int mode) {
switch (mode) {
case NORMAL_MODE:
lettersGuessed.add(letter);
feedbackToUser = feedbackFor(theAnswer);
updatePossibleAnswers();
break;
case HURTFUL_MODE:
lettersGuessed.add(letter);
feedbackToUser = mostCommonFeedback(generateFeedbackMap());
updatePossibleAnswers();
break;
case HELPFUL_MODE:
lettersGuessed.add(letter);
Map<String, Integer> feedbackMap = generateFeedbackMap();
String mostCommon = mostCommonFeedback(feedbackMap);
Iterator<Map.Entry<String, Integer>> itr = feedbackMap.entrySet()
.iterator();
while (itr.hasNext()) {
Map.Entry<String, Integer> e = itr.next();
if (!e.getKey().contains(letter)) {
itr.remove();
}
}
if (feedbackMap.size() != 0) {
feedbackToUser = mostCommonFeedback(feedbackMap);
} else
feedbackToUser = mostCommon;
updatePossibleAnswers();
break;
default:
break;
}
} |
00e0ab5e-c8c7-44a5-894c-2d03c0375b49 | 3 | private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
if (existeUsuarioSelecionado() && exclusaoConfirmada()) {
try {
excluir();
} catch (ValidacaoException ex) {
_unitOfWork.rollback();
JOptionPane.showMessageDialog(this, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
}
}
}//GEN-LAST:event_btnExcluirActionPerformed |
a02a21b2-27bf-43e9-b7db-7ed6471e6984 | 8 | public void putAll( Map<? extends Integer, ? extends Byte> map ) {
Iterator<? extends Entry<? extends Integer,? extends Byte>> it =
map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends Integer,? extends Byte> e = it.next();
this.put( e.getKey(), e.getValue() );
}
} |
0a06af61-7aad-41be-be8e-6fbdf6a1cece | 3 | public void removeLocallyDeclareable(Set set) {
if (type == FOR && initInstr instanceof StoreInstruction) {
StoreInstruction storeOp = (StoreInstruction) initInstr;
if (storeOp.getLValue() instanceof LocalStoreOperator) {
LocalInfo local = ((LocalStoreOperator) storeOp.getLValue())
.getLocalInfo();
set.remove(local);
}
}
} |
e61d9a0f-67f0-43a2-bbe9-7098b7e50678 | 2 | public void moveEnemies() {
for (Enemy e : getEnemyList()) {
if(e.isAlive()){
e.setPosX(e.getPosX() + e.speed);
}
}
} |
9e22242b-1de1-4ae1-91c4-d3fa1461dc86 | 1 | private void loadImages() {
try {
slate = ImageIO.read(this.getClass().getResource("computer.png"));
java = ImageIO.read(this.getClass().getResource("java.png"));
pane = ImageIO.read(this.getClass().getResource("pane.png"));
} catch (IOException ex) {
Logger.getLogger(Textures.class.getName()).log(Level.SEVERE, null, ex);
}
} |
a988c36f-a451-4c7e-b41f-115b3155b147 | 7 | @Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if((affected!=null)
&&(affected instanceof Room)
&&(msg.amITarget(affected))
&&(newRoom().fetchEffect(ID())==null)
&&((msg.targetMinor()==CMMsg.TYP_LOOK)||(msg.targetMinor()==CMMsg.TYP_EXAMINE)))
{
final CMMsg msg2=CMClass.getMsg(msg.source(),newRoom(),msg.tool(),
msg.sourceCode(),msg.sourceMessage(),
msg.targetCode(),msg.targetMessage(),
msg.othersCode(),msg.othersMessage());
if(newRoom().okMessage(myHost,msg2))
{
newRoom().executeMsg(myHost,msg2);
return false;
}
}
return super.okMessage(myHost,msg);
} |
ce656cad-6ded-4349-a4bc-76ec97cae9d7 | 2 | @Override
public void keyReleased(KeyEvent e) {
if(e.getSource().equals(pfPassword)) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
validatePassUser();
}
}
} |
125d6c76-83ce-4e32-a03c-ff91746c692d | 6 | public void currentBids(){
auctions.removeAll(auctions);
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
}
PreparedStatement ps = null;
Connection con = null;
ResultSet rs;
try {
con = DriverManager.getConnection("jdbc:mysql://mysql2.cs.stonybrook.edu:3306/mlavina", "mlavina", "108262940");
if (con != null) {
con.setAutoCommit(false);
try {
String sql = "SELECT * FROM Auctions WHERE AccountNo = ? AND AirlineID = ? AND FlightNo = ? AND Class = ? ORDER BY `Date` DESC LIMIT 0,1;";
ps = con.prepareStatement(sql);
ps.setInt(1, accountNo);
ps.setString(2, selectedAuction.airlineId);
ps.setInt(3, selectedAuction.flightNo);
ps.setString(4, selectedAuction.seatClass);
ps.execute();
rs = ps.getResultSet();
while (rs.next()) {
auctions.add(new Auction(rs.getString("AirlineID"), rs.getInt("FlightNo"), rs.getString("Class"), rs.getTimestamp("Date"), rs.getDouble("NYOP"), rs.getInt("Accepted")));
}
con.commit();
} catch (Exception e) {
con.rollback();
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
con.setAutoCommit(true);
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
d6ac2bfa-7761-480e-9359-463f660b81a1 | 8 | @Override
public void setValueAt(Object value, int row, int col) {
if (data != null) {
Boolean readOnly = (Boolean) getYProperty().get(YIComponent.READ_ONLY);
if (readOnly == null || !readOnly.booleanValue()) {
Object rowObject = data.get(row);
String fieldName = (String) columns[col].
getYProperty().get(YIComponent.MVC_NAME);
if (fieldName == null) {
// the column is not connected to any special POJO field, updating the whole row POJO:
// checking if value has truly changed:
if (ObjectUtils.equals(rowObject, value)) {
return;
}
data.set(row, value);
YTable.this.modelCollection.remove(rowObject);
YTable.this.modelCollection.add(value);
} else {
// setting value into the row POJO
// checking if value has truly changed:
try {
if (ObjectUtils.equals(value,
YCoreToolkit.getBeanValue(rowObject, fieldName))) {
return;
}
} catch (Exception ex) {
controller.modelGetValueFailed(new YModelGetValueException(ex, YTable.this));
}
try {
YCoreToolkit.setBeanValue(rowObject, fieldName, value);
} catch (Exception ex) {
controller.modelSetValueFailed(new YModelSetValueException(ex,
YTable.this, value));
}
}
YTable.this.lastEditedRow = row;
YTable.this.lastEditedColumn = col;
autoInsertCancel = false; // cell has been changed, not cancelling auto-insert row
// triggering ContentChanged event:
String methodName = YUIToolkit.createMVCMethodName(YTable.this, "Changed");
Object[] params = {new YTableChangeData(row, col, value)};
Class[] paramClasses = {YTableChangeData.class};
controller.invokeMethodIfFound(methodName, params, paramClasses);
controller.updateModelAndController(YTable.this);
}
fireTableCellUpdated(row, col);
}
} |
a59fe6bb-092d-4045-a540-110dc34df549 | 2 | @Override
public void salvar(Secao secao) throws LojaDLOException {
if (secao.getId() != null){
Secao secaoFinal = dao.obter(secao.getId());
secaoFinal.setNome(secao.getNome());
secaoFinal.setDescricao(secao.getDescricao());
} else {
if (dao.obter(secao.getNome()) == null){
dao.incluir(secao);
} else {
throw new LojaDLOException("Este nome já existe");
}
}
} |
4475f346-63af-4a07-861f-ef62cdebf13f | 8 | public XConstPoolImpl(ObjectInput in) throws IOException{
int size = in.readUnsignedShort();
ints = new int[size];
for(int i=0; i<size; i++){
ints[i] = in.readInt();
}
size = in.readUnsignedShort();
longs = new long[size];
for(int i=0; i<size; i++){
longs[i] = in.readLong();
}
size = in.readUnsignedShort();
floats = new float[size];
for(int i=0; i<size; i++){
floats[i] = in.readFloat();
}
size = in.readUnsignedShort();
doubles = new double[size];
for(int i=0; i<size; i++){
doubles[i] = in.readDouble();
}
size = in.readUnsignedShort();
strings = new String[size];
for(int i=0; i<size; i++){
strings[i] = in.readUTF();
}
size = in.readUnsignedShort();
bytes = new byte[size][];
for(int i=0; i<size; i++){
int size2 = in.readUnsignedShort();
byte[] b = new byte[size2];
int readed = size2==0?0:in.read(b);
if(readed!=size2){
throw new IOException("Expected "+size2+" bytes but got "+readed);
}
bytes[i] = b;
}
} |
ec772327-0838-45aa-8983-8eb17a0815c7 | 6 | public boolean orMethod(Pair p) {
if (p == null) {
return false;
} else if (p.getCdr().getCar() == null) {// call has no expressions
return false;
}
if (p.getCar() != null && p.getCdr() == null) {// end of expressions
return Boolean.parseBoolean(run(((Pair) p.getCar())).toString());
} else if (Boolean.parseBoolean(run(((Pair) p.getCar())).toString()) == true
&& p.getCdr() != null) {
return orMethod(p.getCdr());
}
return false;
} |
162eac7f-9b2e-43a7-aa42-f9d0223f71ef | 1 | private void createPlanTickets() throws Exception
{
//Here we are creating plan tickets those can be free sold between any two stations.
int maxStopSeq = this._route.getStops().size() - 1;
StopRangeGroup fullRangeGroup = new StopRangeGroup();
StopRange stopRange = new StopRange();
stopRange.start = 0;
stopRange.end = maxStopSeq;
fullRangeGroup.setRange(stopRange);
this._stopRangeGroups.add(fullRangeGroup);
for(OperatingSeat seat : Queries.query(this._train.getCars()).selectMany(new Selector<Car, Iterable<OperatingSeat>>(){
@Override
public Iterable<OperatingSeat> select(Car item) {
return item.getSeats();
}}))
{
PlanTicket pt = new PlanTicket();
pt.setStartStop(0);
pt.setEndStop(maxStopSeq);
pt.setId(UUID.randomUUID());
pt.setOrginalId(pt.getId());
pt.setSeat(seat);
SalableRange range = pt.getSalableRange();
range.setDepartureStart(0);
range.setDepartureEnd(maxStopSeq);
range.setDestinationStart(0);
range.setDestinationEnd(maxStopSeq);
fullRangeGroup.getTickets().add(pt);
pt.setGroup(fullRangeGroup);
// break;
}
} |
c71eaec3-0d3e-43e8-9776-69baf076ef03 | 0 | public void SetOnBusTicks(int onBusTicks)
{
//set the tick time person got on the bus
this.onBusTicks = onBusTicks;
} |
e88e282a-9feb-409c-b071-91c0f14a02d4 | 9 | public static void main(String[] args) throws Throwable{
Escaner sc = new Escaner();
for (int c = 0, C = sc.nextInt(); c < C; c++) {
TreeSet<Tablero> noVisitar = new TreeSet<Tablero>();
TreeSet<Tablero> visitados = new TreeSet<Tablero>();
LinkedList<Tablero> cola = new LinkedList<Tablero>();
Tablero tabInicial = new Tablero(new int[]{sc.nextInt(), sc.nextInt(), sc.nextInt(), sc.nextInt()}, 0);
Tablero tabFinal = new Tablero(new int[]{sc.nextInt(), sc.nextInt(), sc.nextInt(), sc.nextInt()}, 0);
for(int i = 0, N = sc.nextInt(); i < N; i++)
noVisitar.add(new Tablero(new int[]{sc.nextInt(), sc.nextInt(), sc.nextInt(), sc.nextInt()}, 0));
cola.add(tabInicial);
visitados.add(tabInicial);
while(!cola.isEmpty()){
if(tabFinal.compareTo(cola.getFirst()) == 0)break;
Tablero tab = cola.removeFirst();
for (int i = 0; i < 4; i++)
for (int j = -1; j < 2; j+=2) {
int[] temp = tab.pos.clone();
temp[i]+=j;
Tablero t = new Tablero(temp, tab.pasos + 1);
if(!noVisitar.contains(t) && !visitados.contains(t)){
cola.add(t);
visitados.add(t);
}
}
}
if(cola.isEmpty())System.out.println(-1);
else System.out.println(cola.getFirst().pasos);
}
} |
d1fbbc59-3caf-4a39-ad62-e67b4445b250 | 0 | public static void setEventDesription(String eventDescription){
EventDescriptionWindow.eventDescription.append(eventDescription);
} |
a8658d63-520e-4d80-924d-15e60e433cbf | 2 | public double standardizedAllResponsesMean(){
if(!this.dataPreprocessed)this.preprocessData();
if(!this.variancesCalculated)this.meansAndVariances();
return this.standardizedAllResponsesMean;
} |
3dd82429-b079-4f62-b9b3-98119a0fd535 | 0 | public double get2CoordLat()
{
return markerRect.get2CoordLat();
} |
4dbfd0f9-81ca-4882-976d-ac60903a0fa0 | 6 | public void factory_order() {
draw_.clear();
discard_.clear();
int deck_size = 52;
if (has_jokers_) deck_size = 54;
for (int i = 0; i < size_; ++i) {
Suit temp;
if (i % deck_size < 13) { temp = Suit.SPADES; }
else if (i % deck_size < 26) { temp = Suit.DIAMONDS; }
else if (i % deck_size < 39) { temp = Suit.CLUBS; }
else if (i % deck_size < 52) { temp = Suit.HEARTS; }
else { temp = Suit.JOKERS; }
draw_.add( new Card( (i % 13) + 1, temp ) );
}
} |
8c572127-b515-4fa1-829e-e9f6e4efbb08 | 0 | public OrderQuestView() {
super();
setLayout(null);
addAnswersTable();
colNum = 0;
rowNum = 0;
// quest = QuestFactory.createQuest(QuestType.ORDERQUEST);
} |
88167c48-4679-4020-9bf5-e70159695cd7 | 7 | protected String getDataType()
{
int offset = getOffsetInDataHeaderForDataName();
int maxLength = getDataNameMaxLength();
int nameLength = 0;
// skip first 0
while ( (0 != dataHeader[offset + nameLength]) && (nameLength < maxLength) )
nameLength++;
if (nameLength >= maxLength) return null;
int typeLength = nameLength + 1;
while ( (0 != dataHeader[offset + typeLength]) && (typeLength < maxLength) )
typeLength++;
if (typeLength >= maxLength) return null;
if ((offset + nameLength + 1) == typeLength) return null;
return new String(dataHeader, offset + nameLength + 1, typeLength - (offset + nameLength + 1));
} |
179c7630-4857-48f3-8798-2bda0dd973c6 | 1 | public static void main(String[] args) throws InterruptedException, IOException {
String id = args.length == 0 ? "Dummy_"+System.currentTimeMillis() : args[0];
client = new NettyClient(id);
client.setListener(new PrintingListener());
client.connect("localhost", 1883);
beInteractive();
client.disconnect();
} |
802fc670-692d-42a3-ad47-33675d7526cc | 4 | @SuppressWarnings("unchecked")
public T getAdaptiveExtension() {
if (!hasAdaptiveAnnotation()) {
throw new IllegalStateException("Adaptive annotation not found in class : " + iFaceType);
}
Object instance = cachedAdaptiveInstance.get();
if (instance == null) {
synchronized (cachedAdaptiveInstance) {
instance = cachedAdaptiveInstance.get();
if (instance == null) {
try {
instance = createAdaptiveExtension();
cachedAdaptiveInstance.set(instance);
} catch (Throwable t) {
throw new IllegalStateException("fail to create adaptive instance: " + t.toString(), t);
}
}
}
}
return (T) instance;
} |
6a2528cf-7f83-45f3-850c-8599f5a9631b | 7 | public void choix_utilisateur() {
choix = sc.nextLine();
if (choix.equals("")) {
choix = "0";
System.out.println("Choix vide --- QUITTER");
}
System.out.println("------------------------");
int n = Integer.parseInt(choix);
switch(n) {
case 0 :
// QUITTER
System.out.println("Vous venez de quitter.");
System.out.println("------------------------");
break;
case 1 :
// VOIR POKEDECK
sousMenu.parcoursDeck(paquetJoueur);
System.out.println("------------------------");
break;
case 2 :
// AJOUTER CARTE
sousMenu.ajoutCarteDansDeck(paquetJoueur);
System.out.println("------------------------");
break;
case 3 :
// SUPPRIMER CARTE
sousMenu.supprimerCarteDansDeck(paquetJoueur);
System.out.println("------------------------");
break;
case 4 :
// MODIFIER CARTE
sousMenu.modifierCarteDansDeck(paquetJoueur);
System.out.println("------------------------");
break;
case 5 :
// RECHERCHER CARTE
sousMenu.rechercherCarte(paquetJoueur);
System.out.println("------------------------");
break;
default :
System.out.println("Ce n'est pas un choix valide !");
break;
}
} |
c7da8e33-f32a-4ab2-8d6f-2c60c15f4ff9 | 5 | public boolean canPlace() {
// This only gets called just before entering the world, so I think I can
// put this here. TODO: Move the location-verification code from the
// TerrainGen class to here? ...Might be neater.
final World world = origin().world ;
for (Tile t : world.tilesIn(area(), false)) {
if (t == null || t.blocked()) return false ;
if (type == TYPE_DUNE && t.habitat() != Habitat.DUNE) return false ;
}
return true ;
} |
d8bb0863-0059-49c2-b7fc-472535590a91 | 7 | public static Rule_QUOT parse(ParserContext context)
{
context.push("QUOT");
boolean parsed = true;
int s0 = context.index;
ArrayList<Rule> e0 = new ArrayList<Rule>();
Rule rule;
parsed = false;
if (!parsed)
{
{
ArrayList<Rule> e1 = new ArrayList<Rule>();
int s1 = context.index;
parsed = true;
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Terminal_NumericValue.parse(context, "%x22", "[\\x22]", 1);
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
e0.addAll(e1);
else
context.index = s1;
}
}
rule = null;
if (parsed)
rule = new Rule_QUOT(context.text.substring(s0, context.index), e0);
else
context.index = s0;
context.pop("QUOT", parsed);
return (Rule_QUOT)rule;
} |
e4643815-e30a-4412-8ac2-10fc844d64d5 | 2 | public int fbMethod(int n)
{
if(n ==2 || n == 1)
{
return 1;
}
else
{
return fbMethod(n -2) + fbMethod(n -1);
}
} |
cbc524bb-5f4c-4256-afa6-d54c9f338169 | 5 | @Override
public Path shortestPath(Vertex a, Vertex b) {
Hashtable<Vertex,Integer> distance=new Hashtable<Vertex,Integer>();
Hashtable<Vertex,Vertex> path=new Hashtable<Vertex,Vertex>();
Hashtable<Vertex,Integer> heur = new Hashtable<Vertex,Integer>();
Iterator<Vertex> r = new Iterator<Vertex>(graph.getVertices());
MinHeap<Vertex> h = new MinHeap<Vertex>(graph.getVertices().size());
while(r.hasNext()){
Vertex v = r.getNext();
distance.put(v, Integer.MAX_VALUE-10000);
heur.put(v, this.heuristics.getHeuristics(v, b));
path.put(v, null);
}
distance.put(a,0);
r.clear();
while(r.hasNext()){
Vertex v = r.getNext();
h.insert(distance.get(v)+this.heuristics.getHeuristics(v, b), v);
}
Vertex u = h.pop();
while(!h.isEmpty()){
LinkedList<Vertex> adjacencyVertices = graph.getAdjacencyVertices(u);
Iterator<Vertex> i = new Iterator<Vertex>(adjacencyVertices);
while(i.hasNext()){
Vertex v = i.getNext();
if(h.inHeap(v)){
super.relax(u,v,distance,path);
h.decrease(v,distance.get(v)+heur.get(v));
}
}
u=h.pop();
}
return super.getPath(a,b,path,distance);
} |
81c1a18f-e789-4a21-9c7f-4be862ed3603 | 4 | public void resizeMovingACorner(int corner, int posX, int posY){
int newWidth, newHeight;
if(corner == Drawable.TOP_LEFT_HAND_CORNER){
newWidth = getWidth() + (getOriginX()-posX);
newHeight = getHeight() + (getOriginY()-posY);
setWidth(newWidth);
setHeigth(newHeight);
this.moveOrigin(posX, posY);
}else if(corner == Drawable.BOTTOM_LEFT_HAND_CORNER){
newWidth = getWidth() + (getOriginX()-posX);
newHeight = posY - getOriginY();
setHeigth(newHeight);
setWidth(newWidth);
this.setOriginX(posX);
}else if(corner == Drawable.TOP_RIGHT_HAND_CORNER){
newWidth = posX - getOriginX();
newHeight = getHeight() - (posY-getOriginY());
setWidth(newWidth);
setHeigth(newHeight);
setOriginY(posY);
}else if(corner == Drawable.BOTTOM_RIGHT_HAND_CORNER){
setWidth(posX-getOriginX());
setHeigth(posY-getOriginY());
}
adaptNegative();
recalculate();
} |
7dea2c09-8022-40e4-8a01-80c8ad3c4916 | 4 | public void paintComponent(Graphics g){
BufferedImage image = null;
if(data.orientation == 0){
if(focused){
image = topBgImageFocused;
}
else{
image = topBgImage;
}
}
else if(data.orientation == 1){
if(focused){
image = bottomBgImageFocused;
}
else{
image = bottomBgImage;
}
}
g.drawImage(image, 0, 0, null);
super.paintComponent(g);
} |
fc297bca-ea01-40b3-a345-20284710bfbd | 5 | public void secondInterval() {
boolean test = false;
if (test || m_test) {
System.out.println("Timer :: secondInterval() BEGIN");
}
try {
Thread.sleep(SECOND);
} catch (Exception e) {
System.out.println("hey");
}
if (test || m_test) {
System.out.println("Timer :: secondInterva() END");
}
} |
b06e7167-b44a-4382-bf6a-8d89a4cbd6fa | 2 | @Override
public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd, String[] args) {
if (!Commands.isPlayer(sender)) return false;
Player p = (Player) sender;
if (args.length == 0) {
channel.leaveChannel(p, PlayerChat.plugin.CustomChat.get(p.getName()));
return true;
} else {
channel.leaveChannel(p, args[0]);
return true;
}
} |
6a324e26-99dc-4f4a-ba61-a848f31c3431 | 1 | public static void main(String ... args) {
File f = new File("src/img/8000bce-600bce/East_Asia");
int length = f.listFiles().length;
for(int i = 0; i < length; ++i) {
System.out.println(f.listFiles()[i].getName());
}
} |
9e0e1124-184a-403e-9861-8c7b35166db6 | 0 | public List findBySampleCode(Object sampleCode) {
return findByProperty(SAMPLE_CODE, sampleCode);
} |
753cbbd8-ac43-4743-bfe9-633c449d5a4d | 1 | public static void main(String[] args) {
/*
Exceptions - Rules to Remember
* A try block may be followed by multiple catch blocks, and the catch blocks may be followed by a single
finally block
* A try block may be followed by either a catch or a finally block or both. However, a finally block alone
wouldn't suffice if code in the try block throws a checked exception.
* The try, catch and finally block can't not exist independently.
* The finally block can't appear before a catch block.
* A finally block always executes, regardless of whether the code throws an exception.
*/
// invalid array index (maximum value is [3])
String[] students = {"Benjamin", "Joe", "Matthew"};
try {
System.out.println(students[5].toString());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("error thrown");
e.printStackTrace();
} finally {
/*
Exam Tip - The finally block will execute regardless of whether the try blocks throws an exception
*/
System.out.println("Finally Block is always executed");
}
System.out.println("code has continued to run");
/*
Why handle exceptions separately?
For actual conditions you may have to verify whether you've completed the previous step before you can
progress with the next step.
If exception handlers are defined separately, any confusion with the steps that you need to accomplish to
complete an action (or set of actions) has been clarified. Additionally, the code doesn't compromise the
completion of a step before moving on to the next step, courtesy of teh appropriate exception handlers.
If an exception is thrown, a catch statement can process the exception (printStackTrace() / log) and continue
to process the remainder of the code, the application will not fall over (unless you tell it to).
Do exceptions offer any other benefits?
Apart from separating concerns between defining the regular program logic and the exception handling code,
exceptions also can help pinpoint the offending code (code that throws an exception), together with the
method in which it is defined, by providing a stack trace of the exception or error.
What happens when an exception is thrown?
* An exception is a Java object.
* All types of exceptions subclass java.lang.Throwable.
* When a piece of code hits an obstacle in the form of an exceptional condition, it creates an object of
class java.lang.Throwable (at runtime an object of the most appropriate subtype will be created) and is then
assigned a type.
* This newly created object is then handed to the JVM, the JVM blows a siren in the form of this exception
and looks for an appropriate code block that can "handle" this exception.
*/
} |
2809ed3f-5355-4a19-8a96-6e0319a6d93a | 8 | public void receiveFirst() {
System.out.println("-- Bob --");
if (betray) {
System.out.println("ACHTUNG: Betrugsmodus aktiv!!!");
}
// Part 0 ---------------------------------------------------------------
// Hard coded ElGamal
BigInteger El_p_B = new BigInteger("7789788965135663714690749102453072297748091458564354001035945418057913886819451721947477667556269500246451521462308030406227237346483679855991947569361139");
BigInteger El_g_B = new BigInteger("6064211169633122201619014531987050083527855665630754543345421103270545526304595525644519493777291154802011605984321393354028831270292432551124003674426238");
BigInteger El_y_B = new BigInteger("3437627792030969437324738830672923365331058766427964788898937390314623633227168012908665090706697391878208866573481456022491841700034626290242749535475902");
// private:
BigInteger El_x_B = new BigInteger("3396148360179732969395840357777168909721385739804535508222449486018759668590512304433229713789117927644143586092277750293910884717312503836910153525557232");
// Objekt initialisieren mit priv key
ElGamal elGamal_B = new ElGamal(El_p_B, El_g_B, El_y_B, El_x_B);
// Bob empfängt Alice ElGamal pub key
BigInteger El_p_A = new BigInteger(Com.receive(), 16); // R1
BigInteger El_g_A = new BigInteger(Com.receive(), 16); // R2
BigInteger El_y_A = new BigInteger(Com.receive(), 16); // R3
// ElGamal Objekt ohne priv key bauen
ElGamal elGamal_A = new ElGamal(El_p_A, El_g_A, El_y_A);
// Bob sendet ElGamal public key an Alice
Com.sendTo(0, elGamal_B.p.toString(16)); // S1
Com.sendTo(0, elGamal_B.g.toString(16)); // S2
Com.sendTo(0, elGamal_B.y.toString(16)); // S3
// Vertrag einlesen
String vertrag_B = vertragString(new File("vertrag.txt"));
// Bob empfängt n, p_A und M
int n = Integer.parseInt(Com.receive(), 16); // R4
BigInteger p_A = new BigInteger(Com.receive(), 16); // R5
BigInteger M = new BigInteger(Com.receive(), 16); // R6
if (!p_A.isProbablePrime(100)) {
System.out.println("Bobs p_B is keine Primzahl!");
System.exit(1);
}
// eigene Primzahl M < p_B < 2^52
BigInteger p_B = computePrimeBetween(M);
// Bob sendet p_B an Alice
Com.sendTo(0, p_B.toString(16)); // S4
// Part 1 ---------------------------------------------------------------
// Arrays bauen
BigInteger[][] B = getDoubleArray(n, p_B);
System.out.println("Bob:");
BigInteger[] C_B = get_C_Array(M, B, p_B);
BigInteger[] C_A = new BigInteger[2 * n];
for (int i = 0; i < C_B.length; i++) {
C_A[i] = new BigInteger(Com.receive(), 16); // Ri
System.out.println("Receive C_A[i]: " + C_A[i].toString(16));
Com.sendTo(0, C_B[i].toString(16)); // Si
System.out.println("Send C_B[i]: " + C_B[i].toString(16));
}
System.out.println("Bob:");
for (int i = 0; i < C_A.length; i++) {
System.out.println("C_A[i] = " + C_A[i]);
}
for (int i = 0; i < C_B.length; i++) {
System.out.println("C_B[i] = " + C_B[i]);
}
// Empfange erklärung, text und signed hash von alice
String erklaerung_A = Com.receive(); // R5
String vertrag_A = Com.receive(); // R6
BigInteger H_A_signed = new BigInteger(Com.receive(), 16); // R7
System.out.println("Erklaerung_A: " + erklaerung_A);
System.out.println("vertrag_A: " + vertrag_A);
System.out.println("H_A_signed: " + H_A_signed);
String erklaerung_B = erklaerungBob(C_B);
String text_B = erklaerung_B + vertrag_B;
BigInteger H_B = computeSHA(text_B);
BigInteger H_B_signed = elGamal_B.sign(H_B);
// Sende erklärung, text, signed hash
Com.sendTo(0, erklaerung_B); // S5
Com.sendTo(0, vertrag_B); // S6
Com.sendTo(0, H_B_signed.toString(16)); // S7
// check sig
BigInteger H_A = computeSHA(erklaerung_A + vertrag_A);
if (Com.receive() == "1") {
System.out.println("Alice bricht ab!");
System.exit(1);
}
if (elGamal_A.verify(H_A, H_A_signed)) {
System.out.println("Jo is signed!");
Com.sendTo(0, "0");
} else {
System.out.println("Is nich signed, Exit!");
Com.sendTo(0, "1");
System.exit(1);
}
// Geheimnisprotokoll
BigInteger[][] A = geheimnisBob(n, 4, 51, B);
System.out.println("Bob: Checking Arrays !-o-o-o-o-o-!");
BigInteger[] C2_A = get_C_Array(M, A, p_A);
if (check(C_A, C2_A)) {
System.out.println("Bob: Alles klar!");
} else {
System.out.println("Bob: FUUUUUUUUU");
System.exit(0);
}
} |
d9477380-d807-48d2-982f-e6b18aa65d50 | 9 | protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
} |
e99d6b67-6e57-4415-a155-2e9efcccf5e7 | 5 | public LinkedList<String> list() {
LinkedList<String> files = new LinkedList<String>();
if(carrierString!=null) {
if(carrierString.length()>0) {
files.add(CARRIER_PATCH.substring(CARRIER_PATCH.lastIndexOf("/")+1));
}
}
if(textColour!=null) {
if(textColour!=Color.WHITE) {
files.add(TEXTCOLOUR_PATCH.substring(TEXTCOLOUR_PATCH.lastIndexOf("/")+1));
}
}
if(opacity!=100) {
files.add(OPACITY_PATCH.substring(OPACITY_PATCH.lastIndexOf("/")+1));
}
return files;
} |
0a65a755-9f45-4e8b-8416-d61ab485f3dd | 4 | public static void writeFile(String fileName) {
if (fileName == null) // Go back to reading standard output
writeStandardOutput();
else {
PrintWriter newout;
try {
newout = new PrintWriter(new FileWriter(fileName));
}
catch (Exception e) {
throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for output.\n"
+ "(Error :" + e + ")");
}
if (!writingStandardOutput) {
try {
out.close();
}
catch (Exception e) {
}
}
out = newout;
writingStandardOutput = false;
outputFileName = fileName;
outputErrorCount = 0;
}
} |
29b99917-bfc4-430c-949d-046acb770bbf | 7 | private synchronized void receiveAd(Sim_event ev)
{
if (super.reportWriter_ != null) {
super.write("receive router ad from, " +
GridSim.getEntityName(ev.get_src()));
}
// what to do when an ad is received
RIPAdPack ad = (RIPAdPack)ev.get_data();
// prevent count-to-infinity
if (ad.getHopCount() > Router.MAX_HOP_COUNT) {
return;
}
String sender = ad.getSender();
Iterator it = ad.getHosts().iterator();
while ( it.hasNext() )
{
String host = (String) it.next();
if ( host.equals(super.get_name()) ) {
continue;
}
if (hostTable.containsValue(host)) { // direct connection
continue;
}
if (forwardTable.containsKey(host))
{
Object[] data = (Object[]) forwardTable.get(host);
int hop = ((Integer) data[1]).intValue();
if ((hop) > ad.getHopCount())
{
Object[] toPut = {sender, new Integer(ad.getHopCount()) };
forwardTable.put(host, toPut);
}
}
else
{
Object[] toPut = {sender, new Integer(ad.getHopCount()) };
forwardTable.put(host, toPut);
}
}
forwardAd(ad);
} |
b793b4b2-3477-4e2e-9102-3e2bdb171bf8 | 2 | private static void writeXDRString(DataOutputStream dos, String s) throws IOException {
dos.writeInt(s.length());
dos.writeBytes(s);
int offset = s.length() % 4;
if (offset != 0) {
for (int i = offset; i < 4; ++i) {
dos.writeByte(0);
}
}
} |
8ed646f3-e337-462e-952a-4e0e538fda1f | 8 | public boolean equals(final Object o){
if(this == o)
{
return true;
}
if(!(o instanceof Type))
{
return false;
}
Type t = (Type) o;
if(sort != t.sort)
{
return false;
}
if(sort == Type.OBJECT || sort == Type.ARRAY)
{
if(len != t.len)
{
return false;
}
for(int i = off, j = t.off, end = i + len; i < end; i++, j++)
{
if(buf[i] != t.buf[j])
{
return false;
}
}
}
return true;
} |
9ab0459c-979a-46c8-80c7-f488b6158408 | 7 | public void abrirExtraccion(int id)
{
ArrayList nom;
String[] enlace;
String[] campos = new String[]{"id_enl_audio","id_proyecto","nombre_enlace"};
nom = extraccion.busquedaBD("enlaces_audio", "indice_enlaces_audioid_proyecto", campos, id);
for(int i=0;i<nom.size();i++)
{
enlace = (String[])nom.get(i);
this.enlaces_audios.add(enlace[2]);
}
campos = new String[]{"id_enl_imagen","id_proyecto","nombre_enlace"};
nom = extraccion.busquedaBD("enlaces_imagen", "indice_enlaces_imagenid_proyecto", campos, id);
for(int i=0;i<nom.size();i++)
{
enlace = (String[])nom.get(i);
this.enlaces_imagenes.add(enlace[2]);
}
campos = new String[]{"id_enl_video","id_proyecto","nombre_enlace"};
nom = extraccion.busquedaBD("enlaces_video", "indice_enlaces_videoid_proyecto", campos, id);
for(int i=0;i<nom.size();i++)
{
enlace = (String[])nom.get(i);
this.enlaces_videos.add(enlace[2]);
}
campos = new String[]{"id_enl_documento","id_proyecto","nombre_enlace"};
nom = extraccion.busquedaBD("enlaces_documento", "indice_enlaces_documentoid_proyecto", campos, id);
for(int i=0;i<nom.size();i++)
{
enlace = (String[])nom.get(i);
this.enlaces_documentos.add(enlace[2]);
}
campos = new String[]{"id_enl_otro","id_proyecto","nombre_enlace"};
nom = extraccion.busquedaBD("enlaces_otro", "indice_enlaces_otroid_proyecto", campos, id);
for(int i=0;i<nom.size();i++)
{
enlace = (String[])nom.get(i);
this.enlaces_otros.add(enlace[2]);
}
campos = new String[]{"id_enl_recorrido","id_proyecto","nombre_enlace"};
nom = extraccion.busquedaBD("enlaces_recorrido", "indice_enlaces_recorridoid_proyecto", campos, id);
for(int i=0;i<nom.size();i++)
{
enlace = (String[])nom.get(i);
this.enlaces_recorridos.add(enlace[2]);
}
campos = new String[]{"id_enl_sin_recorrer","id_proyecto","nombre_enlace"};
nom = extraccion.busquedaBD("enlaces_sin_recorrer", "indice_enlaces_sin_recorrerid_proyecto", campos, id);
for(int i=0;i<nom.size();i++)
{
enlace = (String[])nom.get(i);
this.enlaces_sin_recorrer.add(enlace[2]);
}
} |
76d41ae8-c261-4eec-bb6d-cf3fd774146e | 1 | public static void main(String[] args)
{
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 1; i <= 49; i++)
numbers.add(i);
Collections.shuffle(numbers);
List<Integer> winningCombination = numbers.subList(0, 6);
Collections.sort(winningCombination);
System.out.println(winningCombination);
} |
0edfddf3-bb7e-4b13-9324-2ae65ad6023a | 7 | private boolean doubleMillDetection(GameBoard gamestate, GamePiece doubleMillPosition, Team doubleMillTeam){
if (doubleMillPosition.getP() % 2 == 1) { return false;} //double mill detection in this method does not consider the 4 middle square double mills.
Team emptyTeam = new Team();
emptyTeam.setTeamSymbol(GameBoard.EMPTY); //empty square checking
//assumes the square doubleMillPosition is already empty
//check side pieces
int pNext = (doubleMillPosition.getP()+1)%8; //next spot on the ring
int pPrev = doubleMillPosition.getP()-1; //p minus one mod eight
if (pPrev < 0) {
pPrev+=8;
}
if (gamestate.checkForTeamPiece(doubleMillTeam, doubleMillPosition.getR(), pNext) && gamestate.checkForTeamPiece(doubleMillTeam, doubleMillPosition.getR(), pPrev)){
//There's a piece both before and after this one. We need to check one square farther to make sure they are also empty.
pNext = (pNext+1)%8; //next spot on the ring
pPrev = pPrev-1; //p minus one mod eight
if (pPrev < 0) {
pPrev+=8;
}
if (gamestate.checkForTeamPiece(emptyTeam, doubleMillPosition.getR(), pNext) && gamestate.checkForTeamPiece(emptyTeam, doubleMillPosition.getR(), pPrev)) {
return true; //this is a double mill spot
}
}
return false; //no double mill found
} |
7918db95-1440-4566-b91d-6a82ded6361c | 9 | public static void main(String[] args) {
// TODO code application logic here
boolean validar=true;
int valor1=0;
int valor2=0;
double resultado;
char continuar;
int opcion=0;
Scanner teclado=new Scanner(System.in);
Operaciones oOperaciones= new Operaciones();
do
{
System.out.println("Digite una opcion");
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");
teclado=new Scanner(System.in);
valor1=Integer.parseInt(teclado.nextLine());
System.out.println("Digite el valor del segundo diito");
valor2=Integer.parseInt(teclado.nextLine());
System.out.println("El resultado de la suma es");
resultado= oOperaciones.Sumar(valor1, valor2);
System.out.println(resultado);
break;
case 2:
System.out.println("Digite el valor del primer digito");
teclado=new Scanner(System.in);
valor1=Integer.parseInt(teclado.nextLine());
System.out.println("Digite el valor del segundo diito");
valor2=Integer.parseInt(teclado.nextLine());
System.out.println("El resultado de la resta es");
resultado= oOperaciones.Resta(valor1, valor2);
System.out.println(resultado);
break;
case 3:
System.out.println("Digite el valor del primer digito");
teclado=new Scanner(System.in);
valor1=Integer.parseInt(teclado.nextLine());
System.out.println("Digite el valor del segundo diito");
valor2=Integer.parseInt(teclado.nextLine());
System.out.println("El resultado de la Division es");
resultado= oOperaciones.Division(valor1, valor2);
System.out.println(resultado);
break;
case 4:
System.out.println("Digite el valor del primer digito");
teclado=new Scanner(System.in);
valor1=Integer.parseInt(teclado.nextLine());
System.out.println("Digite el valor del segundo diito");
valor2=Integer.parseInt(teclado.nextLine());
System.out.println("EL resultado de la multiplicacion es");
resultado= oOperaciones.Multiplicacion(valor1, valor2);
System.out.println(resultado);
break;
case 5:
System.out.println("Digite el valor del primer digito");
teclado=new Scanner(System.in);
valor1=Integer.parseInt(teclado.nextLine());
System.out.println("El resultado de la raiz es");
resultado= oOperaciones.Raiz(valor1, valor2);
System.out.println(resultado);
break;
case 6:
System.out.println("Digite el valor del primer digito");
teclado=new Scanner(System.in);
valor1=Integer.parseInt(teclado.nextLine());
System.out.println("Digite el valor del segundo diito");
valor2=Integer.parseInt(teclado.nextLine());
System.out.println("El resultado de la potencia es");
resultado= oOperaciones.Potencia(valor1, valor2);
System.out.println(resultado);
break;
default:
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);
} |
1541ac2b-367c-4102-b83f-c150bc7c6adb | 0 | public static void main(String[] args) throws InterruptedException {
Semaphore s = new Semaphore(10);
s.acquire(); // ++
s.release(); // --
List<String> list = Collections.synchronizedList(new ArrayList<String>());
Map<String, String> map1 = Collections.synchronizedMap(new HashMap<String,String>());
ConcurrentHashMap<String, String> map2 = new ConcurrentHashMap<>();
map2.putIfAbsent("s", "s");
CopyOnWriteArrayList<String> l = new CopyOnWriteArrayList<>();
} |
dade4e2b-df86-4892-a32a-ddb13d1311e7 | 7 | public String getResourceTotal()
{
int cpu_count = 0;
long memoryAvailable = 0;
long diskAvailable = 0;
try
{
List<String> regionList = ControllerEngine.gdb.getNodeList(null,null,null);
//Map<String,Map<String,String>> ahm = new HashMap<String,Map<String,String>>();
//System.out.println("Region Count: " + regionList.size());
Map<String,String> rMap = new HashMap<String,String>();
for(String region : regionList)
{
List<String> agentList = ControllerEngine.gdb.getNodeList(region,null,null);
//System.out.println("Agent Count: " + agentList.size());
for(String agent: agentList)
{
List<String> pluginList = ControllerEngine.gdb.getNodeList(region,agent,null);
boolean isRecorded = false;
for(String plugin : pluginList)
{
if(!isRecorded)
{
String pluginConfigparams = ControllerEngine.gdb.getNodeParam(region, agent, plugin, "configparams");
Map<String,String> pMap = paramStringToMap(pluginConfigparams);
if(pMap.get("pluginname").equals("cresco-agent-sysinfo-plugin"))
{
System.out.println("region=" + region +" agent=" + agent);
String agent_path = region + "_" + agent;
String agentConfigparams = ControllerEngine.gdb.getNodeParam(region, agent, null, "configparams");
Map<String,String> aMap = paramStringToMap(agentConfigparams);
String resourceKey = aMap.get("platform") + "_" + aMap.get("environment") + "_" + aMap.get("location");
for(Entry<String, String> entry : pMap.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
System.out.println("\t" + key + ":" + value);
}
isRecorded = true;
}
}
}
}
}
System.out.println("Total CPU core count : " + cpu_count);
System.out.println("Total Memory count : " + memoryAvailable);
System.out.println("Total Disk space : " + diskAvailable);
}
catch(Exception ex)
{
System.out.println("GraphDBEngine : getResourceTotal() : Error " + ex.toString());
}
return "woot";
} |
3e85801d-9970-466e-9355-606320991da6 | 0 | public final Object getSource() {
return source;
} |
9c23a7e4-e9e5-4dcd-9cc4-fd22b358a4fa | 6 | private static Map<String, String> loadSeedProducts(String seedFileName) throws Exception {
int totalRows = 0, badUPCCount = 0, badProductIdCount = 0;
Map<String, String> products = new LinkedHashMap<String, String>();
XSSFWorkbook wb = readFile(seedFileName);
for (int k = 0; k < 1; k++) {
XSSFSheet sheet = wb.getSheetAt(k);
int rows = sheet.getPhysicalNumberOfRows();
totalRows = rows - 1;
for (int r = 1; r < rows; r++) {
try {
XSSFRow row = sheet.getRow(r);
if (row == null) {
System.out.println("Ignoring Empty Row: " + r);
continue;
}
XSSFCell cell0 = row.getCell(0);// SKU
XSSFCell cell1 = row.getCell(1);// Viking URL
if (cell0 != null) {
String sku = getCellData(cell0);
if (cell1 != null) {
String url = cell1.getStringCellValue();
products.put(sku, url);
}
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("row = " + r + " has invalid data.");
badUPCCount++;
throw ex;
}
}
}
System.out.println("Valid Seed Products = " + products.size());
System.out.println("Bad UPCs = " + badUPCCount);
System.out.println("No RSProduct Ids = " + badProductIdCount);
System.out.println(" -----");
System.out.println("Total Seed Products = " + totalRows);
return products;
} |
09256538-5969-4648-b2e1-0dc6f51c572a | 3 | public float getX(float percent) {
// No movement
if(pattern[0] == 0) { return (float)(0+offset[0]); }
// left to right
if(pattern[0] == 1) { return (float)(percent*600.0-50.0+offset[0]); }
// Right to left
if(pattern[0] == 2) { return (float)(percent*-600.0+50.0+offset[0]); }
// donno
// This last one is essentially the else.
return (float)0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.