text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public int getIndex(String opCode) {
for (int i = 0; i < size; i++) {
if (tuples[i].getValue() != null) {
if (tuples[i].getValue().equals(opCode)) {
return i;
}
}
}
return -1;
} | 3 |
private void writeArray(List<Byte> ret, Object[] val) throws EncodingException, NotImplementedException
{
writeInt(ret, (val.length << 1) | 1);
ret.add((byte)0x01);
for (Object obj : val)
encode(ret, obj);
} | 1 |
private boolean r_combo_suffix() {
int among_var;
int v_1;
// test, line 91
v_1 = limit - cursor;
// (, line 91
// [, line 92
ket = cursor;
// substring, line 92
among_var = find_among_b(a_2, 46);
if (among_var == 0)
{
return false;
}
// ], line 92
bra = cursor;
// call R1, line 92
if (!r_R1())
{
return false;
}
// (, line 92
switch(among_var) {
case 0:
return false;
case 1:
// (, line 100
// <-, line 101
slice_from("abil");
break;
case 2:
// (, line 103
// <-, line 104
slice_from("ibil");
break;
case 3:
// (, line 106
// <-, line 107
slice_from("iv");
break;
case 4:
// (, line 112
// <-, line 113
slice_from("ic");
break;
case 5:
// (, line 117
// <-, line 118
slice_from("at");
break;
case 6:
// (, line 121
// <-, line 122
slice_from("it");
break;
}
// set standard_suffix_removed, line 125
B_standard_suffix_removed = true;
cursor = limit - v_1;
return true;
} | 9 |
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++)
exec.execute(new LiftOff());
exec.shutdown();
System.out.println("Waiting for LiftOff");
} | 1 |
private void init()
{
this.clock.add(DAWN);
for(int i = 0; i < MAX_CLOCK_SIZE-1; i++)
{
this.clock.add(NIGHT);
}
this.shuffle(this.clock);
for(int i = 0; i < 5; i++)
{
this.library.add(NIGHT);
}
for(int i = 0; i < 18; i++)
{
this.library.add(RUMOR);
}
for(int i = 0; i < 15; i++)
{
this.library.add(COMPONENT);
}
for(int i = 0; i < 16; i++)
{
this.library.add(BITE);
}
this.shuffle(this.library);
} | 5 |
public static boolean sleepClauseActive(Pokemon[] p, int pokemonAvailable)
{
for(int i=0; i<pokemonAvailable; i++)
{
if(p[i].status==Pokemon.Status.SLP)
return true;
}
return false;
} | 2 |
@Override
public boolean numericalCheck() {
//
// over all time steps.
//
for (int f = 0; f < this.data.framewidth; f++) {
//
// for all cells.
//
for (int j = 0; j < this.structure.cellsnum; j++) {
if (!check(this.data.input[f][j])) return false;
if (!check(this.data.output[f][j])) return false;
if (!check(this.data.gradinput[f][j])) return false;
if (!check(this.data.gradoutput[f][j])) return false;
}
}
//
// for all weights.
//
for (int i = 0; i < this.data.weightsnum; i++) {
if (!check(this.data.weights[i])) return false;
}
return true;
} | 8 |
public boolean updatePosListaPrecioCeroA(final PosListaPrecio itemOracle){
Session hbSessionOracle = getSession(); // SESSION MYSQL
Transaction tsOracle = hbSessionOracle.beginTransaction();
boolean successOracle = false;
try {
getHibernateTemplate().execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query = session.createQuery(
"update PosListaPrecio set pcaCantidad = 0, pcaEstado = 'A'" +
" where pcaPosId = ? and pcaIdElemento = ? "
);
query.setInteger(0, itemOracle.getPcaPosId());
query.setInteger(1, itemOracle.getPcaIdElemento());
query.executeUpdate();
return null; //To change body of implemented methods use File | Settings | File Templates.
}
});
successOracle = true;
} catch (DataAccessException e) {
e.printStackTrace(); //
return false;
} finally {
if (!successOracle) {
tsOracle.rollback();
hbSessionOracle.flush();
hbSessionOracle.close();
} else {
tsOracle.commit();
hbSessionOracle.flush();
hbSessionOracle.close();
}
}
getHibernateTemplate().flush();
return successOracle;
} | 2 |
private void OpenButtonDialogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OpenButtonDialogActionPerformed
this.OpenDialog.setVisible(false);
try {
System.out.println(this.FileChooser.getSelectedFile().getName());
String name = StringTools.getNameWithoutExtension(this.FileChooser.getSelectedFile().getName());
HashMap<String,String> tmp = StringTools.convertStringToHashMapFormat(
CryptoTools.decryptFile3DES(this.FileChooser.getSelectedFile().getCanonicalPath(),name + new String(this.OpenPasswordField.getPassword())));
if(!tmp.isEmpty())
{
this.InfoField.setText("File opened");
this.notebook1.setData(tmp);
}
else
this.InfoField.setText("Bad Password");
this.InfoDialog.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(MainWindows.class.getName()).log(Level.SEVERE, null, ex);
}
this.OpenPasswordField.setText(null);
}//GEN-LAST:event_OpenButtonDialogActionPerformed | 2 |
public void callFunc(final int startIndex, final int endIndex, MInteger outBegIdx, MInteger outNbElement)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
int count = 0;
for (Object item : callInputParams) {
if (PriceInputParameter.class.isAssignableFrom(item.getClass())) {
count += ((PriceInputParameter)item).getCount();
} else {
count++;
}
}
count += callOutputParams.length;
count += callOptInputParams.length;
Object[] params = new Object[count+4];
count = 0;
params[count++] = startIndex;
params[count++] = endIndex;
for (Object item : callInputParams) {
if (PriceInputParameter.class.isAssignableFrom(item.getClass())) {
Object objs[] = ((PriceInputParameter)item).toArrays();
for (int i=0; i<objs.length; i++) {
params[count++] = objs[i];
}
} else {
params[count++] = item;
}
}
for (Object item : callOptInputParams) {
params[count++] = item;
}
params[count++] = outBegIdx;
params[count++] = outNbElement;
for (Object item : callOutputParams) {
params[count++] = item;
}
Type[] types = function.getGenericParameterTypes();
if (types.length != params.length) throw new IllegalArgumentException(ILLEGAL_NUMBER_OF_ARGUMENTS);
//for (int i=0; i<types.length; i++) {
// if (! (params[i].getClass().isAssignableFrom(types[i])) ) {
// throw new IllegalArgumentException("Type mismatch on argument "+i+": "+types[i]);
// }
//}
function.invoke(taCore, params);
} | 8 |
private DateTime getADate(String s) {
DateTime retDT = null;
try {
retDT = new DateTime(s, DateTimeZone.UTC);
} catch (IllegalArgumentException pe) {
pe.printStackTrace();
}
return retDT;
} | 1 |
private void moveTo(Point point) {
Point nextLocation = getLocation();
if (point.x > nextLocation.x) {
nextLocation.x++;
}
if (point.x < nextLocation.x) {
nextLocation.x--;
}
if (point.y > nextLocation.y) {
nextLocation.y++;
}
if (point.y < nextLocation.y) {
nextLocation.y--;
}
setLocation(nextLocation.x, nextLocation.y);
} | 4 |
@Override
public void run()
{
double distance = Math.abs((endPoint - startPoint) / numberOfProbes);
double[] evaluationPoints = getEvaluationPoints(startPoint, distance, numberOfProbes);
List<Double> startingPointsToCheck = findRangesWhereSignsChange(f, evaluationPoints, numberOfProbes);
/*
* For each interval where the sign changed, used the Secant method to find the root.
* If secant method fails, do Bisection three times on the interval and try again
*/
for (int i = 0; i < startingPointsToCheck.size(); i++)
{
double start = startingPointsToCheck.get(i);
double end = start + distance;
double currentLocation = (start + end) / 2;
double oldLocation = currentLocation + 0.0005;
double currentValue = f.evaluate(currentLocation);
double nextLocation = getNextSecantLocation(f, currentLocation, oldLocation);
double nextValue = f.evaluate(nextLocation);
boolean wasFound = false;
//Keep doing secant until we find a root or stall out
while (Math.abs(nextValue) < 0.5 * Math.abs(currentValue))
{
if (Math.abs(nextValue) < tolerance) //We found the root. w00t!
{
resultList.add(nextLocation);
wasFound = true;
break;
}
oldLocation = currentLocation;
currentLocation = nextLocation;
nextLocation = getNextSecantLocation(f, currentLocation, oldLocation);
nextValue = f.evaluate(nextLocation);
}
//If we didn't find it, do bisection three times,
//Then add the new location to the list and try again
if (wasFound == false)
{
double tempStart = start;
double tempEnd = end;
double mid = (tempStart + tempEnd) / 2;
for (int j = 0; j < 3; j++)
{
double startVal = f.evaluate(tempStart);
double endVal = f.evaluate(tempEnd);
double midVal = f.evaluate(mid);
if (startVal * midVal <= 0)
{
tempEnd = mid;
continue;
}
else if (midVal * endVal <= 0)
{
tempStart = mid;
continue;
}
}
startingPointsToCheck.add(tempStart);
}
}
} | 7 |
public void setId(Integer id) {
this.id = id;
} | 0 |
public Decision decide(RobotView controlledRobot, RobotEnvironmentView environmentView) {
// okreslamy czy robot ma cos w kieszeni
if (controlledRobot.getCache().isEmpty()) {
// kieszen jest pusta
logger.level2("Kieszen pusta");
// sprawdzamy czyjakis student czegos nie potrzebuje
// przegladamy wszystkie biurka
for (DeskView desk : environmentView.getDeskViews()) {
// sprawdzamy liste zamowien na biurku
for (Integer isbn : desk.getWishList()) {
// jesli cos znalezlismy, to jedziemy po to
logger.level2("Jedziemy do polki po ksiazke do wypozyczenia: " + isbn);
// rozkaz automatycznie (na podstawie isbn ksiazki) okresli o ktora polke chodzi
return new Decision(DecisionType.TAKE_FROM_BOOKSHELF, isbn);
}
}
// jesli nikt nic nie zamawia, to mozemy sprobowac odlazyc jakas ksiazke na polke
for (DeskView desk : environmentView.getDeskViews()) {
// sprawdzamy liste zamowien na biurku
for (Book bookToReturn : desk.getBooksToReturn()) {
logger.level2("Jedziemy po ksiazke do oddania do bourka: " + desk);
// jesli cos znalezlismy, to jedziemy po to
return new Decision(DecisionType.TAKE_FROM_DESK, desk.getNumber(), bookToReturn.getIsbn());
}
}
// jesli nic nie ma do zrobienia to czekamy
return new Decision(DecisionType.WAIT);
} else {
// jest cos w kieszeni
// ksiazka ktora jest w kieszeni
Book bookInCache = controlledRobot.getCache().get(0);
logger.level2("Mamy w kieszeni ksiazke: " + bookInCache);
// skoro mamy ksiazke w kieszeni, to sa 2 mozliwosci
// albo student ta ksiazke zamowil i trzeba mu dostarczyc
// albo trzeba ja odwiezc na polke
// sprawdzamy czy ktos zamowil
// przegladamy wszystkie biurka
for (DeskView desk : environmentView.getDeskViews()) {
// sprawdzamy liste zamowien na biurku
for (Integer isbn : desk.getWishList()) {
// jesli to to samo co ktos zamowil
if (bookInCache.getIsbn() == isbn) {
logger.level2("Jedziemy dostarczyc ksiazke do bourka: " + desk);
// zwracanie rozkazu dostarczenia tam ksiazki
return new Decision(DecisionType.DELIVER_TO_DESK, desk.getNumber(), bookInCache.getIsbn());
}
}
}
logger.level2("Jedziemy odlozyc ksiazke na polke");
// widac nikt tej ksiazki nie potrzebuje wiec zawozimy na polke
// rozkaz automatycznie (na podstawie isbn ksiazki) okresli o ktora polke chodzi
return new Decision(DecisionType.DELIVER_TO_BOOKSHELF, bookInCache.getIsbn());
}
} | 8 |
@Override
public void run()
{
while(!end)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e) {}
repaint();
}
} | 2 |
private boolean jj_3_40() {
if (jj_3R_59()) return true;
return false;
} | 1 |
public boolean correctCombination(AnswerCombination answerCombination) {
if (answerCombination.getBlackCount() == 5) {
return true;
}
else {
return false;
}
} | 1 |
@Override
public String onKill(L2Npc npc, L2PcInstance killer, boolean isPet)
{
switch (npc.getNpcId())
{
case Lilith:
if (getQuestTimer("spawn_exitgk_lilith", null, null) == null)
startQuestTimer("spawn_exitgk_lilith", 10000, null, null, 0);
break;
case Anakim:
if (getQuestTimer("spawn_exitgk_lilith", null, null) == null)
startQuestTimer("spawn_exitgk_anakim", 10000, null, null, 0);
break;
}
return super.onKill(npc, killer, isPet);
} | 4 |
private Set<String> placeFigureAtPositionOnBoard(char figure, int position, String board) {
int dimension = (int) Math.sqrt(board.length()) + 1;
isBoardLegal(board, dimension);
Set<String> setOfPossibleBoards = new HashSet<>((int) IntStream
.range(0, board.length())
.filter(i -> board.charAt(i) == EMPTY_FIELD_CHAR)
.boxed()
.count());
char[] boardArray = board.toCharArray();
if (boardArray[position] == EMPTY_FIELD_CHAR) {
if (isFigurePlacementOnPositionPossible(position, boardArray, dimension)) {
boardArray[position] = figure;
setOfPossibleBoards.add(new String(boardArray));
}
}
return setOfPossibleBoards;
} | 2 |
public void expandNode(final Node n) {
new Thread() {
@Override
public void run() {
synchronized (LocalityUtils.this) {
if (!locality.getCompleteEltSet().contains(n))
return;
manager.stopDamper();
for (int i = 0; i < n.edgeCount(); i++) {
Node newNode = n.edgeAt(i).getOtherEndpt(n);
if (!locality.contains(newNode)) {
newNode.justMadeLocal = true;
try {
locality.addNodeWithEdges(newNode);
Thread.sleep(50);
} catch (TGException tge) {
System.err.println("TGException: " + tge.getMessage());
} catch (InterruptedException ex) {
}
} else if (!locality.contains(n.edgeAt(i))) {
locality.addEdge(n.edgeAt(i));
}
}
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
}
unmarkNewAdditions();
manager.resetDamper();
}
}
}.start();
} | 7 |
public void updateRaws(String cookieName) {
ArrayList<String> materials = getIng(cookieName);
for (int i = 0; i < materials.size(); i++) {
ResultSet rs1 = null;
ResultSet rs2 = null;
String materialType = materials.get(i);
int amountInStock = 0;
int amountNeeded = 0;
String sql1 = "select amountNeeded from RecipesHasIngridients where materialType = ?";
try {
PreparedStatement ps = conn.prepareStatement(sql1);
ps.setString(1, materialType);
rs1 = ps.executeQuery();
if(rs1.next()){
amountNeeded = rs1.getInt("amountNeeded");
};
} catch (SQLException e) {
e.printStackTrace();
}
String sql2 = "select amountInStock from RawMaterials where materialType = ?";
try {
PreparedStatement ps = conn.prepareStatement(sql2);
ps.setString(1, materialType);
rs2 = ps.executeQuery();
if(rs2.next()){
amountInStock = rs2.getInt("amountInStock");
};
} catch (SQLException e) {
e.printStackTrace();
}
int howManyPallets = PalletsProduced(cookieName);
int calc = amountInStock - howManyPallets * 54 * amountNeeded;
String sql3 = "update RawMaterials set amountInStock = ? where materialType = ?";
try {
PreparedStatement ps3 = conn.prepareStatement(sql3);
ps3.setInt(1, calc);
ps3.setString(2, materialType);
ps3.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
} | 6 |
public static Mascota crearMascota(int tipo, String nombre){
Mascota mascota = null;
if(tipo == 1){
mascota = new Perro(nombre);
}else if(tipo == 2){
mascota = new Gato(nombre);
}else if(tipo == 3){
mascota = new Ave();
}
return mascota;
} | 3 |
private int getVillagerCount() {
int count = 0;
for (Player player : players.getPlayers()) {
if (player.getRole().equals(Role.Villager.toString())) count++;
}
return count;
} | 2 |
public void putField(Reference ref, Object obj, Object value)
throws InterpreterException {
Field f;
try {
Class clazz = TypeSignature.getClass(ref.getClazz());
try {
f = clazz.getField(ref.getName());
} catch (NoSuchFieldException ex) {
f = clazz.getDeclaredField(ref.getName());
}
} catch (ClassNotFoundException ex) {
throw new InterpreterException(ref + ": Class not found");
} catch (NoSuchFieldException ex) {
throw new InterpreterException("Constructor " + ref + " not found");
} catch (SecurityException ex) {
throw new InterpreterException(ref + ": Security exception");
}
try {
f.set(obj, toReflectType(ref.getType(), value));
} catch (IllegalAccessException ex) {
throw new InterpreterException("Field " + ref + " not accessible");
}
} | 5 |
private void parseDocument() {
// get the root elememt
Element docEle = dom.getDocumentElement();
// get a nodelist of <employee> elements
NodeList shapeNodeList = docEle.getElementsByTagName("Shape");
if (shapeNodeList != null && shapeNodeList.getLength() > 0) {
for (int i = 0; i < shapeNodeList.getLength(); i++) {
// get the employee element
Element el = (Element) shapeNodeList.item(i);
// get the Employee object
UMLShape_Class sc = getShapeClass(el);
// add it to list
shapesList.put(sc.getID(), sc);
}
}
NodeList lineNodeList = docEle.getElementsByTagName("Line");
if (lineNodeList != null && lineNodeList.getLength() > 0) {
for (int i = 0; i < lineNodeList.getLength(); i++) {
// get the employee element
Element el = (Element) lineNodeList.item(i);
// get the Employee object
UMLLine l = getLine(el);
// add it to list
linesList.add(l);
}
}
NodeList commentBoxNodeList = docEle.getElementsByTagName("CommentBox");
if (commentBoxNodeList != null && commentBoxNodeList.getLength() > 0) {
for (int i = 0; i < commentBoxNodeList.getLength(); i++) {
// get the employee element
Element el = (Element) commentBoxNodeList.item(i);
// get the Employee object
UMLShape_CommentBox sc = getShapeCommentBox(el);
// add it to list
commentBoxList.put(sc.getID(), sc);
}
}
} | 9 |
private Connection getConnection() {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
Utilities.outputError("Could not find sqlite drivers");
return null;
}
try {
return DriverManager.getConnection("jdbc:sqlite:" + m_databaseFile.getAbsolutePath());
} catch (SQLException e) {
return null;
}
} | 2 |
public void setSerialNo(String value) {
this.serialNo = value;
} | 0 |
@Override
public void parseArgs(String[] args) {
this.args = args;
int i = 0;
if (args[0].equals("-v")) {
verbose = true;
i++;
}
if ((args.length - i) != 2) usage(null);
numSplits = Gpr.parseIntSafe(args[i++]);
fastqFile = args[i++];
if (numSplits <= 1) usage("Number of splits should be more than 1.");
} | 3 |
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int plots = 24;
int rounds;
int players;
System.out.println("'Welcome to Monopoly Board Game'");
System.out.println();
System.out.print("Please enter number of rounds: ");
for(;;) //an endless loop...
{
if(!scan.hasNextInt() )// hasNextInt() checks if the input is an integer
{
System.out.println("only integers!: ");
scan.next();
continue;
}
rounds=scan.nextInt();
break;
}
System.out.print("PLease enter number of players (2-6): ");
for(;;)
{
if(!scan.hasNextInt() )
{
System.out.print("Please type an number!! Try again! : ");
scan.next();
continue;
}
players= scan.nextInt();
if (players<2 || players>6)
{
System.out.print("Number of players can be 2 to 6: ");
continue;
}
break;
}
System.out.println();
//Generate a new instance of the board and start the game
Board_Game Game= new Board_Game(rounds, players, plots);
} | 6 |
public static byte[] readStream(InputStream fin) throws IOException {
byte[][] bufs = new byte[8][];
int bufsize = 4096;
for (int i = 0; i < 8; ++i) {
bufs[i] = new byte[bufsize];
int size = 0;
int len = 0;
do {
len = fin.read(bufs[i], size, bufsize - size);
if (len >= 0)
size += len;
else {
byte[] result = new byte[bufsize - 4096 + size];
int s = 0;
for (int j = 0; j < i; ++j) {
System.arraycopy(bufs[j], 0, result, s, s + 4096);
s = s + s + 4096;
}
System.arraycopy(bufs[i], 0, result, s, size);
return result;
}
} while (size < bufsize);
bufsize *= 2;
}
throw new IOException("too much data");
} | 4 |
public boolean info(CommandSender sender, String[] args)
{
String name;
if (args.length > 1) { //Player specified a name
name = args[1];
} else {
name = sender.getName();
}
Resident resident = em.find(Resident.class, name);
if (resident == null) {
sender.sendMessage(ChatColor.RED + "That player does not exist.");
return true;
}
boolean onlineNow = false;
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.getName().equals(resident.getName())) {
onlineNow = true;
break;
}
}
sender.sendMessage(ChatColor.LIGHT_PURPLE + "+---------------------------------------------------+");
sender.sendMessage(ChatColor.GOLD + "Name: " + ChatColor.YELLOW + resident.getName());
if(onlineNow) {
sender.sendMessage(ChatColor.GOLD + "Last Online: " + ChatColor.YELLOW + "Online now!");
} else {
sender.sendMessage(ChatColor.GOLD + "Last Online: " + ChatColor.YELLOW + resident.getLastOnline().toString());
}
sender.sendMessage(ChatColor.GOLD + "First Online: " + ChatColor.YELLOW + resident.getFirstOnline().toString());
sender.sendMessage(ChatColor.GOLD + "Online Time: " + ChatColor.YELLOW + resident.getOnlineTimeString());
listFriends(sender, args);
return true;
} | 5 |
public void run() {
try {
while(s.isConnected() && out != null) {
try {
Thread.sleep(400);
} catch (InterruptedException e) {}
out.flush();
out.reset();
System.out.println("Sent an update!");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
if (!s.isClosed())
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} | 7 |
public static TrafficStatusEnum fromValue(String v) {
for (TrafficStatusEnum c: TrafficStatusEnum.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
} | 2 |
public String execute() {
Map<String, Object> session = ActionContext.getContext().getSession();
User user = (User) session.get("USER");
list = null;
String actionResult = "";
reportBusinesService = new ReportBusinesService();
log.info(user.getFname() + startDate + endDate + vregistration_num);
list = reportBusinesService.createIdealTime(user, startDate, endDate, vregistration_num);
if (list != null) {
// latitude = Report.getLatitudeList();
// longitude = Report.getLongitudeList();
x = start_location_flag;
for (int i = 0; i < list.size(); i++) {
if (dummyLat.equalsIgnoreCase("")) {
dummyLat = list.get(i).getLatitudeList();
} else {
dummyLat = dummyLat + ',' + list.get(i).getLatitudeList();
}
if (dummyLong.equalsIgnoreCase("")) {
dummyLong = list.get(i).getLongitudeList();
} else {
dummyLong = dummyLong + ',' + list.get(i).getLongitudeList();
}
}
setLatitude(dummyLat);
setLongitude(dummyLong);
setCurrentUserName(user.getFname() + " " + user.getLname());
if (user.getUprofile() == 1) {
actionResult = "individual";
setCurrentUserName(getCurrentUserName() + " [I]");
} else {
if (user.getUprofile() == 2) {
actionResult = "group";
setCurrentUserName(getCurrentUserName() + " [G]");
} else {
if (user.getUprofile() == 3) {
actionResult = "admin";
setCurrentUserName(getCurrentUserName() + " [A]");
}
}
}
} else {
actionResult = "input";
}
return actionResult;
} | 7 |
public void kaynnista() {
while (true) {
System.out.print("Anna lauseke (tyhja lopettaa): ");
String syote = lukija.nextLine();
if (syote.equals("")) {
break;
}
try {
MerkkijononKasittelija kasittelija
= new MerkkijononKasittelija(syote, kirjasto);
kasittelija.kasitteleLauseke();
System.out.print("Lausekkeen arvo: ");
System.out.println(kasittelija.getLauseke().arvo());
} catch (Exception e) {
System.out.println("Virheellinen lauseke.");
}
}
} | 3 |
@Override
public void update(Observable o, Object arg) {
if(this.model.getCurrentPlayer() == this.player &&
this.model.getGameState() == GameState.DURING) {
ArrayList<Piece> validMoves = this.model.getBoard()
.getValidMoves(this.player.getColor());
if(validMoves.size() > 0) {
depth = 0;
int moveIndex = getBestMove(this.model.getBoard().getDeepCopy(), validMoves);
this.model.getBoard().makeMove(validMoves.get(moveIndex));
}
}
} | 3 |
private void submitExpression(boolean showErrors) {
Expression.setEnteredExpression(expression.getText());
if (expression.getText().equals("")) {
makeTableDisplay();
} else {
try {
if (Expression.validate()) {
makeTableDisplay();
}
} catch (ValidationException ex) {
// if the function caller was from the evaluate button then tell them what they did wrong, if it was from dynamic
// update then dont show errors.
if (showErrors){
createErrorBox(ex.getMessage());
}
}
}
expression.requestFocus();
expression.deselect();
expression.positionCaret(caretLocation);
} | 4 |
public void setRepita(List<?> list)
{
for(PComando e : this._repita_)
{
e.parent(null);
}
this._repita_.clear();
for(Object obj_e : list)
{
PComando e = (PComando) obj_e;
if(e.parent() != null)
{
e.parent().removeChild(e);
}
e.parent(this);
this._repita_.add(e);
}
} | 4 |
public void doStep() {
anz = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
newCells[i][j] = 0;
}
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
switch (calcNeighborsPeriodic(i, j)) {
case 0:
case 1:
newCells[i][j] = 0; // dies
break;
case 2:
if ((newCells[i][j] = (byte) latticeFrame.getValue(i, j)) == 1) {
anz++;
}
break;
case 3:
newCells[i][j] = 1; // condition for birth
anz++;
break;
default:
newCells[i][j] = 0; // dies of overcrowding if >3
}
}
}
latticeFrame.setAll(newCells);
dichtePlot.append(0, (double) (anz2/(double)(size*size)), (double) (anz/(double)(size*size)));
anz2 = anz;
} | 9 |
public String getValue() {
try {
return readValue();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} | 3 |
public Object[] subarray_as_Object(int start, int end){
if(end>=this.length)throw new IllegalArgumentException("end, " + end + ", is greater than the highest index, " + (this.length-1));
Object[] arrayo= new Object[end-start+1];
for(int i=start; i<=end; i++)arrayo[i-start] = this.array.get(i);
return arrayo;
} | 2 |
public void finjectInpPayload (Circuit c, byte[] info, boolean alice_inputs) {
int i, j, k, line_num, consumed_bytes ;
for (i = k = 0; i < FMT.size(); i++) {
IO io = FMT.elementAt(i);
// Verify it's a relevant i/o object
if (!io.isInput()) continue;
if (io.isAlice() != alice_inputs) continue;
// Scan all specified input bits, one by one,
// and inject the payload data
for (j = 0; j < io.getNLines(); j++) {
// This bit belongs to output of j'th line_num
line_num = io.getLinenum(j);
Gate g = c.getGate(line_num);
consumed_bytes = g.ginjectInpPayload(info, k);
k += consumed_bytes;
}
}
} | 4 |
public void print(){
for (int i = 0; i < FIELD_SIZE; i++){
for (int j = 0; j < FIELD_SIZE; j++){
System.out.print(points[i][j].getLetter() + " ");
}
System.out.println("");
}
} | 2 |
private synchronized HttpClient getHttpClient() {
if (client == null) {
// #ifdef DEBUG
log.info("Creating HttpClient instance"); //$NON-NLS-1$
// #endif
client = new HttpClient(aditoHostname, aditoPort, isSecure);
client.setAuthenticationPrompt(defaultAuthenticationPrompt != null ? defaultAuthenticationPrompt : getGUI());
if (defaultProxyHost != null && !defaultProxyHost.equals("")) { //$NON-NLS-1$
// #ifdef DEBUG
log.info("Configuring proxies for HttpClient instance"); //$NON-NLS-1$
// #endif
client
.setProxyAuthenticationPrompt(defaultProxyAuthenticationPrompt);
client.setProxyHost(defaultProxyHost);
client.setProxyPort(defaultProxyPort);
client.setProxyType(defaultProxyType);
if (defaultProxyCredentials != null
&& defaultProxyCredentials.getUsername() != null
&& !defaultProxyCredentials.getUsername().equals("")) { //$NON-NLS-1$
/**
* LDP - This used to set preemptive authentication but its
* causing problems with NTLM
*/
client.setProxyCredentials(defaultProxyCredentials);
/**
* LDP - It seems preemptive might be needed for Basic
* authentication. There are lots of users seeing
* EOFExceptions after 407 proxy authentication required.
*/
if ("BASIC"
.equalsIgnoreCase(defaultProxyPreferredAuthentication)) {
client.setProxyPreemptiveAuthentication(true);
}
}
client
.setProxyPreferedAuthentication("AUTO".equalsIgnoreCase(defaultProxyPreferredAuthentication) ? null //$NON-NLS-1$
: defaultProxyPreferredAuthentication);
}
}
return client;
} | 9 |
public void run() //listening
{
Server.print("running function: run()");
boolean isOK = true;
while (isOK)
{
try
{
String in = input.readUTF();
if (in.equals("#move"))//new move
{
int bX = input.readInt();
int bY = input.readInt();
int eX = input.readInt();
int eY = input.readInt();
table.sendMoveToOther(this, bX, bY, eX, eY);
}
else if (in.equals("#message"))//new message
{
String str = input.readUTF();
table.sendMessageToAll(nick + ": " + str);
}
else if(in.equals("#undoAsk") || in.equals("#undoAnswerNegative") )
{
table.sendToAll(this, in);
}
else if(in.equals("#undoAnswerPositive") )
{
table.sendUndoToAll(this, in);
}
}
catch (IOException ex)
{
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
isOK = false;
try
{
table.sendErrorConnectionToOther(this);
}
catch (IOException ex1)
{
Logger.getLogger(SClient.class.getName()).log(Level.SEVERE, null, ex1);
}
}
}
} | 8 |
@Basic
@Column(name = "FUN_USUARIO")
public String getFunUsuario() {
return funUsuario;
} | 0 |
public List<String> readCaptionRow() {
List<String> captions = new ArrayList<String>();
HSSFSheet sheet = wb.getSheetAt(0);
Iterator<Row> rowIt = sheet.iterator();
Row row = rowIt.next();
for (Cell cell : row) {
captions.add(cell.getStringCellValue());
}
return captions;
} | 1 |
public void registerName (String name) {
// Do nothing if the player already registered a name.
if (this.name != null) return;
// Do nothing if the name is invalid.
if (name == null) return;
name = name.trim();
if (name.length() == 0) return;
// Store the player's name.
this.name = name;
// Add a "connected" message to everyone's chat frame, except the new player.
String message = name + " connected.";
for (Player player : players)
if (player != this) player.frame.addMessage(message);
// Set the names on everyone's chat frame.
updateNames();
} | 5 |
public Construct getParentForBinding(EInterfaceAction binding) {
switch(binding) {
case Bind_InsertAfter:
case Bind_InsertBefore:
case Bind_InsertReplace:
case Bind_DuplicateToAdjacent:
case Bind_InsertPaste:
return parent;
case Bind_InsertChild:
return this;
default:
break;
}
return this;
} | 6 |
@Override
public void caseAAvalieComando(AAvalieComando node)
{
inAAvalieComando(node);
if(node.getPadrao() != null)
{
node.getPadrao().apply(this);
}
{
List<PCasoOpcao> copy = new ArrayList<PCasoOpcao>(node.getCasoOpcao());
Collections.reverse(copy);
for(PCasoOpcao e : copy)
{
e.apply(this);
}
}
if(node.getExp() != null)
{
node.getExp().apply(this);
}
outAAvalieComando(node);
} | 3 |
public String toString(){
return typeOf;
} | 0 |
public void enterFromRail(Color player, Integer dest) {
if ((player == this.getPlayer1()
&& dest < 7)
|| (player == this.getPlayer2()
&& dest > 18)) {
// make sure it's in the correct quadrant
Integer dist = 0; // if this doesn't get changed below, something seriously bad is hapened
if (player == this.getPlayer1()) {
dist = dest;
} else if (player == this.getPlayer2()) {
dist = 25 - dest;
}
if (this.getState().movesLeft.contains(dist)) {
// make sure they can move there
BackgammonState newState = new BackgammonState(this.getState());
// "use" the move
newState.movesLeft.remove(dist);
// move the piece
if (newState.move(newState.rails.get(player), newState.points.get(dest - 1))) {
// if the move was valid
// push the undo state
this.state.add(newState);
}
}
}
} | 8 |
public boolean isTuringMachine()
{
/*
* Sorry about this pretty cheap method.
*/
return simulator instanceof TMSimulator;
} | 0 |
public static void main(String[] args) {
String filename = args[0];
String separator = args[1];
In in = new In(filename);
ST<String, Queue<String>> st = new ST<String, Queue<String>>();
ST<String, Queue<String>> ts = new ST<String, Queue<String>>();
while (in.hasNextLine()) {
String line = in.readLine();
String[] fields = line.split(separator);
String key = fields[0];
for (int i = 1; i < fields.length; i++) {
String val = fields[i];
if (!st.contains(key))
st.put(key, new Queue<String>());
if (!ts.contains(val))
ts.put(val, new Queue<String>());
st.get(key).enqueue(val);
ts.get(val).enqueue(key);
}
}
StdOut.println("Done indexing");
// read queries from standard input, one per line
while (!StdIn.isEmpty()) {
String query = StdIn.readLine();
if (st.contains(query))
for (String vals : st.get(query))
StdOut.println(" " + vals);
if (ts.contains(query))
for (String keys : ts.get(query))
StdOut.println(" " + keys);
}
} | 9 |
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(membre_modifier_vehicule.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(membre_modifier_vehicule.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(membre_modifier_vehicule.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(membre_modifier_vehicule.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 membre_modifier_vehicule().setVisible(true);
}
});
} | 6 |
public static Entity getBiomeTree(Biome biome) {
switch (biome) {
case FOREST:
//return new TreeCarniferous(new Point());
case DESERT:
return null;
}
return null;
} | 2 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
if(commands.size()<2)
{
mob.tell(L("You must specify who or what to cast this on, and what you want said."));
return false;
}
final Physical target=mob.location().fetchFromRoomFavorItems(null,commands.get(0));
if((target==null)||(!CMLib.flags().canBeSeenBy(target,mob)))
{
mob.tell(L("You don't see '@x1' here.",(commands.get(0))));
return false;
}
if(target==mob)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),null);
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
mob.location().show(mob,target,CMMsg.MSG_SPEAK,L("^T<T-NAME> say(s) '@x1'^?",CMParms.combine(commands,1)));
}
}
else
beneficialWordsFizzle(mob,target,L("<S-NAME> attempt(s) to ventriloquate through <T-NAMESELF>, but no one is fooled."));
// return whether it worked
return success;
} | 7 |
private void renderTopRow(Graphics2D g) {
List<List<Card>> topRow = game.getTopRow();
double x = X_BOARD_OFFSET;
double y = CARD_Y_NO_OVERLAP;
for (List<Card> cards : topRow) {
if (cards.size() > 0) {
Card toRender = cards.get(cards.size() - 1);
//If top of pile isn't hidden, render that
if (!toRender.isHidden()) {
renderCard(toRender, g, x, y);
}//Otherwise, render the 2nd highest if it exists
else if (cards.size() > 1) {
renderCard(cards.get(cards.size() - 2), g, x, y);
}//Only one card in pile, so render empty.
else {
renderCard(null, g, x, y);
}
} else {
renderCard(null, g, x, y);
}
x += CARD_WIDTH + CARD_X_GAP;
}
} | 4 |
public static void reduce(String str) {
char[] buff = str.toCharArray();
boolean keepGoing = true;
while (keepGoing) {
keepGoing = false;
int start = -1;
int end = -1;
for (int i = 0; i < buff.length; i++) {
if (buff[i] == 0)
continue;
if (start == -1) {
start = i;
continue;
}
if (end == -1) {
end = i;
if (buff[start] == buff[end]) {
start = end;
end = -1;
continue;
}
char temp = changeToMake(buff[start], buff[end]);
buff[start] = temp;
buff[end] = 0;
end = -1;
keepGoing = true;
}
}
}
StringBuilder strbuilder = new StringBuilder();
for (int i = 0; i < buff.length; i++) {
if (buff[i] != 0)
strbuilder.append(buff[i]);
}
System.out.println(strbuilder.toString().length());
} | 8 |
public static void corner(Component comp, final byte CORNER)
{
screenOffset();
Rectangle DEST;
switch (CORNER)
{
default:
case TOP_LEFT:
DEST = new Rectangle(offset,
0,
(int) comp.getSize().getWidth(),
(int) comp.getSize().getHeight());
break;
case TOP_RIGHT:
DEST = new Rectangle((int) ((noOffset ? screenBounds : maxWinBounds).getWidth() - comp.getSize().getWidth())
+ offset,
0,
(int) comp.getSize().getWidth(),
(int) comp.getSize().getHeight());
break;
case BOTTOM_RIGHT:
DEST = new Rectangle((int) ((noOffset ? screenBounds : maxWinBounds).getWidth() - comp.getSize().getWidth())
+ offset,
(int) ((noOffset ? screenBounds : maxWinBounds).getHeight() - comp.getSize().getHeight()),
(int) comp.getSize().getWidth(),
(int) comp.getSize().getHeight());
break;
case BOTTOM_LEFT:
DEST = new Rectangle(offset,
(int) ((noOffset ? screenBounds : maxWinBounds).getHeight() - comp.getSize().getHeight()),
(int) comp.getSize().getWidth(),
(int) comp.getSize().getHeight());
break;
}
location(comp, DEST);
// System.out.println("snapped to " + DEST + ".");
} | 8 |
private boolean r_Step_3() {
int among_var;
// (, line 81
// [, line 82
ket = cursor;
// substring, line 82
among_var = find_among_b(a_4, 7);
if (among_var == 0)
{
return false;
}
// ], line 82
bra = cursor;
// call R1, line 82
if (!r_R1())
{
return false;
}
switch(among_var) {
case 0:
return false;
case 1:
// (, line 83
// <-, line 83
slice_from("al");
break;
case 2:
// (, line 85
// <-, line 85
slice_from("ic");
break;
case 3:
// (, line 87
// delete, line 87
slice_del();
break;
}
return true;
} | 6 |
private void operation() {
User attacker = getRandomUser();
if (attacker == null) {
System.out.println("NULL PTR ECPT!");
return;
}
int attackerDBID = galaxyIDToDBID.get(attacker.getGid());
int targetGalaxyID = attacker.getRandomTargetGID(1, 4);
int targetDBID = galaxyIDToDBID.get(targetGalaxyID);
// System.out.println("targetGalaxy : "+ targetGalaxyID);
String sql = "{CALL GET_ATTACK_POWER(?, ?)}";
Connection attackConnection = null;
Connection targetConnection = null;
try {
attackConnection = shardConnectionPools.get(attackerDBID).getConnection();
targetConnection = shardConnectionPools.get(targetDBID).getConnection();
CallableStatement callableStatement;
callableStatement = attackConnection.prepareCall(sql);
callableStatement.setInt(1, attacker.getUid());
callableStatement.registerOutParameter(2, Types.INTEGER);
callableStatement.execute();
int damage = callableStatement.getInt(2);
//System.out.println(damage);
int remainHp = attack(attacker.getUid(), damage, targetGalaxyID,
targetConnection);
callableStatement.close();
if (remainHp > 0) {
sql = "{CALL LOG(?, ?, ?, ?)}";
callableStatement = attackConnection.prepareCall(sql);
callableStatement.setInt(1, attacker.getUid());
callableStatement.setInt(2, targetGalaxyID);
callableStatement.setInt(3, damage);
callableStatement.registerOutParameter(4, Types.VARCHAR);
callableStatement.execute();
String log = callableStatement.getString(4);
Log.getInstance().addList(log);
callableStatement.close();
} else {
System.out.println("GAME OVER!");
Main.gameOver();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (attackConnection != null)
attackConnection.close();
if (targetConnection != null)
targetConnection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} | 6 |
public void readExternal(ObjectInput paramObjectInput)
throws ClassNotFoundException, IOException
{
super.readExternalWithoutImages(paramObjectInput);
this.state = paramObjectInput.readInt();
this.frame = paramObjectInput.readInt();
this.victim = ((Robot)paramObjectInput.readObject());
this.victimPos = ((Position)paramObjectInput.readObject());
this.emptyCountDown = paramObjectInput.readInt();
Vector localVector = (Vector)paramObjectInput.readObject();
if (localVector != null)
{
this.oldImages = new Image[localVector.size()];
for (int i = 0; i < localVector.size(); i++)
this.oldImages[i] = GameApplet.thisApplet.getImage((String)localVector.elementAt(i));
}
this.comp = ((AnimationComponent)paramObjectInput.readObject());
if (this.state == 0) {
setImages(this.oldImages);
return;
}
AnimationComponent[] arrayOfAnimationComponent = new AnimationComponent[1];
arrayOfAnimationComponent[0] = this.comp;
setImages(arrayOfAnimationComponent);
} | 3 |
@Override
public boolean isVisible() {
if (!getTab().isOpen()) {
return false;
}
final WidgetChild list = Widgets.get(EMOTE_WIDGET, EMOTE_LIST);
if (list == null || !list.validate()) {
return false;
}
final WidgetChild emote = list.getChild(childId);
return emote.visible() && list.getBoundingRectangle().contains(emote.getBoundingRectangle());
} | 4 |
private DockLayout pushDown() {
DockLayout layout = new DockLayout();
layout.mParent = this;
for (int i = 0; i < mChildren.length; i++) {
if (mChildren[i] instanceof DockLayout) {
((DockLayout) mChildren[i]).mParent = layout;
}
layout.mChildren[i] = mChildren[i];
}
layout.mHorizontal = mHorizontal;
layout.mDividerPosition = mDividerPosition;
return layout;
} | 2 |
private boolean decode5(ByteArrayOutputStream baos)
throws PDFParseException {
// stream ends in ~>
int[] five = new int[5];
int i;
for (i = 0; i < 5; i++) {
five[i] = nextChar();
if (five[i] == '~') {
if (nextChar() == '>') {
break;
} else {
throw new PDFParseException("Bad character in ASCII85Decode: not ~>");
}
} else if (five[i] >= '!' && five[i] <= 'u') {
five[i] -= '!';
} else if (five[i] == 'z') {
if (i == 0) {
five[i] = 0;
i = 4;
} else {
throw new PDFParseException("Inappropriate 'z' in ASCII85Decode");
}
} else {
throw new PDFParseException("Bad character in ASCII85Decode: " + five[i] + " (" + (char) five[i] + ")");
}
}
if (i > 0) {
i -= 1;
}
int value =
five[0] * 85 * 85 * 85 * 85 +
five[1] * 85 * 85 * 85 +
five[2] * 85 * 85 +
five[3] * 85 +
five[4];
for (int j = 0; j < i; j++) {
int shift = 8 * (3 - j);
baos.write((byte) ((value >> shift) & 0xff));
}
return (i == 4);
} | 9 |
public static void comButtons() {
for (int i = 0; i < intrfce.Menu.BUTTONS.length; i++) {
if (r.intersects(intrfce.Menu.BUTTONS[i].r)) {
if (isPressed) {
intrfce.Menu.BUTTONS[i].isClicked = true;
intrfce.Menu.BUTTONS[i].isHoveredOver = false;
} else {
intrfce.Menu.BUTTONS[i].isClicked = false;
intrfce.Menu.BUTTONS[i].isHoveredOver = true;
}
} else {
intrfce.Menu.BUTTONS[i].isClicked = false;
intrfce.Menu.BUTTONS[i].isHoveredOver = false;
}
}
for (int i = 0; i < intrfce.Menu.TEXTBOXES.length; i++) {
if (r.intersects(intrfce.Menu.TEXTBOXES[i].b.r)) {
if (isPressed) {
intrfce.Menu.TEXTBOXES[i].b.isClicked = true;
intrfce.Menu.TEXTBOXES[i].b.isHoveredOver = false;
} else {
intrfce.Menu.TEXTBOXES[i].b.isClicked = false;
intrfce.Menu.TEXTBOXES[i].b.isHoveredOver = true;
}
} else {
intrfce.Menu.TEXTBOXES[i].b.isClicked = false;
intrfce.Menu.TEXTBOXES[i].b.isHoveredOver = false;
}
}
} | 6 |
public void run ()
{
while (dir != null) {
// No matter how we learn that something may have
// changed, we do the same thing to figure out
// exactly what changed: scan usbdevfs
while (scan ())
continue;
// FIXME: add native support to poll() on
// /proc/bus/usb/devices ...
try { Thread.sleep (POLL_PERIOD * 1000); }
catch (InterruptedException e) {
// set dir to null to cause a clean exit
}
}
} | 3 |
public synchronized int[] aaNumber2Pos() {
if (aa2pos != null) return aa2pos;
calcCdsStartEnd();
aa2pos = new int[protein().length()];
for (int i = 0; i < aa2pos.length; i++)
aa2pos[i] = -1;
int cdsMin = Math.min(cdsStart, cdsEnd);
int cdsMax = Math.max(cdsStart, cdsEnd);
// For each exon, add CDS position to array
int aaBaseNum = 0;
for (Exon exon : sortedStrand()) {
int min = isStrandPlus() ? exon.getStart() : exon.getEnd();
int step = isStrandPlus() ? 3 : -3;
for (int pos = min; exon.intersects(pos) && aaBaseNum < aa2pos.length; pos += step)
if ((cdsMin <= pos) && (pos <= cdsMax)) aa2pos[aaBaseNum++] = pos;
}
return aa2pos;
} | 9 |
private void connectVoice() {
RtmpReader reader = null;
RtmpWriter writer = null;
if (audioFilename != null && audioFilename.length() > 0) {
if (sendAudio) {
try {
reader = new FlvReader(audioFilename);
} catch (Exception e) {
e.printStackTrace();
log.error("Can't create a FlvReader instance for " + audioFilename);
}
} else if (recordAudio) {
try {
writer = new LimitedSizeFlvWriter(audioFilename, audioSampleSize);
} catch (Exception e) {
e.printStackTrace();
log.error("Can't create a FlvWriter instance for " + audioFilename);
}
}
}
voiceConnection = new BbbVoiceConnection(this, reader, writer) {
private void reconnect() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// do nothing, just return
return;
}
voiceConnection.start();
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
super.channelDisconnected(ctx, e);
if (!disconnected_myself) {
log.error("{} has dropped from the voice conference, reconnecting to {}", name, getJoinService().getApplicationService().getServerUrl());
reconnect();
}
}
@Override
protected void onConnectedUnsuccessfully() {
if (!disconnected_myself) {
log.error("The voice connection of {} to {} was unsucceeded, trying one more time", name, getJoinService().getApplicationService().getServerUrl());
reconnect();
}
}
};
voiceConnection.setListenOnly(listenOnly);
voiceConnection.setLoop(true);
voiceConnection.start();
} | 9 |
private void notifyObservers(Roll roll) {
for (Observer o : observers) {
o.updateObserver(this, roll);
}
} | 1 |
public void reset() {
this.state = State.DEFAULT;
} | 0 |
public static String humanReadableBytes(long bytes, boolean si)
{
// This algorithm doesn't like negatives
boolean positive = true;
if(bytes < 0)
{
bytes = -bytes;
positive = false;
}
// Figure out if we're using powers of 2 (non-SI) or 10 (SI)
int unit = si ? 1000 : 1024;
if(bytes < unit)
{
if(positive)
{
return bytes + " B";
}
else
{
return "-" + bytes + " B";
}
}
// Figure out the unit being used
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
// Return as a formatted string
String result = String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
if(!positive)
{
result = "-" + result;
}
return result;
} | 7 |
public void ron(String[] split, String command)
{
if (split.length != 6)
{
PrintMessage("Syntax:!ron [game] [winner] [hou] [han|y|dy] [loser]");
return;
}
TournyGame m = (TournyGame) games.get(split[1]);
if (m == null)
{
PrintMessage(split[1] + " is not a valid game");
return;
}
String p = split[2];
String p2 = split[5];
if (!m.exists(new String[]
{ p, p2 }))
{
return;
}
try
{
int hou = new Integer(split[3]);
if (split[4].equalsIgnoreCase("y"))
m.ron(p, p2, hou, -1);
else if (split[4].equalsIgnoreCase("dy"))
m.ron(p, p2, hou, -2);
else
{
int han = new Integer(split[4]);
m.ron(p, p2, hou, han);
}
} catch (NumberFormatException e)
{
PrintMessage("Syntax:!ron [game] [winner] [hou] [han|y|dy] [loser]");
return;
}
m.update();
m.printnextround();
m.updatedetail(command);
} | 6 |
public void rotACW()
{
forme.rotACW();
} | 0 |
private float[] toCmyk(float[] colorvalue) {
float y = colorvalue[0], cb = colorvalue[1], cr = colorvalue[2], k = colorvalue[3];
float[] cmyk = new float[4];
float v;
v = (float) (1.0 - (y + 1.402 * (cr - 0.5)));
cmyk[0] = v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v);
v = (float) (1.0 - (y - 0.34414 * (cb - 0.5) - 0.71414 * (cr - 0.5)));
cmyk[1] = v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v);
v = (float) (1.0 - (y + 1.772 * (cb - 0.5)));
cmyk[2] = v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v);
cmyk[3] = k;
return cmyk;
} | 6 |
public static void inicializar(String repositoryType){
switch(repositoryType){
case "array":
compras = new ManagerCompras(comprasArray);
contas = new ManagerConta(contasArray);
servicos = new ManagerServico(servicosArray);
break;
case "arquivo":
String pathname = "planilha.xls"; //Guarda o caminho relativo ate a planilha.
File file = new File(pathname);
POIFSFileSystem fs;
InputStream inputStream = null;
try
{
if(file.exists()){
inputStream = new FileInputStream (pathname); //Cria um InputStream e seta o WorkBook.
fs = new POIFSFileSystem(inputStream);
wb = new HSSFWorkbook(fs);
contasArquivo = new RepositorioContasArquivo(wb);
contas = new ManagerConta(contasArquivo);
comprasArquivo = new RepositorioCompraArquivo(wb);
compras = new ManagerCompras(comprasArquivo);
servicosArquivo = new RepositorioServicoArquivo(wb);
servicos = new ManagerServico(servicosArquivo);
}else{
file.createNewFile(); //Cria o arquivo planilha.xls.
inputStream = new FileInputStream (new File("planilha.xls"));
FileOutputStream output = new FileOutputStream(new File(pathname));
wb = new HSSFWorkbook(); //Seta o novo workBook e as workSheets padrao.
wb.createSheet("contas");
wb.createSheet("compras");
wb.createSheet("servicos");
wb.write(output);
contasArquivo = new RepositorioContasArquivo(wb);
contas = new ManagerConta(contasArquivo);
comprasArquivo = new RepositorioCompraArquivo(wb);
compras = new ManagerCompras(comprasArquivo);
servicosArquivo = new RepositorioServicoArquivo(wb);
servicos = new ManagerServico(servicosArquivo);
}
}
catch (FileNotFoundException e)
{
System.out.println ("File not found in the specified path.");
e.printStackTrace ();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close(); //Fechamos um input para utilizarmos o output.
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream stream = null;
try {
stream = new FileOutputStream("planilha.xls");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
wb.write(stream); //Executar as modificacoes de fato.
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
case "lista": //IF HE CHOOSES TO USE LISTS INSTEAD.
RepositorioComprasLista comprasLista = new RepositorioComprasLista();
RepositorioContasLista contasLista = new RepositorioContasLista();
RepositorioServicoLista servicosLista = new RepositorioServicoLista();
compras = new ManagerCompras(comprasLista);
contas = new ManagerConta(contasLista);
servicos = new ManagerServico(servicosLista);
break;
}
} | 9 |
public void saveProjectFile(String statFilePath) {
Element stat = new Element("stat");
Document statDoc = new Document(stat);
//load meta-data elements
Element metaDataElement = new Element("metadata");
for (String attrib : METADATA_ATTRIBS) {
String value = metaData.get(attrib);
if (value != null && !value.isEmpty()) {
metaDataElement.addContent(new Element(attrib).setText(value));
}
}
statDoc.getRootElement().addContent(metaDataElement);
//load stakeholders
Element stakeholdersElement = new Element("stakeholders");
for (Stakeholder stakeHolder : stakeholders.values()) {
Element stakeholderElement = new Element("stakeholder");
Map<String, String> tempAttribs = stakeHolder.getAttributes();
for (String attrib : STAKEHOLDER_ATTRIBS) {
String value = tempAttribs.get(attrib);
if (value != null && !value.isEmpty()) {
stakeholderElement.addContent(new Element(attrib).setText(value));
}
}
//load influences for this stakeholder
Element influencesElement = new Element("influences");
ArrayList<Relationship> influences = stakeHolder.getInfluences();
for (Relationship relationship : influences) {
Element influenceElement = new Element("influence");
influenceElement.addContent(new Element("id").setText(relationship.getName()));
influenceElement.addContent(new Element("strength").setText(String.valueOf(relationship.getMagnitude())));
influencesElement.addContent(influenceElement);
}
stakeholderElement.addContent(influencesElement);
stakeholdersElement.addContent(stakeholderElement);
}
statDoc.getRootElement().addContent(stakeholdersElement);
XMLOutputter statOutput = new XMLOutputter(Format.getPrettyFormat());
try {
statOutput.output(statDoc, new FileWriter(statFilePath));
} catch (IOException ex) {
ex.printStackTrace();
}
} | 9 |
private static void drawRightToLeft(Graphics g, LivingEntity e, int x, int y, int size) {
float ratio = tex.bar[0].getWidth() / (float)e.getMaxHP();
int sizeX = tex.frame[0].getWidth() * size;
g.drawImage(tex.frame[3], x - sizeX, y, sizeX, tex.frame[0].getHeight() * size, null);
int color;
if (e.getHP() > e.getMaxHP() * 0.40) {
color = 2;
} else if (e.getHP() > e.getMaxHP() * 0.25) {
color = 3;
} else if (e.getHP() > e.getMaxHP() * 0.10) {
color = 4;
} else {
color = 5;
}
int barX = x - sizeX + (28 * size);
if (e.getHP() > 0) g.drawImage(tex.bar[color], barX + (int)(ratio * (e.getMaxHP() - e.getHP())) * size, y + 10 * size, (int)(ratio * e.getHP()) * size, tex.bar[2].getHeight() * size, null);
ratio = tex.bar[0].getWidth() / (float)e.getMaxAir();
if (e.getAir() > 0) g.drawImage(tex.bar[0], barX + (int)(ratio * (e.getMaxAir() - e.getAir())) * size, y + 16 * size, (int)(ratio * e.getAir()) * size, tex.bar[2].getHeight() * size, null);
g.drawImage(tex.frame[4], x - sizeX, y, sizeX, tex.frame[1].getHeight() * size,null);
g.drawImage(tex.frame[5], x - sizeX, y, sizeX, tex.frame[2].getHeight() * size, null);
e.getAvatar().drawAnimation(g, x - (30 * size), y, 32 * size, 32 * size);
} | 5 |
private void asignarFitness() {
//Marcar la poblacion como no dominada
for (Individuo ind : poblacion) {
ind.setDominado(false);
}
int frentes = 0; // cuenta de frentes
double df = (double) qap.getN(); // dummyFitness para la poblacion inicial
List<Individuo> poblacionaux = new ArrayList<Individuo>();
poblacionaux.addAll(poblacion); //poblacionaux para sacar individuos
while (!poblacionaux.isEmpty()) {
frentes++;
for (int i = 0; i < poblacionaux.size(); i++) {
for (int j = 0; j < poblacionaux.size(); j++) {
//comparar los individuos
if ((i != j)
&& dominaA(poblacionaux.get(j), poblacionaux.get(i))) {
poblacionaux.get(i).setDominado(true);
break;
}
}
}
// sacar todos los individuos no dominados
List<Individuo> frentePareto = new ArrayList<Individuo>();
for (Individuo ind : poblacionaux) {
//boolean b = ind.isDominado();
if (!ind.isDominado()) {
//asignarles el dummyFitness
ind.setFitness((double) df);
frentePareto.add(ind);
}
}
fitnessSharing(frentePareto);
// df para el siguiente frente
df = siguienteDF(frentePareto);
removerDePoblacion(poblacionaux, frentePareto);
for (Individuo ind : poblacionaux) {
ind.setDominado(false);
}
}
} | 9 |
public static Map<String, Class<?>> propertyMap(Class<?> baseClass) {
Map<String, Class<?>> map = new HashMap<String, Class<?>>();
Method[] methods = baseClass.getMethods();
for (Method method : methods) {
String name = method.getName();
if (name.startsWith("get")) {
if (!name.equals("getClass")) {
String shortName = name.substring(3, 4).toLowerCase(Locale.ENGLISH) + name.substring(4);
map.put(shortName, method.getReturnType());
}
} else if (name.startsWith("is")) {
String shortName = name.substring(2, 3).toLowerCase(Locale.ENGLISH) + name.substring(3);
map.put(shortName, method.getReturnType());
}
}
return map;
} | 8 |
public ArrayList<Integer> AllEmpIDInFranchise(int FranID)
throws UnauthorizedUserException, BadConnectionException, DoubleEntryException
{
/* Variable Section Start */
/* Database and Query Preperation */
PreparedStatement statment = null;
ResultSet results = null;
String statString = "SELECT * FROM `employee` WHERE 'EmployeeID' = ?";
/* Return Parameter */
ArrayList<Integer> BPList = new ArrayList<Integer>();
/* Variable Section Stop */
/* TRY BLOCK START */
try
{
/* Preparing Statment Section Start */
statment = con.prepareStatement(statString);
statment.setInt(1, FranID);
/* Preparing Statment Section Stop */
/* Query Section Start */
results = statment.executeQuery();
/* Query Section Stop */
/* Metadata Section Start*/
//ResultSetMetaData metaData = results.getMetaData();
/* Metadata Section Start*/
/* List Prepare Section Start */
while (results.next())
{
int temp = 0;
//rs.getBigDecimal("AMOUNT")
temp = results.getInt("EmployeeID");
BPList.add(temp);
}
/* List Prepare Section Stop */
}
catch(SQLException sqlE)
{
if(sqlE.getErrorCode() == 1142)
throw(new UnauthorizedUserException("AccessDenied"));
else if(sqlE.getErrorCode() == 1062)
throw(new DoubleEntryException("DoubleEntry"));
else
throw(new BadConnectionException("BadConnection"));
}
finally
{
try
{
if (results != null) results.close();
}
catch (Exception e) {};
try
{
if (statment != null) statment.close();
}
catch (Exception e) {};
}
/* TRY BLOCK STOP*/
/* Return to Buisness Section Start */
return BPList;
/* Return to Buisness Section Start */
} | 8 |
public static void main(String[] args) throws D2S_ModuleException, D2S_ModuleParameterException {
if (args.length < 3) {
System.out
.println("\nModuleWrapper\n" +
"Please use the following arguments: \n" +
"[1] - The Java Class that is your module (use the full package path)" +
"[2] - RDF file containing the data your module must run on.\n" +
"[3] - The named graph URI in that file that contains the actual data (use 'default' for no graph).\n" +
"[4] - The URI of a specific resource in the file."
);
return;
}
String moduleName = args[0];
String fileName = args[1];
String graph = args[2];
String resource = args[3];
D2S_AbstractModule module = constructModule(moduleName, fileName, graph,
resource);
log.info("Starting module");
Repository outputRepository = module.start();
log.info("Module run completed");
// TODO Add provenance information about ModuleWrapper run
String outputFileName = "output.n3";
try {
log.info("Starting RepositoryWriter (writing to output.n3)");
FileOutputStream outputStream = new FileOutputStream(new File(
outputFileName));
OutputStreamWriter streamWriter = new OutputStreamWriter(
outputStream);
D2S_RepositoryWriter rw = new D2S_RepositoryWriter(outputRepository,
streamWriter);
rw.write();
log.info("Done");
}
catch (FileNotFoundException e) {
log.error("Failed to create output file " + outputFileName);
}
} | 2 |
public void make_pivot_hier(node head){
// stop if so less than OUTLIERS_SIZE objects present
if(head.list_objects.size() < PIVOT_SIZE_TOTAL){
//add all children to the children and return
for(finger_print f: head.list_objects){
head.children.add(new node(f));
}
//System.out.println("XX "+head.list_objects.size());
return;
}
ArrayList<node> pivot_lst= new ArrayList<node>();
Random r= new Random();
// choose pivots
// has to be done better
//remove for non sampling
int maxsize=Math.max(PIVOT_SIZE_TOTAL,(int)(0.001*head.list_objects.size()));
ArrayList<Integer> num= new ArrayList<Integer>();
for(int k=0;k<maxsize;k++){
int l=r.nextInt(head.list_objects.size());
while(num.contains(l)){
l=r.nextInt(head.list_objects.size());
}
num.add(l);
}
for(int i=0;i<PIVOT_SIZE_TOTAL;i++){
//choose random
//int j=r.nextInt(head.list_objects.size());
//choose far away points
int j=get_farthest_sampling(head.list_objects,pivot_lst,num);
//without sampling
//int j=get_farthest(head.list_objects,pivot_lst);
/*then the same*/
pivot_lst.add(new node(head.list_objects.get(j)));
head.list_objects.remove(j);
}
// set closest pivot
for(finger_print p : head.list_objects){
p.set_sim_pivot(pivot_lst);
p.closest_pivot.set_object(p);
}
// set the children to pivot_lst
head.children=pivot_lst;
//recursive call
for(node pivot : pivot_lst){
make_pivot_hier(pivot);
}
return;
} | 7 |
private void connectVerbInstanceBaseToFeatures() {
for (int CA = 0; CA < getSize() / vInstCASize; CA++) {
for (int baseNeuron = 0; baseNeuron < 40; baseNeuron++) {
for (int feature = 0; feature < 13; feature++) {
int fromNeuron = baseNeuron + (CA * vInstCASize);
for (int synapse = 0; synapse < 5; synapse++) {
int toNeuron = ((baseNeuron / 5) * 5) % 20; // 0,5,10,15
toNeuron += synapse + 40 + (feature * 20);
toNeuron += (CA * vInstCASize);
if (feature == 5)
addConnection(fromNeuron, toNeuron, 0.30);
// skip obj, loc, inst and act done
else if ((feature != 1) && (feature != 2) && (feature != 3)
&& (feature != 11))
addConnection(fromNeuron, toNeuron, 0.15);
}
}
}
}
} | 9 |
public boolean isBestMovebidiDLS(Site node, Site target, int depth) {
if(depth >= 0) {
boolean worked = true;
for(Site tChild: graph.neighbors(target)) //base case
worked = worked && graph.neighbors(node).contains(tChild);
if(worked) return worked;
else {
for(Site nChild: graph.neighbors(node)) {
boolean worked2= true;
for(Site tChild: graph.neighbors(target)) {
boolean temp= isBestMovebidiDLS(nChild, tChild, depth-1);
if(!temp) {
worked2= temp;
break;
}
}
if(worked2) return worked2;
}
}
}
return false;
} | 8 |
private boolean jj_3_80() {
if (jj_scan_token(NO)) return true;
return false;
} | 1 |
public static int characterSize(int character) throws JSONException {
if (character < 0 || character > 0x10FFFF) {
throw new JSONException("Bad character " + character);
}
return character <= 0x7F ? 1 : character <= 0x3FFF ? 2 : 3;
} | 4 |
@Override
public void analysis() {
int halfOfWidth = this.currentWidth / 2;
/*if (controlPoints.get(currentControlPointToReach).getY() < currentCoord.getY()) {
System.out.println("jumping");
setHeroOwnVerticalSpeed(-OWN_VERTICAL_SPEED);
}*/
if ((controlPoints.get(currentControlPointToReach).getX() > currentCoord.getX() + halfOfWidth) && (movingRight)) {
setHeroOwnHorizontalSpeed(OWN_HORIZONTAL_SPEED);
} else if ((controlPoints.get(currentControlPointToReach).getX() < currentCoord.getX() + halfOfWidth) && (!movingRight)) {
setHeroOwnHorizontalSpeed(-OWN_HORIZONTAL_SPEED);
} else {
if (movingPositiveDirection) {
if (currentControlPointToReach < controlPoints.size() - 1) {
currentControlPointToReach++;
movingRight = this.currentCoord.getX() < controlPoints.get(currentControlPointToReach).getX();
} else {
setHeroOwnHorizontalSpeed(0);
movingPositiveDirection = false;
currentControlPointToReach--;
movingRight = this.currentCoord.getX() < controlPoints.get(currentControlPointToReach).getX();
}
} else {
if (currentControlPointToReach > 0) {
currentControlPointToReach--;
movingRight = this.currentCoord.getX() < controlPoints.get(currentControlPointToReach).getX();
} else {
setHeroOwnHorizontalSpeed(0);
movingPositiveDirection = true;
currentControlPointToReach++;
movingRight = this.currentCoord.getX() < controlPoints.get(currentControlPointToReach).getX();
}
}
}
//System.out.println(currentControlPointToReach + " " + movingRight);
} | 7 |
private int sweep() {
int nDeallocated = 0;
long pos;
gcDone = true;
for (int i = dbFirstUserId, j = committedIndexSize; i < j; i++) {
pos = getGCPos(i);
if (pos != 0
&& ((int) pos & (dbPageObjectFlag | dbFreeHandleFlag)) == 0) {
int bit = (int) (pos >>> dbAllocationQuantumBits);
if ((blackBitmap[bit >>> 5] & (1 << (bit & 31))) == 0) {
// object is not accessible
if (getPos(i) == pos) {
int offs = (int) pos & (Page.pageSize - 1);
Page pg = pool.getPage(pos - offs);
int typeOid = ObjectHeader.getType(pg.data, offs);
if (typeOid != 0) {
ClassDescriptor desc = findClassDescriptor(typeOid);
nDeallocated += 1;
if (Btree.class.isAssignableFrom(desc.cls)) {
Btree btree = new Btree(pg.data,
ObjectHeader.sizeof + offs);
pool.unfix(pg);
btree.assignOid(this, i, false);
btree.deallocate();
}
else {
int size = ObjectHeader.getSize(pg.data, offs);
pool.unfix(pg);
freeId(i);
objectCache.remove(i);
cloneBitmap(pos, size);
}
if (listener != null) {
listener.deallocateObject(desc.cls, i);
}
}
}
}
}
}
greyBitmap = null;
blackBitmap = null;
allocatedDelta = 0;
gcActive = false;
if (listener != null) {
listener.gcCompleted(nDeallocated);
}
return nDeallocated;
} | 9 |
protected void addWallObject(int x, int y, int z, int drawHeight,
int orientation, int orientation2, int uid, Animable renderable,
Animable renderable2, byte objConf) {
if (renderable == null && renderable2 == null)
return;
WallObject wallObject = new WallObject();
wallObject.uid = uid;
wallObject.objConf = objConf;
wallObject.x = x * 128 + 64;
wallObject.y = y * 128 + 64;
wallObject.z = drawHeight;
wallObject.renderable = renderable;
wallObject.renderable2 = renderable2;
wallObject.orientation = orientation;
wallObject.orientation2 = orientation2;
for (int _z = z; _z >= 0; _z--)
if (groundArray[_z][x][y] == null)
groundArray[_z][x][y] = new Ground(_z, x, y);
groundArray[z][x][y].wallObject = wallObject;
} | 4 |
public ArrayList<Double> barHeight() {
ArrayList<Double> values;
values = A;
ArrayList<Double> barDimen = new ArrayList<Double>(); //Convert to ArrayList
double numBars = n;
double sum = 0; //Sum of values
//double classNum = 0; //Number of classes: sum of values divided by number of bars
//ArrayList<Double> clone = (ArrayList<Double>)values.clone(); //works if all values are consecutive
//Collections.sort(clone); //couldnt just sort the values, caused some lcl ucl values to encapsulate a larger amount of values than other classes
ArrayList<Double> clone = new ArrayList<Double>();
for(int i = 0; i < values.size();i++)//creates consecutive values that can be used for calculating amount of values for each class
{
clone.add((double)i);
}
int[] width = new int[(int)numBars];//holds the sizes that each class can hold
double lower = 0;
double w = barWidth(lower, values.size(), numBars);
double upper = lower + w;
double last = -1;
//Calculates the amount of values to place into each bin (class)
for (int i = 0; i < width.length; i++) {
//System.out.println("i: " + i);
for (int j = 0; j < clone.size(); j++) {
//System.out.println("j " + j);
if (clone.get(j) >= lower && clone.get(j)<= upper) {
if (clone.get(j) == last) {}
else {
width[i]++;
last = clone.get(j);
}//end else
}//end if
}//end for
lower+= w;
upper+= w;
}//end for
//End of Calculating amount of values for each bin
int count = 0;
for (int i = 0; i < width.length; i++) {
for(int j = 0; j < width[i]; j++)
{
sum += values.get(count);
//System.out.println("Class Number " + i + " value "+ j +":\t" + values.get(count)+ "\t+=\t"+sum);//for testing
count++;
}
//System.out.println("BarHeight["+i+"]:\t" + sum); //for testing
//classNum = sum/width[i]; //The average value for the class
//barDimen.add(classNum);
barDimen.add(sum); //all values in class summed together
sum = 0;
}
return barDimen;
} | 8 |
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MongoCredential that = (MongoCredential) o;
if (mechanism != null ? !mechanism.equals(that.mechanism) : that.mechanism != null) {
return false;
}
if (!mechanismProperties.equals(that.mechanismProperties)) {
return false;
}
if (!Arrays.equals(password, that.password)) {
return false;
}
if (!source.equals(that.source)) {
return false;
}
if (!userName.equals(that.userName)) {
return false;
}
return true;
} | 9 |
public void mouseEntered(MouseEvent e) {
if (!b.isEnabled()) return;
if (b instanceof javax.swing.JToggleButton && b.isSelected())
return;
b.setBorder(raised);
b.setBorderPainted(true);
} | 3 |
public boolean rmNode(final Node n) {
synchronized (nodes) {
if (nodes.containsKey(n.getRemoteAddress())) {
nodes.remove(n.getRemoteAddress());
addresses.remove(n.getRemoteAddress());
if (nodes.size() == 0 && closeIfEmpty) {
close();
}
return true;
} else {
return false;
}
}
} | 3 |
public int searchEdgesToSetNull(Edge[] list, Vertex in, Vertex out, int index){
int edgePos = -1;
for(int i = 0;i < numEdges; i++){
if(list[i]!=null && list[i].inVertex != null && list[i].outVertex != null){
//checking for exact match with an edge
//System.out.println("***** List[i]:: "+list[i].inVertex.name +" - "+list[i].outVertex.name);
if(((list[i].inVertex.name.equalsIgnoreCase(in.name))//|| list[i].inVertex.name.contains(in.name)
&& (list[i].outVertex.name.equalsIgnoreCase(out.name))) || //|| list[i].outVertex.name.contains(out.name)
((list[i].inVertex.name.equalsIgnoreCase(out.name))//|| list[i].inVertex.name.contains(out.name)
&& (list[i].outVertex.name.equalsIgnoreCase(in.name)))){//|| list[i].outVertex.name.contains(in.name)
//System.out.println("***** Found edge! : index::"+index+"list[i].index::"+list[i].index);
//if an edge was found
edgePos = i;//returning its position in the array
//INCREMENT FREQUENCY IF THE EDGE WAS FOUND IN A DIFFERENT SENT. (CHECK BY MAINTAINING A TEXT NUMBER AND CHECKING IF THE NEW # IS DIFF FROM PREV #)
if(index != list[i].index){
list[i].frequency++;
}
//System.out.println(list[i].inVertex.name+" - "+list[i].outVertex.name+" freq:: "+list[i].frequency);
//System.out.println(in.name+" - "+out.name+" freq:: "+list[i].frequency);
}
}
}
// System.out.println("***** searchEdgesToSetNull:: "+in.name +" - "+out.name+" returning:: "+edgePos);
return edgePos;
} | 9 |
private static byte[] encode3to4(byte[] source, int srcOffset,
int numSigBytes, byte[] destination, int destOffset, byte[] alphabet) {
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index alphabet
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff =
(numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)
| (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
| (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
switch (numSigBytes) {
case 3:
destination[destOffset] = alphabet[(inBuff >>> 18)];
destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = alphabet[(inBuff) & 0x3f];
return destination;
case 2:
destination[destOffset] = alphabet[(inBuff >>> 18)];
destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
case 1:
destination[destOffset] = alphabet[(inBuff >>> 18)];
destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = EQUALS_SIGN;
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4 | 6 |
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage:\njava TestRegularExpression "
+ "characterSequence regularExpression+");
System.exit(0);
}
System.out.println("Input: \"" + args[0] + "\"");
for (String arg : args) {
System.out.println("Regular expression: \"" + arg + "\"");
Pattern p = Pattern.compile(arg);
Matcher m = p.matcher(args[0]);
while (m.find()) {
System.out.println("Match \"" + m.group() + "\" at positions "
+ m.start() + "-" + (m.end() - 1));
}
}
} | 3 |
public String getName() {
return name;
} | 0 |