method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
797780fc-81ba-4eae-a0cd-00a2c687dcac | 0 | public int getMalesCount() {
return getGenderCount(Gender.MALE);
} |
fdf6ece0-d167-4e24-91da-7a4b748e5ee3 | 8 | private static void fillArray( final String s1,
final String s2,
final SubstitutionMatrix sm,
final float gapPenalty,
final int affinePenalty,
final boolean noPenaltyForBeginningOrEndingGaps,
final AlignmentCell[][] cels )
throws Exception
{
cels[0][0] = new AlignmentCell(START, 0);
if( noPenaltyForBeginningOrEndingGaps )
{
for( int x=1; x <= s1.length(); x++)
cels[x][0] = new AlignmentCell(LEFT, 0);
for( int x=1; x <= s2.length(); x++)
cels[0][x] = new AlignmentCell(UP, 0);
}
else if( affinePenalty > 0) // linear gap
{
final CountDownLatch cdl1 = new CountDownLatch(2);
new Thread( new Runnable()
{
@Override
public void run()
{
for( int x=1; x <= s1.length(); x++)
cels[x][0] = new AlignmentCell(LEFT, x * gapPenalty );
cdl1.countDown();
}
}).start();;
new Thread(
new Runnable()
{
@Override
public void run()
{
for( int x=1; x <= s2.length(); x++)
cels[0][x] = new AlignmentCell(UP, x * gapPenalty);
cdl1.countDown();
}
}).start();;
cdl1.await();
}
else
{
cels[1][0] = new AlignmentCell(LEFT, gapPenalty);
for( int x=2; x <= s1.length(); x++)
cels[x][0] = new AlignmentCell(LEFT, gapPenalty + x * affinePenalty);
cels[0][1] = new AlignmentCell(UP, gapPenalty);
for( int x=2; x <= s2.length(); x++)
cels[0][x] = new AlignmentCell(UP, gapPenalty + x * affinePenalty);
}
Semaphore semaphore = new Semaphore(2);
AtomicInteger lastX = new AtomicInteger(1);
AtomicInteger lastY = new AtomicInteger(1);
AlignmentCell cel = getACel(1, 1, affinePenalty, cels, gapPenalty, sm, s1, s2);
cels[1][1] = cel;
semaphore.acquire();
semaphore.acquire();
new Thread(new RunAStrip(
affinePenalty, gapPenalty, cels, s1, s2, sm, semaphore,
true, lastX, lastY)).start();
new Thread(new RunAStrip(
affinePenalty, gapPenalty, cels, s1, s2, sm, semaphore,
false, lastX, lastY)).start();
// wait for both threads to finish
semaphore.acquire();
semaphore.acquire();
synchronized(cels) {}; // make visible all our published changes to this thread
} |
a1b8ef11-c005-463c-ad69-f9fdba58830b | 5 | private static int calculate(final Collection<Rotation4D> group,
final Collection<Rotation4D> arg1, final Collection<Rotation4D> arg2,
final Collection<Rotation4D> dist) {
int newElems = 0;
Rotation4D z;
for (Rotation4D x : arg1) {
for (Rotation4D y : arg2) {
z = x.nextRotation(y);
if (!group.contains(z) && !arg1.contains(z) && !arg2.contains(z)) {
dist.add(z);
newElems++;
}
}
}
return newElems;
} |
b78a2eb7-3885-4c3f-bc5e-03a67e480076 | 1 | public void visitTableSwitchInsn(final int min, final int max,
final Label dflt, final Label[] labels) {
if (mv != null) {
mv.visitTableSwitchInsn(min, max, dflt, labels);
}
execute(Opcodes.TABLESWITCH, 0, null);
this.locals = null;
this.stack = null;
} |
beaacf04-ac01-4c80-8b9b-4c9e2ffef5e8 | 3 | @SafeVarargs
public CommandHandler(P plugin, String defaultLabel, int pageCommands, AbstractCommand<P>... commands) throws IllegalArgumentException {
this.plugin = plugin;
this.defaultLabel = defaultLabel;
this.commands = new LinkedHashMap<String, AbstractCommand<P>>();
for (AbstractCommand<P> command : commands) {
String name = command.getName();
if (this.commands.containsKey(name) || name.equals("help")) {
throw new IllegalArgumentException("Duplicate command names");
}
this.commands.put(name, command);
}
this.commands.put("help", new HelpCommand(this, pageCommands));
} |
1f78f170-296b-4a6b-a3f8-5de0699dc65a | 0 | @After
public void tearDown() {
} |
1ee9007b-642c-4632-9e3e-7f65f0058d94 | 2 | @Override
public void onTestUserKeyChanged(String userKey) {
BmTestManager bmTestManager = BmTestManager.getInstance();
boolean isUserKeyValid = bmTestManager.isUserKeyValid();
if (signUpButton.isVisible()) {
signUpButton.setEnabled(!(userKey.matches(Constants.USERKEY_REGEX) & isUserKeyValid));
}
if (isUserKeyValid) {
HashMap<String, Object> applyNotificationTo = new HashMap<String, Object>();
applyNotificationTo.put(TestListNotification.TEST_ID_COMBOBOX, testIdComboBox);
applyNotificationTo.put(TestListNotification.MAIN_PANEL, mainPanel);
applyNotificationTo.put(TestListNotification.CLOUD_PANEL, cloudPanel);
ITestListReceivedNotification testListNotification = new TestListNotification(applyNotificationTo, true);
TestListController.setNotification(testListNotification);
bmTestManager.getUsers(true);
} else {
TestInfoController.stop();
}
} |
ff016f2d-bd32-46dc-9887-9fed826da143 | 2 | @Override
public String getDescription() {
if (descriptionValue == null || isEmpty(descriptionValue.getText())) {
return "";
}
return descriptionValue.getText();
} |
a629fa93-bad3-41b4-a465-fa65b12b0a47 | 3 | void integer_operation(int[][] A, int[][] B, int[][] C)
{
for(int i=0;i<cnt;i++)
{
for(int j=0;j<cnt;j++)
{
C[i][j] = 0;
for(int k=0;k<cnt;++k)
{
C[i][j]+=A[i][k]+B[k][j];
}
}
}
} |
d11ab46e-4823-4fb5-869b-4463454b5256 | 9 | @Override
protected boolean isValidNonDropMove(GameState state, int x, int y) {
/* Begins by verifying if a move is within the range of the board.
* Then verifies if a move is on one of the diagonals (the change in x equals the change in y).
* Then it checks to see if all tile on the way to the target tile is empty.
* Finally, it check whether the target tile can be landed on.
*/
int dx = x - this.x;
int dy = y - this.y;
boolean validMove = !(x < 0 || x > 8) && !(y < 0 || y > 8);
if (validMove && Math.abs(dx) == Math.abs(dy) && dy != 0) {
for (int i = 1; validMove && i < Math.abs(dy); i++) {
validMove = state.getPieceAt(this.x+i*((int)Math.signum(dx)), this.y+i*((int)Math.signum(dy))) instanceof EmptyPiece;
}
if (validMove) {
validMove = state.getPieceAt(x, y).getAllegiance() != this.allegiance;
}
} else {
validMove = false;
}
return validMove;
} |
0f2e285e-5575-4612-bcac-7683e6788686 | 6 | public Node reverseAlter2KNodes(Node head, int k){
//process 2K nodes at a time
//reverse till k nodes and set the the pointer to k+1
int x = k;
Node moving = head;
Node head_prev = null;
Node head_next = null;
while(x>0 && moving!=null){
head_next = moving.next;
moving.next = head_prev;
head_prev = moving;
moving = head_next;
x--;
}
if(head!=null)
head.next = moving;
x =k;
while(x>1 && moving!=null){
moving = moving.next;
x--;
}
if(moving!=null){
moving.next = reverseAlter2KNodes(moving.next,k);
}
return head_prev;
} |
bc61db7d-2bf5-4948-b6c8-a17465fe9c40 | 2 | public void computeSuplementalFactors() {
for (Entry<Float, float[][]> week : DB_ARRAY.entrySet()) {
float[][] weekNumber = week.getValue();
float[][][] techs = DB_PRICES.get(week.getKey());
float[][] sups = new float[weekNumber.length][];
for (int i = 0; i < weekNumber.length; i++) {
float[] suplementalFactors = new float[DBLabels.COMPUTED.length];
float[] fundies = weekNumber[i];
float[][] techies = techs[i];
suplementalFactors[0] = fundies[40] / fundies[41];
// compute all other suplementals
//
//
//
//
sups[i] = suplementalFactors;
}
DB_SUP.put(week.getKey(), sups);
}
} |
f2a48218-2f94-4f2e-a98e-19206b4e28e5 | 6 | public static int getArrayOrListLength(Object arrayOrList) {
if (arrayOrList == null) {
return 0;
}
Class<?> clazz = arrayOrList.getClass();
boolean isArray = ClassHelper.isTypeArray(clazz);
boolean isList = ClassHelper.isTypeList(clazz);
if (!isArray && !isList) {
throw new IllegalArgumentException("arrayOrList参数必须为数组或者List的实现类");
}
if(isArray) {
return getLength(arrayOrList);
} else {
return ((List<?>) arrayOrList).size();
}
} |
79e319df-da04-42cd-b9ec-00ea3b06640d | 7 | public void addHistory(String date, String name1, String name2, String score, String duration) throws IOException {
// Add a new record to the top of the log
String savedGame = date + "," + name1 + "," + name2 + "," + score + "," + duration;
String temp = "temp-history.csv";
String p = null;
BufferedReader br = null;
InputStream is = null;
InputStreamReader isr = null;
BufferedWriter bw = null;
try {
// Create temp file to combine old data with new record
if(historyFile.exists()){
// Read History log from generated file
br = new BufferedReader(new FileReader(historyFile));
}
else{
// Read History log from internal file
is = getClass().getResourceAsStream("/" + csvFileName);
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
}
bw = new BufferedWriter(new FileWriter(tempFile));
bw.write(savedGame);
bw.newLine();
while ((p = br.readLine()) != null ){
bw.write(p);
bw.newLine();
}
br.close();
bw.close();
// Overwrite old file with temp file contents
// is = getClass().getResourceAsStream("/" + temp);
// isr = new InputStreamReader(is);
// br = new BufferedReader(isr);
// System.out.println(new File("").getAbsolutePath() + "/res");
br = new BufferedReader(new FileReader(tempFile));
bw = new BufferedWriter(new FileWriter(historyFile));
p = null;
while ((p = br.readLine()) != null ){
bw.write(p);
bw.newLine();
}
br.close();
bw.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
// Reload the history data into memory
loadHistory();
} |
d5a71666-bf49-44fe-9779-5bac89146ed3 | 6 | private void threadroot() {
// this should be running the current thread
Lib.assertTrue(javaThread == Thread.currentThread());
if (!isFirstTCB) {
/* start() is waiting for us to wake it up, signalling that it's OK
* to context switch to us. We leave the running flag false so that
* we'll still run if a context switch happens before we go to
* sleep. All we have to do is wake up the current TCB and then
* wait to get woken up by contextSwitch() or destroy().
*/
currentTCB.interrupt();
this.yield();
}
else {
/* start() called us directly, so we just need to initialize
* a couple things.
*/
currentTCB = this;
running = true;
}
try {
target.run();
// no way out of here without going throw one of the catch blocks
Lib.assertNotReached();
}
catch (ThreadDeath e) {
// make sure this TCB is being destroyed properly
if (!done) {
System.out.print("\nTCB terminated improperly!\n");
privilege.exit(1);
}
runningThreads.removeElement(this);
if (runningThreads.isEmpty())
privilege.exit(0);
}
catch (Throwable e) {
System.out.print("\n");
e.printStackTrace();
runningThreads.removeElement(this);
if (runningThreads.isEmpty())
privilege.exit(1);
else
die();
}
} |
a5f0fb0a-ad66-4f78-bb3a-54e92e988e08 | 7 | private void playGame() {
// if second player then becomes backup server
if (gameState.getBackupServerID() == this.id) {
becomeBackupServer();
}
// play
while (!gameState.isGameOver()) {
curClock++;
int randSleep = rand.nextInt(PLAYER_MOVE_MAX_DELAY) + 1;
sleep(randSleep);
Direction dir = getRandomDirection();
try {
System.err.println("PLAYER: Sending move request no " + curClock + " to Primary Server (" + gameState.getPrimaryServerID() + ")");
gameState = gameState.getPrimaryServer().move(id, dir, curClock);
} catch (RemoteException e) {
System.err.println("PLAYER: Primary Server crashed");
try {
System.err.println("PLAYER: Redirecting move request no " + curClock + " to Backup Server (" + gameState.getBackupServerID() + ")");
gameState = gameState.getBackupServer().move(id, dir, curClock);
} catch (RemoteException ee) {
System.err.println("PLAYER: Primary and Backup Server not supposed to crash at the same time");
ee.printStackTrace();
System.exit(1);
}
}
System.err.println("PLAYER: Request " + curClock + " ACK'd");
if (PLAYER_PRINTS_STATES) {
System.err.println("PLAYER: Current game state:\n" + gameState + "\n");
}
// Backup server crashed and current player
// becomes new backup server
if (gameState.getBackupServerID() == this.id && !isBackupServer) {
becomeBackupServer();
}
}
} |
c7a4790f-493f-4baf-b5fd-1cdbacff57b1 | 6 | public void learn(double[] expectedOutputs) {
this.learningCycles++;
double sum = 0;
double error = 0;
double weight = 0;
//Last layer
int lastLayer = layers.length - 1;
for(int j = 0; j < layers[lastLayer].getSize(); j++) {
for(int k = 0; k < layers[lastLayer].getNeuron(j).getInputSize(); k++){
//Multiply by derivative of 1/(1+exp(-x))
double delta = layers[lastLayer].getNeuron(j).lastOutput() * (1 - layers[lastLayer].getNeuron(j).lastOutput()) * (expectedOutputs[j] - layers[lastLayer].getNeuron(j).lastOutput());
layers[lastLayer].getNeuron(j).setError(delta);
layers[lastLayer].getNeuron(j).setWeight(k, layers[lastLayer].getNeuron(j).getWeight(k) + learningRate * layers[lastLayer].getNeuron(j).getError() * layers[lastLayer].getNeuron(j).getLastInput(k));
}
}
//Other layers
for(int i = layers.length - 2; i >= 0; i--){
for(int j = 0; j < layers[i].getSize(); j++) {
//Get error
sum = 0;
for(int k = 0; k < layers[i+1].getSize(); k++){
error = layers[i+1].getNeuron(k).getError();
weight = layers[i+1].getNeuron(k).getWeight(j);
sum += error * weight;
}
for(int k = 0; k < layers[i].getNeuron(j).getInputSize(); k++){
//Multiply by derivative of 1/(1+exp(-x))
double delta = layers[i].getNeuron(j).lastOutput() * (1 - layers[i].getNeuron(j).lastOutput()) * sum;
layers[i].getNeuron(j).setError(delta);
layers[i].getNeuron(j).setWeight(k, layers[i].getNeuron(j).getWeight(k) + learningRate * layers[i].getNeuron(j).getError() * layers[i].getNeuron(j).getLastInput(k));
}
}
}
} |
f11a47e5-bc70-4661-9c62-a2bdd1f4da62 | 2 | private static Connection getConnection(){
String dbtime=null;
String dbUrl = "jdbc:mysql://your.database.domain/yourDBname";
String dbClass = "com.mysql.jdbc.Driver";
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection (dbUrl);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
} |
ed11714c-d807-406c-9883-393eecdd6cff | 3 | @Override
public int hashCode() {
int result;
long temp;
result = consignmentId;
result = 31 * result + (logTime != null ? logTime.hashCode() : 0);
temp = amount != +0.0d ? Double.doubleToLongBits(amount) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + employeeId;
result = 31 * result + (comment != null ? comment.hashCode() : 0);
return result;
} |
6cdcd988-459d-44ee-85eb-6b2730ba0748 | 9 | private void checkDirectoryListing(Path path, String[] expected_children,
boolean[] expected_kinds) {
// List the given directory.
String[] listing = null;
try {
listing = serviceStub.list(path);
} catch(Throwable t) {
t.printStackTrace();
Assert.fail("unable to list directory " + path);
}
if(listing == null) {
Assert.fail("listing directory " + path + " resulted in " +
"null");
}
// Compare the result of the list method and the set of expected
// children.
if(!TestUtil.sameElements(listing, expected_children)) {
Assert.fail("directory listing incorrect for " + path);
}
// Go through all the expected children. For each child, ensure that the
// isDirectory method returns the correct result.
for(int child_index = 0; child_index < expected_children.length;
++child_index) {
Path child_path = new Path(path, expected_children[child_index]);
boolean isDirectory = false;
try {
isDirectory = serviceStub.isDirectory(child_path);
} catch(Throwable t) {
t.printStackTrace();
Assert.fail("unable to determine if " + child_path +
" is a directory");
}
if(isDirectory && !expected_kinds[child_index]) {
Assert.fail(child_path + " is reported as a " +
"directory but is in fact a file");
}
if(!isDirectory && expected_kinds[child_index]) {
Assert.fail(child_path + " is reported as a file " +
"but is in fact a directory");
}
}
} |
5afbe7f6-f6e9-4694-a3c9-0a4df1031402 | 0 | public DecisionQuest() {
super(QuestType.DECISIONQUEST);
} |
f33f5f19-da04-42fe-b954-befb06bdf815 | 5 | public final Node state() {
synchronized (lock) {
final Node stateNode = this.current_node.get();
if (stateNode != null && stateNode.isAlive()) {
return null;
} else {
for (final Node state : nodes) {
if (state != null && state.activate()) {
return state;
}
}
}
return null;
}
} |
585335ff-d66c-4723-865f-aa34c6c0ac49 | 9 | private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
Funcionario f = new Funcionario();
if (!(txCodigo.getText().equals("") || ((txCodigo.getText().equals(null))))) {
f.setId(Integer.parseInt(txCodigo.getText()));
}
f.setNome(txNome.getText());
f.setTelefoneContato1(txTelefone1.getText());
f.setTelefoneContato2(txTelefone2.getText());
f.setEmail(txEmail.getText());
f.setCpf(txCpf.getText());
f.setRg(txRg.getText());
f.setSalario(Double.parseDouble(txSalario.getText()));
f.setCtps(txCtps.getText());
f.setSenha(txSenha.getText());
f.setLogin(txLogin.getText());
if (rbFeminino.isSelected()) {
f.setSexo("Feminino");
} else if (rbMasculino.isSelected()) {
f.setSexo("Masculino");
}
try {
String data = txDataNascimento.getText();
f.setDataNascimento(new SimpleDateFormat("dd/MM/yyyy").parse(data));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro ao converter data.");
}
try {
String data = txDataAdmissao.getText();
f.setDataAdimissao(new SimpleDateFormat("dd/MM/yyyy").parse(data));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro ao converter data.");
}
FuncionarioController fc = new FuncionarioController();
if (f.getId() == 0) {
int id = fc.salvar(f);
if (id > 0) {
modelo.addRow(new Object[]{id, f.getNome(), f.getCpf(), f.getSalario()});
JOptionPane.showMessageDialog(null, "Usuário cadastrado com sucesso");
}
} else {
int id = fc.salvar(f);
if (id > 0) {
modelo.removeRow(linhaSelecionada);
modelo.addRow(new Object[]{id, f.getNome(), f.getCpf(), f.getSalario()});
JOptionPane.showMessageDialog(null, "Usuário atualizado com sucesso");
}
}
// comando fechar janela
dispose();
}//GEN-LAST:event_btSalvarActionPerformed |
bcaa1135-08ec-49ab-bb44-9e0b7d20762f | 2 | public Matrix transpose() {
Matrix n = new Matrix();
for (int c = 0; c != 4; c++) {
for (int r = 0; r != 4; r++) {
n.set(c, r, get(r, c));
}
}
return n;
} |
5eba3908-684f-4bdf-8881-6f6be94ba1d7 | 4 | private static void downloadClient(){
try{
LauncherFrame.notificationLabel.setText("Download del client in corso ... 0%");
URL url = new URL(Settings.updateFile);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int filesize = connection.getContentLength();
float totalDataRead = 0;
BufferedInputStream in = new java.io.BufferedInputStream(connection.getInputStream());
FileOutputStream fos = new FileOutputStream(Util.getWorkingDirectory() + File.separator + "update.zip");
BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
byte[] data = new byte[1024];
int i = 0;
System.out.println("Downloading " + Settings.updateFile);
while ((i = in.read(data, 0, 1024)) >= 0) {
totalDataRead = totalDataRead + i;
bout.write(data, 0, i);
float Percent = (totalDataRead * 100) / filesize;
LauncherFrame.progressBar.setValue((int) Percent);
LauncherFrame.notificationLabel.setText("Download del client in corso ... " + (int) Percent + "%");
}
bout.close();
fos.close();
in.close();
connection.disconnect();
String strZipFile = Util.getWorkingDirectory() + File.separator + "update.zip";
if (strZipFile == null || strZipFile.equals("")) {
System.out.println("Invalid source file");
System.exit(0);
} else {
unzip(strZipFile);
}
} catch (Exception e) {
LauncherFrame.notificationLabel.setText("Errore nel download del client!");
e.printStackTrace();
}
} |
9c526a01-0758-4d98-9780-c35587ba832b | 7 | public void start() throws IOException {
myServerSocket = new ServerSocket();
myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));
myThread = new Thread(new Runnable() {
@Override
public void run() {
do {
try {
final Socket finalAccept = myServerSocket.accept();
registerConnection(finalAccept);
finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
final InputStream inputStream = finalAccept.getInputStream();
asyncRunner.exec(new Runnable() {
@Override
public void run() {
OutputStream outputStream = null;
try {
outputStream = finalAccept.getOutputStream();
TempFileManager tempFileManager = tempFileManagerFactory.create();
HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress());
while (!finalAccept.isClosed()) {
session.execute();
}
} catch (Exception e) {
// When the socket is closed by the client, we throw our own SocketException
// to break the "keep alive" loop above.
if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
e.printStackTrace();
}
} finally {
safeClose(outputStream);
safeClose(inputStream);
safeClose(finalAccept);
unRegisterConnection(finalAccept);
}
}
});
} catch (IOException e) {
}
} while (!myServerSocket.isClosed());
}
});
myThread.setDaemon(true);
myThread.setName("NanoHttpd Main Listener");
myThread.start();
} |
f667f96d-0f87-4ead-804d-35c7ce12ee19 | 0 | public void addTreatmentMeta(TreatmentMeta treatmentMeta){
this.treatmentMeta.add(treatmentMeta);
} |
ef8f53fa-834c-4bbd-bb71-df929c859095 | 0 | public WorldCommand(TotalPermissions p) {
plugin = p;
} |
967aa708-2cb6-4a36-808e-342587ca84dc | 2 | public int valueofCadEquals(String cad) {
for (int i = 0; i < this.getLista().size() - 1; i++) {
if (cad.equals(this.getLista().get(i).getMatch())) {
return this.getLista().get(i).getValor();
}
}
return 0; // si no coincide retorn ]a valor de otros
} |
c6768180-89ae-4cc6-94f8-97ebb6a5a501 | 5 | protected ActorMind initAI() {
final Fauna actor = this ;
return new ActorMind(actor) {
protected Behaviour createBehaviour() {
final Choice choice = new Choice(actor) ;
addChoices(choice) ;
return choice.weightedPick() ;
}
protected void updateAI(int numUpdates) {
super.updateAI(numUpdates) ;
}
protected void addReactions(Element seen, Choice choice) {
if (seen instanceof Actor) choice.add(nextDefence((Actor) seen)) ;
}
//
// We install some default relationships with other animals-
public float relationValue(Actor other) {
if (other instanceof Fauna) {
final Fauna f = (Fauna) other ;
if (f.species == species) return 0.25f ;
if (f.species.type == Species.Type.BROWSER) return 0 ;
if (f.species.predator()) return -0.5f ;
}
return -0.25f ;
}
} ;
} |
b459116b-aca5-4f44-bf66-dd695fb89ade | 1 | private static void populate(String s){
if(Cards.containsKey(s))
return;
else
CardsInfo.Cards.put(s, new Card(s));
} |
dca592b2-da48-4cdc-b959-16be6f456a50 | 9 | public void drawHill(Grid g) {
Random r = new Random();
int height;
int width;
int seed;
height = r.nextInt(20) + 1;
seed = r.nextInt(50) + 2;
HashMap<Point, GridSpace> grid = g.getGrid();
ArrayList<Integer> a = new ArrayList<Integer>();
for (int p = 0; p <= height; p = p + r.nextInt(3) + 1) {
a.add(23 - p);
}
int xpos = seed;
for (int i = 0; i < a.size(); i++) {
width = (r.nextInt(7) + 1);
while(width + seed >= 100)
width = (r.nextInt(7) + 1);
for (int s = 0; s < width; s++) {
int topBlock = a.get(i);
for (int j = 23; j > topBlock; j--) {
GridSpace f = new GridSpace(new ArrayList<Thing>());
f.add(new Terrain(true, Color.GREEN));
grid.put(new Point(xpos, j), f);
}
xpos++;
}
}
for (int i = 0; i < a.size(); i++) {
width = (r.nextInt(7) + 1);
while(width + seed >= 100)
width = (r.nextInt(7) + 1);
for (int s = 0; s < width; s++) {
int topBlock = a.get((a.size()-1)-i);
for (int j = 23; j > topBlock; j--) {
GridSpace f = new GridSpace(new ArrayList<Thing>());
f.add(new Terrain(true, Color.GREEN));
grid.put(new Point(xpos, j), f);
}
xpos++;
}
}
} |
841c3e03-4821-4e7b-aff3-595659b8f665 | 9 | @Override
public void mouseClicked(MouseEvent e) {
// Check if ok to send card.
if (chooseCard) {
boolean lastCard = nbrOfPlayedCards == nbrOfPlayers;
if (lastCard || card.getSuit() == firstCardsSuit) {
removeCardFromHand();
} else {
boolean hasTrumf = false;
boolean hasSuit = false;
for (Card card : currentHand) {
if (card.getSuit() == trumf.getSuit()) {
hasTrumf = true;
}
if (card.getSuit() == firstCardsSuit) {
hasSuit = true;
}
}
if (hasSuit) {
return;
} else if (hasTrumf && card.getSuit() != trumf.getSuit()) {
return;
} else {
removeCardFromHand();
}
}
}
} |
60ee5f1e-5075-499a-b03e-b78226a5c156 | 1 | public Map getConfiguration() {
Map config = (HashMap) servletContext.getAttribute(Constants.CONFIG);
// so unit tests don't puke when nothing's been set
if (config == null) {
return new HashMap();
}
return config;
} |
db01bb5d-8353-474d-a5fa-9fec1d0adc05 | 2 | public float setBand(int band, float neweq)
{
float eq = 0.0f;
if ((band>=0) && (band<BANDS))
{
eq = settings[band];
settings[band] = limit(neweq);
}
return eq;
} |
caa9584c-af8f-4978-b4a6-fd2186f05f7e | 3 | public static Vector min(Vector a, Vector b){
return new Vector((a.getX() < b.getX() ? a.getX() : b.getX()), (a.getY() < b.getY() ? a.getY() : b.getY()), (a.getZ() < b.getZ() ? a.getZ() : b.getZ()));
} |
07d9682f-8904-40c2-b986-ba3ccf2b69e1 | 9 | private void writeValue(Object value) throws JSONException {
if (value instanceof Number) {
String string = JSONObject.numberToString((Number) value);
int integer = this.valuekeep.find(string);
if (integer != none) {
write(2, 2);
write(integer, this.valuekeep);
return;
}
if (value instanceof Integer || value instanceof Long) {
long longer = ((Number) value).longValue();
if (longer >= 0 && longer < int14) {
write(0, 2);
if (longer < int4) {
zero();
write((int) longer, 4);
return;
}
one();
if (longer < int7) {
zero();
write((int) (longer - int4), 7);
return;
}
one();
write((int) (longer - int7), 14);
return;
}
}
write(1, 2);
for (int i = 0; i < string.length(); i += 1) {
write(bcd(string.charAt(i)), 4);
}
write(endOfNumber, 4);
this.valuekeep.register(string);
} else {
write(3, 2);
writeJSON(value);
}
} |
8fb0905f-cb2a-4bd1-acf0-b30bba5000c2 | 8 | public void waddleForImprovement()
{
if (queueTiles.size() == 0)
{
City nearestCity = location.grid.nearestCivCity(owner, location.row, location.col);
Tile t = location.grid.bestToImprove(nearestCity);
if (t != null)
waddleTo(t.row, t.col);
else
waddleInTerritory();
}
if (queueTiles.size() > 0)
{
//location.grid.moveTo(this, queueTiles.get(0).row, queueTiles.get(0).col);
passiveWaddle(queueTiles.get(queueTiles.size()-1).row - location.row, queueTiles.get(queueTiles.size()-1).col - location.col);
queueTiles.remove(queueTiles.size()-1);
}
else
{
while (action > 0)
{
int r,c;
int trials = 0;
while (true)
{
r = (int)(Math.random()*3) - 1;
c = (int)(Math.random()*3) - 1;
Tile t = location.grid.getTile(location.row + r, location.col + c);
if (t != null)
if (owner.equals(t.owner))
break;
trials++;
if (trials >= 10)
{
r = (int)(Math.random()*3) - 1;
c = (int)(Math.random()*3) - 1;
break;
}
}
passiveWaddle(r,c);
}
}
} |
f80b4930-b7f4-4522-8cd7-472d5fc17501 | 7 | public static String[] getArgs(String arg) throws AccessException{
int index = 0;
String args[] = new String[2];
if(!arg.isEmpty() && arg.charAt(0) == ' '){
while(index < arg.length() && arg.charAt(index) == ' ') index++;
}
int split = arg.indexOf(' ',index);
if(split == -1) split = arg.length();
args[0] = arg.substring(index, split);
if(args[0].contains("/")) throw new AccessException("Invalid filename");
if(arg.length() > split+1){
args[1] = arg.substring(split+1, arg.length());
}else{
args[1] = "";
}
return args;
} |
ff04088a-4aa1-4b78-97f1-8f8ad39d0eb9 | 7 | public static Class<?> getCallingClass(Class<?>... ignore) {
List<Class<?>> list = Arrays.asList(ignore);
StackTraceElement[] stes = new Throwable().getStackTrace();
for (int i = 1; i < stes.length; i++) {
try {
Class<?> cls = Class.forName(stes[i].getClassName());
if (!list.contains(cls)) return cls;
} catch (Exception e) {e.printStackTrace();}
}
return null;
} |
52327756-a54c-4398-8bf2-195ed67195b7 | 6 | public void updateUser(User user, int port){
if(port == LOGIN_PORT || port == CASH_PORT){
try {
String serverAddress = (port == LOGIN_PORT ? SERVER_ADDRESS_LOGIN : SERVER_ADDRESS_CASH);
Socket socket = new Socket(serverAddress, port);
socket.setSoTimeout(TIMEOUT);
OutputStream outputStream = socket.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
outputStream);
objectOutputStream.writeObject("UPDATE_USER");
objectOutputStream.writeObject(user);
objectOutputStream.flush();
socket.close();
}catch (SocketException e){
new ErrorFrame("Server unreachable!");
} catch (SocketTimeoutException e){
new ErrorFrame("Connection timed out");
} catch (Exception e) {
new ErrorFrame("An unknown Error occoured");
}
}
} |
bb48d60c-1cb1-4afc-8429-57a4bfa0401f | 5 | private void fixNegativeRed(Node negRed){
Node n1, n2, n3, n4, t1, t2, t3, child;
Node parent = negRed.parent;
if (parent.left == negRed){
n1 = negRed.left;
n2 = negRed;
n3 = negRed.right;
n4 = parent;
t1 = n3.left;
t2 = n3.right;
t3 = n4.right;
n1.color = red;
n2.color = black;
n4.color = black;
n2.setRightChild(t1);
Comparable temp = n4.data; n4.data = n3.data; n3.data = temp;
n3.setLeftChild(t2);
n3.setRightChild(t3);
n4.setRightChild(n3);
child = n1;
}else{
n4 = negRed.right;
n3 = negRed;
n2 = negRed.left;
n1 = parent;
t3 = n2.right;
t2 = n2.left;
t1 = n1.left;
n4.color = red;
n3.color = black;
n1.color = black;
n3.setLeftChild(t3);
Comparable temp = n1.data; n1.data = n2.data; n2.data = temp;
n2.setRightChild(t2);
n2.setLeftChild(t1);
n1.setLeftChild(n2);
child = n4;
}
if (child.left != null && child.left.color == red){
fixDoubleRed(child.left);
return;
}
if (child.right != null && child.right.color == red){
fixDoubleRed(child.right);
}
} |
ecab8cd3-f203-4482-8f72-dcec73422f4f | 0 | public int GetMaximumPassenger()
{
return maximumPassenger;
} |
a78c4508-668d-4f20-bcdb-0d5a9386f0f3 | 8 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
T2Impl<?, ?> other = (T2Impl<?, ?>) obj;
return Tuples.equals(_first, other._first)
&& Tuples.equals(_second, other._second);
} |
f6ed49f0-991d-4fe9-ad22-239ace6b9dbc | 9 | protected void drawRadarPoly(Graphics2D g2,
Rectangle2D plotArea,
Point2D centre,
PlotRenderingInfo info,
int series, int catCount,
double headH, double headW) {
Polygon polygon = new Polygon();
EntityCollection entities = null;
if (info != null) {
entities = info.getOwner().getEntityCollection();
}
// plot the data...
for (int cat = 0; cat < catCount; cat++) {
Number dataValue = getPlotValue(series, cat);
if (dataValue != null) {
double value = dataValue.doubleValue();
if (value >= 0) { // draw the polygon series...
// Finds our starting angle from the centre for this axis
double angle = getStartAngle()
+ (getDirection().getFactor() * cat * 360 / catCount);
// The following angle calc will ensure there isn't a top
// vertical axis - this may be useful if you don't want any
// given criteria to 'appear' move important than the
// others..
// + (getDirection().getFactor()
// * (cat + 0.5) * 360 / catCount);
// find the point at the appropriate distance end point
// along the axis/angle identified above and add it to the
// polygon
Point2D point = getWebPoint(plotArea, angle,
value / this.maxValue);
polygon.addPoint((int) point.getX(), (int) point.getY());
// put an elipse at the point being plotted..
Paint paint = getSeriesPaint(series);
Paint outlinePaint = getSeriesOutlinePaint(series);
Stroke outlineStroke = getSeriesOutlineStroke(series);
Ellipse2D head = new Ellipse2D.Double(point.getX()
- headW / 2, point.getY() - headH / 2, headW,
headH);
g2.setPaint(paint);
g2.fill(head);
g2.setStroke(outlineStroke);
g2.setPaint(outlinePaint);
g2.draw(head);
if (entities != null) {
int row; int col;
if (this.dataExtractOrder == TableOrder.BY_ROW) {
row = series;
col = cat;
}
else {
row = cat;
col = series;
}
String tip = null;
if (this.toolTipGenerator != null) {
tip = this.toolTipGenerator.generateToolTip(
this.dataset, row, col);
}
String url = null;
if (this.urlGenerator != null) {
url = this.urlGenerator.generateURL(this.dataset,
row, col);
}
Shape area = new Rectangle(
(int) (point.getX() - headW),
(int) (point.getY() - headH),
(int) (headW * 2), (int) (headH * 2));
CategoryItemEntity entity = new CategoryItemEntity(
area, tip, url, this.dataset,
this.dataset.getRowKey(row),
this.dataset.getColumnKey(col));
entities.add(entity);
}
}
}
}
// Plot the polygon
Paint paint = getSeriesPaint(series);
g2.setPaint(paint);
g2.setStroke(getSeriesOutlineStroke(series));
g2.draw(polygon);
// Lastly, fill the web polygon if this is required
if (this.webFilled) {
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
0.1f));
g2.fill(polygon);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
getForegroundAlpha()));
}
} |
679737e2-0cb7-4469-a48f-67be9334ae64 | 1 | public void downsample() {
//read the image
Mat image = Highgui.imread(path);
//mat out
Mat out = new Mat();
if(image.empty()) {
System.out.println("Image not found !!");
return;
}
//Show the Image before down sampling
ImageUtils.displayImage(ImageUtils.toBufferedImage(image), "Before Downsampling");
//Down sample the image by factor of 2
Imgproc.pyrDown(image, out);
//show the image after down sampling
ImageUtils.displayImage(ImageUtils.toBufferedImage(out), "Down sampled Image");
} |
8997d73c-d3e4-436b-8a56-09d27a7ba2e7 | 9 | protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
} |
740af90c-ae76-4fe4-aa1e-5843d34f5ec4 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Manager other = (Manager) obj;
if (code == null) {
if (other.code != null)
return false;
} else if (!code.equals(other.code))
return false;
if (teacher == null) {
if (other.teacher != null)
return false;
} else if (!teacher.equals(other.teacher))
return false;
return true;
} |
1ed2ab25-9064-48c8-abee-0b9bc83ede61 | 7 | public static void correctRuleIndices(Node<?> node, int n) {
if (n == 0)
return;
for (;;) {
if (node instanceof CallNode) {
((CallNode) node).ruleIndex += n;
} else if (node instanceof RuleNode) {
((RuleNode) node).index += n;
}
if (node instanceof UnaryNode) {
node = ((UnaryNode) node).sibling;
} else if (node instanceof BinaryNode) {
BinaryNode x = (BinaryNode) node;
correctRuleIndices(x.firstSibling, n);
node = x.secondSibling;
} else {
return;
}
}
} |
112817ac-3370-45d8-9bc9-7f0a39b7ca7d | 5 | public void cancel()
{
int counter = 0;
int prevSize = 0;
while (getNotifyQueue().size() != 0)
{
if (prevSize != getNotifyQueue().size())
{
prevSize = getNotifyQueue().size();
counter = 0;
}
else if ((prevSize == getNotifyQueue().size()) && (counter == 25)) break;
try
{
Thread.sleep(200);
}
catch (Exception e)
{
// Swallow this... its an artificial delay to drain queue of events...
}
counter++;
}
getNotifyQueueManager().cancel();
} |
67b4a9a2-d845-468f-93a3-c5c1ee6411f5 | 3 | public static boolean position(String position){
position=position.toLowerCase();
if(!position.equals("tech")||!position.equals("manager")||!position.equals("pharmacist")){
return false;}
else return true;
} |
42dee837-9703-43fc-8860-276d39805eae | 2 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((domain == null) ? 0 : domain.hashCode());
result = prime * result + ((local == null) ? 0 : local.hashCode());
return result;
} |
bb8977b2-f8f2-45ce-bb9c-7c6feb37160b | 0 | public void persist() {
System.out.println(typeEntity.getName());
roomEntity.setType(typeEntity);
em.persist(roomEntity);
typeEntity.setRooms(rooms);
em.persist(typeEntity);
} |
4316eedd-de1b-49b2-a1a6-0af8573e4358 | 7 | @Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
Collection<String> requiredPermissions = new ArrayList<>();
Class<?> resourceClass = resourceInfo.getResourceClass();
Method method = resourceInfo.getResourceMethod();
if(resourceClass.isAnnotationPresent(RequiresPermissions.class)) {
requiredPermissions.addAll(asList(resourceClass.getAnnotation(RequiresPermissions.class).value()));
}
if(method.isAnnotationPresent(RequiresPermissions.class)) {
requiredPermissions.addAll(asList(method.getAnnotation(RequiresPermissions.class).value()));
}
// in case of Spring bean proxied by CGLIB (where we cannot access annotations anymore)
Class<?> superClass = resourceClass.getSuperclass();
if(superClass.isAnnotationPresent(RequiresPermissions.class)) {
requiredPermissions.addAll(asList(superClass.getAnnotation(RequiresPermissions.class).value()));
}
if(isSuperMethodAnnotated(superClass, method, RequiresPermissions.class)) {
requiredPermissions
.addAll(asList(getSuperMethodAnnotation(superClass, method, RequiresPermissions.class).value()));
}
if(!requiredPermissions.isEmpty()) {
log.debug("Register RequiresPermissionsRequestFilter for {} with {}", resourceInfo, requiredPermissions);
context.register(
new RequiresPermissionsRequestFilter(requiredPermissions.toArray(new String[requiredPermissions.size()])));
}
} |
e8368e04-476e-4563-98e9-b7a4e2791978 | 3 | public HashMap getTableValue(int table, int row, int field) throws Exception
{
HashMap<String, Integer> result = new HashMap<String, Integer>();
byte[] bytes = java.nio.ByteBuffer.allocate(4).putInt(row).array();
char[] params = new char[]{(char)table, (char)bytes[2], (char)bytes[3], (char)field};
ArrayList<Integer> answer = this.device.send(0x1F, 10, params);
if (answer.size() == 0)
throw new Exception("Пустой ответ");
if (answer.get(0) == Status.OK)
{
if (answer.size() > 1)
{
result.put("error_code", answer.get(4));
}
}
return result;
} |
8b1a306e-4be7-4d07-b800-b23ff71dd44e | 6 | private Tree elementPro(){
Symbol identifier = null;
Tree parameterList = null,
compoundStatement = null;
if(accept(Symbol.Id.KEYWORD, "function")!=null){
if((identifier = accept(Symbol.Id.IDENTIFIER_NAME))!=null){
if(accept(Symbol.Id.PUNCTUATORS, "\\(")!=null){
parameterList = parameterListPro();
if(accept(Symbol.Id.PUNCTUATORS, "\\)")!=null){
if((compoundStatement = compoundStatementPro())!=null){
return new FunctionStatement(identifier, parameterList, compoundStatement);
}
}
}
}
}
if((compoundStatement = statementsPro())!= null){
return compoundStatement;
}
return null;
} |
53d574aa-3f36-47c7-9698-643423c8297a | 3 | @Override
public void addEntry(Entry entry) throws IOException {
if (exampleWord == null) {
exampleWord = entry.getWord();
}
if (r.nextInt(100) == 1) {
exampleWord = entry.getWord();
}
wordBuilder.append("'" + escape(entry.getWord()) + "',");
definitionBuilder.append("'" + escape(entry.getDefinition()) + "',");
notesBuilder.append("'" + escape(entry.getNotes()) + "',");
categoryBuilder.append("'" + escape(entry.getCategory()) + "',");
tagsBuilder.append("[");
for (String tag : entry.getTags()) {
tagsBuilder.append("'" + escape(tag) + "',");
}
tagsBuilder.append("],");
} |
6ebd88b6-e155-46a4-b640-13566466e17e | 3 | @Test
public void testStronglyConnectedComponentsMin() {
DirectedGraph<String> graphM = new DirectedGraph<String>();
DirectedGraph<String> reversedGraphM = new DirectedGraph<String>();
List<String> input = new ArrayList<String>();
input.add("A B");
input.add("B D");
input.add("D A");
input.add("A F");
input.add("F E");
input.add("E F");
input.add("E C");
input.add("C G");
input.add("D G");
input.add("G H");
input.add("H C");
for(String line : input) {
String[] split = line.split(" ");
Vertex<String> source = new Vertex<String>(split[0]);
Vertex<String> dest = new Vertex<String>(split[1]);
graphM.addVertex(source);
graphM.addVertex(dest);
if (!graphM.isEdge(source, dest)) {
graphM.addEdge(source, dest);
}
source = new Vertex<String>(split[0]);
dest = new Vertex<String>(split[1]);
reversedGraphM.addVertex(source);
reversedGraphM.addVertex(dest);
if (!reversedGraphM.isEdge(dest, source)) {
reversedGraphM.addEdge(dest, source);
}
}
List<Integer> scc = new StronglyConnectedComponents<String>().getSCC(graphM, reversedGraphM);
Collections.sort(scc);
System.out.println(scc.toString());
} |
eb598129-9b0f-4f67-bef4-d2634b4c60ae | 8 | @Override
public void unInvoke()
{
if(!(affected instanceof MOB))
return;
// undo the affects of this spell
final MOB mob=(MOB)affected;
super.unInvoke();
if((canBeUninvoked()&&(!mob.amDead())))
{
mob.tell(L("Your piety curse has been lifted"));
if(mob.isMonster() && (!mob.amDead()))
{
CMLib.commands().postStand(mob,true);
CMLib.tracking().wanderAway(mob,false,true);
if((invoker!=null)&&(invoker!=mob)&&(invoker.location()==mob.location()))
CMLib.combat().postAttack(mob, invoker, mob.fetchWieldedItem());
}
}
} |
4283eacb-b2aa-4bf6-91c8-f8a6c564fd99 | 8 | @Override
public void runCommand(CommandSender sender, String label, String[] args) {
tntControlHelper = tntControlConfig.getTNTControlHelper();
Player player = null;
String pname = "(Console)";
if ((sender instanceof Player)) {
player = (Player) sender;
pname = player.getName();
if (main.hasPermission(player, tntControlConfig.getPERM_TNT_RECLAIM_COMMAND())) {
if (args.length == 0) {
main.sendPlayerMessage(player, INFO_MESSAGES + tntControlConfig.getMessage(Messages.INFO_ALLOWED_RECLAIM_COMMAND));
if (tntControlHelper.isOnReclaim(player)) {
main.sendPlayerMessage(player, INFO_MESSAGES + tntControlConfig.getMessage(Messages.RECLAIMING_IS_ONOFF).replace("%onOff", tntControlConfig.getMessage(Messages.ON_STRING)));
} else {
main.sendPlayerMessage(player, INFO_MESSAGES + tntControlConfig.getMessage(Messages.RECLAIMING_IS_ONOFF).replace("%onOff", tntControlConfig.getMessage(Messages.OFF_STRING)));
}
main.sendPlayerMessage(player, INFO_MESSAGES + tntControlConfig.getMessage(Messages.RECLAIM_COMMAND_REQUIRES).replace("%cmd", getCommandName()));
return;
}
if (args.length >= 1) {
tntControlLogger.debug("option", args[0]);
if (args[0].equalsIgnoreCase(helpOption)) {
tntControlLogger.debug("helpOption", helpOption);
displayHelp(player, this);
return;
}
if (args[0].equalsIgnoreCase(tntControlConfig.getMessage(Messages.ON_STRING))) {
tntControlHelper.addPlayerToReclaim(player);
main.sendPlayerMessage(player, INFO_MESSAGES + tntControlConfig.getMessage(Messages.SETTING_RECLAIM_TO).replace("%onOff", tntControlConfig.getMessage(Messages.ON_STRING)));
return;
}
if (args[0].equalsIgnoreCase(tntControlConfig.getMessage(Messages.OFF_STRING))) {
tntControlHelper.removePlayerFromReclaim(player);
main.sendPlayerMessage(player, INFO_MESSAGES + tntControlConfig.getMessage(Messages.SETTING_RECLAIM_TO).replace("%onOff", tntControlConfig.getMessage(Messages.OFF_STRING)));
return;
}
}
displayHelp(player, this);
return;
} else {
permDenied(player, this);
}
sender.sendMessage("This is not a console command!");
}
} |
4c166295-44b2-43b8-9cb9-8059b6d5f182 | 6 | public String toString() {
return "Extension(use): " + (useExtension ? "true" : "false") + "\n" +
"Hash(use/name): " + (useHash ? "true" : "false") + "/" + nameHash + "\n" +
"Name(use/percentage/algo-ordinal): " + (useName ? "true" : "false") +
"/" + String.valueOf(percentageMatchName) + "/" + matchAlgorithmName + "\n" +
"Size(use/percentage/metric): " + (useSize ? "true" : "false") + "/" +
String.valueOf(percentageMatchSize) + "/" + metricSize + "\n" +
"Thorough(use/percentage): " + (useThorough ? "true" : "false") + "/" +
String.valueOf(percentageMatchThorough) + "/" + (exitAfterFirstByteMisMatch ? "true" : "false");
} |
ea812957-5b40-47c9-bf6a-c1828bf4449d | 2 | private void fixAfterAdd(Node newNode){
if (newNode.parent == null){newNode.color = black;}
else{
newNode.color = red;
if (newNode.parent.color == red) { fixDoubleRed(newNode); }
}
} |
ffcf4c1a-2898-4653-9c26-58851f627d0c | 7 | public void tick() {
if (shouldTake != null) {
if (shouldTake.activeItem instanceof PowerGloveItem) {
remove();
shouldTake.inventory.add(0, shouldTake.activeItem);
shouldTake.activeItem = new FurnitureItem(this);
}
shouldTake = null;
}
if (pushDir == 0) move(0, +1);
if (pushDir == 1) move(0, -1);
if (pushDir == 2) move(-1, 0);
if (pushDir == 3) move(+1, 0);
pushDir = -1;
if (pushTime > 0) pushTime--;
} |
e55ef05b-b6ce-4e39-8d25-a7222fa48d48 | 5 | public void updateObjDetails(JObjective obj, String name){
//if there is a change in objective name
if(!obj.getName().equals(name))
for (int i=0; i<alts.size(); i++){
HashMap temp = (HashMap)alts.get(i);
temp.put(obj.getName(), temp.get(name));
temp.remove(name);
}
//changes in objective details
for (int i=0; i<all_objs.size(); i++){
if ((all_objs.get(i).toString()).equals(obj.getName()) ||
(all_objs.get(i).toString()).equals(name)){
all_objs.remove(i);
all_objs.add(obj);
return;
}
}
} |
f58e8337-57ec-45cc-8c41-ce0eec4eec16 | 1 | @Override
public int hashCode() {
int hash = 0;
hash += (idapplicant != null ? idapplicant.hashCode() : 0);
return hash;
} |
c7241a27-ab7d-491b-87f9-ce442bc34066 | 9 | private void notifySelectionListeners(Event event) {
if (!(event.widget instanceof Control)) {
return;
}
if (getDecorationRectangle((Control) event.widget).contains(event.x,
event.y)) {
SelectionEvent clientEvent = new SelectionEvent(event);
clientEvent.data = this;
if (getImage() != null) {
clientEvent.height = getImage().getBounds().height;
clientEvent.width = getImage().getBounds().width;
}
Object[] listeners;
switch (event.type) {
case SWT.MouseDoubleClick:
if (event.button == 1) {
listeners = selectionListeners.getListeners();
for (int i = 0; i < listeners.length; i++) {
((SelectionListener) listeners[i])
.widgetDefaultSelected(clientEvent);
}
}
break;
case SWT.MouseDown:
if (event.button == 1) {
listeners = selectionListeners.getListeners();
for (int i = 0; i < listeners.length; i++) {
((SelectionListener) listeners[i])
.widgetSelected(clientEvent);
}
}
break;
}
}
} |
8582e6ae-ec49-43f5-b5f4-48e6bc8e77e7 | 3 | public Object copyColorData() {
// Note: This is a fudge. The data about defaultColor,
// groutingColor, and alwaysDrawGrouting is added to the
// last row of the grid. If alwaysDrawGrouting is true,
// this is recorded by adding an extra empty space to
// that row.
Color[][] copy = new Color[rows][columns];
// Replace the last row with a longer row.
if (alwaysDrawGrouting)
copy[rows-1] = new Color[columns+3];
else
copy[rows-1] = new Color[columns+2];
for (int r = 0; r < rows; r++)
for (int c = 0; c < columns; c++)
copy[r][c] = grid[r][c];
copy[rows-1][columns] = defaultColor;
copy[rows-1][columns+1] = groutingColor;
return copy;
} |
4a70416b-b0bf-4a3a-b24d-9e66d449b2a6 | 4 | public void optionSelect()
{
System.out.println("WELCOME TO WORD LADDER MADNESS ");
System.out.println();
System.out.println("Enter option 1 for Discovery mode: ");
System.out.println("Enter option 2 for Generation mode: ");
System.out.println("Enter option 3 for information on modes: ");
System.out.println("Enter option 4 to close program: ");
System.out.println("Please enter a number");
int choice = in.nextInt();
switch (choice)
{
case 1:
discovery();
break;
case 2:
generation();
break;
case 3:
information();
break;
case 4:
System.exit(0);
default:
System.out.println("Invalid Choice!");
optionSelect();
}
} |
2d748311-9739-45d8-971c-eafc4ca432ec | 5 | private boolean recombinationInitialization(HaploStruct hs, double recombPos)
throws Exception {
if (hs==null || !this.getChrom().equals(hs.chrom)) {
throw new Exception("recombine: parameter hs invalid");
}
if (recombPos<chrom.getHeadPos() || recombPos>chrom.getTailPos()) {
throw new Exception("recombine: parameter recombPos invalid");
}
return recombPos>chrom.getHeadPos() && recombPos<chrom.getTailPos();
//recombination exactly at head or tail will be ignored)
} |
5c241327-fed1-40dd-bb12-27a6c16996c8 | 7 | @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(sender.hasPermission("NE.freeze") || sender.isOp() || sender instanceof ConsoleCommandSender || sender instanceof BlockCommandSender) {
if(command.getName().equalsIgnoreCase("Freeze")) {
if(args.length == 0) {
return true;
}
if (args.length == 1) {
Player player = Bukkit.getPlayerExact(args[0]);
frozen.add(player);
return true;
}
}
}
sender.sendMessage(plugin.prefix + "You don't have permissions to use Freeze");
return true;
} |
fde7388d-fd4e-4d1b-8acd-93275aad0c51 | 9 | static public ParseException generateParseException() {
jj_expentries.removeAllElements();
boolean[] la1tokens = new boolean[9];
for (int i = 0; i < 9; i++) {
la1tokens[i] = false;
}
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 2; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
}
}
}
for (int i = 0; i < 9; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.addElement(jj_expentry);
}
}
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = (int[])jj_expentries.elementAt(i);
}
return new ParseException(token, exptokseq, tokenImage);
} |
146c0b4c-ac45-4a99-b1b5-844cdf5713b6 | 9 | public SNMPSequence processGetNextRequest(SNMPPDU requestPDU, String communityName) throws SNMPGetException
{
SNMPSequence varBindList = requestPDU.getVarBindList();
SNMPSequence responseList = new SNMPSequence();
byte pduType = requestPDU.getPDUType();
for (int i = 0; i < varBindList.size(); i++)
{
SNMPSequence variablePair = (SNMPSequence )varBindList.getSNMPObjectAt(i);
SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier) variablePair.getSNMPObjectAt(0);
String snmpOIDStr = snmpOID.toString();
// check to see if supplied community name is ours; if not, we'll just silently
// ignore the request by not returning anything
if (!communityName.equals(this.communityName))
{
continue;
}
if (pduType == SNMPBERCodec.SNMPGETNEXTREQUEST)
{
int index;
for (index = 0; index < SNMP_DATABASE.length; index++)
{
String oid = (String) SNMP_DATABASE[index][0];
if (oid.startsWith(snmpOIDStr))
break;
}
if (index < SNMP_DATABASE.length - 1)
{
if (snmpOIDStr.length() == ((String) SNMP_DATABASE[index][0]).length())
index++;
try
{
if (index < SNMP_DATABASE.length)
{
String nextOIDStr = (String) SNMP_DATABASE[index][0];
// create SNMPVariablePair for the next OID and its value
SNMPObjectIdentifier nextOID = new SNMPObjectIdentifier(nextOIDStr);
SNMPVariablePair innerPair = new SNMPVariablePair(nextOID, getSnmpOIDValue(nextOIDStr));
// now create a pair containing the supplied OID and the variable pair containing the following
// OID and its value; this allows the ANMPv1AgentInterface to know which of the supplied OIDs
// the new OID corresponds to (follows).
SNMPVariablePair outerPair = new SNMPVariablePair(snmpOID, innerPair);
// add the "compound" SNMPVariablePair to the response list
responseList.addSNMPObject(outerPair);
}
}
catch (SNMPBadValueException e)
{
e.printStackTrace();
}
}
}
}
return responseList;
} |
dfa9bafe-0e40-4f45-bafa-21d4018b347c | 4 | public String authentic(String userID, String pwd) {
Connection connection = DBconnection.getInstance();
Statement stmt;
try {
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("");
while (rs.next()) {
String userID1 = rs.getString("userID");
String pwd1 = rs.getString("pwd");
if (userID.equals(userID1) && pwd.equals(pwd1)) {
return rs.getString("userType");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
} |
c798a333-4d00-4157-883a-d5013b2e22e5 | 6 | private void llenarLista(JTable tabla, int numColumnas, LinkedList listaDeDatos) {
Object[] renglonDeDatos = new Object[numColumnas];
DefaultTableModel modeloLista = (DefaultTableModel) tabla.getModel();
limpiarLista(tabla);
boolean seAgregaranProveedores = false;
for (Object dato : listaDeDatos) {
switch (numColumnas) {
case numColumnasDeClientes:
renglonDeDatos[0] = ((Cliente) dato).getIdPersona();
renglonDeDatos[1] = ((Cliente) dato).getNombrePersona();
renglonDeDatos[2] = ((Cliente) dato).getDireccionPersona();
renglonDeDatos[3] = ((Cliente) dato).getTelefonoPersona();
renglonDeDatos[4] = ((Cliente) dato).getCorreoPersona();
break;
case numColumnasDeMesas:
renglonDeDatos[0] = ((MesaDeDulces) dato).getIdMesaDulces();
renglonDeDatos[1] = ((MesaDeDulces) dato).getNombreDeMesa();
renglonDeDatos[2] = ((MesaDeDulces) dato).getPrecio();
break;
case numColumnasDeProveedores:
String nombreProveedor = ((Proveedor) dato).getNombrePersona();
int idProveedor = ((Proveedor) dato).getIdPersona();
LinkedList<Servicio> serviciosDeProveedor = ((Proveedor) dato).getServiciosQueProvee();
for (Servicio unServicio : serviciosDeProveedor) {
renglonDeDatos[0] = idProveedor;
renglonDeDatos[1] = nombreProveedor;
renglonDeDatos[2] = unServicio.getServNombre();
renglonDeDatos[3] = unServicio.getCosto();
modeloLista.addRow(renglonDeDatos);
}
seAgregaranProveedores = true;
break;
}
//Si se agregan proveedores, entonces los renglones
//ya han sido agregados a las tablas.
if (!seAgregaranProveedores) {
modeloLista.addRow(renglonDeDatos);
}
}
tabla.setModel(modeloLista);
} |
320182f5-7f62-4c4e-92ea-89a7fac9c8e1 | 9 | static double prim(double[][] mAdy){
int n,p[]=new int[n=mAdy.length],v=0;double d[]=new double[n];boolean[] vis=new boolean[n];
PriorityQueue<double[]> cola=new PriorityQueue<double[]>(n,new Comparator<double[]>() {
public int compare(double[] o1,double[] o2){
return o1[1]!=o2[1]?(o1[1]<o2[1]?-1:1):(int)o1[0]-(int)o2[0];
}
});
Arrays.fill(d, Double.POSITIVE_INFINITY);d[v]=0;vis[v]=true;
Arrays.fill(p, -1);cola.add(new double[]{v,0});
for(;!cola.isEmpty();){
double[] ult=cola.poll();int s=(int)ult[0];vis[s]=true;
for(int u=0;u<n;u++)
if(u!=s&&!vis[u]&&d[u]>mAdy[s][u]){
p[u]=s;
cola.add(new double[]{u,d[u]=mAdy[s][u]});
}
}
double res=0;
for(int i=0;i<n;i++)if(p[i]>=0){res+=mAdy[p[i]][i];}
return res;
} |
649548a7-fb7b-4907-930f-532c75cd50e1 | 4 | public void run() throws Exception {
System.out.println("Running " + algorithm.FLAG + " algorithm:");
for (Dataset dataset : datasets_to_run) {
System.out.println("\nRunning " + dataset.NAME + " dataset.");
System.out.println("Training...");
train(dataset);
for (Filetype filetype : dataset.FILETYPES) {
System.out.println("Calculuating predictions for ." + filetype.FLAG + " data.");
predict(dataset, filetype);
}
}
System.out.println("\n\n\nResults for " + algorithm.FLAG + " algorithm:\n");
for (Dataset dataset : datasets_to_run) {
System.out.println("Accuracy on " + dataset.NAME + " dataset:");
for (Filetype filetype : dataset.FILETYPES) {
System.out.println(filetype.FLAG + " data: " + String.valueOf(evaluate(dataset, filetype)));
}
System.out.println();
}
} |
656922ff-c70d-4d0d-935a-ceef2ef78063 | 8 | public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) {
this.plugin = plugin;
this.type = type;
this.announce = announce;
this.file = file;
this.id = id;
this.updateFolder = new File(plugin.getDataFolder().getParent(), plugin.getServer().getUpdateFolder());
final File pluginFile = plugin.getDataFolder().getParentFile();
final File updaterFile = new File(pluginFile, "Updater");
final File updaterConfigFile = new File(updaterFile, "config.yml");
YamlConfiguration config = new YamlConfiguration();
config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n'
+ "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n'
+ "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration.");
config.addDefault(API_KEY_CONFIG_KEY, API_KEY_DEFAULT);
config.addDefault(DISABLE_CONFIG_KEY, DISABLE_DEFAULT);
if (!updaterFile.exists()) {
this.fileIOOrError(updaterFile, updaterFile.mkdir(), true);
}
boolean createFile = !updaterConfigFile.exists();
try {
if (createFile) {
this.fileIOOrError(updaterConfigFile, updaterConfigFile.mkdir(), true);
config.options().copyDefaults(true);
config.save(updaterConfigFile);
} else {
config.load(updaterConfigFile);
}
} catch (final Exception e) {
if (createFile) {
plugin.getLogger().severe("The updater could not create configuration at " + updaterFile.getAbsolutePath());
} else {
plugin.getLogger().severe("The updater could not load configuration at " + updaterFile.getAbsolutePath());
}
plugin.getLogger().log(Level.SEVERE, null, e);
}
if (config.getBoolean(DISABLE_CONFIG_KEY)) {
this.result = UpdateResult.DISABLED;
return;
}
String key = config.getString(API_KEY_CONFIG_KEY);
if (API_KEY_DEFAULT.equalsIgnoreCase(key) || "".equals(key)) {
key = null;
}
this.apiKey = key;
try {
this.url = new URL(Updater.HOST + Updater.QUERY + id);
} catch (final MalformedURLException e) {
plugin.getLogger().log(Level.SEVERE, "The project ID provided for updating, " + id + " is invalid.", e);
this.result = UpdateResult.FAIL_BADID;
}
this.thread = new Thread(new UpdateRunnable());
this.thread.start();
} |
33344cf6-45f1-42aa-8b1f-ada381a526c7 | 3 | public void tallenna() {
ObjectOutputStream output = null;
try
{
output = new ObjectOutputStream(new FileOutputStream(new File(henkilonTiedot)));
output.writeObject(henkilot);
}
catch (IOException ex)
{
System.out.println("Virhe tiedostoon kirjoittamisessa " +ex);
}
finally
{
try
{
if (output != null) output.close();
}
catch (IOException ex)
{
System.out.println("Virhe tiedostoa sulkiessa" +ex);
}
}
} |
4cd40df8-1104-45e5-8e88-5a49e61d0e29 | 7 | public void turnOnePlayer() {
GameEngine gEngine = new GameEngine();
if (activeP >= GameEngine.playerCount) {
int[] results = new int[GameEngine.playerCount];
int winSum = 0;
for (int i = 0; i < winners.size(); i++) {
winSum = winSum + GameEngine.Players.get(winners.get(i)).getLastReward();
}
int losersLose;
if(losers.size() > 0) {losersLose = winSum/losers.size();}
else {losersLose = 0;};
for (int i = 0; i < losers.size(); i++) {
GameEngine.Players.get(losers.get(i)).changeBank(-1 * losersLose);
}
String message = "Players " + Arrays.toString(gEngine.Players.get(0).listToArray(winners)) + " took " + (losersLose) + " each from " + Arrays.toString(gEngine.Players.get(0).listToArray(losers));
message = message + "\n";
// 1. and 2.: Dice face values, 3.and 4. Guesses, 5. Amount we have bet, 6. is reward.
message = message + "The right values is " + turnData.get(0)[0] + " and " + turnData.get(0)[1] + "\n";
for (int i = 0; i < turnData.size(); i++) {
message = message + "Player " + (i+1) + " guessed " + turnData.get(i)[2] + " and " + turnData.get(i)[3] + " and bet " + turnData.get(i)[4] + " and won/lost " + (turnData.get(i)[5]-turnData.get(i)[4]) + "\n\n";
}
JOptionPane.showMessageDialog(null, message, "End of turn results", JOptionPane.INFORMATION_MESSAGE);
winners.clear();
losers.clear();
int[] playersAlive = GameEngine.playersAlive();
if (playersAlive[0] > 1) {
activeP = 0;
newTurn();
} else if(playersAlive[0] == 1) {
GameEngine.theEnd(playersAlive[1]);
}
}
System.out.println("settings player to " + activeP);
gEngine.activePlayer = gEngine.Players.get(activeP);
Player player = gEngine.activePlayer;
GameMain.userInterface.returnPlayer();
GameMain.userInterface.setMyBet(thrown);
System.out.println("Player " + (player.getI()+1) + " is playing!");
} |
3eb05ca8-562d-478e-86ce-05167b1df882 | 2 | @Override
public List<Tourist> load(Criteria criteria, GenericLoadQuery loadGeneric, Connection conn) throws DaoQueryException {
int pageSize = 50;
List paramList = new ArrayList<>();
StringBuilder sb = new StringBuilder(WHERE);
String queryStr = new QueryMapper() {
@Override
public String mapQuery() {
Appender.append(DAO_ID_TOURIST, DB_TOURIST_ID_TOURIST, criteria, paramList, sb, AND);
Appender.append(DAO_ID_ORDER, DB_TOURIST_ID_ORDER, criteria, paramList, sb, AND);
Appender.append(DAO_TOURIST_FNAME, DB_TOURIST_FNAME, criteria, paramList, sb, AND);
Appender.append(DAO_TOURIST_MNAME, DB_TOURIST_MNAME, criteria, paramList, sb, AND);
Appender.append(DAO_TOURIST_LNAME, DB_TOURIST_LNAME, criteria, paramList, sb, AND);
Appender.append(DAO_TOURIST_BIRTH, DB_TOURIST_BIRTH, criteria, paramList, sb, AND);
Appender.append(DAO_TOURIST_PASSPORT, DB_TOURIST_PASSPORT, criteria, paramList, sb, AND);
Appender.append(DAO_TOURIST_STATUS, DB_TOURIST_STATUS, criteria, paramList, sb, AND);
if (paramList.isEmpty()) {
return LOAD_QUERY;
} else {
return sb.insert(0, LOAD_QUERY).toString();
}
}
}.mapQuery();
try {
return loadGeneric.sendQuery(queryStr, paramList.toArray(), pageSize, conn, (ResultSet rs, int rowNum) -> {
Tourist bean = new Tourist();
bean.setIdTourist(rs.getInt(DB_TOURIST_ID_TOURIST));
bean.setOrder(new Order(rs.getInt(DB_TOURIST_ID_ORDER)));
bean.setFirstName(rs.getString(DB_TOURIST_FNAME));
bean.setMiddleName(rs.getString(DB_TOURIST_MNAME));
bean.setLastName(rs.getString(DB_TOURIST_LNAME));
bean.setBirthDate(rs.getDate(DB_TOURIST_BIRTH));
bean.setPassport(rs.getString(DB_TOURIST_PASSPORT));
bean.setStatus(rs.getShort(DB_TOURIST_STATUS));
return bean;
});
} catch (DaoException ex) {
throw new DaoQueryException(ERR_TOURIST_LOAD, ex);
}
} |
e341294d-31e1-484d-a315-b3edad36c18a | 3 | private Element parseLoop() throws ParserException, XMLStreamException {
String type = getAttribute("type", "test-first");
switch (type) {
case "test-first":
return parseTestLoop(true);
case "test-last":
return parseTestLoop(false);
case "infinite":
return parseInfiniteLoop();
default:
throw new ParserException("Loop type must be 'test-first', 'test-last' or 'infinite'.");
}
} |
07056265-add0-4411-b4dd-8e3d5a4564c9 | 4 | public static boolean libraryCompatible(Class<?> libraryClass) {
if (libraryClass == null) {
errorMessage("Parameter 'libraryClass' null in method"
+ "'librayCompatible'");
return false;
}
if (!Library.class.isAssignableFrom(libraryClass)) {
errorMessage("The specified class does not extend class "
+ "'Library' in method 'libraryCompatible'");
return false;
}
Object o = runMethod(libraryClass, "libraryCompatible", new Class[0],
new Object[0]);
if (o == null) {
errorMessage("Method 'Library.libraryCompatible' returned "
+ "'null' in method 'libraryCompatible'");
return false;
}
return (((Boolean) o).booleanValue());
} |
07e45232-63ea-49c9-95e4-7dfaa47c5285 | 4 | public void refreshPanel() {
vakLijst.clear();
if (Sessie.getIngelogdeGebruiker().heeftPermissie(
PermissieHelper.permissies.get("BEHEERALLEKLASSEN"))) {
List<Vak> vakken = Dao.getInstance().getVakken();
for (Vak vak : vakken) {
vakLijst.addElement(vak);
}
} else if (Sessie.getIngelogdeGebruiker().heeftPermissie(
PermissieHelper.permissies.get("BEHEEREIGENKLASSEN"))) {
List<Vak> vakken = Dao.getInstance().getVakkenVanDocent(
Sessie.getIngelogdeGebruiker().getId());
for (Vak vak : vakken) {
vakLijst.addElement(vak);
}
}
toetsInfoPanel.clear();
} |
3adbb688-39dc-49d8-a963-b187486b3139 | 2 | public Map<Object, Object> toMap() {
final Map<Object, Object> map = new HashMap<Object, Object>(this.size());
try {
for (E elt : this) {
CycList<Object> eltAsList = (CycList<Object>)elt;
map.put(eltAsList.first(), eltAsList.rest());
}
} catch (Exception e) {
throw new UnsupportedOperationException("Unable to convert CycList to Map because CycList is not an association-list.", e);
}
return map;
} |
4a9f3ea6-ac69-4dfa-925d-7de5bd5fd97d | 1 | public void order() {
if (b > a) {
Integer temp = a;
a = b;
b = temp;
}
} |
dfca90c2-3231-44b2-a1ac-18c0187ce976 | 9 | @Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj == null) {
return false;
}
if(getClass() != obj.getClass()) {
return false;
}
CamLocalUser other = (CamLocalUser) obj;
if(this.name == null) {
if(other.name != null) {
return false;
}
} else if(!this.name.equals(other.name)) {
return false;
}
if(this.role == null) {
if(other.role != null) {
return false;
}
} else if(!this.role.equals(other.role)) {
return false;
}
return true;
} |
cf6e2d83-eb74-4f31-9f15-78eadf38bd80 | 8 | public void updatePosition() {
if (position.mX < destination.mX) position.mX++;
else if (position.mX > destination.mX) position.mX--;
if (position.mY < destination.mY) position.mY++;
else if (position.mY > destination.mY) position.mY--;
if (position.mX == destination.mX && position.mY == destination.mY) {
if (state.equals(State.goingToCooking)) {
//CHASE: wtf
}
if (! state.equals(State.idle)) {
state = State.idle;
((CwagonerCookRole)role).msgAnimationFinished();
}
}
} |
99fc155f-0b0e-484f-a804-f292958068d3 | 0 | int g(final int i) {
return i + 1;
} |
58aa8441-0a28-4788-9cb2-425f2ad38845 | 9 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (age != person.age) return false;
if (firstName != null ? !firstName.equals(person.firstName) : person.firstName != null) return false;
if (position != person.position) return false;
if (secondName != null ? !secondName.equals(person.secondName) : person.secondName != null) return false;
return true;
} |
8e36baa5-ece1-4fbc-8697-e6432d259ffa | 1 | @Override
public void action() {
if(log.isLoggable(Logger.INFO))
log.log(Logger.INFO, "action()");
// dfd = new DFAgentDescription();
// description = new ServiceDescription();
// description.setName("Wumpus' Wumpus-Game");
// description.setType("wumpus-game");
// dfd.addServices(description);
// try {
// if(log.isLoggable(Logger.WARNING))
// log.log(Logger.WARNING, "Register game 'wumpus-game'");
// if (DFService.search(myAgent, dfd).length > 0) {
// DFService.deregister(myAgent, dfd);
// }
// DFService.register(myAgent, dfd);
// } catch (FIPAException e) {
// if(log.isLoggable(Logger.WARNING))
// log.log(Logger.WARNING, "ERROR: " + e.getMessage());
// e.printStackTrace();
// }
} |
4ceeb8af-2bb3-4932-a32b-bafad68fbd9d | 0 | public void request()
{
System.out.println("From Real Subject !");
} |
a412986e-52ca-4f7e-84c6-d7ccca2ed05c | 0 | public void setFunUnidad(String funUnidad) {
this.funUnidad = funUnidad;
} |
7e9e8535-84eb-4c68-8e5a-f1d0df35255b | 0 | public String getOrderCount() {
return orderCount;
} |
1cc36c5b-0f34-41ed-ba56-dc9d181a89a4 | 7 | public void testAddDocument() throws Exception {
Document testDoc = new Document();
DocHelper.setupDoc(testDoc);
Analyzer analyzer = new WhitespaceAnalyzer();
IndexWriter writer = new IndexWriter(dir, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);
writer.addDocument(testDoc);
writer.commit();
SegmentInfo info = writer.newestSegment();
writer.close();
//After adding the document, we should be able to read it back in
SegmentReader reader = SegmentReader.get(true, info, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR);
assertTrue(reader != null);
Document doc = reader.document(0);
assertTrue(doc != null);
//System.out.println("Document: " + doc);
Fieldable [] fields = doc.getFields("textField2");
assertTrue(fields != null && fields.length == 1);
assertTrue(fields[0].stringValue().equals(DocHelper.FIELD_2_TEXT));
assertTrue(fields[0].isTermVectorStored());
fields = doc.getFields("textField1");
assertTrue(fields != null && fields.length == 1);
assertTrue(fields[0].stringValue().equals(DocHelper.FIELD_1_TEXT));
assertFalse(fields[0].isTermVectorStored());
fields = doc.getFields("keyField");
assertTrue(fields != null && fields.length == 1);
assertTrue(fields[0].stringValue().equals(DocHelper.KEYWORD_TEXT));
fields = doc.getFields(DocHelper.NO_NORMS_KEY);
assertTrue(fields != null && fields.length == 1);
assertTrue(fields[0].stringValue().equals(DocHelper.NO_NORMS_TEXT));
fields = doc.getFields(DocHelper.TEXT_FIELD_3_KEY);
assertTrue(fields != null && fields.length == 1);
assertTrue(fields[0].stringValue().equals(DocHelper.FIELD_3_TEXT));
// test that the norms are not present in the segment if
// omitNorms is true
for (int i = 0; i < reader.core.fieldInfos.size(); i++) {
FieldInfo fi = reader.core.fieldInfos.fieldInfo(i);
if (fi.isIndexed) {
assertTrue(fi.omitNorms == !reader.hasNorms(fi.name));
}
}
} |
5108c001-0f28-49c2-b6d8-5684539ab0c4 | 8 | private Collection<Boolean> shift(Collection<Boolean> data, int difference) {
if (difference > 0 && difference < data.size()) {
/* Ištrinama pradžia */
int size = data.size() - difference;
ArrayList<Boolean> result = new ArrayList<Boolean>(size);
int i = 0;
for (Boolean bit : data) {
if (i >= difference) {
result.add(bit);
} else {
i++;
}
}
return result;
} else if (difference < 0 && -difference < data.size()) {
/* Ištrinamas galas */
int size = data.size() + difference;
ArrayList<Boolean> result = new ArrayList<Boolean>(size);
int i = 0;
for (Boolean bit : data) {
if (i < size) {
result.add(bit);
} else {
break;
}
i++;
}
return result;
} else {
/* Seka nekeičiama */
return data;
}
} |
9b92c208-52db-47c9-b29b-de0310238a04 | 4 | public Host replace(String failedPath, Host... failedHosts) {
for (Host failedHost : failedHosts) {
if (routingTable_.contains(failedHost)) {
routingTable_.removeReference(failedHost);
}
}
replace_.execute(routingTable_, new PGridPath(failedPath));
routingTable_.refresh(maxRef_);
for (Host failedHost : failedHosts) {
if (registry_.containsPath(failedHost.getHostPath().toString())) {
registry_.getIssue(failedHost.getHostPath().toString()).issueState = IssueState.SOLVED;
}
}
return routingTable_.getLocalhost();
} |
f1d9398c-3641-46aa-9e99-9600a78de4cd | 9 | protected boolean[] datasetIntegrity(
boolean nominalPredictor,
boolean numericPredictor,
boolean stringPredictor,
boolean datePredictor,
boolean relationalPredictor,
boolean multiInstance,
int classType,
boolean predictorMissing,
boolean classMissing) {
print("associator doesn't alter original datasets");
printAttributeSummary(
nominalPredictor, numericPredictor, stringPredictor, datePredictor, relationalPredictor, multiInstance, classType);
print("...");
int numTrain = getNumInstances(),
numClasses = 2, missingLevel = 20;
boolean[] result = new boolean[2];
Instances train = null;
Associator associator = null;
try {
train = makeTestDataset(42, numTrain,
nominalPredictor ? getNumNominal() : 0,
numericPredictor ? getNumNumeric() : 0,
stringPredictor ? getNumString() : 0,
datePredictor ? getNumDate() : 0,
relationalPredictor ? getNumRelational() : 0,
numClasses,
classType,
multiInstance);
if (missingLevel > 0)
addMissing(train, missingLevel, predictorMissing, classMissing);
associator = AbstractAssociator.makeCopies(getAssociator(), 1)[0];
} catch (Exception ex) {
throw new Error("Error setting up for tests: " + ex.getMessage());
}
try {
Instances trainCopy = new Instances(train);
associator.buildAssociations(trainCopy);
compareDatasets(train, trainCopy);
println("yes");
result[0] = true;
} catch (Exception ex) {
println("no");
result[0] = false;
if (m_Debug) {
println("\n=== Full Report ===");
print("Problem during building");
println(": " + ex.getMessage() + "\n");
println("Here is the dataset:\n");
println("=== Train Dataset ===\n"
+ train.toString() + "\n");
}
}
return result;
} |
93dcf223-5a71-4da4-8e55-8d4fa1dada2e | 4 | private void createHiveGroups(int groupDimension, int groupCount, int groupSize, int x, int y, int dimensionX,
int dimensionY, int pixelX, int pixelY, int groupFixed, int fullLineSwitch) {
for (int yg = 0; yg < groupDimension; yg++) {
for (int xg = 0; xg < groupDimension; xg++) {
if (groupCount < groupSize) {
int lastPositionedHiveX;
int lastPositionedHiveY;
if (fullLineSwitch == 1) {
lastPositionedHiveX = (x - dimensionX / 2) - pixelX / 2 + xg - groupDimension / 2;
lastPositionedHiveY = (y - dimensionY / 2) - pixelY / 2 + yg - groupDimension / 2;
} else {
lastPositionedHiveX = (x - dimensionX / 2) + xg - groupDimension / 2;
lastPositionedHiveY = (y - dimensionY / 2) + yg - pixelY / 2 - groupDimension / 2;
}
registerHive(Position.createFromCoordinates(lastPositionedHiveX, lastPositionedHiveY),
_inputData.getNumberOfBeesPerHive(), "Hive" + groupFixed + "_" + groupCount);
groupCount++;
}
}
}
} |
1b1af11a-acc4-46f7-b4e6-2aeb1adf6e74 | 1 | public void addOperand(final LocalExpr operand) {
for (int i = 0; i < operands.size(); i++) {
final LocalExpr expr = (LocalExpr) operands.get(i);
Assert.isTrue(expr.def() != operand.def());
}
operands.add(operand);
operand.setParent(this);
} |
18269b2e-89d6-4919-ab5f-6cd6d995bb0d | 7 | private MoveValue negaMax(Board b, int remainingDepth, double alpha, double beta)
throws ExitThreadException {
if ( ((IterativeDeepeningThread)Thread.currentThread()).isStopped() ) {
throw new ExitThreadException();
}
if (remainingDepth <= 0 || b.isGameOver()) { //At bottom of tree, return node with its board value
double boardVal = myHeuristic.evaluateBoard(b);
return new MoveValue(null,
(b.getWhoseTurn() == COLOR.BLACK ? -boardVal : boardVal));
}
double bestScore = AiInterface.MIN_SCORE;
double subScore;
List<Move> moves = b.getAllValidMoves();
Move bestMove = moves.get(0);
for (Move m: moves) {
Board boardAfterMove = b.performMoveAndClone(m);
subScore = -negaMax(boardAfterMove, remainingDepth - 1, -beta, -Math.max(bestScore, alpha)).getValue();
if (subScore > bestScore) {
bestScore = subScore;
bestMove = m;
}
if (bestScore >= beta) {
return new MoveValue(bestMove, bestScore);
}
}
return new MoveValue(bestMove, bestScore);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.