method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
140efadd-cbdb-4ba7-8b54-b5ee29b4233e | 9 | public static void testCorrectness(boolean isBWT)
{
System.out.println("\nBWT"+(!isBWT?"S":"")+" Correctness test");
// Test behavior
for (int ii=1; ii<=20; ii++)
{
System.out.println("\nTest "+ii);
int start = 0;
byte[] buf1;
Random rnd = new Random();
if (ii == 1)
{
buf1 = "mississippi".getBytes();
}
else if (ii == 2)
{
buf1 = "3.14159265358979323846264338327950288419716939937510".getBytes();
}
else if (ii == 3)
{
buf1 = "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES".getBytes();
}
else
{
buf1 = new byte[128];
for (int i=0; i<buf1.length; i++)
{
buf1[i] = (byte) (65 + rnd.nextInt(4*ii));
}
}
byte[] buf2 = new byte[buf1.length];
byte[] buf3 = new byte[buf1.length];
SliceByteArray sa1 = new SliceByteArray(buf1, 0);
SliceByteArray sa2 = new SliceByteArray(buf2, 0);
SliceByteArray sa3 = new SliceByteArray(buf3, 0);
ByteTransform bwt = (isBWT) ? new BWT() : new BWTS();
String str1 = new String(buf1, start, buf1.length-start);
System.out.println("Input: "+str1);
sa1.index = start;
sa2.index = 0;
bwt.forward(sa1, sa2);
String str2 = new String(buf2);
System.out.print("Encoded: "+str2);
if (isBWT)
{
int primaryIndex = ((BWT) bwt).getPrimaryIndex();
System.out.println(" (Primary index="+primaryIndex+")");
((BWT) bwt).setPrimaryIndex(primaryIndex);
}
else
{
System.out.println("");
}
sa2.index = 0;
sa3.index = start;
bwt.inverse(sa2, sa3);
String str3 = new String(buf3, start, buf3.length-start);
System.out.println("Output: "+str3);
if (str1.equals(str3) == true)
System.out.println("Identical");
else
{
System.out.println("Different");
System.exit(1);
}
}
} |
7f651f80-b1c6-44e8-9706-7f12fbc970d3 | 2 | public static int maximun(int ar[]) {
int max = ar[0];
System.out.print("Array Is :\t");
System.out.print(ar[0] + " ");
for (int i = 1; i < ar.length; i++) {
System.out.print(ar[i] + " ");
if (max < ar[i]) {
max = ar[i];
}
}
System.out.println();
return max;
} |
1204e99d-4957-4645-9575-f2b3721fe419 | 1 | public Type getSuperType() {
if (elementType instanceof IntegerType)
return tRange(tObject, this);
else
return tRange(tObject,
(ReferenceType) tArray(elementType.getSuperType()));
} |
8fc165d8-7869-4ab6-87b0-5d0fa8a9f044 | 5 | private Scenery[][] loadRandomMap(GameMap g, int multiplier, int xOfMap, int yOfMap,
int levelsDeep, TextDisplay textDisplay) throws Exception {
String path = PATH_TO_MAPS;
if (notSpawnedPlayerCount > 2) {
path += "PlayerMaps" + File.separator;
initPlayerMaps();
} else {
initMapLoader();
}
int index = new Random().nextInt(numOfFiles);
// create an input stream from the class loader and make an input stream
// reader from that and make a buffered reader from the input stream reader
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getClassLoader()
.getResourceAsStream(path + mapFileNames[index])));
Scenery[][] data = new Scenery[cellHeight][cellWidth];
String currentLine;
int y = 0;
while ((currentLine = br.readLine()) != null) {
String sceneryChars[] = currentLine.split(" ");
for (int x = 0; x < sceneryChars.length; x++) {
String sceneryChar = sceneryChars[x];
Scenery scenery = sceneryFactory.getScenery(sceneryChar, x + xOfMap * cellWidth, y + yOfMap
* cellHeight, g, multiplier, levelsDeep, textDisplay);
data[y][x] = scenery;
if (sceneryChar.equals("P")) {
possibleSpawnPoints.add(new Point(x + xOfMap * cellWidth, y + yOfMap * cellHeight));
spawnedPlayer = true;
}
}
y++;
}
if (!spawnedPlayer) {
notSpawnedPlayerCount++;
}
br.close();
return data;
} |
c642c57f-c6f5-4a86-b18c-8b870a8fe39d | 8 | public Response serve( String uri, String method, Properties header, Properties parms, String data )
{
try{
String response_string=null;
if(data!=null){
System.out.println(DateFormat.getTimeInstance(DateFormat.FULL).format(Calendar.getInstance().getTime()));
System.out.println("Command: " + data);
String command=getCommand(data);
if(command==null){
throw(new IllegalArgumentException("Unknown message format"));
}else if(command.equals("START")){
response_string="READY";
commandStart(data);
}else if(command.equals("PLAY")){
response_string=commandPlay(data);
/* }else if(command.equals("replay")){
response_string=commandReplay(data);*/
}else if(command.equals("STOP")){
response_string="DONE";
commandStop(data);
}else{
throw(new IllegalArgumentException("Unknown command:"+command));
}
}else{
throw(new IllegalArgumentException("Message is empty!"));
}
System.out.println(DateFormat.getTimeInstance(DateFormat.FULL).format(Calendar.getInstance().getTime()));
System.out.println("Response:"+response_string);
if(response_string!=null && response_string.equals("")) response_string=null;
return new Response( HTTP_OK, "text/acl", response_string );
}catch(IllegalArgumentException ex){
System.err.println(ex);
ex.printStackTrace();
return new Response( HTTP_BADREQUEST, "text/acl", "NIL" );
}
} |
e65d8761-1069-4ea3-954c-5c211f8c9939 | 8 | @Override
public boolean equals(Object obj) {
if(!(obj instanceof Anime)) {
return false;
}
Anime anime = (Anime)obj;
return (anime.episodes == episodes && anime.id == id &&
anime.score == score && anime.title.equals(title) &&
anime.type.equals(type) && anime.watched_episodes == watched_episodes &&
anime.watched_status.equals(watched_status) &&
anime.url.equals(url));
} |
947d03bc-630d-498f-ad4d-8f5e3b428ed3 | 6 | public Loop(List<String> identifiers, List<String> values) {
this.rows = new ArrayList<Map<String,String>>();
int identSize = identifiers.size();
// TODO check that the identifiers are unique
int valIndex = 0;
// don't want to loop endlessly if there's no keys
if(identSize == 0 && values.size() > 0) {
throw new RuntimeException("Star Loop with > 0 values must have > 0 identifiers");
}
while(true) {
// takes care of the case that the values are empty
if(valIndex == values.size()) {
break;
} else if (values.size() - valIndex < identSize) {
throw new RuntimeException("Star Loop must have a number of values that's an integer multiple of the number of identifiers");
}
Map<String, String> row = new HashMap<String, String>();
for(int j = 0; j < identSize; j++, valIndex++) {
row.put(identifiers.get(j), values.get(j));
}
this.rows.add(row);
}
} |
d947405a-047f-43e5-a30e-563ca8824428 | 2 | @SuppressWarnings("unchecked")
public E previous() {
if (nextIndex == 0) {
throw new NoSuchElementException();
}
if(next != null) {
lastReturned = next = next.previous;
} else {
lastReturned = next = tail.previous; // index > 0 => not tail is not head.
}
nextIndex--;
checkForComodification();
return (E) lastReturned.object;
} |
c40dd1f3-bcc7-4e7c-b224-5c52e646eb9e | 5 | public void imprimirRelatorio(int argumento1,int argumento2, String nomedorelatorio, String nomedocampoparaarguemntacao, String nomedegravacaodorelatorio) throws IOException, JRException, ClassNotFoundException, Exception {
ServletOutputStream servletOutputStream;
File arquivoGerado;
System.out.println("Entrou no Metodo");
HashMap parameters = new HashMap();
try {
FacesContext facesContext = FacesContext.getCurrentInstance();
String caminhorelatorio = facesContext.getExternalContext().getRealPath("relatorio");
System.out.println(nomedocampoparaarguemntacao + " e argumento "+argumento1);
parameters.put(nomedocampoparaarguemntacao, argumento1);
System.out.println("ano e argumento "+argumento2);
parameters.put("ano", argumento2);
ServletContext scontext = (ServletContext) facesContext.getExternalContext().getContext();
JasperPrint jasperPrint = JasperFillManager.fillReport(scontext.getResourceAsStream("/relatorio/" + nomedorelatorio + ".jasper"), parameters, getConn());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JRPdfExporter exporter = new JRPdfExporter();
String caminhoArquivoRelatorio = caminhorelatorio + File.separator + nomedegravacaodorelatorio + ".pdf";
arquivoGerado = new File(caminhoArquivoRelatorio);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE, arquivoGerado);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
exporter.exportReport();
arquivoGerado.deleteOnExit();
System.out.println("Fim da exportação");
byte[] bytes = baos.toByteArray();
System.out.println("Tamanho: " + bytes.length + " Bytes");
if (bytes != null && bytes.length > 0) {
System.out.println("Escrevendo bytes!");
HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "inline; filename=" + nomedegravacaodorelatorio + ".pdf");
response.setContentLength(bytes.length);
servletOutputStream = response.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
servletOutputStream.write(bytes, 0, bytes.length);
servletOutputStream.flush();
servletOutputStream.close();
facesContext.renderResponse();
facesContext.responseComplete();
System.out.println("Relatório gerado!");
}
} catch (IOException ioe) {
ioe.printStackTrace();
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Falta do arquivo para geração do relatório!", null);
FacesContext.getCurrentInstance().addMessage("add", msg);
} catch (JRException jreE) {
jreE.printStackTrace();
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro no Ireport!", null);
FacesContext.getCurrentInstance().addMessage("add", msg);
} catch (Exception cnfe) {
cnfe.printStackTrace();
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro de Biblioteca que não Existe!", null);
FacesContext.getCurrentInstance().addMessage("add", msg);
}
} |
6463c47e-f93d-4ba0-8f49-cc405d996590 | 8 | public Integer getBiggestBorrower() {
Integer id = -1;
Integer max = 0;
Map<Integer, Integer> total = new HashMap<Integer, Integer>();
for (Integer stockId : this.stock.keySet()) {
Map<Integer, Integer> currentStock = stock.get(stockId)
.getBookingTotals();
for (Integer borrowerId : currentStock.keySet()) {
if (total.get(borrowerId) == null) {
total.put(borrowerId, currentStock.get(borrowerId));
} else {
if (currentStock.get(borrowerId) != null) {
total.put(borrowerId, total.get(borrowerId)
+ currentStock.get(borrowerId));
}
}
}
}
for (Integer i : total.keySet()) {
if (i != -1 && total.get(i) > max) {
max = total.get(i);
id = i;
}
}
if (id == -1) {
return null;
}
return id;
} |
f05cf8d2-538a-4673-8a4d-83b00ca726f0 | 9 | @Override
public void setEntityValue(ResultSet rs, int index, Object entity) throws Exception {
Field f = getField();
Integer ordinal = rs.getInt(index);
Enum<?> value = null;
if(ordinal == null) {
getField().set(entity, value);
return;
}
@SuppressWarnings("unchecked")
Class<? extends Enum<?>> type = (Class<? extends Enum<?>>) f.getType();
for(Enum<?> e : type.getEnumConstants()) {
if(e.ordinal() == ordinal) {
value = e;
break;
}
}
getField().set(entity, value);
} |
45c07892-3915-44c4-9565-8124db46a4ff | 4 | private String getExpression(int index) throws SyntaxErrorException {
int c = 1;
for (int j = index + 1; j < expression.length(); j++) {
char s = expression.charAt(j);
if (s == '(')
c++;
if (s == ')')
c--;
currentPosition = j;
if (c == 0)
return expression.substring(index + 1, j);
}
throw new SyntaxErrorException(
Tools.getLocalizedString("MISSING_BRACKETS"), index);
} |
8b846ca6-f817-4fc4-b98f-97d9669fefe8 | 1 | public List<String> getDescription() {
if (description == null) {
description = new ArrayList<String>();
}
return description;
} |
6c24c5f9-95e8-40a0-bf83-0826c9e54436 | 9 | public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
int n = 0;
d: do {
line = br.readLine();
if (line == null || line.length() == 0)
break d;
char[] a = line.toCharArray();
for (int i = 0; i < a.length; i++) {
if (a[i] == '"' && n % 2 == 0) {
out.append("``");
n++;
} else if (a[i] == '"' && n % 2 == 1) {
out.append("''");
n++;
} else
out.append(a[i]);
}
out.append("\n");
} while (line != null && line.length() != 0);
System.out.print(out);
} |
ae66cdf2-9478-43e7-a58b-cb12f0c18c3d | 3 | private void draw() {
double size = getWidth() < getHeight() ? getWidth() : getHeight();
canvas.setWidth(size);
canvas.setHeight(size);
ctx.clearRect(0, 0, size, size);
if (isFrameVisible()) { //frame
Paint frame = new LinearGradient(0.14 * size, 0.14 * size,
0.84 * size, 0.84 * size,
false, CycleMethod.NO_CYCLE,
new Stop(0.0, Color.rgb(20, 20, 20, 0.65)),
new Stop(0.15, Color.rgb(20, 20, 20, 0.65)),
new Stop(0.26, Color.rgb(41, 41, 41, 0.65)),
new Stop(0.26, Color.rgb(41, 41, 41, 0.64)),
new Stop(0.85, Color.rgb(200, 200, 200, 0.41)),
new Stop(1.0, Color.rgb(200, 200, 200, 0.35)));
ctx.setFill(frame);
ctx.fillOval(0, 0, size, size);
}
InnerShadow innerShadow = new InnerShadow(BlurType.TWO_PASS_BOX, Color.rgb(0, 0, 0, 0.65), 0.07 * size, 0, 0, 0);
if (isOn()) { //on
ctx.save();
Paint on = new LinearGradient(0.25 * size, 0.25 * size,
0.74 * size, 0.74 * size,
false, CycleMethod.NO_CYCLE,
new Stop(0.0, ((Color)ledColor.get()).deriveColor(0d, 1d, 0.77, 1d)),
new Stop(0.49, ((Color)ledColor.get()).deriveColor(0d, 1d, 0.5, 1d)),
new Stop(1.0, ((Color)ledColor.get())));
innerShadow.setInput(new DropShadow(BlurType.TWO_PASS_BOX, (Color)ledColor.get(), 0.36 * size, 0, 0, 0));
ctx.setEffect(innerShadow);
ctx.setFill(on);
ctx.fillOval(0.14 * size, 0.14 * size, 0.72 * size, 0.72 * size);
ctx.restore();
} else { // off
ctx.save();
Paint off = new LinearGradient(0.25 * size, 0.25 * size,
0.74 * size, 0.74 * size,
false, CycleMethod.NO_CYCLE,
new Stop(0.0, ((Color)ledColor.get()).deriveColor(0d, 1d, 0.20, 1d)),
new Stop(0.49, ((Color)ledColor.get()).deriveColor(0d, 1d, 0.13, 1d)),
new Stop(1.0, ((Color)ledColor.get()).deriveColor(0d, 1d, 0.2, 1d)));
ctx.setEffect(innerShadow);
ctx.setFill(off);
ctx.fillOval(0.14 * size, 0.14 * size, 0.72 * size, 0.72 * size);
ctx.restore();
}
//highlight
Paint highlight = new RadialGradient(0, 0,
0.3 * size, 0.3 * size,
0.29 * size,
false, CycleMethod.NO_CYCLE,
new Stop(0.0, Color.WHITE),
new Stop(1.0, Color.TRANSPARENT));
ctx.setFill(highlight);
ctx.fillOval(0.21 * size, 0.21 * size, 0.58 * size, 0.58 * size);
} |
8006b909-e1b1-484f-b3da-618b2bc0c1ce | 4 | public void rollback() throws DatabaseManagerException {
try {
if( conn == null || conn.isClosed() || conn.getAutoCommit() == true ) {
throw new IllegalStateException("Transaction not valid for commit operation.");
}
conn.rollback();
} catch(SQLException e) {
throw new DatabaseManagerException("Error rolling back the transaction!");
}
} |
028a52ec-4e93-4a8b-8cf5-7f0b982fe22b | 1 | public void resolveCollision(Sprite collidee)
{
// The normal is a unit vector along the line between the sprites.
Vector2d normal = collidee.getPosition().minus(getPosition());
normal.setMagnitude(1);
Vector2d relativeVelocity = collidee.getVelocity().minus(getVelocity());
double velocityAlongNormal = normal.dotProduct(relativeVelocity);
// Only bounce if they're moving towards each other.
if (velocityAlongNormal < 0)
{
double impulseMagnitude = (velocityAlongNormal * (1 + collidee
.getReboundCoefficient()))
/ (getInverseMass() + collidee.getInverseMass());
Vector2d impulse = normal.times(impulseMagnitude);
applyImpulse(impulse);
collidee.applyImpulse(impulse.times(-1));
}
} |
7a7e56af-70dc-4ea9-acb8-a87433b9d477 | 9 | @Override
public void processGameEvent(GameEvent e) {
if(e instanceof TimerEvent)
return;
if(e instanceof InternalGameEvent)
return;
if(e instanceof GameStartEvent)
synchronized(this) { notify(); }
else if(e instanceof GameEndEvent) {
out.println(e.getUpdateString());
out.flush();
disconnect();
} else if (e instanceof BeginTurnEvent) {
if(((BeginTurnEvent) e).getPlayer().equals(this)) {
out.println(e.getUpdateString());
out.flush();
}
}
else if(e instanceof ScoreEvent) {
if(((ScoreEvent)e).getPlayer().equals(this))
player.setScore(player.getScore() + ((ScoreEvent)e).getScore());
out.println(e.getUpdateString());
}
else if (e instanceof GameEvent) {
out.println(e.getUpdateString());
out.flush();
}
} |
56cbec68-946b-438d-a238-c570018a74cd | 2 | public HierarchicalClustering(int link, Instances data) {
if (link == 0)
this.link = new CompleteLink();
else if (link == 1)
this.link = new SingleLink();
else
this.link = new AverageLink();
this.instances = data;
} |
fe272003-fb81-4281-8e5d-d4a1fcda1b0e | 7 | public NodeBuilder<?,?> addChildNode(Class<CallableData<?,?>> clazz, Initializer<? extends CallableData<T,E>> initializer){
NodeBuilder<?,?> node = new NodeBuilder(clazz,initializer,root);
local.getNext().add(node.getLocal());
return node;
} |
c963c15b-5c49-4333-9c7d-28b8af4c88f9 | 4 | public void invoke(T entity, EntityProperty entityProperty, Cell cell) {
try {
Method method = entityProperty.getPropertyDescriptor().getWriteMethod();
switch (entityProperty.getColumnType()) {
case TEXT:
method.invoke(entity, cell.getStr());
break;
case DOUBLE:
method.invoke(entity, new Double(cell.getStr()));
break;
case INTEGER:
method.invoke(entity, new Integer(cell.getStr()));
break;
}
} catch (Exception ex) {
System.out.println("In exceptin thrown: "+entity);
}
} |
11387901-c15b-4e08-9efc-85e386b151db | 2 | public PayloadSubjectExceptionData(Node exception) {
if(exception == null) {
throw new IllegalArgumentException("Node not specified.");
}
if(!exception.getLocalName().equals("PayloadSubjectException")) {
throw new IllegalArgumentException("Unknown node \'" + exception.getNodeName() + "\', expected PayloadSubjectException.");
}
this.node = exception;
} |
3dbfa011-9ae0-4ed6-b939-30b4565e7509 | 0 | protected AnnotatedHandlerBuilder<Field> handleField()
{
return wrapped.handleField();
} |
6863f4a8-fb2e-4647-8997-a7b488772068 | 9 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
final Room R=target.location();
if(success)
{
final Prayer_Thunderbolt newOne=(Prayer_Thunderbolt)this.copyOf();
final CMMsg msg=CMClass.getMsg(mob,target,newOne,verbalCastCode(mob,target,auto),L(auto?"<T-NAME> is filled with a holy charge!":"^S<S-NAME> "+prayForWord(mob)+" to strike down <T-NAMESELF>!^?")+CMLib.protocol().msp("lightning.wav",40));
final CMMsg msg2=CMClass.getMsg(mob,target,this,CMMsg.MSK_CAST_MALICIOUS_VERBAL|CMMsg.TYP_ELECTRIC|(auto?CMMsg.MASK_ALWAYS:0),null);
if((R.okMessage(mob,msg))&&((R.okMessage(mob,msg2))))
{
R.send(mob,msg);
R.send(mob,msg2);
if((msg.value()<=0)&&(msg2.value()<=0))
{
final int harming=CMLib.dice().roll(1,adjustedLevel(mob,asLevel),adjustedLevel(mob,asLevel));
CMLib.combat().postDamage(mob,target,this,harming,CMMsg.MASK_ALWAYS|CMMsg.TYP_ELECTRIC,Weapon.TYPE_STRIKING,L("^SThe STRIKE of @x1 <DAMAGES> <T-NAME>!^?",hisHerDiety(mob)));
}
}
}
else
return maliciousFizzle(mob,target,L("<S-NAME> @x1, but nothing happens.",prayWord(mob)));
// return whether it worked
return success;
} |
e957f9f8-1faf-4265-8429-1ef003535c7d | 0 | @Override
public void setHouseNumber(String houseNumber) {
super.setHouseNumber(houseNumber);
} |
06100a2d-8749-4389-a195-57ed30b6b201 | 1 | public static synchronized void monitorBalance() {
int b = myValue;
if (b != 1) {
System.out.println("Balance change: " + b);
System.exit(1);
}
} |
a929848c-25cb-4b3a-b881-1822787a16a3 | 2 | private static void printSummary() {
GlobalOptions.err.println();
if (failedClasses.size() > 0) {
GlobalOptions.err.println("Failed to decompile these classes:");
Enumeration enum_ = failedClasses.elements();
while (enum_.hasMoreElements()) {
GlobalOptions.err.println("\t" + enum_.nextElement());
}
GlobalOptions.err.println("Failed to decompile "+ failedClasses.size() + " classes.");
}
GlobalOptions.err.println("Decompiled " + successCount + " classes.");
} |
e299bf3b-2f8b-4b00-8d16-92f60141ab7c | 4 | public static void main(String[] args) throws Exception {
LOG.info("Args: ");
int i = 0;
for (String arg : args) {
LOG.info("{}:{}", i++, arg);
}
// create Options object
Options options = new Options();
options.addOption("array_id", true, "the parameter to process");
options.addOption("database", true, "the database stem to use");
options.addOption("db_hostname", true, "the database hostname to use");
options.addOption("db_port", true, "the database port to use");
options.addOption("?", false, "print this message");
try {
CommandLineParser parser = new GnuParser();
// parse the command line arguments
CommandLine line = parser.parse(options, args);
if (line.hasOption("?")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("MergeSkynetResults", options);
return;
}
if (!line.hasOption("db_hostname")) {
LOG.error("DB Hostname not given");
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("MergeSkynetResults", options);
return;
}
setup(line);
} catch (Throwable e) {
// oops, something went wrong
LOG.error("Exception Caught", e);
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("MergeSkynetResults Error", options);
return;
}
MergeSkynetResults msr = new MergeSkynetResults();
msr.mergeParameterNumber();
} |
161e03df-cc63-47d5-8d0c-82feed1303fd | 3 | public static void Spectrum(byte[] audioBytes, AudioFormat format, Vector<Line2D.Double> SpectrumData) {
SpectrumData.removeAllElements();
int h=105, w=689;
int[] audioData = null;
int nlengthInSamples = audioBytes.length/2;
audioData = new int[nlengthInSamples];
for (int i = 0; i < nlengthInSamples; i++) {
int LSB = (int)audioBytes[2*i];
int MSB = (int)audioBytes[2*i+1];
audioData[i] = MSB << 8 | (255 & LSB);
}
int frames_per_pixel = audioBytes.length/format.getFrameSize()/w;
byte my_byte = 0;
double y_last = 0;
int numChannels = format.getChannels();
for (double x=0; x<w && audioData != null; x++) {
int idx = (int) (frames_per_pixel * numChannels * x);
my_byte = (byte) (128 * audioData[idx] / 32768 );
double y_new = (double) (h * (128 - my_byte) / 256);
SpectrumData.add(new Line2D.Double(x+25.F, y_last+35.F, x+25.F, y_new+35.F));
frame.repaint();
y_last = y_new;
}
} |
eb3177a4-1332-4504-b0cc-74de5600c674 | 4 | private boolean dropTargetValidate(DropTargetEvent event, File targetFile) {
if (targetFile != null && targetFile.isDirectory()) {
if (event.detail != DND.DROP_COPY && event.detail != DND.DROP_MOVE) {
event.detail = DND.DROP_MOVE;
}
} else {
event.detail = DND.DROP_NONE;
}
return event.detail != DND.DROP_NONE;
} |
abeebaeb-1800-4a1b-8308-523e9c2d244c | 2 | public boolean isFull() {
for(Park park : this.parkList) {
if(!park.isFull()) {
return false;
}
}
return true;
} |
2d0f7f98-c99f-4b72-b4a7-e666bb93dc13 | 8 | protected void done() {
fr.setVisible(true);
if (exito && !this.isCancelled() && Vista.OS.equals("windows")){
eti.setText("Minecraft instalado con éxito en " + System.getProperty("user.home") + "\\AppData\\Roaming\\.minecraft");
bot.setVisible(true);
bot.setEnabled(true);
prog.setValue(100);
bot1.setVisible(false);
} else if(exito && !this.isCancelled() && Vista.OS.equals("linux")){
eti.setText("Minecraft instalado con éxito en " + System.getProperty("user.home") + "/.minecraft");
bot.setVisible(true);
bot.setEnabled(true);
prog.setValue(100);
bot1.setVisible(false);
} else if (!exito){
eti.setText("Minecraft no ha podido ser instalado.");
} else if (this.isCancelled()){
fr.retry();
}
} |
8ed3ea0f-bc10-481b-86b8-9d888113e1b8 | 6 | public UpcomingEventType getEventType() {
if ("HTML".equalsIgnoreCase(getType())) return UpcomingEventType.Html;
if ("MANAGED_OD".equalsIgnoreCase(getType())) return UpcomingEventType.Html;
if ("MANAGED_HTML".equalsIgnoreCase(getType())) return UpcomingEventType.Html;
if ("THREAD".equalsIgnoreCase(getType())) return UpcomingEventType.Thread;
if ("MANAGED_THREADS".equalsIgnoreCase(getType())) return UpcomingEventType.Thread;
if ("IQT".equalsIgnoreCase(getType())) return UpcomingEventType.QuizExamTest;
return UpcomingEventType.Ignored;
} |
aa74b952-9bf3-4188-9b95-0c194c540164 | 4 | public static float convertTensionUnitIndexToFactor(int index) {
switch (index) {
case 0:
return NEWTON;
case 1:
return POUND_FORCE;
case 2:
return KILOGRAM_FORCE;
case 3:
return DECANEWTON;
default:
return NEWTON;
}
} |
61ed7200-5bd7-4172-aa40-5a8b0963ce78 | 3 | public static String toString(JSONObject jo) throws JSONException {
boolean b = false;
Iterator<String> keys = jo.keys();
String string;
StringBuilder sb = new StringBuilder();
while (keys.hasNext()) {
string = keys.next();
if (!jo.isNull(string)) {
if (b) {
sb.append(';');
}
sb.append(Cookie.escape(string));
sb.append("=");
sb.append(Cookie.escape(jo.getString(string)));
b = true;
}
}
return sb.toString();
} |
35c073d1-7cd5-4070-8b9c-b93290446aec | 3 | protected void close() {
if(!statusSent) status(500); // Internal server error
if(!headersSent) completeHeaders();
try {
connection.shutdownOutput();
connection.close();
} catch (IOException e) { e.printStackTrace(); }
} |
ae0fa4a4-cec0-4765-9617-f39d6055ee78 | 5 | static final public void simpleExpr() throws ParseException {
terme();
label_8:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case OU:
case ADD:
case SUBNEG:
;
break;
default:
jj_la1[18] = jj_gen;
break label_8;
}
opAdd();
terme();
expression.testAdd();
expression.executerOpAdd();
}
} |
e8f351c1-5eac-42e4-ac93-9ff0c007ca48 | 4 | public static Player Load()
{ //loads the character's file (plaintext)
Scanner Input = new Scanner(System.in);
Player player;
Player decoy = new Player();
String strFile;
String charName;
int[] stats = new int[9];
String cmd="";
System.out.println("Enter your old character's name:");
strFile = (Input.nextLine());
cmd = strFile.toLowerCase();
strFile = strFile.toLowerCase() + ".stats";
//Reads File
File file = new File(strFile);
if (file.exists() == true)
{
System.out.println("Loading...");
try{
Scanner Read = new Scanner(file);
int i;
charName = Read.nextLine();
for(i=1; i < 9; i++)
{
stats[i]= Read.nextInt();
//System.out.println(stats[i]); //debug
}
player = new Player(charName, stats, "Load");
System.out.println(player.toString()); //test
System.out.println("File loaded Successfully.");
System.out.println("\n");
return player;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
else if(cmd.equals(".."))
{
System.out.println("Returning to menu.");
mainMenu.Menu();
}
else
{
System.out.println("That character does not exist");
Load();
}
// Story.Start();
return decoy;
} |
853f3659-4963-40e8-a99d-6ca58838627c | 3 | public static synchronized void open(File file) {
if (PASS_THROUGH) {
OpenDataFileCommand opener = new OpenDataFileCommand(file);
if (!SwingUtilities.isEventDispatchThread()) {
EventQueue.invokeLater(opener);
} else {
opener.run();
}
} else {
if (PENDING_FILES == null) {
PENDING_FILES = new ArrayList<>();
}
PENDING_FILES.add(file);
}
} |
7cd86473-9c9e-47f4-a423-5ad5cd4d6cf0 | 4 | public String getColumnData(int i) throws Exception {
if (i == 0)
return getPersonID();
else if (i == 1)
return getName();
else if (i == 2)
return getProjectID();
else if (i == 3)
return getRole();
else
throw new Exception("Error: invalid column index in courselist table");
} |
5df3b1da-45e8-4b0c-9a14-c7f9a3c15496 | 9 | void menuOpenFile() {
animate = false; // stop any animation in progress
// Get the user to choose an image file.
FileDialog fileChooser = new FileDialog(shell, SWT.OPEN);
if (lastPath != null)
fileChooser.setFilterPath(lastPath);
fileChooser.setFilterExtensions(OPEN_FILTER_EXTENSIONS);
fileChooser.setFilterNames(OPEN_FILTER_NAMES);
String filename = fileChooser.open();
lastPath = fileChooser.getFilterPath();
if (filename == null)
return;
Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
shell.setCursor(waitCursor);
imageCanvas.setCursor(waitCursor);
ImageLoader oldLoader = loader;
try {
loader = new ImageLoader();
if (incremental) {
// Prepare to handle incremental events.
loader.addImageLoaderListener(new ImageLoaderListener() {
public void imageDataLoaded(ImageLoaderEvent event) {
incrementalDataLoaded(event);
}
});
incrementalThreadStart();
}
// Read the new image(s) from the chosen file.
long startTime = System.currentTimeMillis();
imageDataArray = loader.load(filename);
loadTime = System.currentTimeMillis() - startTime;
if (imageDataArray.length > 0) {
// Cache the filename.
currentName = filename;
fileName = filename;
// If there are multiple images in the file (typically GIF)
// then enable the Previous, Next and Animate buttons.
previousButton.setEnabled(imageDataArray.length > 1);
nextButton.setEnabled(imageDataArray.length > 1);
animateButton.setEnabled(imageDataArray.length > 1 && loader.logicalScreenWidth > 0 && loader.logicalScreenHeight > 0);
// Display the first image in the file.
imageDataIndex = 0;
displayImage(imageDataArray[imageDataIndex]);
}
} catch (SWTException e) {
showErrorDialog(bundle.getString("Loading_lc"), filename, e);
loader = oldLoader;
} catch (SWTError e) {
showErrorDialog(bundle.getString("Loading_lc"), filename, e);
loader = oldLoader;
} catch (OutOfMemoryError e) {
showErrorDialog(bundle.getString("Loading_lc"), filename, e);
loader = oldLoader;
} finally {
shell.setCursor(null);
imageCanvas.setCursor(crossCursor);
waitCursor.dispose();
}
} |
3541b362-b00a-44df-8af8-7211b3d80bfc | 9 | @SuppressWarnings("rawtypes")
private BeanDefinition createProxyBeanDefinition(String serviceName,
Class serviceInterface, Exposer exposer) {
// HTTP http://host:port/contextPath/serviceName
String httpServiceUrl = new StringBuilder(HTTP_PROTOCOL)
.append(getHost()).append(":").append(getHttpPort())
.append(getHttpContextPath()).append("/").append(serviceName)
.toString();
// RMI rmi://host:port//serviceName
String rmiServiceUrl = new StringBuilder(RMI_PROTOCOL)
.append(getHost()).append(":").append(getRmiPort()).append("/")
.append(serviceName).toString();
BeanDefinitionBuilder beanDefinitionBuilder = null;
UsernamePasswordCredentials credentials = null;
if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(password))
credentials = new UsernamePasswordCredentials(userName, password);
if (Exposer.BURLAP == exposer) {
LOGGER.debug("Creating BURLAP service definition");
beanDefinitionBuilder = BeanDefinitionBuilder
.genericBeanDefinition(BurlapProxyFactoryBean.class)
.addPropertyValue("serviceInterface", serviceInterface)
.addPropertyValue("serviceUrl", httpServiceUrl);
if (null != credentials) {
beanDefinitionBuilder.addPropertyValue("username",
credentials.getUserName()).addPropertyValue("password",
credentials.getPassword());
}
} else if (Exposer.HESSIAN == exposer) {
LOGGER.debug("Creating HESSIAN service definition");
beanDefinitionBuilder = BeanDefinitionBuilder
.genericBeanDefinition(HessianProxyFactoryBean.class)
.addPropertyValue("serviceInterface", serviceInterface)
.addPropertyValue("serviceUrl", httpServiceUrl);
if (null != credentials) {
beanDefinitionBuilder.addPropertyValue("username",
credentials.getUserName()).addPropertyValue("password",
credentials.getPassword());
}
} else if (Exposer.HTTP == exposer) {
LOGGER.debug("Creating HTTP service definition");
beanDefinitionBuilder = BeanDefinitionBuilder
.genericBeanDefinition(HttpInvokerProxyFactoryBean.class)
.addPropertyValue("serviceInterface", serviceInterface)
.addPropertyValue("serviceUrl", httpServiceUrl);
if (null != credentials) {
SimpleHttpState httpState = new SimpleHttpState();
httpState.setCredentials(credentials);
HttpClient httpClient = new HttpClient();
httpClient.setState(httpState);
beanDefinitionBuilder.addPropertyValue(
"httpInvokerRequestExecutor",
new CommonsHttpInvokerRequestExecutor(httpClient));
}
} else if (Exposer.RMI == exposer) {
LOGGER.debug("Creating RMI service definition");
beanDefinitionBuilder = BeanDefinitionBuilder
.genericBeanDefinition(RmiProxyFactoryBean.class)
.addPropertyValue("serviceInterface", serviceInterface)
.addPropertyValue("serviceUrl", rmiServiceUrl);
}
return beanDefinitionBuilder.getBeanDefinition();
} |
f84cb877-a568-4e4e-93ac-9e974ad2a52b | 9 | void run(){
Scanner sc = new Scanner(System.in);
dp = new int[30][51][6];
for(;;){
C = sc.nextInt(); D = sc.nextInt(); W = sc.nextInt(); X = sc.nextInt();
if((C|D|W|X)==0)break;
E = new int[C][D]; F = new int[C][D];
for(int i=0;i<C;i++)for(int j=0;j<D;j++)E[i][j]=sc.nextInt();
for(int i=0;i<C;i++)for(int j=0;j<D;j++)F[i][j]=sc.nextInt();
for(int i=0;i<D;i++)for(int j=0;j<=W;j++)for(int k=0;k<=X;k++)dp[i][j][k]=-1;
System.out.println(get(0, W, X));
}
} |
4a09722a-284e-4238-bf13-60965e29c31e | 9 | public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
} |
16556715-063d-43c4-b184-aadafe69bd3e | 1 | public MiniXMLToken getToken() {
MiniXMLToken oMiniXMLToken = new MiniXMLToken();
oMiniXMLToken.setType(tError);
if (!bInsideTag)
return getTokenOutsideTag(oMiniXMLToken);
else
return getTokenInsideTag(oMiniXMLToken);
} |
7885e5d4-95f5-43b2-aa8f-b5d0f8925344 | 4 | private void checkVarDeclaration() throws Exception {
if(iterator < tokenList.size() && tokenList.get(iterator++).getType() != TokenType.ID) {
// missing identificator
throw new Exception("Syntax Error at line " + tokenList.get(iterator-1).getLine() +
": Expected identificator and got \"" + tokenList.get(iterator-1).getKey() + "\" instead");
}
if(iterator < tokenList.size() && tokenList.get(iterator++).getType() != TokenType.SEMICOLLON) {
// missing semicollon
throw new Exception("Syntax Error at line " + tokenList.get(iterator-1).getLine() +
": Expected ; and got \"" + tokenList.get(iterator-1).getKey() + "\" instead");
}
} |
788129d2-559c-4311-8431-13ba7d4706b2 | 8 | public void acceptClusterer(BatchClustererEvent ce) {
if (ce.getTestSet() == null ||
ce.getTestOrTrain() == BatchClustererEvent.TEST ||
ce.getTestSet().isStructureOnly()) {
return;
}
Instances trainHeader = new Instances(ce.getTestSet().getDataSet(), 0);
String titleString = ce.getClusterer().getClass().getName();
titleString = titleString.
substring(titleString.lastIndexOf('.') + 1,
titleString.length());
String prefix = "";
String relationName = (m_includeRelationName)
? trainHeader.relationName()
: "";
try {
prefix = m_env.substitute(m_filenamePrefix);
} catch (Exception ex) {
stop(); // stop all processing
String message = "[SerializedModelSaver] "
+ statusMessagePrefix()
+ " Can't save model. Reason: "
+ ex.getMessage();
if (m_logger != null) {
m_logger.logMessage(message);
m_logger.statusMessage(statusMessagePrefix()
+ "ERROR (See log for details)");
} else {
System.err.println(message);
}
return;
}
String fileName = ""
+ prefix
+ relationName
+ titleString
+ "_"
+ ce.getSetNumber()
+ "_" + ce.getMaxSetNumber();
fileName = sanitizeFilename(fileName);
String dirName = m_directory.getPath();
try {
dirName = m_env.substitute(dirName);
} catch (Exception ex) {
stop(); // stop all processing
String message = "[SerializedModelSaver] "
+ statusMessagePrefix() + " Can't save model. Reason: "
+ ex.getMessage();
if (m_logger != null) {
m_logger.logMessage(message);
m_logger.statusMessage(statusMessagePrefix()
+ "ERROR (See log for details)");
} else {
System.err.println(message);
}
return;
}
File tempFile = new File(dirName);
fileName = tempFile.getAbsolutePath()
+ File.separator
+ fileName;
saveModel(fileName, trainHeader, ce.getClusterer());
} |
15a733ed-17ce-4812-845c-b494754f3d1d | 4 | public static ArrayList<Kill> compairEntityKill(ArrayList<Kill> Kills,
String name) {
ArrayList<Kill> output = new ArrayList<Kill>();
for (Kill k : Kills) {
if (k.getAttackers().size() != 0) {
for (ShipAndChar attacker : k.getAttackers()) {
if (attacker.getPilot().findAttribute(name)) {
output.add(k);
}
}
}
}
return output;
} |
c38525a0-74ca-4577-86a4-26522aab8f4a | 1 | public static void clearEditableText(Node currentNode, JoeTree tree, OutlineLayoutManager layout) {
CompoundUndoablePropertyChange undoable = new CompoundUndoablePropertyChange(tree);
clearEditableForSingleNode(currentNode, undoable);
if (!undoable.isEmpty()) {
undoable.setName("Clear Editability for Node");
tree.getDocument().getUndoQueue().add(undoable);
}
// Redraw
tree.getDocument().attPanel.update();
layout.draw(currentNode, OutlineLayoutManager.TEXT);
} |
789719ca-2f52-4e57-b2ba-1312212f3f3e | 1 | public int queueLengthRec(){
if (nextPatient == null){
return 1;
}
int count = nextPatient.queueLengthRec() + 1;
return count;
} |
23b44f73-2f21-4ae8-9945-949c9220c453 | 3 | public static Const constant(int value) {
switch(value) {
case 0: return C0;
case 1: return C1;
case 2: return C2;
}
return new Const(value);
} |
6342c953-51f0-431a-bf7b-3dd160df24c0 | 7 | public Object nextValue() throws JSONException {
char c = nextClean();
String string;
switch (c) {
case '"':
case '\'':
return nextString(c);
case '{':
back();
return new JSONObject(this);
case '[':
back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuffer sb = new StringBuffer();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = next();
}
back();
string = sb.toString().trim();
if (string.equals("")) {
throw syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
} |
925a9e3d-633c-446d-8e24-a257a1677c30 | 0 | public FrameAddArraysData(){
super("Arrays Editor");
initialize();
} |
7e649724-e798-494b-b47d-acba9967c15c | 9 | public static int parseInt(String s, int offset, int length, int base)
throws NumberFormatException
{
int value=0;
if (length<0)
length=s.length()-offset;
for (int i=0;i<length;i++)
{
char c=s.charAt(offset+i);
int digit=c-'0';
if (digit<0 || digit>=base || digit>=10)
{
digit=10+c-'A';
if (digit<10 || digit>=base)
digit=10+c-'a';
}
if (digit<0 || digit>=base)
throw new NumberFormatException(s.substring(offset,offset+length));
value=value*base+digit;
}
return value;
} |
fa30618f-f555-447c-a623-e87bc7145655 | 7 | public void moveElement(Element element, Direction direction) {
if (element == null || direction == null)
throw new IllegalArgumentException("The given parameters are invalid!");
if (!canMoveElement(element, direction))
throw new IllegalArgumentException("This element can't move in the given direction!");
final Position to = direction.newPosition(getElementPosition(element));
for (Element e : getElementsOnPosition(to)) {
if (e instanceof Collide) {
((Collide) e).collideWith(element);
if (e instanceof Teleporter)
return;
}
}
if (getElementPosition(element) != null)
updateElementPosition(element, to);
} |
f449f5ea-b2ff-4282-a0de-4c340f0cbbeb | 6 | public void setSelectedItem(Object element) {
if (element == null) {
if (elementIndex != -1) {
elementIndex = -1;
fireContentsChanged(this, -1, -1);
}
} else if (element instanceof String) {
int index = 0;
for (DBElement e : elementList) {
if (e.getName().equals((String)element)) {
if (elementIndex != index) {
elementIndex = index;
fireContentsChanged(this, -1, -1);
}
break;
}
index++;
}
}
} |
5e174703-8899-4467-8c1c-2ced0f11528d | 7 | public synchronized void tick() {
if (unchoked.size() == maxUnchoked && interested.size() > maxUnchoked) {
long now = System.currentTimeMillis();
Peer slowest = null;
for (Map.Entry<Peer, Long> e : unchoked.entrySet()) {
if (now - e.getValue() > 10000) {
if (slowest == null) {
slowest = e.getKey();
} else {
if ((float) slowest.getDownloaded() / (now - unchoked.get(slowest)) >
(float) e.getKey().getDownloaded() / (now - e.getValue())) {
slowest = e.getKey();
}
}
}
}
if (slowest != null) {
slowest.setIsChoked(true);
unchoked.remove(slowest);
List<Peer> interestedChoked = new LinkedList<Peer>(interested);
interestedChoked.removeAll(unchoked.keySet());
Peer newUnchoked = interestedChoked.get(new Random().nextInt(interestedChoked.size()));
newUnchoked.setIsChoked(false);
unchoked.put(newUnchoked, now);
}
}
} |
7eec6668-08e6-42aa-a22b-3db1ee78c8ab | 1 | public void setPasswordfieldDownshift(int shift) {
if (shift < 0) {
this.passwordfieldDownshift = UIShiftInits.PWAREA_DOWN.getShift();
} else {
this.passwordfieldDownshift = shift;
}
} |
73638f25-673a-4caf-a068-229dc1083c7f | 2 | private double calcValue(double point) {
double value = 0;
for (int i = 0; i < equationCoef.length; i++) {
if (equationPower[i] != 0) {
value = value + equationCoef[i] * Math.pow(point, equationPower[i]);
} else {
value = value + equationCoef[i];
}
}
return value;
} |
60b0041b-b86a-47aa-b787-f8b270150579 | 7 | @Override
public boolean nextKeyValue() throws IOException, InterruptedException {
if (key == null) {
key = new LongWritable();
}
key.set(pos);
if (value == null) {
value = new Text();
}
value.clear();
final Text endline = new Text("\n");
int newSize = 0;
for(int i=0;i<NLINESTOPROCESS;i++){
Text v = new Text();
while (pos < end) {
newSize = in.readLine(v, maxLineLength,Math.max((int)Math.min(Integer.MAX_VALUE, end-pos),maxLineLength));
value.append(v.getBytes(),0, v.getLength());
value.append(endline.getBytes(),0, endline.getLength());
if (newSize == 0) {
break;
}
pos += newSize;
if (newSize < maxLineLength) {
break;
}
}
}
if (newSize == 0) {
key = null;
value = null;
return false;
} else {
return true;
}
} |
afcabf5d-db25-429d-a714-d0affeb362d1 | 1 | public static void quit() {
if (loggingEnabled)
handler.close();
} |
09fa8f0e-6878-4ef8-b27c-38de5b4a72a0 | 6 | public static AuthorizationToken generateToken(String controller, String type, String id, String passcode) {
if (type.equals(ComponentTypes.Authorization.NONE_FALSE.name())) {
return new AuthorizationToken(controller, ComponentTypes.Authorization.NONE_FALSE);
}
else if (type.equals(ComponentTypes.Authorization.NONE_TRUE.name())) {
return new AuthorizationToken(controller, ComponentTypes.Authorization.NONE_TRUE);
}
else if (type.equals(ComponentTypes.Authorization.TIMED.name())) {
return new AuthorizationToken(controller, ComponentTypes.Authorization.TIMED);
}
else if (type.equals(ComponentTypes.Authorization.DB_PASSCODE.name())) {
return new AuthorizationToken(controller, ComponentTypes.Authorization.DB_PASSCODE, passcode);
}
else if (type.equals(ComponentTypes.Authorization.DB_ID.name())) {
return new AuthorizationToken(controller, ComponentTypes.Authorization.DB_ID, id);
}
else if (type.equals(ComponentTypes.Authorization.DB_USERNAME_PASSWORD.name())) {
return new AuthorizationToken(controller, ComponentTypes.Authorization.DB_USERNAME_PASSWORD, id, passcode);
}
return null;
} |
2cd60298-154c-4800-9fb6-7c8d6bd2790b | 2 | public void saveIssueFired(ActionEvent event) {
final ObservableIssue ref = getSelectedIssue();
final Issue edited = new DetailsData();
SaveState saveState = computeSaveState(edited, ref);
if (saveState == SaveState.UNSAVED) {
model.saveIssue(ref.getId(), edited.getStatus(),
edited.getSynopsis(), edited.getDescription());
}
// We refresh the content of the table because synopsis and/or description
// are likely to have been modified by the user.
int selectedRowIndex = table.getSelectionModel().getSelectedIndex();
table.getItems().clear();
displayedIssues = model.getIssueIds(getSelectedProject());
for (String id : displayedIssues) {
final ObservableIssue issue = model.getIssue(id);
table.getItems().add(issue);
}
table.getSelectionModel().select(selectedRowIndex);
updateSaveIssueButtonState();
} |
cd1ea167-babb-4eb5-95f6-061e9c91c477 | 5 | @Override
public Map<Course, Integer> getMarks(int userId) throws SQLException {
Map<Course, Integer> courseMark = new HashMap<>();
Connection connect = null;
PreparedStatement statement = null;
try {
Class.forName(Params.bundle.getString("urlDriver"));
connect = DriverManager.getConnection(Params.bundle.getString("urlDB"),
Params.bundle.getString("userDB"),Params.bundle.getString("passwordDB"));
String getTeacherId = "select student.id from student " +
"where student.user_id = ?";
statement = connect.prepareStatement(getTeacherId);
statement.setInt(1, userId);
ResultSet studentIdSet = statement.executeQuery();
studentIdSet.next();
int studentId = studentIdSet.getInt("student.id");
String selectMarks = "select mark.id, mark.mark, mark.course_catalog_id from mark where mark.student_id = ?";
statement = connect.prepareStatement(selectMarks);
statement.setInt(1, studentId);
ResultSet resultMark = statement.executeQuery();
while (resultMark.next()){
int mark = resultMark.getInt("mark");
int course_id = resultMark.getInt("course_catalog_id");
String selectCourseDescription = "select general_course_catalog.title from course_catalog " +
"inner join general_course_catalog on course_catalog.general_course_catalog_id=general_course_catalog.id " +
"where course_catalog.id = ?";
statement = connect.prepareStatement(selectCourseDescription);
statement.setInt(1, course_id);
ResultSet titleSet = statement.executeQuery();
titleSet.next();
String title = titleSet.getString("general_course_catalog.title");
Course course = new Course();
course.setId(course_id);
course.setTitle(title);
courseMark.put(course, mark);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(connect != null)
connect.close();
if(statement != null)
statement.close();
return courseMark;
}
} |
dbf1ddb6-2478-4f95-a278-cb435a0043bd | 2 | public Quester(String[] questerInfoInString, Player player) {
//this.plugin = plugin;
this.theQuestersName = player.getName();
this.questID = Integer.parseInt(questerInfoInString[0]);
this.questsCompleted = Integer.parseInt(questerInfoInString[1]);
this.moneyEarnedFromQuests = Integer.parseInt(questerInfoInString[2]);
//this.questsFailed
HashMap<String,Integer> tracker = new HashMap<String,Integer>();
try{
for(String info : questerInfoInString[3].split("~")){
//system.err.println("Info: " + info);
String[] moreInfo = info.split(",");
tracker.put(moreInfo[0], Integer.parseInt(moreInfo[1]));
}
}catch(ArrayIndexOutOfBoundsException aiobe){ }
this.questTracker = tracker;
//defineQuestLevel();
} |
fbb8b7c4-30a4-4447-b605-2aa5ca8b9078 | 6 | public boolean isNearTree(Coordinate coord) {
ElementType to;
for (int i = 0; i < 4; i++) {
Coordinate coordTemp = coord.copy();
switch (i) {
case 0:
coordTemp.moveNorth();
break;
case 1:
coordTemp.moveEast(dimension);
break;
case 2:
coordTemp.moveSouth(dimension);
break;
case 3:
coordTemp.moveWest();
break;
default:
break;
}
to = getCell(coordTemp).getElementType();
if (to == ElementType.TRUNK)
return true;
}
return false;
} |
f5daf891-ed0d-455f-966c-be52bdb8b03b | 7 | private JSONWriter append(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null pointer");
}
if (this.mode == 'o' || this.mode == 'a') {
try {
if (this.comma && this.mode == 'a') {
this.writer.write(',');
}
this.writer.write(string);
} catch (IOException e) {
throw new JSONException(e);
}
if (this.mode == 'o') {
this.mode = 'k';
}
this.comma = true;
return this;
}
throw new JSONException("Value out of sequence.");
} |
d9e7ce12-7b3e-4c7b-8177-b49668df2c33 | 2 | public void setDAO(String daoLine) {
if (daoLine.equals("Mock")) {
dao = new MockDAO();
}
else if (daoLine.equals("MySQL")) {
dao = new MySQLDAO();
}
} |
26ac66a7-2777-4410-88ec-76c8f5a28a29 | 6 | public LayerMatcher(Layer layer)
{
// match 1 = tagname
// match 2 = id
// match 3 = attributes
String layerRegex = "^(<[a-z^>]*>)?([A-z\\-\\_]*)?(\\[.*\\])?$";
String layerName = layer.toString();
Pattern p = Pattern.compile(layerRegex);
Matcher m = p.matcher(layerName);
if(m.matches()) {
// get the tagname (if its there, otherwise default to div)
tag = m.group(1) != null ? m.group(1).substring(1, m.group(1).length() - 1) : "div";
// get the identification (if its there, otherwise leave it empty)
id = m.group(2) != null ? m.group(2) : "";
// check for attributes
if(m.group(3) != null) {
// has attributes
StringTokenizer st = new StringTokenizer(m.group(3).substring(1, m.group(3).length() - 1), ",");
StringTokenizer attr;
while(st.hasMoreTokens()) {
attr = new StringTokenizer(st.nextToken(), "=");
while(attr.hasMoreTokens()) {
String key = attr.nextToken();
String value = attr.nextToken();
attributes.put(key, value.substring(1, value.length() - 1));
}
}
}
}
else {
// verdorie nog aan toe
System.err.println("Couldn't parse layer: " + layerName);
}
} |
c5685bcb-ded2-44d3-a51f-963bda51332c | 1 | public static synchronized Config getInstance() {
if (instance == null) {
instance = new Config();
}
return instance;
} |
896d8acf-8597-4657-85d3-6240aefe1a32 | 8 | public static void main(String[] args) throws IOException {
String s;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Integer t = new Integer(br.readLine());
for(int i=0;i<t;i++){
s = br.readLine();
if(s.length()>3){
System.out.println("3");
}
else{
if((s.contains("o")) && (s.contains("e"))||(s.contains("e")) && (s.contains("n"))||(s.contains("o")) && (s.contains("n"))){
System.out.println("1");
}
else{
System.out.println("2");
}
}
}
} |
fe380f10-edd2-46b1-bbe8-6e4b7d01f807 | 1 | public boolean _setMapCanvas(GenericCanvas mapcanvas)
{
if(mapcanvas != null)
{
this.mapcanvas = mapcanvas;
return true;
}
else
{
return false;
}
} |
b4260155-cfec-4766-bf02-f339109bbd20 | 6 | public void reserve() {
if (this.capacity - this.length < JSONzip.substringLimit) {
int from = 0;
int to = 0;
this.root = new Node();
while (from < this.capacity) {
if (this.uses[from] > 1) {
Kim kim = this.kims[from];
int thru = this.thrus[from];
Node node = this.root;
for (int at = this.froms[from]; at < thru; at += 1) {
Node next = node.vet(kim.get(at));
node = next;
}
node.integer = to;
this.uses[to] = age(this.uses[from]);
this.froms[to] = this.froms[from];
this.thrus[to] = thru;
this.kims[to] = kim;
to += 1;
}
from += 1;
}
// It is possible, but highly unlikely, that too many items survive.
// If that happens, clear the keep.
if (this.capacity - to < JSONzip.substringLimit) {
this.power = 0;
this.root = new Node();
to = 0;
}
this.length = to;
while (to < this.capacity) {
this.uses[to] = 0;
this.kims[to] = null;
this.froms[to] = 0;
this.thrus[to] = 0;
to += 1;
}
}
} |
d48f285b-e3a0-4f15-9048-b02a24497624 | 1 | public ArrayList<Pizza> haeMyydyimmat() throws DAOPoikkeus {
// Hakee etusivulle tiedot kolmesta myydyimmästä pizzasta.
TilastointiDAO tilasto = new TilastointiDAO();
ArrayList<Toppizzat> pizzatop = tilasto.haeToppizzat();
TuoteDAO tDao = new TuoteDAO();
Pizza pizza = new Pizza();
ArrayList<Pizza> myydyimmat = new ArrayList<Pizza>();
for (int i = 0; i < pizzatop.size(); i++) {
pizza = tDao.haePizza(pizzatop.get(i).getId());
myydyimmat.add(pizza);
}
return myydyimmat;
} |
a106622f-5fd4-4323-834b-6aeeb252e573 | 2 | @Override
public void setCourseName(String courseName) {
if(courseName == null || courseName.length() == 0) {
JOptionPane.showMessageDialog(null,
"Error: courseName cannot be null of empty string");
System.exit(0);
}
this.courseName = courseName;
} |
f67901ae-01aa-44c4-91d2-7e20cdd69846 | 6 | public static void main(String args[]) throws Exception
{
final int TOP = 200;
String outputPath = "C:/z-ling/task/HEY/ResultTest/HamTopSim_"+TOP+".txt";
FileOutputStream fos=new FileOutputStream(outputPath);
OutputStreamWriter osw=new OutputStreamWriter(fos);
BufferedWriter bw=new BufferedWriter(osw);
String fileDir = "C:/z-ling/task/HEY/ResultTest/testDataset2";
File f=new File( fileDir);
File[] fs=f.listFiles();
HashMap<String,Float> map = new HashMap<String,Float>();
for(int i=0;i<fs.length;i++){
if(fs[i].isFile()){
File file = new File(fs[i].toString());
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
String tmp[] = tempString.split("\t" , 3);
String key = tmp[0]+"\t"+tmp[1];
String value = tmp[2];
map.put(key, Float.parseFloat(value));
}
reader.close();
}
}
//sort
List<Map.Entry<String, Float>> infoIds =
new ArrayList<Map.Entry<String, Float>>(map.entrySet());
// //����ǰ
// for (int i = 0; i < infoIds.size(); i++) {
// String id = infoIds.get(i).toString();
// System.out.println(id);
// }
//����
Collections.sort(infoIds, new Comparator<Map.Entry<String, Float>>() {
public int compare(Map.Entry<String, Float> o1, Map.Entry<String, Float> o2) {
//sorted by value
if(o2.getValue() - o1.getValue()>= 0)
return 1;
else
return -1;
//sorted by key
// return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
//�����
for (int i = 0; i < infoIds.size() && i< TOP; i++) {
String id = infoIds.get(i).toString();
String[] s = id.split("=");
bw.write(s[0]+"\t"+s[1]);
bw.newLine();
}
bw.close();
System.out.println("Compeleted");
} |
30034516-44bb-4b36-a34c-a2344b203edc | 2 | public JSONObject putOpt(String key, Object value) throws JSONException {
if (key != null && value != null) {
this.put(key, value);
}
return this;
} |
2861ed46-1abe-40c8-a203-904a8505a1ab | 5 | public Button loadButton(Location loca) {
String wName = loca.getWorld().getName();
String saveLoc = Utils.convertLoc(loca);
Button button = new Button();
buttonConfig = new Configuration(new File(configDir + File.separator + "buttons" + File.separator + wName + File.separator + saveLoc + ".yml"));
File finder = new File(configDir + File.separator + "buttons" + File.separator + wName + File.separator + saveLoc + ".yml");
if(finder.exists()) {
buttonConfig.load();
button.setOwner(buttonConfig.getString("owner"));
button.setWorld(wName);
button.setLoc(saveLoc);
button.setPushes(buttonConfig.getInt("pushes"));
button.setIsCharge(buttonConfig.getBoolean("isCharge"));
//Example action config FlatFile
//size = 2
//action_0:
// actionArgs: //0
// -'0' //0
// actionName: charge //0
//action_1:
// actionArgs: //1
// -'HelloWorld' //0
// actionName: text //1
for(int i = 0;i < buttonConfig.getInt("size");i++) {
String[] a = {"", "", "", ""};
for(int j = 0;j < buttonConfig.getStringList("action_" + i + ".actionArgs").size();j++) {
try {
a[j] = buttonConfig.getStringList("action_" + i + ".actionArgs").get(j);
} catch (Exception e) {
log.info(e.toString());
}
}
button.actionArgs.put(i, a);
button.actionNames.put(i, buttonConfig.getString("action_" + i + ".actionName"));
}
List<String> b = new ArrayList<String>();
for(int j = 0;j < buttonConfig.getInt("rSize");j++) {
b.add(buttonConfig.getString("player_" + j));
}
button.setPlayers(b);
return button;
} else {
return null;
}
} |
2221a378-fd45-44fb-b9f8-249b309ea1d0 | 2 | protected void processMouseWheelEvent(MouseWheelEvent e) {
if (hasFocus()) {
int code = InputManager.MOUSE_WHEEL_DOWN;
if (e.getWheelRotation() < 0) {
code = InputManager.MOUSE_WHEEL_UP;
}
mapGameAction(code, true);
}
e.consume();
} |
97a9d34a-0141-4330-8809-64e972ac05e2 | 5 | public static int deleteMstxRecommend(int mid) {
int result = 0;
Connection con = DBUtil.getConnection();
PreparedStatement pstmt = null;
try {
pstmt = con.prepareStatement("delete from mstx_recommend where mid=?");
pstmt.setInt(1, mid);
result = pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
} |
54e77dc9-9a6a-458a-ab24-adf22247f591 | 6 | public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
int[] rgb = new int[3];
int ladoCuadrado;
int ladoMax = 200,
ladoMin = 100;
boolean rgbValido = true;
do System.out.print("Dame el lado del cuadrado [100, 200]: ");
while((ladoCuadrado = teclado.nextInt()) < ladoMin || ladoCuadrado > ladoMax);
do{
rgbValido = true;
System.out.print("Dame los valores del color (R, G, B): ");
rgb[0] = teclado.nextInt();
rgb[1] = teclado.nextInt();
rgb[2] = teclado.nextInt();
for(int i=0; i<rgb.length; i++){
if(rgb[i] < 0 || rgb[i] > 255) rgbValido = false;
}
}while(!rgbValido);
Rectangle cuadrado = new Rectangle(10, 10, ladoCuadrado, ladoCuadrado);
cuadrado.setColor(new Color(rgb[0], rgb[1], rgb[2]));
cuadrado.fill();
teclado.close();
} |
7db8c949-d632-4ab7-92e7-fbbd2ecba83f | 9 | public SortedList quicksort(ListNode head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head==null || head.next==null) return new SortedList(head, head);
ListNode lHead = null;
ListNode gHead = null;
ListNode eHead = head;
ListNode cur = head.next;
head.next = null;
ListNode temp;
while(cur!=null) {
if (cur.val > head.val) {
temp = cur.next;
// Insert current node before gHead node
cur.next = gHead;
gHead = cur;
cur = temp;
}
else if(cur.val < head.val){
temp = cur.next;
cur.next = lHead;
lHead = cur;
cur = temp;
}
else {
temp = cur.next;
cur.next = eHead;
eHead = cur;
cur = temp;
}
}
SortedList sl = quicksort(lHead);
SortedList sg = quicksort(gHead);
SortedList rs;
if(sl.head==null && sg.head==null){
rs = new SortedList(eHead, head);
}
else if(sl.head==null){
head.next = sg.head;
sg.tail.next = null;
rs = new SortedList(eHead, sg.tail);
}
else if (sg.head == null) {
sl.tail.next = eHead;
head.next = null;
rs = new SortedList(sl.head, head);
}
else {
sl.tail.next = eHead;
head.next = sg.head;
sg.tail.next = null;
rs = new SortedList(sl.head, sg.tail);
}
return rs;
} |
05253122-96a1-487f-9199-14c2613b9a5a | 5 | private void spawnFruit() {
//Reset the score for this fruit to 100.
this.nextFruitScore = 100;
/*
* Get a random index based on the number of free spaces left on the board.
*/
int index = random.nextInt(BoardPanel.COL_COUNT * BoardPanel.ROW_COUNT - snake.size());
/*
* While we could just as easily choose a random index on the board
* and check it if it's free until we find an empty one, that method
* tends to hang if the snake becomes very large.
*
* This method simply loops through until it finds the nth free index
* and selects uses that. This means that the game will be able to
* locate an index at a relatively constant rate regardless of the
* size of the snake.
*/
int freeFound = -1;
for(int x = 0; x < BoardPanel.COL_COUNT; x++) {
for(int y = 0; y < BoardPanel.ROW_COUNT; y++) {
TileType type = board.getTile(x, y);
if(type == null || type == TileType.Fruit) {
if(++freeFound == index) {
board.setTile(x, y, TileType.Fruit);
break;
}
}
}
}
} |
36153b4a-5cea-4af7-bdc5-698854ea342e | 2 | @Override
public ParseResult<T, A> parse(LList<T> tokens) {
ParseResult<T,A> r = this.parser.parse(tokens);
if(!r.isSuccess()) {
// parser failed -> fail
return r;
} else if(this.pred.apply(r.getValue())) {
// result is present and predicate passes -> pass
return r;
} else {
// result is present but predicate fails -> fail
return ParseResult.failure("'check' failed", tokens);
}
} |
a6ad9e17-740d-446f-9d7f-c1c23cd3ce9e | 0 | public void run(){
} |
41071c19-25f0-468a-9d5c-47d6e9385f46 | 5 | public Tile(int x, int y, int tilesize, Sprite sprite){
this.x = x;
this.y = y;
this.dX = 0;
this.dY = 0;
this.dir = 1;
this.tilesize = tilesize;
this.sprite = sprite;
this.crect = new Rectangle(x,y,tilesize,tilesize);
if (sprite != null) {
this.id = sprite.getId();
if (this.id > 0 && this.id <= 20) {
solid = true;
moveable = false;
}
if (this.id > 60 && this.id <= 80) {
solid = true;
moveable = true;
}
} else {
solid = false;
moveable = false;
}
} |
5610e956-1a40-4d62-be76-ac33ddd25fb0 | 1 | public int read(CharBuffer cb) {
if (count-- == 0)
return -1;
String result = Double.toString(next()) + " ";
cb.append(result);
return result.length();
} |
9b33f82d-f887-4297-ba62-a3e43c39e41e | 0 | @Override
public void setBoilerState(int boilerState) {
this.boilerState = boilerState;
} |
b2a3f0c1-f8d4-41c5-aa41-a07f933625fc | 4 | public void translateDemands(int period, Conversion cons) {
//
// Firstly, we check to see if the output good is in demand, and if so,
// reset demand for the raw materials-
final float demand = shortageOf(cons.out.type) ;
if (verbose) I.sayAbout(venue, "Demand for "+cons.out.type+" is: "+demand) ;
if (demand <= 0) return ;
float priceBump = 1 ;
//
// We adjust our prices to ensure we can make a profit, and adjust demand
// for the inputs to match demand for the outputs-
final Demand o = demandRecord(cons.out.type) ;
o.pricePaid = o.type.basePrice * priceBump / (1f + cons.raw.length) ;
for (Item raw : cons.raw) {
if (verbose) I.sayAbout(venue, "Needs "+raw) ;
final float needed = raw.amount * demand / cons.out.amount ;
incDemand(raw.type, needed, TIER_CONSUMER, period) ;
}
} |
f171ee75-a733-461b-a99a-0497d08df311 | 2 | public static SingleItem getItem(int id) {
String input = null;
try {
input = Untils.readPage(new URL(SINGLE_ITEM + id));
} catch (MalformedURLException e) {
e.printStackTrace();
}
HashMap<String, Object> parse = Parser.parse(input);
if (parse.get("name") == null)
return null;
parse = Parser.fixData(parse);
String name = parse.get("name").toString().trim();
int parse_id = (int) parse.get("ge_id");
int parse_marketPrice = (int) parse.get("mark_price");
double parse_dailyChange = (double) parse.get("daily_pct_change");
double parse_monthlyChange = (double) parse.get("_30_day_change");
double parse_halfHalfYearlyChange = (double) parse.get("_90_day_change");
double parse_halfYearlyChange = (double) parse.get("_180_day_change");
return new SingleItem(name, parse_id, parse_marketPrice, parse_dailyChange, parse_monthlyChange, parse_halfHalfYearlyChange, parse_halfYearlyChange);
} |
afa1be69-7e0a-4c28-a6f8-cd0d8f131018 | 7 | @Override
public void writeBuffer(ReceiveBuffer wbuf) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
if(wbuf.length() >=4 && wbuf.charAt(0)=='M' && wbuf.charAt(1)=='1' &&wbuf.charAt(2)=='0' &&wbuf.charAt(3)=='5' ){
isM105=true;
}
sendbuf.put(wbuf.array,0,wbuf.length());
isSend=true;
buffer[bufferpos++] = sio.state.lastgcode;
buffercnt++;
if(sio.state.debug){
cons.appendText("Dummy Received:'"+wbuf.toString()+"'");
}
} |
eaaa5507-ac70-41d0-851d-58ad862b82e3 | 8 | private void testData() {
if ((useKNN() && knn != null) || (!useKNN() && gaussian != null)) {
int c = 1;
int numClasses = getNumTestClasses();
int[][] confusionMatrix = new int[numClasses][numClasses];
while (classHasFiles(String.format("c:/ordata/test-%s",testTextField.getText()), String.format("%d",c))) {
int i = 1;
boolean done = false;
while (!done) {
String strFileName = String.format("c:/ordata/test-%s/c%d-%d.jpg",testTextField.getText(),c,i);
File f = new File(strFileName);
if (f.exists()) {
System.out.printf("Processing '%s'\n", strFileName);
int eval_c = processImageFileAndTest(strFileName, c);
if (eval_c == c) {
System.out.printf("'%s' was classified correctly!\n", strFileName);
confusionMatrix[c-1][c-1]++;
} else {
System.out.printf("'%s' (expected %d) was mis-classified as %d\n", strFileName, c, eval_c);
confusionMatrix[c-1][eval_c-1]++;
}
} else {
done = true;
}
i++;
}
c++;
}
displayConfusionMatrix(confusionMatrix);
}
} |
f54c0227-1163-43bd-9f22-a0acb3b5efc6 | 9 | public static void main( String[] args ) throws Exception
{
TestingHelper.CONFIG.read();
OptionManager.initialize( TestingHelper.CONFIG ); // initialize options from config file
OptionManager.initialize( args ); // initialize options from commandline (override the config file)
OptionManager.registerClass( "Scheduler", Scheduler.class );
OptionManager.registerClass( "Test", RegionTester.class );
System.out.println();
TestingHelper.createDisplay();
TestingHelper.setupGL();
TestingHelper.initInput();
Region region = new Region( new CGModulus(), 0, 0, 0 );
region.rebuild();
Camera camera = new Camera(); // the camera of the player
camera.setMinimumPitch( 15f );
camera.setMaximumPitch( 165f );
Controller controller = new Controller( camera ); // the controller for the camera
Input.setBinding( "removeBlocks", InputMedium.KEYBOARD, Keyboard.KEY_R );
Input.setBinding( "addBlocks", InputMedium.KEYBOARD, Keyboard.KEY_F );
Input.setBinding( "saveRegion", InputMedium.KEYBOARD, InputMode.BUTTON_RELEASED, Keyboard.KEY_O );
Input.setBinding( "loadRegion", InputMedium.KEYBOARD, InputMode.BUTTON_RELEASED, Keyboard.KEY_L );
Input.setBinding( "toggleVSync", InputMedium.KEYBOARD, InputMode.BUTTON_RELEASED, Keyboard.KEY_V );
Input.setBinding( "addLighting", InputMedium.KEYBOARD, InputMode.BUTTON_RELEASED, InputMask.CONTROL_MASK, Keyboard.KEY_L );
Input.setBinding( "remLighting", InputMedium.KEYBOARD, InputMode.BUTTON_RELEASED, InputMask.MENU_MASK, Keyboard.KEY_L );
while ( !Display.isCloseRequested() )
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // clear the last frame
Input.poll(); // poll the input
TestingHelper.processInput( camera, controller ); // move and orient the player
if ( Input.isBindingActive( "removeBlocks" ) )
{
removeBlocks( region );
}
if ( Input.isBindingActive( "addBlocks" ) )
{
addBlocks( region );
}
if ( Input.isBindingActive( "saveRegion" ) )
{
saveRegion( region );
}
if ( Input.isBindingActive( "loadRegion" ) )
{
loadRegion( region );
}
if ( Input.isBindingActive( "toggleVSync" ) )
{
if ( VSyncEnabled )
{
OptionManager.setValue( "VSync", "Disabled" );
}
else
{
OptionManager.setValue( "VSync", "Enabled" );
}
}
if ( Input.isBindingActive( "addLighting" ) )
{
TestingHelper.enableLighting();
}
if ( Input.isBindingActive( "remLighting" ) )
{
TestingHelper.disableLighting();
}
Scheduler.doTick(); // ticks the scheduler
renderScene( camera, region ); // render the scene
TestingHelper.updateDisplay( "Region Tester", FPSCap );
}
TestingHelper.destroy(); // destroys everything
} |
ddcdbe0b-0ef7-4771-88ed-910185a01821 | 7 | @EventHandler
public void WitherSpeed(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Wither.Speed.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof WitherSkull) {
WitherSkull a = (WitherSkull) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getWitherConfig().getBoolean("Wither.Speed.Enabled", true) && shooter instanceof Wither && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, plugin.getWitherConfig().getInt("Wither.Speed.Time"), plugin.getWitherConfig().getInt("Wither.Speed.Power")));
}
}
} |
57a04f65-0f54-4043-bad4-14b09b1c2132 | 0 | protected void onDeVoice(String channel, String sourceNick, String sourceLogin, String sourceHostname, String recipient) {} |
8cb4d747-699a-443c-b43e-bb75c58c5de9 | 2 | private boolean setCoordinates(int r, int c) {
// If the coordinates are not already set
if (!areCoordinatesSet()) {
// Ensure valid coordinates
if (!validCoordinates(r, c)) {
throw new IllegalArgumentException("Invalid coordinates");
}
// Set the coordinates
row = r;
col = c;
return true;
}
else {
return false;
}
} |
10d09cf9-5a93-46a9-bd57-df454a98617d | 7 | public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getBarDateTime() != null) {
_hashCode += getBarDateTime().hashCode();
}
if (getOpen() != null) {
_hashCode += getOpen().hashCode();
}
if (getHigh() != null) {
_hashCode += getHigh().hashCode();
}
if (getLow() != null) {
_hashCode += getLow().hashCode();
}
if (getClose() != null) {
_hashCode += getClose().hashCode();
}
if (getVolume() != null) {
_hashCode += getVolume().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
} |
19cb41e6-679e-4505-9ec7-a85b383f84e3 | 6 | public void render(Graphics g){
g.setColor(Color.BLACK);
int size = display.frame.getHeight() / 12;
int xOff = (display.frame.getWidth() - size * 9) / 2;
int yOff = (display.frame.getHeight() - size * 9) / 4;
for(int x = 0; x < 9; x++){
for(int y = 0; y < 9; y++){
if(board.get(x).get(y) != 0){
if(set.contains(x + "," + y)){
BufferedImage img = new BufferedImage(200,200,BufferedImage.TYPE_INT_RGB);
img.getGraphics().drawImage(ImageManager.get(board.get(x).get(y).toString()), 0, 0, null);
ImageManager.replaceColor(Color.BLACK.getRGB(), Color.RED.getRGB(), img);
g.drawImage(img, xOff + x * size, yOff + y * size, size, size, null);
} else {
g.drawImage(ImageManager.get(board.get(x).get(y).toString()), xOff + x * size, yOff + y * size, size, size, null);
}
}
g.drawRect(xOff + x * size, yOff + y * size, size, size);
g.fillRect((xOff + 9 * size) - (size / 30), yOff, size / 15, size * 9);
g.fillRect(xOff, (yOff + 9 * size) - (size / 30), size * 9, size / 15);
if(x % 3 == 0){
g.fillRect(xOff + x * size - (size / 30), yOff + y * size, size / 15, size);
}
if(y % 3 == 0){
g.fillRect(xOff + x * size, yOff + y * size - (size / 30), size, size / 15);
}
}
}
} |
d4a59ea4-9799-40bc-a323-ab7de158f462 | 0 | public String getIP() {
return clientIP;
} |
f120839f-7be7-4f20-a064-3c7fe7718232 | 7 | public void start() {
try {
this.createWindow();
try {
Keyboard.create();
Mouse.create();
} catch (LWJGLException e) {
e.printStackTrace();
}
this.postInit();
while (!Display.isCloseRequested()) {
Display.update();
this.getCamera().input();
this.input();
if(this.isHandleRootUpdate())
this.getRootObject().input();
this.update();
if(this.isHandleRootUpdate())
this.getRootObject().update();
this.updateDisplay();
if(this.isHandleRootUpdate())
this.getRootObject().render();
if (!this.getWindowConfiguration().isVsync()) {
Display.sync(this.getWindowConfiguration().getFps());
}
}
Display.destroy();
System.exit(0);
} catch (Exception e1) {
e1.printStackTrace();
Display.destroy();
Keyboard.destroy();
Mouse.destroy();
System.exit(1);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.