method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
e063ae66-3de4-4580-84c1-c7384250aa61 | 7 | private byte[] readData(FormatConverter converter, InputStream inputStream, LodResource lodResource) throws IOException {
int length = 64;
InputStream convertedInputStream = null;
byte[] data = null;
if (null == converter)
{
convertedInputStream = inputStream;
data = new byte[length];
int total = 0;
while (total < length)
{
int count = convertedInputStream.read(data, total, (length - total));
if (-1 == count) break;
total += count;
}
}
else
{
converter.setSourceInputStreamForNewFormat(inputStream, lodResource);
convertedInputStream = converter.getDestinationInputStreamForOldFormat();
// TODO: recombine the data reading?
data = new byte[length];
int total = 0;
int count = 0;
while (-1 != count)
{
if (total >= data.length)
{
byte[] newData = new byte[data.length * 2];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
count = convertedInputStream.read(data, total, (data.length - total));
if (-1 == count) break;
total += count;
}
if (total != data.length)
{
byte[] newData = new byte[total];
System.arraycopy(data, 0, newData, 0, total);
data = newData;
}
}
return data;
} |
54971cca-b547-4f28-9122-32c1dd0074bd | 4 | @Override
public String getOptionsXML()
{
StringBuffer sb = new StringBuffer();
if( pcBubbleSizeRatio != 100 )
{
sb.append( " BubbleSizeRatio=\"" + pcBubbleSizeRatio + "\"" );
}
if( wBubbleSize != 1 )
{
sb.append( " BubbleSize=\"" + wBubbleSize + "\"" );
}
if( fShowNegBubbles )
{
sb.append( " ShowNeg=\"true\"" );
}
if( fHasShadow )
{
sb.append( " Shadow=\"true\"" );
}
return sb.toString();
} |
a734417f-b420-490a-9428-10d047c6bbbc | 1 | public static void setResolution(PrintRequestAttributeSet set, PrinterResolution resolution) {
if (resolution != null) {
set.add(resolution);
} else {
set.remove(PrinterResolution.class);
}
} |
1d240e90-8d25-443d-b048-9a7ae2f91961 | 8 | public void processMessage(String stream, String message, int attemptNo){
// System.out.println("Message arrived" + stream + ":" + message);
long locked = 0;
String gameid = null;
String gameconf = null;
try{
JSONObject jobj = JSONObject.fromObject(message);
gameid = String.valueOf(jobj.get("gameid"));
String username = (String)jobj.get("username");
String action = (String)jobj.get("action");
if(jobj.get("gameconf") != null){
gameconf = ((JSONObject)jobj.get("gameconf")).toString();
}
String gamescope = (String)jobj.get("scope");
// The following section has to be atomic
if(NLFactory.getPersistance().lock("LK" + gameid)){
String gameJSON = NLFactory.getPersistance().getString(gameid);
NLGameUpdate update = performAction(gameid, gamescope, gameconf, gameJSON, username, action);
if(update != null){
// Increase the event number
update.getGame().bumpEventNo();
String gamestr = serializer.gameToString(update.getGame());
NLFactory.getPersistance().setString(gameid, gamestr);
String updatestr = serializer.updateToString(update);
// Atomicity ends
// System.out.println(gameType + "-out : " + updatestr);
NLFactory.getPub().pub(gameType + "-out", updatestr);
// jedisForPub.publish();
}else{
// System.out.println("Update is null!");
}
}else{
throw(new NLConcurrentModificationException("Could not obtain lock!"));
}
}catch(NLException nlioe){
nlioe.printStackTrace();
if(attemptNo < maxAttempts){
processMessage(stream, message, attemptNo++);
}
System.out.println("******Giving up on update******");
}catch(Exception e){
e.printStackTrace();
}finally{
if(locked == 1 && gameid != null){
NLFactory.getPersistance().delete("LK" + gameid);
}
}
} |
1ab13725-adb3-48a8-b4ae-badc3c4f94a5 | 9 | public boolean checkForRoundCompletion(Player player,List<Player> players) {
if(getTotalActivePlayerInThisRound(players)==1){
return true;
}else if ( isRaiseHappened && player == playerWhoRaisedInthisRound) {
return true;
}else if (!isRaiseHappened && isBetPlaced && player==playerPlacedTheBet){
return true;
}else {
if (!isRaiseHappened && playerStartedThisRound != null && player == playerStartedThisRound) {
return true;
}
}
return false;
} |
f092a401-d596-46ac-bfd7-fff0142afd8e | 8 | void onEntityChanged( final long someEntityId ) {
//setup local variables
List<Class<? extends Data>> processorInterstedDataList;
long processorIdBuffer;
boolean isInterested;
int interestedProcessorCount;
//retrieve all processors and a list with interested entities
final TLongObjectMap<TLongList> processorIntrestedEntityTable =
_dataCore.getProcessId_interestedEntity_Table();
//retrieve all types of data the given entity holds
final List<Class<? extends Data>> entityDataList =
_entityMgr.getAllDataTypesFromEntity( someEntityId );
//iterate over all lists of data types and the processors interested in them
for ( Map.Entry<List<Class<? extends Data>>, TLongList> entry :
_dataCore.getData_InterestedProcessor_Table().entrySet() ) {
//a data type set
processorInterstedDataList = entry.getKey();
//number of processors interested in ^^
interestedProcessorCount = entry.getValue().size();
//number of data types
final int interestedDataCount = processorInterstedDataList.size();
//iterate over all processors interested in the current data type set
for ( int i = 0; i < interestedProcessorCount; ++i ) {
//
processorIdBuffer = entry.getValue().get( i );
//determine if the processor is interested in the given entity
isInterested = true;
for ( int j = 0; j < interestedDataCount; ++j ) {
//if the entity is holding ALL data in which the processor is interested in
//isInterested is going to be true
isInterested &= entityDataList.contains( processorInterstedDataList.get( j ) );
}
//if the processor is interested in this entity
if ( isInterested ) {
//add the id of the entity to the list of interested entites of the processor
processorIntrestedEntityTable.get( processorIdBuffer ).add( someEntityId );
}
//if the processor is not interested, but was befor
else if ( processorIntrestedEntityTable.get( processorIdBuffer ).contains( someEntityId ) ) {
//remove the entity from the interest list
processorIntrestedEntityTable.get( processorIdBuffer ).remove( someEntityId );
}
}
}
} |
6940a432-4799-402d-8c49-f5de0e089bac | 2 | public void setDefaults() {
System.out.println("[BurningCS] Setting default config values");
try {
new File(this.dir).mkdir();
this.configFile.delete();
this.configFile.createNewFile();
} catch (Exception e) {
System.out.println("[BurningCS] Could not read config file!");
e.printStackTrace();
}
this.yml.set("Enderman.Disable Pickup", true);
this.yml.set("Creative Players.Disable Item Dropping", true);
this.yml.set("Creative Players.Disable Item Pickup", true);
this.yml.set("Creative Players.Placed Blocks Give No Drops.Players", true);
this.yml.set("Creative Players.Placed Blocks Give No Drops.Explosions", true);
this.yml.set("Creative Players.Disable Bottom-of-the-World Bedrock Break", true);
this.yml.set("Creative Players.Attack other entities", false);
this.yml.set("Game Mode.Separate Inventories", true);
this.yml.set("Update.Notifications", true);
this.yml.set("Blocks Save Interval", 15);
try {
this.yml.save(configFile);
} catch (IOException ex) {
System.out.println("[BurningCS] Could not save config file!");
ex.printStackTrace();
}
System.out.println("[BurningCS] Default values set!");
} |
0204e26b-638f-4dca-bae2-96f9948d4db4 | 2 | @Override
public void createFrom(int elementIndex, int numberOfPoints){
int size = 0;
for(int i = 0; i<numberOfPoints; i++){
size = size + inData.getLength()/numberOfPoints;
Integer[] array = new Integer[size];
for(int j = 0; j < size; j++ ){
array[j] = ((Integer[])inData.getFromKit(elementIndex))[j];
}
outData.addToKit(array);
}
} |
e3ab563d-f319-428f-af9a-ce6bab50f15d | 6 | public void tick() {
if (isHit) {
return;
}
if (tickCount == 0) {
switch(dir) {
case LEFT:
dx += -speed;
break;
case RIGHT:
dx += speed;
break;
case UP:
dy -= speed;
break;
case DOWN:
dy += speed;
break;
}
setX(getX() + dx);
setY(getY() + dy);
tickCount = ticks;
} else {
tickCount--;
}
} |
47fbd2c0-af72-4f5a-925c-cf5bb754483e | 7 | private FormData readFormData_multiPartFormData( String param_contentType,
HeaderParams headerParams )
throws IOException,
HeaderFormatException,
DataFormatException,
UnsupportedFormatException {
// The content type header should look like something like this:
// Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryeANQMKoBwsmwQrYZ
try {
// System.out.println( "xxxxxxxxx" + getClass().getName() + ": params=" + headerParams );
/*String boundary = headerParams.getTokenByPrefix( 0, // on first level
"boundary=", // the token name - so to say
false // not case sensitive?
);
*/
String boundary = headerParams.getTokenValue( param_contentType, // "multipart/form-data", // on first level
"boundary", // the token name - so to say
false, // not case sensitive?
1 // get first token ('boundary' is at index 0)
);
//KeyValueStringPair kv_boundary = KeyValueStringPair.split( boundary );
if( boundary == null
|| boundary.length() == 0
//|| kv_boundary == null
//|| kv_boundary.getValue() == null
//|| kv_boundary.getValue().length() == 0
) {
this.getLogger().log( Level.INFO,
getClass().getName() + ".readFormData_multiPartFormData()",
"Cannot split multi part form data. Required 'boundary' not present or empty in header field 'Content-Type'." );
throw new HeaderFormatException( "Cannot split multi part form data. Required 'boundary' not present or empty in header field 'Content-Type'." );
}
// Explode boundary (later: use a common parser class here for parsing header lines containing
// tokens with '=').
//String boundary_value = kv_boundary.getValue();
this.getLogger().log( Level.INFO,
getClass().getName() + ".readFormData_multiPartFormData()",
"Processing POST data using boundary '" + boundary + "' ..." );
// The format of the multipart-body is:
// ------------------------------------
// boundary := 0*69<bchars> bcharsnospace
// bchars := bcharsnospace / " "
// bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
// "+" / "_" / "," / "-" / "." /
// "/" / ":" / "=" / "?"
//
// --- with --------------------------
//
// multipart-body := [preamble CRLF]
// dash-boundary transport-padding CRLF
// body-part *encapsulation
// close-delimiter transport-padding
// [CRLF epilogue]
// dash-boundary := "--" boundary
// encapsulation := delimiter transport-padding
// CRLF body-part
// delimiter := CRLF dash-boundary
// close-delimiter := delimiter "--"
//
// --- Example: ----------------------
// --boundary
// 1. body-part
// --boundary
// 2. body-part
// --boundary
// 3. body-part
// --boundary--
//
// (See http://stackoverflow.com/questions/4656287/what-rules-apply-to-mime-boundary)
// So to detect if the last boundary is reached we need to check if the next
// body-party begins with
// '--' CRLF
//
// This can only be done using a pushback input stream.
//
MultipartMIMETokenizer mmt = new MultipartMIMETokenizer( this.getInputStream(),
boundary // Use the raw boundary from the headers here!
);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream( 128 );
FormData formData = new DefaultFormData( boundary );
InputStream token;
int tokenIndex = 0;
long tokenLength = 0;
long totalLength = 0;
byte[] endBuffer = new byte[4];
while( (token = mmt.getNextToken()) != null ) {
this.getLogger().log( Level.INFO,
getClass().getName() + ".readFormData_multiPartFormData()",
"Processing multiform part " + tokenIndex + " by reading from token/input: " + token.toString() + ", globalInputStream=" + this.getInputStream() );
ByteArrayOutputStream bufferOut = new ByteArrayOutputStream( 256 );
CustomUtil.transfer( token,
bufferOut,
-1, // no maxReadLength
128 // bufferSize
);
byte[] byteArray = bufferOut.toByteArray();
// Don't forget that each part itself has a trailing CRLF inside the POST data!
// See http://www.ietf.org/rfc/rfc2046.txt for details.
ByteArrayInputStream bufferIn = null;
if( byteArray.length >= 2
&& byteArray[byteArray.length-2] == Constants.CR
&& byteArray[byteArray.length-1] == Constants.LF ) {
// Drop trailing CRLF
bufferIn = new ByteArrayInputStream( byteArray, 0, byteArray.length-2 );
} else {
// Ooops ... the specification tells that there should be a trailing CRLF, but there isn't.
// --> Don't interrupt; print warning and continue with full data block
this.getLogger().log( Level.WARNING,
getClass().getName() + ".readFormData_multiPartFormData()",
"Multiform part " + tokenIndex + " misses the trailing CRLF bytes (not found). Continuing though with full data block. Further data processing might probably fail!" );
bufferIn = new ByteArrayInputStream( byteArray );
}
/*int b;
tokenLength = 0;
while( (b = token.read()) != - 1 ) {
System.out.print( (char)b );
tokenLength++;
totalLength++;
}*/
HTTPHeaders itemHeaders = HTTPHeaders.read( bufferIn ); // token );
FormDataItem item = new FormDataItem( itemHeaders, bufferIn ); // token );
formData.add( item );
this.getLogger().log( Level.INFO,
getClass().getName() + ".readFormData_multiPartFormData()",
"Processed multiform part " + tokenIndex + ": " + tokenLength + " bytes." );
tokenIndex++;
}
// It is not necesary to consume trailing bytes here; the HTTPRequestDistributor will
// do so later (IF there are more bytes available at all).
return formData;
} catch( IOException e ) {
this.getLogger().log( Level.INFO,
getClass().getName() + ".readFormData_multiPartFormData()",
"[IOException] Failed to read/split multi part form data: " + e.getMessage() );
throw e;
}
} |
0e0102dd-adf9-4f12-b5d5-d5338fac67c6 | 3 | private boolean checkForAttributes(File dataFile) {
try {
m_fileScan = new Scanner(dataFile);
} catch (FileNotFoundException e) {
return false;
}
m_delimiter=",";
m_lineScanner= new Scanner(m_fileScan.nextLine());
m_lineScanner.useDelimiter(m_delimiter);
while(m_lineScanner.hasNext()){
try {
Double.parseDouble(m_lineScanner.next());
} catch(NumberFormatException nfe) {
return true;
}
}
return false;
} |
1c8301ef-0d77-4a6d-a691-069b9e1e64ec | 5 | private void pop(char c) throws JSONException {
if (this.top <= 0) {
throw new JSONException("Nesting error.");
}
char m = this.stack[this.top - 1] == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.top -= 1;
this.mode = this.top == 0 ?
'd' : this.stack[this.top - 1] == null ? 'a' : 'k';
} |
011cee19-c6b5-4fce-bfdc-6801fc58fb06 | 8 | @Override
public void updateThisPlayerMovement(Player player, ByteVector packet) {
if (player.getUpdateFlags().contains("teleporting") || player.getUpdateFlags().contains("map-region")) {
packet.writeBits(1, 1);
packet.writeBits(2, 3);
packet.writeBits(2, player.getPosition().getPlane());
packet.writeBits(1, 1);
packet.writeBits(1, player.isUpdateRequired() ? 1 : 0);
packet.writeBits(7, player.getPosition().getLocalY(player.getLastPosition()));
packet.writeBits(7, player.getPosition().getLocalX(player.getLastPosition()));
} else {
if (player.getWalkingDirection() == -1) {
if (player.isUpdateRequired()) {
packet.writeBits(1, 1);
packet.writeBits(2, 0);
} else {
packet.writeBits(1, 0);
}
} else {
if (player.getRunningDirection() == -1) {
packet.writeBits(1, 1);
packet.writeBits(2, 1);
packet.writeBits(3, player.getWalkingDirection());
packet.writeBits(1, player.isUpdateRequired() ? 1 : 0);
} else {
packet.writeBits(1, 1);
packet.writeBits(2, 2);
packet.writeBits(3, player.getWalkingDirection());
packet.writeBits(3, player.getRunningDirection());
packet.writeBits(1, player.isUpdateRequired() ? 1 : 0);
}
}
}
} |
b407b78b-950f-40f6-b8e3-c1425af62bfa | 1 | @Before
public void setUp() throws Exception {
String[] moments = {
"01/01/2014 11:11","01/01/2014 11:28",
"01/01/2014 11:29","01/01/2014 12:08",
"01/01/2014 12:14","01/01/2014 12:42",
"01/01/2014 13:37","01/01/2014 14:17",
"01/01/2014 14:20","01/01/2014 14:23",
"01/01/2014 14:35","01/01/2014 14:45",
"01/01/2014 15:03","01/01/2014 15:30",
"01/01/2014 16:01","01/01/2014 16:25",
"01/01/2014 16:27","01/01/2014 16:35",
"01/01/2014 16:37","01/01/2014 16:42",
"01/01/2014 16:44","01/01/2014 16:59",
"01/01/2014 17:25","01/01/2014 17:34",
"01/01/2014 17:36","01/01/2014 18:02",
"01/01/2014 18:04","01/01/2014 18:29",
"01/01/2014 18:30","01/01/2014 18:57",
"01/01/2014 19:00","01/01/2014 19:01",
"01/01/2014 19:04","01/01/2014 19:08"};
times = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
for(String m :moments){
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(m));
times.add(cal);
}
} |
37cb9d56-8ce9-4f64-8009-e7e591dd2bb7 | 8 | public int run(String[] args) throws Exception {
if (args.length != 5) {
System.err.println("Usage: Model <input path> " +
"<output path for neuron structure>" +
"<output path for firing extraction>" +
"<output path for membrane potential>" +
"<output path for recovery variable>");
System.exit(-1);
}
IN = args[0];
OUT = args[1];
int timer = 1;
boolean success = false;
String inpath = IN;
// Each iteration we need a different output path because
// we are going to chain map-reduce together. The current output
// of the reducer will be the input of the next stage's mapper's input.
String outpath = OUT + timer;
while (timer <= TIME_IN_MS) {
Job job = new Job(getConf());
job.setJarByClass(Model.class);
job.setJobName("Izhikevich Model");
FileInputFormat.addInputPath(job, new Path(inpath));
FileOutputFormat.setOutputPath(job, new Path(outpath));
job.setMapperClass(SpikingNeuronMapper.class);
job.setReducerClass(SynapticWeightsReducer.class);
job.setMapOutputKeyClass(LongWritable.class);
job.setMapOutputValueClass(Text.class);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(Text.class);
success = job.waitForCompletion(true);
if (success == false) {
break;
}
// Reset the input and output path for the next iteration
inpath = outpath;
timer++;
outpath = OUT + timer;
}
/*
* Start jobs for post-analysis
*/
String inpaths = new String(); // used to construct a comma separated input paths.
for (int i = 1; i < TIME_IN_MS; i++) {
inpaths += "out-dir" + i + ",";
}
inpaths += "out-dir" + TIME_IN_MS;
if (success == true) {
Job job = new Job(getConf());
job.setJarByClass(Model.class);
job.setJobName("Fired Neurons Extraction");
FileInputFormat.addInputPaths(job, inpaths);
FileOutputFormat.setOutputPath(job, new Path(args[2]));
job.setMapperClass(FiredNeuronsMapper.class);
job.setReducerClass(FiredNeuronsReducer.class);
job.setOutputKeyClass(IntWritable.class);
job.setOutputValueClass(LongWritable.class);
job.setNumReduceTasks(1);
success = job.waitForCompletion(true);
}
if (success == true) {
Job job = new Job(getConf());
job.setJarByClass(Model.class);
job.setJobName("Membrane Potentials Extraction");
FileInputFormat.addInputPaths(job, inpaths);
FileOutputFormat.setOutputPath(job, new Path(args[3]));
job.setMapperClass(VCMapper.class);
job.setReducerClass(VCReducer.class);
job.setOutputKeyClass(LongWritable.class);
job.setOutputValueClass(Text.class);
job.setNumReduceTasks(1);
success = job.waitForCompletion(true);
}
if (success == true) {
Job job = new Job(getConf());
job.setJarByClass(Model.class);
job.setJobName("Recovery Variable Extraction");
FileInputFormat.addInputPaths(job, inpaths);
FileOutputFormat.setOutputPath(job, new Path(args[4]));
job.setMapperClass(RVMapper.class);
job.setReducerClass(RVReducer.class);
job.setOutputKeyClass(LongWritable.class);
job.setOutputValueClass(Text.class);
job.setNumReduceTasks(1);
success = job.waitForCompletion(true);
}
return (success ? 0 : 1);
} |
db420571-86d6-4477-8880-c3a4da8afdb0 | 8 | private boolean createDom(Section odMLRoot, boolean asTerminology) {
logger.debug("in createDom\twith RootSection");
doc = new Document();
// create processing instruction the last one added is the preferred one
ProcessingInstruction instr = null;
ProcessingInstruction altInstr = null;
if (asTerminology) {
altInstr = new ProcessingInstruction("xml-stylesheet",
"type=\"text/xsl\" href=\"odml.xsl\"");
instr = new ProcessingInstruction("xml-stylesheet",
"type=\"text/xsl\" href=\"odmlTerms.xsl\"");
} else {
altInstr = new ProcessingInstruction("xml-stylesheet",
"type=\"text/xsl\" href=\"odmlTerms.xsl\"");
instr = new ProcessingInstruction("xml-stylesheet",
"type=\"text/xsl\" href=\"odml.xsl\"");
}
doc.addContent(instr);
doc.addContent(altInstr);
Element rootElement = new Element("odML");
rootElement.setAttribute("version", "1");
doc.setRootElement(rootElement);
// if the odMLRoot has properties, a dummy root is added to ensure that everything is written
Section dummyRoot;
if (odMLRoot.propertyCount() != 0) {
dummyRoot = new Section();
dummyRoot.add(odMLRoot);
dummyRoot.setDocumentAuthor(odMLRoot.getDocumentAuthor());
dummyRoot.setDocumentDate(odMLRoot.getDocumentDate());
dummyRoot.setDocumentVersion(odMLRoot.getDocumentVersion());
dummyRoot.setRepository(odMLRoot.getRepository());
} else {
dummyRoot = odMLRoot;
}
String author = dummyRoot.getDocumentAuthor();
if (author != null) {
Element authorElement = new Element("author");
authorElement.setText(author);
rootElement.addContent(authorElement);
}
String version = dummyRoot.getDocumentVersion();
if (version != null) {
Element versionElement = new Element("version");
versionElement.setText(version);
rootElement.addContent(versionElement);
}
String dateString = null;
Date date = dummyRoot.getDocumentDate();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
if (date != null) {
dateString = sdf.format(date);
} else {
date = new Date(Calendar.getInstance().getTimeInMillis());
dateString = sdf.format(date);
}
if (dateString != null) {
Element dateElement = new Element("date");
dateElement.setText(dateString);
rootElement.addContent(dateElement);
}
URL repository = dummyRoot.getRepository();
if (repository != null) {
Element repElement = new Element("repository");
repElement.setText(repository.toString());
rootElement.addContent(repElement);
}
for (int i = 0; i < dummyRoot.sectionCount(); i++) {
appendSection(rootElement, dummyRoot.getSection(i), asTerminology);
}
return true;
} |
47e24038-a578-4409-80c5-57169b20a5f0 | 0 | public void setOsoba(Osoba osoba) {
this.osoba = osoba;
} |
38892118-d333-4bf4-86fb-7000768e3c2f | 2 | @Override
public void startElement(String uri, String localName, String qName,
org.xml.sax.Attributes attributes) throws SAXException {
tag = Tags.fromString(qName);
if (tag == null) {
return;
}
switch (tag) {
case MESSAGE:
String tmp = attributes.getValue("id").trim();
int bid = Integer.parseInt(tmp);
message = new Message(bid);
tag = null;
break;
default:
}
} |
5b86c95c-933d-4a42-9787-fe70c68fced1 | 4 | private static void addRandomPit(WorldMap w, Random r)
{
boolean valid = false;
while (!valid)
{
int x = rnd(r);
int y = rnd(r);
if (!(x == 1 && y == 1) && !w.hasPit(x, y))
{
valid = true;
w.addPit(x, y);
}
}
} |
48543560-67cf-4720-a55c-8d1bd2c51c51 | 1 | public void add(String word) {
if (word.trim().length() > 0)
m_Words.add(word.trim().toLowerCase());
} |
63c0e2ac-4d0c-459c-8f11-803fa32e94db | 7 | void readToData(boolean returnOnYield)
throws IOException
{
InputStream is = getInputStream();
if (is == null)
return;
for (int tag = is.read(); tag >= 0; tag = is.read()) {
switch (tag) {
case 'Y':
server.freeReadLock();
if (returnOnYield)
return;
server.readChannel(channel);
break;
case 'Q':
server.freeReadLock();
this.is = null;
this.server = null;
return;
case 'U':
this.url = readUTF();
break;
case 'D':
chunkLength = (is.read() << 8) + is.read();
return;
default:
readTag(tag);
break;
}
}
} |
2142e3f6-1379-44a4-b284-27174fa5c851 | 6 | public static void open(File root)
{
System.out.println("Loading cache from " + root + "...");
System.out.println("----------------------------------");
try
{
File file = new File(root, "main_file_cache.dat");
datum = new RandomAccessFile(file, "rw").getChannel();
System.out.println("\tCache found " + file);
for (int i = 0; i < 254; i++)
{
file = new File(root, "main_file_cache.idx" + i);
if (!file.exists())
{
break;
}
cache.put(
i,
new FileMeta(new RandomAccessFile(file, "rw")
.getChannel()));
System.out.println("\t\tFound index " + i + " and built with "
+ cache.get(i).getArchiveCount() + " archives");
}
FileMeta meta = cache.get(0);
System.out.println("\tBuilding CRC32 table with "
+ meta.getArchiveCount() + " entries...");
CRC32 crc = new CRC32();
int[] checksums = new int[meta.getArchiveCount()];
checksums[0] = Constants.CLIENT_REVISION;
for (int i = 1; i < checksums.length; i++)
{
FileDescription description = new FileDescription(0, i);
ByteBuffer buffer = get(description);
crc.reset();
crc.update(buffer.array());
checksums[i] = (int) crc.getValue();
System.out.println("\t\tEntry " + i
+ " generated a crc value of " + checksums[i]);
}
int hash = 1234;
for (int i = 0; i < checksums.length; i++)
{
hash = (hash << 1) + checksums[i];
}
System.out.println("\tUp to date cache hash is " + hash);
FileStore.meta = ByteBuffer.allocate(4 * (checksums.length + 1));
for (int i = 0; i < checksums.length; i++)
{
FileStore.meta.putInt(checksums[i]);
}
FileStore.meta.putInt(hash);
FileStore.meta.flip();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("----------------------------------");
} |
26101e67-ba93-4387-8443-586946e20bee | 9 | public static void markRowColumn(int[][] input) {
boolean[] row = new boolean[input.length];
boolean[] column = new boolean [input[0].length];
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input[0].length; j++) {
if(input[i][j] ==1){
row[i] |= true;
column[j] |= true;
}
}
}
for( int i=0; i< row.length; i++){
for (int j = 0; j < column.length; j++) {
if(row[i]){
input[i][j] = 1;
}
}
}
for( int i=0; i< column.length; i++){
for (int j = 0; j < row.length; j++) {
if(column[i]){
input[j][i] = 1;
}
}
}
} |
65f5fc25-6c8c-491e-b899-8efec862ee2b | 8 | public static void execute() throws Exception{
//creating final dict and dir
File dictFile = new File("dict/final/final.dict");
dictFile.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(dictFile);
OutputStreamWriter finalDictWriter = new OutputStreamWriter(fos);
//list of each dict block names
File dir = new File("dict/block");
String[] files = dir.list();
//creating buffered reader for each temp dict block
ArrayList<BufferedReader> dictReaders = new ArrayList<BufferedReader>();
for (String file : files) {
//System.out.println(file);
dictReaders.add(new BufferedReader(new FileReader(new File(dir + "/" + file))));
}
//hold one index entry in a simple object rather than hashtable, is replaced each time buffered read advances
ArrayList<SingleIndex> currentBlockEntries = new ArrayList<SingleIndex>(dictReaders.size());
//get first index line for each dict block
for (int i = 0; i < dictReaders.size(); i++) {
currentBlockEntries.add(i, new SingleIndex(dictReaders.get(i).readLine()));
}
//loop over each dict block removing them when they reach EOF
while(dictReaders.size() > 0){
//position of the dict block(s) with smallest word
ArrayList<Integer> smallestBlockEntryIndexes = new ArrayList<Integer>();
//instantiate first block with smallest word
String smallestWord = currentBlockEntries.get(0).getTerm();
smallestBlockEntryIndexes.add(0);
//find smallest word
for (int i = 1; i < currentBlockEntries.size(); i++) {
String currentWord = currentBlockEntries.get(i).getTerm();
//if smaller word is found clear current array
if (currentWord.compareTo(smallestWord) < 0) {
smallestBlockEntryIndexes.clear();
smallestBlockEntryIndexes.add(i);
smallestWord = currentWord;
//if same word add to array (to merge posting lists further)
} else if (currentWord.compareTo(smallestWord) == 0) {
smallestBlockEntryIndexes.add(i);
}
}
//creating new posting list to merge and writing current smallest term
PostingList mergedPostingList = new PostingList();
finalDictWriter.write(currentBlockEntries.get(smallestBlockEntryIndexes.get(0)).getTerm());
//loop backwards to remove biggest indexes first for remove() repacking
for (int i = smallestBlockEntryIndexes.size()-1; i >= 0; i--) {
int currentSmallestIndex = smallestBlockEntryIndexes.get(i);
//System.out.println(i+":"+currentSmallestIndex);
//merge posting lists (and sort)
mergedPostingList.addAll(currentBlockEntries.get(currentSmallestIndex).getPl());
//Collections.sort(mergedPostingList.toArray(), new CustomComparator());
Collections.sort(mergedPostingList, new Comparator<TermFrequencyPair>(){
public int compare(TermFrequencyPair o1, TermFrequencyPair o2) {
return o1.getDocId().compareTo(o2.getDocId());
}
});
//read next line from smallest block index
String newCurrentBlockLine = dictReaders.get(currentSmallestIndex).readLine();
//remove current block/reader/smallest index if reach EOF
if (newCurrentBlockLine == null) {
//System.out.println("Removed="+i+":"+currentSmallestIndex);
currentBlockEntries.remove(currentSmallestIndex);
dictReaders.get(currentSmallestIndex).close();
dictReaders.remove(currentSmallestIndex);
smallestBlockEntryIndexes.remove(i);
//replace appropriate block entry with new line
} else {
SingleIndex newCurrentBlockEntry = new SingleIndex(newCurrentBlockLine);
currentBlockEntries.set(currentSmallestIndex, newCurrentBlockEntry);
}
}
//append posting list to term on same dict line
finalDictWriter.write(mergedPostingList.toString() + "\n");
}
finalDictWriter.close();
//add deleting temp dict blocks..?
} |
30b21f28-211a-4b53-8b51-3b1f50eb0d12 | 9 | private ArrayList<String> compileAssignment(String varname, String value) throws MCCAssignmentException {
if (!vars.containsKey(varname)) throw new MCCAssignmentException();
ArrayList<String> out = new ArrayList<String>();
Variable targetVar = vars.get(varname);
boolean byVar = false;
if (value == "false" || value == "true") {
if (!targetVar.isOfType("boolean")) throw new MCCAssignmentException();
} else if (value.matches("^" + REGEX_NUMBER + "$")) {
if (targetVar.isOfType("boolean")) throw new MCCAssignmentException();
} else {
if (!vars.containsKey(value)) throw new MCCAssignmentException();
byVar = true;
}
if (byVar) {
Variable sourceVar = vars.get(value);
if (Variable.loadedAddress != sourceVar.address) out.add("read " + REGISTER_VAR + " " + vars.get(value).address);
} else {
out.add("movi " + REGISTER_VAR + " " + value);
}
out.add("save " + REGISTER_VAR + " " + targetVar.address);
Variable.loadedAddress = targetVar.address;
System.out.println("assigned " + value + " to " + varname);
return out;
} |
fdba0634-d9df-4748-8242-2fcbf5f614d3 | 2 | private void display() {
num = getArray();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(num[i][j] + " ");
}
System.out.println();
}
} |
27fbefa2-16cb-4f48-93de-4f21f0f474c9 | 0 | public void setId(Long id) {
this.id = id;
} |
0c93e0b8-aa24-4542-b83b-28b7d263774b | 6 | private Node parseRange() {
if (input.charAt(offset) == '^') {
throwError("Negotiated ranges are forbidden");
}
Decision result = new Decision(this);
while (offset < input.length()) {
char from = input.charAt(offset);
if (from == ']') {
offset++;
break;
}
char sep = input.charAt(offset + 1);
if (sep == '-' && from != '\\') {
char to = input.charAt(offset + 2);
if (to != ']') {
offset += 3;
result.append(new Range(this, from, to));
}
else {
result.append(parseLiteral(false));
}
}
else {
result.append(parseLiteral(false));
}
}
parseQuantifier(result);
return result;
} |
1e5b8e06-7941-4b5c-af8c-13c605806c20 | 0 | public int getHeight() {
return height;
} |
528cf3da-ad1b-4205-a57f-b0f5d9f99979 | 0 | public void setNick(String nick){ this.Nick = nick; } |
e6ea5d82-9fef-45d5-b8a4-9932b902de0a | 3 | @Override
public AbstractComponent parse(String string) throws BookParseException {
if (string == null) {
throw new BookParseException("String is null");
}
try {
TextComponent component = (TextComponent) factory
.newComponent(EComponentType.PARAGRAPH);
Pattern sentencePattern = Pattern.compile(SENTENCE_REGEX,
Pattern.UNICODE_CHARACTER_CLASS);
Matcher sentenceMatcher = sentencePattern.matcher(string);
while (sentenceMatcher.find()) {
component.addComponent(sentenceParser.parse(sentenceMatcher
.group()));
}
return component;
} catch (ComponentException e) {
throw new BookParseException("Paragraph parse failed", e);
}
} |
c382fc31-a91e-4163-9d8a-59f4fc9a470e | 8 | @Override
public void reduce(DoubleTextPair key, Iterable<Text> values, Context context) throws IOException,
InterruptedException {
String tmp;
List<String> fk = new ArrayList<String>();
List<String> pk = new ArrayList<String>();
for (Text v : values) {
tmp = v.toString();
// FIXLATER 只有支援一個表格一個顯示欄位
if (tmp.contains(COMMA + WHITE_SPACE)) {
fk.add(tmp);
} else {
pk.add(tmp);
}
}
String[] tmpArray;
StringBuffer key_sb = new StringBuffer();
StringBuffer val_sb = new StringBuffer();
// 對於每個外來鍵建立一組Key-Value Pair
for (String k : fk) {
tmpArray = k.split(COMMA + WHITE_SPACE);
// without rf
for (int i = 0; i < tmpArray.length - 1; i++) {
key_sb.append(tmpArray[i]);
key_sb.append(COMMA + WHITE_SPACE);
}
// delete ", "
if (key_sb.length() > 0) {
key_sb.delete(key_sb.length() - 2, key_sb.length());
}
// column set start
// FIXLATER 目前根據欄位給予編號(第三階段會使用)
val_sb.append(key.getIndex());
val_sb.append(TAB);
// column set end
String[] tmptmp;
for (String v : pk) {
tmptmp = v.split(COMMA + WHITE_SPACE);
for (int j = 0; j < tmptmp.length; j++) {
if (!tmptmp[j].equals(EMPTY)) {
val_sb.append(tmptmp[j]);
val_sb.append("\t");
}
}
}
val_sb.append(tmpArray[tmpArray.length - 1]);// rf
context.write(new Text(key_sb.toString()), new Text(val_sb.toString()));
val_sb.delete(0, val_sb.length());
key_sb.delete(0, key_sb.length());
}
} |
178e8b0c-d02a-4dc3-91ff-27bd4d448a6a | 7 | public ArrayList<String> splitInput(String input) {
boolean quote = false;
int index = 0;
ArrayList<String> sentences = new ArrayList<>();
for (int i = 0; i < input.length(); i++) {
if (input.substring(i, i + 1).equals("\"")) {
quote = !quote;
}
if ((input.substring(i, i + 1).matches("[.!?]") || (i == input.length() - 1))) {
if (!quote && !(input.substring(i - 2, i).matches("Mr|Ms|Dr|St|Jr|Sr|co")) && !(input.substring(i - 3, i).matches("Mrs|etc|Gen|inc"))) {
sentences.add(input.substring(index, i + 1));
index = i + 2;
}
}
}
return sentences;
} |
496d2ae6-abb4-4e35-ac97-7fe5f3629a73 | 3 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final CvOutlet other = (CvOutlet) obj;
if (!Objects.equals(this.Outlet, other.Outlet)) {
return false;
}
return true;
} |
5de03b4b-24f9-4d47-8c51-b767d4916640 | 3 | public PGM affichage(){
PGM img = new PGM(255, valeurs.length*5, this.getMaxValeurs());
ArrayList<Integer> list = new ArrayList<>();
for(int i = this.getMaxValeurs(); i > 0; i--){
for (int j = 0; j < valeurs.length; j++){
if (valeurs[j] >= i){
list.add(0);
list.add(0);
list.add(0);
list.add(0);
list.add(255);
}
else {
list.add(255);
list.add(255);
list.add(255);
list.add(255);
list.add(255);
}
}
}
img.setNiveauxGris(list);
return img;
} |
0c5c8222-3d78-4feb-bb7e-c8b268dfb0a0 | 7 | public void addContent(String path, File pContent) {
if (pContent.isFile()) {
if (pContent.getName().endsWith(EXT_XCS)) {
addConfigurationSchemaFile(path);
} else if (pContent.getName().endsWith(EXT_XCU)) {
addConfigurationDataFile(path);
} else if (pContent.getName().endsWith(EXT_RDB)) {
addTypelibraryFile(path, "RDB");
} else if (pContent.getName().equals("description.xml")) {
addDescription(path, Locale.getDefault());
}
} else if (pContent.isDirectory()) {
// Recurse on the directory
for (File child : pContent.listFiles()) {
addContent(path + "/" + child.getName(), child );
}
} else {
throw new IllegalArgumentException("pContent [" + pContent + "] does not exists");
}
} |
9501fea8-5fab-4a3a-9e0e-21a27a27006e | 2 | public void testPropertyAddHour() {
Partial test = new Partial(TYPES, VALUES);
Partial copy = test.property(DateTimeFieldType.hourOfDay()).addToCopy(9);
check(test, 10, 20, 30, 40);
check(copy, 19, 20, 30, 40);
copy = test.property(DateTimeFieldType.hourOfDay()).addToCopy(0);
check(copy, 10, 20, 30, 40);
copy = test.property(DateTimeFieldType.hourOfDay()).addToCopy(13);
check(copy, 23, 20, 30, 40);
try {
test.property(DateTimeFieldType.hourOfDay()).addToCopy(14);
fail();
} catch (IllegalArgumentException ex) {}
check(test, 10, 20, 30, 40);
copy = test.property(DateTimeFieldType.hourOfDay()).addToCopy(-10);
check(copy, 0, 20, 30, 40);
try {
test.property(DateTimeFieldType.hourOfDay()).addToCopy(-11);
fail();
} catch (IllegalArgumentException ex) {}
check(test, 10, 20, 30, 40);
} |
79fb83c4-7387-4a98-9b20-dc066d09dcff | 0 | public static void setSessionId(URLConnection con,String value){
con.setRequestProperty("Cookie", value);
} |
a9080397-1b83-4669-a816-de3cc986eb6a | 1 | private static void inOrderTraversal(Node root) {
if (root == null)
return;
inOrderTraversal(root.left);
System.out.println(root.v);
inOrderTraversal(root.right);
} |
5af70192-cb1e-4d9f-8de6-a0d2a9f7bf0d | 4 | @Override
public SignalAspect getSignalAspect() {
if (isWaitingForRetest() || isBeingPaired()) {
return SignalAspect.BLINK_YELLOW;
}
if (!isPaired()) {
return SignalAspect.BLINK_RED;
}
SignalAspect aspect = SignalAspect.GREEN;
for (WorldCoordinate otherCoord : getPairs()) {
aspect = SignalAspect.mostRestrictive(aspect, aspects.get(otherCoord));
}
return aspect;
} |
3acf8a1d-ae84-4b7a-8b4a-781ca8030b2a | 2 | public static int getSinglePrice(final int ids) {
String add = "http://scriptwith.us/api/?return=text&item=" + ids;
try {
final BufferedReader in = new BufferedReader(new InputStreamReader(new URL(add).openConnection().getInputStream()));
final String line = in.readLine();
in.close();
final String[] sets = line.split("[;]");
for (String s : sets) {
final String[] set = s.split("[:]");
return Integer.parseInt(set[1]);
}
} catch (Exception e) {
e.printStackTrace();
}
return -1;
} |
6beb5455-97d6-4f57-8cd2-c3f8907025ab | 6 | public static void run_spell_check(File dic, File doc, String option)
{
// Creating a new SpellCheckerUtil object with the dictionary file
SpellCheckUtil mySC = new SpellCheckUtil(dic);
// Creating a list of misspelled words after checking spellcheking the document
List<String> misspelledWords = mySC.spellCheck(doc);
if (misspelledWords.size() == 0)
System.out.println("\nThere are no misspelled words in file " + doc + ".\n");
else
{
System.out.println("\nThere are " + misspelledWords.size() + " misspelled words in file " + doc + ".");
if(option.equals("-p"))
{
for(String word : misspelledWords)
System.out.println(word);
}
else if(option.equals("-f"))
try
{
FileWriter writer = new FileWriter("misspelled.txt");
for(String word : misspelledWords)
writer.write(word + "\n");
writer.close();
System.out.println("Please see misspelled.txt for a list of the words.");
}
catch (IOException e)
{
System.out.println("Unable to create a file for the misspelled words!");
return;
}
System.out.println("\nHave a nice day!\n");
}
} |
19e2b0ad-7eea-40fb-8aa7-51b3fb032cab | 8 | @Override
public Ranking<Candidate> vote() {
Map<LinkedList<Candidate>, Integer> dg = getDirectedGraph();
Candidate winner = null;
Integer score = -1;
// argmin(max(score(Y,X))) =-> winner
// X Y
for (Candidate X : cans)
{
if (winner == null)
{
winner = X;
}
Integer max = -1;
for (Candidate Y : cans)
{
if (X != Y)
{
LinkedList<Candidate> pair = new LinkedList<>();
pair.push(Y);
pair.push(X);
if (dg.containsKey(pair) && dg.get(pair) > max)
{
max = dg.get(pair);
}
}
}
if (max < score || score == -1)
{
score = max;
winner = X;
}
}
r = new Ranking<>();
r.pushCandidate(winner);
return r;
} |
db48a6d3-781a-4323-9dcf-97239d061cc9 | 8 | @Override
public boolean equals(Object obj) {
if (obj != null) {
if (obj instanceof Node) {
Node n = (Node)obj;
if (n.getId() != null && this.getId() != null
&& n.getId().equals(this.getId())) {
return true;
}
} else if (obj instanceof String) {
String s = (String)obj;
if (this.getId() != null && s.equals(this.getId())) {
return true;
}
}
}
return false;
} |
8047ff43-c8a6-433c-99d0-d1f342a1b96f | 2 | public static final boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
} |
3f12f867-6d24-4923-ac0b-d9a6d9392c82 | 2 | @Test
public void delMinReturnsValuesInCorrectOrderWhenInputIsGivenInDescendingOrder() {
int[] expected = new int[100];
for (int i = 99; i >= 0; i--) {
h.insert(new Vertex(0, i));
expected[i] = i;
}
Arrays.sort(expected);
int[] actual = new int[100];
for (int i = 0; i < 100; i++) {
actual[i] = h.delMin().getDistance();
}
assertArrayEquals(expected, actual);
} |
18cf4285-2ad4-4c39-b47c-3cdfecde26ea | 6 | public void refine() {
List<Component> usedComponentsEP = getNecessaryComponents(bestSequenceAlternativesEnergyPoint);
List<Component> usedComponentsW = getNecessaryComponents(bestSequenceAlternativesWatt);
for (Component component : usedComponentsEP) {
for (DeployedComponent deployedComponent : deploymentAlternative.getDeployedComponents())
if (deployedComponent.getComponent().equals(component))
deploymentEP.getDeployedComponents().add(deployedComponent);
}
for (Component component : usedComponentsW) {
for (DeployedComponent deployedComponent : deploymentAlternative.getDeployedComponents())
if (deployedComponent.getComponent().equals(component))
deploymentW.getDeployedComponents().add(deployedComponent);
}
} |
5406f958-83d0-42e0-8331-ae6918dd21b2 | 9 | public static Object[] getWFIPath(mxAnalysisGraph aGraph, ArrayList<Object[][]> FWIresult, Object startVertex, Object targetVertex)
throws StructuralException
{
Object[][] dist = FWIresult.get(0);
Object[][] paths = FWIresult.get(1);
ArrayList<Object> result = null;
if (aGraph == null || paths == null || startVertex == null || targetVertex == null)
{
throw new IllegalArgumentException();
}
for (int i = 0; i < dist[0].length; i++)
{
if ((Double) dist[i][i] < 0)
{
throw new StructuralException("The graph has negative cycles");
}
}
if (startVertex != targetVertex)
{
mxCostFunction cf = aGraph.getGenerator().getCostFunction();
mxGraphView view = aGraph.getGraph().getView();
ArrayList<Object> currPath = new ArrayList<Object>();
currPath.add(startVertex);
while (startVertex != targetVertex)
{
result = getWFIPathRec(aGraph, paths, startVertex, targetVertex, currPath, cf, view);
startVertex = result.get(result.size() - 1);
}
}
if (result == null)
{
result = new ArrayList<Object>();
}
return result.toArray();
}; |
425998e8-cb3b-4a89-a8ce-0e354702c11c | 5 | public static int[] bubble(int[] array) {
if(array==null || array.length==0) return array;
int tmp;
int cnt=0;
for(int i=0;i<array.length;++i) {
for(int j=0;j<array.length-i-1;++j) {
if(array[j]>array[j+1]) {
cnt++;
tmp = array[j];
array[j] = array[j+1];
array[j+1] = tmp;
}
}
}
System.out.print("Bubble sort, N="+array.length+", Excution times="+cnt+", Extra Space=0");
return array;
} |
46931e83-cb26-4a85-94b9-011ee59e88a1 | 4 | private boolean _jspx_meth_c_when_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_0 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_0.setPageContext(_jspx_page_context);
_jspx_th_c_when_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_0);
_jspx_th_c_when_0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${db.connectedOK}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_0 = _jspx_th_c_when_0.doStartTag();
if (_jspx_eval_c_when_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("連線成功!");
int evalDoAfterBody = _jspx_th_c_when_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_0);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_0);
return false;
} |
30697ade-5f7d-4def-b135-1e2e7de9e66d | 7 | @Override
public boolean equals(Object o) {
if (!(o instanceof Tuple))
return false;
Tuple oo = (Tuple)o;
if( oo.arg1_type.length() != this.arg1_type.length() )
return false;
if( oo.relation.length() != this.relation.length() )
return false;
if( oo.arg2_type.length() != this.arg2_type.length() )
return false;
if( !oo.arg1_type.equals( this.arg1_type ) )
return false;
if( !oo.arg2_type.equals( this.arg2_type ) )
return false;
if( !oo.relation.equals( this.relation ) )
return false;
return true;
} |
94c83540-2b82-43b4-be49-ee535c711478 | 5 | public boolean isVisible(User user) {
if(visibility == VISIBILITY_PUBLIC) {
return true;
}
if(visibility == VISIBILITY_FRIENDS) {
if(owner.friendsWith(user)) {
return true;
}
}
if(visibility == VISIBILITY_PRIVATE) {
if(owner.equals(user)) {
return true;
}
}
return false;
} |
977b8fe6-7241-43c7-b7e9-a9ba6b5d0317 | 5 | @Override
protected void mouseClicked(int var1, int var2, int var3) {
if (var3 == 0) {
if (this.mc.ingameGUI.field_933_a != null) {
if (this.message.length() > 0 && !this.message.endsWith(" ")) {
this.message = this.message + " ";
}
this.message = this.message + this.mc.ingameGUI.field_933_a;
byte var4 = 100;
if (this.message.length() > var4) {
this.message = this.message.substring(0, var4);
}
} else {
super.mouseClicked(var1, var2, var3);
}
}
} |
c9a6928b-df5a-4957-a47f-ceb81bbec13b | 9 | public void testGetDurationMillis_Object2() throws Exception {
try {
StringConverter.INSTANCE.getDurationMillis("P2Y6M9DXYZ");
fail();
} catch (IllegalArgumentException ex) {}
try {
StringConverter.INSTANCE.getDurationMillis("PTS");
fail();
} catch (IllegalArgumentException ex) {}
try {
StringConverter.INSTANCE.getDurationMillis("XT0S");
fail();
} catch (IllegalArgumentException ex) {}
try {
StringConverter.INSTANCE.getDurationMillis("PX0S");
fail();
} catch (IllegalArgumentException ex) {}
try {
StringConverter.INSTANCE.getDurationMillis("PT0X");
fail();
} catch (IllegalArgumentException ex) {}
try {
StringConverter.INSTANCE.getDurationMillis("PTXS");
fail();
} catch (IllegalArgumentException ex) {}
try {
StringConverter.INSTANCE.getDurationMillis("PT0.0.0S");
fail();
} catch (IllegalArgumentException ex) {}
try {
StringConverter.INSTANCE.getDurationMillis("PT0-00S");
fail();
} catch (IllegalArgumentException ex) {}
try {
StringConverter.INSTANCE.getDurationMillis("PT-.001S");
fail();
} catch (IllegalArgumentException ex) {}
} |
041cd7bd-e2a9-4177-bbd6-56f1a2d1e19a | 5 | @Override
public List<ModelLoader> convert(Text[] texts) {
List<ModelLoader> modelList = new LinkedList<>();
for (Text text : texts) {
totalIndex = 0;
ModelLoader model = new ModelLoader();
model.texture = text.font.getAtlas();
// List of bounds of chars in graphicsfont
Rectangle[] allBounds = text.font.getBounds();
for (Text.TextInstance instance : text.instances) {
// How much to move the next character
int charAdvance = instance.point.x;
// Iterate through all the characters in the string
for (int i = 0; i < instance.string.length(); i++) {
char c = instance.string.charAt(i);
if (c > 255) c = ' '; //char is not ascii
//bounds of the current char
Rectangle bounds = allBounds[c];
// char is not displayable or is whitespace
if (bounds != null) {
// copy the bounds and scale to texture coordinates
Texture atlas = text.font.getAtlas();
float top = atlas.yRatio(atlas.getHeight() - bounds.y);
float bottom = atlas.yRatio(atlas.getHeight() - (bounds.y + bounds.height));
float left = atlas.xRatio(bounds.x);
float right = atlas.xRatio(bounds.x + bounds.width);
// copy the bounds (for width and height)
Rectangle r = bounds.getBounds();
// change the position from texture pixel position to text position
r.x = charAdvance;
r.y = instance.point.y;
// put vertices
// 0--------3
// | \ |
// | \ |
// 1--------2
model.vertices.put((float) r.x, r.y, 0);
model.vertices.put((float) r.x, r.y + r.height, 0);
model.vertices.put((float) r.x + r.width, r.y + r.height, 0);
model.vertices.put((float) r.x + r.width, r.y, 0);
// put texture coordinates
// 0,1-----1,1
// | |
// | |
// 0,0-----1,0
model.textureCoords.put(left, top);
model.textureCoords.put(left, bottom);
model.textureCoords.put(right, bottom);
model.textureCoords.put(right, top);
int color = instance.color.getRGB();
color = color << 8 | color >>> 24;
//add the color; one for each of the vertices.
model.color.add(color);
model.color.add(color);
model.color.add(color);
model.color.add(color);
// put indices;
model.addFace(totalIndex++, totalIndex++, totalIndex++, totalIndex++);
}
charAdvance += text.font.getFontMetrics().charWidth(c);
}
}
modelList.add(model);
}
return modelList;
} |
4fb2ef63-20f9-43c7-841f-b7bbe01fa7ae | 6 | public void playfile() {
FileInputStream in;
String path = mp3list.getSong().getPath();
if (!path.equals("")) {
try {
in = new FileInputStream(path);
if (player != null) {
player.close();
};
player = new Player(in);
markPlaying();
setLivePanel();
mp3list.markNextSong();
mp3list = mp3list.nextList();
status = READY;
Thread t = new Thread() {
public void run() {
try {
player.play();
} catch (JavaLayerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (status != STOP) {
playfile();
}
}
};
t.start();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JavaLayerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
7712a598-e8f2-47e9-ac80-4b8c92bc0796 | 0 | public static Hand FullHouse(Rank tripsRank, Rank pairRank) {
return new Hand(HandRank.FullHouse, null, tripsRank, pairRank, Rank.Null, Rank.Null, Rank.Null);
} |
5eb6bbd6-7797-4f1b-8589-4fc9a52015af | 6 | Vector<Integer> sortIntegers(int a, int b, int c) {
Vector<Integer> result = new Vector<>(3);
if ((a <= b) && (a <= c)) {
result.add(a);
if (b <= c) {
result.add(b);
result.add(c);
} else {
result.add(c);
result.add(b);
}
} else if (b <= c) {
result.add(b);
if (a <= c) {
result.add(a);
result.add(c);
} else {
result.add(c);
result.add(a);
}
} else {
result.add(c);
if (a <= b) {
result.add(a);
result.add(b);
} else {
result.add(b);
result.add(a);
}
}
return result;
} |
62d223e7-dce3-42cf-9e86-a868a85b6552 | 1 | public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ObjectID2IntgerMain window = new ObjectID2IntgerMain();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} |
6d738b00-4b8f-4c00-8d4d-bb20e7a7d584 | 8 | @Override
public void e(float sideMot, float forMot) {
if (this.passenger == null || !(this.passenger instanceof EntityHuman)) {
super.e(sideMot, forMot);
this.W = 0.5F; // Make sure the entity can walk over half slabs,
// instead of jumping
return;
}
EntityHuman human = (EntityHuman) this.passenger;
if (!RideThaMob.control.contains(human.getBukkitEntity().getName())) {
// Same as before
super.e(sideMot, forMot);
this.W = 0.5F;
return;
}
this.lastYaw = this.yaw = this.passenger.yaw;
this.pitch = this.passenger.pitch * 0.5F;
// Set the entity's pitch, yaw, head rotation etc.
this.b(this.yaw, this.pitch); // https://github.com/Bukkit/mc-dev/blob/master/net/minecraft/server/Entity.java#L163-L166
this.aO = this.aM = this.yaw;
this.W = 1.0F; // The custom entity will now automatically climb up 1
// high blocks
sideMot = ((EntityLiving) this.passenger).bd * 0.5F;
forMot = ((EntityLiving) this.passenger).be;
if (forMot <= 0.0F) {
forMot *= 0.25F; // Make backwards slower
}
sideMot *= 0.75F; // Also make sideways slower
float speed = 0.35F; // 0.2 is the default entity speed. I made it
// slightly faster so that riding is better than
// walking
this.i(speed); // Apply the speed
super.e(sideMot, forMot); // Apply the motion to the entity
try {
Field jump = null;
jump = EntityLiving.class.getDeclaredField("bc");
jump.setAccessible(true);
if (jump != null && this.onGround) { // Wouldn't want it jumping
// while
// on the ground would we?
if (jump.getBoolean(this.passenger)) {
double jumpHeight = 0.5D;
this.motY = jumpHeight; // Used all the time in NMS for
// entity jumping
}
}
} catch (Exception e) {
e.printStackTrace();
}
} |
8a1557ee-10c0-49f6-90a4-885b5ff606e1 | 9 | public void discoveryTransfer()
{
if(fileManager.getPrevNode().equals(fileManager.getNextNode())) //When second node is connected to the network, all files on this system need to be replicated
{
fileReplicationTransfer(fileManager.getOwnedFiles());
}
else
{
for(FileProperties f : fileManager.getOwnedOwnerFiles())
{
if(((fileManager.getThisNode().getHash() < fileManager.getNextNode().getHash()) && ((f.getHash() > fileManager.getNextNode().getHash()) || (f.getHash() < fileManager.getThisNode().getHash()))) || ((fileManager.getThisNode().getHash() > fileManager.getNextNode().getHash()) && (f.getHash() > fileManager.getNextNode().getHash()) && (f.getHash() < fileManager.getThisNode().getHash()))) //Next node is the new file owner
{
try
{
FileManagerInterface iFaceNode = (FileManagerInterface) fileManager.getFileManagerInterface(fileManager.getNextNode());
iFaceNode.ownerSwitchFile(f.getFilename(), fileManager.getThisNode());
}
catch(NullPointerException | RemoteException e)
{
System.err.println("Failed to contact to node '" + fileManager.getNextNode().getHostname() + "': " + e.getMessage());
fileManager.nodeConnectionFailure(fileManager.getNextNode().getHostname());
continue;
}
}
}
}
} |
72417ae3-2016-4319-910d-e3dcf5d012db | 2 | public void repaintGrid() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
gridCells[i][j].repaint();
}
}
} |
ccf63c58-a05f-4fff-8a4d-36ac465c014e | 5 | public CheckResultMessage check2(int day) {
BigDecimal a1 = new BigDecimal(0);
int r1 = get(6, 5);
int c1 = get(7, 5);
if (version.equals("2003")) {
try {
in = new FileInputStream(file);
hWorkbook = new HSSFWorkbook(in);
a1 = getValue(r1 + day, c1 + 1, 1).add(
getValue(r1 + day, c1 + 2, 1));
if (0 != getValue(r1 + day, c1, 1).compareTo(a1)) {
return error("支付机构汇总报表<" + fileName + ">业务系统借记客户资金金额:"
+ day + "日错误");
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
in = new FileInputStream(file);
xWorkbook = new XSSFWorkbook(in);
a1 = getValue1(r1 + day, c1 + 1, 1).add(
getValue1(r1 + day, c1 + 2, 1));
if (0 != getValue1(r1 + day, c1, 1).compareTo(a1)) {
return error("支付机构汇总报表<" + fileName + ">业务系统借记客户资金金额:"
+ day + "日错误");
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return pass("支付机构汇总报表<" + fileName + ">业务系统借记客户资金金额:" + day + "日正确");
} |
60a54828-b545-44d6-8dec-32dcec23249e | 5 | public void populateWithNatives(int tribeID) {
float meadowed = (1 + totalFertility) / 2f ;
final int
numMajorHuts = (int) ((meadowed * numMajor) + 0.5f),
numMinorHuts = (int) ((meadowed * numMinor) + 0.5f) ;
I.say("Major/minor huts: "+numMajorHuts+"/"+numMinorHuts) ;
final Base base = world.baseWithName("Natives", true, true) ;
for (int n = numMajorHuts + numMinorHuts ; n-- > 0 ;) {
final int SS = World.SECTOR_SIZE ;
Coord pos = findBasePosition(null, 1) ;
I.say("Huts site at: "+pos) ;
final Tile centre = world.tileAt(
(pos.x + 0.5f) * SS,
(pos.y + 0.5f) * SS
) ;
final boolean minor = n < numMinorHuts ;
int maxHuts = (minor ? 4 : 2) + Rand.index(3) ;
final Batch <Venue> huts = new Batch <Venue> () ;
final NativeHall hall = NativeHut.newHall(tribeID, base) ;
Placement.establishVenue(hall, centre.x, centre.y, true, world) ;
if (hall.inWorld()) huts.add(hall) ;
while (maxHuts-- > 0) {
final NativeHut r = NativeHut.newHut(hall) ;
Placement.establishVenue(r, centre.x, centre.y, true, world) ;
if (r.inWorld()) huts.add(r) ;
}
populateNatives(huts, minor) ;
}
} |
07add7d3-f2e5-4b82-902a-b00d1f21920b | 5 | public MyList findTwoTilesMoves(String player) {
// Check if player is valid (so we don't have to worry about
// null pointers later).
if (player == null || ! (player.equals("red") ||
player.equals("blue")))
return null;
MyList moves = new MyList();
// Iterate over all Hexpos's
Set set = owner.keySet();
Iterator it = set.iterator();
while(it.hasNext()) {
Hexpos hp = (Hexpos) it.next();
MyList movesTo = findTwoTilesMovesTo(hp, player);
if (movesTo != null)
moves.addAll(movesTo);
}
return moves;
} |
47d4a864-fef1-4c2b-8b00-ba49888cdd3f | 6 | private Page getPagePotentiallyNotInitedByRecursiveIndex(int globalIndex) {
int globalIndexSoFar = 0;
int numLocalKids = kidsPageAndPages.size();
for (int i = 0; i < numLocalKids; i++) {
Object pageOrPages = getPageOrPagesPotentiallyNotInitedFromReferenceAt(i);
if (pageOrPages instanceof Page) {
if (globalIndex == globalIndexSoFar)
return (Page) pageOrPages;
globalIndexSoFar++;
} else if (pageOrPages instanceof PageTree) {
PageTree childPageTree = (PageTree) pageOrPages;
childPageTree.init();
int numChildPages = childPageTree.getNumberOfPages();
if (globalIndex >= globalIndexSoFar && globalIndex < (globalIndexSoFar + numChildPages)) {
return childPageTree.getPagePotentiallyNotInitedByRecursiveIndex(
globalIndex - globalIndexSoFar);
}
globalIndexSoFar += numChildPages;
}
}
return null;
} |
3384a472-a0df-4f3c-a772-f00b2695256c | 3 | public void printGrid()
{
for (int i = 0; i < grid.length; i++)
{
for (int j = 0; j < grid[i].length; j++)
{
if (grid[i][j] != null)
System.out.print(grid[i][j].getActive() + " " + i + " " + j);
}
System.out.println();
}
System.out.println();
System.out.println();
} |
556dc889-d999-4374-a9bb-9c5f40593840 | 1 | public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject jo = new JSONObject();
JSONTokener x = new JSONTokener(string);
while (x.more()) {
String name = Cookie.unescape(x.nextTo('='));
x.next('=');
jo.put(name, Cookie.unescape(x.nextTo(';')));
x.next();
}
return jo;
} |
f32370ec-b340-49dc-817c-af9282f95214 | 6 | public Image getPlayerImage(){
StringBuilder playerImg;
switch(facingDirection){
case EAST:
playerImg = new StringBuilder("playerEast");
break;
case NORTH:
playerImg = new StringBuilder("playerNorth");
break;
case SOUTH:
playerImg = new StringBuilder("playerSouth");
break;
case WEST:
playerImg = new StringBuilder("playerWest");
break;
default:
playerImg = new StringBuilder("playerSouth");
break;
}
//String healthMod = "";
String healthMod = health <= 3 && health >= 0 ? Integer.toString(health) : "3";
playerImg.append(healthMod + ".png");
ImageIcon img = new ImageIcon(playerImg.toString());
this.player=img.getImage();
return this.player;
} |
20892829-815d-4b71-8129-4dc296b483c1 | 0 | @Override
public void setJarName(String jarName) {
this.jarName = jarName;
} |
da0ba611-e207-47d0-9a2d-477d83c99b69 | 6 | private void createTextStyleAttributes(VariableMap varMap) {
//Dynamic
if (schemaParser != null) {
Map<String, VariableMap> typeAttrTemplates = schemaParser.getTypeAttributeTemplates();
if (typeAttrTemplates != null) {
String schemaTypeName = "TextStyleType";
//varMap.setType(schemaTypeName);
VariableMap template = typeAttrTemplates.get(schemaTypeName);
if (template != null) {
for (int i=0; i<template.getSize(); i++)
varMap.add(template.get(i).clone());
}
}
}
//Hard coded
else {
List<Variable> list = getTextStyleList();
if (list != null) {
for (int i=0; i<list.size(); i++)
varMap.add(list.get(i).clone());
}
}
} |
34977e9f-b29c-4274-a722-7b24fc3c6aec | 1 | public static void handleAway(String reason) {
if ( reason.isEmpty() )
reason = "Prostě se flákam.";
getCurrentServerTab().getConnection().setAway(reason);
clearInput();
} |
a455299f-2bee-4bca-8f53-f6aad00d3bb5 | 9 | public String multiply(String num1, String num2) {
if (num1 == null || num1.length() == 0
|| num2 == null || num2.length() == 0
|| num1.equals("0") || num2.equals("0")) {
return "0";
}
int[] res = mult(num1.toCharArray(), num2.toCharArray());
StringBuilder buf = new StringBuilder();
int i;
for (i = res.length - 1; i >= 0 && res[i] == 0; i --);
for (; i >= 0; i --) {
buf.append(res[i]);
}
return buf.toString();
} |
5c021322-cf5d-4119-a1c7-b68d92b6d627 | 8 | public static final String getLevelString(final int level) {
switch(level) {
case SyslogConstants.LEVEL_DEBUG: return "DEBUG";
case SyslogConstants.LEVEL_INFO: return "INFO";
case SyslogConstants.LEVEL_NOTICE: return "NOTICE";
case SyslogConstants.LEVEL_WARN: return "WARN";
case SyslogConstants.LEVEL_ERROR: return "ERROR";
case SyslogConstants.LEVEL_CRITICAL: return "CRITICAL";
case SyslogConstants.LEVEL_ALERT: return "ALERT";
case SyslogConstants.LEVEL_EMERGENCY: return "EMERGENCY";
default:
return "UNKNOWN";
}
} |
70cdc145-76aa-4206-884c-30380ef881d6 | 2 | public String listWikis() {
String list = "Available wikis: ";
Set<String> wikiNames = this.wikis.keySet();
if (wikiNames.isEmpty()) {
return "(No wikis are available right now.)";
}
for (String wikiName : this.wikis.keySet()) {
list += wikiName + ", ";
}
return list.substring(0, list.length() - 2);
} |
953f2769-009b-40f3-92f3-11cc379fbf5b | 7 | public double cg(double delta) {
int n = model.getNumberOfAtoms();
if (n <= 1)
return -1.0;
if (congvxAtLastStep == null || congvyAtLastStep == null)
initCongArrays();
double potential = 0.0;
double scalar = 1.0;
double sumgrad = 0.0;
double tempx = 0.0, tempy = 0.0;
for (int i = 0; i < n; i++)
sumgrad += model.atom[i].fx * model.atom[i].fx + model.atom[i].fy * model.atom[i].fy;
scalar = -sumgrad / modeGradientAtLastStep;
modeGradientAtLastStep = sumgrad;
sumgrad = 0.0;
for (int i = 0; i < n; i++) {
tempx = scalar * congvxAtLastStep[i] + model.atom[i].fx;
tempy = scalar * congvyAtLastStep[i] + model.atom[i].fy;
congvxAtLastStep[i] = tempx;
congvyAtLastStep[i] = tempy;
sumgrad += congvxAtLastStep[i] * congvxAtLastStep[i] + congvyAtLastStep[i] * congvyAtLastStep[i];
}
model.putInBounds();
sumgrad = Math.sqrt(sumgrad);
for (int i = 0; i < n; i++) {
if (!model.atom[i].isMovable())
continue;
congvxAtLastStep[i] /= sumgrad;
congvyAtLastStep[i] /= sumgrad;
model.atom[i].rx = model.atom[i].rx + congvxAtLastStep[i] * delta;
model.atom[i].ry = model.atom[i].ry + congvyAtLastStep[i] * delta;
}
potential = model.computeForce(-1);
return potential;
} |
5f1e9195-b190-4b9b-9825-1c65b689ec69 | 4 | public boolean isSlaComplient(Long timeUnits){
if(this.sla == null){
throw new AutomatonException("no Service Level Agreement defined");
}
return isTimeComplient(timeUnits) && isRateComplient(timeUnits) && isProbabilityComplient() && isTimeComplient(timeUnits);
} |
47ab93b7-b939-4edb-8847-de0edde4232d | 1 | @Override
public void mouseExited(MouseEvent e) {
try {
setImg(ImageIO.read(new File("img/button/button.png")));
} catch (IOException ex) {
ex.printStackTrace();
}
} |
65c4c00d-871f-4857-869e-3365976bad90 | 9 | public Object[][] getCells() {
int i;
int n;
Vector<Object[]> result;
Object[] row;
int rowCount;
boolean proceed;
initialize();
result = new Vector<Object[]>();
try {
// do know the number of rows?
rowCount = getRowCount();
if (rowCount == -1) {
rowCount = getMaxRows();
proceed = m_ResultSet.next();
}
else {
proceed = m_ResultSet.first();
}
if (proceed) {
i = 0;
while (true) {
row = new Object[getColumnCount()];
result.add(row);
for (n = 0; n < getColumnCount(); n++) {
try {
// to get around byte arrays when using getObject(int)
if (getColumnClasses()[n] == String.class)
row[n] = m_ResultSet.getString(n + 1);
else
row[n] = m_ResultSet.getObject(n + 1);
}
catch (Exception e) {
row[n] = null;
}
}
// get next row, if possible
if (i == rowCount - 1) {
break;
}
else {
// no more rows -> exit
if (!m_ResultSet.next())
break;
}
i++;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return result.toArray(new Object[result.size()][getColumnCount()]);
} |
eb75ac4a-d1cf-44c1-a7c3-87050dd62057 | 4 | public int compareTo(Point2D that) {
if (this.y < that.y) return -1;
if (this.y > that.y) return +1;
if (this.x < that.x) return -1;
if (this.x > that.x) return +1;
return 0;
} |
ffba8d52-f631-4886-bcc4-1936259929b8 | 4 | @Override
public void run() {
try{
Random rnd=new Random();
while(true)
{
Integer item=scheduledQueue.retrieveItem();
if(item==null){
//There is nothing to consume , producer is too slow or even dead
if(!isAnyProducerAlive()){
break;// there is no alive producers
}
}else{
//We consume successfully an item
totalConsumedItemsCounter++;
System.out.println("Consumer ["+name+"] consumed <<< '"+item+"'");
}
Thread.sleep(rnd.nextInt(50));
}
}catch(InterruptedException e){
System.out.println("Consumer process "+name+" is killed");
}
//Print statistics
System.out.println("Number of items consumed by process "+name+" is # "+totalConsumedItemsCounter);
} |
7433d42c-c1f3-4c20-9f66-1be899620e0c | 6 | public String getRoomText(){
if (currentRoom==RoomState.BLOOD)
return "Blood!";
else if (currentRoom==RoomState.EMPTY)
return "Nothing in this room...";
else if (currentRoom==RoomState.GOOP)
return "There's goop on the ground!";
else if (currentRoom==RoomState.PIT)
return "You fell to your doom!";
else if (currentRoom == RoomState.SLIME)
return "SLIIIME!";
else if (currentRoom==RoomState.WUMPUS)
return "The Wumpus caught ye!";
else return "Oh noes, an error is occured! #&*(&#!";
} |
ed94dd13-fe31-43ca-a672-33f9a0f958a2 | 1 | public void close() throws IOException {
if (br != null) {
br.close();
br = null;
}
} |
246c4a46-d1b2-45ce-bc17-fbcd3acc15d6 | 3 | public JetrisGrid(final Point dimension) {
super(dimension, TETRIS_GRID_BACKGROUND_COLOR, TETRIS_GRID_EMPTY_BORDER);
setPreferredSize(new Dimension(10*CELL_H, 25*CELL_H));
lines = 0;
score = 0;
level = 1;
try{
hiScores = HiScore.load(DAT_FILE);
} catch (Exception e) {
hiScores = new HiScore[3];
for (int i = 0; i < hiScores.length; i++) {
hiScores[i] = new HiScore();
hiScores[i].name = "<empty>";
}
File f = new File(DAT_FILE);
try {
HiScore.write(hiScores, f);
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, "Could not load HiScore!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
listeners = new ArrayList<JetrisGridEventsListener>();
} |
89f2a61c-73c3-45ff-95e6-0ad54f7aefc1 | 0 | @Override
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
} |
f2dd1478-4c45-4854-9b45-1f1525bf756f | 0 | public JButton getjButtonNext() {
return jButtonNext;
} |
01d845d5-d6af-499c-af17-e538d94e74c5 | 7 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final Room targetR=mob.location();
if(targetR==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
int chance=0;
if((mob.location().domainType()&Room.INDOORS)>0)
chance-=25;
final boolean success=proficiencyCheck(mob,chance,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,targetR,this,somanticCastCode(mob,targetR,auto),auto?"":L("^S<S-NAME> commune(s) with <S-HIS-HER> natural surroundings.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
final int radius=3 + super.getXLEVELLevel(mob) + super.getXMAXRANGELevel(mob);
final List<Room> rooms=CMLib.tracking().getRadiantRooms(mob.location(), CMLib.tracking().newFlags(), radius);
final List<String> stuff=new Vector<String>();
communeWithThisRoom(mob,mob.location(),stuff);
for(final Room R : rooms)
communeWithThisRoom(mob,R,stuff);
mob.tell(L("Your surroundings show the following natural signs: @x1.",CMLib.english().toEnglishStringList(stuff.toArray(new String[0]))));
}
}
else
beneficialVisualFizzle(mob,targetR,L("<S-NAME> attempt(s) to commune with nature, and fail(s)."));
// return whether it worked
return success;
} |
8941ee57-8b47-4fe8-9180-bcb799e601d4 | 8 | private <V, E> void testMapping(final JGraphXAdapter<V, E> graph) {
// Edges
HashMap<mxICell, E> cellToEdgeMap = graph.getCellToEdgeMap();
HashMap<E, mxICell> edgeToCellMap = graph.getEdgeToCellMap();
// Test for null
if (cellToEdgeMap == null) {
fail("GetCellToEdgeMap returned null");
}
if (edgeToCellMap == null) {
fail("GetEdgeToCellMap returned null");
}
// Compare keys to values
if (!compare(edgeToCellMap.values(), cellToEdgeMap.keySet())) {
fail("CellToEdgeMap has not the "
+ "same keys as the values in EdgeToCellMap");
}
if (!compare(cellToEdgeMap.values(), edgeToCellMap.keySet())) {
fail("EdgeToCellMap has not the "
+ "same keys as the values in CellToEdgeMap");
}
// Vertices
HashMap<mxICell, V> cellToVertexMap = graph.getCellToVertexMap();
HashMap<V, mxICell> vertexToCellMap = graph.getVertexToCellMap();
// Test for null
if (cellToVertexMap == null) {
fail("GetVertexToCellMap returned null");
}
if (vertexToCellMap == null) {
fail("GetCellToVertexMap returned null");
}
// Compare keys to values
if (!compare(vertexToCellMap.values(), cellToVertexMap.keySet())) {
fail("CellToVertexMap has not the same "
+ "keys as the values in VertexToCellMap");
}
if (!compare(cellToVertexMap.values(), vertexToCellMap.keySet())) {
fail("VertexToCellMap has not the same "
+ "keys as the values in CellToVertexMap");
}
} |
ee9d9e5d-7c08-440a-be49-718699973feb | 0 | public void setFinishedById(Integer id, boolean isFinished) {
String query = "update Task set isFinished = :isFinished where id = :taskId";
sessionFactory.getCurrentSession().createQuery(query)
.setInteger("taskId", id)
.setBoolean("isFinished", isFinished)
.executeUpdate();
} |
22aa842f-89af-4dd1-941e-7e42362722d2 | 7 | public static Integer GetBinaryValue(int length, String string)
{
if(string.length() != length)
{
System.out.println("LENGHT != STRING SIZE");
return 1 / 0;
}
if(length % 2 != 0)
{
System.out.println("LENGTH % 2 IS NOT 0");
return 1 / 0;
}
Character[] chars = StringToCharArray(string);
for(char ch : chars)
{
if(ch != '0' && ch != '1')
{
System.out.println("A CHARACTER ISN'T 0 OR 1");
return 1 / 0;
}
}
chars = Reverse(chars);
int value = 0;
int val = 1;
for(char nil : chars)
{
if(nil == '1')
value += val;
val *= 2;
}
return value;
} |
3d17ca85-c687-4caa-bc19-6cd1f28cef9e | 1 | @Override
public void undo(UndoQueueEvent e) {
if (e.getDocument() == Outliner.documents.getMostRecentDocumentTouched()) {
calculateEnabledState(e.getDocument());
}
} |
eba10b63-7790-4680-a8dd-bd35a06e78d4 | 6 | @Override
public void insert(Card data) {
Node<Card> currNode;
Node<Card> prevNode;
Node<Card> aNode = new Node<Card>(data);
if (head == null) {
head = aNode;
head.setData(data);
} else {
currNode = head;
prevNode = head;
// loop till you find the right place
while (currNode != null && data.compareTo(currNode.getData()) >= 0) {
if (data.compareTo(currNode.getData()) == 0) {
// Since we allow for duplicates, if they are equal then we
// will
// simply break out of the loop and put it before the
// currNode.
break;
} else {
// parse further along in the list to find the right
// position
prevNode = currNode;
currNode = currNode.getNext();
}
}// end while
// data belongs right here
if (currNode == head) {
// data belongs before current head
aNode.setNext(head);
head = aNode;
} else if (currNode == null) {
// data belongs after last node
prevNode.setNext(aNode);
} else {
// belongs between two nodes
aNode.setNext(currNode);
prevNode.setNext(aNode);
}
}
} |
8b14d024-a022-4c51-b38a-09b61fd3911d | 5 | public static void main(String[] args){
long max_p = 0;
long max_triangle = 0;
for(int p = 12; p <= 1000; p++){
int triangle_count = 0;
for(int c = (3 / p); c <= p; c++){
for(int a = 3; a <= (p - c) / 2; a++){
int b = p - c - a;
if(Math.pow(a, 2) + Math.pow(b, 2) == Math.pow(c, 2)){
System.out.println("a = " + a + ", b = " + b + ", c = " + c);
triangle_count++;
}
}
}
if(max_triangle < triangle_count){
max_triangle = triangle_count;
max_p = p;
}
}
System.out.println("Answer:" + max_p);
} |
ba06699d-b63d-42db-965c-af157d42af1c | 8 | public void combineTwoFiles() {
try {
//make a temporal file to contain both index txt file and memory hashmap
File newFile = new File(TEMPORAL_FILEPATH);
//if the file doesn't exist, make a new file
if (!newFile.exists()) {
newFile.createNewFile();
}
//make FileWrite and BufferedWrite to prepare for writing
FileWriter fw = new FileWriter(newFile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
//make BufferedReader to read from index txt file
BufferedReader br = new BufferedReader(new FileReader(FILEPATH));
String line;
//read in line by line
while ((line = br.readLine()) != null) {
for(int i = 0 ; i < insertWordList.size() ; i++){
String insertWord = insertWordList.get(i);
if(insertWord.compareTo(line) > 0) break;
//if insertWord equals to line, combine them.
else if(insertWord.compareTo(line) == 0) break;
else{
bw.write(insertWord + "\n");
insertWordList.remove(insertWord);
}
}//end for
bw.write(line + "\n");
}//end while
//close BufferedReader and BufferedWriter
br.close();
bw.close();
//delete oldfile
File oldFile = new File(FILEPATH);
if(oldFile.delete()){
System.out.println(oldFile.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
//rename "newfile" to "oldfile"
File fromThisName =new File(TEMPORAL_FILEPATH);
File toThisName =new File(FILEPATH);
if(fromThisName.renameTo(toThisName)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
} catch (IOException e) {
e.printStackTrace();
}//end try and catch
}//end Combine |
9bb76420-e309-467d-a0ae-000b1af1fdba | 8 | static private int jjMoveStringLiteralDfa3_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(1, old0);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(2, active0);
return 3;
}
switch(curChar)
{
case 97:
return jjMoveStringLiteralDfa4_0(active0, 0x4000L);
case 100:
if ((active0 & 0x20000L) != 0L)
return jjStartNfaWithStates_0(3, 17, 3);
break;
case 111:
return jjMoveStringLiteralDfa4_0(active0, 0x400L);
case 112:
return jjMoveStringLiteralDfa4_0(active0, 0x10000L);
case 116:
return jjMoveStringLiteralDfa4_0(active0, 0x2800L);
default :
break;
}
return jjStartNfa_0(2, active0);
} |
be73f751-9284-41a9-a3c0-7f726e40a10f | 8 | public NO findLeading( String name ) {
/*
OBS experimentell metod
klarar inmatning typ "bevä" som ger Beväringsgatan
man måste mata in tillräckligt många tecken för att det skall vara
ett unikt namn (och trycka return)
detta är dyrbart och inte optimalt så använd den inte i onödan
tex inte när du bygger upp grafen
behövs egentligen inte för labben, find ovan räcker
@TODO felokänslig typ "bevaring" ger Beväringsgatan
*/
// make sure that name is lower case
//name = name.toLowerCase();
// try to lookup the name
NO tmpNode = fromName.get(name);
if ( tmpNode != null ) { // direct hit
return tmpNode;
} else {
// here is the challenge
// we didn't find the name, try to find a substring
// this is expensive...
// we want to create an array of the available stations
// make a string of the map
String tmp = fromName.toString();
// take away {} in the beginning and the end
tmp = tmp.substring(1, tmp.length()-1);
// split the string
String[] tmpArr = tmp.split(", ");
// now we have an array with the strings twice
// like this "station=station"
// make it an array with only the station i.e. "station"
for (int i=0; i< tmpArr.length; i++) {
tmpArr[i] = tmpArr[i].split("=")[1];
}
// make sure data is sorted since a TreeMap can't sort rigth!!!!
// TODO fix this
Arrays.sort(tmpArr);
/*
Now we do a binary search for the station. We don't expect to find
it but we get the position where it should be.
So we can search in the neighbourhood .
@return index of the search key, if it is contained in the list; otherwise,
(-(insertion point) - 1). (So this is what we expect to get.)
The insertion point is defined as the point
at which the key would be inserted into the list: the index of the
first element greater than the key, or list.size(), if all elements
in the list are less than the specified key. Note that this guarantees
that the return value will be >= 0 if and only if the key is found.
*/
//name = name.toLowerCase();
int pos = Arrays.binarySearch(tmpArr, name);
pos = Math.abs(pos+1);
// ===========================================================
/* Debug start
// print tmpArr with its position in the array
int i = 0;
System.out.println("tmpArr= ");
for (String p : tmpArr ) {
System.out.println( "" + i++ + " *" + p + "*");
}
System.out.println("****" + pos); // debug
if ( pos<tmpArr.length ) {
System.out.println(tmpArr[pos]); // debug
}
System.out.println("name= " + name); // debug
*/ //Debug end
// ===========================================================
int l = name.length();
if ( pos>=tmpArr.length // outside table
// long input strings are not ok i.e name="beväqewfqwefqwef"
|| l > tmpArr[pos].length() ) {
return null;
}
/*
Om vi nu antar att name="ull" och att tabellen ser ut så här
...
116 *UlleviNorra*
117 *UlleviSödra*
...
132 *ÖstraSjukhuset*
....
så kommer pos att vara = 116, första större än "ull"
om tmp[pos] == "ull" och tmp[pos+1] != "ull" så har vi en träff
men om tmp[pos] == "ull" och tmp[pos+1] == "ull" så kan vi inte skilja på 116/117.
om det inte är den sista (dvs pos==tmpArr.length-1) för då har vi ändå en träff.
Sista alternativet är om vi söker efter "SahlgrenskaHuvuden"
och har tabellen
95 *SahlgrenskaHuvudentre*
96 *Saltholmen*
då kollar vi så längden på det vi söker inte är större än innehållet i
nästa position innan vi jämför nästa position (l>tmpArr[pos+1].length)
*/
if ( tmpArr[pos].substring(0, l).equals(name) // found?
&& ( pos==tmpArr.length-1 // sista?
|| l>tmpArr[pos+1].length() // nästa station för "lång"?
|| !(tmpArr[pos+1].substring(0, l).equals(name))) // nästa lika?
) {
return find(tmpArr[pos]);
} else {
return null;
}
}
} |
6e8f53f0-eb55-404d-b227-a367184fffcb | 6 | @Override
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
if (kirjaudutaankoUlos(request)) {
kirjauduUlos(request, response);
} else if (onkoKirjautunut(request, response)) {
try {
if (Varaus.haeAjatLaakariIdlla(getKayttaja().getId()).isEmpty()) {
request.setAttribute("tyotehtavienTila", "Sinulla ei ole tyotehtäviä.");
avaaSivunakyma(request, response, "tyotehtavat", "laakarinviikkoaikataulu", "potilaat", "web/tyotehtavat.jsp");
} else {
if (napinPainallus("kuittaus", request)) {
Varaus.varausSuoritettu(Integer.parseInt(request.getParameter("kuittaus")));
lahetaTyotehtavanTiedotLisaaPotilasRaporttiServletille(request);
response.sendRedirect("lisaapotilasraportti");
} else {
List<Varaus> tyot = Varaus.haeAjatLaakariIdlla(getKayttaja().getId());
request.setAttribute("tyot", tyot);
muunnaPaivamaaratSuomalaisiksi(request, tyot);
List<Oirekuvaus> l = new ArrayList<Oirekuvaus>();
for (Varaus tyot1 : tyot) {
Oirekuvaus oire = Oirekuvaus.haeOirekuvausVarausIdlla(tyot1.getId());
l.add(oire);
}
request.setAttribute("oireet", l);
avaaSivunakyma(request, response, "tyotehtavat", "laakarinviikkoaikataulu", "potilaat", "web/tyotehtavat.jsp");
}
}
} catch (Exception e) {
naytaVirheSivu("Lääkärin työtehtävien näyttäminen epäonnistui.", request, response);
}
}
} |
1675f662-94cf-4daf-8dea-762144406075 | 7 | private void updateEnemyPositions() {
nextRow = 0;
for(int i = 0; i < enemys.length; i++) {
for(int j = 0; j < enemys[i].length; j++) {
if(!enemys[i][j].isAlive()) {
continue;
}
//Update all positions and if one reaches the bound the variable is set
nextRow |= enemys[i][j].move(ENEMY_MOVEMENT_SPEED, this.getWidth());
}
}
if(nextRow == 1 || nextRow == -1) {
for(int i = 0; i < enemys.length; i++) {
for(int j = 0; j < enemys[i].length; j++) {
enemys[i][j].oneRowDown(nextRow);
enemys[i][j].move(ENEMY_MOVEMENT_SPEED * 2, this.getWidth());
}
}
}
} |
836b1c64-f043-41f4-ad8f-35cce4e7542f | 2 | @Override
public String toString() {
String name = getName();
String append = "";
if(name != null && !name.equals("")) {
append = "(\"" + this.getName() + "\")";
}
return "TAG_Byte" + append + ": " + value;
} |
f9530e9b-4379-4622-be40-d3475563bb34 | 4 | @Override
public void mouseClicked(MouseEvent e) {
System.out.println("CLICKED");
if(!isClicked){
for(Rectangle rec : Rectangle.moveList){
if (rec.isIn(e.getX(),e.getY()) && (rec instanceof Field)){
isClicked = true;
Field.focusedField=(Field)rec;
}
}
}else{
Field.focusedField.setX(e.getX());
Field.focusedField.setY(e.getY());
isClicked=false;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.