method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
1a1eeff2-7eab-46eb-8e1c-976e060fae7d | 1 | public String generateCacheKey(Object[] args) {
String oriKey = buildSimpleKey(args, getParsedKey(), getKeyGetterMethods(), getKeyParameterIndexes());
StringBuilder cacheKey = new StringBuilder();
cacheKey.append(oriKey);
Page page = getPageArgument(args);
if (page != null) {
cacheKey.append("-p").append(page.getCurpage());
}
return cacheKey.toString();
} |
956cb534-8418-43d1-b103-9f60f69f2894 | 2 | private double average(int[] record){
int sum=0;
int i;
double avg;
int ct = 0;
for (i=0;i<record.length;i++){
sum = sum+record[i];
System.out.printf("\n the %d th record is %d\n",i, record[i]);
if (record[i]!=0)
ct=i;
}
avg = sum/(ct+1);
System.out.printf("\n the avg score is %f\n", avg);
return avg;
} |
aa7bae6a-121d-4618-9c10-5cdd10d3b534 | 4 | public BloodParticle(int id, int x, int y, int col, int size, double force, Dungeon dungeon, Random random) {
super(id, x, y, dungeon, random);
this.size = size + random.nextInt(2);
int r = random.nextInt(10);
if(r <= 10) this.col = 0xff752323;
if(r <= 7) this.col = 0xff912C2C;
if(r <= 3) this.col = 0xff6E1010;
if(r <= 1) this.col = 0xff4A0C0C;
xx = x;
yy = y;
zz = 20;
xa = random.nextGaussian() * force;
ya = random.nextGaussian() * force;
za = random.nextFloat();
} |
e49e0bce-3a04-4f06-a549-cd4ead641b91 | 4 | public static boolean applyLookAndFeelByName(String name)
{
try
{
if (name != null)
{
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
{
if (name.equals(info.getName()))
{
UIManager.setLookAndFeel(info.getClassName());
return true;
}
}
}
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e)
{
System.out.println("Cannot apply Look And Feel!");
e.printStackTrace();
return false;
}
return false;
} |
ecbd56da-722a-4230-ba47-deeec9b926cf | 6 | @Override
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
if (event.isCancelled()) {
return;
}
Player player = event.getPlayer();
if (player.getGameMode().equals(GameMode.CREATIVE)) {
if (!this.config.yml.getBoolean("Game Mode.Separate Inventories", true)) {
return;
}
if (player.hasPermission("bcs.bypass.chestaccess")) {
return;
}
Entity entity = event.getRightClicked();
if (entity instanceof StorageMinecart || entity instanceof PoweredMinecart) {
event.setCancelled(true);
}
}
} |
e13c4f22-38ba-49ea-b2e0-647d8e83fb27 | 5 | private String buildMacroCall() {
// Assemble the file to get the available macros
MacroStatement[] macros = new SyntaxAnalyser(editor.getSourceFile()).getMacroStatements();
if(macros.length == 0) {
// No macros are available
UIUtilities.showErrorDialog(this, "No macros found");
return null;
}
// Show a dialog to allow the user to select a macro
MacroStatement selectedMacro = (MacroStatement) JOptionPane.showInputDialog(
this, // owner
"Select macro to use", // Message
"MacroCall Builder", // Title
JOptionPane.QUESTION_MESSAGE, // Dialog type
null, // Icon
macros, // Selection values
macros[0]); // Initial selection
// Check the dialog wasn't cancelled
if(selectedMacro == null) {
return null;
}
// Build the macro call statement
StringBuilder statement = new StringBuilder(selectedMacro.getName());
// Loop through arguments and show input dialog to get the operand
for(String argumentLabel : selectedMacro.getArgumentLabels()) {
String argumentValue = (String) JOptionPane.showInputDialog(
this, // owner
"Enter operand for argument '" + argumentLabel + "'", // Message
"Macro Builder", // Title
JOptionPane.PLAIN_MESSAGE);
// If the dialog was cancell / nothing entered return null
if(argumentValue == null || argumentValue.equals("")) {
return null;
}
statement.append(" " + argumentValue);
}
return statement.toString();
} |
46898836-1dfa-4674-b510-d5ba617f51d1 | 6 | public static Tetromino spawnRandomTetromino()
{
double rand = Math.random();
if (rand > .86)
return new SquareTetromino();
else if (rand > .72)
return new LineTetromino();
else if (rand > .58)
return new RightLTetromino();
else if (rand > .44)
return new LeftLTetromino();
else if (rand > .30)
return new LeftZigZagTetromino();
else if (rand > .15)
return new RightZigZagTetromino();
else
return new IntersectTetromino();
} |
982555a5-ae09-42c8-a1cf-db1198628455 | 3 | private void findNamesByTitle() {
Integer[] aPos = perPos.toArray(new Integer[perPos.size()]);
for(int p : aPos) {
String before;
int befPos;
if(pFill.matcher(tokens.get(p-1)).matches()) {
before = tokens.get(p-2);
befPos = 2;
}
else {
before = tokens.get(p-1);
befPos = 1;
}
// Künstler-Bezeichnung gefunden
if(pTitles.matcher(before).matches()) {
String name = tokens.get(p);
String mname = cd.getName();
Calendar date = cd.getDate();
foundNames.add(new NameData(mname, date, name, 2));
tokens.set(p, "");
tokens.set(p - befPos, "");
perPos.remove(p);
}
}
} |
aaf32288-177b-437f-9e6e-76ef33854a12 | 1 | public void leaveQueues(User leavingUser){
Iterator<Entry<Integer, Queue<User>>> it = gameQueueMap.entrySet().iterator();
while(it.hasNext()){
it.next().getValue().remove(leavingUser);
}
} |
6ea56f36-4238-483f-bb99-49a24f0a2481 | 3 | @Override
public ExecutionContext run(ExecutionContext context) throws InterpretationException {
AbsValueNode temp = (AbsValueNode) getChildAt(this.getChildCount() - 1);
assert(temp!=null);
Value test = (temp.evaluate(context));
if (test.getType() != VariableType.BOOLEAN)
throw new InterpretationException(InterpretationErrorType.BOOLEAN_EXPECTED, line, null);
while (test.getValue(Boolean.class)) {
for (int j = 0; j < this.getChildCount() - 1; j++) {
((AbsStatementNode) this.getChildAt(j)).run(context);
}
test = temp.evaluate(context);
}
return context;
} |
bbc83304-4f4b-48de-8f6c-affead7140d6 | 4 | public void transmitFile(String src)
{
TextProcessor.spellcheckFile(src, "prepare_" + src);
TextProcessor.compressFile("prepare_" + src, "transfer_" + src);
initializeNetwork();
int delay = 0, time = 0;
LinkedList<String> path = network.dijkstrasShortestPath("control", "device");
System.out.println("\nStablishing a connection, please wait ...");
for (int i = 0; i < path.size() - 1; i++)
{
for (Edge e : network.getVertices().get(path.get(i)).getEdges())
if (e.getOtherVertex().getName().equals(path.get(i + 1)))
delay = e.getWeight();
try
{
Thread.sleep(100 * delay);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
System.out.println("\tData arrived at " + path.get(i + 1) + " in " + delay + " seconds.");
time += delay;
}
System.out.println("\"" + src + "\" reached after " + time + " seconds! Done...");
} |
8830bf88-145b-4dbf-a4e8-b1de2541818c | 0 | @Override
public void execute(VirtualMachine vm) {
((DebuggerVirtualMachine) vm).enterEnvironmentRecord(identifier, offset);
} |
2decbdef-3402-4b0f-9835-53c99fee082e | 9 | public ListNode mergeTwpLists(ListNode l1, ListNode l2)
{
ListNode head = null;
ListNode n = null;
if (l1 == null)
{
head = l2;
return head;
}
if (l2 == null)
{
head = l1;
return head;
}
while (l1 != null && l2 != null)
{
if (l1.val < l2.val)
{
if (head == null)
{
head = l1;
n = head;
}
else
{
n.next = l1;
n = n.next;
}
l1 = l1.next;
}
else
{
if (head == null)
{
head = l2;
n = head;
}
else
{
n.next = l2;
n = n.next;
}
l2 = l2.next;
}
}
if (l1 != null)
n.next = l1;
if (l2 != null)
n.next = l2;
return head;
} |
aac1d540-cd6d-4e67-95f0-b01a508a13ab | 8 | private static String directUploadSession(InputStream is, OutputStream os) throws IOException, ClassNotFoundException{
//Wait for the downloader to put his session description on the stream
int timeout = 100;
while(is.available() < 10 && timeout > 0){
try { Thread.sleep(50);} catch (InterruptedException e) {}
timeout--;
}
if (timeout == 0){
System.out.println("DEBUG: Did not receive FTP session identifier, dropping connection");
return null;
}
ObjectInputStream ois = new ObjectInputStream(is);
String session = (String) ois.readObject();
//Are we being remote invoked?
if (session.startsWith("REMOTE_INVOCATION:")){
return session.substring(18);
}
System.out.println("DEBUG: Starting upload session \"" + session + "\"");
//Receive session identifier
boolean knownsession = false;
synchronized(openDownloadables){
knownsession = openDownloadables.containsKey(session);
}
if (!knownsession){
//If an unknown session is being requested send a 0 (false)
System.out.println("DEBUG: Unknown download session requested (\""+session+"\"), exiting");
os.write(0);
os.flush();
return null;
}
//If an known session is being requested send a 1 (true)
os.write(1);
os.flush();
HashMap<Integer, String> filemapping = null;
synchronized(openDownloadables){
filemapping = openDownloadables.remove(session);
}
for (Integer map : filemapping.keySet()){
String fpath = filemapping.get(map);
FileInputStream fis = new FileInputStream(fpath);
//Write our file identifier before the stream, so
//the receiver knows what is coming in.
byte[] identifier = ByteBuffer.allocate(4).putInt(map.intValue()).array();
os.write(identifier);
//Put the file size on the stream
long filesize = new File(fpath).length();
byte[] filesizeheader = ByteBuffer.allocate(8).putLong(filesize).array();
os.write(filesizeheader);
os.flush();
System.out.println("DEBUG: Sending fileid " + map.intValue() + " (" + filesize + " bytes)");
//Write the raw file to stream
int data = 0;
while ((data = fis.read()) != -1)
os.write(data);
fis.close();
System.out.println("DEBUG: Done sending file");
os.flush();
int flag = is.read();
System.out.println("DEBUG: Downloader sent flag: " + flag);
}
System.out.println("DEBUG: Finished session \"" + session + "\"");
return null;
} |
7840b7e3-a0fe-49ee-808f-cbb85cc9cfdd | 5 | void descendFileSystem(File startDir) throws IOException {
log.fine(String.format("FileSub.searchFiles(%s)%n", startDir));
if (startDir.isDirectory()) {
String name = startDir.getName();
for (String dir : IGNORE_DIRS) {
if (dir.equals(name)) {
log.finer("IGNORING " + startDir);
return;
}
}
File[] list = startDir.listFiles();
for (File f : list) {
descendFileSystem(f); // recurse
}
} else if (startDir.isFile()) {
processFile(startDir);
} else {
System.err.printf("Warning: %s neither file nor directory, ignoring%n", startDir);
}
} |
6497e1af-76ce-4239-b87b-28fd1226749d | 3 | public List<Frame> getFramesForTargetLemma(String targetLemma){ //depricated
List<Frame> result = new ArrayList<Frame>();
for(Frame frame: frames){
if(frame.getTargetLemmaIDref().equals(targetLemma))
result.add(frame);
}
if(result.size()>0) return result;
return null;
} |
0e41a926-4a35-48a4-93dc-4ed8049e96f3 | 3 | private ArrayList<File> searchTileFiles() {
File dir = new File("assets/tiles");
String find = ".pbt";
File[] files = dir.listFiles();
ArrayList<File> matches = new ArrayList<File> ();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].getName().endsWith(find)) {
matches.add(files[i]);
}
}
}
return matches;
} |
985499c9-b5bd-4824-a59f-0952128a0795 | 8 | @Override
public Model getRotatedModel() {
if (npcDefinition == null)
return null;
Model rotatedModel = getChildModel();
if (rotatedModel == null)
return null;
super.height = rotatedModel.modelHeight;
if (super.graphicId != -1 && super.currentAnimationId != -1) {
SpotAnimation spotAnimation = SpotAnimation.cache[super.graphicId];
Model animationModel = spotAnimation.getModel();
if (animationModel != null) {
int frameId = spotAnimation.sequences.frame2Ids[super.currentAnimationId];
Model animatedModel = new Model(true,
Animation.isNullFrame(frameId), false, animationModel);
animatedModel.translate(0, -super.graphicHeight, 0);
animatedModel.createBones();
animatedModel.applyTransformation(frameId);
animatedModel.triangleSkin = null;
animatedModel.vertexSkin = null;
if (spotAnimation.scaleXY != 128 || spotAnimation.scaleZ != 128)
animatedModel.scaleT(spotAnimation.scaleXY,
spotAnimation.scaleXY, spotAnimation.scaleZ);
animatedModel.applyLighting(
64 + spotAnimation.modelLightFalloff,
850 + spotAnimation.modelLightAmbient, -30, -50, -30,
true);
Model models[] = { rotatedModel, animatedModel };
rotatedModel = new Model(models);
}
}
if (npcDefinition.boundaryDimension == 1)
rotatedModel.singleTile = true;
return rotatedModel;
} |
34702282-e55a-4e48-8037-c06dc38b972a | 7 | private boolean checkToSetCodedContent(Element in, Component out) {
// first look for coded content
CodedContentCollection collector = new CodedContentCollection();
// String codedID = in.getAttribute("name");
if (in.getAttribute("radlex:id") != null && in.getAttribute("radlex:id") != "") {
collector.add(in.getAttribute("name"), in.getAttribute("radlex:id"), "2.16.840.1.113883.6.256");
}
if (in.getAttribute("snomed:id") != null && in.getAttribute("snomed:id") != "") {
collector.add(in.getAttribute("name"), in.getAttribute("snomed:id"), "2.16.840.1.113883.6.96");
}
if (in.getAttribute("loinc:id") != null && in.getAttribute("loinc:id") != "") {
collector.add(in.getAttribute("name"), in.getAttribute("loinc:id"), "2.16.840.1.113883.6.1");
}
// now if there's some items, process them in one fell swoop
if (collector.getContent().size() > 0) {
collector.setId(template.getNextCodedID());
out.setCodedContentCollection(collector);
template.getCodedContentSet().add(collector);
return true;
} else {
return false;
}
} |
5d8c2ffa-92d1-423e-bb4f-952e1fdc6d19 | 3 | @Override
public void doAction(Player player, Grid grid) throws InvalidActionException {
if (player.getRemainingTurns() <= 0)
throw new InvalidActionException("The player has no turns left!");
Position currentPos = player.getPosition();
Position newPos = new Position(currentPos.getxCoordinate() - 1, currentPos.getyCoordinate() + 1);
if (!canMoveToPosition(player, grid, newPos) || !canMoveDiagonal(grid, newPos))
throw new InvalidActionException("The player can't move to the desired position!");
player.setPosition(newPos);
player.getLightTrail().addPosition(currentPos);
player.decrementTurn();
} |
3ecaaafb-d6b6-48bb-a092-297d43f32f64 | 5 | @Override
public Object getValueAt(int rowIndex, int columnIndex) {
FileModel file = historyFileListUtils.getFileAt(rowIndex);
switch (columnIndex) {
case 0:
return file.getFrom().toString();
case 1:
return file.getTo().toString();
case 2:
return file.getName();
case 3:
return file.getProgress();
case 4:
return file.getStatus();
}
return null;
} |
6faa508f-629e-4ed0-96ca-78968aed34f9 | 3 | private byte[] padPassword(byte[] password) {
if (password == null) {
password = new byte[0];
}
// Step 1: Pad or truncate the password string to exactly 32 bytes. If
// the password string is more than 32 bytes long, use only its first 32
// bytes; if it is less than 32 bytes long, pad it by appending the
// required number of additional bytes from the beginning of the
// following padding string:
// < 28 BF 4E 5E 4E 75 8A 41 64 00 4E 56 FF FA 01 08
// 2E 2E 00 B6 D0 68 3E 80 2F 0C A9 FE 64 53 69 7A >
// That is, if the password string is n bytes long, append the first 32
// â n bytes of the padding string to the end of the password string. If
// the password string is empty (zero-length), meaning there is no user
// password, substitute the entire padding string in its place.
byte[] padded = new byte[32];
// limit password to 32 bytes
final int numContributingPasswordBytes =
password.length > padded.length ?
padded.length : password.length;
System.arraycopy(password, 0, padded, 0, numContributingPasswordBytes);
// Copy padding
if (password.length < padded.length) {
System.arraycopy(PW_PADDING, 0, padded, password.length,
padded.length - password.length);
}
return padded;
} |
9672ec8a-cb13-4e97-8d83-710d7f0269e4 | 0 | @Override
public Object clone() {
return new Rabin((HashSet<Integer>) states.clone(), (HashSet<Integer>) liveStates.clone(), new Integer(initialState), (HashSet<AcceptingPair>) acceptanceCondition.clone(), (HashSet<Transition>) transitionRelation.clone());
} |
6bd0deef-3e67-4b3c-931b-ddbd9aadc213 | 5 | public int readProp() throws ServerException {
int port = 7070;
if (log.isDebugEnabled())
log.debug("Method call");
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("servConfig.properties");
prop.load(input);
port = Integer.parseInt(prop.getProperty("port"));
} catch (IOException e) {
ServerException ex = new ServerException(e);
log.error("Exception", ex);
throw ex;
} catch(NumberFormatException e) {
ServerException ex = new ServerException("Specified port is not correct, using port 7070",e);
log.error("Exception", ex);
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
ServerException ex = new ServerException(e);
log.error("Exception", ex);
throw ex;
}
}
return port;
} |
3c66bc23-db05-4826-9f1a-51dd1770de1e | 5 | public static void main (String[] args) throws IOException{
char[] hexArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
// args[0] = "E:/1.txt";
File file = new File(args[0]);
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
while ((line = in.readLine()) != null) {
String[] lineArray = line.split("\n");
if (lineArray.length > 0) {
char[] charArray = line.toCharArray();
int sum = 0;
int capacity = 0;
for (int i = 0; i < charArray.length; i++) {
for (int j = 0; j < hexArray.length; j++) {
if (charArray[i] == hexArray[j]) {
sum += j * Math.pow(16, charArray.length - capacity - 1);
capacity++;
}
}
}
System.out.println(sum);
}
}
} |
ac3d991a-4a8e-4039-bc1d-2aa3a818a642 | 7 | @Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
super.executeMsg(myHost,msg);
if(!(affected instanceof MOB))
return;
final MOB mob=(MOB)affected;
if((msg.amISource(mob))
&&(msg.tool()!=this)
&&(!CMath.bset(msg.sourceMajor(),CMMsg.MASK_CHANNEL))
&&((CMath.bset(msg.sourceMajor(),CMMsg.MASK_MOVE))||(CMath.bset(msg.sourceMajor(),CMMsg.MASK_HANDS))||(CMath.bset(msg.sourceMajor(),CMMsg.MASK_MOUTH))))
unInvoke();
return;
} |
5c3e9311-3e2c-41d5-b92f-319d755935c6 | 0 | public int getX() {
return x;
} |
7d0fb631-ef7d-400b-822f-d3012bcf1f83 | 6 | @SuppressWarnings("unchecked")
public void eval(EvalContext context) {
context.logEntering("Comparaison " + operator);
right.eval(context);
Object rightB = context.pop();
context.log("Evaluating right operand: " + rightB);
//
left.eval(context);
Object leftB = context.pop();
context.log("Evaluating left operand: " + rightB);
//
int val = ((Comparable<Object>)leftB).compareTo(rightB);
boolean res;
if(val==0) {
res = operator==Op.GreaterOrEqual || operator==Op.Equal || operator==Op.LowerOrEqual;
}
else if(val>0) {
res = operator==Op.GreaterOrEqual || operator==Op.Greater;
}
else {
res = operator==Op.LowerOrEqual || operator==Op.Lower;
}
context.push(res);
context.logLeaving("Comparaison " + operator +" res: " + res);
} |
41a616b9-6323-4c1e-a5d6-9eb55b6fa528 | 9 | public ArrayList<Politica> listAll(Connection c) throws SQLException {
String sql = "SELECT * FROM M_POLIROLL ORDER BY VCCODRUTINA ASC ";
ArrayList<Politica> results = new ArrayList();
ResultSet result = null;
PreparedStatement stm = null;
try {
stm = c.prepareStatement(sql);
result = stm.executeQuery();
while (result.next()) {
Politica valueObject = new Politica();
valueObject.setVccodrutina(result.getString("VCCODRUTINA"));
valueObject.setLopcion(Boolean.parseBoolean(result.getString("LOPCION")) ? "Si" : "No");
valueObject.setLgrabar(Boolean.parseBoolean(result.getString("LGRABAR")) ? "Si" : "No");
valueObject.setLborrar(Boolean.parseBoolean(result.getString("LBORRAR")) ? "Si" : "No");
valueObject.setLimprimir(Boolean.parseBoolean(result.getString("LIMPRIMIR")) ? "Si" : "No");
valueObject.setLsimex(Boolean.parseBoolean(result.getString("LSIMEX")) ? "Si" : "No");
results.add(valueObject);
}
} catch (SQLException ex) {
Logger.getLogger(PoliticaDao.class.getName()).log(Level.SEVERE, null, ex);
} finally {
c.close();
if (result != null) {
result.close();
}
if (stm != null) {
stm.close();
}
}
return results;
} |
a8d8177b-7f7b-4ef4-bc1b-b9da65f7358a | 4 | public static void shiftMap(int position){
switch (position) {
case UP: map.setOffsetY(-15); break;
case DOWN: map.setOffsetY(15); break;
case LEFT: map.setOffsetX(-20); break;
case RIGHT: map.setOffsetX(20); break;
}
EntityManager.cleanUp();
} |
324fb732-491d-4feb-85f3-037d58464b78 | 1 | public String convert(HashMap<String, Integer> dv) {
String result = "" + from.getId();
for (String name : dv.keySet()) {
result += " " + name + ":" + dv.get(name);
}
return result + "\n";
} |
38dd05ea-4d40-4a09-91dd-86a5848284df | 3 | public User login(String username, String password) {
for (int i=0; i<members.size(); i++)
if (members.get(i).getUsername().equals(username) &&
members.get(i).getPassword().equals(password)) return members.get(i);
return null;
} |
45b9bd63-73ce-4e95-bba1-ef961a257438 | 5 | public void rollBack() {
clear();
if (excecuteHistory == MOVE_DOWN) {
currentY--;
} else if (excecuteHistory == MOVE_LEFT) {
currentX++;
} else if (excecuteHistory == MOVE_RIGHT) {
currentX--;
} else if (excecuteHistory == ROTATE_CLOCKWISE) {
shape.rotate(false);
} else if (excecuteHistory == ROTATE_COUNTERCLOCKWISE) {
shape.rotate(true);
}
excecuteHistory = 0;
setShapeInMatrix();
} |
fbcf69ef-4307-459c-91ca-4f4b376015c1 | 8 | protected long skipBytes(long bytes) throws BasicPlayerException
{
long totalSkipped = 0;
if (m_dataSource instanceof File)
{
log.info("Bytes to skip : " + bytes);
int previousStatus = m_status;
m_status = SEEKING;
long skipped = 0;
try
{
synchronized (m_audioInputStream)
{
notifyEvent(BasicPlayerEvent.SEEKING, getEncodedStreamPosition(), -1, null);
initAudioInputStream();
if (m_audioInputStream != null)
{
// Loop until bytes are really skipped.
while (totalSkipped < (bytes - SKIP_INACCURACY_SIZE))
{
skipped = m_audioInputStream.skip(bytes - totalSkipped);
if (skipped == 0) break;
totalSkipped = totalSkipped + skipped;
log.info("Skipped : " + totalSkipped + "/" + bytes);
if (totalSkipped == -1) throw new BasicPlayerException(BasicPlayerException.SKIPNOTSUPPORTED);
}
}
}
notifyEvent(BasicPlayerEvent.SEEKED, getEncodedStreamPosition(), -1, null);
m_status = OPENED;
if (previousStatus == PLAYING) startPlayback();
else if (previousStatus == PAUSED)
{
startPlayback();
pausePlayback();
}
}
catch (IOException e)
{
throw new BasicPlayerException(e);
}
}
return totalSkipped;
} |
d5b818da-e41d-4f6f-ab2f-fe38903d1e3c | 4 | public ArrayList<Libros> getByNombre(Libros l){
PreparedStatement ps;
ArrayList<Libros> libros = new ArrayList<>();
try {
ps = mycon.prepareStatement("SELECT * FROM Libros WHERE nombre LIKE ?");
ps.setString(1, "%"+l.getNombrelibro()+"%");
ResultSet rs = ps.executeQuery();
if(rs!=null){
try {
while(rs.next()){
Libros l1 = new Libros(
rs.getString("codigo"),
rs.getString("nombre"),
rs.getString("titulo"),
rs.getString("autor"),
rs.getInt("cantidad")
);
l1.setPrestados(rs.getInt("prestados"));
libros.add(l1);
}
} catch (SQLException ex) {
Logger.getLogger(Libros.class.getName()).
log(Level.SEVERE, null, ex);
}
}else{
System.out.println("Total de registros encontrados es: 0");
}
} catch (SQLException ex) {
Logger.getLogger(LibrosCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
return libros;
} |
5cf21e39-3ae4-4582-8b05-54caa49dd17a | 9 | public boolean willThisMoveCauseCheckOrEaten(int x, int y, int a, int b)
{
boolean causeCheck=false;
v1Bobby enemy = new v1Bobby(this.getB(), !color);
Point oldLocation= new Point(x,y);
Point p4=new Point(a,b);
boolean possibleMove=false;
boolean dontLook= false;
if(this.b[a][b].toString().charAt(1) != 'X'){
dontLook=true;
}
if(dontLook==true)
{
if(numDefenders(a,b)!=0) causeCheck=true;
}
if(dontLook==false)
{
move(x,y,a,b);
enemy.getBoard(this.b);
int bob= enemy.numDefenders(a,b);
if(bob!=0 && (bob>numDefenders(a,b) || this.b[a][b].toString().charAt(1) == 'Q' || this.b[a][b].toString().charAt(1) == 'R')) causeCheck=true;
if(check()==true) causeCheck=true;
move(a,b,x,y);
}
enemy.getBoard(this.b);
return causeCheck;
} |
eaea7905-bc7a-48ad-ad61-14829b0c954a | 0 | public InputManager(Component comp) {
this.comp = comp;
mouseLocation = new Point();
centerLocation = new Point();
// register key and mouse listeners
comp.addKeyListener(this);
comp.addMouseListener(this);
comp.addMouseMotionListener(this);
comp.addMouseWheelListener(this);
// allow input of the TAB key and other keys normally
// used for focus traversal
comp.setFocusTraversalKeysEnabled(false);
} |
df258637-874c-419f-96e4-64cabd542ada | 0 | public void automataTransitionChange(AutomataTransitionEvent e) {
setDirty();
} |
95fe5a46-5b96-416f-aa8d-8e1d01dcceac | 7 | public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/xml; charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = new PrintWriter(new OutputStreamWriter(
resp.getOutputStream(), "UTF-8"), true);
writer.println("<?xml version='1.0' encoding='utf-8'?>");
String from = req.getParameter("from");
if (from == null || from.equals("")) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 5);
calendar.add(Calendar.MONTH, -2);
from = format.format(calendar.getTime());
}
String to = req.getParameter("to");
if (to == null || to.equals("")) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
to = format.format(calendar.getTime());
}
long tick = getTick();
writer.println("<response result='OK' type='games' tick='" + tick
+ "'>");
ArrayList<Game> games = getGames(from, to);
for (Game game : games) {
writer.print("<game ");
writer.print("gameId='" + game.getGameId() + "' ");
writer.print("gameDate='" + game.getDate() + "' ");
int playerCount = game.getPlayerCount();
writer.print("playerCount='" + playerCount + "' ");
writer.println(">");
for (int i = 0; i < Common.MAX_PLAYER_COUNT; i++) {
writer.print("<player ");
writer.print("id='");
writer.print(i);
writer.print("' ");
writer.print("name='");
if (i < playerCount)
writer.print(game.getPlayerName(i));
else
writer.print("Player " + i);
writer.print("' ");
writer.println("/>");
}
writer.println("</game>");
}
writer.println("</response>");
} |
98fcafb5-d48a-4922-acdd-5c312a9bd643 | 2 | public static void printGamestats(ConcurrentLinkedQueue<AIConnection> globalClientsArg){
if(developerMode){
System.out.println("####################### GAME STATS: #######################");
for(AIConnection ai: globalClientsArg){
ai.printStats();
}
System.out.println("###########################################################");
}
} |
6a1d78ac-9dc9-48ab-881c-cfe2c8186faa | 4 | private void deleteBookingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteBookingButtonActionPerformed
int reply = jOptionPane.showConfirmDialog(this, "Are you sure you want to delete this booking?", "Delete?", jOptionPane.YES_NO_OPTION);
if (reply == jOptionPane.YES_OPTION) {
boolean deleteSuccess;
boolean commitSuccess;
if (bookingTable.getSelectedRow() > -1) {
int selectedRowIndex = bookingTable.getSelectedRow();
int bookingId = (Integer) bookingTableModel.getValueAt(selectedRowIndex, 0);
deleteSuccess = ctr.deleteBookingFromDB(bookingId);
if (deleteSuccess) {
commitSuccess = ctr.commitTransaction();
if (commitSuccess) {
jOptionPane.showMessageDialog(this, "Booking deleted!");
refreshBookingTable(bookingTableModel);
}
else {
jOptionPane.showMessageDialog(this, "Fail in commit", "Commit failed", jOptionPane.ERROR_MESSAGE);
}
}
else {
jOptionPane.showMessageDialog(this, "Something went wrong with the deletion", "Delete failed", jOptionPane.ERROR_MESSAGE);
}
}
else {
jOptionPane.showMessageDialog(this, "You must choose a booking!");
}
}
}//GEN-LAST:event_deleteBookingButtonActionPerformed |
3916a813-9856-448c-9fd5-97c2b0aa2a6a | 1 | Pawn(int t, boolean w, int x, int y){
super(t,w,x,y);
dist = 1;
if (!white) {
int[][] ex = {{1, 0}, {1, 1}, {1, -1}, {2, 0}};
moves = ex;
} else {
int[][] ex = {{-1, 0}, {-1, 1}, {-1, -1}, {-2, 0}};
moves = ex;
}
} |
684cc02a-d806-4151-8e0b-f010dc02cc69 | 6 | public static void main(String args[]) throws Exception {
/* 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(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Gui(new Aritmetiikkakone()).setVisible(true);
}
});
} |
afa69395-376e-407f-b4ac-623114421cc0 | 6 | public static void updateButtonBlock(Global global, EffectBlock block){
block.setBlockImg(global.getImageByName("block_btnDown"));
Block door = block.getAffectedBlock();
Rectangle origPos = block.getAffectedOrigPos();
//find doorway block
for (Block b : global.getCurrent().getCurrentVerse().getVerseBlocks()){
if (b.getBlockImg().getName().contains("doorway")){
//find up or down from door
Rectangle up = new Rectangle(origPos.getX(),origPos.getY()-30,30,30);
Rectangle down = new Rectangle(origPos.getX(),origPos.getY()+30,30,30);
if (up.intersects(b.getBlockPos())){
if (!door.getBlockPos().equals(b.getBlockPos())){
door.setBlockY(door.getBlockY() - 2);
}
}
else if (down.intersects(b.getBlockPos())){
if (!door.getBlockPos().equals(b.getBlockPos())){
door.setBlockY(door.getBlockY() + 2);
}
}
}
}
} |
68b1d62a-be61-4907-8e7b-6d4fd37d1e44 | 9 | public static void main(String[] args) throws IOException {
APIKey = getAPIKey();
String[] arguments = {"masteries","chaosdusk","adc"};
if (args.length != 0)
arguments = args;
switch(arguments.length) {
case 0:
displayHelp();
break;
case 1:
switch(arguments[0].toLowerCase()) {
case "help":
displayHelp();
break;
default:
String name = arguments[0];
System.out.println(new Summoner(getContent("v1.2/summoner/by-name/" + name)));
break;
}
break;
case 2:
switch(arguments[0].toLowerCase()) {
case "masteries":
System.out.println(new Masteries(getContent("v1.2/summoner/" + getIdFromName(arguments[1]) + "/masteries")));
break;
default:
throw new IllegalArgumentException("First argument not recognized.");
}
break;
case 3:
switch(arguments[0].toLowerCase()) {
case "masteries":
String name = arguments[1];
Masteries masteryPages = new Masteries(getContent("v1.2/summoner/" + getIdFromName(name) + "/masteries"));
MasteryPage masteryPage = masteryPages.getPageByName(arguments[2]);
if (masteryPage != null)
System.out.println(masteryPage);
else
System.out.println("Mastery page \"" + arguments[2] + "\" not found for summoner \"" + arguments[1] + ".\"");
break;
default:
throw new IllegalArgumentException("First argument not recognized.");
}
break;
default:
throw new IllegalArgumentException("Too many arguements.");
}
} |
8bef4d38-2fdc-4313-8e36-85828df387d3 | 4 | private static User deserialize(String serialized) {
User user = new User();
int start = serialized.indexOf("name:");
int end = serialized.indexOf(",", start + 5);
user.setName(serialized.substring(start + 5 ,end));
Logger.log("reading user's name: \"" + user.name + "\"");
start = serialized.indexOf("id:");
end = serialized.indexOf(",", start + 3 );
user.setId(Integer.parseInt(serialized.substring(start + 3,end)));
Logger.log("reading user's id: \"" + user.id + "\"");
start = serialized.indexOf("kanjis:{");
end = serialized.indexOf("}", start + 8);
Logger.log("reading user's serialized kanjisList: \"" + serialized.substring(start + 8, end) + "\"");
String serializedKanjis = serialized.substring(start + 8, end);
if(!serializedKanjis.isEmpty()) {
for(String sKanji : serializedKanjis.split(",")) {
String[] splittedKanji = sKanji.split(":");
if(splittedKanji.length == 2 ) {
try {
user.kanjis.put(
(Dictionary.getInstance().queryKanjis(new Condition(Criterias.UCS, splittedKanji[0]))).get(0),
Double.parseDouble(splittedKanji[1])
);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return user;
} |
538bd9a6-7e8a-4cb5-9e97-7fe08974d794 | 5 | public String getUsedEncodingName(TLanguageFile file)
{
String back = "ISO-8859-1" ;
if (file != null)
{
// not WYSIWYG mode or the encoding is java utf with escape sequences
if ( !settings.getSaveWYSIWYGmode() ||
( TEncodingList.isJavaEncoding( file.getDefaultEncoding() ) ) )
{
back = "ISO-8859-1" ;
}
else // WYSIWYG mode
{
back = file.getDefaultEncoding() ;
// valid ?
if ( ( back == null ) || ( back.length() < 1 ) )
back = "ISO-8859-1" ;
}
}
return back ;
} |
aff6e4ed-aed2-4f8c-ad7b-ed52a24df520 | 1 | public String getCode(){
String str = "";
if(argumentListOpt!=null){
str += argumentListOpt.getCode();
}
str += this.printLineNumber(true) + "push := " + String.valueOf(this.currentLineNumber + 2) + "\n";
str += this.printLineNumber(true) + "goto := " + identifier.getNewName() + "\n";
return str;
} |
b7fd9ee0-da9b-4f3b-a748-6e7cfe416192 | 6 | public void drawBanditInitial(Graphics g) {
if(player.getBandit().getRoomCoords(player.getBandit().getArea())[0]==-1
||player.getBandit().getRoomCoords(player.getBandit().getArea())[1]==-1) {
int i = player.getBandit().getAdjacentGrid()[0];
int j = player.getBandit().getAdjacentGrid()[1];
if(i==0) {
i = i*heightBlock+padding+2-heightBlock;
j = j*widthBlock+padding+2;
}else if(i==grid.length-1) {
i = i*heightBlock+padding+2+heightBlock;
j = j*widthBlock+padding+2;
}else if(j==grid[0].length-1) {
j = j*widthBlock+padding+2+widthBlock;
i = i*heightBlock+padding+2;
}else if(j==0) {
j = j*widthBlock+padding+2-widthBlock;
i = i*heightBlock+padding+2;
}
transformPointer(player.getBandit().getFace());
g.drawImage(op.filter(pointer, null), j, i, bandit, bandit, null);
}
} |
6d859b02-a7be-4999-a6f2-efa22a4e0e6e | 7 | private void load(Mesh mesh) {
int list = glGenLists(1);
glNewList(list, GL_COMPILE);
int type;
if (mesh.getType() == Mesh.TRIAGLES)
type = GL_TRIANGLES;
else if (mesh.getType() == Mesh.QUADS)
type = GL_QUADS;
else
throw new RuntimeException(
"critical error, no typ given -> someone hacked some shit in");
glBegin(type);
for (Face f : mesh.getIndices()) {
for (int i = 0; i < 3; i++) {
// System.out.println(mesh.getNormals().size()+" "+mesh.getVertices().size()+" ["+(f.getVertexIndices()[i]-1)+"] "+mesh.getIndices().size());
Vector3f v = mesh.getVertices()
.get(f.getVertexIndices()[i] - 1);
if (f.getNormalIndices()[i] != 0) {
Vector3f n = mesh.getNormals().get(
f.getNormalIndices()[i] - 1);
glNormal3f(n.x, n.y, n.z);
} else {
// TODO: calculate normals
}
if (f.getTextureCoords()[i] != 0) {
Vector2f t = mesh.getTexCoords().get(
f.getTextureCoords()[i] - 1);
glTexCoord2f(t.x, t.y);
}
// System.out.println("["+k+++"] vx "+v.x+" vy "+v.y+" vz "+v.z+" nx "+n.x+" ny "+n.y+" nz "+n.z+" tx "+t.x+" ty "+t.y);
//
// glColor3d(Math.abs(v.x/10f),Math.abs(v.y/10f),Math.abs(v.z/10f));
glColor3f(1f, 1f, 1f);
glVertex3f(v.x, v.y, v.z);
}
}
glEnd();
glEndList();
mesh.setId(list);
Shader shader;
if(mesh.hasShader()) {
shader = mesh.getShader();
loadShader(shader);
}
} |
cb57292a-ebca-4d9f-8a38-19922b4265d4 | 9 | @Override
public StringBuilder getHelpList(String helpStr,
Properties rHelpFile1,
Properties rHelpFile2,
MOB forMOB)
{
helpStr=helpStr.toUpperCase().trim();
if(helpStr.indexOf(' ')>=0)
helpStr=helpStr.replace(' ','_');
final List<String> matches=new Vector<String>();
for(final Enumeration<Object> e=rHelpFile1.keys();e.hasMoreElements();)
{
final String key=(String)e.nextElement();
final String prop=rHelpFile1.getProperty(key,"");
if((key.toUpperCase().indexOf(helpStr)>=0)||(CMLib.english().containsString(prop,helpStr)))
matches.add(key.toUpperCase());
}
if(rHelpFile2!=null)
{
for(final Enumeration<Object> e=rHelpFile2.keys();e.hasMoreElements();)
{
final String key=(String)e.nextElement();
final String prop=rHelpFile1.getProperty(key,"");
if((key.toUpperCase().indexOf(helpStr)>=0)||(CMLib.english().containsString(prop,helpStr)))
matches.add(key.toUpperCase());
}
}
if(matches.size()==0)
return new StringBuilder("");
return CMLib.lister().fourColumns(forMOB,matches);
} |
2638c7af-5337-44b5-b4a0-fbc238e80e30 | 1 | * @return the count of the instances of the given collection
*
* @throws IOException if a data communication error occurs
* @throws CycApiException if the api request results in a cyc server error
*/
public int countAllInstances_Cached(CycFort collection, CycObject mt)
throws IOException, CycApiException {
Integer countAllInstances = countAllInstancesCache.get(collection);
if (countAllInstances != null) {
return countAllInstances;
}
final int answer = countAllInstances(collection, makeELMt(mt));
countAllInstancesCache.put(collection, answer);
return answer;
} |
3f377cb3-6b6b-44c2-9f26-e3ba80fc7fe1 | 1 | public boolean isSetForCommitting() {
// TODO Auto-generated method stub
return session != null || session.getTransaction().isActive();
} |
a95ee75f-60a5-4cc6-b5f7-ae2ff596e8a8 | 8 | public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TimeSeriesDataItem)) {
return false;
}
TimeSeriesDataItem timeSeriesDataItem = (TimeSeriesDataItem) o;
if (this.period != null) {
if (!this.period.equals(timeSeriesDataItem.period)) {
return false;
}
}
else if (timeSeriesDataItem.period != null) {
return false;
}
if (this.value != null) {
if (!this.value.equals(timeSeriesDataItem.value)) {
return false;
}
}
else if (timeSeriesDataItem.value != null) {
return false;
}
return true;
} |
b0118871-f2ae-4ee9-9b61-c8a05aa4b1af | 7 | public boolean addComponentParts(World par1World, Random par2Random, StructureBoundingBox par3StructureBoundingBox)
{
if (averageGroundLevel < 0)
{
averageGroundLevel = getAverageGroundLevel(par1World, par3StructureBoundingBox);
if (averageGroundLevel < 0)
{
return true;
}
boundingBox.offset(0, ((averageGroundLevel - boundingBox.maxY) + 12) - 1, 0);
}
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 1, 3, 3, 7, 0, 0, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 5, 1, 3, 9, 3, 0, 0, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 0, 0, 3, 0, 8, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 0, 3, 10, 0, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 1, 1, 0, 10, 3, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 4, 1, 1, 4, 10, 3, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 0, 4, 0, 4, 7, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 4, 0, 4, 4, 4, 7, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 8, 3, 4, 8, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 5, 4, 3, 10, 4, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 5, 5, 3, 5, 7, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 9, 0, 4, 9, 4, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 4, 0, 4, 4, 4, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 0, 11, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 4, 11, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 2, 11, 0, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 2, 11, 4, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 1, 1, 6, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 1, 1, 7, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 2, 1, 7, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 3, 1, 6, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.cobblestone.blockID, 0, 3, 1, 7, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 3), 1, 1, 5, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 3), 2, 1, 6, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 3), 3, 1, 5, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 1), 1, 2, 7, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 0), 3, 2, 7, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 2, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 3, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 4, 2, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 4, 3, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 6, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 7, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 4, 6, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 4, 7, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 2, 6, 0, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 2, 7, 0, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 2, 6, 4, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 2, 7, 4, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 3, 6, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 4, 3, 6, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 2, 3, 8, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, 2, 4, 7, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, 1, 4, 6, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, 3, 4, 6, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, 2, 4, 5, par3StructureBoundingBox);
int i = getMetadataWithOffset(Block.ladder.blockID, 4);
for (int j = 1; j <= 9; j++)
{
placeBlockAtCurrentPosition(par1World, Block.ladder.blockID, i, 3, j, 3, par3StructureBoundingBox);
}
placeBlockAtCurrentPosition(par1World, 0, 0, 2, 1, 0, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, 0, 0, 2, 2, 0, par3StructureBoundingBox);
placeDoorAtCurrentPosition(par1World, par3StructureBoundingBox, par2Random, 2, 1, 0, getMetadataWithOffset(Block.doorWood.blockID, 1));
if (getBlockIdAtCurrentPosition(par1World, 2, 0, -1, par3StructureBoundingBox) == 0 && getBlockIdAtCurrentPosition(par1World, 2, -1, -1, par3StructureBoundingBox) != 0)
{
placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 3), 2, 0, -1, par3StructureBoundingBox);
}
for (int k = 0; k < 9; k++)
{
for (int l = 0; l < 5; l++)
{
clearCurrentPositionBlocksUpwards(par1World, l, 12, k, par3StructureBoundingBox);
fillCurrentPositionBlocksDownwards(par1World, Block.cobblestone.blockID, 0, l, -1, k, par3StructureBoundingBox);
}
}
spawnVillagers(par1World, par3StructureBoundingBox, 2, 1, 2, 1);
return true;
} |
21c5797b-25c5-4563-b9b9-f519c4e379bf | 9 | void updateSubTree(double[][] A, edge nearEdge, node v, node root,
node newNode, double dcoeff, direction d )
{
edge sib;
switch( d )
{
case UP: //newNode is above the edge nearEdge
A[v.index][nearEdge.head.index] = A[nearEdge.head.index][v.index];
A[newNode.index][nearEdge.head.index] =
A[nearEdge.head.index][newNode.index] =
A[nearEdge.head.index][root.index];
if (null != nearEdge.head.leftEdge)
updateSubTree(A, nearEdge.head.leftEdge, v, root, newNode,
0.5*dcoeff, direction.UP);
if (null != nearEdge.head.rightEdge)
updateSubTree(A, nearEdge.head.rightEdge, v, root, newNode,
0.5*dcoeff, direction.UP);
updatePair(A, nearEdge, nearEdge, v, root, dcoeff, direction.UP);
break;
case DOWN: //newNode is below the edge nearEdge
A[nearEdge.head.index][v.index] = A[v.index][nearEdge.head.index];
A[newNode.index][nearEdge.head.index] =
A[nearEdge.head.index][newNode.index] =
0.5*(A[nearEdge.head.index][root.index]
+ A[v.index][nearEdge.head.index]);
sib = nearEdge.siblingEdge();
if (null != sib)
updateSubTree(A, sib, v, root, newNode, 0.5*dcoeff,
direction.SKEW);
if (null != nearEdge.tail.parentEdge)
updateSubTree(A, nearEdge.tail.parentEdge, v, root,
newNode, 0.5*dcoeff, direction.DOWN);
updatePair(A, nearEdge, nearEdge, v, root, dcoeff, direction.DOWN);
break;
case SKEW: //newNode is neither above nor below nearEdge
A[v.index][nearEdge.head.index] = A[nearEdge.head.index][v.index];
A[newNode.index][nearEdge.head.index] =
A[nearEdge.head.index][newNode.index] =
0.5*(A[nearEdge.head.index][root.index] +
A[nearEdge.head.index][v.index]);
if (null != nearEdge.head.leftEdge)
updateSubTree(A, nearEdge.head.leftEdge, v, root,
newNode, 0.5*dcoeff,direction.SKEW);
if (null != nearEdge.head.rightEdge)
updateSubTree(A, nearEdge.head.rightEdge, v, root,
newNode, 0.5*dcoeff,direction.SKEW);
updatePair(A, nearEdge, nearEdge, v, root, dcoeff, direction.UP);
}
} |
0d16b948-4d1d-40e5-b4d4-83c304451a5c | 0 | public Tiedostonkirjoittaja() {
} |
b0083e7a-b898-4fe5-8f05-dd5d6d145c37 | 7 | Point3f getMin() {
if (min == null)
min = new Point3f();
if (list.isEmpty()) {
min.set(0, 0, 0);
return min;
}
Cuboid c = getCuboid(0);
min.x = c.getMinX();
min.y = c.getMinY();
min.z = c.getMinZ();
synchronized (list) {
int n = count();
if (n > 1) {
for (int i = 1; i < n; i++) {
c = getCuboid(i);
if (min.x > c.getMinX()) {
min.x = c.getMinX();
}
if (min.y > c.getMinY()) {
min.y = c.getMinY();
}
if (min.z > c.getMinZ()) {
min.z = c.getMinZ();
}
}
}
}
return min;
} |
d5390f92-836f-456b-97fa-d10f27cfc7f0 | 4 | public boolean experiment() {
int sum = 0;
for (int i = 0; i < diceScoreTracker.length; i++) {
diceScoreTracker[i] = 1 + (int)(6 * Math.random());
/* Loop through current scores and check if any add
up to 7 when compared to the newly inserted score */
/* With this method, the newly added value is compared
to itself as well, but since 3+3 != 7 and 4+4 != 7
it makes no difference. To avoid, simply add continue
statement if i = j.*/
int j = 0;
while (j < diceScoreTracker.length && diceScoreTracker[j] != 0) {
if (diceScoreTracker[i] + diceScoreTracker[j] == 7) {
return true;
}
j++;
}
}
return false;
} |
1578a3e7-6f73-438b-8073-b667f514614a | 0 | private void Stop(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Stop
programmerThread.stop();
hidePanels(lastPane);
}//GEN-LAST:event_Stop |
902ffdbe-4e4d-45f9-8569-d49129806e70 | 5 | @Override
public void learn() {
world.setData(Data.SHAPES[6]);
network.learn();
int i=0;
while (i < 100 && !Options.getOptions().getStopped()) {
// recuperer un certain nombre de donnees
int nbNew = (int)(Math.random() * world.getData().size());
double lx = Math.random();
double ly = Math.random();
System.out.println(" lx = " + lx + " ly = " + ly);
for (int j = 0 ; j < nbNew ; j++) {
int index = (int)(Math.random() * world.getData().size());
DataPoint data = world.getData().get(index);
double nbdim = Math.random();
double x,y;
if (nbdim < .333) {
// modification de la premiere dimension
x = Math.random() * lx;
y = (double) data.getPoids().get(1);
} else if (nbdim < .666) {
// modification de la seconde dimension
x = (double) data.getPoids().get(1);
y = Math.random() * ly;
} else {
// modification des deux dimensions
x = Math.random() * lx;
y = Math.random() * ly;
}
ArrayList<Float> poids = new ArrayList<Float>();
poids.add(new Float(x));
poids.add(new Float(y));
world.getData().set(index,new DataPoint(poids));
}
i++;
network.learn();
}
} |
4f6e80ac-fedd-4f4a-81ee-0282e4370b7b | 1 | public TimerTask getAlarm() {
TimerTask task;
if(repeating) {
task = repeatingAlarm();
} else {
task = singleAlarm();
}
scheduledTask = task;
return task;
} |
8de91e82-e7cf-4efb-8629-130ba1471550 | 2 | public Metrics(final Plugin plugin) throws IOException {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin;
// load the config
configurationFile = getConfigFile();
configuration = YamlConfiguration.loadConfiguration(configurationFile);
// add some defaults
configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString());
configuration.addDefault("debug", false);
// Do we need to create the file?
if (configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org").copyDefaults(true);
configuration.save(configurationFile);
}
// Load the guid then
guid = configuration.getString("guid");
debug = configuration.getBoolean("debug", false);
} |
d22bec85-2f52-44df-90f8-3c338f9487fb | 9 | protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption)
{
init();
this.options = options;
// an iterator for the command line tokens
Iterator iter = Arrays.asList(arguments).iterator();
// process each command line token
while (iter.hasNext())
{
// get the next command line token
String token = (String) iter.next();
// handle long option --foo or --foo=bar
if (token.startsWith("--"))
{
int pos = token.indexOf('=');
String opt = pos == -1 ? token : token.substring(0, pos); // --foo
if (!options.hasOption(opt))
{
processNonOptionToken(token, stopAtNonOption);
}
else
{
currentOption = options.getOption(opt);
tokens.add(opt);
if (pos != -1)
{
tokens.add(token.substring(pos + 1));
}
}
}
// single hyphen
else if ("-".equals(token))
{
tokens.add(token);
}
else if (token.startsWith("-"))
{
if (token.length() == 2 || options.hasOption(token))
{
processOptionToken(token, stopAtNonOption);
}
// requires bursting
else
{
burstToken(token, stopAtNonOption);
}
}
else
{
processNonOptionToken(token, stopAtNonOption);
}
gobble(iter);
}
return (String[]) tokens.toArray(new String[tokens.size()]);
} |
44891649-8ae6-461c-be93-74d9fa0f786e | 5 | public static void loadPreferences(File prefSet) {
if (loadFrom == null){
try {
loadFrom = prefSet;
Scanner lineIter = new Scanner(prefSet);
lineIter.useDelimiter(",\n?");
String flag = null;
double value = 0;
int i = 0;
Preferences insert = new Preferences();
while (lineIter.hasNext()){
try{
flag = lineIter.next(); //gets a pair
value = lineIter.nextDouble();
}catch(Exception e)
{
e.printStackTrace();
}
insert.put(Enum.valueOf(Preference.class, flag), value);
if (i%Preference.values().length == Preference.values().length - 1){
//insert.put(Preference.smallestAlloc, 0.01); i++; //temporary to load new value type.
loaded.add(insert);
insert = new Preferences();
}
i++;
}
lineIter.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
54eb5bbc-fc23-4ed2-b7a8-3ee0c0f30fe1 | 0 | @After
public void tearDown() {
} |
b95cb2af-cf0e-49f4-8bb3-07d50b2809d0 | 0 | public static String getString(byte [] src, int srcPos,int destPos,int length){
byte[] tmp=new byte[length];
System.arraycopy(src, srcPos, tmp, destPos, length);
return (new String(tmp).trim());
} |
ccc04ecb-f66a-4edc-b123-1fd9691d2341 | 0 | public void setDoubleOptin(boolean doubleOptin) {
this.doubleOptin = doubleOptin;
} |
ca02e375-0ba7-4f9a-964b-8898a251ad5e | 3 | private void convertToUserTime(ArrayList result, double userTimeZone)
{
if (result == null) {
return;
}
double resTimeZone = resource_.getResourceTimeZone();
long[] array = null;
long from = 0;
try
{
// convert the start time of a local time to a user time
Iterator it = result.iterator();
while ( it.hasNext() )
{
array = (long[]) it.next();
from = AdvanceReservation.convertTimeZone(array[0], resTimeZone,
userTimeZone);
array[0] = from;
}
}
catch (Exception e) {
// print error msg
}
} |
27989e48-3566-4c4c-9280-05ef821d5fd3 | 1 | */
protected void repaintProxyRow(Row row) {
repaint(getRowBounds(row));
for (OutlineProxy proxy : mProxies) {
proxy.repaintProxy(proxy.getRowBounds(row));
}
} |
3628dce9-d403-4af8-9016-3f26e67fa048 | 0 | private void newTournButtonActionPerformed(java.awt.event.ActionEvent evt) {
worlds = new ArrayList<>();
brains = new ArrayList<>();
} |
d3198915-621a-444d-ade7-6209c168f334 | 2 | public void create(String user, String host) throws JSchException{
try{
// RFC 1964
Oid krb5=new Oid("1.2.840.113554.1.2.2");
// Kerberos Principal Name Form
Oid principalName=new Oid("1.2.840.113554.1.2.2.1");
GSSManager mgr=GSSManager.getInstance();
GSSCredential crd=null;
/*
try{
GSSName _user=mgr.createName(user, principalName);
crd=mgr.createCredential(_user,
GSSCredential.DEFAULT_LIFETIME,
krb5,
GSSCredential.INITIATE_ONLY);
}
catch(GSSException crdex){
}
*/
String cname=host;
try{
cname=InetAddress.getByName(cname).getCanonicalHostName();
}
catch(UnknownHostException e){
}
GSSName _host=mgr.createName("host/"+cname, principalName);
context=mgr.createContext(_host,
krb5,
crd,
GSSContext.DEFAULT_LIFETIME);
// RFC4462 3.4. GSS-API Session
//
// When calling GSS_Init_sec_context(), the client MUST set
// integ_req_flag to "true" to request that per-message integrity
// protection be supported for this context. In addition,
// deleg_req_flag MAY be set to "true" to request access delegation, if
// requested by the user.
//
// Since the user authentication process by its nature authenticates
// only the client, the setting of mutual_req_flag is not needed for
// this process. This flag SHOULD be set to "false".
// TODO: OpenSSH's sshd does accepts 'false' for mutual_req_flag
//context.requestMutualAuth(false);
context.requestMutualAuth(true);
context.requestConf(true);
context.requestInteg(true); // for MIC
context.requestCredDeleg(true);
context.requestAnonymity(false);
return;
}
catch(GSSException ex){
throw new JSchException(ex.toString());
}
} |
7d1f0f2e-ebda-4caf-8bc8-f5f7b9461061 | 5 | private void onCommand(String cmd) {
String[] parts = cmd.split(" ");
if(parts.length < 1) {
return;
}
switch(parts[0]) {
case "/help":
output.println("Available commands:");
output.println("/help");
output.println("/start");
output.println("/list");
output.println("/kick");
break;
case "/ai":
output.println("add ai...");
addAi(120, null);
break;
case "/sunzi":
output.println("add SunZi...");
addAi(2000, "SunZi");
break;
case "/start":
startServer();
break;
default:
output.println("Unknown command!");
}
} |
30d5eb19-2eb2-42f5-80ab-7ff3b8ed592a | 3 | private void initializeLanguageMenuSelection() {
Logger.getLogger(MainInterface.class.getName()).entering(MainInterface.class.getName(), "initializeLanguageMenuSelection");
String languageWanted = PropertiesManager.getInstance().getKey("language");
if (languageWanted != null) {
switch (languageWanted) {
case "fr":
frenchLanguageCheckBoxMenuItem.setSelected(true);
Logger.getLogger(MainInterface.class.getName()).log(Level.INFO, "Setting language menu selection to French");
break;
case "en":
englishLanguageCheckBoxMenuItem.setSelected(true);
Logger.getLogger(MainInterface.class.getName()).log(Level.INFO, "Setting language menu selection to English");
break;
}
}
Logger.getLogger(MainInterface.class.getName()).exiting(MainInterface.class.getName(), "initializeLanguageMenuSelection");
} |
e3d82a38-9af8-4f39-923c-0dd53cdbe03d | 1 | public void setOptstring(String optstring) {
if (optstring.length() == 0)
optstring = " ";
this.optstring = optstring;
} |
c93938e1-73f5-461b-99cd-f49d3bf51c86 | 7 | public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
// Tell all plotters to stop gathering information.
for (Graph graph : graphs) {
graph.onOptOut();
}
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
} |
5c568c45-4018-4b84-bc22-6df754b1d172 | 9 | public void travelTo(double x1, double y1, int speed) {
// instantiate variables
double x0, y0; // current position
double theta1; // new heading
double forwardError; // distance from destination coordinates
double[] displacementVector = new double[2]; // vector connecting actual
// position to
// destination
// coordinates
// set isNavigating to true
setIsNavigating(true);
// set destinationReached = false
setDestinationReached(false);
// stop motors
setSpeeds(0, 0);
while (!destinationReached && !ObjectDetection.objectDetected) {
// set isNavigating to true
setIsNavigating(true);
// get robot's current position
x0 = odometer.getX();
y0 = odometer.getY();
// calculate new heading (ie. towards destination point)
theta1 = Math.atan((y1 - y0) / (x1 - x0)) * 180 / Math.PI;
// adjust value of theta1 according to deltaX and deltaY
if ((x1 - x0) < 0 && (y1 - y0) > 0) { // if heading should be in 2nd
// quadrant
theta1 = theta1 + 180;
}
if ((x1 - x0) < 0 && (y1 - y0) < 0) { // if heading should be in 3rd
// quadrant
theta1 = theta1 + 180;
}
if ((x1 - x0) > 0 && (y1 - y0) < 0) { // if heading should be in 4th
// quadrant
theta1 = theta1 + 360;
}
turnTo(theta1, speed);
// // Forward Error Calculation
// get update robot's current position and heading
x0 = odometer.getX();
y0 = odometer.getY();
// calculation of displacement vector
displacementVector[0] = x1 - x0;
displacementVector[1] = y1 - y0;
// find magnitude of displacement vector to obtain forward error
forwardError = Math
.sqrt((displacementVector[0] * displacementVector[0])
+ (displacementVector[1] * displacementVector[1]));
// decide whether destination has been reached or not. If yes, stop
// motors.
if (Math.abs(forwardError) <= POSITION_ERR) {
setDestinationReached(true);
leftMotor.stop(true);
rightMotor.stop(true);
} else {
setDestinationReached(false);
// make robot move forward
leftMotor.forward();
rightMotor.forward();
leftMotor.setSpeed(speed);
rightMotor.setSpeed(speed);
}
// set isNavigating to false
setIsNavigating(false);
}
} |
8809b816-f1a2-44fa-ac54-0389b2862b3a | 8 | private void runPPD(ATMCell cell){
boolean cellDropped = false;
double dropProbability = 0.0;
if (cell.getData().equals("")) {
this.dropSamePacketCell = false;
}
if (this.dropSamePacketCell == false) {
if (outputBuffer.size() > this.startDropAt) {
if (outputBuffer.size() < this.maximumBufferCells) {
dropProbability = (outputBuffer.size() - this.startDropAt)
/ (double)(this.maximumBufferCells - this.startDropAt);
}
else {
dropProbability = 1;
}
}
if (dropProbability > 0) {
double r = Math.random() * 1.0 / dropProbability;
if (r <= 1.0) {
cellDropped = true;
this.dropSamePacketCell = true;
}
}
}
else {
cellDropped = true;
}
// Output to the console what happened
if(cellDropped)
System.out.println("The cell " + cell.getTraceID() + " was dropped");
else {
outputBuffer.add(cell);
if(this.trace)
System.out.println("The cell " + cell.getTraceID() + " was added to the output queue");
}
} |
1082360c-be1d-4714-9491-fccb32d5e58e | 4 | private void removePlayer(Player plr) {
if(plr.Privatechat != 2) { //PM System
for(int i = 1; i < maxPlayers; i++) {
if (players[i] == null || players[i].isActive == false) continue;
players[i].pmupdate(plr.playerId, 0);
}
}
// anything can be done here like unlinking this player structure from any of the other existing structures
plr.destruct();
} |
f5accbd9-494b-412e-88bb-ace2b08923ba | 3 | public BufferedImage getEffectImage(){
if((int)animation == 3){
animation =0.0f;
if(!isLooping){
stop =true;
}
}
if(!stop){
img = animImages[(int)animation];
animation += 0.33f;
return img;
}else{
img = stoppedImg;
return img;
}
} |
e7470bf9-2067-4fe7-886e-bd6f0eba56a1 | 5 | private Object getNextItem(Object component,
Object item, boolean recursive) {
if (!recursive) { return get(item, ":next"); }
Object next = get(item, ":comp");
if ((next == null) || !getBoolean(item, "expanded", true)) {
while ((item != component) && ((next = get(item, ":next")) == null)) {
item = getParent(item);
}
}
return next;
} |
241cbdfa-fc3d-433a-9624-c408335b9b6c | 5 | public void gfxAll(int id, int Y, int X)
{
for (Player p : server.playerHandler.players)
{
if(p != null)
{
client person = (client)p;
if((person.playerName != null || person.playerName != "null"))
{
if(person.distanceToPoint(X, Y) <= 60)
{
person.stillgfx2(id, Y, X);
}
}
}
}
} |
2d805b5f-30d8-4091-8198-3be44713da4f | 8 | public Packet packet() throws IOException {
if(eos)
return(null);
if(strm == null) {
strm = new StreamState();
page = in.page();
strm.init(page.serialno());
}
Packet pkt = new Packet();
while(true) {
int ret = strm.packetout(pkt);
if(ret < 0)
throw(new OggException()); /* ? */
if(ret == 1)
return(pkt);
if(page == null) {
if((page = in.page()) == null) {
eos = true;
return(null);
}
}
if(strm.pagein(page) != 0)
throw(new OggException());
page = null;
}
} |
cacf10a2-62c3-4a96-b998-948ff7a8eeeb | 0 | public CrossJoinIterable(Iterable<T> first, Iterable<TInner> second, Joint<T, TInner, TResult> joint)
{
this._first = first;
this._second = second;
this._joint = joint;
} |
efb249d2-947f-4b0c-8e68-2e67a9afb867 | 2 | public void update(GameContainer container, int delta) {
boolean isOn = InputChecker.isInputDown(container, KeyBindings.P1_INPUT);
if (!eventList.isEmpty() && eventList.get(0).isOn() == isOn) {
eventList.get(0).pushLength(delta);
} else {
eventList.add(0, new RhythmEvent(isOn, delta));
}
} |
8f645cef-2153-4b8d-975a-efdd6e9444d2 | 5 | public eNfa(List<State> states, List<String> symbols, List<Transition> transitions, State startingState,
List<State> acceptableStates) {
super(states, symbols, transitions, startingState, acceptableStates);
this.states = states;
this.symbols = symbols;
this.transitions = transitions;
this.startingState = startingState;
this.acceptableStates = acceptableStates;
for (Transition t : this.transitions) {
if (t.getKey().equals(EPSILON)) {
this.epsilonInstances.add(t.getOrigin());
t.getOrigin().eTransition = t;
}
t.getOrigin().transitions.add(t);
if (!this.states.contains(t.getOrigin()) || !this.states.containsAll(t.getDestinations())) {
StringBuilder sb = new StringBuilder();
sb.append("Transition contains a state not present in the state list!\nTransition:\n\t");
sb.append(t);
sb.append("\nState list:\n");
for (State s : states) {
sb.append("\t");
sb.append(s);
sb.append("\n");
}
throw new IllegalArgumentException(sb.toString());
}
}
minimise();
initialise();
} |
76e41eab-eaac-4780-b3fc-587e83d61009 | 4 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Server other = (Server) obj;
if (id != other.id)
return false;
return true;
} |
9dad0696-dc2a-4632-91d0-9b59470b31a0 | 4 | public void insert(TemperatureStatus t) {
Object[] args=new Object[2];
args[0]=t.pv;
args[1]="";
if (t.cooling) args[1]="cooling";
if (t.heating) args[1]="heating";
if (t.heating && t.cooling) args[1]="heating,cooling";
String sql="replace into pv set pv=?,output=?";
tp.update(sql,args);
} |
abd584d5-9721-4009-bcf4-72c8fcd64c18 | 8 | public Boolean updatePosition()
{
Boolean retour = true;
// Choix de la nouvelle position
Integer[] mvt = model.move(new Neighborhood(this));
// Definition des variables pour la nouvelle position
Integer[] nextPos = new Integer[3];
nextPos[0] = line + mvt[0];
nextPos[1] = colonne + mvt[1];
nextPos[2] = id;
// On verifie si la case est libre
if(!controlleur.isOccupied(nextPos))
{
line += mvt[0];
colonne += mvt[1];
// Si la prochaine case n'est pas dans le systeme
if( line < 0 || line > getGrid().getNbLines() - 1 ||
colonne < 0 || colonne > getGrid().getNbColumns() - 1 )
{
retour = false;
}
else
{
// Si la personne ne s'est pas deplacee en diagonale, on augmente la distance
if(Math.abs(mvt[0] + mvt[1]) == 1)
{
//System.out.println("Depla. ligne - " + distance);
distance = distance + 1;
}
// Si elle deplacee en diagonale, on change l'operation
else if(mvt[0] != 0 && mvt[1] != 0)
{
//System.out.println("Depla. diag - " + distance);
distance = distance + 1 + diagonalLength;
}
}
}
return retour;
} |
b07ab30e-855c-48cd-8d84-ba19b5fef488 | 5 | private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
Convenio f = new Convenio();
if(!(txCodigo.getText().equals(""))||(txCodigo.getText().equals(null))){
f.setCodigo(Integer.parseInt(txCodigo.getText()));
}
f.setNome(txNome.getText());
ConvenioController fc = new ConvenioController();
if(f.getCodigo() == 0){
int id = fc.salvar(f);
if(id>0){
JOptionPane.showMessageDialog(this, "Salvo com sucesso... Voltando ao menu Pirncipal");
modelo.addRow(new Object[]{id , f.getNome()});
}
}
else{
int id = fc.salvar(f);
if(id > 0){
modelo.removeRow(linhaSelecionada);
modelo.addRow(new Object[]{id, f.getNome()});
}
}
dispose();
}//GEN-LAST:event_btSalvarActionPerformed |
db5a02ea-3ae9-47bc-a83b-4bb1761ba6ad | 7 | private void setMinMaxPoints(List<Vector> points) {
int minX = points.get(0).getBlockX();
int minY = points.get(0).getBlockY();
int minZ = points.get(0).getBlockZ();
int maxX = minX;
int maxY = minY;
int maxZ = minZ;
for (Vector v : points) {
int x = v.getBlockX();
int y = v.getBlockY();
int z = v.getBlockZ();
if (x < minX) {
minX = x;
}
if (y < minY) {
minY = y;
}
if (z < minZ) {
minZ = z;
}
if (x > maxX) {
maxX = x;
}
if (y > maxY) {
maxY = y;
}
if (z > maxZ) {
maxZ = z;
}
}
min = new BlockVector(minX, minY, minZ);
max = new BlockVector(maxX, maxY, maxZ);
} |
9abfcf57-06f3-4e10-aefa-30edba87b0e7 | 3 | public static void computePaths(Vertex source) {
source.setMinDistance(0.);
// Using PriorityQueue class with minDistance as a priority (see the comparator of Vertex)
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();
// Visit each edge exiting u
for (Edge_old e : u.getEdges()) {
Vertex v = e.getTarget();
double weight = e.getWeight();
// relax the edge (u, v) :
// if (u, v) is an edge and u is on the shortest path to v, then d(u) + w(u,v) = d(v).
double distanceThroughU = u.getMinDistance() + weight;
if (distanceThroughU < v.getMinDistance()) {
// The priority queue does not like when the ordering of its elements is changed, so
// when we change the minimum distance of any vertex, we need to remove it and re-insert
// it into the set.
vertexQueue.remove(v);
v.setMinDistance(distanceThroughU);
v.setPrevious(u);
vertexQueue.add(v);
}
}
}
} |
2563c696-ece5-4800-a856-2bde50bf6d95 | 2 | public void initialize() {
String parameter = this.getParamString();
if(parameter.equals("")){
if(Configuration.dimX < Configuration.dimY){
radius = Configuration.dimX / 3.0;
}
else{
radius = Configuration.dimY / 3.0;
}
}
else{
radius = Double.parseDouble(parameter);
}
oneStep = 360.0 / numberOfNodes;
} |
09647b35-31ca-4c9b-bf52-32b1920f0477 | 7 | @Override
public void onTrackerStateChanged(int trackerState) {
trackeStateOK = false;
String errorMessage = "";
if (trackerState == 0)
trackeStateOK = true;
else if (trackerState == 1)
errorMessage = "Device not connected.";
else if (trackerState == 2)
errorMessage = "A firmware updated is required.";
else if (trackerState == 3)
errorMessage = "Device connected to a USB2.0 port";
else if (trackerState == 4)
errorMessage = "No data coming out of the sensor.";
System.out.println(trackeStateOK + " --> " + errorMessage);
if (isAborting){
StopAndClose(errorMessage);
}
if (trackeStateOK == false){
// Lost device, abort calib now (raise event)
AbortCalibration(errorMessage);
}
} |
8c38a1f5-639e-416f-92cf-1e58821b7e24 | 7 | public String combineStr(REPrimitiveFragment frag)
{
String ret = "[";
for(int i = 0; i < chars.length; i++)
{
if(chars[i] && frag.chars[i])
{
if(i == 91 - 32 ) ret += "\\[";
else if(i == 93 - 32) ret += "\\]";
else if(i == 94 - 32) ret += "\\^";
else if(i == 92 - 32) ret += "\\\\";
else ret += String.valueOf((char)(i + 32));
}
}
return ret + "]";
} |
c159ff22-2221-4259-bada-6ea1e08337ae | 6 | public boolean hasUnaryInput() {
if (left instanceof LvalExpression &&
((LvalExpression) left).hasUnaryInput()) {
return true;
}
if (middle instanceof LvalExpression &&
((LvalExpression) middle).hasUnaryInput()) {
return true;
}
if (right instanceof LvalExpression &&
((LvalExpression) right).hasUnaryInput()) {
return true;
}
return false;
} |
e9ebd51f-6610-4f80-9322-c41fe0014692 | 4 | public void testGraphWithMatrix() {
long[][] graph = {{0, 1, 7, 1000, 1000}, {1, 0, 1000, 4, 1}, {7, 1000, 0, 1, 1000}, {1000, 4, 1, 0, 1}, {1000, 1, 1000, 1, 0}};
long[][] paths = new long[5][5];
Floyd.calculate(graph, paths);
for (int i = 0; i < graph.length; i++) {
for (int j = 0; j < graph.length; j++) {
System.out.print(graph[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println();
for (int i = 0; i < paths.length; i++) {
for (int j = 0; j < paths.length; j++) {
System.out.print(paths[i][j] + " ");
}
System.out.println();
}
} |
2f4e3940-8423-4f2e-8350-2368f618ba0f | 8 | private static int applyMaskPenaltyRule1Internal(ByteMatrix matrix, boolean isHorizontal) {
int penalty = 0;
int numSameBitCells = 0;
int prevBit = -1;
// Horizontal mode:
// for (int i = 0; i < matrix.height(); ++i) {
// for (int j = 0; j < matrix.width(); ++j) {
// int bit = matrix.get(i, j);
// Vertical mode:
// for (int i = 0; i < matrix.width(); ++i) {
// for (int j = 0; j < matrix.height(); ++j) {
// int bit = matrix.get(j, i);
int iLimit = isHorizontal ? matrix.getHeight() : matrix.getWidth();
int jLimit = isHorizontal ? matrix.getWidth() : matrix.getHeight();
byte[][] array = matrix.getArray();
for (int i = 0; i < iLimit; ++i) {
for (int j = 0; j < jLimit; ++j) {
int bit = isHorizontal ? array[i][j] : array[j][i];
if (bit == prevBit) {
numSameBitCells += 1;
// Found five repetitive cells with the same color (bit).
// We'll give penalty of 3.
if (numSameBitCells == 5) {
penalty += 3;
} else if (numSameBitCells > 5) {
// After five repetitive cells, we'll add the penalty one
// by one.
penalty += 1;
}
} else {
numSameBitCells = 1; // Include the cell itself.
prevBit = bit;
}
}
numSameBitCells = 0; // Clear at each row/column.
}
return penalty;
} |
d0095fc8-cced-4170-8d3f-da0223cd1d05 | 8 | public static void main(final String args[]) {
System.out.println("Starting launcher");
EventQueue.invokeLater(new Runnable() {
public void run() {
System.out.println("Creating new instance");
instance = new LauncherMain();
System.out.println("Setting visible");
instance.setVisible(true);
if (args.length >= 1) {
instance.loginPanel1.setUsername(args[0]);
if (args.length >= 2) {
instance.loginPanel1.setPassword(args[1]);
if (args.length >= 3) {
instance.loginPanel1.setForceUpdate(args[2]);
}
}
}
System.out.println("Creating site pages");
try {
URL pageList = new URL("https://raw.github.com/LordRalex/DebugMCLauncher/master/pages.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(pageList.openStream()));
String line;
List<String> list = new ArrayList<String>();
while ((line = reader.readLine()) != null) {
System.out.println(line);
System.out.println(line.substring(0, line.indexOf("|")).trim());
System.out.println(line.substring(line.indexOf("|") + 1).trim());
list.add(line);
}
reader.close();
for (String page : list) {
if (page == null || !page.contains("|")) {
continue;
}
String tabName = page.substring(0, page.indexOf("|")).trim();
String link = page.substring(page.indexOf("|") + 1).trim();
InformationPanel panel = new InformationPanel();
instance.webPagesTabPanel.addTab(tabName, panel);
panel.getNewsFeed(link);
}
} catch (IOException e) {
e.printStackTrace(System.out);
instance.webPagesTabPanel.removeAll();
System.out.println("Loading MC tumblr");
InformationPanel mcupdate = new InformationPanel();
instance.webPagesTabPanel.addTab("Minecraft Tumblr", mcupdate);
mcupdate.getNewsFeed("http://mcupdate.tumblr.com/");
System.out.println("Loading SG page");
InformationPanel supportguru = new InformationPanel();
instance.webPagesTabPanel.addTab("Support Guru", supportguru);
supportguru.getNewsFeed("http://supportgurus.org/");
}
System.out.println("Loading system information");
instance.systemInformationPanel1.getSystemInfo();
System.out.println("Refreshing main screen");
instance.update(instance.getGraphics());
}
});
System.out.println("Event invoked");
} |
ba5dcba3-052f-451d-9054-60c014a2ad19 | 2 | public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Hello: " + i + " Thread: " + Thread.currentThread().getName());
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {}
}
}
});
thread1.start();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.