text stringlengths 14 410k | label int32 0 9 |
|---|---|
protected double objectiveFunction(double[] x){
double nll = 0; // -LogLikelihood
int dim = m_NumPredictors+1; // Number of variables per class
for(int i=0; i<cls.length; i++){ // ith instance
double[] exp = new double[m_NumClasses-1];
int index;
for(int offset=0; offset<m_NumClasses-1; offset++){
index = offset * dim;
for(int j=0; j<dim; j++)
exp[offset] += m_Data[i][j]*x[index + j];
}
double max = exp[Utils.maxIndex(exp)];
double denom = Math.exp(-max);
double num;
if (cls[i] == m_NumClasses - 1) { // Class of this instance
num = -max;
} else {
num = exp[cls[i]] - max;
}
for(int offset=0; offset<m_NumClasses-1; offset++){
denom += Math.exp(exp[offset] - max);
}
nll -= weights[i]*(num - Math.log(denom)); // Weighted NLL
}
// Ridge: note that intercepts NOT included
for(int offset=0; offset<m_NumClasses-1; offset++){
for(int r=1; r<dim; r++)
nll += m_Ridge*x[offset*dim+r]*x[offset*dim+r];
}
return nll;
} | 7 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
try
{
HttpSession session = request.getSession(true);
AlumnoBean alumno = ((AlumnoBean) (session.getAttribute("currentSessionUser")));
System.out.println("RUT SESION: "+alumno.getRut());
System.out.println("TIPO SESION: "+alumno.getType());
//Se Definen las estructuras
Curriculum curriculum = new Curriculum();
List<AreaInteres> listAreas = new ArrayList<AreaInteres>();
List<Idioma> listIdiomas = new ArrayList<Idioma>();
List<DatoAcademico> datosAcademicos= new ArrayList<DatoAcademico>();
List<HistorialLaboral> laborales = new ArrayList<HistorialLaboral>();
// Captura de datos academicos
DatoAcademico academico = new DatoAcademico();
String contadorDA = request.getParameter("contadorDA");
String descripcion_da = request.getParameter("descripcion_da");
String establecimiento_da = request.getParameter("establecimiento_da");
String fechaInicio_da = request.getParameter("fechaInicio_da");
String fechaTermino_da = request.getParameter("fechaTermino_da");
int cda = Integer.parseInt(contadorDA);
System.out.println(contadorDA + " " + descripcion_da + " " + establecimiento_da + " " +
fechaInicio_da + " " + fechaTermino_da);
academico.setDescripcion(descripcion_da);
academico.setEstablecimiento(establecimiento_da);
academico.setInicio(fechaInicio_da);
academico.setFin(fechaTermino_da);
datosAcademicos.add(academico);
for (int i = 2; i <= cda; i++) { //for (int i = 2; i <= cda; i++)
academico= new DatoAcademico();
descripcion_da = request.getParameter("descripcion_da:"+i);
if(descripcion_da!=null){
establecimiento_da = request.getParameter("establecimiento_da:"+i);
fechaInicio_da = request.getParameter("fechaInicio_da:"+i);
fechaTermino_da = request.getParameter("fechaTermino_da:"+i);
System.out.println(contadorDA + " " + descripcion_da + " " + establecimiento_da + " " +
fechaInicio_da + " " + fechaTermino_da);
academico.setDescripcion(descripcion_da);
academico.setEstablecimiento(establecimiento_da);
academico.setInicio(fechaInicio_da);
academico.setFin(fechaTermino_da);
datosAcademicos.add(academico);
}
}
System.out.println("Lista de datos academicos "+datosAcademicos.size());
// // Captura de historial academico
HistorialLaboral laboral = new HistorialLaboral();
String contadorHL = request.getParameter("contadorHL");
String descripcion_hl = request.getParameter("descripcion_hl");
String establecimiento_hl = request.getParameter("establecimiento_hl");
String cargo_hl = request.getParameter("cargo_hl");
String fechaInicio_hl = request.getParameter("fechaInicio_hl");
String fechaTermino_hl = request.getParameter("fechaTermino_hl");
System.out.println(contadorHL + " " + descripcion_hl + " " + establecimiento_hl + " " + cargo_hl + " " +
fechaInicio_hl + " " + fechaTermino_hl);
laboral.setDescripcion(descripcion_hl);
laboral.setEstablecimiento(establecimiento_hl);
laboral.setCargo(cargo_hl);
laboral.setInicio(fechaInicio_hl);
laboral.setFin(fechaTermino_hl);
laborales.add(laboral);
int chl = Integer.parseInt(contadorHL);
for (int i = 2; i <= chl; i++) {
laboral = new HistorialLaboral();
descripcion_hl = request.getParameter("descripcion_hl:"+i);
if(descripcion_hl != null){
establecimiento_hl = request.getParameter("establecimiento_hl:"+i);
cargo_hl = request.getParameter("cargo_hl:"+i);
fechaInicio_hl = request.getParameter("fechaInicio_hl:"+i);
fechaTermino_hl = request.getParameter("fechaTermino_hl:"+i);
System.out.println(contadorHL + " " + descripcion_hl + " " + establecimiento_hl + " " + cargo_hl + " " +
fechaInicio_hl + " " + fechaTermino_hl);
laboral.setDescripcion(descripcion_hl);
laboral.setEstablecimiento(establecimiento_hl);
laboral.setCargo(cargo_hl);
laboral.setInicio(fechaInicio_hl);
laboral.setFin(fechaTermino_hl);
laborales.add(laboral);
}
}
System.out.println("Laboral: "+laborales.size());
// datos de idiomas
Idioma idiomaI = new Idioma();
String contadorID = request.getParameter("contadorID");
String idioma = request.getParameter("idioma");
String nivel = request.getParameter("nivel");
System.out.println(contadorID + " " + idioma + " " + nivel);
idiomaI.setIdioma(idioma);
idiomaI.setNivel(nivel);
listIdiomas.add(idiomaI);
int cid = Integer.parseInt(contadorID);
for (int i = 2; i <= cid; i++) {
idiomaI = new Idioma();
idioma = request.getParameter("idioma:"+i);
if(idioma != null){
nivel = request.getParameter("nivel:"+i);
System.out.println(contadorID + " " + idioma + " " + nivel);
idiomaI.setIdioma(idioma);
idiomaI.setNivel(nivel);
listIdiomas.add(idiomaI);
}
}
String[] areas = request.getParameterValues("areas[]");
AreaInteres interes;
for(int i =0; i < areas.length; i++){
interes= new AreaInteres();
interes.setArea(areas[i]);
listAreas.add(interes);
}
System.out.println("Areas de Interes: "+listAreas.size());
// SE ASOCIAN LOS DATOS AL CURRICULUM
curriculum.setId(1);
curriculum.setRun(alumno.getRut());
curriculum.setDatosAcademicos(datosAcademicos);
curriculum.setIdiomas(listIdiomas);
curriculum.setIntereses(listAreas);
curriculum.setLaborales(laborales);
// Se inserta el curriculum al DAO
alumno.setCurriculum(curriculum);
boolean flag=CurriculumDAO.updateCurriculum(alumno);
if(flag){
response.sendRedirect("exitosaPeticion.jsp");
}else{
response.sendRedirect("errorModificacion.jsp");
}
}catch (Throwable theException)
{
System.out.println(theException);
}
} | 9 |
public void insertCommentDependencies(BasicDBList comments) {
Map<String, List<DBObject>> map = new HashMap<String, List<DBObject>>();
BasicDBList photoIds = new BasicDBList();
for (Object objectComment : comments) {
DBObject comment = (DBObject) objectComment;
String photoId = (String) comment.get("itemId");
photoIds.add(photoId);
if (!map.containsKey(photoId)) {
map.put(photoId, new ArrayList<DBObject>());
}
map.get(photoId).add(comment);
}
BasicDBList photos = readPhotos(photoIds);
for (Object objectPhoto : photos) {
DBObject photo = (DBObject) objectPhoto;
String idPhoto = (String) photo.get("_id");
for (DBObject comment : map.get(idPhoto)) {
comment.put("photo", photo);
}
}
} | 4 |
public void setLeft(PExp node)
{
if(this._left_ != null)
{
this._left_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._left_ = node;
} | 3 |
public void setPos(ChessPosition pos) {
if (state != GameState.PLAYING) {
System.out.println("finish game: " + state);
return;
}
if (isChooseForMove(pos)) { // chon quan de di chuyen
// loai bo pos khong hop le
if (board.getPiece(pos) == 0)
return;
oldPos = pos; // neu hop le thi danh dau oldPos da chon
newPos = null;
updatePosCanMove();
} else if (oldPos != null) { // neu da co pos duoc chon
// thi di chuyen quan den vi tri moi
// vi tri di chuyen den phai nam trong posCanMove
boolean validPos = false;
for (ChessPosition posCM : posCanMove) {
if (posCM.getRow() == pos.getRow()
&& posCM.getCol() == pos.getCol()) {
validPos = true;
break;
}
}
if (validPos == false)
return;
// vi tri hop le thi tien hanh di chuyen
newPos = pos;
this.move(oldPos, newPos);
}
} | 8 |
public synchronized Promotion removePromotion(Promotion promotion) {
if (promotion != null) {
for (Promotion promotionAux : listPromotion) {
if (promotionAux.getPromotionCode() == promotion
.getPromotionCode()) {
listPromotion.remove(promotionAux);
logger.info("Promotion successfully Removed! Promotion Code: "
+ promotionAux.getPromotionCode());
return promotionAux;
}
}
}
logger.info("Error removing promotion: Promotion is not added!");
return null;
} | 3 |
private void initInput() {
moveLeft = new GameAction("moveLeft");
moveRight = new GameAction("moveRight");
jump = new GameAction("jump",
GameAction.DETECT_INITAL_PRESS_ONLY);
exit = new GameAction("exit",
GameAction.DETECT_INITAL_PRESS_ONLY);
fire = new GameAction("fire");
pause = new GameAction("pause", GameAction.DETECT_INITAL_PRESS_ONLY);
restart = new GameAction("restart", GameAction.DETECT_INITAL_PRESS_ONLY);
instructions = new GameAction("instructions", GameAction.DETECT_INITAL_PRESS_ONLY);
credits = new GameAction("credits", GameAction.DETECT_INITAL_PRESS_ONLY);
sound = new GameAction("sound", GameAction.DETECT_INITAL_PRESS_ONLY);
inputManager = new InputManager(
screen.getFullScreenWindow());
inputManager.setCursor(InputManager.INVISIBLE_CURSOR);
inputManager.mapToKey(moveLeft, KeyEvent.VK_LEFT);
inputManager.mapToKey(moveRight, KeyEvent.VK_RIGHT);
inputManager.mapToKey(jump, KeyEvent.VK_UP);
inputManager.mapToKey(fire, KeyEvent.VK_SPACE);
inputManager.mapToKey(exit, KeyEvent.VK_ESCAPE);
inputManager.mapToKey(pause, KeyEvent.VK_P);
inputManager.mapToKey(restart, KeyEvent.VK_ENTER);
inputManager.mapToKey(instructions, KeyEvent.VK_I);
inputManager.mapToKey(credits, KeyEvent.VK_C);
inputManager.mapToKey(sound, KeyEvent.VK_S);
} | 0 |
public boolean compleixRes(Clausula c, ClausulaNom cn) {
Aula aulaa = cn.getAula();
int horaa = cn.getHora();
String diaa = cn.getDia();
int dur = c.getDuracio();
boolean compleix = true;
if (this.aula.equals(aulaa)) { //Si hablan de la aula que esta restringida
if (this.hora != null) { //Si este aula no puede usarse un dia a una hora concreta...
if (this.dia.equals(diaa)) {
if (this.hora >= horaa && this.hora < horaa+dur)
compleix = false; //Si se va a usar la hora que esta prohibida.
}
} else { //Si este aula no puede usarse un dia entero...
if (this.dia.equals(diaa)) compleix = false;
}
}
return compleix;
} | 6 |
public void getSignature(SourceWriter writer)
{
writer.printIndent();
// process visibility
if (this._visibility != null && this._visibility.length() > 0)
{
writer.print(this._visibility).print(" ");
}
if (this.getSuperClass() != Type.OBJECT_CLASS)
{
writer.print("type ").print(this.getName()).print(" extends ").println(this.getSuperClass().getName());
}
else
{
writer.print("type ").println(this.getName());
}
writer.printlnWithIndent("{").increaseIndent();
if (this.hasConstructors())
{
// copy constructor list and sort
List<Constructor> constructors = new ArrayList<Constructor>(this._constructors);
SignatureUtils.sort(constructors);
for (Constructor constructor : constructors)
{
constructor.getSignature(writer);
writer.println();
}
}
if (this.hasProperties())
{
// copy property list and sort
List<Property> properties = new ArrayList<Property>(this._properties);
SignatureUtils.sort(properties);
for (Property property : properties)
{
property.getSignature(writer);
writer.println();
}
}
if (this.hasMethods())
{
// copy method list and sort
List<Method> methods = new ArrayList<Method>(this._methods);
SignatureUtils.sort(methods);
for (Method method : methods)
{
method.getSignature(writer);
writer.println();
}
}
writer.decreaseIndent().printlnWithIndent("}");
} | 9 |
@Override
public int compare(double[] b1, double[] b2) {
if (b1[col] < b2[col]) {
return -1 * order;
} else if (b1[col] == b2[col]) {
return 0 * order;
} else {
return 1 * order;
}
} | 2 |
public void reset() {
history.clear();
for (Cell cell : all()) {
if (cell.isEditable()) {
cell.clear();
if (!initialPoss) {
cell.poss().clear();
}
}
}
if (initialPoss) {
for (Cell cell : all()) {
cell.poss().addAll();
for (Cell neighbour : neighbours(cell.row, cell.column, false)) {
if (neighbour.value() != 0) {
cell.poss().remove(neighbour.value());
}
}
}
}
} | 7 |
public static void setFontForComponent(Component Comp, Font font) {
if (font == null) {
try {
if (Locale.getDefault().toString().toLowerCase().contains("zh")) {
font = new Font("Microsoft YaHei", Font.PLAIN, 12);
}
} catch (Throwable e) {
}
}
if (font == null) {
return;
}
if (Comp != null) {
try {
Comp.setFont(font);
} catch (Exception e) {
return;
}
}
if (Comp instanceof Container) {
Component[] components = ((Container) Comp).getComponents();
for (int i = 0; i < components.length; i++) {
Component child = components[i];
if (child != null) {
setFontForComponent(child, font);
}
}
}
return;
} | 9 |
private boolean menuHasAddFriend(int arg0) {
if (arg0 < 0) {
return false;
}
int k = menuActionOpcode[arg0];
if (k >= 2000) {
k -= 2000;
}
return k == 337;
} | 2 |
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == load)
try {
loadFile();
} catch (FileNotFoundException ex) {
System.out.println("File not found: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("General I/O exception: " + ex.getMessage());
}
if (e.getSource() == solve)
startSolver();
} | 4 |
public void setClientName(String clientName) {
this.clientName = clientName;
} | 0 |
@Override
public Carte modifier_carte(HashMap<String, Object> map) {
String nom = this.nom,actions = this.actions;
int type = this.type_dresseur;
if(map.get("nom") instanceof String && !map.get("nom").equals(""))
nom = map.get("nom").toString();
if(map.get("actions") instanceof String && !map.get("actions").equals(this.actions))
actions = map.get("actions").toString();
if(map.get("type") instanceof Integer)
type = ((Integer)map.get("type") < 0 || (Integer)map.get("type") > TYPE_DRESSEUR_NOM.length)?this.type_dresseur:(Integer)map.get("type");
return new Dresseur(this.numero, type , nom,actions);
} | 7 |
private void RegenerateFurniCollisionMap()
{
for(int x = 0; x < this.GrabModel().MapSizeX; x++) //Loopception courtesy of Cobe & Cecer
{
for(int y = 0; y < this.GrabModel().MapSizeY; y++)
{
FurniCollisionMap[x][y] = 1;
}
}
for(FloorItem Item : FloorItems.values())
{
for(AffectedTile Tile : AffectedTile.GetAffectedTiles(Item.GetBaseItem().Length, Item.GetBaseItem().Width, Item.X, Item.Y, Item.Rotation))
{
if (!Item.GetBaseItem().Sitable && !Item.GetBaseItem().Walkable && !Item.GetBaseItem().Layable)
{
FurniCollisionMap[Tile.X][Tile.Y] = 0;
}
if (Item.GetBaseItem().Sitable || Item.GetBaseItem().Layable)
{
FurniCollisionMap[Tile.X][Tile.Y] = 2;
}
}
}
} | 9 |
public VariableStack mapStackToLocal(VariableStack stack) {
if (!stack.isEmpty())
throw new IllegalArgumentException("stack is not empty at RET");
return null;
} | 1 |
@Override
public void execute() throws BuildException {
PageUnit.init();
try {
if (theFile != null) {
PageUnit.processFile(theFile);
} else if (theDir != null) {
PageUnit.processFile(theDir);
} else if (theTest != null) {
if (thePath == null) {
PageUnit.processFile(new File(theTest));
} else {
// walk thePath, looking for test, first found, process
throw new BuildException("code not written yet: walk thePath, looking for test, first found, process");
}
} else {
throw new BuildException("Either file, or dir, or test (and optionally path) must be specified");
}
} catch (Exception e) {
throw new BuildException(e.toString());
}
if (PageUnit.isFailed()) {
throw new BuildException(PageUnit.getTestResults().toString());
}
} | 6 |
@Override
public boolean isEmailInDatabase(String email) {
String sql = "SELECT * FROM customer WHERE email='" + email + "';";
Connection con = null;
try {
con = getConnection();
PreparedStatement statement = con.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
return resultSet.next();
} catch (SQLException e) {
e.printStackTrace();
return true; // prompt user for password again
} finally {
if (con != null) closeConnection(con);
}
} | 2 |
public static int countNeighbours(boolean[][] world, int col, int row) {
int c = 0;
if (getCell(world, col - 1, row - 1) == true) {
c += 1;
}
if (getCell(world, col, row - 1) == true) {
c += 1;
}
if (getCell(world, col + 1, row - 1) == true) {
c += 1;
}
if (getCell(world, col - 1, row) == true) {
c += 1;
}
if (getCell(world, col + 1, row) == true) {
c += 1;
}
if (getCell(world, col - 1, row + 1) == true) {
c += 1;
}
if (getCell(world, col, row + 1) == true) {
c += 1;
}
if (getCell(world, col + 1, row + 1) == true) {
c += 1;
}
return c;
} | 8 |
public void setVariable(String var, Object val){
for(String p : localVars.keySet()){
if(p.equals(var)){
String type = localVars.get(p).getClass().getSimpleName();
if(!var.getClass().getSimpleName().equals(type)){
try{
if(type.toLowerCase().equals("float"))
localVars.put(p, (float) val);
if(type.toLowerCase().equals("integer"))
localVars.put(p,(int) val);
if(type.toLowerCase().equals("string"))
localVars.put(p,(String) val);
if(type.toLowerCase().equals("boolean"))
localVars.put(p, Boolean.parseBoolean(val.toString()));
} catch (Exception e){
System.out.println("Wrong type; "+type);
e.printStackTrace();
}
} else
localVars.put(p,val);
}
}
} | 8 |
public static Random getRandom() {
// construct the singleton random object if it does not yet exist
if(randomGenerator == null) {
if(Configuration.useSameSeedAsInPreviousRun) {
randomSeed = AppConfig.getAppConfig().seedFromLastRun;
} else {
if(Configuration.useFixedSeed){
randomSeed = Configuration.fixedSeed;
} else {
randomSeed = (new java.util.Random()).nextLong();
Configuration.fixedSeed = randomSeed;
}
}
randomGenerator = new Random(randomSeed); // use a random seed
}
return randomGenerator;
} | 3 |
public void done() {
int remain = remainingTransitions.size();
if (remain != 0) {
Transition t = (Transition) remainingTransitions.iterator().next();
drawer.addSelected(t.getFromState());
JOptionPane.showMessageDialog(view, remain + " transition"
+ (remain == 1 ? "" : "s") + " remain " + "to be placed.\n"
+ "One comes from the state highlighted.");
drawer.clearSelected();
return;
}
JOptionPane.showMessageDialog(view,
"The minimized automaton is fully built!\n"
+ "It will now be placed in a new window.");
FrameFactory.createFrame((FiniteStateAutomaton) minDfa.clone());
} | 2 |
@Override
public void undo() {
if(prevSpeed==CeiligFan.HIGH){
ceilingFan.high();
}else if(prevSpeed==CeiligFan.MEDIUM){
ceilingFan.medium();
}
else if(prevSpeed==CeiligFan.LOW){
ceilingFan.low();
}
else if(prevSpeed==CeiligFan.OFF){
ceilingFan.OFF();
}
} | 4 |
static public Class getWrapperClass (Class type) {
if (type == int.class)
return Integer.class;
else if (type == float.class)
return Float.class;
else if (type == boolean.class)
return Boolean.class;
else if (type == long.class)
return Long.class;
else if (type == byte.class)
return Byte.class;
else if (type == char.class)
return Character.class;
else if (type == short.class) //
return Short.class;
return Double.class;
} | 7 |
public static Orientation valueOf(boolean flipAroundHorizontal, Rotation rotation) {
Orientation result = null;
if (!flipAroundHorizontal) {
switch (rotation) {
case NOTHING: result = TOP_LEFT ; break;
case LEFT : result = LEFT_BOTTOM ; break;
case OVER : result = BOTTOM_RIGHT; break;
case RIGHT : result = RIGHT_TOP ; break;
}
} else {
switch (rotation) {
case NOTHING: result = BOTTOM_LEFT ; break;
case LEFT : result = RIGHT_BOTTOM; break;
case OVER : result = TOP_RIGHT ; break;
case RIGHT : result = LEFT_TOP ; break;
}
}
return result;
} | 9 |
public AchaMazeWindow() throws AchaMazeException {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(640, 480);
setTitle("AchaMaze");
MyPanel panel = new MyPanel();
add(panel);
setVisible(true);
say("Welcome.");
maze = MazeExamples.ExampleMaze1();
drawMaze = new DrawMaze(maze);
panel.repaint();
// Players
maze.addPlayer();
// From this position, both FollowLeftWall and Pledge work.
maze.getPlayer(maze.getNumberOfPlayers()-1).setPosition(0, 0);
maze.addPlayer();
// From that position, Pledge works but FollowLeftWall loops forever.
maze.getPlayer(maze.getNumberOfPlayers()-1).setPosition(3, 3);
panel.repaint();
// Load solving algorithms
int n = maze.getNumberOfPlayers();
for (int playerId = 0; playerId < n; playerId++) {
Player player = maze.getPlayer(playerId);
MazeSolvingAlgorithm algo = new FollowLeftWallAlgo(player.getStateForMazeAlgo());
player.setMazeSolvingAlgorithm(algo);
// Add player at same place but with other algorithm
maze.addPlayer();
Player player2 = maze.getPlayer(maze.getNumberOfPlayers()-1);
player2.setPosition(player.getPositionLine(), player.getPositionColumn());
MazeSolvingAlgorithm algo2 = new PledgeAlgorithm(player2.getStateForMazeAlgo());
player2.setMazeSolvingAlgorithm(algo2);
}
int numberOfPlayersInMaze = maze.getNumberOfPlayers();
while (numberOfPlayersInMaze > 0) {
// Wait so the user can see the changes.
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new AchaMazeException("InterruptedException thrown: " + e);
}
for (int playerId = 0; playerId < maze.getNumberOfPlayers(); playerId++) {
Player player = maze.getPlayer(playerId);
if (!player.isInMaze()) {
// Player out of maze, so skip.
continue;
}
// Player is in maze.
player.getMazeSolvingAlgorithm().move();
// Is player still in maze?
if (!player.isInMaze()) {
numberOfPlayersInMaze--;
say("Player "
+ player
+ " with id "
+ player.getPlayerId()
+ " exited from the maze.");
}
// Display the new game state.
panel.repaint();
}
}
say("All players have exited maze.");
} | 6 |
private boolean runChecks(){
// Check 1: Is it time to go home?
if(office.getTime() >= dayEndTime){
// End the thread
return false;
}
// Lunch time?
if(office.getTime() >= lunchTime && !hadLunch){
try {
long startCheck = System.currentTimeMillis();
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " goes to lunch");
sleep(lunchDuration*10);
long endCheck = System.currentTimeMillis();
timeSpentAtLunch += (endCheck - startCheck)/10;
} catch (InterruptedException e) {
e.printStackTrace();
}
hadLunch = true;
synchronized(leadQLock){
leadQLock.notifyAll();
}
}
// Is it time for the 4 oclock meeting?
if(office.getTime() >= 1600 && !attendedEndOfDayMeeting){
long startCheck = System.currentTimeMillis();
synchronized (leadQLock){
leadQLock.notifyAll();
}
office.waitForEndOfDayMeeting();
try {
System.out.println(office.getStringTime() + " Developer " + (int)(teamNumber+1) + "" + (int)(empNumber+1) + " attends end of day meeting");
sleep(150);
long endCheck = System.currentTimeMillis();
timeSpentInMeetings += (endCheck - startCheck)/10;
} catch (InterruptedException e) {
e.printStackTrace();
}
attendedEndOfDayMeeting = true;
}
return true;
} | 7 |
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Change ch = changes.get(rowIndex);
switch (columnIndex) {
case 0:
return changeSelected.get(rowIndex);
case 1:
return ch.getType();
case 2:
return ch.getDescription();
case 3:
return ch.getTarget();
case 4:
return ch.getNewValue();
case 5:
return ch.getOldValue();
}
return null;
} | 6 |
public void restore() {
logger.debug("enter restore method");
configService.initRestoreConfig();
List<String> restoreIndices = configService.getRestoreIndices();
if(restoreIndices == null || restoreIndices.size()==0){
restoreIndices = findAllIndexesFromDir();
}
if(restoreIndices!=null && restoreIndices.size()>0){
logger.debug("search index list:[{}]",restoreIndices);
if(configService.disableMultiThread()){
for(String indexName : restoreIndices){
restoreByIndexName(indexName);
}
}
else {
//采用队列多线程模式
int cpuCoreNumber = Runtime.getRuntime().availableProcessors();
logger.debug("cpu core(threadpool number):{}",cpuCoreNumber);
exec = Executors.newFixedThreadPool(cpuCoreNumber);
int indexCount=0;
for(String indexName : restoreIndices){
final String iName = indexName;
exec.submit(new Callable<Object>(){
public Object call() throws Exception {
restoreByIndexName(iName);
return null;
}
});
indexCount++;
}
logger.info("{} index will be restore",indexCount);
try {
exec.shutdown();
exec.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS);
} catch (Exception e) {
e.printStackTrace();
}
}
}
else {
logger.info("find no indices to restore");
}
configService.getRestoreClient().close();
logger.debug("exit restore method");
} | 8 |
@Override
public <T extends Comparable<? super T>> int search(T[] array, T key) {
if (array == null)
throw new NullPointerException("argument array is null");
if (key == null)
throw new NullPointerException("argument key is null");
// Make sure every element is not null.
for (T elem: array) {
if (elem == null)
throw new NullPointerException("All elements must not be null");
}
// Make sure the array is sorted.
if (!Util.isSorted(array))
throw new IllegalArgumentException(getClass().getSimpleName() +
" argument array is not sorted");
int lo = 0;
int hi = array.length - 1;
while (lo <= hi) {
// Key is in a[lo..hi] or not present.
int mid = lo + (hi - lo) / 2;
if (key.compareTo(array[mid]) < 0)
hi = mid - 2;
else if (key.compareTo(array[mid]) > 0)
// NOTE adds lo = mid + 1; instead of lo = mid + 2.
lo = mid + 1;
else
return mid;
}
return -1;
} | 9 |
public static synchronized Date stringToDate(String dateString) throws ParseException {
if (dateString.length() == 4) {
return YEAR_FORMAT.parse(dateString);
} else if (dateString.length() == 6) {
return MONTH_FORMAT.parse(dateString);
} else if (dateString.length() == 8) {
return DAY_FORMAT.parse(dateString);
} else if (dateString.length() == 10) {
return HOUR_FORMAT.parse(dateString);
} else if (dateString.length() == 12) {
return MINUTE_FORMAT.parse(dateString);
} else if (dateString.length() == 14) {
return SECOND_FORMAT.parse(dateString);
} else if (dateString.length() == 17) {
return MILLISECOND_FORMAT.parse(dateString);
}
throw new ParseException("Input is not valid date string: " + dateString, 0);
} | 7 |
public static String getRequestChatName(String inString)
throws JDOMException, IOException, TagFormatException {
String result = "";
SAXBuilder mSAXBuilder = new SAXBuilder();
Document mDocument = mSAXBuilder.build(new StringReader(inString));
Element rootNode = mDocument.getRootElement();
String protType = rootNode.getName();
if (protType.equals(Tags.CHAT_REQ)) {
result = rootNode.getChildText(Tags.PEER_NAME);
} else {
TagFormatException tfe = new TagFormatException(
"It's not a request chat protocol");
throw tfe;
}
System.out.print(result);
return result;
} | 1 |
public Task getTaskByIdName(String id, String name) throws FileNotFoundException, JAXBException{
//Check this line
//FileInputStream stream = new FileInputStream("/WEB-INF/task-manager-xml.xml");
FileInputStream stream = new FileInputStream("C:/Users/Efrin Gonzalez/Documents/task-manager-xml.xml");
// create an instance context class, to serialize/deserialize.
JAXBContext jaxbContext = JAXBContext.newInstance(Cal.class);
// Deserialize university xml into java objects.
Cal cal = (Cal) jaxbContext.createUnmarshaller().unmarshal(stream);
//With the iterator we can full fill the list that will be sent in response
ListIterator<Task> listIterator = cal.tasks.listIterator();
while (listIterator.hasNext()) {
Task task = listIterator.next();
if(task.id.equals(id)&& task.name.equals(name)){
return task;
}
}
return null;
} | 3 |
public boolean recordParamNames(CodeAttribute ca, int numOfLocalVars)
throws CompileError
{
LocalVariableAttribute va
= (LocalVariableAttribute)
ca.getAttribute(LocalVariableAttribute.tag);
if (va == null)
return false;
int n = va.tableLength();
for (int i = 0; i < n; ++i) {
int index = va.index(i);
if (index < numOfLocalVars)
gen.recordVariable(va.descriptor(i), va.variableName(i),
index, stable);
}
return true;
} | 3 |
public int extraerUltimoRegistro(String nombretabla, String[] campos)
{
int resultado = 0;
try {
this.bd.open();
this.bd.beginTransaction(SqlJetTransactionMode.READ_ONLY);
this.table = this.bd.getTable(nombretabla);
// Con esta función buscamos en la tabla, según su índice, el valor
this.cursor = table.order(table.getPrimaryKeyIndexName());
// devuelve el numero de campos en el registro actual
// this.cursor.getFieldsCount();
if (!cursor.eof())
{
do
{
// en esta variable al final te guardará la ultima id
resultado=(int)cursor.getRowId();
}
while(cursor.next());
}
this.bd.commit();
this.bd.close();
}
catch (SqlJetException ex)
{
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
return resultado;
} | 3 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Picking))
return false;
Picking other = (Picking) obj;
if (id.equals(other.id))
return false;
return true;
} | 4 |
public Point findPointIntersection (Point P1, Point P2, Point P3, Point P4){
a1=P1.getY()-P2.getY();
a2=P3.getY()-P4.getY();
b1=P2.getX()-P1.getX();
b2=P4.getX()-P3.getX();
c1=P1.getX()*P2.getY()-P2.getX()*P1.getY();
c2=P3.getX()*P4.getY()-P4.getX()*P3.getY();
xDen=(b2*a1-a2*b1);
if (xDen==0){
//проверка на коллинеарность
if (c1==c2) System.out.println("Линии совпадают");
//if (c1!=c2) System.out.println("Линии паралельные");
}
else {
y=(a2*c1-c2*a1)/xDen;
x=-(c1*b2-c2*b1)/xDen;
rezult= (x<=Math.max(P1.getX(), P2.getX()) && x>=Math.min(P1.getX(), P2.getX())
&& x<=Math.max(P3.getX(), P4.getX()) && x>=Math.min(P3.getX(), P4.getX())
&& y<=Math.max(P1.getY(), P2.getY()) && y>=Math.min(P1.getY(), P2.getY())
&& y<=Math.max(P3.getY(), P4.getY()) && y>=Math.min(P3.getY(), P4.getY()));
Intercec=new Point(x, y, rezult);
}
return Intercec;
} | 9 |
private String shrtTip() {
String tt = shorttip();
if (tt != null) {
tt = RichText.Parser.quote(tt);
if (meter > 0) {
tt = tt + " (" + meter + "%)";
}
if (FEP != null) {
tt += FEP;
}
if (curio_stat != null && qmult > 0) {
if (UI.instance.wnd_char != null)
tt += "\nLP: $col[205,205,0]{" + Math.round(curio_stat.baseLP * qmult * UI.instance.wnd_char.getExpMode()) + "}";
if (meter >= 0) {
double time = (double) meter / 100;
tt += " in " + min2hours(curio_stat.studyTime - (int) (curio_stat.studyTime * time));
}
tt += " Att: " + curio_stat.attention;
}
}
return tt;
} | 7 |
public void setUpdateExisting(boolean updateExisting) {
this.updateExisting = updateExisting;
} | 0 |
public long playGame(final Board start, List<Integer> nextPiece)
{
System.out.println(start);
System.out.println("avail moves: " + nextPiece.size());
Board curBoard = new Board(start);
int moves = 0;
long startTime = System.nanoTime();
List<Board.Direction> moveList;
do
{
moveList = this.nextMoveMultiple(curBoard, nextPiece);
if (moveList != null)
{
for (Board.Direction d : moveList)
{
movePrint(d);
curBoard = curBoard.move(d, nextPiece.get(0));
nextPiece.remove(0);
moves++;
}
}
}while(moveList != null && !nextPiece.isEmpty());
long duration = System.nanoTime() - startTime;
System.err.print(this+"\t"+curBoard.scoreOfBoard()+"\t");
System.err.format("%.3f\n", 1.0e9*moves/duration);
/*
System.out.println();
System.out.print(curBoard);
System.out.println("Searcher: " + this);
System.out.println("Score: " + curBoard.scoreOfBoard());
System.out.println("Played: " + moves);
System.out.format("TotalT: %.3f\n", 1.0e-9*duration);
System.out.format("Mov/S: %.3f\n", 1.0e9*moves/duration);
System.out.println("---------------");
*/
return curBoard.scoreOfBoard();
} | 4 |
MethodConstructorStringConverter(Class<T> cls, Method toString, Constructor<T> fromString) {
super(cls, toString);
if (cls.isInterface() || Modifier.isAbstract(cls.getModifiers()) || cls.isLocalClass() || cls.isMemberClass()) {
throw new IllegalArgumentException("FromString constructor must be on an instantiable class: " + fromString);
}
if (fromString.getDeclaringClass() != cls) {
throw new IllegalStateException("FromString constructor must be defined on specified class: " + fromString);
}
this.fromString = fromString;
} | 5 |
public void parseInput(String state)
{
char type = state.charAt(0);
if (type != ':') {
return;
}
type = state.charAt(1);
String value = state.substring(3);
if (type == 'l') {
this.light = Integer.decode(value);
}
if (type == 'r') {
this.relayA = Integer.decode(value) == 1;
}
if (type == 's') {
this.relayB = Integer.decode(value) == 1;
}
if (type == 't') {
this.temperature = Float.valueOf(value);
}
} | 5 |
public static String stringOfCollection(Collection<?> collection, String sep, String prefix, String suffix) {
StringBuilder res = new StringBuilder(prefix == null ? "" : prefix);
if (collection != null) {
boolean first_element = true;
for (Object elem : collection) {
if (elem != null) {
res.append((first_element ? "" : sep));
res.append(elem.toString());
first_element = false;
}
}
}
return res.append(suffix == null ? "" : suffix).toString();
} | 7 |
private String stackString() {
Object[] o = STACK.toArray();
StringBuffer sb = new StringBuffer();
for (int i = o.length - 1; i >= 0; i--)
sb.append(o[i]);
return sb.toString();
} | 1 |
public static Map<String, String> simpleUPnPcommand(String url,
String service, String action, Map<String, String> args)
throws IOException, SAXException {
String soapAction = "\"" + service + "#" + action + "\"";
StringBuilder soapBody = new StringBuilder();
soapBody.append("<?xml version=\"1.0\"?>\r\n" +
"<SOAP-ENV:Envelope " +
"xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
"<SOAP-ENV:Body>" +
"<m:" + action + " xmlns:m=\"" + service + "\">");
if (args != null && args.size() > 0) {
Set<Map.Entry<String, String>> entrySet = args.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
soapBody.append("<" + entry.getKey() + ">" + entry.getValue() +
"</" + entry.getKey() + ">");
}
}
soapBody.append("</m:" + action + ">");
soapBody.append("</SOAP-ENV:Body></SOAP-ENV:Envelope>");
URL postUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(HTTP_RECEIVE_TIMEOUT);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/xml");
conn.setRequestProperty("SOAPAction", soapAction);
conn.setRequestProperty("Connection", "Close");
byte[] soapBodyBytes = soapBody.toString().getBytes();
conn.setRequestProperty("Content-Length",
String.valueOf(soapBodyBytes.length));
conn.getOutputStream().write(soapBodyBytes);
Map<String, String> nameValue = new HashMap<String, String>();
XMLReader parser = XMLReaderFactory.createXMLReader();
parser.setContentHandler(new NameValueHandler(nameValue));
if (conn.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
try {
// attempt to parse the error message
parser.parse(new InputSource(conn.getErrorStream()));
} catch (SAXException e) {
// ignore the exception
// FIXME We probably need to find a better way to return
// significant information when we reach this point
}
conn.disconnect();
return nameValue;
} else {
parser.parse(new InputSource(conn.getInputStream()));
conn.disconnect();
return nameValue;
}
} | 5 |
public void save() throws SQLException
{
if (groopNumber == -1)
groopNumber = GetGroops.build().addGroop(this);
else if (updated)
GetGroops.build().save(this);
} | 2 |
public SqlErrorFrame() {
initComponents();
} | 0 |
public void draw(Graphics2D g) {
g.setColor(Color.WHITE);
if(onFire)
g.drawImage(fireImage, xPos, yPos, null);
else if(SimCityGui.GRADINGVIEW) {
g.drawString("W"+mNum, xPos+10, yPos-5);
}
else {
g.drawImage(image, xPos, yPos, null);
}
switch(state) {
case deliveringFood: {
g.drawString(food, xPos-2, yPos-5);
break;
}
case deliveringCheck: {
if(!SimCityGui.GRADINGVIEW) {
g.drawImage(check, xPos-14, yPos+10, null);
}
break;
}
case asking: {
if(!SimCityGui.GRADINGVIEW) {
g.drawImage(askingBubble, xPos-14, yPos+10, null);
}
break;
}
default:
break;
}
} | 7 |
public boolean checkBook() {
boolean hasBook = false;
ArrayList<Card> list = getList();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < list.size(); i++) {
int numb = list.get(i).getCardNum();
if (!map.containsKey(numb)) {
map.put(numb, 1);
} else {
int qty = map.get(numb) + 1;
map.put(numb, qty);
}
}
if (map.containsValue(4)) {
hasBook = true;
}
return hasBook;
} | 3 |
@Override
public void run() {
// loop to receive broadcasted UDP packets
active = true;
DatagramPacket packet = new DatagramPacket(
new byte[NetInterface.UDP_PACKET_SIZE],
NetInterface.UDP_PACKET_SIZE);
while (active) {
try {
// blocks thread until reception of a packet
if (verbose) {
System.out
.println(("Net: broadcast receiver blocked on receive"));
}
socket.receive(packet);
if (verbose) {
System.out.println("Net: broadcast receiver received "
+ packet.getLength() + " bytes");
}
ByteArrayInputStream bais = new ByteArrayInputStream(
packet.getData());
ObjectInputStream ois = new ObjectInputStream(bais);
Address senderAddress = (Address) ois.readObject();
Serializable obj = (Serializable) ois.readObject();
net.notifyBroadcastReception(senderAddress, obj);
} catch (SocketException e) {
// socket closed by call to close()
active = false;
if (verbose) {
System.out
.println(("Net: closing broadcast receiver socket... done"));
}
} catch (IOException e) {
System.out
.println("Net: broadcast receiver closing after unexpected IO exception");
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} | 7 |
public void insert(LinkedListRange node, LinkedListRange root) {
if (root == null) {
root = node;
return;
}
while (root.getNext() != null)
root = root.getNext();
root.setNext(node);
} | 2 |
private IShelf setPosition(IItem item) throws TaskFailureException {
for (int i = 1; i < 4; i++) {
try {
Aisle aisle = (Aisle) manager.get("A" + i);
List<Rack> racks = aisle.getRacks();
for (int j = 0; j < racks.size(); j++) {
Rack rack = racks.get(j);
List<IShelf> lst = rack.getShelfs();
for (int k = 0; k < lst.size(); k++) {
IShelf proxyS = lst.get(k);
if (proxyS.getFreeSpace() >= item.getAmount()) {
int rackID = j;
System.out.println("RACK : - " + rack.getCode() + " = " + rackID);
int aisleID =i;
item.setPosition(new Position(proxyS.getID(), rackID, aisleID));
proxyS.prepare(item); //Prepare !!
System.out.println("Proxy ID - setPos :" + proxyS.getID());
return proxyS;
}
}
}
} catch (Exception ex) {
Logger.getLogger(Storage.class.getName()).log(Level.SEVERE, null, ex);
}
}
throw new TaskFailureException();
} | 5 |
@Override
public String[] getTableRenameStatements(String oldTableName, Class<?> oldClass, String newTableName, Class<?> newClass)
{
StringBuilder sb = new StringBuilder("RENAME TABLE ");
sb.append(oldTableName);
sb.append(" TO ");
sb.append(newTableName);
return new String[] { sb.toString() };
} | 2 |
public void doMission() {
final Unit unit = getUnit();
String reason = invalidReason();
if (reason != null) {
logger.finest(tag + " broken(" + reason + "): " + this);
return;
}
// Make random moves in a reasonably consistent direction,
// checking for a target along the way.
final AIMain aiMain = getAIMain();
final AIUnit aiUnit = getAIUnit();
int check = 0, checkTurns = Utils.randomInt(logger, "Hostile",
getAIRandom(), 4);
Direction d = Direction.getRandomDirection(tag, getAIRandom());
boolean moved = false;
Mission m;
while (unit.getMovesLeft() > 0) {
// Every checkTurns, look for a target of opportunity.
if (check == 0) {
Location loc = UnitSeekAndDestroyMission.findTarget(aiUnit, 1);
if (loc != null) {
m = new UnitSeekAndDestroyMission(aiMain, aiUnit, loc);
aiUnit.setMission(m);
m.doMission();
return;
}
check = checkTurns;
} else check--;
if ((d = moveRandomly(tag, d)) == null) break;
moved = true;
}
if (moved) {
logger.finest(tag + " moved to " + unit.getLocation()
+ ": " + this);
}
} | 6 |
@SuppressWarnings("fallthrough")
private void beforeValue(boolean root) throws IOException {
switch (peek()) {
case NONEMPTY_DOCUMENT:
if (!lenient) {
throw new IllegalStateException(
"JSON must have only one top-level value.");
}
// fall-through
case EMPTY_DOCUMENT: // first in document
if (!lenient && !root) {
throw new IllegalStateException(
"JSON must start with an array or an object.");
}
replaceTop(NONEMPTY_DOCUMENT);
break;
case EMPTY_ARRAY: // first in array
replaceTop(NONEMPTY_ARRAY);
newline();
break;
case NONEMPTY_ARRAY: // another in array
out.append(',');
newline();
break;
case DANGLING_NAME: // value for name
out.append(separator);
replaceTop(NONEMPTY_OBJECT);
break;
default:
throw new IllegalStateException("Nesting problem.");
}
} | 8 |
public void checkPawn() {
if (color == 'W') {
for (int i = 0; i < 8; i++) {
if (aiarr[i][0].toString().charAt(1) == 'P') {
aiarr[i][0] = new Queen(true);
}
}
}
if (color == 'B') {
for (int i = 0; i < 8; i++) {
if (aiarr[i][7].toString().charAt(1) == 'P') {
aiarr[i][7] = new Queen(false);
}
}
}
} | 6 |
public static byte[] decodeFromFile( String filename )
throws java.io.IOException {
byte[] decodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = null;
int length = 0;
int numBytes = 0;
// Check for size of file
if( file.length() > Integer.MAX_VALUE )
{
throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." );
} // end if: file too big for int index
buffer = new byte[ (int)file.length() ];
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.DECODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
length += numBytes;
} // end while
// Save in a variable to return
decodedData = new byte[ length ];
System.arraycopy( buffer, 0, decodedData, 0, length );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try{ bis.close(); } catch( Exception e) {}
} // end finally
return decodedData;
} // end decodeFromFile | 4 |
private void searchByLivreEmprunt(String toSearch) throws Exception {
try {
StringTokenizer st = new StringTokenizer(toSearch, " ");
if (st.countTokens() != 0) {
List<String> list = new ArrayList<>();
for (int i = 0; i < st.countTokens() + 1; i++) {
list.add(st.nextToken());
}
List<Livre> byMotsClefs = livreMetierService.getByMotsClefs(list);
List<Emprunt> byLivre = new ArrayList<>();
for (int i = 0; i < byMotsClefs.size(); i++) {
Emprunt byLivre1 = empruntMetierService.getByLivre(byMotsClefs.get(i));
if (byLivre1 != null) {
byLivre.add(byLivre1);
}
}
if (byLivre.size() > 1) {
jLabelNbFoundEmprunt.setText(byLivre.size() + " emprunts ont été trouvés");
this.fireJTableEmprunt(byLivre, null);
} else {
if (byLivre.size() == 1) {
jLabelNbFoundEmprunt.setText(byLivre.size() + " emprunt a été trouvé");
this.fireJTableEmprunt(byLivre, null);
} else {
jLabelNbFoundEmprunt.setText("Aucun emprunt n'a été trouvé");
this.fireJTableEmprunt(null, null);
}
}
} else {
jLabelNbFoundEmprunt.setText("Aucun emprunt n'a été cherché");
this.fireJTableEmprunt(null, null);
}
} catch (Exception ex) {
Logger.getLogger(TableauDeBord.class.getName()).log(Level.SEVERE, null, ex);
jLabelNbFoundEmprunt.setText("<html><body><font color='red'>" + ex.getMessage() + "</font></body></html>");
}
} | 7 |
public synchronized void run() {
try {
while (true) {
Thread.sleep(time - 14);
secound += 1;
if (secound >= 60) { minute += 1; secound = 0; }
if (minute >= 60) { hour += 1; minute = 0; }
if (hour >= 1) { hour = 0; minute = 0; secound = 0; }
}
} catch(Exception e) {
e.printStackTrace();
}
} | 5 |
public File wavCombiner(File synthFile, File inputFile){
Synthesizer synth = JSyn.createSynthesizer();
LineOut lineOut;
synth.add(lineOut = new LineOut());
synth.start();
FloatSample sample;
FloatSample sample2;
try {
// AddUnit mixer = new AddUnit();
sample = SampleLoader.loadFloatSample(synthFile);
sample2 = SampleLoader.loadFloatSample(inputFile);
VariableRateStereoReader samplePlayer = new VariableRateStereoReader();
VariableRateMonoReader samplePlayer2 = new VariableRateMonoReader();
synth.add(samplePlayer);
synth.add(samplePlayer2);
System.out.println(sample.getFrameRate());
System.out.println(sample2.getFrameRate());
samplePlayer.rate.set(sample.getFrameRate());
samplePlayer2.rate.set(sample2.getFrameRate());
// samplePlayer.output.connect(0, mixer.inputA, 0);
// samplePlayer.output.connect(1, mixer.inputB, 1);
samplePlayer2.dataQueue.queue(sample2);
samplePlayer.dataQueue.queue(sample);
samplePlayer.output.connect(0,lineOut.input, 0);
samplePlayer2.output.connect(0,lineOut.input, 1);
WaveRecorder recorder;
String fileName = null;
//removing the wav suffix before renaming the file
for(int i = 0; i < inputFile.getName().length(); i++){
if(inputFile.getName().charAt(i)=='.'){
fileName = inputFile.getName().substring(0, i);
}
}
synthFile = new File(AudioData.AUDIO_FOLDER + fileName + "C.wav");
recorder = new WaveRecorder(synth, synthFile);
samplePlayer.output.connect(0, recorder.getInput(), 0);
samplePlayer.output.connect(0, recorder.getInput(), 1);
//starting the input and accompaniment samples and the synth and recorder
synth.startUnit(lineOut);
samplePlayer.start();
samplePlayer2.start();
recorder.start();
do
{
synth.sleepFor(1.0);
} while(samplePlayer.dataQueue.hasMore());
samplePlayer.stop();
samplePlayer2.stop();
recorder.stop();
synth.stop();
} catch (Exception ex){
ex.printStackTrace();
}
return combinedFile;
} | 4 |
void paintImage(PaintEvent event) {
GC gc = event.gc;
Image paintImage = image;
/* If the user wants to see the transparent pixel in its actual color,
* then temporarily turn off transparency.
*/
int transparentPixel = imageData.transparentPixel;
if (transparentPixel != -1 && !transparent) {
imageData.transparentPixel = -1;
paintImage = new Image(display, imageData);
}
/* Scale the image when drawing, using the user's selected scaling factor. */
int w = Math.round(imageData.width * xscale);
int h = Math.round(imageData.height * yscale);
/* If any of the background is visible, fill it with the background color. */
Rectangle bounds = imageCanvas.getBounds();
if (imageData.getTransparencyType() != SWT.TRANSPARENCY_NONE) {
/* If there is any transparency at all, fill the whole background. */
gc.fillRectangle(0, 0, bounds.width, bounds.height);
} else {
/* Otherwise, just fill in the backwards L. */
if (ix + w < bounds.width) gc.fillRectangle(ix + w, 0, bounds.width - (ix + w), bounds.height);
if (iy + h < bounds.height) gc.fillRectangle(0, iy + h, ix + w, bounds.height - (iy + h));
}
/* Draw the image */
gc.drawImage(
paintImage,
0,
0,
imageData.width,
imageData.height,
ix + imageData.x,
iy + imageData.y,
w,
h);
/* If there is a mask and the user wants to see it, draw it. */
if (showMask && (imageData.getTransparencyType() != SWT.TRANSPARENCY_NONE)) {
ImageData maskImageData = imageData.getTransparencyMask();
Image maskImage = new Image(display, maskImageData);
gc.drawImage(
maskImage,
0,
0,
imageData.width,
imageData.height,
w + 10 + ix + imageData.x,
iy + imageData.y,
w,
h);
maskImage.dispose();
}
/* If transparency was temporarily disabled, restore it. */
if (transparentPixel != -1 && !transparent) {
imageData.transparentPixel = transparentPixel;
paintImage.dispose();
}
} | 9 |
public Transporte recebeuPSH(int n_seq, InetAddress adress){
Transporte t1=new Transporte(initTransportePSH);
this.Recebidos.lock();
ArrayList<DatagramPacket> lista = (ArrayList<DatagramPacket>) this.Recebidos.lista.clone();
this.Recebidos.unlock();
for(DatagramPacket p : lista){
if(p.getAddress().equals(adress)){
try { t1 = t1.receberDeDatagramPacket(p); } catch (IOException ex) {}
//se enviarmos pacote com seq=0, o ACK recebido vai ter seqAck=1
if( Transporte.byteToInt(t1.getSeq(), 2) == n_seq ){
this.Recebidos.lock();
this.Recebidos.lista.remove(p);
this.Recebidos.unlock();
return t1;
}
}
}
return null;
} | 4 |
private static Icon getIconForValue ( BencodeTreeModel model, BencodeTreeNode node ) {
if ( node.getParent() == null ) {
return ICON_ROOT;
}
Value<?> value = node.getValue();
if ( value instanceof IntegerValue ) {
return ICON_INTEGER;
} else if ( value instanceof StringValue ) {
if ( ( (StringValue) value ).isValidUtf8() ) {
return ICON_STRING;
} else {
return ICON_BINARY;
}
} else if ( value instanceof ListValue ) {
return ICON_LIST;
} else if ( value instanceof DictionaryValue ) {
return ICON_DICTIONARY;
}
return null;
} | 7 |
private void fillMaxTotalScores() {
int numEntries = entryList.size();
Vector cellList = new Vector(16);
rootPane.getAttributeCells(cellList);
double[] accumulatedRatios = new double[numEntries * noOfUsers];
int j = 0;
for (int i = 0; i < numEntries; i++) {//for each alternative
int users=0;
double avgAlternativeScore = 0;
String entryName = entryList.get(i).name;
for(IndividualEntryMap e : chart.listOfEntryMaps.values()){//for each user
for (Iterator it = cellList.iterator(); it.hasNext();) {//for each attribute
AttributeCell cell = (AttributeCell) it.next();
double weight = e.getEntryWeight(cell.getName(), entryName);
double or = cell.getHeightFromAttributeMap(e.username,cell.getName());///chart.heightScalingConstant;
accumulatedRatios[j] += or * weight;
}
String srcKey = e.username;
double srcValue = accumulatedRatios[j];
// maxTotalScores2.put(srcKey, srcValue);
if(maxTotalScores.containsKey(srcKey)){
double destValue = maxTotalScores.get(srcKey);
if(destValue <= srcValue){
maxTotalScores.remove(srcKey);
topAltforUsers.remove(srcKey);
maxTotalScores.put(srcKey, srcValue);
topAltforUsers.put(srcKey, entryName);
}
}else{
maxTotalScores.put(srcKey, srcValue);
topAltforUsers.put(srcKey, entryName);
}
avgAlternativeScore += accumulatedRatios[j];
j++;
users++;
}
averageTotalScores.put(entryName, avgAlternativeScore/users);
}
for(IndividualAttributeMaps a : chart.listOfAttributeMaps){
for(Map.Entry<String, String> m : topAltforUsers.entrySet()){
if(a.userName.equals(m.getKey())){
a.setTopAlternative(m.getValue());
}
}
// System.out.println(a.userName+" "+a.topAlternative);
}
// System.out.println(maxTotalScores2);
// System.out.println(averageTotalScores);
// System.out.println(topAltforUsers);
} | 8 |
public static void main(String[] args) {
// Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
//
// @Override
// public void uncaughtException(Thread t, Throwable e) {
// System.out.println("e: " + e.getMessage());
// }
//
// });
Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("e: " + e.getMessage() +", t: " + t.getName());
}
});
fooMethod();
} | 0 |
private double noise2D(double xin, double yin) {
double n0, n1, n2; // Noise contributions from the three corners
// Skew the input space to determine which simplex cell we're in
double s = (xin+yin)*F2; // Hairy factor for 2D
int i = fastfloor(xin+s);
int j = fastfloor(yin+s);
double t = (i+j)*G2;
double X0 = i-t; // Unskew the cell origin back to (x,y) space
double Y0 = j-t;
double x0 = xin-X0; // The x,y distances from the cell origin
double y0 = yin-Y0;
// For the 2D case, the simplex shape is an equilateral triangle.
// Determine which simplex we are in.
int i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords
if(x0>y0) {i1=1; j1=0;} // lower triangle, XY order: (0,0)->(1,0)->(1,1)
else {i1=0; j1=1;} // upper triangle, YX order: (0,0)->(0,1)->(1,1)
// A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
// a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
// c = (3-sqrt(3))/6
double x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords
double y1 = y0 - j1 + G2;
double x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords
double y2 = y0 - 1.0 + 2.0 * G2;
// Work out the hashed gradient indices of the three simplex corners
int ii = i & 255;
int jj = j & 255;
int gi0 = permMod12[ii+perm[jj]];
int gi1 = permMod12[ii+i1+perm[jj+j1]];
int gi2 = permMod12[ii+1+perm[jj+1]];
// Calculate the contribution from the three corners
double t0 = 0.5 - x0*x0-y0*y0;
if(t0<0) n0 = 0.0;
else {
t0 *= t0;
n0 = t0 * t0 * dot(grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient
}
double t1 = 0.5 - x1*x1-y1*y1;
if(t1<0) n1 = 0.0;
else {
t1 *= t1;
n1 = t1 * t1 * dot(grad3[gi1], x1, y1);
}
double t2 = 0.5 - x2*x2-y2*y2;
if(t2<0) n2 = 0.0;
else {
t2 *= t2;
n2 = t2 * t2 * dot(grad3[gi2], x2, y2);
}
// Add contributions from each corner to get the final noise value.
// The result is scaled to return values in the interval [-1,1].
return 70.0 * (n0 + n1 + n2);
} | 4 |
public Ants(int loadTime, int turnTime, int rows, int cols, int turns, int viewRadius2,
int attackRadius2, int spawnRadius2) {
this.loadTime = loadTime;
this.turnTime = turnTime;
this.rows = rows;
this.cols = cols;
this.turns = turns;
this.viewRadius2 = viewRadius2;
this.attackRadius2 = attackRadius2;
this.spawnRadius2 = spawnRadius2;
map = new Ilk[rows][cols];
for (Ilk[] row : map) {
Arrays.fill(row, Ilk.LAND);
}
visible = new boolean[rows][cols];
for (boolean[] row : visible) {
Arrays.fill(row, false);
}
// calc vision offsets
visionOffsets = new HashSet<Tile>();
int mx = (int)Math.sqrt(viewRadius2);
for (int row = -mx; row <= mx; ++row) {
for (int col = -mx; col <= mx; ++col) {
int d = row * row + col * col;
if (d <= viewRadius2) {
visionOffsets.add(new Tile(row, col));
}
}
}
} | 5 |
public static Set getUselessStates(Automaton a) {
if (a.getInitialState() == null) {
throw new IllegalArgumentException(
"Automata does not have an initial state!");
}
Set finalized = findFinal(a);
Set initialized = findInitial(a);
Set useless = new HashSet(Arrays.asList(a.getStates()));
finalized.retainAll(initialized);
useless.removeAll(finalized);
return useless;
} | 1 |
public MenuPanel(){
players = new ArrayList<Player>();
nameLabel = new JLabel("Name: ");
nameField = new JTextField("",20);
addButton = new JButton("Add Player");
startButton = new JButton("Start Game");
nameLabel.setLabelFor(nameField);
updateAddButton();
updateStartButton();
nameField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent arg0) {
update();
}
@Override
public void insertUpdate(DocumentEvent arg0) {
update();
}
@Override
public void changedUpdate(DocumentEvent arg0) {
update();
}
private void update(){
updateAddButton();
updateStartButton();
}
});
addButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
String name = nameField.getText();
if(name == null || name.trim().length()==0
|| players.size() >= 4){
return;
}
players.add(new StandardPlayer(name.trim()));
nameField.setText("");
updateAddButton();
updateStartButton();
}
});
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
startGame();
}
});
add(nameLabel);
add(nameField);
add(addButton);
add(startButton);
} | 3 |
private boolean calulateHueSaturation(ij.process.ImageProcessor ip) {
boolean huesaturation = false;
int w = ip.getWidth();
int h = ip.getHeight();
int [] h_hist = new int [360];
for (int i=0; i<360; i++) {
h_hist[i] = 0;
}
//set image as current window
ImagePlus hs_imp;
hs_imp = WindowManager.getCurrentImage();
for (int x=0; x<w; x++) {
for (int y=0; y<h; y++) {
int [] piksels = hs_imp.getPixel(x,y);
double [] hsv_piksels = RGBtoHSV(piksels[0],piksels[1],piksels[2]);
//if value null set 0
int h_piksel = (int) hsv_piksels[0];
if (h_piksel <0) {
h_piksel =0;
}
h_hist[h_piksel] += 1;
}
}
//get max value for histogram
int h_hist_max =0;
for (int i=0; i<360; i++) {
if (h_hist_max <h_hist[i]) {
h_hist_max = h_hist[i];
}
}
//calc 5 most highest or lowest frequencies
int sum_first = 0;
int sum_last = 0;
for (int i=0; i<5; i++) {
sum_first += h_hist[i];
sum_last += h_hist[359-i];
}
//decide what to do
int perc_of_max = h_hist_max/7;
if ((sum_first <perc_of_max) ||(sum_last <perc_of_max)) {
huesaturation = true;
}
Window_Closer Wind_Clow = new Window_Closer();
Wind_Clow.run(argument);
return huesaturation;
} | 9 |
public AlphaImageDemo() {
MinuetoWindow window; // The Minueto window
MinuetoImage imageTank; // MinuetoImage used to store
// the image we will load.
MinuetoImage imageBackGround; // Background image
double x; // Position to draw the image.
if (MinuetoTool.isWindows()) {
MinuetoOptions.enableDirectXAcceleration();
} else {
MinuetoOptions.enableOpenGLAcceleration();
}
MinuetoOptions.enableAlpha(true);
// Create a 640 by 480 window
window = new MinuetoFrame(640, 480, true);
imageBackGround = new MinuetoImage(640,480);
imageBackGround.draw(new MinuetoRectangle(160, 480,MinuetoColor.BLUE, true), 0, 0);
imageBackGround.draw(new MinuetoRectangle(160, 480,MinuetoColor.GREEN, true), 160, 0);
imageBackGround.draw(new MinuetoRectangle(160, 480,MinuetoColor.YELLOW, true), 320, 0);
imageBackGround.draw(new MinuetoRectangle(160, 480,MinuetoColor.RED, true), 480, 0);
// Load our image.
try {
imageTank = new MinuetoImageFile("images/alphatank.png");
} catch (MinuetoFileException e) {
System.out.println("Could not load tank file");
System.exit(0);
return;
}
// Starting position of our image.
x = 0;
// Show the game window.
window.setVisible(true);
// Game/rendering loop
while(true) {
// Clear the window.
window.clear();
window.draw(imageBackGround, 0, 0);
// Move the image at every frame.
x = x + 0.05;
if (x > 639) {x = 0;}
// Draw the image.
window.draw(imageTank, (int)x, 50);
// Render all graphics in the back buffer.
window.render();
}
} | 4 |
private Object getIdString() {
try {
Field idField = this.getClass().getDeclaredField("id");
return idField.get(this);
} catch (SecurityException e) {
return "";
} catch (NoSuchFieldException e) {
return "";
} catch (IllegalArgumentException e) {
return "";
} catch (IllegalAccessException e) {
return "";
}
} | 4 |
public synchronized User detachUser(String nickname) {
for (User user : model) {
if ( user.getNickname().equals(nickname) ) {
model.remove(user);
contentChanged();
return user;
}
}
return null;
} | 2 |
private String get_alphabet_morse(int cnt)
{
StringBuilder sb=new StringBuilder();
int first_line=cnt/9;
switch(first_line)
{
case 0:
sb.append(".");
break;
case 1:
sb.append("-");
break;
case 2:
sb.append("x");
break;
}
int second_line=cnt%9;
if(second_line>=0 && second_line<=2)
{
sb.append(".");
}
else if(second_line>=3 && second_line<=5)
{
sb.append("-");
}
else
{
sb.append("x");
}
int third_line=cnt%3;
if(third_line==0)
{
sb.append(".");
}
else if (third_line==1)
{
sb.append("-");
}
else
{
sb.append("x");
}
return sb.toString();
} | 9 |
public void setConfiguration (int index)
throws USBException
{
int status;
if (index < 0 || index > descriptor.getNumConfigurations ())
throw new IllegalArgumentException ();
throw new USBException ("can't set configuration (unimplemented)", 0);
/*
synchronized (lock) {
if ((status = setConfiguration (fd, index)) < 0)
throw new USBException ("can't set configuration", -status);
if (selectedConfig != index) {
selectedConfig = index;
currentConfig = null;
}
}
*/
} | 2 |
private void createEntry(String pFileWildcardPath, Map<String, String> pInstructionMap)
throws ExParser {
//Get and validate the loader name
String lLoader = pInstructionMap.remove(CONFIG_INSTRUCTION_LOADER);
if(XFUtil.isNull(lLoader)){
throw new ExParser("Invalid config file definition - 'Loader:' section cannot be null or empty");
}
//Retrieve the other values from the map
int lStartOffset;
int lFileOffset;
try {
lStartOffset = Integer.parseInt(pInstructionMap.remove(CONFIG_INSTRUCTION_START_OFFSET));
lFileOffset = Integer.parseInt(pInstructionMap.remove(CONFIG_INSTRUCTION_FILE_OFFSET));
}
catch (NumberFormatException e) {
throw new ExParser("Invalid integer value for Files section " + pFileWildcardPath);
}
catch (NullPointerException e){
throw new ExParser("Invalid Files section " + pFileWildcardPath + " - both " + CONFIG_INSTRUCTION_START_OFFSET +
" and " + CONFIG_INSTRUCTION_FILE_OFFSET + " instructions must be specified");
}
String lProperties = pInstructionMap.remove(CONFIG_INSTRUCTION_PROPERTIES);
if(pInstructionMap.size() > 0){
throw new ExParser("Unrecognised config file instruction: " + pInstructionMap.keySet().iterator().next());
}
mConfigFileEntryList.add(new ConfigFileEntry(mManifestBuilder, pFileWildcardPath, lLoader, lStartOffset, lFileOffset, lProperties));
} | 4 |
void doItCompareDomains()
{
for (String name : _a1.keySet()) {
Chromosome c1 = _a1.get(name);
Chromosome c2 = _a2.get(name);
if (c2 != null) {
StatisticResultComparisonDomains r1 = c1.analyze();
r1.setComparisonResult(c1.comparisonOfDomains(c2, epsilon));
results1.add(r1);
}
}
for (String name : _a2.keySet()) {
Chromosome c1 = _a2.get(name);
Chromosome c2 = _a1.get(name);
if (c2 != null) {
StatisticResultComparisonDomains r1 = c1.analyze();
r1.setComparisonResult(c1.comparisonOfDomains(c2, epsilon));
results2.add(r1);
}
}
} | 4 |
@Override
public void run() {
System.out.println("Hello, The Host is started");
while(nm.comp.isRunning()){
try {
Socket socket = serverSocket.accept();
Logger.println("Connection from IP: " + socket.getInetAddress());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
DataInputStream in = new DataInputStream(socket.getInputStream());
String data = in.readUTF();
PacketAction pa = PacketActions.parsePacketData(data, networkType);
if(pa != null){
if(pa instanceof PacketLoginAction){
PacketLoginAction pla = (PacketLoginAction) pa;
Boolean b = false;
for(int i = 0; i < hostClients.length; i++){
if(hostClients[i] == null){
pla.activate(new Object[]{this,socket,in,out,i});
}
}
if(!b){
sendPacket(new PacketRejected(),"slots",out);
}
} else {
sendPacket(new PacketRejected(),"invalidLogin",out);
}
}
} catch (Exception e) {
}
}
} | 7 |
@SuppressWarnings("rawtypes")
public void valueChanged(ListSelectionEvent e)
{
if (e.getValueIsAdjusting() == false)
{
JList list = (JList) e.getSource();
String selectedValue = (String) list.getSelectedValue();
String oldValue = textComponent.getText();
textComponent.setText(selectedValue);
if (!oldValue.equalsIgnoreCase(selectedValue))
{
textComponent.selectAll();
textComponent.requestFocus();
}
updateSampleFont();
}
} | 2 |
private void initializeResultsFile()
{
if (trace_flag == false) {
return;
}
// Initialize the results file
FileWriter fwriter = null;
FileWriter fwriterFin = null;
try
{
fwriter = new FileWriter(super.get_name(), true);
fwriterFin = new FileWriter(super.get_name() + "_Fin", true);
} catch (Exception ex)
{
ex.printStackTrace();
System.out.println(
"Unwanted errors while opening file " + super.get_name() +
" or " + super.get_name()+"_Fin");
}
try
{
fwriter.write(
"User \t\t Event \t GridletID \t Resource \t GridletStatus \t\t\t Clock\n");
fwriterFin.write(
"User \t\t GridletID \t Resource \t Cost \t CPU time \t Latency\n");
} catch (Exception ex)
{
ex.printStackTrace();
System.out.println(
"Unwanted errors while writing on file " + super.get_name()+
" or " + super.get_name()+"_Fin");
}
try
{
fwriter.close();
fwriterFin.close();
} catch (Exception ex)
{
ex.printStackTrace();
System.out.println(
"Unwanted errors while closing file " + super.get_name()+
" or " + super.get_name()+"_Fin");
}
} | 4 |
@Override
public void run() {
/* Todos los resultados posibles de X*10^r sin repetir
* Ejemplo: 1 dado, 2 caras, 2 bandejas:
* [0, 1, 2, 20, 21]
*/
if(trays == 1){
resultado = diceNumber * faces + 1;
}else{
Set<Integer> lcombinaciones = new HashSet<Integer>();
for(int tray = 0; tray<trays; tray++){
for(int face = 0; face<=faces; face++){
lcombinaciones.add(ponderacion(face, tray));
}
}
Set<Integer> lcomb = new HashSet<Integer>();
lcomb.addAll(lcombinaciones);
/* Combinaciones posibles de todos los dados
* X*10^r + X*10^r + X*10^r ....
*/
for(int i = 1; i < diceNumber; i++){
Set<Integer> aux = new HashSet<Integer>();
for(Integer num1: lcombinaciones){
for(Integer num2: lcomb){
aux.add(num1 + num2);
}
}
lcomb.addAll(aux);
}
/* Comprobar que entero i falta en el conjunto que contiene todas las combinaciones
posibles de todos los dados.
*/
for(int i = 0; i<lcomb.size(); i++){
if(!lcomb.contains(i)){
resultado = i;
break;
}
}
}
} | 8 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AcompanhamentoFisico other = (AcompanhamentoFisico) obj;
if (idAcompanhamentoFisico == null) {
if (other.idAcompanhamentoFisico != null)
return false;
} else if (!idAcompanhamentoFisico.equals(other.idAcompanhamentoFisico))
return false;
return true;
} | 6 |
public static long ncr(int n, int k)
{
return factorial(n).divide(factorial(n-k).multiply(factorial(k))).longValue();
} | 0 |
public static String getValidDnaCharsOrN( String inString )
{
StringBuffer buff = new StringBuffer();
for ( int x=0; x < inString.length(); x++ )
{
char c = inString.charAt(x);
if ( c == 'A' || c == 'C' || c == 'G' || c == 'T' ||
c == 'N' )
buff.append(c);
}
return buff.toString();
} | 6 |
@Override
public double[] evaluate(double[] parameters) {
if(this.numberOfEvaluation <= 0){
return null;
}
this.numberOfEvaluation -= 1;
controllers.singlePlayer.ucbOptimizerAgent.Agent.parameters = parameters;
double[] results = new double[this.getNumberOfObjectives()];
for(int i=0; i<this.gamePaths.length; i++){
double totalWins = 0;
double totalScore = 0;
for(int j=0; j<this.repetition; j++){
double[] gameResults = null;
do{
gameResults = ArcadeMachine.runOneGame(this.gamePaths[i], this.levelPaths[i], false,
"controllers.singlePlayer.ucbOptimizerAgent.Agent", null, new Random().nextInt(), 0);
}while(gameResults[0] < -10);
totalWins += Math.max(gameResults[0], 0);
totalScore += gameResults[1];
}
results[i] = 1000 * totalWins / this.repetition + totalScore / this.repetition;
}
return results;
} | 4 |
@Test
public void testPropertiesConfiguredInstanceName()
throws Exception
{
assertEquals( scheduler.getSchedulerName(), INSTANCE_NAME );
} | 0 |
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Handle)) {
return false;
}
Handle h = (Handle) obj;
return tag == h.tag && owner.equals(h.owner) && name.equals(h.name)
&& desc.equals(h.desc);
} | 5 |
static final boolean method3455(String string, int i) {
anInt4324++;
if (string == null)
return false;
for (int i_0_ = 0; ((Class348_Sub42_Sub12.ignoreListLength ^ 0xffffffff)
< (i_0_ ^ 0xffffffff)); i_0_++) {
if (string.equalsIgnoreCase(Class122.aStringArray1808[i_0_]))
return true;
if (string.equalsIgnoreCase(aa_Sub2.aStringArray5197[i_0_]))
return true;
}
if (i != 28280)
consoleActive = false;
return false;
} | 5 |
public static void save(HashMap<String, ArrayList<String>> map, String path) {
try {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(path));
oos.writeObject(map);
oos.flush();
oos.close();
// Handle I/O exceptions
} catch (Exception e) {
e.printStackTrace();
}
} | 1 |
void findBeginningAndFinishLocations() {
char character;
beginning = null;
finish = null;
for (int column = 0; column < dimension; column++) {
for (int row = 0; row < dimension; row++) {
character = getValueAtLocation(column, row);
if (character == BEGINNING) {
beginning = new Location(column, row);
if (finish != null) return;
} else if (character == FINISH) {
finish = new Location(column, row);
if (beginning != null) return;
}
}
}
} | 6 |
public void tick(){
if(y + ny >= 0 && y + ny <= maxY - height){
y += ny;
}else{
ny *= -1;
y += ny;
}
if(x + nx >= 0 && x + nx <= maxX -width){
x += nx;
}else{
nx *=-1;
x += nx;
}
if(x <= 0){
x = 0;
}
if(x >= maxX -width){
x = maxX -width;
}
if(y >= maxY -height){
y = maxY -height;
}
if(y <= 0){
y = 0;
}
this.setLocation(x, y);
if(this.intersects(start.gs[start.currentLevel].player)){
this.setDead(true);
this.addBuff(start.gs[start.currentLevel].player);
}
} | 9 |
public PrecisionLab getPrecisionLab()
{
precisionLabLock.readLock().lock();
if (precisionLabInstance == null)
{
precisionLabLock.readLock().unlock();
precisionLabLock.writeLock().lock();
try
{
if (precisionLabInstance == null)
{
precisionLabInstance = createPrecisionLab();
}
}
finally
{
precisionLabLock.writeLock().unlock();
}
}
else
{
precisionLabLock.readLock().unlock();
}
return precisionLabInstance;
} | 2 |
public JLabel getjLabelMotifVisite() {
return jLabelMotifVisite;
} | 0 |
public static void setUpEntities(){
bat = new Bat(WIDTH / 2, HEIGHT -30 , 80, 20);
ball = new Ball(bat.getX() + 20, bat.getY() - 30, 10, 10);
ball.setDY(.1);
int xPos = 20, yPos = 20;
for (int i = 0; i < 15; i++) {
bricks.add(new Brick(xPos, yPos, true));
xPos += 120;
if (xPos > 500) {
xPos = 20;
yPos += 100;
}
}
} | 2 |
private boolean worldChanged()
{
//Wenn sich die Original-Linienanzahl veraendert hat
if(numlines != Reflines.size())
{
//Originallinien kopieren
Lines.clear();
for(int i=0; i<Reflines.size(); i++)
{
int[] x = new int[4];
x[0] = Reflines.elementAt(i)[0];
x[1] = Reflines.elementAt(i)[1];
x[2] = Reflines.elementAt(i)[2];
x[3] = Reflines.elementAt(i)[3];
this.Lines.add(x);
}
numlines = Reflines.size();
//Ueberpruefen ob selbst-berechnete Linien noch gueltig sind, sonst aussortieren
int num = 0;
for(int u=0; u<Calculatedlines.size(); u++)
{
//Jede berechnete Linie braucht mindestens 2 Schnittpunkte, sonst fliegt sie raus
for(int z=0; z<Lines.size(); z++)
{
if(Mat.getCrossPointLL(Calculatedlines.elementAt(u), Lines.elementAt(z))[0] != -1)
{
num++;
}
}
if(num < 2)
{
Calculatedlines.remove(u);
}
}
//Selbst berechnete Linien beifuegen
for(int l=0; l<Calculatedlines.size(); l++)
{
int[] x = new int[4];
x[0] = Calculatedlines.elementAt(l)[0];
x[1] = Calculatedlines.elementAt(l)[1];
x[2] = Calculatedlines.elementAt(l)[2];
x[3] = Calculatedlines.elementAt(l)[3];
this.Lines.add(x);
}
return(true);
}
//Wenn sich die Anzahl der Tore veraendert hat
if(numgoals != Goals.size())
{
numgoals = Goals.size();
return(true);
}
return(false);
} | 8 |
@POST
@Path("/v2.0/subnets")
@Produces(MediaType.APPLICATION_JSON)
public Response createSubnet(final String request) throws MalformedURLException, IOException{
//Convert input object NetworkData into a String like a Json text
Object sub;
sub = JsonUtility.fromResponseStringToObject(request,Subnet.class);
String input = JsonUtility.toJsonString(sub);
//Connect to a REST service
HttpURLConnection conn=HTTPConnector.HTTPConnect(new URL(this.URLpath), OpenstackNetProxyConstants.HTTP_METHOD_POST, input);
//Get the response text from the REST service
String response=HTTPConnector.printStream(conn);
Object result;
if(response.equals("Multiple created")) result=response;
else result=(Subnet) JsonUtility.fromResponseStringToObject(response, Subnet.class);
int responseCode=conn.getResponseCode();
HTTPConnector.HTTPDisconnect(conn);
//Insert data into the Knowledge Base
if (responseCode==201){
// Subnet s=(Subnet)result;
// if(s.getSubnets()==null)SubnetOntology.insertSubnet(s, null);
// else SubnetOntology.insertMultipleSubnets(s);
}
//Build the response
return Response.status(responseCode).header("Access-Control-Allow-Origin", "*").entity(result).build();
} | 2 |
static void handleUDP(DatagramSocket udpSocket) throws IOException {
while (true) {
//will represent the received data as bytes
byte[] receiveData = new byte[1024];
//sent data as bytes
byte[] sendData = new byte[1024];
//represent received packet
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
//waits until a packet is received form the client
udpSocket.receive(receivePacket);
//receive client string by extracting the data from the received packet
clientString = new String(receivePacket.getData());
System.out.println(receivePacket.getAddress().toString() + ":" + receivePacket.getPort() + " sent this message: " + clientString);
//get the client ip and port
InetAddress clientIPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
//build the data to be sent to the client
sendData = clientString.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, clientIPAddress, port);
//send data to client
udpSocket.send(sendPacket);
}
}
}
/*represents a single tcp connection from a client*/
class TcpSendThread extends Thread {
//message sent form the client
private static String clientString;
private Socket socket = null;
public TcpSendThread(Socket socket) {
super("TcpSendThread");
this.socket = socket;
}
public void run() {
try {
handleTCP(socket);
} catch (IOException ex) {
ex.printStackTrace();
}
}
/*responsible for handling all TCP connections to the server*/
static void handleTCP(Socket clientSocket) throws IOException {
//get socket
Socket connectionSocket = clientSocket;
//input stream from client
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
//output stream to client
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
//message received from the client
clientString = inFromClient.readLine() + "\n";
System.out.println(connectionSocket.getInetAddress().toString() + ":" + connectionSocket.getPort() + " sent this message: " + clientString);
//sent the modified message to client
outToClient.writeBytes(clientString);
} | 1 |
@Override
public void deserialize(Buffer buf) {
msgId = buf.readShort();
if (msgId < 0)
throw new RuntimeException("Forbidden value on msgId = " + msgId + ", it doesn't respect the following condition : msgId < 0");
timeStamp = buf.readUInt();
if (timeStamp < 0 || timeStamp > 4294967295L)
throw new RuntimeException("Forbidden value on timeStamp = " + timeStamp + ", it doesn't respect the following condition : timeStamp < 0 || timeStamp > 4294967295L");
owner = buf.readString();
objectGenericId = buf.readUInt();
if (objectGenericId < 0 || objectGenericId > 4294967295L)
throw new RuntimeException("Forbidden value on objectGenericId = " + objectGenericId + ", it doesn't respect the following condition : objectGenericId < 0 || objectGenericId > 4294967295L");
} | 5 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.