method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
3fc3f0c1-737f-4671-bdc7-5121b8650e98 | 2 | final public void forceSubtreeValid() {
if(children==null)
return;
for(PropertyTree child : children) {
child.forceSubtreeValid();
}
} |
740f3efb-30e9-424a-93c7-9c4328eeff0c | 3 | public static Company [] findAllCompanyData() {
Company [] companydata;
String read;
ArrayList<String> companyData = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new FileReader("company.txt"));
while((read = reader.readLine()) != null) {
companyData.add(read);
}
reader.close();
}
catch(IOException i) {
try{
File file = new File("company.txt");
file.createNewFile();
}
catch(IOException j){}
}
companydata = stringToCompany(companyData);
return companydata;
} |
c2a2edfa-0a5b-4b4d-9f04-c34120e02d38 | 5 | @Override
public void valueChanged(ListSelectionEvent arg0) {
int select = table.getSelectedRow();
if (select != -1) {
Item item = null;
String title = (String) table.getValueAt(select, 0);
String author = (String) table.getValueAt(select, 1);
String genre = (String) table.getValueAt(select, 2);
double length = (double) table.getValueAt(select, 3);
int rating = (int) table.getValueAt(select, 4);
ItemType type = (ItemType) table.getValueAt(select, 5);
try {
switch (type) {
case BOOK:
item = new Music(title, author, length,
genre, rating, Item.ItemType.BOOK);
break;
case MUSIC:
item = new Music(title, author, length, genre,
rating, Item.ItemType.MUSIC);
break;
default:
System.out.println("Missing type?");
break;
}
}
catch (IllegalItemException e) {
e.printStackTrace();
}
if (item != null) {
new InfoDialog(MainFrame.instance, item, image);
}
}
} |
4d017a21-d3f7-4930-b8aa-a8b0b0bb6cfd | 1 | public Integer increment(K key){
if (map.containsKey(key)){
map.put(key, map.get(key)+1);
}
else {
map.put(key, 1);
}
return map.get(key);
} |
f1ce9739-ed53-420c-a8ed-5b461421cd16 | 0 | public void setCity(String city) {
City = city;
} |
fcc3c69c-0f95-4a6b-9399-7d4e9b7de44f | 6 | private void collisionCheck() {
if ( (ballY <= 0) || (ballY >= frameHeight - size - 22) )
ballSpeedY *= -1;//reverses y direction when the ball hits the sides
if (ballX < width) {
if ((new Rectangle(p1x, (int) p1y, width, height).contains(new Point((int)ballX, (int) ballY + (size / 2) ))) )
ballBounce(1);
else p2Score();
}
if (ballX > frameWidth - size - width) {
if (new Rectangle(p2x, (int) p2y, width, height).contains(new Point((int) ballX + size, (int)ballY + (size / 2) )) )
ballBounce(2);
else p1Score();
}
} |
2eafa9c5-1a5c-40ac-822b-71ecf7226d8f | 0 | public Date getEnd() {
return end;
} |
6e492e49-e4fe-4017-9eb8-d4c5f871c0bc | 3 | public List<T> create(int nElements){
List<T> result = new ArrayList<T>();
try {
for(int i=0;i < nElements;i ++){
result.add(type.newInstance());
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return result;
} |
9ec02049-5ea6-4325-bad2-5b8862d0e26d | 8 | public FileStream(RandomAccessFile source) throws OggFormatException, IOException {
this.source = source;
ArrayList<Long> po = new ArrayList<>();
int pageNumber = 0;
try {
while (true) {
po.add(this.source.getFilePointer());
// skip data if pageNumber>0
OggPage op = getNextPage(pageNumber > 0);
if (op == null) {
break;
}
LogicalOggStreamImpl los = (LogicalOggStreamImpl) getLogicalStream(op
.getStreamSerialNumber());
if (los == null) {
los = new LogicalOggStreamImpl(this);
logicalStreams.put(op.getStreamSerialNumber(), los);
}
if (pageNumber == 0) {
los.checkFormat(op);
}
los.addPageNumberMapping(pageNumber);
los.addGranulePosition(op.getAbsoluteGranulePosition());
if (pageNumber > 0) {
this.source.seek(this.source.getFilePointer() + op.getTotalLength());
}
pageNumber++;
}
} catch (EndOfOggStreamException e) {
// ok
} catch (IOException e) {
throw e;
}
// System.out.println("pageNumber: "+pageNumber);
this.source.seek(0L);
pageOffsets = new long[po.size()];
int i = 0;
for (Long next : po) {
pageOffsets[i++] = next;
}
} |
88b03913-c40d-4ac0-85a8-3d2df97859ad | 6 | private void btn_proximoDadosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_proximoDadosActionPerformed
try {
if (txt_operacao.getText().equals("INCLUSÃO") == true) {
if (cbx_segmento.getSelectedItem() == null) {
JOptionPane.showMessageDialog(null, "Selecione um segmento!");
} else {
if ((existeCNPJ(txt_cpf.getText()) == false) && (existeRazao(txt_razaoSocial.getText()) == false) && (existeEmail(txt_email.getText()) == false)) {
validaDadosPessoais(txt_cpf.getText(), txt_inscEstadual.getText(), txt_razaoSocial.getText(),
txt_nomeFantasia.getText(), txt_responsavel.getText(), txt_email.getText(), cbx_segmento.getSelectedItem().toString());
}
}
} else {
validaDadosPessoais(txt_cpf.getText(), txt_inscEstadual.getText(), txt_razaoSocial.getText(),
txt_nomeFantasia.getText(), txt_responsavel.getText(), txt_email.getText(), cbx_segmento.getSelectedItem().toString());
}
} catch (Exception e) {
System.out.println(e);
}
} |
c028d51c-93a3-48b9-b3f6-6872bd0c6886 | 0 | public List<RoomEvent> findRoomEventsByHallEventIdForTimeInterval(
final Long hallEventId, final Long start, final Long end
) {
return new ArrayList<RoomEvent>();
} |
2e906f20-7840-4e11-8de1-83b5afe741a5 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof CappedValue)) {
return false;
}
CappedValue other = (CappedValue) obj;
if (max == null) {
if (other.max != null) {
return false;
}
} else if (!max.equals(other.max)) {
return false;
}
if (current == null) {
if (other.current != null) {
return false;
}
} else if (!current.equals(other.current)) {
return false;
}
return true;
} |
5454ded0-cf07-4ef2-ae20-815f62748d4f | 5 | public boolean updateHotkeyBinding(String key, HotkeyEntry entry) {
if (!this.fileLoaded) {
return false;
}
try {
XMLNode hotkeysNode = this.rootNode.getChildNodesByType("hotkeys")[0];
XMLNode[] hotkeyNodes = hotkeysNode.getChildNodesByType("hotkey");
for (XMLNode node : hotkeyNodes) {
XMLNode name = node.getChildNodesByType("name")[0];
if (name.getValue().equalsIgnoreCase(key)) {
name.setValue(entry.getName());
node.getChildNodesByType("comb")[0].setValue(entry.getCombination());
if (entry.isTrayPopup()) {
node.addParameter(new KeyValue<String, String>("tray-popup", "true"));
} else {
node.removeParameter("tray-popup");
}
this._getHotkeys();
return true;
}
}
return false;
} catch (Exception ex) {
return false;
}
} |
4ea6b788-8a18-4ee6-b2c6-98af0e67448a | 4 | protected void typeTableGen(){
for(String key: dataTable.keySet()){
/*This http transanction happens more than once*/
String typeType = dataTable.get(key).returnType();
// System.out.println("Pcik out record with type of: "+typeType);
int typeCount = dataTable.get(key).returnCount();
int typeSize = typeCount*dataTable.get(key).returnSize();
InfoItemSlot item = new InfoItemSlot(typeType,typeSize,typeCount);
/*generate the type-based table*/
if(!typeTable.containsKey(typeType)){
/*update the dupTable*/
typeTable.put(typeType,item);
}else{
typeTable.get(typeType).sizePlus(typeSize);
typeTable.get(typeType).countPlus(typeCount);
}
/*generate the type-based dup table*/
if(typeCount>1){
/*we only count the unique part!*/
typeCount--;
typeSize-=dataTable.get(key).returnSize();
InfoItemSlot dupItem = new InfoItemSlot(typeType,typeSize,typeCount);
if(!dupTable.containsKey(typeType)){
/*update the dupTable*/
dupTable.put(typeType,dupItem);
}else{
dupTable.get(typeType).sizePlus(typeSize);
dupTable.get(typeType).countPlus(typeCount);
}
}
}
} |
f2531078-9611-49cf-8749-88423f6575da | 6 | @Override
public void simpleInitApp() {
try {
initLogging();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
setDisplayStatView(false);
setDisplayFps(false);
try {
String[] roots = { "assets/Scripts" };
gsm = new GameScriptManager(roots);
gsm.loadComponentClasses("assets" + File.separator + "GameObjects");
} catch (Exception e) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "Couldnt create GameScriptManager", e);
stop();
}
try {
Parameters.createParameterSet("general", "assets/GameDefs/standard_generation_parameters.xml");
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
try {
initNifty();
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "Couldnt validate screens.xml", ex);
stop();
}
inputManager.setCursorVisible(true);
flyCam.setDragToRotate(true);
NiftyEventAnnotationProcessor.process(this);
} |
e14bb964-c7a8-449c-b008-3b5f393e79a0 | 2 | @Test
public void checkRandomness()
{
List<Integer> sides = Arrays.asList(1,2,3,4,5,6);
int[] counts = new int[sides.size()];
Dice<Integer> dice = new Dice<Integer>(sides);
for ( int i = 0; i < NUMBER_OF_THROWS; i++)
{
counts[dice.roll() - 1]++;
}
final int averageNumberExpected = NUMBER_OF_THROWS / sides.size();
System.out.println("Expected to roll " + averageNumberExpected + " on each side.");
for ( int i = 0; i < counts.length; i++)
{
System.out.println( i + " : " + counts[i]);
// Check that each side has approximately the expect number of occurrences to <5%
assertTrue("Too few rolls for " + i, counts[i] > averageNumberExpected * 0.95);
assertTrue("Too many rolls for " + i, counts[i] < averageNumberExpected * 1.05);
}
} |
492f396f-73ec-4cbc-9800-821d6083dfbf | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof TaxonNameStatus)) {
return false;
}
TaxonNameStatus other = (TaxonNameStatus) object;
if ((this.key == null && other.key != null) || (this.key != null && !this.key.equals(other.key))) {
return false;
}
return true;
} |
5253a70b-dd2e-4999-b437-8ab17b04db32 | 7 | final public void conclusion() throws ParseException {
Token conclusionType;
Literal literal;
if (jj_2_70(7)) {
conclusionType = jj_consume_token(DEFINITE_PROVABLE);
} else if (jj_2_71(7)) {
conclusionType = jj_consume_token(DEFINITE_NOT_PROVABLE);
} else if (jj_2_72(7)) {
conclusionType = jj_consume_token(DEFEASIBLE_PROVABLE);
} else if (jj_2_73(7)) {
conclusionType = jj_consume_token(DEFEASIBLE_NOT_PROVABLE);
} else {
jj_consume_token(-1);
throw new ParseException();
}
literal = literal();
try {
ConclusionType ct=ConclusionType.getConclusionType(conclusionType.image.trim());
Map<ConclusionType, Conclusion> conclusionList = conclusions.get(literal);
if (null==conclusionList) {
conclusionList = new TreeMap<ConclusionType, Conclusion>();
conclusions.put(literal, conclusionList);
}
conclusionList.put(ct,new Conclusion(ct,literal));
} catch (Exception e) {
{if (true) throw new Error(e);}
}
} |
a9352f6c-269f-4391-9dd6-b447aa46624a | 0 | public BlueprintList() {
BPO = new ArrayList<Blueprint>();
} |
fa3fa3fb-ed26-4b06-96de-b503970e6f67 | 0 | public GrammarChecker() {
} |
a9c135b9-1bff-4022-b2c9-487124f4dc13 | 0 | public boolean getConcurrent(){
return this.concurrent;
} |
539ee384-4875-4517-ae5b-25b0e3e0fbbc | 1 | public Class<? extends APacket> getPacketClassByID(int id) {
return PList.get(id);
} |
04a6ae7a-e7b7-4154-bf34-476665fba108 | 4 | @Override
public void validate(Object obj, Errors e) {
Image image = (Image) obj;
if (image.getFile() == null) {
e.rejectValue("file", "error.nothing.to.upload");
return;
}
String mime = image
.getFile()
.getContentType()
.substring(image.getFile().getContentType().indexOf("/") + 1, image.getFile().getContentType().length())
.toUpperCase();
for (ImageMIMETypes supportedMime : ImageMIMETypes.values()) {
if (mime.contains(supportedMime.toString())) {
if (image.getFile().getSize() > MAX_IMAGE_SIZE) {
e.rejectValue("file", "error.image.too.big");
}
return;
}
}
e.rejectValue("file", "error.image.of.not.supported.type");
} |
429a45e1-b9b0-41f0-8446-7f7def7a45bd | 4 | public static byte[] getExcelEncoding( String s )
{
byte[] strbytes = null;
try
{
strbytes = s.getBytes( "UnicodeLittleUnmarked" );
}
catch( UnsupportedEncodingException e )
{
log.warn( "Error creating encoded string: " + e, e );
}
boolean unicode = false;
for( int i = 0; i < strbytes.length; i++ )
{
i = i + 1;
if( strbytes[i] != 0x0 )
{
unicode = true;
i = strbytes.length;
}
}
if( unicode )
{
//try{
return strbytes;
//}catch(UnsupportedEncodingException e){Logger.logInfo("Error creating encoded string: " + e);}
}
return s.getBytes();
} |
563f8764-660d-477a-ae00-01333b4ed5e3 | 7 | public void block(MatchData data)
{
numCorrectPairs = countCorrectPairs(data);
pairList = new ArrayList();
for (int i=0; i<data.numSources(); i++) {
int lo1 = clusterMode? i : i+1;
for (int j=lo1; j<data.numSources(); j++) {
String src1 = data.getSource(i);
String src2 = data.getSource(j);
for (int k=0; k<data.numInstances(src1); k++) {
int lo2 = (clusterMode && src1==src2) ? k+1 : 0;
for (int el=lo2; el<data.numInstances(src2); el++) {
MatchData.Instance a = data.getInstance(src1,k);
MatchData.Instance b = data.getInstance(src2,el);
Pair p = new Pair( a, b, a.sameId(b) );
pairList.add(p);
}
}
}
}
} |
67b7e172-cc14-40d3-8d77-7e72515e9866 | 1 | public void check() {
try {
status = a.isReachable(600);
} catch (IOException e) {
e.printStackTrace();
}
} |
85b02931-e75e-4964-b420-2487177bf06b | 6 | public static String reverse(String input) {
if (input == null || input.isEmpty()) {
return input;
}
String reverse = "";
String word = "";
String output = "";
for (int i = input.length() - 1; i >= 0; i--) {
reverse = reverse + input.charAt(i);
}
for (int j = 0; j < reverse.length(); j++) {
if (reverse.charAt(j) == ' ') {
output = output + " " + word;
word = "";
} else {
word = reverse.charAt(j) + word;
if (j == reverse.length() - 1) {
output = output + " " + word;
}
}
}
return output.trim();
} |
4e441e5f-e840-4228-a6d4-0cfc1debb4ac | 5 | private void doFirmwareUpload() throws FirmwareFlashException {
int exitCode;
try {
ProcessBuilder pb = new ProcessBuilder();
// this would be where you'd switch based on OS to run the appropriate
// firmware upload command.
Vector<String> commandLine = new Vector<String>();
if (os == OS.WINDOWS) {
// pb.directory(new File("windows_flash"));
commandLine.add("windows_flash/avrdude.exe");
commandLine.add("-Cwindows_flash/avrdude.conf");
}
if (os == OS.MAC) {
commandLine.add("./mac_flash/avrdude");
commandLine.add("-Cmac_flash/avrdude.conf");
}
if (os == OS.LINUX) {
pb.directory(new File(System.getProperty("user.dir")));
commandLine.add("avrdude");
}
commandLine.add("-Ueeprom:w:firmware/blank_eeprom.hex:i");
commandLine.add("-Uflash:w:firmware/firmware.hex:i");
commandLine.add("-q");
commandLine.add("-patmega328p");
commandLine.add("-cstk500v1");
commandLine.add("-P" + window.getSelectedCOMPort());
commandLine.add("-b57600");
commandLine.add("-D");
pb.command(commandLine);
Process p = pb.start();
StreamLogPump errorPump = new StreamLogPump(p.getErrorStream(), "error");
StreamLogPump outputPump = new StreamLogPump(p.getInputStream(), "altimeter");
errorPump.start();
outputPump.start();
exitCode = p.waitFor();
} catch (Exception e) {
e.printStackTrace();
throw new FirmwareFlashException();
}
if (exitCode != 0) {
log("avrdude failed with exit code: " + exitCode, "error");
throw new FirmwareFlashException();
}
} |
c749195a-85a6-494b-8085-4d62cef901ec | 2 | public ArrayList<Yhdistelma> mahdollisetYhdistelmat(){
Yhdistelma y = new Yhdistelma(kasi);
ArrayList<Yhdistelma> yhdistelmat = y.getYhdistelmat(); // Kaikki kädestä saatavat yhdistelmät
ArrayList<Yhdistelma> toReturn = new ArrayList<Yhdistelma>(); // Palautettavat yhdistelmät
for(int i=0; i<yhdistelmat.size(); i++){
try{
vihko.getPisteet(yhdistelmat.get(i).getNimi()); // Kokeillaan, onko vihkoon jo asetettu yhdistelmälle pisteet
}
catch(NoPointsException e){ // Yhdistelmälle ei ole vielä asetettu pisteitä, joten lisätään yhdistelmä palautettaviin
toReturn.add(yhdistelmat.get(i));
}
}
Collections.sort(toReturn, Collections.reverseOrder()); // Järjestää yhdistelmät pisteiden mukaan laskevaan järjestykseen
return toReturn;
} |
d798edd4-4ab4-4115-a22c-e897b0efb461 | 1 | public static void main(String[] args)
{
Comparator<fringeObject> comparator = new fringeObjectComparator();
PriorityQueue<fringeObject> queue =
new PriorityQueue<fringeObject>(10, comparator);
queue.add(new fringeObject(null, null, 121, 22222222));
queue.add(new fringeObject(null, null, 121, 321));
queue.add(new fringeObject(null, null, 121, 864));
queue.add(new fringeObject(null, null, 121, 1646));
queue.offer(new fringeObject(null, null, 121, 23));
while (queue.size() != 0)
{
System.out.println(queue.remove().toString());
}
} |
19f75941-0775-4142-93e9-56b5980ffca2 | 4 | public static void main(String[] args) {
CommandLine cmd;
if (args.length == 6) {
cmd = doCommandLineParsing(args);
} else {
fromUI();
return;
}
/*
* Fügen Sie hier Anweisungen zum Einlesen einer PNG-Datei gemäß der
* Hinweise auf dem Übungblatt ein.
*/
BufferedImage inIMG = null;
try {
File in = new File(cmd.getOptionValue("s"));
inIMG = ImageIO.read(in);
} catch (IOException e) {
System.out.println("File not found or invalid. Please enter a valid source image");
System.exit(0);
}
// Ändern Sie den Namen "SimpleColorReduction" nicht!
SimpleColorReduction scr = new SimpleColorReduction();
/*
* Fügen Sie hier Anweisungen zum Aufruf Ihrer Implementierung ein.
* Dabei sollte die Farbanzahl des eingelesenen PNG-Bilds reduziert
* werden.
*/
int depth = 0;
scr.setSourceImage(inIMG);
try {
depth = Integer.parseInt(cmd.getOptionValue("c"));
} catch (NumberFormatException e) {
System.out.println("The new depth has to be a number divisible by 3");
System.exit(0);
}
scr.setDestBitDepth(depth);
scr.generateImage();
/*
* Fügen Sie hier Anweisungen zum Schreiben einer PNG-Datei gemäß der
* Hinweise auf dem Übungblatt ein.
*/
File out = new File(cmd.getOptionValue("d"));
try {
ImageIO.write(scr.getReducedImage(), "png", out);
} catch (IOException e) {
System.out.println("The specified output path is invalid");
System.exit(0);
}
} |
89c90ab3-81f9-4247-91d0-774924a9da08 | 0 | public void setFovY(float fovY) {
Radar.fovY = fovY;
} |
ac52d27b-e697-4e34-a8d1-3e679dfbd703 | 6 | private void method46(int i, Stream stream)
{
while(stream.bitPosition + 21 < i * 8)
{
int k = stream.readBits(14);
if(k == 16383)
break;
if(npcArray[k] == null)
npcArray[k] = new NPC();
NPC npc = npcArray[k];
npcIndices[npcCount++] = k;
npc.anInt1537 = loopCycle;
int l = stream.readBits(5);
if(l > 15)
l -= 32;
int i1 = stream.readBits(5);
if(i1 > 15)
i1 -= 32;
int j1 = stream.readBits(1);
npc.desc = EntityDef.forID(stream.readBits(12));
int k1 = stream.readBits(1);
if(k1 == 1)
anIntArray894[anInt893++] = k;
npc.anInt1540 = npc.desc.aByte68;
npc.anInt1504 = npc.desc.anInt79;
npc.anInt1554 = npc.desc.anInt67;
npc.anInt1555 = npc.desc.anInt58;
npc.anInt1556 = npc.desc.anInt83;
npc.anInt1557 = npc.desc.anInt55;
npc.anInt1511 = npc.desc.anInt77;
npc.setPos(myPlayer.smallX[0] + i1, myPlayer.smallY[0] + l, j1 == 1);
}
stream.finishBitAccess();
} |
78b86606-00a1-45e5-a907-fbdf87b8db24 | 6 | public void process() {
if (action != null) {
if (player.isDead()) {
forceStop();
} else if (!action.process(player)) {
forceStop();
}
}
if (actionDelay > 0) {
actionDelay--;
return;
}
if (action == null)
return;
int delay = action.processWithDelay(player);
if (delay == -1) {
forceStop();
return;
}
actionDelay += delay;
} |
706a26ff-1c01-4d1f-81b5-6367c12838ed | 8 | static String seq_name(int[] code, int max)
{
int j;
String buffer="";
StringBuilder dest = new StringBuilder();
for(j=0;j<SEQ_MAX;++j)
{
String name;
if ((code)[j] ==CODE_NONE)
break;
if (j != 0 && 1 + 1 <= max)
{
dest.append(' ');//*dest = ' ';
//dest += 1;
max -= 1;
}
name = code_name(code[j]);
if (name==null)
break;
if (name.length() + 1 <= max)//if (strlen(name) + 1 <= max)
{
dest.append(name);
//dest += strlen(name);
max -= strlen(name);
}
}
if (dest.toString().equals(buffer) && 4 + 1 <= max)
return dest.append("None").toString();
else
return dest.toString();
} |
6778ebcb-b8a2-4fc1-86ad-ea311cdced81 | 2 | public Collection<Column> getHiddenColumns() {
ArrayList<Column> list = new ArrayList<>();
for (Column column : mColumns) {
if (!column.isVisible()) {
list.add(column);
}
}
return list;
} |
7f1874fd-ebdf-4716-a4ae-6a4b74f57897 | 2 | public static void main(String[] args) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>();
Random rand = new Random(47);
for (int i = 0; i < 10; i++)
priorityQueue.offer(rand.nextInt(i + 10));
QueueDemo.printQ(priorityQueue);
List<Integer> ints = Arrays.asList(25, 22, 20, 18, 14, 9, 3, 1, 1, 2,
3, 9, 14, 18, 21, 23, 25);
priorityQueue = new PriorityQueue<Integer>(ints);
QueueDemo.printQ(priorityQueue);
priorityQueue = new PriorityQueue<Integer>(ints.size(),
Collections.reverseOrder());
priorityQueue.addAll(ints);
QueueDemo.printQ(priorityQueue);
String fact = "EDUCATION SHOULD ESCHEW OBFUSCATION";
List<String> strings = Arrays.asList(fact.split(""));
PriorityQueue<String> stringPQ = new PriorityQueue<String>(strings);
QueueDemo.printQ(stringPQ);
stringPQ = new PriorityQueue<String>(strings.size(),
Collections.reverseOrder());
stringPQ.addAll(strings);
QueueDemo.printQ(stringPQ);
Set<Character> charSet = new HashSet<Character>();
for (char c : fact.toCharArray())
charSet.add(c); // Autoboxing
PriorityQueue<Character> characterPQ = new PriorityQueue<Character>(
charSet);
QueueDemo.printQ(characterPQ);
} |
1b499187-8fd1-4089-8a87-a39dda3ada5b | 0 | public String getTelefono() {
return telefono;
} |
052f3826-7d5e-46ec-859f-0140e4c09e3a | 5 | private synchronized void albumsTableValueChanged(javax.swing.event.ListSelectionEvent evt) {
Logger.getLogger(MainInterface.class.getName()).entering(MainInterface.class.getName(), "albumsTableValueChanged");
album = null;
if (booksDirectory == null) {
return;
}
int selectedRow = albumsTable.getSelectedRow();
if (!evt.getValueIsAdjusting() && selectedRow != -1) {
stopThreadedPreviewLoaderID.add(threadedPreviewLoader.getId());
while (threadedPreviewLoader.isAlive()) {
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
}
album = new File(serie.toString() + File.separator + albumsTable.getValueAt(selectedRow, 0).toString() + albumsTable.getValueAt(selectedRow, 1).toString());
Logger.getLogger(MainInterface.class.getName()).log(Level.INFO, "Album \"{0}\" Selected", album);
threadedPreviewLoader = new PreviewImageLoader();
threadedPreviewLoader.start();
}
Logger.getLogger(MainInterface.class.getName()).exiting(MainInterface.class.getName(), "albumsTableValueChanged");
} |
01e1392a-48e4-4298-baca-4ce46cb92b37 | 8 | public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestUsername = request.getParameter("username");
String requestPassword = request.getParameter("password");
Map <String, Object> pageVariables = new HashMap<>();
String path = request.getPathInfo();
if(path.equals("/auth.html") || path.equals("/auth")){
if (accountService.authorize(requestUsername, requestPassword)) {
response.sendRedirect("/user");
pageVariables.put("serverTime", getTime());
pageVariables.put("refreshPeriod", "1000");
} else {
pageVariables.put("errorMessage", "Login or password was incorrect!");
response.getWriter().println(PageGenerator.getPage("auth.html", pageVariables));
}
}
if(path.equals("/reg.html") || path.equals("/reg")){
if(requestUsername.isEmpty() || requestPassword.isEmpty()){
pageVariables.put("registrationMessage", "Login or password was empty! Error!");
} else {
if(accountService.register(requestUsername, requestPassword)){
HttpSession session = request.getSession();
session.setAttribute("userId", accountService.getUserId(requestUsername));
pageVariables.put("registrationMessage", "User " + requestUsername + " was registered!");
} else {
pageVariables.put("registrationMessage", "User " + requestUsername + " is already registered! Try another login!");
}
}
response.getWriter().println(PageGenerator.getPage("reg.html", pageVariables));
}
} |
919fe80c-09da-4d3e-a4b3-47bec5094d80 | 9 | private int buildJump(int xo, int maxLength)
{ gaps++;
//jl: jump length
//js: the number of blocks that are available at either side for free
int js = random.nextInt(4) + 2;
int jl = random.nextInt(2) + 2;
int length = js * 2 + jl;
boolean hasStairs = random.nextInt(3) == 0;
int floor = height - 1 - random.nextInt(4);
//run from the start x position, for the whole length
for (int x = xo; x < xo + length; x++)
{
if (x < xo + js || x > xo + length - js - 1)
{
//run for all y's since we need to paint blocks upward
for (int y = 0; y < height; y++)
{ //paint ground up until the floor
if (y >= floor)
{
setBlock(x, y, GROUND);
}
//if it is above ground, start making stairs of rocks
else if (hasStairs)
{ //LEFT SIDE
if (x < xo + js)
{ //we need to max it out and level because it wont
//paint ground correctly unless two bricks are side by side
if (y >= floor - (x - xo) + 1)
{
setBlock(x, y, ROCK);
}
}
else
{ //RIGHT SIDE
if (y >= floor - ((xo + length) - x) + 2)
{
setBlock(x, y, ROCK);
}
}
}
}
}
}
return length;
} |
937a1c12-856b-46da-b064-85394427c9f0 | 2 | private void processQueue() {
SoftValueRef ref;
while ((ref = (SoftValueRef)queue.poll()) != null) {
if (ref == (SoftValueRef)hash.get(ref.key)) {
// only remove if it is the *exact* same WeakValueRef
//
hash.remove(ref.key);
}
}
} |
ff0272ac-0201-4c0b-bc3d-4e9938974962 | 5 | private void muoviBianca (boolean turno) { // cerca possibili mosse bianche (movimenti e mangiate)
// try catch usati per evitare i controlli sulle celle (superamento estremi damiera)
boolean occupata = false; // cella vicina è occupata da una pedina
try{
if(damiera.getCella(x-1,y+1).isEmpty()) // se cella diagonale in alto a destra è vuota
listaMosseValide.add(new Mossa(damiera.getCella(x, y),damiera.getCella(x-1, y+1),null,0)); // aggiungo la mossa alla lista (con percorso vuoto e pedine mangiate 0)
else // possibile mangiata
occupata=true;
}
catch(Exception e){}
try{
if(damiera.getCella(x-1,y-1).isEmpty()) // se cella diagonale in alto a sinistra è vuota
listaMosseValide.add(new Mossa(damiera.getCella(x, y),damiera.getCella(x-1, y-1),null,0)); // aggiungo la mossa alla lista (con percorso vuoto e pedine mangiate 0)
else // possibile mangiata
occupata=true;
}
catch(Exception e){}
if(occupata) // controllo possibili mangiate
muoviBiancaSeOccupata(x, y, 0, null, turno);
} |
9b2be9f3-4c37-4ba6-b907-b8df8e2c07b3 | 8 | @Override
public File createFile(final HTTPRequest request, String filePath)
{
final Pair<String,String> mountPath=config.getMount(request.getHost(),request.getClientPort(),filePath);
if(mountPath != null)
{
String newFullPath=filePath.substring(mountPath.first.length());
if(newFullPath.startsWith("/")&&mountPath.second.endsWith("/"))
newFullPath=newFullPath.substring(1);
filePath = (mountPath.second+newFullPath);
}
final FileManager mgr=config.getFileManager();
File finalFile = mgr.createFileFromPath(filePath.replace('/', mgr.getFileSeparator()));
// see if the path we have is complete, or if there's an implicit default page requested.
if(request.getUrlPath().endsWith("/"))
{
final File dirFile = finalFile;
finalFile=mgr.createFileFromPath(finalFile,config.getDefaultPage());
if((!finalFile.exists())&&(dirFile.exists())&&(dirFile.isDirectory()))
{
String browseCode = config.getBrowseCode(request.getHost(),request.getClientPort(),filePath);
if(browseCode != null) // it's allowed to be browsed
finalFile = dirFile;
}
}
return finalFile;
} |
02982cd0-5d9b-4c9b-aac2-5eeb9b88d0df | 0 | public String getCountry() {
return country.get();
} |
3cbe3e9f-b206-48a8-8868-6381eae4be97 | 8 | private static void UnZip(String ZipName,long fileSize, ProgressBar progressCurr,ProgressBar progressBarTotal) throws PrivilegedActionException
{
String szZipFilePath;
String szExtractPath;
String path = (String)AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
return Utils.GetCurrentClientDir() + File.separator + ".minecraft" + File.separator;
}
});
int i;
szZipFilePath = path + ZipName;
File f = new File(szZipFilePath);
if(!f.exists())
{
System.out.println(
"\nNot found: " + szZipFilePath);
}
if(f.isDirectory())
{
System.out.println(
"\nNot file: " + szZipFilePath);
}
//System.out.println("Enter path to extract files: ");
szExtractPath = path;
File f1 = new File(szExtractPath);
if(!f1.exists())
{
System.out.println(
"\nNot found: " + szExtractPath);
}
if(!f1.isDirectory())
{
System.out.println(
"\nNot directory: " + szExtractPath);
}
ZipFile zf;
Vector zipEntries = new Vector();
try
{
zf = new ZipFile(szZipFilePath);
Enumeration en = zf.entries();
while(en.hasMoreElements())
{
zipEntries.addElement(
(ZipEntry)en.nextElement());
}
int sizetemp = 1;
double oldpercentTotal = 0.0;
double currFilePercent = 0.0;
for (i = 0; i < zipEntries.size(); i++)
{
ZipEntry ze =
(ZipEntry)zipEntries.elementAt(i);
sizetemp +=ze.getCompressedSize();
try{
currFilePercent = ((sizetemp /1024) *100/fileSize)/100;
progressCurr.setProgress(currFilePercent);
//progressCurr.setString("Извлечение "+ZipName + " "+progressCurr.getValue()+"%");
CurentTotalProgress += ( ((sizetemp/1024)*100/totalsize)-oldpercentTotal )/100 ;
progressBarTotal.setProgress(CurentTotalProgress);
oldpercentTotal = ((sizetemp/1024)*100/totalsize);
}catch(ArithmeticException ae){
}
extractFromZip(szZipFilePath, szExtractPath,
ze.getName(), zf, ze);
}
zf.close();
//System.out.println("Done!");
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
f.delete();
} |
62d4684a-d5c2-462c-8a45-ee6d245fe0d0 | 5 | private CalcState testPoints(CalcState state, Point p2, Point p3) {
double bestDist = state.bestDist;
Triangle bestTriangle = null;
int[] rgba = new int[4];
for (int r = 0; r <= conf.colorSteps; r++) {
rgba[0] = expandColor(r);
for (int g = 0; g <= conf.colorSteps; g++) {
rgba[1] = expandColor(g);
for (int b = 0; b <= conf.colorSteps; b++) {
rgba[2] = expandColor(b);
for (int a = 0; a <= conf.alphaSteps; a++) {
//trianglesTested++;
rgba[3] = expandColor(a);
Triangle t = new Triangle(rgba, state.p1, p2, p3);
Picture tmpPic = new Picture(state.p.getData(), state.p.getWidth(), state.p.getHeight());
Square dirty = dirty(state.p1, p2, p3);
double dirtyDistanceBefore = state.p.distance(conf.pic, dirty);
tmpPic.addTriangle(t);
double dirtyDistanceAfter = tmpPic.distance(conf.pic, dirty);
double distance = state.pDist - (dirtyDistanceBefore - dirtyDistanceAfter);
if (distance < bestDist) {
bestTriangle = new Triangle(rgba.clone(), state.p1, p2, p3);
bestDist = distance;
}
}
}
}
}
return new CalcState(state.p, state.pDist, state.triangleNumber, state.point1, state.p1, bestDist, bestTriangle);
} |
980cb388-d2e8-4e7f-a05b-f1cc75a8909d | 6 | public List<Contestant> getActiveContestants(boolean active) {
List<Contestant> list = new ArrayList<Contestant>(
allContestants.size());
for (Contestant c : allContestants) {
if (c != null) {
if (active && !c.isCastOff()) {
list.add(c);
} else if (!active && c.isCastOff()) {
list.add(c);
}
}
}
return list;
} |
9d76ec37-c3fe-4ff9-b24a-88289681a4c4 | 6 | public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
} |
b7ca18d1-0920-49ef-867e-c730a73ecdd7 | 2 | public int map_pf_move(Coord real_coord) {
if (path != null) {
path.clear();
path_moving = false;
path_step = 0;
path_interact_object = null;
}
path = APXUtils._pf_find_path(real_coord, 0);
update_pf_moving();
return path == null ? -1 : path.size();
} |
a88f9ac8-8e03-47ad-9077-93486fa3eea4 | 6 | public static FileOutputStream createOutputStream(File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (!file.canWrite()) {
throw new IOException("File '" + file + "' exists but cannot be written to");
}
} else {
File parent = file.getParentFile();
if (parent != null && !parent.exists()) {
if (!parent.mkdirs()) {
throw new IOException("File '" + file + "' could not be created");
}
}
}
return new FileOutputStream(file);
} |
90eba4d7-cd84-42b3-ac12-5e45162f6483 | 0 | @Basic
@Column(name = "supplier_id")
public Integer getSupplierId() {
return supplierId;
} |
425f2ca7-0f19-4869-a376-91d54e50ad21 | 6 | private void setStartPoint( Calendar t, int unit, long exactStart )
{
t.setTimeInMillis( exactStart );
t.setFirstDayOfWeek( firstDayOfWeek );
for (int i = 0; i < HOUR && i <= unit; i++)
t.set( calendarUnit[i], 0 );
if ( unit >= HOUR )
t.set( Calendar.HOUR_OF_DAY, 0 );
if ( unit == WEEK )
t.set( Calendar.DAY_OF_WEEK, t.getFirstDayOfWeek() );
else if ( unit == MONTH )
t.set( Calendar.DAY_OF_MONTH, 1 );
else if ( unit == YEAR )
{
t.set( Calendar.DATE, 1 );
t.set( Calendar.MONTH, 0 );
}
} |
76678c63-b4a7-4a67-8586-3d94543d2bd6 | 1 | public void printPatients() {
System.out.println("Patient: " + name + ", age: " + age + ", illness: " + illness);
if (nextPatient != null) {
nextPatient.printPatients();
}
} |
512cbf1d-d8bd-44e0-9433-2a8d97c0dbea | 9 | public boolean skipPast(String to) throws JSONException {
boolean b;
char c;
int i;
int j;
int offset = 0;
int length = to.length();
char[] circle = new char[length];
/*
* First fill the circle buffer with as many characters as are in the
* to string. If we reach an early end, bail.
*/
for (i = 0; i < length; i += 1) {
c = next();
if (c == 0) {
return false;
}
circle[i] = c;
}
/*
* We will loop, possibly for all of the remaining characters.
*/
for (;;) {
j = offset;
b = true;
/*
* Compare the circle buffer with the to string.
*/
for (i = 0; i < length; i += 1) {
if (circle[j] != to.charAt(i)) {
b = false;
break;
}
j += 1;
if (j >= length) {
j -= length;
}
}
/*
* If we exit the loop with b intact, then victory is ours.
*/
if (b) {
return true;
}
/*
* Get the next character. If there isn't one, then defeat is ours.
*/
c = next();
if (c == 0) {
return false;
}
/*
* Shove the character in the circle buffer and advance the
* circle offset. The offset is mod n.
*/
circle[offset] = c;
offset += 1;
if (offset >= length) {
offset -= length;
}
}
} |
8935317d-b9d6-4c5b-ba25-1666bd2c63ff | 1 | public void makeDeclaration(Set done) {
super.makeDeclaration(done);
if (subBlocks[0] instanceof InstructionBlock)
/*
* An instruction block may declare a variable for us.
*/
((InstructionBlock) subBlocks[0]).checkDeclaration(this.declare);
} |
3635ab1a-ef31-41a7-86c3-cde99abc8a5a | 3 | private static void test_toggle(TestCase t) {
// Print the name of the function to the log
pw.printf("\nTesting %s:\n", t.name);
// Run each test for this test case
int score = 0;
for (int i = 0; i < t.tests.length; i += 3) {
int bits = (Integer) t.tests[i];
int exp = (Integer) t.tests[i + 1];
int arg1 = (Integer) t.tests[i + 2];
try {
field.setInt(vec, bits);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
vec.toggle(arg1);
int res = vec.getBits();
boolean cor = exp == res;
if (cor) {
++score;
}
pw.printf(
"%s(%2d): Bits: %8X Expected: %8X Result: %8X Correct: %5b\n",
t.name, arg1, bits, exp, res, cor);
pw.flush();
}
// Set the score for this test case
t.score = (double) score / (t.tests.length / 3);
} |
d1af9695-5b8a-4575-9eba-69d4ab887efa | 2 | public void deposit(BigInteger amount) throws IllegalArgumentException {
if ( (amount == null) || (amount.compareTo(BigInteger.ZERO) < 0) )
throw new IllegalArgumentException();
setBalance(this.getBalance().add(amount));
} |
24a0bb04-5e42-41c9-b12e-6b54ca53e94f | 6 | public boolean unload100OldestChunks()
{
int var1;
for (var1 = 0; var1 < 100; ++var1)
{
if (!this.droppedChunksSet.isEmpty())
{
Long var2 = (Long)this.droppedChunksSet.iterator().next();
Chunk var3 = (Chunk)this.chunkMap.getValueByKey(var2.longValue());
var3.onChunkUnload();
this.saveChunkData(var3);
this.saveChunkExtraData(var3);
this.droppedChunksSet.remove(var2);
this.chunkMap.remove(var2.longValue());
this.chunkList.remove(var3);
}
}
for (var1 = 0; var1 < 10; ++var1)
{
if (this.field_35392_h >= this.chunkList.size())
{
this.field_35392_h = 0;
break;
}
Chunk var4 = (Chunk)this.chunkList.get(this.field_35392_h++);
EntityPlayer var5 = this.worldObj.func_48456_a((double)(var4.xPosition << 4) + 8.0D, (double)(var4.zPosition << 4) + 8.0D, 288.0D);
if (var5 == null)
{
this.dropChunk(var4.xPosition, var4.zPosition);
}
}
if (this.chunkLoader != null)
{
this.chunkLoader.chunkTick();
}
return this.chunkProvider.unload100OldestChunks();
} |
33abd859-5271-4e5c-b9ed-8c7c16dd162e | 8 | @SuppressWarnings("unchecked") // FIXME in Java7
public BuildQueuePanel(FreeColClient freeColClient, GUI gui, Colony colony) {
super(freeColClient, gui, new MigLayout("wrap 3", "[260:][390:, fill][260:]", "[][][300:400:][]"));
this.colony = colony;
this.unitCount = colony.getUnitCount();
featureContainer = new FeatureContainer();
for (UnitType unitType : getSpecification().getUnitTypeList()) {
if (!(unitType.getGoodsRequired().isEmpty()
|| unitType.hasAbility(Ability.BORN_IN_COLONY))) {
// can be built
buildableUnits.add(unitType);
}
}
DefaultListModel current = new DefaultListModel();
for (BuildableType type : colony.getBuildQueue()) {
current.addElement(type);
FeatureContainer.addFeatures(featureContainer, type);
}
cellRenderer = getCellRenderer();
// remove previous listeners
for (ItemListener listener : compact.getItemListeners()) {
compact.removeItemListener(listener);
}
compact.setText(Messages.message("colonyPanel.compactView"));
compact.addItemListener(this);
// remove previous listeners
for (ItemListener listener : showAll.getItemListeners()) {
showAll.removeItemListener(listener);
}
showAll.setText(Messages.message("colonyPanel.showAll"));
showAll.addItemListener(this);
buildQueueList = new JList(current);
buildQueueList.setTransferHandler(buildQueueHandler);
buildQueueList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
buildQueueList.setDragEnabled(true);
buildQueueList.setCellRenderer(cellRenderer);
buildQueueList.addMouseListener(new BuildQueueMouseAdapter(false));
Action deleteAction = new AbstractAction() {
@SuppressWarnings("deprecation") // FIXME in Java7
public void actionPerformed(ActionEvent e) {
for (Object type : buildQueueList.getSelectedValues()) {
removeBuildable(type);
}
updateAllLists();
}
};
buildQueueList.getInputMap().put(KeyStroke.getKeyStroke("DELETE"), "delete");
buildQueueList.getActionMap().put("delete", deleteAction);
Action addAction = new AbstractAction() {
@SuppressWarnings("deprecation") // FIXME in Java7
public void actionPerformed(ActionEvent e) {
DefaultListModel model = (DefaultListModel) buildQueueList.getModel();
for (Object type : ((JList) e.getSource()).getSelectedValues()) {
model.addElement(type);
}
updateAllLists();
}
};
BuildQueueMouseAdapter adapter = new BuildQueueMouseAdapter(true);
DefaultListModel units = new DefaultListModel();
unitList = new JList(units);
unitList.setTransferHandler(buildQueueHandler);
unitList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
unitList.setDragEnabled(true);
unitList.setCellRenderer(cellRenderer);
unitList.addMouseListener(adapter);
unitList.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "add");
unitList.getActionMap().put("add", addAction);
DefaultListModel buildings = new DefaultListModel();
buildingList = new JList(buildings);
buildingList.setTransferHandler(buildQueueHandler);
buildingList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
buildingList.setDragEnabled(true);
buildingList.setCellRenderer(cellRenderer);
buildingList.addMouseListener(adapter);
buildingList.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "add");
buildingList.getActionMap().put("add", addAction);
JLabel headLine = new JLabel(Messages.message("colonyPanel.buildQueue"));
headLine.setFont(bigHeaderFont);
buyBuilding = new JButton(Messages.message("colonyPanel.buyBuilding"));
buyBuilding.setActionCommand(BUY);
buyBuilding.addActionListener(this);
constructionPanel = new ConstructionPanel(gui, colony, false);
constructionPanel.setOpaque(false);
StringTemplate buildingNothing = StringTemplate.template("colonyPanel.currentlyBuilding")
.add("%buildable%", "nothing");
constructionPanel.setDefaultLabel(buildingNothing);
updateAllLists();
add(headLine, "span 3, align center, wrap 40");
add(new JLabel(Messages.message("colonyPanel.units")), "align center");
add(new JLabel(Messages.message("colonyPanel.buildQueue")), "align center");
add(new JLabel(Messages.message("colonyPanel.buildings")), "align center");
add(new JScrollPane(unitList), "grow");
add(constructionPanel, "split 2, flowy");
add(new JScrollPane(buildQueueList), "grow");
add(new JScrollPane(buildingList), "grow, wrap 20");
add(buyBuilding, "span, split 4");
add(compact);
add(showAll);
add(okButton, "tag ok");
} |
046e649d-6cc8-4796-b129-01028420d559 | 9 | public long toLong() {
switch (this) {
case _0:
return 0L;
case _1:
return 1L;
case _2:
return 2L;
case _3:
return 3L;
case _4:
return 4L;
case _5:
return 5L;
case _6:
return 6L;
case _7:
return 7L;
case _8:
return 8L;
default:
return 9L;
}
} |
6b35e982-4440-47dc-a53b-205e38de74c8 | 7 | private void initCloseCode() throws InvalidFrameException {
code = CloseFrame.NOCODE;
ByteBuffer payload = super.getPayloadData();
payload.mark();
if( payload.remaining() >= 2 ) {
ByteBuffer bb = ByteBuffer.allocate( 4 );
bb.position( 2 );
bb.putShort( payload.getShort() );
bb.position( 0 );
code = bb.getInt();
if( code == CloseFrame.ABNORMAL_CLOSE || code == CloseFrame.TLS_ERROR || code == CloseFrame.NOCODE || code > 4999 || code < 1000 || code == 1004 ) {
throw new InvalidFrameException( "closecode must not be sent over the wire: " + code );
}
}
payload.reset();
} |
222f11b5-6bd0-4982-ae57-25d70ed1d422 | 2 | @Override
public void registerTrigger(ITrigger<?> trigger) {
if (!wrapper.triggers.contains(trigger))
wrapper.triggers.add(trigger);
} |
ab568be4-169a-4a45-8f28-783f6aba61af | 4 | public ImageList getImages(String asImageType, boolean abEncodedData, int aiMaxSize,
String asLastModified) {
Map<String, String> lhtParameters = new HashMap<String, String>();
if (UtilityMethods.isValidString(asLastModified)) {
lhtParameters.put(PARAM_LAST_MODIFIED, encode(asLastModified));
}
// I like to only include it if it is > 0
if (aiMaxSize > 0) {
lhtParameters.put(PARAM_MAX_SIZE, String.valueOf(aiMaxSize));
}
// I like to only include it if it needs to be true
if (abEncodedData) {
lhtParameters.put(PARAM_ENCODED_DATA, String.valueOf(abEncodedData));
}
return get(ImageList.class,
REST_URL_IMAGES
+ (UtilityMethods.isValidString(asImageType) ? "/"
+ encode(asImageType) : ""), lhtParameters);
} |
1006b202-0f90-4bc4-a402-067e41ffc6da | 5 | public static ArrayList<String> getAllXlsFilesFromFolder(String path) {
ArrayList<String> filesList = new ArrayList<String>();
String files;
File folder = null;
try{
folder = new File(path);
}catch(Exception e){
e.printStackTrace();
}
if(folder.listFiles() != null){
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
if (files.endsWith(".xls")){// || files.endsWith(".XLS")) {
filesList.add(path+files);
}
}
}
return filesList;
} else
return null;
} |
07a4d85e-f390-4b52-a1e6-d724a80315d4 | 6 | @EventHandler
public void SnowmanNightVision(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.getsnowgolemConfig().getDouble("Snowman.NightVision.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if ( plugin.getsnowgolemConfig().getBoolean("Snowman.NightVision.Enabled", true) && damager instanceof Snowman && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, plugin.getsnowgolemConfig().getInt("Snowman.NightVision.Time"), plugin.getsnowgolemConfig().getInt("Snowman.NightVision.Power")));
}
} |
2a15e612-55c4-4e2f-b035-4a68da750904 | 1 | public String getString(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof String) {
return (String) object;
}
throw new JSONException("JSONObject[" + quote(key) + "] not a string.");
} |
23278600-9810-4c81-880e-9b01d782678f | 8 | public static Vektor3D determineSpeedVW(Sprite sp)
{
Vektor3D vekt = new Vektor3D();
if(sp.getDirection() == Consts.NORTH)
{
vekt.setX(sp.getSpeedInitWalk()/Math.sqrt(2));
vekt.setY(sp.getSpeedInitWalk()/Math.sqrt(2));
}
else if(sp.getDirection() == Consts.EAST)
{
vekt.setX(-sp.getSpeedInitWalk()/Math.sqrt(2));
vekt.setY(sp.getSpeedInitWalk()/Math.sqrt(2));
}
else if(sp.getDirection() == Consts.SOUTH)
{
vekt.setX(-sp.getSpeedInitWalk()/Math.sqrt(2));
vekt.setY(-sp.getSpeedInitWalk()/Math.sqrt(2));
}
else if(sp.getDirection() == Consts.WEST)
{
vekt.setX(sp.getSpeedInitWalk()/Math.sqrt(2));
vekt.setY(-sp.getSpeedInitWalk()/Math.sqrt(2));
}
else if(sp.getDirection() == Consts.NORTHWEST)
{
vekt.setX(sp.getSpeedInitWalk());
vekt.setY(0);
}
else if(sp.getDirection() == Consts.NORTHEAST)
{
vekt.setX(0);
vekt.setY(sp.getSpeedInitWalk());
}
else if(sp.getDirection() == Consts.SOUTHEAST)
{
vekt.setX(-sp.getSpeedInitWalk());
vekt.setY(0);
}
else if(sp.getDirection() == Consts.SOUTHWEST)
{
vekt.setX(0);
vekt.setY(-sp.getSpeedInitWalk());
}
return vekt;
} |
105c94ec-f30f-4097-923d-24b12063dcb8 | 3 | public ArrayList<ArrayList<String>> translate(ArrayList<ArrayList<String>> sentenceBundle) {
ArrayList<String> charIdentifier = sentenceBundle.get(1);
for (int i = 0; i < charIdentifier.size(); i++) {
for (int j = 0; j < key.length; j++) {
if (charIdentifier.get(i).equals(key[j][0])) {
charIdentifier.set(i, key[j][1]);
}
}
}
return this.passVar(sentenceBundle.get(0), charIdentifier);
} |
1016161a-2468-4069-844b-66291ddbf6e2 | 8 | public void close() {
try {
if( m_ClientOutput != null ) {
m_ClientOutput.flush();
m_ClientOutput.close();
}
}
catch( IOException e ) {
}
try {
if( m_ServerOutput != null ) {
m_ServerOutput.flush();
m_ServerOutput.close();
}
}
catch( IOException e ) {
}
try {
if( m_ClientSocket != null ) {
m_ClientSocket.close();
}
}
catch( IOException e ) {
}
try {
if( m_ServerSocket != null ) {
m_ServerSocket.close();
}
}
catch( IOException e ) {
}
m_ServerSocket = null;
m_ClientSocket = null;
DebugLog.getInstance().println( "Proxy Closed." );
} |
aa286b53-b49d-4741-83ac-dedfdc4509aa | 4 | public double computeSimilarity(int user1, int user2) {
double sim = 0;
// generate arrays containing ratings from users which rated both movies
List<Integer> sharedMovies = findSharedMovies(user1, user2);
if (sharedMovies.isEmpty()) {
return sim;
}
Double[] userOneRatings = new Double[sharedMovies.size()];
Double[] userTwoRatings = new Double[sharedMovies.size()];
for (int i = 0; i < sharedMovies.size(); i++) {
userOneRatings[i] = userMovieRatings.get(user1).get(sharedMovies.get(i));
userTwoRatings[i] = userMovieRatings.get(user2).get(sharedMovies.get(i));
}
// Calculate the similarity using the defined metric
if (sMetric.toLowerCase().equals("cosinesimilarity")) {
sim = Similarity.calculateCosineSimilarity(userOneRatings, userTwoRatings);
} else if (sMetric.toLowerCase().equals("pearsoncorrelation")) {
sim = Similarity.calculatePearsonCorrelation(userOneRatings, userTwoRatings, averageRatings.get(user1),
averageRatings.get(user2));
}
return sim;
} |
0ffdc882-e654-427d-8d96-9406151d03c7 | 8 | public static DataPersister lookupForField(Field field) {
// see if the any of the registered persisters are valid first
if (registeredPersisters != null) {
for (DataPersister persister : registeredPersisters) {
if (persister.isValidForField(field)) {
return persister;
}
// check the classes instead
for (Class<?> clazz : persister.getAssociatedClasses()) {
if (field.getType() == clazz) {
return persister;
}
}
}
}
// look it up in our built-in map by class
DataPersister dataPersister = builtInMap.get(field.getType().getName());
if (dataPersister != null) {
return dataPersister;
}
/*
* Special case for enum types. We can't put this in the registered persisters because we want people to be able
* to override it.
*/
if (field.getType().isEnum()) {
return DEFAULT_ENUM_PERSISTER;
} else {
/*
* Serializable classes return null here because we don't want them to be automatically configured for
* forwards compatibility with future field types that happen to be Serializable.
*/
return null;
}
} |
0e7b86e4-8ea5-4873-b148-27a766bd761d | 1 | public List<EncryptionPropertyType> getEncryptionProperty() {
if (encryptionProperty == null) {
encryptionProperty = new ArrayList<EncryptionPropertyType>();
}
return this.encryptionProperty;
} |
06375d22-6813-4897-940f-dfd1a127111b | 9 | public PropertiesWindow(Shell parent) {
shell = new Shell(parent, SWT.BORDER | SWT.TITLE);
shell.setFont(Main.appFont);
shell.setSize(186, 235);
shell.setLocation(parent.getLocation().x + 100, parent.getLocation().y + 100);
shell.setLayout(new GridLayout(2, false));
lblRoomId = new Label(shell, SWT.NONE);
lblRoomId.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
lblRoomId.setText("Room ID:");
lblRoomId.setToolTipText("The room's number.\nRoom with a lower ID is on higher layer than a room with higher ID.");
lblRoomId.setFont(Main.appFont);
spId = new Spinner(shell, SWT.BORDER);
spId.setMaximum(999);
spId.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, true, 1, 1));
spId.setFont(Main.appFont);
lblLevel = new Label(shell, SWT.NONE);
lblLevel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
lblLevel.setFont(Main.appFont);
lblLevel.setText("Level:");
spLevel = new Spinner(shell, SWT.BORDER | SWT.CENTER);
spLevel.setMinimum(1);
spLevel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, true, 1, 1));
spLevel.setFont(Main.appFont);
spLevel.setTextLimit(2);
scaleLevel = new Scale(shell, SWT.NONE);
scaleLevel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 5, 2));
scaleLevel.setFont(Main.appFont);
scaleLevel.setPageIncrement(1);
scaleLevel.setMinimum(1);
scaleLevel.setMaximum(8);
lblPower = new Label(shell, SWT.NONE);
lblPower.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
lblPower.setFont(Main.appFont);
lblPower.setText("Power");
spPower = new Spinner(shell, SWT.BORDER | SWT.CENTER);
spPower.setMinimum(1);
spPower.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, true, 1, 1));
spPower.setFont(Main.appFont);
spPower.setTextLimit(2);
scalePower = new Scale(shell, SWT.NONE);
scalePower.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 2));
scalePower.setFont(Main.appFont);
scalePower.setPageIncrement(1);
scalePower.setMaximum(8);
btnAvailable = new Button(shell, SWT.CHECK);
GridData gd_btnAvailable = new GridData(SWT.LEFT, SWT.CENTER, true, true, 3, 1);
gd_btnAvailable.horizontalIndent = 5;
btnAvailable.setLayoutData(gd_btnAvailable);
btnAvailable.setFont(Main.appFont);
btnAvailable.setToolTipText("When set to true, this system will be available and installed at the beggining of the game.\n"
+ "When set to false, the system will have to be bought at a store to unlock it.\n"
+ "Systems that have not been placed on the ship will not be functional, even after buying.");
btnAvailable.setText("Available At Start");
composite = new Composite(shell, SWT.NONE);
composite.setLayout(new GridLayout(2, true));
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 5, 1));
btnOk = new Button(composite, SWT.NONE);
btnOk.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
btnOk.setFont(Main.appFont);
btnOk.setText("OK");
Button btnCancel = new Button(composite, SWT.NONE);
btnCancel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
btnCancel.setFont(Main.appFont);
btnCancel.setText("Cancel");
shell.pack();
spLevel.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
scaleLevel.setSelection(spLevel.getSelection());
}
});
spPower.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
scalePower.setSelection(spPower.getSelection());
if (!Main.ship.isPlayer) {
scaleLevel.setMaximum(scalePower.getSelection());
spLevel.setMaximum(scalePower.getSelection());
}
}
});
btnCancel.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
shell.setVisible(false);
}
});
btnOk.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
int newId = spId.getSelection();
int oldId = currentRoom.id;
if (newId != oldId) {
FTLRoom other = Main.ship.getRoomWithId(newId);
Main.ship.rooms.remove(currentRoom);
if (other != null) {
Main.ship.rooms.remove(other);
other.id = oldId;
}
currentRoom.id = newId;
Main.ship.rooms.add(currentRoom);
if (other != null)
Main.ship.rooms.add(other);
}
if (!currentRoom.getSystem().equals(Systems.EMPTY)) {
if (Main.ship.isPlayer) {
Main.ship.levelMap.put(sys, Integer.valueOf(spLevel.getText()));
} else {
Main.ship.levelMap.put(sys, Integer.valueOf(spPower.getText()));
int i = Integer.valueOf(spLevel.getText());
Main.ship.powerMap.put(sys, ((i <= Integer.valueOf(spPower.getText()) ? i : Integer.valueOf(spPower.getText()))));
}
Main.ship.startMap.put(sys, btnAvailable.getSelection());
Main.systemsMap.get(sys).setAvailable(btnAvailable.getSelection());
currentRoom.updateColor();
Main.canvasRedraw(currentRoom.getBounds(), true);
}
shell.setVisible(false);
}
});
scaleLevel.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
spLevel.setSelection(scaleLevel.getSelection());
}
});
scalePower.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
spPower.setSelection(scalePower.getSelection());
if (!Main.ship.isPlayer) {
scaleLevel.setMaximum(scalePower.getSelection());
spLevel.setMaximum(scalePower.getSelection());
}
}
});
shell.addListener(SWT.Traverse, new Listener() {
@Override
public void handleEvent(Event e) {
if (e.detail == SWT.TRAVERSE_ESCAPE) {
e.doit = false;
shell.setVisible(false);
}
}
});
} |
4ef84aef-bdbb-4f3f-ade7-dfbca19237b6 | 6 | private static boolean b1(int i, int j, BufferedImage image) {
Boolean above = ((image.getRGB(i-1, j+1) == BLACK) ||
(image.getRGB(i , j+1) == BLACK) ||
(image.getRGB(i+1, j+1) == BLACK));
Boolean with = ((image.getRGB(i-1, j-1) == WHITE) &&
(image.getRGB(i , j-1) == BLACK) &&
(image.getRGB(i , j ) == BLACK) &&
(image.getRGB(i+1, j ) == WHITE));
return ( above && with );
} |
eca3bfca-8cd2-41db-b110-a001ac6b0317 | 5 | public static boolean authenticateManager(String inName, String inPassword) {
Connection c = null;
Statement stmt = null;
boolean authenticated = false;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:Restuarant.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM USERS;");
while (rs.next()) {
String name = rs.getString("name");
String job = rs.getString("job");
String password = rs.getString("password");
if (name.equals(inName) && job.equals("Manager")
&& password.equals(inPassword)) {
authenticated = true;
rs.close();
stmt.close();
c.close();
System.out.println("Database closed.");
}
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
return authenticated;
} |
59c385cf-b019-4aa4-bfd6-dd1f02c5738a | 4 | public static boolean validID(int ID) {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(System.getProperty("resources") + "/database/spells"));
String line;
while((line = reader.readLine()) != null) {
String[] temp = line.split(";");
if(Integer.parseInt(temp[0]) == ID) {
return true;
}
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("The spell database has been misplaced!");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Spell database failed to load!");
e.printStackTrace();
}
return false;
} |
23569603-3796-4d4d-b29f-b6b1e85954e0 | 7 | private void merge(int[] array, int startIndex, int splitIndex, int endIndex){
int[] tmpArray = new int[endIndex - startIndex + 1]; //new temporary array for storing merged elements
int tmpIndex = 0; //index to iterate over temporary array
int i=startIndex, j=splitIndex+1;
while(i<=splitIndex || j<=endIndex){ //while there are any items in the array part
if(i <= splitIndex && j<=endIndex){ //of there are items in both left and right parts
if(array[i] < array[j]){ //if left part is smaller
tmpArray[tmpIndex++] = array[i++];
}
else{ //if right part is smaller
tmpArray[tmpIndex++] = array[j++];
}
}
else if(i <= splitIndex){ //if there are items only in left part
tmpArray[tmpIndex++] = array[i++];
}
else{ //if there are items only in right part
tmpArray[tmpIndex++] = array[j++];
}
}
//copy the merged items from temporary array to the main array
for(i=startIndex, tmpIndex=0; tmpIndex<tmpArray.length; i++, tmpIndex++){
array[i] = tmpArray[tmpIndex];
}
tmpArray = null;
} |
0b5f4408-6214-4bd7-adb9-f8a0720da318 | 5 | public static void main(String[] args) throws IOException {
Scanner seuss;
// Step 0:
// seuss = new Scanner(CLASSIC).useDelimiter("[^A-Za-z]+");
// System.out.println(findUniqueWords(seuss).size()); // how many words did Dr Seuss use?
// seuss.close();
// Step 1:
// seuss = new Scanner(CLASSIC).useDelimiter("[^A-Za-z]+");
// Map<String, Integer> counts = countWords(seuss);
// System.out.println(counts); // how often did he use each word?
// seuss.close();
// Step 2:
// Map<Integer, List<String>> reverseCounts = reverseMap(counts);
// System.out.println(reverseCounts); // how often did he use each word?
// Step 3:
// printMap(reverseCounts);
// Step 4:
Scanner dickens1 = scannerForWebPage("http://www.gutenberg.org/ebooks/98.txt.utf-8").useDelimiter("[^a-zA-Z]+");
Scanner dickens2 = scannerForWebPage("http://www.gutenberg.org/ebooks/1400.txt.utf-8").useDelimiter("[^a-zA-Z]+");
Scanner austen1 = scannerForWebPage("http://www.gutenberg.org/ebooks/1342.txt.utf-8").useDelimiter("[^a-zA-Z]+");
Scanner austen2 = scannerForWebPage("http://www.gutenberg.org/ebooks/158.txt.utf-8").useDelimiter("[^a-zA-Z]+");
Map<String,Integer> d1 = countWords(dickens1);
Map<String,Integer> d2 = countWords(dickens2);
Map<String,Integer> a1 = countWords(austen1);
Map<String,Integer> a2 = countWords(austen2);
dickens1.close();
dickens2.close();
austen1.close();
austen2.close();
double[][] diffs = {
{
wordDifference(d1,d1),
wordDifference(d1,d2),
wordDifference(d1,a1),
wordDifference(d1,a2)
},
{
wordDifference(d2,d1),
wordDifference(d2,d2),
wordDifference(d2,a1),
wordDifference(d2,a2)
},
{
wordDifference(a1,d1),
wordDifference(a1,d2),
wordDifference(a1,a1),
wordDifference(a1,a2)
},
{
wordDifference(a2,d1),
wordDifference(a2,d2),
wordDifference(a2,a1),
wordDifference(a2,a2)
}
};
System.out.println(" \tDickens1\tDickens2\tAusten1 \tAusten2 ");
for(int i=0; i<4; ++i) {
if (i == 0) System.out.print("Dickens1\t");
else if (i == 1) System.out.print("Dickens2\t");
else if (i == 2) System.out.print("Austen1 \t");
else System.out.print("Austen2 \t");
for(int j=0; j<4; ++j) {
System.out.printf("%.6f\t", diffs[i][j]);
}
System.out.println();
}
// */
} |
e6f58cc1-f503-4ac9-8e45-d64b972c65cc | 0 | public void SetFirstTicks(int firstTicks)
{
//set the tick time the person got to the stop for the bus
this.firstTicks = firstTicks;
} |
15aff1c5-f1c9-4804-9f83-b616a5cd2271 | 2 | private void addProgram(String text, int type)
{
int shader = glCreateShader(type);
if(shader == 0)
{
System.err.println("Shader creation failed: Could not find valid memory location when adding shader");
System.exit(1);
}
glShaderSource(shader, text);
glCompileShader(shader);
if(glGetShader(shader, GL_COMPILE_STATUS) == 0)
{
System.err.println(glGetShaderInfoLog(shader, 1024));
System.exit(1);
}
glAttachShader(program, shader);
} |
efba70fd-d1d7-4787-924d-96dd468ece06 | 7 | public static void makeCompactGrid(Container parent, int rows, int cols, int initialX, int initialY, int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout) parent.getLayout();
} catch (ClassCastException exc) {
System.err.println("The first argument to makeCompactGrid must use SpringLayout.");
return;
}
// Align all cells in each column and make them the same width.
Spring x = Spring.constant(initialX);
for (int c = 0; c < cols; c++) {
Spring width = Spring.constant(0);
for (int r = 0; r < rows; r++) {
width = Spring.max(width, getConstraintsForCell(r, c, parent, cols).getWidth());
}
for (int r = 0; r < rows; r++) {
SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols);
constraints.setX(x);
constraints.setWidth(width);
}
x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
}
// Align all cells in each row and make them the same height.
Spring y = Spring.constant(initialY);
for (int r = 0; r < rows; r++) {
Spring height = Spring.constant(0);
for (int c = 0; c < cols; c++) {
height = Spring.max(height, getConstraintsForCell(r, c, parent, cols).getHeight());
}
for (int c = 0; c < cols; c++) {
SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols);
constraints.setY(y);
constraints.setHeight(height);
}
y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
}
// Set the parent's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH, y);
pCons.setConstraint(SpringLayout.EAST, x);
} |
fd33691d-a6e9-4f70-9c39-47a2e3080cdc | 4 | @Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(backgroundColor);
g2d.fillRect(0, 0, this.getBounds().width + 1, this.getBounds().height + 1);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
if (readImage != null) {
g2d.drawImage(readImage, startXDrawingPoint, startYDrawingPoint, drawingImageWidth, drawingImageHeigh, this);
}
if (firstPageReached || lastPageReached) {
Font font = new Font(g2d.getFont().getName(), Font.BOLD, 15);
FontRenderContext frc = new FontRenderContext(null, false, false);
g2d.setFont(font);
String text;
if (firstPageReached) {
text = java.util.ResourceBundle.getBundle("booknaviger/resources/ReadComponent").getString("firstPage.text");
} else {
text = java.util.ResourceBundle.getBundle("booknaviger/resources/ReadComponent").getString("lastPage.text");
}
int fontWidth = (int) font.getStringBounds(text, frc).getWidth();
g2d.setColor(Color.BLACK);
g2d.fillRect(5, 5, fontWidth + 10, 20);
g2d.fillRect(this.getWidth() - fontWidth - 15, 5, fontWidth + 10, 20);
g2d.fillRect(5, this.getHeight() - 25, fontWidth + 10, 20);
g2d.fillRect(this.getWidth() - fontWidth - 15, this.getHeight() - 25, fontWidth + 10, 20);
g2d.setColor(Color.YELLOW);
g2d.drawString(text, 10, 20);
g2d.drawString(text, this.getWidth() - fontWidth - 10, 20);
g2d.drawString(text, 10, this.getHeight() - 10);
g2d.drawString(text, this.getWidth() - fontWidth - 10, this.getHeight() - 10);
}
g2d.dispose();
} |
42749ac5-0ebc-4e65-9822-5b6c6028c6b6 | 5 | private Object decodeAMF0() throws NotImplementedException, EncodingException
{
int type = readByte();
switch (type)
{
case 0x00:
return readIntAMF0();
case 0x02:
return readStringAMF0();
case 0x03:
return readObjectAMF0();
case 0x05:
return null;
case 0x11: // AMF3
return decode();
}
throw new NotImplementedException("AMF0 type not supported: " + type);
} |
18ac4b32-8b32-4d80-93aa-d03c44886bd3 | 4 | @SuppressWarnings("unchecked")
@Override
public void validate(ProcessingEnvironment procEnv,
RoundEnvironment roundEnv, TypeElement annotationType,
AnnotationMirror annotation, Element e) {
AnnotationMirror steretypeAnnotation = AnnotationProcessingUtils
.findAnnotationMirror(procEnv, e,
"javax.enterprise.inject.Stereotype");
if (!(e instanceof ExecutableElement) && steretypeAnnotation == null) {
procEnv.getMessager()
.printMessage(
Diagnostic.Kind.ERROR,
"Non executable element '"
+ e.getSimpleName()
+ "' has been annotated with the constrainted annotation '"
+ annotationType.getQualifiedName()
+ "' that expects executable element", e,
annotation);
return;
}
if (steretypeAnnotation != null) {
// Iterate over all elements that are annotated with the stereotype
// annotation
// and call this method recursivly to also support arbitrary depth
// of stereotyping
for (Element newE : (Set<Element>) roundEnv
.getElementsAnnotatedWith((TypeElement) e)) {
validate(procEnv, roundEnv, annotationType, annotation, newE);
}
} else {
validate(procEnv, roundEnv, annotationType, annotation,
(ExecutableElement) e);
}
} |
e4107e2a-7c21-4672-88ac-50008952e87a | 3 | private static String stackToString(Throwable exception) {
String result = "";
if (exception.getMessage() == null) result = exception.toString();
else result = exception.getMessage() + ": ";
if (exception.getStackTrace() == null) result = result + " <== stacktrace is null";
else {
StackTraceElement[] stackTrace = exception.getStackTrace();
for (int i = 0; i < stackTrace.length; i++) {
result = result +
" <== " + stackTrace[i].getClassName() + "." + stackTrace[i].getMethodName() +
" (" + stackTrace[i].getFileName() + ": " + stackTrace[i].getLineNumber() + ")";
}
}
return result;
} |
b9b31021-63c8-49f2-83ab-a07ef59ce096 | 2 | private void fetchSubscribedCategoryList(HttpSession session) {
StudentBean bean = (StudentBean)session.getAttribute("person");
StudentDao dao=new StudentDao();
HashMap<String, Boolean> categoryMap = new HashMap<String, Boolean>();
List<String> nonSubscribed = dao.fetchCategories(bean.getUserid(), "NotSubscribed");
List<String> subscribed = dao.fetchCategories(bean.getUserid(), "subscribed");
for(String val:nonSubscribed){
categoryMap.put(val, false);
}
for(String val:subscribed){
categoryMap.put(val, true);
}
session.setAttribute("categoryMap", categoryMap);
} |
19677a89-ffac-44c6-b044-1f5b1f5f44f1 | 0 | @Test
public void testBubbleSort(){
bubbleSort.load(array,null,null);
bubbleSort.run();
assertArrayEquals(array, arrayActuals);
} |
9ebbef85-1def-4e14-8fba-cf5433cf908a | 1 | public synchronized void start() {
if (running)
return;
running = true;
game = new Thread(this, "game");
game.start();
} |
8354a58e-3614-4708-9d9d-b2b76c8c3ad0 | 2 | public String getOpenFileFormatNameForExtension(String extension) {
String lowerCaseExtension = extension.toLowerCase();
for (int i = 0, limit = openers.size(); i < limit; i++) {
OpenFileFormat format = (OpenFileFormat) openers.get(i);
if (format.extensionExists(lowerCaseExtension)) {
return (String) openerNames.get(i);
}
}
int index = openers.indexOf(getDefaultOpenFileFormat());
return (String) openerNames.get(index);
} |
87010d8b-ab93-4321-b114-67334adcdc14 | 7 | @Override
public int compareTo(Object o) {
int row1 = modelIndex;
int row2 = ((Row) o).modelIndex;
for (Directive directive : sortingColumns) {
int column = directive.column;
Object o1 = tableModel.getValueAt(row1, column);
Object o2 = tableModel.getValueAt(row2, column);
int comparison;
// Define null less than everything, except null.
if (o1 == null && o2 == null) {
comparison = 0;
} else if (o1 == null) {
comparison = -1;
} else if (o2 == null) {
comparison = 1;
} else {
comparison = getComparator(column).compare(o1, o2);
}
if (comparison != 0) {
return directive.direction == DESCENDING ? -comparison : comparison;
}
}
return 0;
} |
49b2a59b-e0c9-496e-a537-abe8b24ba2c3 | 6 | DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, File dir)
{
String curPath = dir.getPath();
DefaultMutableTreeNode curDir = new DefaultMutableTreeNode(curPath);
if (curTop != null)
{ // should only be null at root
curTop.add(curDir);
}
Vector ol = new Vector();
String[] tmp = dir.list();
for (int i = 0; i < tmp.length; i++)
{
ol.addElement(tmp[i]);
}
Collections.sort(ol, String.CASE_INSENSITIVE_ORDER);
File f;
Vector files = new Vector();
// Make two passes, one for Dirs and one for Files. This is #1.
for (int i = 0; i < ol.size(); i++)
{
String thisObject = (String) ol.elementAt(i);
String newPath;
if (curPath.equals(".")) newPath = thisObject;
else newPath = curPath + File.separator + thisObject;
if ((f = new File(newPath)).isDirectory()) addNodes(curDir, f);
else files.addElement(thisObject);
}
// Pass two: for files.
for (int fnum = 0; fnum < files.size(); fnum++)
{
curDir.add(new DefaultMutableTreeNode(files.elementAt(fnum)));
}
return curDir;
} |
8e973227-f38d-44d2-89f7-305389b11559 | 3 | public static List<Kurssi> getKurssit() {
Connection c = connect();
if (c == null) return null;
try {
List<Kurssi> kurssit = new ArrayList<Kurssi>();
PreparedStatement ps = c.prepareStatement("SELECT * FROM kurssi;");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
kurssit.add(kurssiResultSetista(rs));
}
return kurssit;
} catch (SQLException e) {
return null;
} finally {
closeConnection(c);
}
} |
e81d0c87-59dd-42d9-b53c-422fb8f4b89d | 4 | @Override
public void update(int delta) {
super.update(delta);
if(standAnim != null && moveAnim != null && bumpAnim != null) {
for(int i = 0; i < 4; i++) {
standAnim[i].update(delta);
moveAnim[i].update(delta);
bumpAnim[i].update(delta);
}
}
} |
63fa5aaa-8ff5-4b36-bb5c-a365580b14b4 | 7 | public Automata buildDFA() {
if (states.length > maxStateOfNFA) {
return null;
}
optimaze();
Automata a = createTemplateForDFA();
int maxMask = (1 << states.length);
Queue<Integer> queue = new LinkedList<>();
boolean was[] = new boolean[maxMask];
for (int i = 0; i < maxMask; i++) {
was[i] = false;
}
queue.add(pow[state0.getNumber()]);
was[pow[state0.getNumber()]] = true;
while (!queue.isEmpty()) {
int mask = queue.poll();
State curState = a.states[mask];
for (Character ch : alphavet) {
if (ch == 'e') {
continue;
}
int nextMask = getNextStatesOfMaskByCharacter(mask, ch);
if (nextMask != 0) {
if (!was[nextMask]) {
was[nextMask] = true;
queue.add(nextMask);
}
curState.addNextState(ch, a.states[nextMask]);
}
}
}
a.state0 = a.states[pow[state0.getNumber()]];
a.optimaze();
return a;
} |
8fe33906-cfac-466b-accf-75da8c02a8e2 | 2 | public void RevealRooms(){
for(int i=0; i<grid.length; i++)
for (int j=0; j<grid.length; j++)
visited[i][j] = RoomState.VISITED;
} |
3fc15afb-8750-4583-9cc4-a96c6ec28698 | 4 | public void msgRefreshClientInfoHard(String userId, ArrayList<String> usersId, String turnUserId, String winnerId, String field) {
UserSession userSession = sessionIdToUserSession.get(userId);
if (userSession.isHardRefreshProcessing()) {
utils.resources.Game gameRes = (utils.resources.Game)utils.resources.Resources.getInstance().getResource("data/game.xml");
String tmpl = "refreshHard %d %d " + field + " %s %d";
String id = winnerId != null ? winnerId : turnUserId;
String send = String.format(tmpl, gameRes.getFieldSize(), gameRes.getFieldSize(),
userId, usersId.size());
Integer count = 0;
for (String uId: usersId) {
UserSession uSs = sessionIdToUserSession.get(uId);
send += " " + uSs.getLogin();
send += " " + uId;
send += " " + (count++).toString();
}
send += " " + id + (winnerId != null ? " win" : "");
userSession.setInfoForSend(send);
userSession.setHardRefreshReady();
}
} |
c91d2aae-0ef6-452e-8382-d1a6132e8e55 | 3 | public static void main(String[] args) {
String[] a = {"Color","Apple","Boy"};
List<String> list = Arrays.asList(a);
Collections.sort(list);
System.out.println(list);
Iterator<String> t = list.iterator();
while(t.hasNext()){
System.out.println(t.next());
}
ListIterator<String> lt = list.listIterator();
while(lt.hasNext()){
lt.set(lt.next()+"#");
}
while(lt.hasPrevious()){
System.out.println(lt.previous());
}
} |
b06550bc-8e03-4eac-8ae5-feebbca97342 | 5 | public void uimsg(String msg, Object... args) {
if (msg == "upd") {
this.avagob = (Integer) args[0];
return;
}
if (msg == "ch") {
List<Indir<Resource>> rl = new LinkedList<Indir<Resource>>();
for (Object arg : args)
rl.add(ui.sess.getres((Integer) arg));
if (rl.size() == 0) {
this.myown = null;
none = true;
} else {
if (myown != null)
myown.setlay(rl);
else
myown = new AvaRender(rl);
none = false;
}
return;
}
super.uimsg(msg, args);
} |
d04b38a9-5374-4923-b9c0-4080e27ff307 | 5 | @Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
// TODO Auto-generated method stub
JCas jcas = aJCas;
try {
chunker = (ConfidenceChunker) AbstractExternalizable.readObject(modelFile);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
FSIterator<org.apache.uima.jcas.tcas.Annotation> it = jcas.getAnnotationIndex(sentenceTag.type)
.iterator();
while (it.hasNext()) {
sentenceTag sentenceAnnotator = (sentenceTag) it.next();
String content = sentenceAnnotator.getContent();
char[] temp = content.toCharArray();
Iterator<Chunk> gene_iterator = chunker.nBestChunks(temp, 0, temp.length, MAX);
while (gene_iterator.hasNext()) {
Chunk chunk = gene_iterator.next();
double conf = Math.pow(2.0, chunk.score()); // Probability of the detected gene.
if (conf < 0.66) { // At this time, the number of genes approximates to the number in
// sample.out.
break;
}
int begin = chunk.start();
int end = chunk.end();
String gene = content.substring(begin, end);
begin = begin - countWhiteSpaces(content.substring(0, begin));
end = begin + gene.length() - countWhiteSpaces(gene) - 1;
geneTag annotate_g = new geneTag(jcas);
annotate_g.setBegin(begin);
annotate_g.setEnd(end);
annotate_g.setId(sentenceAnnotator.getId());
annotate_g.setContent(gene);
annotate_g.addToIndexes(jcas);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.