method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
3af2f5fd-1c26-4aed-9844-9d861b25181c
| 0
|
public void setEspTitle(String title) {
this.espTitle.add(title);
}
|
0d2df44a-ba30-4bdf-bd41-efea7dadfc42
| 4
|
private void painaAlas(int paikka) {
int pieninLapsi;
//Käydään läpi niin kauan kun ei olla puun lehtitasolla
while (!onkoLehti(paikka)) {
//Vasemmalla on aina pienempi lapsi
pieninLapsi = vasenLapsi(paikka);
//
if ((pieninLapsi < koko) && (Taulu[pieninLapsi].getMatkaaJaljella() > Taulu[pieninLapsi+1].getMatkaaJaljella()))
pieninLapsi = pieninLapsi + 1;
//
if (Taulu[paikka].getMatkaaJaljella() <= Taulu[pieninLapsi].getMatkaaJaljella())
return;
//
vaihda(paikka,pieninLapsi);
paikka = pieninLapsi;
}
}
|
123e42d0-e085-4c10-b3f1-fa84b88d6541
| 7
|
@FXML
public void updateQ(ActionEvent evt)
{
try
{
String q = qEd.getText();
String a = aEd.getText();
String o1 = o1Ed.getText();
String o2 = o2Ed.getText();
String o3 = o3Ed.getText();
String o4 = o4Ed.getText();
String i = iEd.getText();
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection cn = DriverManager.getConnection("jdbc:mysql://"+host+":"+port+"/"+database, user, pass);
if(qEd.getText().equals("") || aEd.getText().equals("") || o1Ed.getText().equals("") || o2Ed.getText().equals("") || o3Ed.getText().equals("") || o4Ed.getText().equals(""))
{
MessageBox.show(null,"Please fill all textfields marked as important form.\n", "Error", MessageBox.ICON_ERROR | MessageBox.OK);
}
else
{
PreparedStatement pre = cn.prepareStatement("update " + database + ".quizdata set question = ?, answer = ?, option_1 = ?, option_2 = ?, option_3 = ?, option_4 = ?, image = ? where id = " + qid.getText() + ";");
pre.setString(1, q);
pre.setString(2, a);
pre.setString(3, o1);
pre.setString(4, o2);
pre.setString(5, o3);
pre.setString(6, o4);
pre.setString(7, i);
pre.executeUpdate();
MessageBox.show(null, "Successfully upadated the entries...!!!", "Success", MessageBox.ICON_INFORMATION | MessageBox.OK);
qEd.setText("");
aEd.setText("");
o1Ed.setText("");
o2Ed.setText("");
o3Ed.setText("");
o4Ed.setText("");
iEd.setText("");
}
}
catch(ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex)
{
MessageBox.show(null, ex.toString(), "Error", MessageBox.ICON_ERROR | MessageBox.OK);
}
}
|
003ad64c-d630-4572-a605-d4f49ff2cbf4
| 4
|
public void addInterface( Class<?> serviceInterface )
{
final RemoteInterface remoteInterface = serviceInterface.getAnnotation( RemoteInterface.class );
final int interfaceId = remoteInterface.id();
entries = ensureIndex( entries, interfaceId );
final int methodMax = getMaxRemoteMethodId( serviceInterface );
entries[interfaceId] = ensureIndex( entries[interfaceId], methodMax );
for (Method method : serviceInterface.getMethods())
{
final RemoteMethod remoteMethod = method.getAnnotation( RemoteMethod.class );
if (remoteMethod != null && entries[interfaceId][remoteMethod.id()] == null)
{
RemoteMethodEntry entry = new RemoteMethodEntry();
entry.method = method;
entry.remoteMethod = remoteMethod;
entry.reflectMethod = ReflectFactory.addMethod( method );
entries[interfaceId][remoteMethod.id()] = entry;
}
}
}
|
2baca5b8-3281-4311-8ed9-3418468df80c
| 0
|
public Game createGame() {
Game newGame = gameGenerator.generate();
addGame(newGame);
return newGame;
}
|
ed2332e0-b568-4368-a717-a279993db887
| 9
|
public static String toHankakuCase(String str)
{
int f = str.length();
char[] chars = {0xFF9E, 0xFF9F};
StringBuilder buffer = new StringBuilder();
for(int i=0;i<f;i++)
{
char c = str.charAt(i);
if(Z2H.containsKey(c)){
buffer.append(Z2H.get(c));
} else if(0x30AB <= c && c <= 0x30C9){
buffer.append(Z2H.get((char)(c - 1))).append('\uFF9E');
} else if(c == 0x3000) {
buffer.append('\u0020');
} else if(0x30CF <= c && c <= 0x30DD) {
buffer.append(Z2H.get((char)(c - c % 3))).append(chars[c % 3 - 1]);
} else if(0xFF01 <= c && c <= 0xFF5E) {
buffer.append((char)(c - 0xFEE0));
} else {
buffer.append(c);
};
};
return buffer.toString();
};
|
20c775c2-6694-45f5-b65e-fab4041d8ea9
| 3
|
public void visitTree(final Tree tree) {
if (to instanceof Stmt) {
((Stmt) to).setParent(tree);
// The most common statement replacement is the last statement.
// so search from the end of the statement list.
final ListIterator iter = tree.stmts
.listIterator(tree.stmts.size());
while (iter.hasPrevious()) {
final Stmt s = (Stmt) iter.previous();
if (s == from) {
iter.set(to);
break;
}
}
} else {
tree.visitChildren(this);
}
}
|
a7110284-3658-4f4c-9ed0-d95e15ed3c96
| 2
|
@Test
public void testGetAllAvailableCaptures() {
System.out.println("getAllAvailableCaptures");
Board board = new Board(8, 12);
RuleManager instance = new RuleManager();
SetMultimap<Position, Position> expResult = HashMultimap.create();
SetMultimap<Position, Position> result = instance.getAllAvailableCaptures(Player.PLAYER_TWO, board);
assertEquals(expResult, result);
try {
board.movePiece(new Position(3, 2), new Position(5, 2));
} catch (IllegalPieceMovementException ex) {
Logger.getLogger(RuleManagerTest.class.getName()).log(Level.SEVERE, null, ex);
}
expResult = HashMultimap.create();
expResult.put(new Position(6, 1), new Position(4, 3));
expResult.put(new Position(6, 3), new Position(4, 1));
result = instance.getAllAvailableCaptures(Player.PLAYER_TWO, board);
assertEquals(expResult, result);
board = new Board(8, 12);
try {
board.movePiece(new Position(1, 2), new Position(5, 2));
board.movePiece(new Position(1, 4), new Position(5, 4));
} catch (IllegalPieceMovementException ex) {
Logger.getLogger(RuleManagerTest.class.getName()).log(Level.SEVERE, null, ex);
}
expResult = HashMultimap.create();
expResult.put(new Position(6, 3), new Position(4, 5));
expResult.put(new Position(6, 3), new Position(4, 1));
expResult.put(new Position(6, 1), new Position(4, 3));
expResult.put(new Position(6, 5), new Position(4, 3));
result = instance.getAllAvailableCaptures(Player.PLAYER_TWO, board);
assertEquals(expResult, result);
}
|
882be5c2-0620-420a-a16e-70e95378a926
| 9
|
public static ArrayList<String> parseStringToArray(String txt, String sep, int mode) {
String text = "";
txt = txt==null?"":txt;
if(mode==1) {
text = txt.toUpperCase();
}
else {
text = txt;
}
ArrayList<String> out = new ArrayList<String>();
if(txt == null) {
return out;
}
if(text.length()==0) return out;
int i0 = text.lastIndexOf(sep);
if(i0<0)
{
out.add(text.trim());
return out;
}
while(i0>-1)
{
String tros = text.substring(i0+sep.length(),text.length());
tros = tros.trim();
if(!tros.equals("")) out.add(tros);
text = text.substring(0, i0);
i0 = text.lastIndexOf(sep);
}
String tros = text.trim();
if(!tros.equals(""))
out.add(tros);
//aquest out esta invertit (darrer element al primer)
ArrayList<String> out2 = new ArrayList<String>();
for(int i=0; i<out.size(); i++)
{
out2.add(out.get(out.size()-i-1));
}
return out2;
}
|
2e6b2474-5a9c-4ce1-8cca-bc13e7bf72eb
| 3
|
public Movie(final String dataLine) {
final int startIndexYear = dataLine.indexOf('(') + 1;
final int endIndexYear = Math.min(dataLine.indexOf(')', startIndexYear), startIndexYear + 4);
final int startIndexActors = dataLine.indexOf('/');
this.title = dataLine.substring(0, startIndexYear - 1).trim();
this.releaseYear = Integer.parseInt(dataLine.substring(startIndexYear, endIndexYear));
this.actors = new ArrayList<>();
for (final String actorName : dataLine.substring(startIndexActors + 1).split("/")) {
final int commaIndex = actorName.indexOf(',');
final String firstName = (commaIndex != -1) ? actorName.substring(commaIndex + 1).trim() : actorName;
final String lastName = (commaIndex != -1) ? actorName.substring(0, commaIndex).trim() : "";
this.actors.add(new Actor(firstName, lastName));
}
}
|
1db3011c-ed10-4440-a284-ab78e7d8cfd9
| 2
|
public void addGetMethod(Field field, Method method) {
if(field == null) {
throw new IllegalArgumentException("Field cannot be null");
}
FieldStoreItem item = store.get(FieldStoreItem.createKey(field));
if(item != null) {
item.setGetMethod(method);
} else {
item = new FieldStoreItem(field);
item.setGetMethod(method);
store.put(item.getKey(),item);
}
}
|
8a1cf631-d729-4a76-8140-33309f349c7e
| 2
|
@Override
protected Void doInBackground() throws Exception {
try {
controlUnit.activate();
}
catch (NullPointerException e) {
JOptionPane.showMessageDialog(null, "Assembly program logic error! Please ensure program logic is sound.");
}
catch (ClassCastException e) {
JOptionPane.showMessageDialog(null, "Assembly program logic error! Please ensure program logic is sound.");
}
return null;
}
|
622dd141-8ccc-47b7-aca8-a59e1129a606
| 4
|
public void Extract(Object oo) throws IOException {
//ID
if(oo instanceof ClientHandeler){
ClientHandeler client = (ClientHandeler)oo;
System.out.println(client.id + " Just Connected");
this.clients.add(client);
}
//IMAGEM
else if(oo instanceof ImageDto){
ImageDto image = (ImageDto)oo;
//Criar Directorio
File theDir = new File(image._sender);
// if the directory does not exist, create it
if (!theDir.exists()) {
System.out.println("creating directory: " + image._sender);
boolean result = theDir.mkdir();
if(result) {
System.out.println("DIR created");
}
}
File f = new File(image._sender + "/" + image.time + ".png");
BufferedImage img = image._image.getImage();
ImageIO.write(img, "PNG", f);
}
}
|
723a86aa-0331-4312-89fc-c68b4c631edf
| 2
|
private void actionAdd(HttpServletRequest request, RequestData rd, Class clazz){
try{
Object obj;
obj = helper.addElement(clazz, request.getParameterMap());
if (obj == null) request.setAttribute("error", "Не удалось добавить объект");
}
catch (RuntimeException ex){
request.setAttribute("error", ex);
}
}
|
43699dcf-b6e3-405c-b5db-f3829ce7a8cf
| 6
|
private boolean r_other_endings() {
int among_var;
int v_1;
int v_2;
int v_3;
// (, line 141
// setlimit, line 142
v_1 = limit - cursor;
// tomark, line 142
if (cursor < I_p2)
{
return false;
}
cursor = I_p2;
v_2 = limit_backward;
limit_backward = cursor;
cursor = limit - v_1;
// (, line 142
// [, line 142
ket = cursor;
// substring, line 142
among_var = find_among_b(a_7, 14);
if (among_var == 0)
{
limit_backward = v_2;
return false;
}
// ], line 142
bra = cursor;
limit_backward = v_2;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 146
// not, line 146
{
v_3 = limit - cursor;
lab0: do {
// literal, line 146
if (!(eq_s_b(2, "po")))
{
break lab0;
}
return false;
} while (false);
cursor = limit - v_3;
}
break;
}
// delete, line 151
slice_del();
return true;
}
|
4e37f00b-2c62-41bd-b90a-6f2040452ae4
| 5
|
public String whoHasLargestArmy() {
// The current owner of the largest army keeps the largest army
// in the event of a tie
String defendingOwner = this.largestArmyOwner;
int defendingOwnerSize = this.largestArmySize;
String updatedLargestArmyPlayer = null;
int updatedLargestArmySize = 0;
for (Player player: userArray) {
int playersLargestArmySize = player.getNumKnightsPlayed();
// If the player is the defending owner, store the size of the
// defending owner's army
if (player.getUsername().equals(defendingOwner)) {
defendingOwnerSize = playersLargestArmySize;
}
// If this player has the largest army so far, set the largest army
// size as this size and the player as the owner of the
// largest army so far
if (playersLargestArmySize > updatedLargestArmySize) {
updatedLargestArmySize = playersLargestArmySize;
updatedLargestArmyPlayer = player.getUsername();
}
// DEBUG MESSAGE
System.out.println(player.getUsername() + "'s army size: " +
playersLargestArmySize);
}
this.largestArmySize = updatedLargestArmySize;
// If all of the roads have length less than 5, no one has longest road
if (updatedLargestArmySize < 3) {
this.largestArmyOwner = null;
} else {
// If the defending owner still has the largest army, keep
// the defending owner (even in the event of a tie). Otherwise,
// choose the player with the greatest longest road.
if (defendingOwnerSize != updatedLargestArmySize) {
this.largestArmyOwner = updatedLargestArmyPlayer;
}
}
return this.largestArmyOwner;
}
|
4a7833f0-50ca-444c-baf9-bdf0f5527328
| 3
|
public void totalRun(HashSet<Long> completedUsers,
TreeMap<Long, Long> parent, TreeMap<Long, Integer> local,
TreeMap<Long, Integer> total) throws InterruptedException {
for (Entry<Long, Integer> e : total.entrySet()) {
if (!tr.containsKey(e.getKey()))
tr.put(e.getKey(), new UserNode());
UserNode u = tr.get(e.getKey());
if (!e.getValue().equals(new Integer(0))) {
u.totalInfSum.addAndGet(e.getValue());
u.updateMinTotalInf(e.getValue());
// System.out.println("updating Mx total Info "
// + e.getValue());
u.updateMaxTotalInf(e.getValue());
// System.out.println("finished with Mx total info "
// + e.getValue());
}
}
}
|
4a0d8950-6b79-4265-9abf-1680d8f09dc8
| 9
|
static int getCantidad(char[][] matG, char[][] matP){
int cant = 0;
for (int i = 0; i < matG.length; i++)
for (int j = 0; j < matG.length; j++) {
boolean ws = true;
for (int k = 0; k < matP.length && ws; k++)
for (int h = 0; h < matP.length && ws; h++)
ws = i+k<matG.length && j+h < matG.length && matP[k][h]==matG[i+k][j+h];
if(ws)cant++;
}
return cant;
}
|
1a498994-077a-4db9-a759-327018382a97
| 5
|
public static void execute(final Executable[] p_executables, final int p_threadCount) {
final ExecutorService executorService;
final Future<?>[] futures;
Contract.checkNotEmpty(p_executables, "no executables given");
Contract.check(p_threadCount > 0, "invalid thread count given");
executorService = Executors.newFixedThreadPool(p_threadCount);
futures = new Future[p_executables.length];
for (int i = 0;i < p_executables.length;i++) {
futures[i] = executorService.submit(new Executor(p_executables[i]));
}
for (final Future<?> future : futures) {
try {
future.get();
} catch (final Exception e) {
e.printStackTrace();
}
}
executorService.shutdown();
}
|
5afc5504-c2d9-4791-bf1a-7c8a0dd778f3
| 7
|
private boolean isLegit(int col, int row, int currentPlayer)
{
return checkHorizontallyLeft2Right(col, row, currentPlayer) ||
checkHorizontallyRight2Left(col, row, currentPlayer) ||
checkVerticallyTop2Bottom(col, row, currentPlayer) ||
checkVerticallyBottom2Top(col, row, currentPlayer) ||
checkDiagonallyBottomLeft2TopRight(col, row, currentPlayer) ||
checkDiagonallyBottomRight2TopLeft(col, row, currentPlayer) ||
checkDiagonallyTopRight2BottomLeft(col, row, currentPlayer) ||
checkDiagonallyTopLeft2BottomRight(col, row, currentPlayer);
}
|
44383b79-a735-406c-8da7-496e74b30cae
| 4
|
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
/* Muestra los datos de las ventas realizadas filtradas segun el rut del cliente que realizó la compra,
* los datos son almacenados en un TableModel y mostrados en la tabla 2 de la clase administrador.
*/
boolean match=false;
for(int i=0;i<jTable1.getRowCount();i++){
if(jTable1.getValueAt(i, 5).equals(jTextField1.getText())){
match=true;
}
if(match==true){
Object ed[]={jTable1.getValueAt(i, 0),jTable1.getValueAt(i, 1),jTable1.getValueAt(i, 2),
jTable1.getValueAt(i, 3),jTable1.getValueAt(i, 4),jTable1.getValueAt(i, 5),
jTable1.getValueAt(i, 6)};
Datos.addRow(ed);
jTable2.setModel(Datos);
}
}
if(match==false){
JOptionPane.showMessageDialog(this, "El cliente no ha realizado compras");
}
}//GEN-LAST:event_jButton1ActionPerformed
|
0a38053e-4f48-4a47-85e7-252cf888bdf9
| 5
|
@Override
public boolean move(int row, int col) {
//Vertical
if (this.col == col && this.row != row) {
this.row = row;
return true;
//Horizontal
} else if (this.row == row && this.col != col) {
this.col = col;
return true;
} else if (Math.abs(this.row - row) == Math.abs(this.col - col)) {
this.row = row;
this.col = col;
return true;
}
return false;
}
|
617a0642-a826-4826-a972-5c71159fb14b
| 7
|
private JSONWriter append(String s) throws JSONException {
if (s == null) {
throw new JSONException("Null pointer");
}
if (this.mode == 'o' || this.mode == 'a') {
try {
if (this.comma && this.mode == 'a') {
this.writer.write(',');
}
this.writer.write(s);
} catch (IOException e) {
throw new JSONException(e);
}
if (this.mode == 'o') {
this.mode = 'k';
}
this.comma = true;
return this;
}
throw new JSONException("Value out of sequence.");
}
|
a5a3ddc2-9540-4b6b-b820-aa8f9b8bbf89
| 4
|
public ArrayList<String> getOfflineUsers(String userItself) {
System.out.println("getOfflineUsers");
ArrayList<String> offlineUsers = new ArrayList();
File file = new File(userFilePath);
if (file.exists()) {
System.out.println("file exists");
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
String ligne;
while ((ligne = br.readLine()) != null) {
String[] resultSplit = ligne.split(":");
System.out.println("current user: "+resultSplit[0]);
if (!resultSplit[0].equals(userItself)) {
offlineUsers.add(resultSplit[0]);
}
return offlineUsers;
}
br.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
offlineUsers.add("There are currently no Users");
return offlineUsers;
}
|
3c77185e-b6ba-4dbb-920b-4699ebbc6ca8
| 0
|
@SuppressWarnings("unchecked")
@Override
public <T> T getRequiredService(Class<T> serviceType) throws Exception {
return (T) this.getRequiredService2(serviceType);
}
|
7f46f71c-b17b-4be5-ba61-841b2f6ac33a
| 2
|
private List<Hex> getRandomChits(List<Hex> defaultHexes) {
ArrayList<Hex> randomChits = new ArrayList<Hex>(defaultHexes);
List<Integer> randomValues = ModelDefaults.getDefaultNumbers();
randomizeList(randomValues);
int chitIndex = 0;
for(Hex hex : randomChits) {
if(hex.getResourceType() != null) {
hex.setChit(randomValues.get(chitIndex++));
}
}
return randomChits;
}
|
1dc6e3b4-bdb0-4ba4-a26c-474b0ae1de0d
| 5
|
@Override
public Boolean isPolinomeRepresentationValid(String input) {
if(input.isEmpty()) return false;
String[] allow = {"-", "+", "x", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
String aux;
int error_detector = 0;
for (int i = 0; i < input.length(); i++) {
error_detector = 0;
aux = input.substring(i, i + 1);
for (int j = 0; j < allow.length; j++) {
if (aux.equals(allow[j])) {
error_detector++;
}
}
if (error_detector == 0) {
return false;
}
}
return true;
}
|
d7158a09-8bce-4fc8-8bdf-bc2eb2adf356
| 3
|
@Override
public void commitTransaction() throws SQLException {
try {
this.connection.commit();
} catch (SQLException e) {
try {
this.connection.rollback();
} catch (SQLException e2) {
throw new DBException("error rolling back transaction", e2);
}
throw new SQLException("could not commit transaction - a rollback is performed");
}
try {
this.connection.setAutoCommit(true);
} catch (SQLException e) {
throw new DBException("error stopping transaction", e);
}
}
|
470f14ee-77b8-4f7e-8982-230ff6457445
| 1
|
public HbaseConfModel getHbaseConfModel() {
HbaseConfModel hbaseConfModel = new HbaseConfModel();
JsonNode node = rootNode.get("HBase");
hbaseConfModel.setExecute(node.get("execute").getBooleanValue());
// resource
JsonNode resouceNode = node.get("resource");
List<String> resouceArray = new ArrayList<String>();
for (int i = 0; i < resouceNode.size(); i++) {
resouceArray.add(resouceNode.path(i).getTextValue());
}
hbaseConfModel.setResource(resouceArray);
return hbaseConfModel;
}
|
04d42f58-a5a8-4efa-9ff9-1d8ad2e0f3aa
| 0
|
public void setPosition(Point position) {
this.exactPostitionX = position.x;
this.exactPostitionY = position.y;
}
|
60fee18e-aa33-4c2b-a0ec-5a5f92a889ff
| 2
|
public StructuredBlock getNextBlock(StructuredBlock subBlock) {
for (int i = 0; i < caseBlocks.length - 1; i++) {
if (subBlock == caseBlocks[i]) {
return caseBlocks[i + 1];
}
}
return getNextBlock();
}
|
16a70158-de1d-430a-88fc-a1d5bf63a2e6
| 4
|
public static MarioData load()
{
MarioData marioData = null;
ObjectInputStream savedGame = null;
File a;
a = new File(System.getProperty("user.home") + "\\.Awesome Mario Remake\\MarioData.save");
try
{
if (!a.exists())
{
a.createNewFile();
}
FileInputStream f = new FileInputStream(System.getProperty("user.home") + "\\.Awesome Mario Remake\\MarioData.save");
savedGame = new ObjectInputStream(f);
marioData = (MarioData) savedGame.readObject();
}// <editor-fold defaultstate="collapsed" desc="Catch and finally blocks">
catch (ClassNotFoundException ex)
{
Logger.getLogger(loadAndSave.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex)
{
JOptionPane.showMessageDialog(null, "Het inladen is mislukt \n Voor het bevoegde gezag:" + ex, "Er is een fout opgetreden", JOptionPane.WARNING_MESSAGE);
} finally
{
try
{
savedGame.close();
} catch (IOException ex)
{
JOptionPane.showMessageDialog(null, "Het lezen is mislukt \n Voor het bevoegde gezag:" + ex, "Er is een fout opgetreden", JOptionPane.WARNING_MESSAGE);
}
}// </editor-fold>
MarioData game = marioData;
return game;
}
|
9d794c38-2f4a-4622-a995-f2152fc87512
| 6
|
public int[][] spawnCaves(int[][] currentBlockArray, int caves, int minX, int maxX, int minZ, int maxZ) {
ArrayList maxCaveSpots = new ArrayList();
for(int i = 0; i < caves*3; i++) {
int iMax = getMaxZCaveSpot();
int[] caveSpot = null;
if(iMax > -1) {
caveSpot = (int[])caveSpots.remove(iMax);
}
if(caveSpot != null) {
maxCaveSpots.add(caveSpot);
}
}
int removes = maxCaveSpots.size() - caves;
for(int i = 0; i < removes; i++) {
maxCaveSpots.remove(Rand.getRange(0, maxCaveSpots.size() - 1));
}
for(int i = 0; i < maxCaveSpots.size(); i++) {
int[] caveSpot = (int[])maxCaveSpots.get(i);
World.direction direction;
if(Rand.getFloat() < .5) {
direction = World.direction.Left;
} else {
direction = World.direction.Right;
}
WorldCavern cavern = new WorldCavern(world, worldTown, 5, 3, 3, ground);
currentBlockArray = cavern.carveCave(currentBlockArray, (caveSpot[1]+caveSpot[2])/2, caveSpot[0], minX, minZ, maxX, maxZ, 0.0f, direction);
}
return currentBlockArray;
}
|
1f40e112-ea59-4de0-a05b-df29e5a5da52
| 5
|
private GSprite getSpriteForState(ButtonState buttonState)
throws IllegalArgumentException {
// Make sure the state is non-null.
if (buttonState == null) {
// The state is null.
throw new IllegalArgumentException("state == null");
}
// First, see what we've got.
GSprite i = sprites.get(buttonState);
// If it's non-null, use that.
if (i != null) {
// Good.
return i;
}
// Otherwise, can we extrapolate?
switch (buttonState) {
case HOVERED:
// The button is hovered. If there's no GSprite set, we'll use the
// default GSprite.
return getSpriteForState(ButtonState.NONE);
case PRESSED:
// The button is pressed. If there's no GSprite set, we'll use the
// hovered GSprite.
return getSpriteForState(ButtonState.HOVERED);
case NONE:
// Well this is the end of the line. If there's no GSprite here,
// there's nothing.
return null;
default:
// That shouldn't happen, but if it does, we don't know what to do.
return null;
}
}
|
6ce081d6-9e69-4ff5-b81d-13c797e255b9
| 0
|
public GUI(World w) {
hexgrid = new HexGrid(this);
hexgrid.createAndShowGUI();
}
|
24e817ff-1aa9-49bf-96eb-612fff60582a
| 9
|
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString();
String[] segment = line.split("\t");// 原始数据为(实体编号+实体属性向量)
// 读取实体属性向量
char[] entityFeature = segment[1].toCharArray();
if (entityFeature.length != EntityDriver.DIMENSION) {
System.err.println("卧槽这数据是个坑");
}
boolean[] boolFeature = new boolean[EntityDriver.DIMENSION];
for (int i = 0; i < EntityDriver.DIMENSION; i++) {
boolFeature[i] = entityFeature[i] == '1';
}
// 生成签名
boolean[] signature = new boolean[EntityDriver.RANDOM_VECTORS];
int count = 0;
for (int i = 0; i < EntityDriver.RANDOM_VECTORS; i++) {
count = 0;
for (int j = 0; j < EntityDriver.DIMENSION; j++) {
count += boolFeature[j] == randomVector[i][j] ? 1 : -1;
}
signature[i] = count >= 0 ? true : false;
}
// 随机变换
Random random = new Random(20);
int a, b, newPosition;
for (int i = 0; i < EntityDriver.PERMUTATION; i++) {
EntityData outputValue = new EntityData();
boolean[] permutedSignature = new boolean[EntityDriver.DIMENSION];
do {
a = random.nextInt(EntityDriver.RANDOM_VECTORS - 2) + 1;
} while (primeCheck(EntityDriver.PERMUTATION, a) == false);
b = random.nextInt(EntityDriver.RANDOM_VECTORS - 2) + 1;
for (int j = 0; j < EntityDriver.RANDOM_VECTORS; j++) {
newPosition = (a * j + b) % EntityDriver.RANDOM_VECTORS;
permutedSignature[newPosition] = signature[j];
}
outputValue.set(new IntWritable(Integer.parseInt(segment[0])),
permutedSignature);
context.write(new IntWritable(i), outputValue);
}
}
|
11d247a1-a36a-4f78-b014-198ae012eb3d
| 2
|
private RegistrationNumber(char letterIdentifier, int numberIdentifier, String stringRepresentation){
Random randomLetterIdentifier = new Random();
this.letterIdentifier=(char)(randomLetterIdentifier.nextInt(26) + 'a');
if (Character.isDigit(letterIdentifier))
throw new IllegalArgumentException("That is not a valid letter identifier.");
Random randomNumberIdentifier = new Random();
this.numberIdentifier=randomNumberIdentifier.nextInt(9999) + 1001;
if (Integer.toString(numberIdentifier).length()!=4)
throw new IllegalArgumentException("That is not a valid number identifier.");
this.stringRepresentation = stringRepresentation;
}
|
13dafef7-cb88-420f-b63e-fc34e9cf9384
| 2
|
@Override
public void addTextBack() {
Element textBack = text.getOwnerDocument().createElement("path");
String d = "M";
for (Coordinate c : geometry.getCoordinates()) {
if(d.length()>1){
d=d+" L";
}
d = d + " " + c.x + "," + c.y;
}
textBack.setAttribute("d", d);
textBack.setAttribute("style", "fill:red;opacity:0.5;");
text.getParentNode().insertBefore(textBack, text);
}
|
4f3fc7cf-dd19-4a58-bad0-b9b78e54a578
| 4
|
@SuppressWarnings("unchecked")
public static final byte[] encode(Object o) throws BencodingException
{
if(o instanceof HashMap)
return encodeDictionary((HashMap)o);
else if(o instanceof ArrayList)
return encodeList((ArrayList)o);
else if(o instanceof Integer)
return encodeInteger((Integer)o);
else if(o instanceof ByteBuffer)
return encodeString((ByteBuffer)o);
else
throw new BencodingException("Error: Object not of valid type for Bencoding.");
}
|
c43bbe78-3eb5-4d17-aae5-bb8974f52bc0
| 0
|
public int getManagerFirewallId() {
return managerFirewallId;
}
|
fe7dca61-a27f-4cb8-93fe-2cf5655593f2
| 5
|
public boolean isIn(String key, String value) {
String ligne;
String usr;
String psw;
try {
while ((ligne = _br.readLine()) != null) {
int a = 0;
while (ligne.charAt(a) != '@') {
a++;
}
usr = ligne.substring(0, a);
psw = ligne.substring(a + 1, ligne.length());
if (key.equals(usr) && (value.equals(psw))) {
_br.close();
return true;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("erreur lecture bdd");
}
return false;
}
|
dde3b492-9849-45c1-995f-56509c1b4ac2
| 5
|
@Override
public void mouseReleased(MouseEvent e) { // Called after a button is released
mx = e.getX();
my = e.getY();
if(!main.hasAbilitySelected()) {
if(e.getButton() == MouseEvent.BUTTON1) { // Left button released
LinkedList<ClickableObject> selection = new LinkedList<ClickableObject>();
int x = Math.min(mx, selectStartX);
int y = Math.min(my, selectStartY);
int width = Math.abs(selectStartX - mx);
int height = Math.abs(selectStartY - my);
for(Unit unit : main.getUnits()) {
if(unit.isInRectangle(x, y, width, height)) {
selection.add(unit);
unit.setSelected(true);
} else {
unit.setSelected(false);
}
}
isButtonPressed = false;
main.setSelection(selection);
} else if(e.getButton() == MouseEvent.BUTTON2) { // Middle button released
} else { // Right button released
}
} else {
//main.addAnimatedObject(new AnimatedObject(mx, my, main.getSelectedAbility().getAnimation(), true, State.PERFORMING_ACTION));
//main.clearSelectedAbility();
//this.setCursor(Cursor.getDefaultCursor());
}
repaint();
e.consume();
}
|
db88f27d-609d-40d8-aeb7-1f3c37376391
| 9
|
public Boolean executeStep(AbstractBuild build,
SkytapGlobalVariables globalVars) {
JenkinsLogger.defaultLogMessage("----------------------------------------");
JenkinsLogger.defaultLogMessage("Creating Template from Environment");
JenkinsLogger.defaultLogMessage("----------------------------------------");
if(preFlightSanityChecks()==false){
return false;
}
this.globalVars = globalVars;
this.authCredentials = SkytapUtils.getAuthCredentials(build);
// reset step parameters with env vars resolved at runtime
String expConfigurationFile = SkytapUtils.expandEnvVars(build,
configurationFile);
// if user has provided just a filename with no path, default to
// place it in their Jenkins workspace
if (!expConfigurationFile.equals("")) {
expConfigurationFile = SkytapUtils.convertFileNameToFullPath(build,
expConfigurationFile);
}
String expTemplateFile = SkytapUtils.expandEnvVars(build, templateSaveFilename);
String expTemplateName = SkytapUtils.expandEnvVars(build, templateName);
String expTemplateDescription = SkytapUtils.expandEnvVars(build, templateDescription);
try {
this.runtimeConfigurationID = SkytapUtils.getRuntimeId(this.configurationID, expConfigurationFile);
} catch (FileNotFoundException e2) {
JenkinsLogger.error("Error obtaining environment id: " + e2.getMessage());
return false;
}
JenkinsLogger.log("Runtime Environment ID: " + this.runtimeConfigurationID);
try {
// create the template
sendTemplateCreationRequest(runtimeConfigurationID);
} catch (SkytapException e1) {
JenkinsLogger.error("Skytap Exception: " + e1.getMessage());
return false;
}
// make sure we have the template id, if we don't something went wrong
if(runtimeTemplateID.equals("") || runtimeTemplateID == null){
JenkinsLogger.error("Template creation failed.");
return false;
}
// update the template with name and description
String httpRespBody;
try {
httpRespBody = sendTemplateUpdateRequest(this.runtimeTemplateID, expTemplateName, expTemplateDescription);
} catch (SkytapException e1) {
JenkinsLogger.error("Skytap Exception: " + e1.getMessage());
return false;
}
// save to template file path
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(httpRespBody);
JsonObject jo = je.getAsJsonObject();
jo = je.getAsJsonObject();
Writer output = null;
// if user has provided just a filename with no path, default to
// place it in their Jenkins workspace
expTemplateFile = SkytapUtils.convertFileNameToFullPath(build, expTemplateFile);
// output to the file system
File file = new File(expTemplateFile);
try {
output = new BufferedWriter(new FileWriter(file));
output.write(httpRespBody);
output.close();
} catch (IOException e) {
JenkinsLogger
.error("Skytap Plugin failed to save template to file: "
+ expTemplateFile);
return false;
}
// Sleep for a 10 seconds to make sure the Template is stable, then we can exit
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
JenkinsLogger.error("Error: " + e.getMessage());
}
JenkinsLogger
.defaultLogMessage("Template " + expTemplateName + " successfully created and saved to file: "
+ expTemplateFile);
JenkinsLogger.defaultLogMessage("----------------------------------------");
return true;
}
|
a38ba27a-1e08-4999-9d82-da38bdb54c50
| 7
|
public void run() {
Scanner scn = new Scanner(System.in);
int testCount = scn.nextInt();
// Loop through all test cases.
for (int testItem = 1; testItem <= testCount; testItem++) {
int numVertices = scn.nextInt();
int numEdges = scn.nextInt();
// create adjacency Matrix
adjacencyMatrix = new int[numVertices][numVertices];
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
adjacencyMatrix[i][j] = 0;
}
}
for (int edge = 0; edge < numEdges; edge++) {
int s = scn.nextInt(); // source vertex
int d = scn.nextInt(); // destination vertex
int w = scn.nextInt(); // distance from s to d
// add to adjacency matrix
adjacencyMatrix[s][d] = w;
}
// Create the matrix with wieght values.
AllPairsShortestPath(adjacencyMatrix);
// Output the resulting Distance from source.
System.out.printf("%d\n", testItem);
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
if(pathWeights[i][j] == Integer.MAX_VALUE){
System.out.print("NP ");
} else {
System.out.printf("%d ", pathWeights[i][j]);
}
}
System.out.println();
}
}
}
|
862f37c9-5638-4ac5-a096-7427b12d7209
| 3
|
public String getReplicaAddress() {
if (slaveAddresses.isEmpty()) {
return masterAddress;
} else {
// randomly give a slaveAdress back
int size = slaveAddresses.size();
int item = new Random().nextInt(size);
int i = 0;
for (String obj : slaveAddresses) {
if (i == item) {
return obj;
} else {
i = i + 1;
}
}
}
return masterAddress;
}
|
c298257b-af57-415b-b310-8045e9d95e77
| 9
|
protected boolean acceptable(ContentHeaderMap contentHeaderMap) {
if (allowedExtensions == null && allowedTypes == null)
return true;
if (allowedTypesSet != null && contentHeaderMap.getContentType() != null) {
if (allowedTypesSet.contains(contentHeaderMap.getContentType())) {
return true;
} else {
exceptionalSet.add(contentHeaderMap);
return false;
}
}
if (contentHeaderMap.isFile() && allowedExtensionsSet != null) {
String extName = this.getExtension(contentHeaderMap.getFileName());
if (extName != null && !allowedExtensionsSet.contains(extName)) {
exceptionalSet.add(contentHeaderMap);
return false;
}
return true;
} else
return true;
}
|
64ef52fb-6544-49fe-af12-8bb284aa1eae
| 4
|
public boolean addCoffer(OfflinePlayer player,Chest chest){
if(player==null || chest==null)
return false;
if(isStore(chest))
return false;
if(isCoffer(chest))
return false;
coffers.put(chest, player);
saveCoffers();
return true;
}
|
725b7fdf-0c16-451c-b2a1-f75efc0ad3c6
| 0
|
@Test
public void testProxy() {
Person person = PersonImpl.personWithNameAndAge("test", 100);
Person proxyPerson = ObjectProxy.newInstance(person, new ObjectProxy.Interceptor() {
@Override
public Object around(Object result) {
System.out.println("Modifying 100 for 200...");
return 200;
}
});
System.out.println("before getAge is invoked in our test");
int modifiedAge = proxyPerson.getAge();
System.out.println("after getAge is invoked in our test");
assertEquals(modifiedAge, 200);
}
|
0e090f0b-887c-4e5b-afab-083f4fd458f4
| 7
|
private void afficherFenMoreInfo(Match m) throws IOException, SQLException {
//Affichage joueurs
if (m != null) {
PlayerDao pdao = DaoFactory.getPlayerDao();
Player p1 = pdao.selectPlayer(m.getIdP1());
Player p2 = pdao.selectPlayer(m.getIdP2());
moreInfo_lbJoueurs.setText(p1.getNameSurname() + " VS " + p2.getNameSurname());
//Affichage heure et terrain
String court = null;
switch (m.getIdTerrain()) {
case 1: court = "Court central"; break;
case 2: court = "Court annexe"; break;
case 3: court = "Court d'entrainement 1"; break;
case 4: court = "Court d'entrainement 2"; break;
case 5: court = "Court d'entrainement 3"; break;
case 6: court = "Court d'entrainement 4"; break;
}
moreInfo_lbHeureTerrain.setText(m.getHeure() + "h - " + court);
//Affichage arbitre
RefereeDao rdao = DaoFactory.getRefereeDao();
Referee r1 = rdao.selectReferee(m.getIdArbitreChaise());
Referee r2 = rdao.selectReferee(m.getIdArbitreFilet());
moreInfo_lbA1.setText(r1.getNameSurname());
moreInfo_lbA2.setText(r2.getNameSurname());
//Affichage ramasseurs
RamasseurDao radao = DaoFactory.getRamasseurDao();
Ramasseur ram1 = radao.selectRamasseur(m.getIdTeamRamasseur1());
Ramasseur ram2 = radao.selectRamasseur(m.getIdTeamRamasseur2());
moreInfo_lbR1.setText(ram1.getNom());
moreInfo_lbR2.setText(ram2.getNom());
}
}
|
4d14b548-f720-452f-898f-aabea8379210
| 5
|
public void insertWord(int _internalId, int _dom, String _lemma, String _link, String _word, String _partOfSpeech, List<String> _properties,List<String> _propertiesValues, int _sentenceId){
try{
String generatedStatement = "INSERT INTO words (internalId, domid, lemma, link, word, partOfSpeech";
int addedValues=0;
for(int i=0; i< _properties.size(); i++){
generatedStatement+=", "+_properties.get(i);
addedValues++;
}
generatedStatement+=", sentenceId) VALUES(?,?,?,?,?,?";
for(int i=0;i<addedValues;i++){
generatedStatement+=",?";
}
generatedStatement+=",?)";
System.out.println("Statement:" +generatedStatement);
PreparedStatement wordStatement = (PreparedStatement) c.prepareStatement(generatedStatement);
try{
wordStatement.setInt(1, _internalId);
wordStatement.setInt(2, _dom);
wordStatement.setString(3, _lemma);
wordStatement.setString(4, _link);
wordStatement.setString(5, _word);
wordStatement.setString(6, _partOfSpeech);
if(addedValues!=0)
for(int i=1;i<=addedValues;i++){
wordStatement.setString(i + 6, _propertiesValues.get(i - 1));
}
wordStatement.setInt(7 + addedValues, _sentenceId);
System.out.println("SQL Statement: " + wordStatement.asSql());
wordStatement.executeUpdate();
} finally {
wordStatement.close(); //without that there should be memory leak (byte[] not GC'd)
}
} catch (SQLException e) {
e.printStackTrace();
}
}
|
290e709e-772b-4ba2-bbe3-1ac613f7ae3e
| 3
|
public void detectCollision() {
for(int i=0; i<EntityManager.getEntityList().size(); ++i) {
if(EntityManager.getEntityList().get(i) instanceof GameBaseEntity) {
if(this.getGlobalBounds().intersection(EntityManager.getEntityList().get(i).getGlobalBounds()) != null) {
touch();
}
}
}
}
|
81ebbd4d-d15c-472d-a27c-f64ae667818a
| 5
|
private String createHashBase()
throws IOException {
if( !this.resource.isOpen() )
throw new IOException( "Cannot create an ETag from an un-opened resource!" );
StringBuffer buffer = new StringBuffer();
// Add the request path
// (better than the inode number, I think)
if( this.relativeURI != null ) {
if( this.relativeURI.getPath() != null )
buffer.append( this.relativeURI.getPath() );
if( this.relativeURI.getQuery() != null )
buffer.append( "?" ).append( this.relativeURI.getQuery() );
}
// Add a delimiter
buffer.append( "#" );
// Add the date of last modification
if( this.resource.getMetaData().getLastModified() != null ) {
buffer.append( this.resource.getMetaData().getLastModified().getTime() );
} else {
// If modification date is not available: use current time stamp
buffer.append( System.currentTimeMillis() );
}
// Add one more delimiter
buffer.append( "#" );
// Add the size of the resource.
// Warning: this might throw an exception.
buffer.append( this.resource.getLength() ); // might be -1, which is OK for the hash
return buffer.toString();
}
|
5dc89c71-9448-4af3-b44f-02429da9b282
| 3
|
@Override
public void close() throws SQLException {
if(resultSet != null) {
resultSet.close();
resultSet = null;
}
if(statement != null) {
statement.close();
statement = null;
}
if(conn != null) {
conn.close();
conn = null;
}
}
|
e14ba129-0cc9-4f1d-9ca3-79d20485e934
| 0
|
public void setBlogLabel(String blogLabel) {
this.blogLabel = blogLabel;
}
|
4c317298-ab2b-4686-9732-68fc5cc13604
| 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(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Login().setVisible(true);
}
});
}
|
e05c4d28-e0ba-4734-a1c2-6868a098ab36
| 7
|
public YamlDataStorageImplementation(Decapitation plugin) throws IOException {
this.plugin = plugin;
this.configFile = new File(plugin.getDataFolder(), "bounties.yml");
if (!(configFile.exists() && !configFile.isDirectory())) {
configFile.createNewFile();
}
this.config = YamlConfiguration.loadConfiguration(configFile);
if (!config.isConfigurationSection("bounties")) {
config.createSection("bounties");
}
lastId = 0;
Set<String> keys = this.config.getConfigurationSection("bounties").getKeys(false);
for (String key : keys) {
try {
int value = Integer.valueOf(key);
if (value < 0) {
this.plugin.getLogger().warning("Picked up an invalid id at bounties." + key);
continue;
}
if (value > lastId) {
this.lastId = value;
}
} catch (NumberFormatException e) {
this.plugin.getLogger().warning("Picked up an invalid key at bounties." + key);
}
}
}
|
b0924d0f-f0e6-40dd-b16e-9d60fe0d9c22
| 2
|
public void setline(String line) {
String prev = this.line;
this.line = line;
if(point > line.length())
point = line.length();
if(!prev.equals(line))
changed();
}
|
96ea0aaa-c763-4b21-9012-1e0beffbcbae
| 3
|
public static Opcode getByName(String name, Map<String, Integer> newNBOpcodes) {
Opcode opcode = BY_NAME.get(name);
if(opcode == null && newNBOpcodes != null) {
Integer number = newNBOpcodes.get(name);
if(number != null) {
opcode = new Opcode(name, number<<4, OpcodeType.CUSTOM);
}
}
return opcode;
}
|
8f58b081-4958-49e9-9dd6-fb780fd30ba7
| 0
|
public void windowActivated(WindowEvent e) {
System.out.println("Die Anwendung wurde aktiviert...");
}
|
5ebf2dd0-8e4e-4b51-9646-2534c3878225
| 8
|
public void invokeBusinessLogic(
org.apache.axis2.context.MessageContext msgContext,
org.apache.axis2.context.MessageContext newMsgContext)
throws org.apache.axis2.AxisFault {
try {
// get the implementation class for the Web Service
Object obj = getTheImplementationObject(msgContext);
WSManager wsmgr = new WSManager();
WSMessagesIn wsMessage = new WSMessagesIn();
try {
wsMessage = wsmgr.checkFromAddress(msgContext);
} catch (Exception ex) {
ex.printStackTrace();
}
DGL_CAL_eReferral_InterfaceSkeleton skel = (DGL_CAL_eReferral_InterfaceSkeleton) obj;
System.out.println("DGL_CAL_eReferral_InterfaceSkeleton ske is " + skel.toString());
// Out Envelop
org.apache.axiom.soap.SOAPEnvelope envelope = null;
// Find the axisOperation that has been set by the Dispatch phase.
org.apache.axis2.description.AxisOperation op = msgContext
.getOperationContext().getAxisOperation();
if (op == null) {
throw new org.apache.axis2.AxisFault(
"Operation is not located, if this is doclit style the SOAP-ACTION should specified via the SOAP Action to use the RawXMLProvider");
}
java.lang.String methodName;
if ((op.getName() != null)
&& ((methodName = org.apache.axis2.util.JavaUtils
.xmlNameToJavaIdentifier(op.getName()
.getLocalPart())) != null)) {
if ("fromCal".equals(methodName)) {
com.ut.dph.webservices.provider.hie.ns1.FromCalResponse fromCalResponse1 = null;
com.ut.dph.webservices.provider.hie.ns1.FromCal wrappedParam =
(com.ut.dph.webservices.provider.hie.ns1.FromCal) fromOM(
msgContext.getEnvelope().getBody()
.getFirstElement(),
com.ut.dph.webservices.provider.hie.ns1.FromCal.class,
getEnvelopeNamespaces(msgContext.getEnvelope()));
fromCalResponse1 =
skel.fromCal(wrappedParam, wsMessage);
envelope = toEnvelope(getSOAPFactory(msgContext),
fromCalResponse1, false,
new javax.xml.namespace.QName("ns1", "fromCal"));
} else {
throw new java.lang.RuntimeException("method not found");
}
newMsgContext.setEnvelope(envelope);
}
} catch (FromCalFaultException e) {
msgContext.setProperty(org.apache.axis2.Constants.FAULT_NAME,
"FromCalFault");
org.apache.axis2.AxisFault f = createAxisFault(e);
if (e.getFaultMessage() != null) {
f.setDetail(toOM(e.getFaultMessage(), false));
}
throw f;
}
catch (java.lang.Exception e) {
e.printStackTrace();
throw org.apache.axis2.AxisFault.makeFault(e);
}
}
|
388f3061-d507-4db2-b0b6-13cb451f230b
| 8
|
public int lengthOfLastWord(String s) {
if (s.length() == 0) {
return 0;
}
int length = 0;
boolean wordStart = false;
int i = s.length() - 1;
while (i >= 0) {
if (s.charAt(i) != ' ' && wordStart == false) {
length++;
wordStart = true;
} else if (wordStart == true && s.charAt(i) != ' ') {
length++;
}
else if (wordStart == true && s.charAt(i) == ' ') {
break;
}
i--;
}
return length;
}
|
ed9643a4-3e99-43ee-8033-09fa1e191f0f
| 2
|
public static void main(String[] args)
{
Map<String, Integer> map = new HashMap<String, Integer>();
for (String element : args)
{
map.put(element, (null == map.get(element) ? 1
: map.get(element) + 1));
}
System.out.println(map);
}
|
ee19600a-1d61-48c2-8ad3-3e5871f20f95
| 6
|
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
if (scheme_ != null) {
sb.append(scheme_);
sb.append(':');
}
if (location_ != null) {
sb.append("//");
sb.append(location_);
}
if (path_ != null) {
sb.append(path_);
}
if (parameters_ != null) {
sb.append(';');
sb.append(parameters_);
}
if (query_ != null) {
sb.append('?');
sb.append(query_);
}
if (fragment_ != null) {
sb.append('#');
sb.append(fragment_);
}
return sb.toString();
}
|
3859e617-5073-48d1-986f-1f55d5cd8055
| 6
|
public static String genServerStatus(String[] data) {
if ((data[0] == null) && (data[1] == null) && (data[2] == null)) return "Server is offline";
if ((data[1] != null) && (data[2] != null)) {
if (data[1].equals(data[2])) return "Server is full (Players: " + data[1] + " of " + data[2] + ")";
return data[1] + " of " + data[2] + " players now playing on this server.";
}
return "Server unreachable";
}
|
eb1b59c6-9a6d-460d-b63f-e7242dc727cc
| 7
|
int decodevs(float[] a, int index, Buffer b, int step, int addmul) {
int entry = decode(b);
if (entry == -1) {
return (-1);
}
switch (addmul) {
case -1:
for (int i = 0, o = 0; i < dim; i++, o += step) {
a[index + o] = valuelist[entry * dim + i];
}
break;
case 0:
for (int i = 0, o = 0; i < dim; i++, o += step) {
a[index + o] += valuelist[entry * dim + i];
}
break;
case 1:
for (int i = 0, o = 0; i < dim; i++, o += step) {
a[index + o] *= valuelist[entry * dim + i];
}
break;
default:
//System.err.println("CodeBook.decodeves: addmul="+addmul);
}
return (entry);
}
|
0588542d-4f5c-47de-a651-28e7b71e86a6
| 7
|
@Override
public boolean mutate(Mutation.Type type) {
switch (type) {
case COPY:
case COPY_TREE:
case CREATE_PARENT:
case REMOVE:
return false;
case SWAP:
return Mutation.swap2(rules);
case REPLICATE:
if (rules.isEmpty()) {
return false;
}
Rule replicate = Utils.randomlySelect(rules);
Rule replicated = replicate.dup(this);
rules.add(replicated);
return true;
default:
throw new AssertionError();
}
}
|
59b6d428-dd38-44a6-9745-dcf0ee89b0bd
| 0
|
public FSAConfigurationIcon(Configuration configuration) {
super(configuration);
}
|
6fa744de-300a-4056-b51a-ba7c92ad9eec
| 1
|
public String toString(){
String str = element.toString();
if(program != null)
str += ";" + program.toString();
return str;
}
|
6efed814-4ec2-433d-8f2b-2157e9960d35
| 3
|
void TokenLexicalActions(Token matchedToken)
{
switch(jjmatchedKind)
{
case 20 :
image.append(jjstrLiteralImages[20]);
lengthOfMatch = jjstrLiteralImages[20].length();
nested.push(DEFAULT);
SwitchTo(nested.peek());
break;
case 21 :
image.append(jjstrLiteralImages[21]);
lengthOfMatch = jjstrLiteralImages[21].length();
nested.pop();
SwitchTo(nested.peek());
break;
case 26 :
image.append(jjstrLiteralImages[26]);
lengthOfMatch = jjstrLiteralImages[26].length();
nested.pop();
nested.push(CONTENT);
SwitchTo(nested.peek());
break;
default :
break;
}
}
|
d0f2c486-80ec-4ee4-8d15-c375d50fac12
| 0
|
public String getValue() {
return _value;
}
|
c7d6db5b-cfee-420c-a5c0-9ee123c41ec0
| 5
|
public BookLanguage getBookLanguage(long id) {
BookLanguage lng = null;
Connection con = null;
Statement stmt = null;
try {
DBconnection dbCon = new DBconnection();
Class.forName(dbCon.getJDBC_DRIVER());
con = DriverManager.getConnection(dbCon.getDATABASE_URL(),
dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD());
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("Select * From bookLanguage Where lan_id=" + id);
if (rs.next()) {
lng = new BookLanguage();
lng.setId(rs.getLong(1));
lng.setCode(rs.getString(2));
lng.setName(rs.getString(3));
}
} catch (SQLException | ClassNotFoundException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
}
}
return lng;
}
|
bf2fded6-3364-4749-be6e-96fc00a81fc8
| 8
|
final public void DoStatement() throws ParseException {
/*@bgen(jjtree) WhileStatement */
BSHWhileStatement jjtn000 = new BSHWhileStatement(JJTWHILESTATEMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(DO);
Statement();
jj_consume_token(WHILE);
jj_consume_token(LPAREN);
Expression();
jj_consume_token(RPAREN);
jj_consume_token(SEMICOLON);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.isDoStatement=true;
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{if (true) throw (RuntimeException)jjte000;}
}
if (jjte000 instanceof ParseException) {
{if (true) throw (ParseException)jjte000;}
}
{if (true) throw (Error)jjte000;}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
|
3cabd6ff-146b-405c-b0bd-c7602243945f
| 7
|
public void save(final FilterDTO filter)
throws DBException
{
class IdFiller extends PreparedStatementHandler
{
public IdFiller()
{
super(FilterDAO.this.mgr, ID_BYNAME_SQL);
}
@Override
protected void handleResults(ResultSet rs)
throws SQLException, DBException
{
// id or empty results selected
if (rs.next())
filter.setId(rs.getInt(1));
else
{
sql = INSERT_NAME_SQL;
execute();
}
}
@Override
protected void handleUpdate(PreparedStatement stmt)
throws SQLException, DBException
{
// new record inserted
ResultSet idrs = stmt.getGeneratedKeys();
if (idrs.next())
filter.setId(idrs.getInt(1));
else
throw new NoSuchRecordException(filter);
}
@Override
protected void bindParameters(PreparedStatement stmt)
throws SQLException
{
stmt.setString(1, filter.getName());
}
@Override
protected String legend()
{
return "updating filter \"" + filter.getName() + '"';
}
};
class Cleaner extends PreparedStatementHandler
{
public Cleaner()
{
super(FilterDAO.this.mgr, CLEAR_ELEMENTS_SQL);
}
public void setType(FilterDTO.Type type)
{
this.type = type;
}
@Override
protected void bindParameters(PreparedStatement stmt) throws SQLException
{
stmt.setInt(1, filter.getId());
stmt.setString(2, type.name());
}
@Override
protected String legend()
{
return "clearing entries of type " + type + " from filter \"" + filter.getName() + '"';
}
private FilterDTO.Type type;
};
class Appender extends PreparedStatementHandler
{
public Appender()
{
super(FilterDAO.this.mgr, APPEND_ELEMENT_SQL);
}
public void setType(FilterDTO.Type type)
{
this.type = type;
this.number = 0;
}
public void setValue(String value)
{
this.value = value;
}
@Override
protected void bindParameters(PreparedStatement stmt) throws SQLException
{
stmt.setInt(1, filter.getId());
stmt.setString(2, type.name());
stmt.setInt(3, ++number);
stmt.setString(4, value);
}
@Override
protected String legend()
{
return "appending element \"" + value
+ "\" of type " + type + " to filter \"" + filter.getName() + '"';
}
private FilterDTO.Type type;
private String value;
private int number;
};
// protect auto-generated filter 'all' from updates
if (ALL_FILTER.equalsIgnoreCase(filter.getName()))
throw new ConstraintViolationException(TABLE_NAME, "Immutable_" + ALL_FILTER,
"Updates of filter \"" + ALL_FILTER + "\" are not allowed");
// update the filter
Transaction txn = mgr.beginTransaction();
try
{
if (0 == filter.getId())
new IdFiller().execute();
Cleaner cleaner = new Cleaner();
Appender appender = new Appender();
for (FilterDTO.Type type : FilterDTO.Type.values())
{
cleaner.setType(type);
cleaner.execute();
appender.setType(type);
List<String> elements = filter.getElementsAsStrings(type);
for (String element : elements)
{
appender.setValue(element);
appender.execute();
}
}
txn.commit();
}
finally
{
if (null != txn && txn.isActive())
try { txn.abort(); }
catch (Exception fault)
{
log().log(Level.WARNING, "Rollback failed after an attempt to save " + filter, fault);
}
}
}
|
d1ae2d39-fe66-4fc0-9f4d-9dc592121ccb
| 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(AtlasFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AtlasFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AtlasFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AtlasFrame.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 AtlasFrame().setVisible(true);
}
});
}
|
4c06a2b9-3218-4bd5-a2d3-a934665c3e60
| 5
|
private void update_estimated_initial_distribution( int j, double[] bowl ) {
// initialization
if( 0 == j ) {
assign_belief_of_initial_distribution(smoothed_distribution_count);
}
// Calculate the smoothed count
if ( 0 == j ) {
for ( int i = 0; i < pref.length; i++) {
smoothed_distribution_count[i] *= updateWeight;
}
}
double sum = 0;
for ( int i = 0; i < pref.length; i++) {
smoothed_distribution_count[i] += (double)(bowl[i]);
sum += smoothed_distribution_count[i];
}
for ( int i = 0; i < pref.length; i++) {
estimated_initial_distribution[i] =
smoothed_distribution_count[i] * ((double)(nfruits) / sum);
}
}
|
51bd5459-f1d4-411f-b6ae-65b7fbd4305e
| 1
|
private int getPort() {
int port = uri.getPort();
return port == -1 ? WebSocket.DEFAULT_PORT : port;
}
|
d5bb49c7-b443-41e5-99b3-1e48cdb68d41
| 5
|
public void deleteNonAxisFields ( Field checkVeld , String direction ) {
//System.out.println("Deleten niet-as velden...");
if (direction.equals("horizontal")) {
for (int i = 0 ; i < remainingFields.size() ; i++) {
Field v = remainingFields.get(i);
if (checkVeld.getX() != v.getX()) {
preferableFields.remove(v);
}
}
} else {
for (int i = 0 ; i < remainingFields.size() ; i++) {
Field v = remainingFields.get(i);
if (checkVeld.getY() != v.getY()) {
preferableFields.remove(v);
}
}
}
}
|
c4fa4f53-091c-4dc7-a026-331c2709b7df
| 5
|
@Override
public ArrayList<Integer[]> selection(ArrayList<Integer[]> population, int size) {
if (size > population.size()) {
return population;
}
ArrayList<Integer[]> parents = new ArrayList<>();
Collections.shuffle(population);
double[] grades = gradeEveryone(population);
int matchLength = grades.length / size;
for (int i = 0; i < size; ++i) {
int best = i * matchLength;
for (int j = 1; j < matchLength && i * size + j < grades.length; ++j) {
if (grades[best] > grades[i * size + j]) {
best = i * size + j;
}
}
parents.add(population.get(best));
}
return parents;
}
|
30d7d9b2-eab8-4934-88ba-8d6e784d64f7
| 1
|
public void move(){
if(x < 0)
x = 600;
x -= 1;
}
|
8b4e73e5-6b70-428a-bb2d-76b692094c15
| 3
|
@Override
public int hashCode() {
//autogenerated by netbeans for me
//this is a really wierd hash
int hash = 7;
hash = 17 * hash + (this.value != null ? this.value.hashCode() : 0);
hash = 17 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 17 * hash + (this.readonly ? 1 : 0);
return hash;
}
|
501ccb38-dc4a-4180-9e93-bcc4da121685
| 3
|
public boolean connection(String userName,String password)
{
boolean response=false;
for(Member m : memberBean.getMembers() )
{
if(m.getUsername().equals(userName)&&m.getPassword().equals(password))
{
currentMember=m;
response=true;
}
}
return response;
}
|
80232525-d958-405b-99f9-077a83d68cdb
| 3
|
public synchronized void actualiza(long tiempoTranscurrido) {
if (cuadros.size() > 1) {
tiempoDeAnimacion += tiempoTranscurrido;
if (tiempoDeAnimacion >= duracionTotal) {
tiempoDeAnimacion = tiempoDeAnimacion % duracionTotal;
indiceCuadroActual = 0;
}
while (tiempoDeAnimacion > getCuadro(indiceCuadroActual).tiempoFinal) {
indiceCuadroActual++;
}
}
}
|
66c5bd42-3346-4cab-9cda-fd07044b3b97
| 4
|
@GET
@Path("/feeds/{repoName}.atom")
@Produces(MediaType.APPLICATION_ATOM_XML)
public String getRepositoryFeed(
@PathParam("repoName") String repoName,
@Context HttpServletRequest request) {
if (StringUtils.isEmpty(repoName)) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
StringWriter writer = new StringWriter();
try {
Feed feed = dao.getReleaseFeed(repoName, getBaseUrl(request), WebConstants.MAX_FEED_ENTRIES);
WireFeedOutput feedOutput = new WireFeedOutput();
feedOutput.output(feed, writer);
}
catch (NotFoundException e) {
logger.log(Level.WARNING, e.getMessage(), e);
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
catch (IOException e) {
logger.log(Level.SEVERE, "Failed to load repo list: {0}", e.getMessage());
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
catch (FeedException e) {
logger.log(Level.SEVERE, "Failed to create feed: {0}", e.getMessage());
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
return writer.toString();
}
|
bcdd49c6-f056-4ff0-ac93-099c461f9920
| 7
|
public ArrayList<Product> Build(){
FileReader fr= null;
try{
fr = new FileReader("C:\\Users\\Canary\\Documents\\NetBeansProjects\\WebApplication1\\src\\java\\Files\\ListaProductos.txt");
BufferedReader bf = new BufferedReader(fr);
String sCadena;
String vec1;
String vec2;
String vec3;
String[] vec4;
ArrayList<Product> product = new ArrayList<>();
while ((sCadena = bf.readLine()) != null) {
vec1 = sCadena.split("@")[0];
vec2 = sCadena.split("@")[1];
try{
vec3 = sCadena.split("@")[2];
try{
vec4 = vec3.split(",");
ArrayList<Author> authors = new ArrayList<>();
for (String string : vec4) {
Author author= new Author(string);
authors.add(author);
//hay que mirar como eliminar un autor.
}
product.add(new Product(vec1,Double.valueOf(vec2),authors));
}
catch (ArrayIndexOutOfBoundsException ex){
product.add(new Product(vec1,Double.valueOf(vec2)));
}
}
catch (ArrayIndexOutOfBoundsException ex){
product.add(new Product(vec1,Double.valueOf(vec2)));
}
}
return product;
}
catch (FileNotFoundException ex){
throw new RuntimeException("Archivo no encontrado");
//Logger.getLogger(ProductListBuilder.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex){
throw new RuntimeException("Ocurrio un error de entrada/salida");
//Logger.getLogger(ProductListBuilder.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
//No sé por qué está el warning
fr.close();
} catch (IOException ex) {
Logger.getLogger(ProductListBuilder.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("No sé que ha pasado");
return null;
}
}
}
|
c762d77a-6c19-4023-be0b-bf1d78945eba
| 4
|
@Override
public List<Scroll> selectPlays(GameState state) {
List<Scroll> plays = new ArrayList<Scroll>();
List<Scroll> hand = new ArrayList<Scroll>(state.getHand());
Collections.sort(hand, new Comparator<Scroll>() {
@Override
public int compare(Scroll lhs, Scroll rhs) {
//This fails for costs at the extremes, but works well enough here.
return rhs.getCost() - lhs.getCost();
}
});
int remainingMana = state.getRemainingMana();
for(Scroll scroll : hand) {
//if we can cast the scroll
if(scroll.getCost() <= remainingMana) {
//if the scroll has a legal targret
if(!scroll.isTargeted() || scroll.getTarget(state) != null) {
plays.add(scroll);
state.setRemainingMana(remainingMana - scroll.getCost());
return plays;
}
}
}
return plays;
}
|
7e30948e-a662-4b7b-ab63-78d7b7a999eb
| 6
|
boolean testLookAhead(TokenID token) {
Token afterNextSymbol = null;
try {
afterNextSymbol = scanner.yylex();
if (afterNextSymbol != null) {
scanner.yypushback(afterNextSymbol.text().length());
}
} catch (java.lang.Error e) {
// will be thrown when next symbol is EOF
// in this case null is a good value for afterNextSymbol
} catch (java.io.FileNotFoundException e) {
System.out.println("File not found : \"" + fileName + "\"");
} catch (java.io.IOException e) {
System.out.println("IO error scanning file \"" + fileName + "\"");
System.out.println(e);
} catch (Exception e) {
System.out.println("Unexpected exception:");
e.printStackTrace();
}
return afterNextSymbol == null ? token == null : afterNextSymbol.id() == token;
}
|
e8e7a2fd-2b8d-440d-9eb1-91acf57e33e5
| 3
|
private boolean isValidPosition(Position newPos, int width, int height) {
return newPos.xCoordinate >= 0 && newPos.yCoordinate >= 0 && newPos.xCoordinate < width && newPos.yCoordinate < height;
}
|
203b21ad-fdb7-4a00-82d6-fbb52d1f5c65
| 8
|
@Override
public <SM, TM, SR, TR> TR execute(final MapReduce<SM, TM, SR, TR> mapReduce, SM source) {
final Collection<TM> slices = mapReduce.getMapper().map(source);
TR result = null;
if (slices != null && !slices.isEmpty()) {
final List<Future<SR>> futures = Lists.newArrayList();
final CountDownLatch countDownLatch = new CountDownLatch(slices.size());
for (final TM slice : slices) {
final Future<SR> future = executorService.submit(new Callable<SR>() {
@Override
public SR call() {
try {
return mapReduce.getWorker().doJob(slice);
} finally {
countDownLatch.countDown();
}
}
});
futures.add(future);
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
// JUST IGNORE
}
final List<SR> futureResults = Lists.newArrayList();
for (Future<SR> future : futures) {
try {
futureResults.add(future.get());
} catch (InterruptedException e) {
// JUST IGNORE
} catch (ExecutionException e) {
throw Throwables.propagate(e);
}
}
if (!futureResults.isEmpty()) {
result = mapReduce.getReducer().reduce(futureResults);
}
}
return result;
}
|
32dc7d62-b463-47c4-876c-5c5a4bf1ade4
| 4
|
protected void requestPlayerInput(Game game)
{
ElapsedCpuTimer ect = new ElapsedCpuTimer(CompetitionParameters.TIMER_TYPE);
ect.setMaxTimeMillis(CompetitionParameters.ACTION_TIME);
Types.ACTIONS action;
if (game.no_players > 1) {
action = this.player.act(game.getObservationMulti(), ect.copy());
} else {
action = this.player.act(game.getObservation(), ect.copy());
}
//System.out.println(action);
if(ect.exceededMaxTime())
{
long exceeded = - ect.remainingTimeMillis();
if(ect.elapsedMillis() > CompetitionParameters.ACTION_TIME_DISQ)
{
//The agent took too long to replay. The game is over and the agent is disqualified
System.out.println("Too long: " + playerID + "(exceeding "+(exceeded)+"ms): controller disqualified.");
game.disqualify(playerID);
}else{
System.out.println("Overspent: " + playerID + "(exceeding "+(exceeded)+"ms): applying ACTION_NIL.");
}
action = Types.ACTIONS.ACTION_NIL;
}
if(!actions.contains(action))
action = Types.ACTIONS.ACTION_NIL;
this.player.logAction(action);
game.setAvatarLastAction(action, getPlayerID());
ki.reset(getPlayerID());
ki.setAction(action, getPlayerID());
}
|
c30169fe-b118-4798-b851-a15ce8929102
| 8
|
private void readEvalPrint() {
buffer = new BufferedReader(new InputStreamReader(System.in));
String arguments[] = null;
while (true) {
System.err.print("> ");
try {
arguments = inputParse(buffer.readLine());
/** invokes the name corresponding to command requested **/
if (arguments[0].equals("q")) {
buffer.close();
return;
} else {
this.getClass()
.getDeclaredMethod(arguments[0], String[].class)
.invoke(this, new Object[] { arguments });
}
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
InfoPrinter.printCommandNotFound(arguments[0]);
}
}
}
|
a8d343f8-db99-41cb-9910-3b468e8d6673
| 8
|
public String lookup(int value, String type) {
String result = null;
Iterator it;
System.out.println("TYPE:" + type);
// this is where we look up rules defined in our two dimensional matrix,
// sorted by contextual type (i.e., temperature)
switch (type) {
case "temperature": {
// temperature fuzzy set
it = tempRules.entrySet().iterator();
Map.Entry currTempEntry = null;
Map.Entry prevTempEntry = null;
// get the first entry
currTempEntry = (Map.Entry) it.next();
while (it.hasNext()) {
// store the previous entry
prevTempEntry = currTempEntry;
// get the next entry
currTempEntry = (Map.Entry) it.next();
// if... then...
// very cold vs cold, cold vs warm, etc.
// if value is between 0 AND value is between 10
// assign it this linguistic type
if (value >= (int) prevTempEntry.getKey()
&& value <= (int) currTempEntry.getKey()) {
result = (String) currTempEntry.getValue();
}
}
break;
}
case "movement": {
// temperature fuzzy set
it = ultrasonicRules.entrySet().iterator();
Map.Entry currTempEntry = null;
Map.Entry prevTempEntry = null;
// get the first entry
currTempEntry = (Map.Entry) it.next();
while (it.hasNext()) {
// store the previous entry
prevTempEntry = currTempEntry;
// get the next entry
currTempEntry = (Map.Entry) it.next();
// if... then...
// away vs present, etc.
// if value is between 0 AND value is between 10
// assign it this linguistic type
if (value >= (int) prevTempEntry.getKey()
&& value <= (int) currTempEntry.getKey()) {
result = (String) currTempEntry.getValue();
}
}
break;
}
}
return result;
}
|
999432f7-1bd8-4ac2-9908-1c2c84afbb1a
| 4
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RID other = (RID) obj;
if (id != other.id)
return false;
return true;
}
|
29dd5817-5ede-4fcd-b146-19e21f31c65e
| 0
|
public RODashboardData() {
lastPacketTime = -1;
lastUptime = -1;
robotState = -1;
lastFirmwareVer = -1;
validRxPackets = 0;
invalidRxPackets = 0;
bundles = new ArrayList<String>();
}
|
4ed53dac-8c6f-49e7-8f98-eb5344f5dac2
| 0
|
void showIndicator(Label indicator) {
clearIndicator();
hboxIndicator.getChildren().add(indicator);
}
|
d9184f18-50a7-4672-8bc5-53b0c22c206a
| 0
|
public Grid createGrid() {
// Random random = new Random();
// Grid gg = new Grid(30 + random.nextInt(20), 30 + random.nextInt(20), 0, 0, 3, 3);
// CellIterator iterator = gg.getCellIterator();
// for (CellIterator ci = gg.getCellIterator(); ci.next();) {
// ci.setAliveInNextGeneration(random.nextBoolean());
// }
// gg.takeNextStep();
//
// return gg;
return null;
}
|
cc97f662-7acf-4dde-81ff-3b92c8613fd3
| 4
|
public void mouseReleased(MouseEvent e) {
if (currentElement == null) return;
else if (currentElement instanceof Spring) {
Point2D.Double p= new Point2D.Double(0,0);
MyWorldView.SPACE_INVERSE_TRANSFORM.transform(e.getPoint(),p);
Spring spring = (Spring) currentElement;
// we dragged a spring, so we look for and attachable element near by
SpringAttachable elementA = world.findSpringAttachable(spring.getAendPosition(), p.getY());
SpringAttachable elementB = world.findSpringAttachable(spring.getBendPosition(), p.getY());
if (elementA != null) {
spring.attachBend(elementA);
}
if (elementB != null) {
spring.attachAend(elementB);
}
}
System.out.println("Mouse released.");
currentElement.setReleased();
currentElement = null;
world.repaintView();
}
|
308d7929-bf1a-4b09-8f6f-753ff14d3cd4
| 5
|
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void handleBlockBurn(BlockBurnEvent event) {
if (!WorldManager.getInstance().isFireSpreadAllowed()) {
if (Cuboid.getCuboid(event.getBlock().getLocation()) == null) {
event.setCancelled(true);
} else {
Cuboid c = Cuboid.getCuboid(event.getBlock().getLocation());
if (c.getCuboidType() != CuboidType.Survival.getTypeID()
|| c.getCuboidType() != CuboidType.Habitat.getTypeID()
|| c.getCuboidType() != CuboidType.Shop.getTypeID()) {
event.setCancelled(true);
}
}
}
}
|
bcc7acec-82b5-4e2f-8b04-0feab2aa9fdc
| 3
|
void init_validation() {
try {
/* Run sharding (preprocessing) if the files do not exist yet */
sharder_validation = IO.createSharder(training + "e", 1);
if (!new File(ChiFilenames.getFilenameIntervals(training + "e", nShards)).exists() ||
!new File(training + "e.matrixinfo").exists()) {
sharder_validation.shard(new FileInputStream(new File(training + "e")), FastSharder.GraphInputFormat.MATRIXMARKET);
} else {
logger.info("Found validation shards -- no need to preprocess");
}
} catch (IOException ex){
logger.warning("Failed to initalize validation input. Aborting.");
}
}
|
42d6ed8e-ae1a-4164-a9df-e3c3428ae556
| 0
|
public void setPlayerTwoWin()
{
currentState = States.PlayerTwoWin;
}
|
095564cd-0d41-407f-bf49-6781e3c979f4
| 9
|
protected int diff_commonOverlap(String text1, String text2) {
// Cache the text lengths to prevent multiple calls.
int text1_length = text1.length();
int text2_length = text2.length();
// Eliminate the null case.
if (text1_length == 0 || text2_length == 0) {
return 0;
}
// Truncate the longer string.
if (text1_length > text2_length) {
text1 = text1.substring(text1_length - text2_length);
} else if (text1_length < text2_length) {
text2 = text2.substring(0, text1_length);
}
int text_length = Math.min(text1_length, text2_length);
// Quick check for the worst case.
if (text1.equals(text2)) {
return text_length;
}
// Start by looking for a single character match
// and increase length until no match is found.
// Performance analysis: http://neil.fraser.name/news/2010/11/04/
int best = 0;
int length = 1;
while (true) {
String pattern = text1.substring(text_length - length);
int found = text2.indexOf(pattern);
if (found == -1) {
return best;
}
length += found;
if (found == 0 || text1.substring(text_length - length).equals(
text2.substring(0, length))) {
best = length;
length++;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.