method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
03d4b8ad-0f8c-4624-a13b-26de9b57d029 | 5 | public String toString(){
String res = new String();
if(msg != null)
res += msg;
if(codErr != null)
res += !res.isEmpty() ? " - " + codErr : codErr;
if(sourceException != null)
res += !res.isEmpty() ? "\n" + sourceException : sourceException;
return res;
} |
bbe488c7-372e-43a6-873a-e9b1c5de9e04 | 8 | public ArrayList<File> indexSearch(String searchPath, String searchKey) {
ArrayList<File> matches = new ArrayList<File>();
for(File searchSubject : indexFiles(searchPath)) {
if(searchSubject.isDirectory()) {
for(File searchSubjectSub : indexSearch(searchSubject.getAbsolutePath(), searchKey)) {
matches.add(searchSubjectSub);
}
} else {
if(searchSubject.getAbsolutePath().contains(searchKey)) {
if(searchSubject.getName().charAt(0) != '.') {
if(searchSubject.isDirectory()) {
matches.add(searchSubject);
} else if(URLConnection.guessContentTypeFromName(searchSubject.getName()) != null) {
if(URLConnection.guessContentTypeFromName(searchSubject.getName()).substring(0, 5).equalsIgnoreCase("image")) {
matches.add(searchSubject);
}
}
}
}
}
}
return matches;
} |
4126ac6e-5da5-4d69-990b-c5a7b6dba627 | 5 | private void playlistEditMenu() {
System.out.println(" Edit Menu ");
System.out.println("1. |Create a playlist |");
System.out.println("2. |Add song to a playlist |");
System.out.println("3. |Delete a playlist |");
System.out.println("4. |Delete a song from a playlist |");
System.out.println("0. |Return |");
int option;
option = new Scanner(System.in).nextInt();
switch (option) {
case 1:
createPlaylist();
break;
case 2:
addSongToPlaylist();
break;
case 3:
deletePlaylist();
break;
case 4:
deleteFromPlaylist();
break;
case 0:
playlistMenu();
break;
}
} |
0e4d8c6b-5dbd-4222-959f-9b74424910b7 | 1 | public CtClass getType() throws NotFoundException {
int type = etable.catchType(index);
if (type == 0)
return null;
else {
ConstPool cp = getConstPool();
String name = cp.getClassInfo(type);
return thisClass.getClassPool().getCtClass(name);
}
} |
ddef6420-38a3-4592-a580-bae6e594988d | 7 | public void draw(Graphics2D g, Player player) {
int Px = player.getScreenXpos()/32; //get row number
int Py = (player.getScreenYpos()/32);
int arroundX = 16;
int arroundY = 10;
int someX = Px-arroundX;
int someXMax = Px+arroundX;
int someY = Py-arroundY;
int someYMax = Py+arroundY;
for(int row = someY; row < someYMax; row ++){
for(int col = someX; col < someXMax; col ++){
if(row >= 0 && row < mapYRows)
;
else
continue;
if(col >= 0 && col < mapXRows)
;
else
continue;
if (map[row][col] == 0)
continue;
final int rc = map[row][col];
final int r = rc / numTilesAcross;
final int c = rc % numTilesAcross;
//TODO only draw a selection of images, not the entire map
g.drawImage(tiles[r][c].getImage(), (int) x + (col * tileSize),
(int) y + (row * tileSize), null);
}
}
// for (int row = rowOffset; row < (rowOffset + numRowsToDraw); row++) {
//
// if (row >= mapYRows)
// break;
//
// for (int col = colOffset; col < (colOffset + numColsToDraw); col++) {
//
// if (col >= mapXRows)
// break;
//
// if (map[row][col] == 0)
// continue;
//
// final int rc = map[row][col];
// final int r = rc / numTilesAcross;
// final int c = rc % numTilesAcross;
// // System.out.println(r + " " + c + " " + numTilesAcross + " " + rc/numTilesAcross);
//
// //TODO only draw a selection of images, not the entire map
// g.drawImage(tiles[r][c].getImage(), (int) x + (col * tileSize),
// (int) y + (row * tileSize), null);
// }
// }
} |
71fa30db-0382-4eb1-941b-cb008f3c47f3 | 1 | @Override
public Object promptForAnswer() {
HashMap<Integer, Integer> userAnswer = new HashMap<Integer, Integer>();
for (int i=1; i<=col1Choices.size(); i++){
int choice = InputHandler.getInt("Which item in column 2 matches item "+i+" from column 1?");
userAnswer.put(i, choice);
}
return userAnswer;
} |
5aa94b30-44b0-49d1-bcc3-0294dd3dd2fc | 9 | public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
} |
3735d3c2-4b82-48ed-829b-36697c97528b | 2 | public static SignalAspect fromOrdinal(int ordinal) {
if (ordinal < 0 || ordinal >= VALUES.length)
return SignalAspect.RED;
return VALUES[ordinal];
} |
998382cd-29e5-4801-8b1a-0998d4a4d8f4 | 6 | public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Player player = (Player) table.getValueAt(row, PlayersTable.PLAYER_COLUMN);
NationType nationType = ((Nation) table.getValueAt(row, PlayersTable.NATION_COLUMN)).getType();
JLabel label;
switch(advantages) {
case FIXED:
label = new JLabel(Messages.message(nationType.getNameKey()));
break;
case SELECTABLE:
if (player == null) {
return new JLabel(Messages.message(nationType.getNameKey()));
} else {
return new JLabel(Messages.message(player.getNationType().getNameKey()));
}
case NONE:
default:
label = new JLabel(Messages.message("model.nationType.none.name"));
break;
}
if (player != null && player.isReady()) {
label.setForeground(Color.GRAY);
} else {
label.setForeground(table.getForeground());
}
label.setBackground(table.getBackground());
return label;
} |
0bc75e48-cdb2-4f03-8ca7-54cdfe94437a | 1 | public void add(UnitsValue<?> other) {
mValue += mUnits.convert(other.mUnits, other.mValue);
} |
0fb4adfe-04f7-42eb-9cf4-4f5f463c26be | 7 | */
public boolean processAtSampling(final String line) {
if (line == null) {
return false;
}
final Matcher matcherBegin = this.patternBegin.matcher(line);
final Matcher matcherEnd = this.patternEnd.matcher(line);
final Matcher matcherCritical = this.patternCritical.matcher(line);
final Matcher matcherException = this.patternException.matcher(line);
final Matcher matcherError = this.patternError.matcher(line);
final Matcher matcherNull = this.patternError.matcher(line);
if (matcherBegin.matches()) {
this.termType = TermType.begin;
} else if (matcherEnd.matches()) {
this.termType = TermType.end;
} else if (matcherCritical.matches()) {
this.termType = TermType.criticalerror;
} else if (matcherNull.matches()) {
this.termType = TermType.nullptr;
} else if (matcherException.matches()) {
this.termType = TermType.exception;
} else if (matcherError.matches()) {
this.termType = TermType.error;
} // End of the if - else //
return this.processTime(line);
} |
e5936540-aee9-4948-b94c-77800f95ec53 | 3 | public void randTestQual(int numTests, int lenMask, long seed) {
Random rand = new Random(seed);
for( int t = 0; t < numTests; t++ ) {
String seq = "", qual = "";
int len = (rand.nextInt() & lenMask) + 10; // Randomly select sequence length
seq = randSeq(len, rand); // Create a random sequence
qual = randQual(len, rand); // Create a random quality
String fullSeq = seq + "\t" + qual;
if( verbose ) System.out.println("DnaAndQualitySequence test:" + t + "\tlen:" + len + "\t" + seq);
DnaAndQualitySequence bseq = new DnaAndQualitySequence(seq, qual, FastqVariant.FASTQ_SANGER);
if( !fullSeq.equals(bseq.toString()) ) throw new RuntimeException("Sequences do not match:\n\tOriginal:\t" + fullSeq + "\n\tDnaAndQSeq:\t" + bseq);
}
} |
38b4ca38-32cb-448a-928e-543694337db7 | 5 | @Override
public void setPosition( float x, float y, float z )
{
super.setPosition( x, y, z );
// Make sure OpenAL information has been created
if( sourcePosition == null )
resetALInformation();
else
positionChanged();
// put the new position information into the buffer:
sourcePosition.put( 0, x );
sourcePosition.put( 1, y );
sourcePosition.put( 2, z );
// make sure we are assigned to a channel:
if( channel != null && channel.attachedSource == this &&
channelOpenAL != null && channelOpenAL.ALSource != null )
{
// move the source:
AL10.alSource( channelOpenAL.ALSource.get( 0 ), AL10.AL_POSITION,
sourcePosition );
checkALError();
}
} |
37e22ffa-cb94-4604-afbd-9c29f5206c29 | 4 | public void remove(T data) throws Exception {
Node<T> currNode;
Node<T> prevNode;
if (head == null) {
throw new ListEmptyException();
} else {
// find the node with the data in it
// adjust the links so the Node is removed from the chain of Nodes
currNode = head;
prevNode = head;
while (currNode != null) {
if (currNode.getData().compareTo(data) == 0) {
// found the data we are looking for
if (currNode == head) {
// reset head and you're done!
head = head.getNext();
return;
} else {
prevNode.setNext(currNode.getNext());
return;
}
} else {
// didn't find it yet, continue on to next node
prevNode = currNode;
currNode = currNode.getNext();
}
}
// exhausted list, didn't find a match
throw new NotFoundException();
}
} |
254a9f6c-8bc6-4a5b-9b33-0fda39a819a0 | 0 | public void Init(ContentManager manager) {
initBlocks(manager.getBlockManager());
initPackets(manager.getPacketManager());
} |
bd0263d2-b318-4490-9215-68f32d829df4 | 0 | public void actionPerformed(ActionEvent event) {
frame.close();
} |
f5232ec3-6c7b-490e-8e51-1e6266bdd0ef | 8 | private final void remove(int[] cursorArray) {
if (cursorArray[1] < cursorArray[2]) {
if (this.head > this.tail) {
copy();
}
final int length = length();
System.arraycopy(this.content[this.cIdx], this.head,
this.content[this.cIdxNext], StringBuilder.PATTERN_SIZE,
cursorArray[1]);
System.arraycopy(this.content[this.cIdx], this.head
+ cursorArray[2], this.content[this.cIdxNext],
StringBuilder.PATTERN_SIZE + cursorArray[1], length
- cursorArray[2]);
switchBuffer();
this.head = StringBuilder.PATTERN_SIZE;
this.tail = (StringBuilder.PATTERN_SIZE + length)
- (cursorArray[2] - cursorArray[1]);
cursorArray[0] = cursorArray[2] = cursorArray[1];
return;
}
final int cursor = cursorArray[0];
if ((this.head == this.tail) || (cursor < 0)) {
cursorArray[0] = 0;
return;
}
if (cursor == 0) {
removeFirst();
} else if (cursor == (length() - 1)) {
removeLast();
} else {
final int length = length();
if (this.head > this.tail) {
copy();
}
if (this.content[this.cIdxNext].length < this.content[this.cIdx].length) {
this.content[this.cIdxNext] = new char[this.content[this.cIdx].length];
}
System.arraycopy(this.content[this.cIdx], this.head,
this.content[this.cIdxNext], StringBuilder.PATTERN_SIZE,
cursor);
System.arraycopy(this.content[this.cIdx], this.head + cursor + 1,
this.content[this.cIdxNext], StringBuilder.PATTERN_SIZE
+ cursor, length - cursor - 1);
switchBuffer();
this.tail = (StringBuilder.PATTERN_SIZE + length) - 1;
this.head = StringBuilder.PATTERN_SIZE;
}
} |
354db7d8-4fe7-4239-85a6-6bad7a16d1d2 | 6 | @EventHandler
public void PlayerBlindness(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getPlayerConfig().getDouble("Player.Blindness.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if ( plugin.getPlayerConfig().getBoolean("Player.Blindness.Enabled", true) && damager instanceof Player && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, plugin.getPlayerConfig().getInt("Player.Blindness.Time"), plugin.getPlayerConfig().getInt("Player.Blindness.Power")));
}
} |
99dd6fcb-8c17-4418-ae1c-9fd845d4142f | 4 | public boolean checkRow(int row)
{
int i = 0, j = 0, count = 0;
for(i = 1; i < 10; i++)
{
count = 0;
for(j = 0; j < 9; j++)
{
if(i == Integer.parseInt(entries[row][j].getText()) )
{
count++;
}
if( count >= 2)
{
System.out.println("checkRow() returned false at i: " + row + " j: "+j + " with " + entries[row][j].getText());
return false;
}
}
}
return true;
} |
d5066c3a-ec45-45cd-ae87-9ef69b503cba | 0 | @Override
public String getVersion() {
return("*");
} |
975008ad-b503-49cb-adf5-b8bbad0e2964 | 4 | private synchronized void dequeue(PacketScheduler sched)
{
Packet np = sched.deque();
// process ping() packet
if (np instanceof InfoPacket) {
((InfoPacket) np).addExitTime( GridSim.clock() );
}
if (super.reportWriter_ != null) {
super.write("dequeuing, " + np);
}
// must distinguish between normal and junk packet
int tag = GridSimTags.PKT_FORWARD;
if (np.getTag() == GridSimTags.JUNK_PKT) {
tag = GridSimTags.JUNK_PKT;
}
// sends the packet via the link
String linkName = getLinkName( np.getDestID() );
super.sim_schedule(GridSim.getEntityId(linkName),
GridSimTags.SCHEDULE_NOW, tag, np);
//System.out.println(super.get_name() + ".deque() time now " + GridSim.clock());
// process the next packet in the scheduler
if ( !sched.isEmpty() )
{
double nextTime = (np.getSize() * NetIO.BITS) / sched.getBaudRate();
sendInternalEvent(nextTime, sched);
}
} |
19a4e763-f075-415f-8f18-2282db551d9d | 2 | protected void touchedBy(Entity entity) {
if (entity instanceof Player && pushTime == 0) {
pushDir = ((Player) entity).dir;
pushTime = 10;
}
} |
a3dce455-2d40-4684-ba3e-25d19c3115ba | 5 | public String readPidFromFile(String targetDirectory) throws IOException {
// PID to return
String pid = "";
// Buffered Reader
BufferedReader br = null;
File pidFile = new File(targetDirectory + PID_FILE_NAME);
if (pidFile.exists()) {
try {
// Setup buffered reader
br = new BufferedReader(new FileReader(pidFile));
// Read first line
String firstLine = br.readLine();
if (!StringUtils.isEmpty(firstLine)) {
pid = firstLine.trim();
}
} catch (IOException e) {
this.getLogger().error("error reading pid from file", e);
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
this.getLogger().error("error reading pid from file", ex);
}
}
}
return pid;
} |
b534f934-2d39-4afa-8c3a-7b8cbd097f17 | 7 | private static void Optimize(DiffData data) {
int startPos, endPos;
startPos = 0;
while (startPos < data.Length) {
while ((startPos < data.Length) && (data.modified[startPos] == false))
startPos++;
endPos = startPos;
while ((endPos < data.Length) && (data.modified[endPos] == true))
endPos++;
if ((endPos < data.Length) && (data.data[startPos] == data.data[endPos])) {
data.modified[startPos] = false;
data.modified[endPos] = true;
} else {
startPos = endPos;
} // if
} // while
} // Optimize |
5617dd60-08b5-4a53-9464-9bff3882bc29 | 7 | public void generateUpdatedEntries()
{
_modifiedEntries.clear();
HashSet<String> newEntries = new HashSet<String>();
for (int i = 0; i < 5; i++)
{
OrderEntry orderEntry = null;
int action = _random.nextInt(100);
if (_orderEntries.size() == 0 || action >= _deleteFactor + _updateFactor)
{
// Action Add
if (_orderEntries.size() >= _maxEntries)
{
continue;
}
orderEntry = getNewOrder();
_orderEntries.add(orderEntry);
}
else if (action < _deleteFactor)
{
// Action Delete
int index = _random.nextInt(_orderEntries.size());
orderEntry = (OrderEntry)_orderEntries.get(index);
if (newEntries.contains(orderEntry.makerId))
{
continue;
}
orderEntry.action = OMMMapEntry.Action.DELETE;
_orderEntries.remove(orderEntry);
}
else
{
// Action Update
int index = _random.nextInt(_orderEntries.size());
OrderEntry updateEntry = (OrderEntry)_orderEntries.get(index);
if (newEntries.contains(updateEntry.makerId))
{
continue;
}
updateOrder(updateEntry);
orderEntry = (OrderEntry)updateEntry.clone();
orderEntry.action = OMMMapEntry.Action.UPDATE;
}
newEntries.add(orderEntry.makerId);
_modifiedEntries.add(orderEntry);
}
} |
3316e48a-5846-4b13-b86a-f5bd6bceb56f | 7 | protected void updatePeProvisioning() {
//Log.printLine("dans updatePeProvisioning");
getPeMap().clear();
for (Pe pe : getPeList()) {
pe.getPeProvisioner().deallocateMipsForAllVms();
}
Iterator<Pe> peIterator = getPeList().iterator();
Pe pe = peIterator.next();
PeProvisioner peProvisioner = pe.getPeProvisioner();
double availableMips = peProvisioner.getAvailableMips();
//Log.printLine("availableMips = " + availableMips);
for (Map.Entry<String, List<Double>> entry : getMipsMap().entrySet()) {
String vmUid = entry.getKey();
getPeMap().put(vmUid, new LinkedList<Pe>());
for (double mips : entry.getValue()) {
// Log.printLine("mips : " + mips + " // available mips : " + availableMips);
while (mips >= 0.1) {
if (availableMips >= mips) {
peProvisioner.allocateMipsForVm(vmUid, mips);
getPeMap().get(vmUid).add(pe);
availableMips -= mips;
break;
} else {
peProvisioner.allocateMipsForVm(vmUid, availableMips);
getPeMap().get(vmUid).add(pe);
mips -= availableMips;
if (mips <= 0.1) {
break;
}
if (!peIterator.hasNext()) {
Log.printLine("There is no enough MIPS (" + mips + ") to accommodate VM " + vmUid);
// System.exit(0);
}
pe = peIterator.next();
peProvisioner = pe.getPeProvisioner();
availableMips = peProvisioner.getAvailableMips();
}
}
}
}
} |
b48b8089-e45f-4fd4-af00-90dee33ddc47 | 2 | public static String checkLevels(double level) {
String message = "";
if (level < 0.0) {
message = " below acceptable range.";
}
if (level > 1.0) {
message = " above acceptable range.";
}
return message;
} |
6e328cfc-e92d-4c19-b3db-3faf58950139 | 9 | public static void main(String[] args) {
try {
FitnessCalc1 FitnessFunc;
String testfile = "C:\\Users\\Vincent\\Documents\\GitHub\\Exercises\\testFiles\\A";
/*Initialisation*/
FitnessFunc = new DCS();
Algorithm.setMaximization(true);
Algorithm.setSolution(0);
Individual.setChromSize(26);
int generationCounter = 0;
DateFormat dateFormat = new SimpleDateFormat("_dd_MM_hh_mm");
Date date = new Date();
filename = "DCS_Results"+dateFormat.format(date)+".txt";
filename2 = "resultToPrint"+dateFormat.format(date)+".txt";
PrintWriter writer = new PrintWriter(filename, "UTF-8");
PrintWriter writer2 = new PrintWriter(filename2, "UTF-8");
PrintStream out = new PrintStream(new FileOutputStream(filename));
PrintStream out2 = new PrintStream(new FileOutputStream(filename2));
/*Fetching values into an individual*/
RealLabelledData testingData = RealLabelledDataFactory.dataFromTextFile(testfile, -1, null);
int[] indexes = {4,5};
RealLabelledData testingDataLabels = RealLabelledDataFactory.selectLabels(testingData, indexes);
ObservationReal[] patients = testingDataLabels.getArrayList().toArray(new ObservationReal[0]);
/*Putting my patient values into my original model ones*/
Population myPop = new Population(patients.length);
for(int j=0; j<patients.length; j++) {
for (int i = 0; i < patients[j].getAttributeSize(); i++) {
myPop.getIndividual(j).setValues(patients[j].getAttribute(i), i);
}
}
/*Beginning the Genetic Algorithm*/
System.out.println("Generation Number, Best Fitness, Average Fitness, Deviance");
out.println("#DCS calculation");
out.println("#Chromosome size : " + myPop.getIndividual(0).getChromSize());
out.println("#Population size : " + patients.length);
out.println("#Crossover rate : " + Algorithm.getUniformRate() + " , Mutation rate : " + Algorithm.getMutationRate() + " , Tournament size : " + Algorithm.getTournamentSize());
out.println("Generation.Number, Best.Fitness, Average.Fitness, Fitness.Deviance");
out2.println("Projection, Label");
while (generationCounter != 100) {
/*Projecting*/
LinProj P1 = new LinProj(26);
for (int i = 0; i < myPop.getIndividual(1).getChromSize(); i++) {
P1.w[i] = myPop.getIndividual(1).getValues(i);
}
int[] labeldata = new int[patients.length];
double[] projdata = new double[patients.length];
for(int i = 0; i<patients.length; i++){
projdata[i] = P1.project(patients[i].getAttributeValues());
labeldata[i] = patients[i].getLabel();
out2.println(projdata[i] +" "+ labeldata[i]);
}
/*Evaluating and Evolving*/
generationCounter++;
System.out.println(generationCounter + " , " + myPop.getFittest(FitnessFunc, projdata, labeldata).getFitness(FitnessFunc, projdata, labeldata) + " , " + myPop.getAvgFitness(FitnessFunc, projdata, labeldata) + " , " + myPop.getDeviance(FitnessFunc, projdata, labeldata));
myPop = Algorithm.evolvePopulation(myPop, FitnessFunc, projdata, labeldata);
out.println(generationCounter + " " + myPop.getFittest(FitnessFunc, projdata, labeldata).getFitness(FitnessFunc, projdata, labeldata) + " " + myPop.getAvgFitness(FitnessFunc, projdata, labeldata) + " " + myPop.getDeviance(FitnessFunc, projdata, labeldata));
}
System.out.println("Finished in " + generationCounter + " generations !");
out.close();
out2.close();
writer.close();
writer2.close();
/*CSV Generation into a file*/
CSVGen.CSVGenerator.main(null);
File file = new File(filename);
/*Simple text file deletion*/
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
} |
aa22b4f3-1f19-4849-914d-508a4fa2438e | 2 | public OrgaEinheit getOrgaEinheitvonBezeichnung(String bezeichnung){
OrgaEinheit rueckgabe = null;
try {
ResultSet resultSet = db.executeQueryStatement("SELECT * FROM OrgaEinheiten WHERE OrgaEinheitBez = '" + bezeichnung + "'");
if(resultSet.next())
rueckgabe = new OrgaEinheit(resultSet, db, this);
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rueckgabe;
} |
6f7e61ec-30a7-4a97-a77f-53952574d7cf | 8 | void fill( Point a, Point b, Point c, Point a0, Point b0, Point c0 ) {
int x0 = (int)Math.floor( Util.minX(a, b, c) ), x1 = (int)Math.ceil( Util.maxX(a, b, c) );
int y0 = (int)Math.floor( Util.minY(a, b, c) ), y1 = (int)Math.ceil( Util.maxY(a, b, c) );
x0 = Math.max(x0, 0); x1 = Math.min(x1, width - 1 );
y0 = Math.max(y0, 0); y1 = Math.min(y1, height - 1 );
for ( int i = x0; i <= x1; ++i ) {
for ( int j = y0; j <= y1; ++j ) {
double []t = Point.TriangleContainsPoint(a, b, c, new Point(i, j) );
if ( t[1] >= 0 && t[2] >= 0 ) {
double srcX = (a0.x * t[0] + b0.x * t[1] + c0.x * t[2]) / (t[0] + t[1] + t[2]);
double srcY = (a0.y * t[0] + b0.y * t[1] + c0.y * t[2]) / (t[0] + t[1] + t[2]);
if ( 0 <= srcX && srcX <= width - 1) {
if ( 0 <= srcY && srcY <= height - 1 ) {
int rgb = query(srcX, srcY);
this.target.setRGB(i, j, rgb);
}
}
}
}
}
} |
02e1fb7f-5a5b-43a4-97f8-66c54f4ca7d4 | 8 | protected OgexTrack toTrack( DataStructure ds, Map<BaseStructure, Object> index ) {
OgexTrack result = new OgexTrack();
BaseStructure target = ds.getProperty("target");
Object resolved = index.get(target);
if( resolved == null ) {
// Need to figure out what it is and create it...
// but not right now FIXME
throw new UnsupportedOperationException("Forward track targets not yet supported.");
}
result.setTarget(resolved);
OgexTime time = null;
OgexValue value = null;
for( BaseStructure child : ds ) {
if( StructTypes.TIME.equals(child.getType()) ) {
if( time != null ) {
throw new RuntimeException("Only one Time structure is allowed in Track, from:" + ds.location());
}
time = toTime((DataStructure)child);
} else if( StructTypes.VALUE.equals(child.getType()) ) {
if( value != null ) {
throw new RuntimeException("Only one Value structure is allowed in Track, from:" + ds.location());
}
value = toValue((DataStructure)child);
} else {
log.warn("Unhandled structure type:" + child.getType() + ", from:" + child.location());
}
}
if( time == null ) {
throw new RuntimeException("No Time structure found in Track, from:" + ds.location());
}
if( value == null ) {
throw new RuntimeException("No Value structure found in Track, from:" + ds.location());
}
result.setTime(time);
result.setValue(value);
return result;
} |
eff8b1cd-dcdd-47c4-b65e-91e3ce6c6954 | 5 | private static String xmlTrim(String text)
{
int start = -1, end = text.length();
while (start < text.length() && isWhitespace(text.charAt(++start)));
while (end > -1 && isWhitespace(text.charAt(--end)));
if (end != -1)
{
return text.substring(start, end + 1);
}
else
{
return "";
}
} |
74d18914-d2dc-40bd-98d0-75bb4aa9709f | 6 | public void handleInput() {
if (Keys.isPressed(Keys.ESCAPE))
gsm.setPaused(true);
if (player.getHealth() == 0)
return;
player.setUp(Keys.keyState[Keys.UP]);
player.setDown(Keys.keyState[Keys.DOWN]);
player.setLeft(Keys.keyState[Keys.LEFT] || Keys.keyState[Keys.A]);
player.setRight(Keys.keyState[Keys.RIGHT] || Keys.keyState[Keys.D]);
player.setJumping(Keys.keyState[Keys.BUTTON1]);
player.setGliding(Keys.keyState[Keys.BUTTON2]);
if (Keys.isPressed(Keys.BUTTON4))
player.setFiring();
if (Keys.isPressed(Keys.BUTTON3))
player.setScratching();
} |
d8401e37-5d71-4687-8f2a-11da13184dca | 6 | public ArrayList<Integer> readGold(ID tid) {
ArrayList<Integer> gtags = null;
BufferedReader br = null;
String line;
try {
gtags = new ArrayList<Integer>();
br = new BufferedReader(new FileReader(gold));
while ((line = br.readLine()) != null) {
gtags.add(0);
for (String s : line.split(" ")) {
Pattern p = Pattern.compile("(.*/)?(.*)");
Matcher m = p.matcher(s);
if (m.matches()) {
gtags.add(tid.getID(m.group(2)));
}
}
}
gtags.add(0);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return gtags;
} |
a4d30ce7-79bf-4e0b-9460-d67ebff6ce65 | 7 | public boolean nodesWithSum(int sum, treeNode root) {
int[] newArray = new int[this.nodeCount];
addToArray(this.root, newArray, 0);
int indexClosetLarger = newArray.length;
int lowIndex = 0;
int matchIndex = -1;
int matchCount = 0;
// find the closet number larger than sum
for (int i = 0; i < newArray.length; i++) {
if (newArray[i] > sum) {
indexClosetLarger = i;
break;
}
}
// the smallest node i==0 or the 2nd smallest node i==1 is already
// bigger than sum
if (indexClosetLarger <= 1)
return false;
// start from biggest which is still smaller than sum, find from 0 for
// the match
for (int j = indexClosetLarger - 1; j > 0 && lowIndex < j; j--) {
matchIndex = this.binarySearch(sum - newArray[j], newArray,
lowIndex, j - 1);
if (matchIndex >= 0) {// find match
System.out.println("One pair: (" + newArray[matchIndex] + ","
+ newArray[j] + ")");
matchCount++;
lowIndex = matchIndex + 1;
}
}
if (matchCount > 0)
return true;
return false;
} |
4d1dc311-85f2-44b8-92ff-4d2f72543ba9 | 6 | @Override
public T build(Map<Class<?>, ClassBuilder<?>> how) {
Constructor<?>[] constructors = underConstruction.getConstructors();
Constructor<?> constructorElegido = this.elegirConstructor(constructors);
if(constructorElegido != null){
try {
return (T)constructorElegido.newInstance(this.getObjects(params));
} catch (Exception e) {
e.printStackTrace();
throw new NoPudimosCrearLaInstanciaException(e);
}
}
return null;
} |
f2d2005a-b44d-48f6-bcf0-09dde7f4ec9b | 4 | public void Draw(Graphics2D g2d, Point mousePosition) {
//draws according to Framework canvas size
//g2d.drawImage(backgroundImg, 0, 0, Framework.frameWidth, Framework.frameHeight, null);
//draw moving bg???????
movingBg.Draw(g2d);
// Draws the course objects
for (int i = 0; i < courseList.size(); i++) {
courseList.get(i).Draw(g2d);
}
if(playerCar.getY() < courseList.get(passedPointLoc[0]).getY()){
//drawpoint passed
g2d.setColor(Color.white);
g2d.drawString("Passed Point A!!!", 5, 175);
passedPoint[0] = true;
}
if(playerCar.getY() < courseList.get(passedPointLoc[1]).getY()){
//drawpoint passed
g2d.setColor(Color.white);
g2d.drawString("Passed Point B!!!", 5, 200);
passedPoint[1] = true;
}
if(playerCar.getY() < courseList.get(passedPointLoc[2]).getY()){
//drawpoint passed
g2d.setColor(Color.white);
g2d.drawString("Passed Point C!!!", 5, 225);
passedPoint[2] = true;
}
//draw the cars
playerCar.Draw(g2d);
enemyCar.Draw(g2d);
} |
5d95798d-71b7-473c-a46c-2e541d683da9 | 6 | public static Cons translateLoomPartitions(Stella_Object partitions, boolean exhaustiveP, Symbol parentconcept) {
{ Cons axioms = Stella.NIL;
Cons partitionList = Stella.NIL;
if (!Stella_Object.consP(partitions)) {
partitions = Cons.consList(Cons.cons(partitions, Stella.NIL));
}
if (Stella_Object.consP(((Cons)(partitions)).value)) {
partitionList = ((Cons)(partitions));
}
else {
{ Stella_Object clause = null;
Cons iter000 = ((Cons)(partitions));
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
clause = iter000.value;
partitionList = Cons.cons(Cons.consList(Cons.cons(clause, Stella.NIL)), partitionList);
}
}
}
{ Cons clause = null;
Cons iter001 = partitionList;
for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) {
clause = ((Cons)(iter001.value));
{ Stella_Object name = clause.value;
Cons concepts = ((Cons)(clause.rest.value));
Cons localaxioms = Stella.NIL;
localaxioms = Cons.cons(Cons.list$(Cons.cons(edu.isi.powerloom.pl_kernel_kb.loom_api.LoomApi.SYM_PL_KERNEL_KB_MUTUALLY_DISJOINT_COLLECTION, Cons.cons(name, Cons.cons(Stella.NIL, Stella.NIL)))), localaxioms);
if (concepts != null) {
localaxioms = Cons.cons(Cons.list$(Cons.cons(Logic.SYM_STELLA_e, Cons.cons(name, Cons.cons(Cons.cons(Cons.cons(Logic.SYM_PL_KERNEL_KB_SETOF, concepts.concatenate(Stella.NIL, Stella.NIL)), Stella.NIL), Stella.NIL)))), localaxioms);
}
if (exhaustiveP) {
localaxioms = Cons.cons(Cons.list$(Cons.cons(edu.isi.powerloom.pl_kernel_kb.loom_api.LoomApi.SYM_PL_KERNEL_KB_COVERING, Cons.cons(name, Cons.cons(Cons.cons(parentconcept, Stella.NIL), Stella.NIL)))), localaxioms);
}
axioms = Cons.cons(Logic.conjoinSentences(localaxioms.reverse()), axioms);
}
}
}
return (axioms);
}
} |
0dd5ec93-82a1-47a1-bd01-3bb46be63b31 | 7 | @EventHandler
public void WitherInvisibility(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Wither.Invisibility.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof WitherSkull) {
WitherSkull a = (WitherSkull) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getWitherConfig().getBoolean("Wither.Invisibility.Enabled", true) && shooter instanceof Wither && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, plugin.getWitherConfig().getInt("Wither.Invisibility.Time"), plugin.getWitherConfig().getInt("Wither.Invisibility.Power")));
}
}
} |
7e34fa8e-44b7-470d-b834-b2db1661c970 | 3 | private void makeRGBTexture(GL2 gl, BufferedImage img, int target) {
/* Setup a BufferedImage suitable for OpenGL */
WritableRaster raster = Raster.createInterleavedRaster (DataBuffer.TYPE_BYTE,
img.getWidth(),
img.getHeight(),
4,
null);
ComponentColorModel colorModel = new ComponentColorModel (ColorSpace.getInstance(ColorSpace.CS_sRGB),
new int[] {8,8,8,8},
true,
false,
ComponentColorModel.TRANSLUCENT,
DataBuffer.TYPE_BYTE);
BufferedImage bufImg = new BufferedImage (colorModel,
raster,
false,
null);
/* Setup a Graphic2D context that will flip the image vertically along the way */
Graphics2D g = bufImg.createGraphics();
AffineTransform gt = new AffineTransform();
gt.translate (0, img.getHeight());
gt.scale (1, -1d);
g.transform (gt);
g.drawImage (img, null, null );
/* Fetch the raw data out of the image and destroy the graphics context */
byte[] imgRGBA = ((DataBufferByte)raster.getDataBuffer()).getData();
g.dispose();
/* Convert the raw data to a buffer for glTexImage2D */
ByteBuffer dest = ByteBuffer.allocateDirect(imgRGBA.length);
dest.order(ByteOrder.nativeOrder());
dest.put(imgRGBA, 0, imgRGBA.length);
// Rewind the buffer so we can read it starting and beginning
dest.rewind();
gl.glTexImage2D(target, 0, GL2.GL_RGBA, img.getWidth(), img.getHeight(), 0, GL2.GL_RGBA, GL2.GL_UNSIGNED_BYTE, dest);
if(gl.glIsTexture(glTexture) == false){
System.err.println("FAILED TO GENERATE TEXTURE");
if(isPowerOfTwo(img.getWidth()) == false || isPowerOfTwo(img.getHeight()) == false){
System.err.println("Texture width or height is not power of two");
System.err.println("Texture width: " + img.getWidth());
System.err.println("Texture height: " + img.getHeight());
return;
}
System.err.println("Unknown reason texture did not generate");
}
} |
ff975395-acfb-4b34-a1ad-9cc05d03e726 | 3 | private synchronized void processInputs() {
int code;
try
{
// Careful: the read*() methods are blocking!
code = hmi.dataIn.readInt();
Command command = Command.values()[code];
if (command == Command.IN_SET_MODE) {
int imode = hmi.dataIn.readInt();
hmi.mode = Mode.values()[imode];
} else if (command == Command.IN_SELECTED_PARKING_SLOT) {
hmi.selectedParkingSlot = hmi.dataIn.readInt();
}
} catch (IOException e)
{
System.out.println("Read exception "+e);
}
} |
d6a39e03-788b-4e03-9ce9-8affb140abd7 | 8 | @Override
public void storeComment(Comment comment) {
ResultSet rs = null;
int ID = comment.getID();
if (ID > 0) { // update
editComment(comment);
} else { // insert
try {
// this.iComment = connection.prepareStatement("INSERT INTO comment (author, text, date, adminID, postID), VALUES (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
// assumiamo che se un commento è postato da un Admin, Comment.author corrisponderà a Admin.Username
this.iComment.setString(1, comment.getAuthor());
this.iComment.setString(2, comment.getText());
this.iComment.setDate(3, new java.sql.Date(System.currentTimeMillis() / 1000L));
this.iComment.setInt(5, comment.getPost().getID());
if (comment.isPostedByAdmin()) {
this.iComment.setInt(4, comment.getAdmin().getID());
} else {
this.iComment.setNull(4, java.sql.Types.INTEGER);
}
// abbiamo finito di compilare la query
if (this.iComment.executeUpdate() == 1) {
rs = this.iComment.getGeneratedKeys();
if (rs.next()) {
ID = rs.getInt(1);
}
}
if (ID > 0) {
comment.copyFrom(getComment(ID)); // aggiorno il post
}
comment.setDirty(false); // dico che è pulito
} catch (SQLException ex) {
Logger.getLogger(SitoDataLayerMysqlImpl.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(SitoDataLayerMysqlImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
} |
3234b061-1700-468f-8413-d5ad030018e5 | 4 | private Comparator<? super TSource> createComparatorChain() {
final List<Comparator<TSource>> comparators = new LinkedList<Comparator<TSource>>();
SortableList<TSource> s = this;
do {
comparators.add(0, s.comparator);
} while ((s = s.parent) != null);
return new Comparator<TSource>() {
@Override
public int compare(TSource t1, TSource t2) {
int compareResult = 0, i = 0;
Comparator<TSource> comparator = null;
do {
comparator = comparators.get(i++);
compareResult = comparator.compare(t1, t2);
} while (compareResult == 0 && CommonUtils.isLegalIndex(comparators, i));
return compareResult;
}
};
} |
dbf1be33-9221-4872-a90a-dcbf7be00921 | 4 | private MouseMotionListener mouseMotionListener(){
return new MouseMotionAdapter() {
@Override
public void mouseDragged( MouseEvent e ) {
if( !moving ){
if( mousePressedPoint != null ){
initMove( mousePressedPoint.x, mousePressedPoint.y );
}
}
if( moving ){
for( MoveableCapability item : items ){
item.moveTo( e.getX(), e.getY() );
}
}
}
};
} |
c3ae0563-a6bd-4698-bea2-08a76dee86bf | 0 | @Override
public void restoreCurrentToDefault() {
copyHashMap(def,cur);
} |
91950226-22ac-4ef5-8461-6375899af548 | 0 | public String expression(String expression){
this.expression = expression;
return this.expression;
} |
d2f3f12a-2a40-43a5-8457-1760fcbe1132 | 7 | @Override
protected void setup(Context context) {
this.conf = context.getConfiguration();
// get cube identifier from hadoop conf
try {
initCubeIdentifierFromHadoopConf();
} catch (CubeIdentifierNotSetException e) {
e.printStackTrace();
// TODO exit is not a good way
System.exit(-1);
}
// get dimensionLengths from hadoop conf
try {
initDimensionLengthsFromHadoopConf();
} catch (DimensionLengthsNotSetException e) {
e.printStackTrace();
// TODO exit is not a good way
System.exit(-1);
}
// get newDimensionLengths from hadoop conf
try {
initNewDimensionLengthsFromHadoopConf();
} catch (DimensionLengthsNotSetException e) {
e.printStackTrace();
// TODO exit is not a good way
System.exit(-1);
}
// get schema from hadoop conf
try {
initSchemaFromConf();
} catch (InvalidObjectStringException e) {
e.printStackTrace();
// TODO exit is not a good way
System.exit(-1);
} catch (SchemaNotSetException e) {
e.printStackTrace();
// TODO exit is not a good way
System.exit(-1);
}
// get newSchema from hadoop conf
try {
initNewSchemaFromConf();
} catch (InvalidObjectStringException e) {
e.printStackTrace();
// TODO exit is not a good way
System.exit(-1);
} catch (NewSchemaNotSetException e) {
e.printStackTrace();
// TODO exit is not a good way
System.exit(-1);
}
} |
01f89635-aa60-4a5b-9186-5a0ce4d3e1d0 | 6 | public boolean isVertexInArea(Point p1, Point p2) {
double[] posX = { p1.getX(), p2.getX() };
double[] posY = { p1.getY(), p2.getY() };
if (posX[0] > posX[1]) {
swapCoords(posX);
}
if (posY[0] > posY[1]) {
swapCoords(posY);
}
if (getCenterX() >= posX[0] && getCenterX() <= posX[1]
&& getCenterY() >= posY[0] && getCenterY() <= posY[1]) {
return true;
}
return false;
} |
ac2aca0b-6cc2-4e91-97d5-4fc9541c8ad5 | 0 | @Override
public void finishOutline () {} |
1d21e649-f208-4ec5-ba12-bf48b46e373c | 3 | public PlantManager(World world, Object3D ground, float range) {
plants=new Plant[MAX_PLANTS];
positions=new SimpleVector[MAX_PLANTS];
for (int i=0; i<MAX_PLANTS; i++) {
Plant plant=new Plant();
plants[i]=plant;
boolean ok=false;
do {
float xpos=(float)(Math.random()-0.5d)*range*2f;
float zpos=(float)(Math.random()-0.5d)*range*2f;
plant.setTranslationMatrix(new Matrix());
plant.translate(xpos, 0, zpos);
ok=plant.place(ground);
} while (!ok);
plant.addToWorld(world);
plant.addCollisionListener(LISTENER);
}
for (int i=0; i<MAX_PLANTS; i++) {
positions[i]=plants[i].getTransformedCenter();
/**
* The positions won't change anymore, so we can do this:
*/
plants[i].enableLazyTransformations();
}
} |
c265e403-c7a8-4dae-9701-860a022770a3 | 4 | public void kick(String message, Object... args) {
if (left)
return;
PacketKick kick = new PacketKick(this);
kick.message = message;
kick.args = args;
if(properties.containsKey("translation")) {
Translation t = (Translation)properties.get("translation");
System.out.println(t.translate("client.kicked", socket.getInetAddress().getCanonicalHostName(), t.translate(message, args)));
}
try {
kick.send();
} catch (IOException e) {
}
try {
socket.close();
} catch (IOException e) {
}
left = true;
} |
8cd0db0f-4d9f-44df-83f2-38444acc4c2c | 4 | @Override
public void parse(CommandInvocation invocation, List<ParsedParameter> params, List<Parameter> suggestions)
{
String token = invocation.currentToken();
for (String name : getNames())
{
if (name.equalsIgnoreCase(token))
{
invocation.consume(1); // TODO perhaps remember parsed name
break;
}
}
if (invocation.isConsumed() && suggestions != null)
{
return;
}
super.parse(invocation, params, suggestions);
} |
298d39a9-48d3-4429-b461-bec507f2c62f | 3 | @Override
protected String makeString(String t, boolean structured) {
String n = ""; //new line
String tt = ""; //tabulators
//create new stuff, if structured
if(structured){
n = "\n";
tt = t+"\t";
}
//temp storage
StringBuilder arrsb = new StringBuilder();
//trick to have commas just where they're needed
char c = '[';
for(JsonElement element : value){
arrsb.append(c+n+tt);
arrsb.append( (element==null) ? ("null") : (element.makeString(tt, structured)) );
c = ',';
}
return arrsb.append(n+t+"]").toString();
} |
7c30d005-5de1-4bb0-aa8c-07a47b334adc | 4 | @Override
public void run() {
while (true)
{
Point p;
try {
p = toLoad.take();
}catch (InterruptedException e) {
e.printStackTrace();
continue;
}
try {
Main.getLoadedWorld().addChunk(load(p));
}catch (NullPointerException e) {
try {
Thread.sleep(10);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Main.getLoadedWorld().addChunk(load(p));
}
}
} |
9687a6ac-879f-459d-a115-c3e98841450c | 0 | public static void print(Object s) {
System.out.print(s);
} |
58643004-663c-4583-8993-90c6db4b0b9a | 3 | @Override
public String process(String content) throws ProcessorException {
// TODO Auto-generated method stub
pipeline = new SimpleAuthenticationPipeline();
context = new AuthenticateContext();
pipeline.setBasic(new LoginEntryValve());
pipeline.addValve(new FlushValve());
pipeline.addValve(new EncodeValve());
pipeline.addValve(new GetTokenValve());
pipeline.addValve(new AuthenticateValve());
pipeline.addValve(new ValidationValve());
pipeline.addValve(new DecoderValve());
// pipeline.addValve(new EncodeValve());
pipeline.setContext(context);
try {
pipeline.invoke(context.getRequest(), context.getResponse(), null);
} catch (ValveException e) {
e.printStackTrace();
User user = context.getRequest().getCurrentUser();
String response = "";
if (user == null || user.getUserName() == null) {
response = ExceptionWrapper.toJSON(503, "Internal Error");
} else {
response = ExceptionWrapper.toJSON(user, e.getCode(),
e.getMessage());
}
return response;
}
return context.getResponse().getResponse();
} |
e09f4a3f-a7ca-4c34-ba5f-a52401704d34 | 2 | public void bind() {
SocketAddress address;
if (ip.isEmpty()) {
address = new InetSocketAddress(this.port);
} else {
address = new InetSocketAddress(this.ip, this.port);
}
ChannelFuture future = this.bootstrap.bind(address);
Channel channel = future.awaitUninterruptibly().channel();
if (!channel.isActive()) {
throw new RuntimeException("**** FAILED TO BIND TO PORT! Perhaps a server is already running on that port?");
}
LOGGER.info("Ready to accept connections on " + address);
} |
60cbf132-6aed-4f6c-9067-9ed0626f4cf4 | 0 | @SuppressWarnings("deprecation")
public void stop(){
downloadThread.stop();
} |
3adf4a0a-3d45-45fa-a9b6-33fa00b5081d | 1 | public void addVertex(UndirectedNode vertex) {
if (!this.vertices.contains(vertex)) {
this.vertices.add(vertex);
}
} |
67e48e11-0598-4147-9039-e10251bc39e9 | 3 | public void writeWsFrameLength(byte type, int length) throws IOException {
writeRawByte(type);
// Encode length.
int b1 = length >>> 28 & 0x7F;
int b2 = length >>> 14 & 0x7F;
int b3 = length >>> 7 & 0x7F;
int b4 = length & 0x7F;
if (b1 == 0) {
if (b2 == 0) {
if (b3 == 0) {
writeRawByte(b4);
} else {
writeRawByte(b3 | 0x80);
writeRawByte(b4);
}
} else {
writeRawByte(b2 | 0x80);
writeRawByte(b3 | 0x80);
writeRawByte(b4);
}
} else {
writeRawByte(b1 | 0x80);
writeRawByte(b2 | 0x80);
writeRawByte(b3 | 0x80);
writeRawByte(b4);
}
} |
9749724d-1c6d-4f9d-8c70-8ae2bba4af3f | 2 | @Override
public String execute(SessionRequestContent request) throws ServletLogicException {
String page = ConfigurationManager.getProperty("path.page.countries");
String prevPage = (String) request.getSessionAttribute(JSP_PAGE);
resaveParamsShowCountry(request);
formCountryList(request);
showSelectedCountry(request);
if (page == null ? prevPage != null : !page.equals(prevPage)) {
request.setSessionAttribute(JSP_PAGE, page);
cleanSessionShowCountry(request);
}
return page;
} |
20d42295-a95a-4410-8b64-63fcbe5378c7 | 5 | @Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Stop JUMP");
break;
case KeyEvent.VK_DOWN:
currentSprite = anim.getImage();
robot.setDucking(false);
break;
case KeyEvent.VK_LEFT:
robot.setMovingLeft(false);
robot.stop();
break;
case KeyEvent.VK_RIGHT:
robot.setMovingRight(false);
robot.stop();
break;
case KeyEvent.VK_CONTROL:
robot.setReadyToFire(true);
break;
}
} |
81828e19-24eb-4730-901e-ad2558b93fb7 | 2 | public int getSize() {
return type == Type.LONG_TYPE || type == Type.DOUBLE_TYPE ? 2 : 1;
} |
a4849cae-f97c-499e-9683-c36d6b4c4cd2 | 4 | public WorldInfo loadWorldInfo() {
File var1 = new File(this.saveDirectory, "level.dat");
NBTTagCompound var2;
NBTTagCompound var3;
if(var1.exists()) {
try {
var2 = CompressedStreamTools.loadGzippedCompoundFromOutputStream(new FileInputStream(var1));
var3 = var2.getCompoundTag("Data");
return new WorldInfo(var3);
} catch (Exception var5) {
var5.printStackTrace();
}
}
var1 = new File(this.saveDirectory, "level.dat_old");
if(var1.exists()) {
try {
var2 = CompressedStreamTools.loadGzippedCompoundFromOutputStream(new FileInputStream(var1));
var3 = var2.getCompoundTag("Data");
return new WorldInfo(var3);
} catch (Exception var4) {
var4.printStackTrace();
}
}
return null;
} |
3fcdfe88-2c54-4ae0-8774-5ed9ba533033 | 8 | public Player play() throws GameEndedUnexpectedlyException {
Player turn = null;
WinResult gameState = WinResult.None;
//The game loop. Halts when the game has ended
while(gameState == WinResult.None)
{
//Determine whose turn it is
if (turn == player1)
{
turn = player2;
}
else
{
turn = player1;
}
//Ask player for the next move, and update the board
//If an invalid move is sent, ask for another move from the player.
int moveTries = 0;
Piece newestPiece = null;
while(moveTries<10 && newestPiece == null) {
Move nextMove = turn.getMove(this.board);
newestPiece = rules.parseMove(nextMove, board);
if (newestPiece == null)
{
moveTries++;
}
setChanged();
notifyObservers(newestPiece);
}
//If after 10 tries, the player has not provided a legal move, stop the game.
//This will make the game throw a gameEndedUnexpectedlyException.
if (moveTries >= 10)
{
break;
}
//Check whether the game has ended
gameState = rules.checkWin(board);
}
switch (gameState)
{
case Won:
return turn;
case Tie:
return null;
default:
//Exited the game loop, but no one has won and there is no tie.
throw new GameEndedUnexpectedlyException();
}
} |
7f83ecf1-7bb0-4bcf-8e10-24f1a4d0f365 | 8 | public static void main(String[] args) throws IOException {
for (int i = 2; i < 1000000; i++)
if (!primos[i])
for (int j = i + i; j < 1000000; j += i)
primos[j] = true;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(true){
int n = Integer.parseInt(in.readLine().trim());
if(n==0)break;
for(int i = 2; i < n; i++)
if(!primos[i]&&!primos[n-i]){
System.out.println(n + " = " + i + " + " + (n-i));
break;
}
}
} |
6cba5efd-b2e0-40e7-99d6-534cebe50869 | 4 | @Override
public boolean grown() {
final FarmingDefinition definition = definition();
if (definition.containsAction("Empty") || definition.containsAction("Take-tomato")) {
return true;
}
final int bits = bits();
return bits == NORMAL_STAGE[2] || bits == SUPER_STAGE[2] || bits == TOMATO_STAGE[2];
} |
1f60bf86-cf83-46bf-a5bf-fbb8061b1a58 | 3 | public cancelService(int route)
{
database.openBusDatabase();
Calendar cal = Calendar.getInstance();
route_id = route;
timing_point += cal.get(Calendar.HOUR_OF_DAY) * 60;
timing_point += cal.get(Calendar.MINUTE);
startDate = (Calendar)cal.clone();
if(startDate.get(Calendar.DAY_OF_WEEK) > 1 && startDate.get(Calendar.DAY_OF_WEEK) < 7)
day_of_week = 0;
else if(startDate.get(Calendar.DAY_OF_WEEK) == 7)
day_of_week = 1;
else
day_of_week = 2;
} |
749e93ae-cbfe-474a-9ff7-cb092a39c998 | 7 | public void mouseWheelMoved(MouseWheelEvent e) {
MapView mapView = (MapView) e.getSource();
ControllerAdapter mController = (ControllerAdapter) mapView.getModel()
.getModeController();
if (mController.isBlocked()) {
return; // block the scroll during edit (PN)
}
Set registeredMouseWheelEventHandler = mController
.getRegisteredMouseWheelEventHandler();
for (Iterator i = registeredMouseWheelEventHandler.iterator(); i
.hasNext(); ) {
MouseWheelEventHandler handler = (MouseWheelEventHandler) i.next();
boolean result = handler.handleMouseWheelEvent(e);
if (result) {
// event was consumed:
return;
}
}
if ((e.getModifiers() & ZOOM_MASK) != 0) {
// fc, 18.11.2003: when control pressed, then the zoom is changed.
float newZoomFactor = 1f + Math.abs((float) e.getWheelRotation()) / 10f;
if (e.getWheelRotation() < 0)
newZoomFactor = 1 / newZoomFactor;
final float oldZoom = ((MapView) e.getComponent()).getZoom();
float newZoom = oldZoom / newZoomFactor;
// round the value due to possible rounding problems.
newZoom = (float) Math.rint(newZoom * 1000f) / 1000f;
newZoom = Math.max(1f / 32f, newZoom);
newZoom = Math.min(32f, newZoom);
if (newZoom != oldZoom) {
mController.getController().setZoom(newZoom);
}
// end zoomchange
} else if ((e.getModifiers() & HORIZONTAL_SCROLL_MASK) != 0) {
((MapView) e.getComponent()).scrollBy(
SCROLL_SKIPS * e.getWheelRotation(), 0);
} else {
((MapView) e.getComponent()).scrollBy(0,
SCROLL_SKIPS * e.getWheelRotation());
}
} |
a35aecf9-f258-4348-ac03-f7c12a21ec68 | 2 | private static boolean checkElementDiscovered(String element) {
for (int x = 0; x <= elementsDiscovered.length -1; x++) { //goes through the elementsDiscovered
int elementInt = elementNumber(element); //and checks if the int of the element passed
if (elementInt == elementsDiscovered[x]){ //through matches any int in the elementsDiscovered
return true;
}
}
return false;
} |
cd3e5df3-1c96-4864-a8ce-df7a2a776508 | 3 | @Test
public void test_solvable_matrix_size_3_solve() throws
ImpossibleSolutionException,UnsquaredMatrixException,
ElementOutOfRangeException{
int height=3;
int width=3;
float[][] matrix;
float[] resultVector;
float[][] knownMatrix = new float[height][width];
float[] knownResults = new float[height];
knownMatrix[0][0] = -.2f;
knownMatrix[0][1] = .6f;
knownMatrix[0][2] = -.2f;
knownMatrix[1][0] = .6f;
knownMatrix[1][1] = .2f;
knownMatrix[1][2] = -.4f;
knownMatrix[2][0] = 0f;
knownMatrix[2][1] = -1f;
knownMatrix[2][2] = 1f;
knownResults[0] = .6f;
knownResults[1] = 1.2f;
knownResults[2] = -2.0f;
try{
test_matrix = new LinearEquationSystem(height,width);
}catch(UnsquaredMatrixException e){
throw e;
}
try{
test_matrix.setValueAt(0,0, 1.0f);
test_matrix.setValueAt(0,1, 2.0f);
test_matrix.setValueAt(0,2, 1.0f);
test_matrix.setValueAt(0,3, 1.0f);
test_matrix.setValueAt(1,0, 3.0f);
test_matrix.setValueAt(1,1, 1.0f);
test_matrix.setValueAt(1,2, 1.0f);
test_matrix.setValueAt(1,3, 1.0f);
test_matrix.setValueAt(2,0, 3.0f);
test_matrix.setValueAt(2,1, 1.0f);
test_matrix.setValueAt(2,2, 2.0f);
test_matrix.setValueAt(2,3, -1.0f);
}catch(ElementOutOfRangeException e){
throw e;
}
try{
resultVector = test_matrix.solve();
}catch(ImpossibleSolutionException e){
throw e;
}
matrix = test_matrix.returnMatrix();
Assert.assertArrayEquals(knownResults,resultVector,.001f);
Assert.assertArrayEquals(knownMatrix[0],matrix[0],.001f);
Assert.assertArrayEquals(knownMatrix[1],matrix[1],.001f);
Assert.assertArrayEquals(knownMatrix[2],matrix[2],.001f);
} |
e23109ed-f45b-461b-832e-83da4ec83e42 | 6 | public String getLyricsSnippet(String artistName,String songName){
if (artistName.equals(null) || artistName.equals("") || songName.equals(null) || songName.equals(""))
return null;
String url = buildUrl(artistName,songName);
try {
Document document = reader.read(url);
// XMLUtil.writeToFile(document, artistName + " - " + songName + ".xml");
Element root = document.getRootElement(); //LyricsResult element
String pageId = root.element("page_id").getText();
if(pageId.equals("")){ //there is NOT lyrics page
System.out.println("No lyrics page.");
return null;
}
else
return root.element("lyrics").getText();
} catch (Exception e) {
return null;
//e.printStackTrace();
}
} |
82699e84-bff1-4edc-af52-dc879e1712a1 | 2 | public GedcomObjectFactory findFactoryForTag(String tag) {
if (tag.equalsIgnoreCase("DATE"))
return dateFactory;
else if (tag.equalsIgnoreCase("PLAC"))
return placeFactory;
else
return null;
} |
1d5aae56-7368-449a-8518-6e9ff9919ad2 | 9 | @EventHandler
public void onPlayerDeathEvent(PlayerDeathEvent event) {
Player player = (Player) event.getEntity();
if (!player.hasPermission("trophyheads.drop")) {
return;
}
if (randomGenerator.nextInt(100) >= DROP_CHANCES.get(EntityType.PLAYER.toString())) {
return;
}
boolean dropOkay = false;
DamageCause dc;
if (player.getLastDamageCause() != null) {
dc = player.getLastDamageCause().getCause();
logDebug("DamageCause: " + dc.toString());
} else {
logDebug("DamageCause: NULL");
return;
}
if (DEATH_TYPES.contains(dc.toString())) {
dropOkay = true;
}
if (DEATH_TYPES.contains("ALL")) {
dropOkay = true;
}
if (player.getKiller() instanceof Player) {
logDebug("Player " + player.getName() + " killed by another player. Checking if PVP is valid death type.");
if (DEATH_TYPES.contains("PVP")) {
dropOkay = isValidItem(EntityType.PLAYER, player.getKiller().getItemInHand().getType());
logDebug("PVP is a valid death type. Killer's item in hand is valid? " + dropOkay);
} else {
logDebug("PVP is not a valid death type.");
}
}
if (dropOkay) {
logDebug("Match: true");
Location loc = player.getLocation().clone();
World world = loc.getWorld();
String pName = player.getName();
ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3);
ItemMeta itemMeta = item.getItemMeta();
ArrayList<String> itemDesc = new ArrayList<>();
itemMeta.setDisplayName("Head of " + pName);
itemDesc.add(event.getDeathMessage());
itemMeta.setLore(itemDesc);
if (playerSkin) {
((SkullMeta) itemMeta).setOwner(pName);
}
item.setItemMeta(itemMeta);
world.dropItemNaturally(loc, item);
} else {
logDebug("Match: false");
}
} |
29810106-f9ad-4da4-aaa7-72d458b229ed | 5 | protected void decodeAttribute(mxCodec dec, Node attr, Object obj)
{
String name = attr.getNodeName();
if (!name.equalsIgnoreCase("as") && !name.equalsIgnoreCase("id"))
{
Object value = attr.getNodeValue();
String fieldname = getFieldName(name);
if (isReference(obj, fieldname, value, false))
{
Object tmp = dec.getObject(String.valueOf(value));
if (tmp == null)
{
System.err.println("mxObjectCodec.decode: No object for "
+ getName() + "." + fieldname + "=" + value);
return; // exit
}
value = tmp;
}
if (!isExcluded(obj, fieldname, value, false))
{
setFieldValue(obj, fieldname, value);
}
}
} |
7846a1ba-192a-4b44-b0a8-6ee4a206593f | 6 | public void dequeueSound( String filename )
{
if( !toStream )
{
errorMessage( "Method 'dequeueSound' may only be used for " +
"streaming and MIDI sources." );
return;
}
if( filename == null || filename.equals( "" ) )
{
errorMessage( "Filename not specified in method 'dequeueSound'" );
return;
}
synchronized( soundSequenceLock )
{
if( soundSequenceQueue != null )
{
ListIterator<FilenameURL> i = soundSequenceQueue.listIterator();
while( i.hasNext() )
{
if( i.next().getFilename().equals( filename ) )
{
i.remove();
break;
}
}
}
}
} |
21aa1558-34e4-4360-9b7b-79973a8c926a | 4 | private void closeDB(){
try {
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
a7da799d-7044-4073-8acc-0d5939278316 | 2 | private static ResCache makeglobal() {
ResCache ret;
if ((ret = JnlpCache.create()) != null)
return (ret);
if ((ret = FileCache.foruser()) != null)
return (ret);
return (null);
} |
8797e0be-f79e-4571-b033-954b29acfb4e | 2 | public static void loadAllAchievements() {
String statement = new String("SELECT * FROM " + DBTable + " WHERE type = ?");
PreparedStatement stmt;
try {
stmt = DBConnection.con.prepareStatement(statement);
stmt.setInt(1, HIGHSCORE_TYPE);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
HighScoreAchievement achievement = new HighScoreAchievement(rs.getInt("aid"), rs.getString("name"), rs.getString("url"),
rs.getString("description"), rs.getInt("threshold"));
allAchievements.add(achievement);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
} |
1befae6b-6cfa-4a42-b30a-2046faecf6e6 | 2 | public ArrayList<Fish> reproduceWithFish(Fish f) {
Random generator = new Random();
ArrayList<Fish> babies = new ArrayList<Fish>();
double num = generator.nextDouble();
if (num <= .01) {
int num1 = generator.nextInt(2);
for (int x = 0; x <= num1; x++) {
babies.add(new Shark(this.x, this.y, this.bounds));
}
}
return babies;
} |
7923af32-e7d6-4f98-a7ce-8ccfe1d58f31 | 1 | @Test
public void testGetSquareContent() {
board.removeAllPawns();
Pawn pawn1 = new Pawn('a', 2, 2, board);
board.addPawn(pawn1);
if (board.getSquareContent(2, 2) != null) {
assertEquals('a', board.getSquareContent(2, 2).getLetter());
} else {
fail();
}
} |
a7c0e7d5-fcc8-4244-9ff2-1d2b255fdd77 | 7 | public void input()
{
System.out.println("Available choices are score, flag, reveal, board, save, help, and exit");
String inputString = input.next().trim().toLowerCase();
if (inputString.equals("score")) {
score();
}
else if (inputString.equals("flag")) {
System.out.println("Where to flag?\nplease input as 'x,y'");
accessCell(1);
score();
}
else if (inputString.equals("reveal")) {
System.out.println("Where to reveal?\nplease input as 'x,y'");
accessCell(0);
score();
}
else if (inputString.equals("board")) {
System.out.println(boardView.boardToString());
}
else if (inputString.equals("save")) {
menuModel.getBoardModel().saveBoard();
System.out.println("game saved");
}
else if (inputString.equals("help")) {
System.out.println("score: Shows the current score and flags");
System.out.println("flag: Flags a cell on the board");
System.out.println("reveal: Reveals a cell on the baord");
System.out.println("save: Saves the game");
System.out.println("exit: Exits back to the main menu");
}
else if (inputString.equals("exit")) {
drawMainMenu();
return;
}
else {
System.out.println("Sorry, I didn't recognise that command");
}
input();
} |
e8279fca-cac9-487a-9f35-f2ff0ac34b96 | 7 | private static int findMatch(String s, String p) {
if (s == null || p == null) return -1;
int m = s.length();
int n = p.length();
if (m < n) return -1;
for (int i = 0; i <= (m - n); i++) { // (M - N) steps
int j = 0;
while(j < n && s.charAt(i + j) == p.charAt(j)) { // at most N steps
j++;
}
if (j == n) return i;
}
return -1;
} |
806ec4f6-1a4e-4d5b-90c3-be1605ffde4a | 0 | public BounceFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setTitle("Bounce");
comp = new BallComponent();
add(comp, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel, "Start", new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
addBall();
}
});
addButton(buttonPanel, "Close", new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
add(buttonPanel, BorderLayout.SOUTH);
} |
d8c3f493-f08a-44f0-9360-d8b6772912ee | 9 | public static String getBaseURI(NodeInfo node) {
String xmlBase = node.getAttributeValue(StandardNames.XML_BASE);
if (xmlBase != null) {
URI baseURI;
try {
baseURI = new URI(xmlBase);
if (!baseURI.isAbsolute()) {
NodeInfo parent = node.getParent();
if (parent == null) {
// We have a parentless element with a relative xml:base attribute.
// See for example test XQTS fn-base-uri-10 and base-uri-27
URI base = new URI(node.getSystemId());
URI resolved = (xmlBase.length()==0 ? base : base.resolve(baseURI));
return resolved.toString();
}
String startSystemId = node.getSystemId();
String parentSystemId = parent.getSystemId();
URI base = new URI(startSystemId.equals(parentSystemId) ? parent.getBaseURI() : startSystemId);
baseURI = (xmlBase.length()==0 ? base : base.resolve(baseURI));
}
} catch (URISyntaxException e) {
// xml:base is an invalid URI. Just return it as is: the operation that needs the base URI
// will probably fail as a result. \
return xmlBase;
}
return baseURI.toString();
}
String startSystemId = node.getSystemId();
NodeInfo parent = node.getParent();
if (parent == null) {
return startSystemId;
}
String parentSystemId = parent.getSystemId();
if (startSystemId.equals(parentSystemId)) {
return parent.getBaseURI();
} else {
return startSystemId;
}
} |
eb636f3b-9374-408b-973c-3d9286d2b6b7 | 2 | public void display(){
int index = 0;
while(index<SIZE) {
if (elements[index] != null) {
LinkedNode node = (LinkedNode) elements[index];
node.display();
}
index++;
}
} |
76108288-73ab-4d73-b2ad-7a708d660f2f | 9 | @Test
public void testPingSocket() {
LOGGER.log(Level.INFO, "----- STARTING TEST testPingSocket -----");
String client_hash = "";
String client_hash2 = "";
server1.setUseDisconnectedSockets(true);
Server server3 = null;
try {
server3 = new Server(game, port, false);
} catch (IOException | ServerSocketCloseException | TimeoutException e) {
exception = true;
}
try {
server1.startThread();
} catch (IOException | ServerSocketCloseException | FeatureNotUsedException e) {
exception = true;
}
waitListenThreadStart(server1);
try {
client_hash = server2.addSocket("127.0.0.1");
} catch (IOException | TimeoutException e) {
exception = true;
}
waitSocketThreadAddNotEmpty(server2);
waitSocketThreadState(server2, client_hash, SocketThread.CONFIRMED);
try {
client_hash2 = server3.addSocket("127.0.0.1");
} catch (IOException | TimeoutException e) {
exception = true;
}
waitSocketThreadAddNotEmpty(server3);
waitSocketThreadState(server3, client_hash2, SocketThread.CONFIRMED);
boolean loop = true;
Timing new_timer = new Timing();
while (loop) {
if (server1.getSocketList().size() == 2 || new_timer.getTime() > timeout) {
loop = false;
}
}
try {
server1.pingSockets();
} catch (IOException e) {
exception = true;
}
time.waitTime(wait);
boolean not_disconnected = server1.getDisconnectedSockets().isEmpty();
Assert.assertTrue(not_disconnected, "Could not ping sockets");
try {
server3.close();
} catch (IOException | ServerSocketCloseException | TimeoutException e) {
exception = true;
}
waitServerState(server3, Server.CLOSED);
Assert.assertFalse(exception, "Exception found");
LOGGER.log(Level.INFO, "----- TEST testPingSocket COMPLETED -----");
} |
93b7661c-8642-4a85-b9a5-b75b1b74a8b8 | 0 | public String toString() {
return "STATE: " + myState.toString() + " COLOR: " + myColor;
} |
a70630cd-075a-4924-85e8-3161c1269a63 | 8 | public void DBDeleteAreaAndRooms(Area A)
{
if(A==null)
return;
if(!A.isSavable())
return;
if(Log.debugChannelOn()&&(CMSecurity.isDebugging(CMSecurity.DbgFlag.CMAREA)||CMSecurity.isDebugging(CMSecurity.DbgFlag.DBROOMS)))
Log.debugOut("RoomLoader","Destroying area "+A.name());
A.setAreaState(Area.State.STOPPED);
final List<String> statements = new Vector<String>(4 + A.numberOfProperIDedRooms());
statements.addAll(getAreaDeleteStrings(A.Name()));
statements.add("DELETE FROM CMROOM WHERE CMAREA='"+A.Name()+"'");
for(Enumeration<String> ids=A.getProperRoomnumbers().getRoomIDs();ids.hasMoreElements();)
statements.addAll(getRoomDeleteStrings(ids.nextElement()));
statements.add("DELETE FROM CMROOM WHERE CMAREA='"+A.Name()+"'");
final String[] statementsBlock = statements.toArray(new String[statements.size()]);
statements.clear();
for(int i=0;i<3;i++)
{
// not even mysql delete everything as commanded.
DB.update(statementsBlock);
try
{
Thread.sleep(A.numberOfProperIDedRooms());
}
catch(Exception e)
{
}
}
} |
6e61abea-9fea-4c91-8ade-b243acb5028e | 9 | void drawEllipse(int color, int sz, int xc, int yc, int a, int b) {
/* e(x,y) = b^2*x^2 + a^2*y^2 - a^2*b^2 */
int x = 0, y = b;
long a2 = (long)a*a;
long b2 = (long)b*b;
long crit1 = -(a2/4 + a%2 + b2);
long crit2 = -(b2/4 + b%2 + a2);
long crit3 = -(b2/4 + b%2);
long t = -a2*y; /* e(x+1/2,y-1/2) - (a^2+b^2)/4 */
long dxt = 2*b2*x;
long dyt = -2*a2*y;
long d2xt = 2*b2;
long d2yt = 2*a2;
while (y>=0 && x<=a) {
paintPixelAreaXY(color, sz, xc+x, yc+y);
if (x!=0 || y!=0)
paintPixelAreaXY(color, sz, xc-x, yc-y);
if (x!=0 && y!=0) {
paintPixelAreaXY(color, sz, xc+x, yc-y);
paintPixelAreaXY(color, sz, xc-x, yc+y);
}
if (t + b2*x <= crit1 || /* e(x+1,y-1/2) <= 0 */
t + a2*y <= crit3) { /* e(x+1/2,y) <= 0 */
x++;
dxt += d2xt;
t += dxt;
} else if (t - a2*y > crit2) { /* e(x+1/2,y-1) > 0 */
y--;
dyt += d2yt;
t += dyt;
} else {
x++;
dxt += d2xt;
t += dxt;
y--;
dyt += d2yt;
t += dyt;
}
}
} |
660728ea-e4e2-4727-936a-5af6d6a86c71 | 1 | public boolean EliminarTrata(Trata p){
if (p!=null) {
cx.Eliminar(p);
return true;
}else {
return false;
}
} |
c670a533-38b2-4f81-bfe7-60584231f1f0 | 4 | @Override
public String newProgrammesThisWeek() throws WhatsNewServiceException
{
List<BroadCastProgramme> programmeList = iProgrammesThisWeekService.programmesThisWeek();
List<Programme> newProgrammes = new ArrayList<Programme>();
if (programmeList != null)
{
for (BroadCastProgramme broadCastProgramme : programmeList)
{
// only add Programmes which are new(i.e no firstBroadcastDateTime)
if (broadCastProgramme.getFirstBroadCaseDateTime() == null)
{
newProgrammes.add(broadCastProgramme.getProgramme());
}
}
}
try
{
return JSONUtils.toJSON(newProgrammes);
} catch (JSONParsingException e)
{
throw new WhatsNewServiceException("Exception parsing JSON", e);
}
} |
38841994-18f6-4bca-be78-dca23bbe4dc8 | 8 | public void checkType(Symtab st) {
exp1.setScope(scope);
exp1.checkType(st);
exp2.setScope(scope);
exp2.checkType(st);
exp1Type = exp1.getType(st);
exp2Type = exp2.getType(st);
if (!exp1Type.equals("int") && !exp1Type.equals("decimal")
&& !exp1Type.equals("String") && !exp1Type.equals("message"))
Main.error("type error in plus expression (" + exp1.getValue() + ")");
if (!exp2Type.equals("int") && !exp2Type.equals("decimal")
&& !exp2Type.equals("String") && !exp2Type.equals("message"))
Main.error("type error in plus expression (" + exp2.getValue() + ")");
} |
ea66ad07-76a4-4ccf-95d9-e8cd796b0cca | 3 | public ArrayList<String> getDimensionsFromPoints(ArrayList<ClusterPoint> p)
{
ArrayList<String> pointDimensionValues = new ArrayList<String>();
for(int i = 0; i < p.size(); i++)
{
for(int j = 0; j < dimensionCount; j++)
{
try { pointDimensionValues.add(Double.toString(p.get(i).getValueAtDimension(j))); }
catch (Exception e) { pointDimensionValues.add("0.0"); }
}
}
return pointDimensionValues;
} |
f88503c5-ce34-4133-b26f-3db9aceee0e8 | 8 | public void cullConnections() throws SQLException
{
int availableCount = 0;
for (IMySQLConnection conn : conns)
{
if(conn.isAvailable()) {
++availableCount;
}
}
double check = ((double)availableCount) / ((double)conns.size());
if((conns.size() > 10) && (availableCount > 5) && (check > 0.3))
{
int cullCount = availableCount / 2;
while(cullCount > 0) {
for (IMySQLConnection conn : conns)
{
if(conn.isAvailable()) {
conn.clean();
conn.close();
conns.remove(conn);
break;
}
}
--cullCount;
}
}
} |
0968cfaa-68b2-418d-9758-71471c6eed7b | 3 | private void createDropWidget(Composite parent) {
parent.setLayout(new FormLayout());
Combo combo = new Combo(parent, SWT.READ_ONLY);
combo.setItems(new String[] {"Toggle Button", "Radio Button", "Checkbox", "Canvas", "Label", "List", "Table", "Tree", "Text", "StyledText", "Combo"});
combo.select(LABEL);
dropControlType = combo.getSelectionIndex();
dropControl = createWidget(dropControlType, parent, "Drop Target");
combo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Object data = dropControl.getLayoutData();
Composite parent = dropControl.getParent();
dropControl.dispose();
Combo c = (Combo)e.widget;
dropControlType = c.getSelectionIndex();
dropControl = createWidget(dropControlType, parent, "Drop Target");
dropControl.setLayoutData(data);
if (dropEnabled) createDropTarget();
parent.layout();
}
});
Button b = new Button(parent, SWT.CHECK);
b.setText("DropTarget");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button)e.widget;
dropEnabled = b.getSelection();
if (dropEnabled) {
createDropTarget();
} else {
if (dropTarget != null){
dropTarget.dispose();
}
dropTarget = null;
}
}
});
// initialize state
b.setSelection(true);
dropEnabled = true;
FormData data = new FormData();
data.top = new FormAttachment(0, 10);
data.bottom = new FormAttachment(combo, -10);
data.left = new FormAttachment(0, 10);
data.right = new FormAttachment(100, -10);
dropControl.setLayoutData(data);
data = new FormData();
data.bottom = new FormAttachment(100, -10);
data.left = new FormAttachment(0, 10);
combo.setLayoutData(data);
data = new FormData();
data.bottom = new FormAttachment(100, -10);
data.left = new FormAttachment(combo, 10);
b.setLayoutData(data);
} |
da17c63d-5c21-4506-ad8e-ac363a2a2abb | 9 | public SampleBuilder<P> blanks2blanks(Map<BlankBuilder<?>, BlankBuilder<?>> blanks2blanks) {
verifyMutable();
if (this.blanks2blanks == null) {
this.blanks2blanks = new HashMap<BlankBuilder<?>, BlankBuilder<?>>();
}
if (blanks2blanks != null) {
for (Map.Entry<BlankBuilder<?>, BlankBuilder<?>> e : blanks2blanks.entrySet()) {
CollectionUtils.putItem(this.blanks2blanks, e.getKey(), e.getValue());
}
}
return this;
} |
8be605a1-58dc-43d6-9dcf-ea0247f688f2 | 1 | private boolean jj_3_52() {
if (jj_3R_70()) return true;
return false;
} |
6d53f85d-ceb6-4d1a-87a7-48c5f9178e80 | 2 | @Transient
public List<LabelValue> getRoleList() {
List<LabelValue> userRoles = new ArrayList<LabelValue>();
if (this.roles != null) {
for (Role role : roles) {
// convert the user's roles to LabelValue Objects
userRoles.add(new LabelValue(role.getName(), role.getName()));
}
}
return userRoles;
} |
f067f862-3c67-43d6-8568-b7a3925ccbaf | 4 | public static double LinkedListFromArrayBench(int number) {
LinkedListFromArray ll = new LinkedListFromArray();
long addLastTime = System.currentTimeMillis();
for (int i = 0; i < number; i++) {
ll.addLast("" + Math.random());
}
addLastTime = System.currentTimeMillis() - addLastTime;
ll = new LinkedListFromArray();
long addFirstTime = System.currentTimeMillis();
for (int i = 0; i < number; i++) {
ll.addFirst("" + Math.random());
}
addFirstTime = System.currentTimeMillis() - addFirstTime;
ll = new LinkedListFromArray();
long insertTime = System.currentTimeMillis();
for (int i = 0; i < number; i++) {
ll.insertAt(ll.getSize() / 2, "" + Math.random());
}
insertTime = System.currentTimeMillis() - insertTime;
long removeTime = System.currentTimeMillis();
for (int i = 0; i < number; i++) {
ll.removeAt(ll.getSize() / 2);
}
removeTime = System.currentTimeMillis() - removeTime;
System.out.println("LLFA: " + LLBenchInfoString(addLastTime, addFirstTime,
insertTime, removeTime));
return addLastTime + addFirstTime + insertTime + removeTime;
} |
Subsets and Splits