method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
db0d1c6f-8336-4cdc-aa95-02d9f0e54642
| 1
|
public List<String> getValues() {
List<String> valuesList = new ArrayList<String>();
for(int i = 0; i < size; i++) {
valuesList.addAll(map[i].getValues());
}
return valuesList;
}
|
7caab213-4e94-4e5e-ad6e-6b3fed7992fa
| 5
|
public static Staff getStaffByID(String staffID){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Statement stmnt = conn.createStatement();
String sql = "SELECT * FROM Staff where staff_id= "+staffID;
ResultSet res = stmnt.executeQuery(sql);
while(res.next()) {
login = new Login(res.getString("staff_id"), res.getString("password"));
staff = new Staff(res.getString("name"), res.getString("first_name"), res.getString("function"), login);
}
}
catch(SQLException e) {
}
return staff;
}
|
829168cd-5c22-469c-b812-c80a5d503f16
| 6
|
public void render()
{
if(isMoving())
{
if(hspeed < 0){
prevDir = LEFT;
anim_left.play();
drawImage(anim_left.getImage(), (int)x, (int)y, 0);
anim_left.update();
}
else if(hspeed > 0) {
prevDir = RIGHT;
anim_right.play();
drawImage(anim_right.getImage(), (int)x, (int)y, 0);
anim_right.update();
}
else if(vspeed < 0) {
prevDir = UP;
anim_back.play();
drawImage(anim_back.getImage(), (int)x, (int)y, 0);
anim_back.update();
}
else if(vspeed > 0) {
prevDir = DOWN;
anim_front.play();
drawImage(anim_front.getImage(), (int)x, (int)y, 0);
anim_front.update();
}
}
else
{
anim_left.stop();
anim_right.stop();
anim_front.stop();
anim_back.stop();
drawImage(img_fix[prevDir], (int)x, (int)y, 0);
}
if(shieldOn) drawImage(armure, (int)x, (int)y, 270);
}
|
39d2cff6-f4f5-406c-bed2-0f43e0937e1c
| 1
|
private Venda finazilarVenda(double desconto, String formaPagamento, String cliente, String dependente) throws ExceptionGerenteVendas {
if(atual != null){
atual.addDesconto(desconto);
atual.setFormaPagamento(formaPagamento);
atual.setCliente(cliente);
atual.setDependente(dependente);
this.vendas.add(atual);
Venda aux = atual;
atual = null;
return aux;
}
throw new ExceptionGerenteVendas( "A venda deve ser criada antes de ser finalizada" );
}
|
82be55f4-23c3-475f-ba1c-12891269238b
| 4
|
private boolean yesOrNo() {
String yesOrNo = scanYesOrNo();
switch (yesOrNo) {
case "YES":
case "Y":
return true;
case "NO":
case "N":
return false;
default:
return false;
}
}
|
01818429-747a-4c97-a956-c5c632109d80
| 8
|
public void onKeyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case VK_UP:
case VK_W:
// Arrow up key: move direction = forward (infinitely)
moveDirection = 1;
moveAmount = Double.POSITIVE_INFINITY;
break;
case VK_DOWN:
case VK_S:
// Arrow down key: move direction = backward (infinitely)
moveDirection = -1;
moveAmount = Double.POSITIVE_INFINITY;
break;
case VK_RIGHT:
case VK_D:
// Arrow right key: turn direction = right
turnDirection = 1;
break;
case VK_LEFT:
case VK_A:
// Arrow left key: turn direction = left
turnDirection = -1;
break;
}
}
|
8d01b4ff-e63d-418d-9fb7-5eefa92b9f25
| 5
|
public boolean addSentence(String word, final Sentence sentence)
throws IOException {
final boolean[] added = new boolean[] { true };
final int[] count = new int[] { 0 };
File file = getWordFile(word);
if (file.exists()) {
if (file.length() > 40000)
return false;
scan(file, new SentenceParserCallback() {
@Override
public boolean found(Sentence sentence1) {
if (sentence.equals(sentence1)) {
added[0] = false;
}
count[0]++;
return true;
}
});
}
if (added[0]) {
FileOutputStream fs;
if (file.exists())
fs = new FileOutputStream(file, true);
else
fs = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fs);
dos.writeUTF(sentence.text);
dos.writeUTF(sentence.bookId);
dos.writeInt(sentence.section);
dos.writeInt(-1);// reserved for position
dos.close();
count[0]++;
}
database.setInSentenceCount(word, count[0]);
return added[0];
}
|
a0291612-3424-4f90-8f8d-9f0531e8eabd
| 1
|
public static Sistema getInstance() {
if (instance == null) {
instance = new Sistema();
}
return instance;
}
|
94075bd9-c0f1-49a5-b647-9d437c3a6a7f
| 7
|
public Object nextValue() throws JSONException {
char c = this.nextClean();
String string;
switch (c) {
case '"':
case '\'':
return this.nextString(c);
case '{':
this.back();
return new JSONObject(this);
case '[':
this.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 = this.next();
}
this.back();
string = sb.toString().trim();
if ("".equals(string)) {
throw this.syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
}
|
c9e6cbb0-caba-46fc-9130-e170d27ad16d
| 4
|
private void saveConfig(){
String str = new String();
for(int i=0; i<config.length; i++)
str = new String(str+properties[i]+";"+config[i]+"\r\n");
BufferedWriter writer = null;
try{
writer = new BufferedWriter( new FileWriter(file));
writer.write(str);
} catch ( IOException e){}
finally{
try{ if ( writer != null)
writer.close( );
}catch ( IOException e){}
}
}
|
75d5c50c-1258-44d0-9cd1-d93ad7af5596
| 2
|
public void loadConfigFiles() {
try {
loadBoardConfigFile();
loadLegendConfigFile();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (BadConfigFormatException e) {
System.out.println(e.getMessage());
}
}
|
1ec39c10-da89-4c21-a10e-8a2b01440435
| 5
|
public static void main(String[] args) {
if (args.length > 1) {
System.err.println("Usage: java HackAssembler [.asm name]");
System.exit(-1);
}
@SuppressWarnings("unused")
HackTranslator assembler;
//If a file is passed as an argument assemble it and quit
if (args.length == 1) {
try {
assembler = new AssemblyParser(args[0] , true);
} catch (HackTranslatorException ae) {
System.err.println(ae.getMessage());
System.exit(1);
}
}
//if no arguments were passed start the GUI
else {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
}
try {
HackAssemblerGUI gui = new AssemblerComponent();
gui.setAboutFileName(HELPFILES_PATH+"asmAbout.html");
gui.setUsageFileName(HELPFILES_PATH+"asmUsage.html");
assembler = new AssemblyParser(gui, Definitions.ROM_SIZE, (short)0, null);
} catch (HackTranslatorException hte) {
System.err.println(hte.getMessage());
System.exit(-1);
}
}
}
|
ac1ccaa5-01ba-4532-b1ad-8765f7907686
| 0
|
public int calculate(int a, int b)
{
return a / b;
}
|
2b1de50a-c26d-4f51-9a67-9addfa54aaff
| 9
|
final private boolean jj_3R_23() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_28()) {
jj_scanpos = xsp;
if (jj_3R_29()) {
jj_scanpos = xsp;
lookingAhead = true;
jj_semLA = (getToken(1).kind == INDENTIFIER1 || getToken(1).kind == INDENTIFIER2) &&
jep.funTab.containsKey(getToken(1).image);
lookingAhead = false;
if (!jj_semLA || jj_3R_30()) {
jj_scanpos = xsp;
if (jj_3R_31()) {
jj_scanpos = xsp;
if (jj_3R_32()) {
jj_scanpos = xsp;
if (jj_3R_33()) return true;
}
}
}
}
}
return false;
}
|
cf33b4fc-bf0a-4201-9346-65b52abfb03d
| 1
|
public static String getStackTrace(Throwable t) {
String stackTrace = null;
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
sw.close();
stackTrace = sw.getBuffer().toString();
} catch (Exception ex) {
}
return stackTrace;
}
|
6f90f82c-1928-4622-8f28-54a38445ccc2
| 5
|
public Metadata(Object obj) {
primitiveValues = new HashSet<String>();
collectionsValues = new HashSet<String>();
associatedValues = new HashSet<String>();
this.obj = obj;
if (obj == null) {
classMetadata = null;
return;
}
classMetadata = getClassMetadata(obj.getClass());
if (classMetadata == null) {
return;
}
String[] names = classMetadata.getPropertyNames();
for (int i = 0; i < names.length; i++) {
String name = names[i];
Type type = classMetadata.getPropertyType(name);
Set<String> targetSet;
if (type.isCollectionType()) {
targetSet = collectionsValues;
} else if (type.isEntityType()) {
// TODO check this
targetSet = associatedValues;
} else {
targetSet = primitiveValues;
}
targetSet.add(name);
}
}
|
c351ef52-815d-4dac-86fc-bfa7a1da82d2
| 9
|
@Override
public Result select(String[] conditions, String[] arguments) {
//Check for parameter errors
if(arguments.length>1){
return new Result(102);
}else if(conditions.length!=arguments.length){
return new Result(103);
}else {
String[] temp = new String[7];
//Encapsulate in a try/catch to prevent database errors
try{
//This part transforms the parameters into a query that the database can handle
String toSend="SELECT * FROM PRODUCTS WHERE ";
for(int i=0; i<conditions.length; i++){
toSend=toSend+" "+conditions[i]+"="+arguments[i];
//Adds and AND in each for and doesn't in the last loop
if(i!=(conditions.length-1))
toSend=toSend+" AND ";
}
//This part of the code makes the DATABASE CONNECTION
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:" + databasePath +"/"+ databaseName);
c.setAutoCommit(false);
//This part of the code makes the QUERY
//This stament will look inside PRODUCTS TABLE
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(toSend);
while ( rs.next() ) {
temp[0] = rs.getString("product_id");
temp[1] = rs.getString("barcode");
temp[2] = rs.getString("name");
temp[3] = rs.getString("description");
temp[4] = rs.getString("price");
}
rs.close();
stmt.close();
//This stament will look inside PRODUCTS_TAXES TABLE
toSend="SELECT * FROM PRODUCTS_TAXES WHERE product_id="+temp[0];
stmt = c.createStatement();
rs = stmt.executeQuery(toSend);
while ( rs.next() ) {
temp[5] = rs.getString("percent");
}
rs.close();
stmt.close();
//This stament will look inside PRODUCTS_QUANTITIES TABLE
toSend="SELECT * FROM PRODUCTS_QUANTITIES WHERE product_id="+temp[0];
stmt = c.createStatement();
rs = stmt.executeQuery(toSend);
while ( rs.next() ) {
temp[5] = rs.getString("quantity");
}
rs.close();
stmt.close();
//Closes the database connection
c.close();
} catch ( Exception e ) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
return new Result(100);
}
if(temp!=null)
return new Result(temp);
else
return new Result(104);
}
}
|
886d4c11-3b0e-4112-beca-62c0197734f0
| 5
|
final public Number number(boolean requireEOF) throws ParseException {
Number val = null;
Token t = null;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case INTEGER:
t = jj_consume_token(INTEGER);
val = new Long((t.image.startsWith("+")) ? t.image.substring(1) : t.image);
break;
case FLOAT:
t = jj_consume_token(FLOAT);
val = new Double(t.image.toLowerCase().replaceAll("d", "e"));
break;
default:
jj_la1[31] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
eof(requireEOF);
{if (true) return val;}
throw new Error("Missing return statement in function");
}
|
375c0f63-37f9-45f5-a297-c594163abf18
| 6
|
public <T> T requestService(Class<T> service) {
T result = null;
ServiceLoader<T> impl = ServiceLoader.load(service);
for (T loadedImpl : impl) {
result = loadedImpl;
if (result != null && DEFAULT_SERVICES.containsKey(service.getName())) {
if (DEFAULT_SERVICES.get(service.getName()).equals(result.getClass().getName())) {
System.out.println("had default");
break;
}
} else if (result != null) {
break;
}
}
if (result == null) {
throw new RuntimeException("Cannot find implementation for: " + service);
}
return result;
}
|
b23bfcdb-4d97-4549-bb13-d2df0eaabb0b
| 1
|
public void save(String fileName, String outputFormat) throws IOException {
BufferedImage output = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
int[] data = ((DataBufferInt) output.getRaster().getDataBuffer())
.getData();
for (int i = 0; i < data.length; i++) {
data[i] = pixels[i];
}
ImageIO.write(output, outputFormat, new File(fileName));
}
|
db90ba2f-dd40-4509-805b-6628c2a2f96b
| 0
|
public FrameGeneralWindow getMainWindow(){
return mainWindow;
}
|
ad39506b-0342-4629-9731-3e6983198c95
| 0
|
@Override
public double getArea() {
return Math.PI * _radius * _radius;
}
|
82913f7f-935e-4343-88be-77043bd32de3
| 0
|
@Override
public String getDesc() {
return "EarthQuake";
}
|
c42df320-e87d-4b82-a945-91f80ba855fb
| 3
|
public double winPossibility(ActionList history, GameInfo gameInfo, int playerHandStrength) {
// find number of raise actions in history
int numRaises = history.numberOfRaises();
// find histogram and adjusted hand strength
int[] histogram = historyToHandStrength.get(numRaises);
int aphs = adjustedHandStrength(playerHandStrength);
// if there is no observed history for this number of raises,
// return a default probability based on adjusted hand strength
if(histogram == null)
return 1 - (aphs / 8);
// calculate win% = hands player can defeat / total hands
int handsPlayerWins = 0;
int handsOpponentWins = 0;
int i;
for(i = 0; i < aphs; i++) {
handsOpponentWins += histogram[i];
}
for(; i < histogram.length; i++) {
handsPlayerWins += histogram[i];
}
return (double) handsPlayerWins / (handsPlayerWins + handsOpponentWins);
}
|
be232abb-b412-4c7e-9686-b81faf4134d9
| 0
|
public static void main(String[] args)
{
(new InterfaceDeUsuario()).menu() ;
}
|
7c32b31f-8a62-4098-aee2-708f945bbdff
| 3
|
@Override
public List<User> getAll() throws SQLException {
List<User>users = null;
Session session=null;
try{
session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
users = session.createCriteria(User.class).list();
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
}finally{
if(session!=null && session.isOpen())
session.close();
}
return users;
}
|
af0ff1c3-2e09-40a1-878f-5f5efbdd2d66
| 4
|
public boolean insert(final Block block) {
final Def def = operandAt(block);
if (def == null) {
return true;
}
if (!def.downSafe()) {
return true;
}
if ((def instanceof Phi) && !((Phi) def).willBeAvail()) {
return true;
}
return false;
}
|
c4a2c963-0ff6-4dfd-b22a-3c2cc3f57177
| 5
|
public void writeToSimpleAdjacencyList(ArrayList<Node> network, String file){
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(file));
Set<String> links = new HashSet<String>();
for(Node N : network)
{
if(N.id % 1000 == 0)
{
System.out.println("Node " + N.id);
}
for(int i=0;i<N.getDegree();i++)
{
if(!links.contains((N.getNeighbour(i).id + " " + N.id)))
{
links.add((N.id + " " + N.getNeighbour(i).id));
out.write(N.id + " " + N.getNeighbour(i).id + "\n");
}
}
}
out.flush();
out.close();
}
catch (Exception ex)
{
Logger.getLogger(NetworkGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
90699cec-d3f5-4449-a31e-90bb8506a5d5
| 2
|
@Override
public UsuarioBean set(UsuarioBean oUsuarioBean) throws Exception {
try {
oMysql.conexion(enumTipoConexion);
oMysql.initTrans();
if (oUsuarioBean.getId() == 0) {
oUsuarioBean.setId(oMysql.insertOne("usuario"));
}
oMysql.updateOne(oUsuarioBean.getId(), "usuario", "nombre", oUsuarioBean.getNombre());
oMysql.updateOne(oUsuarioBean.getId(), "usuario", "login", oUsuarioBean.getLogin());
oMysql.updateOne(oUsuarioBean.getId(), "usuario", "password", oUsuarioBean.getPassword());
oMysql.updateOne(oUsuarioBean.getId(), "usuario", "email", oUsuarioBean.getEmail());
oMysql.commitTrans();
} catch (Exception e) {
oMysql.rollbackTrans();
throw new Exception("UsuarioDao.setUsuario: Error: " + e.getMessage());
} finally {
oMysql.desconexion();
}
return oUsuarioBean;
}
|
da7e370f-4646-4c0c-93b0-d0c3807f9192
| 4
|
private int getNearestPeriodStartToAndBefore(LocalDateTime start) {
// compute periods count difference from referenceStart to given start
int periods = 0;
switch(repeatingPeriod.getClass().getName()) {
case "org.joda.time.Months":
periods = Months.monthsBetween(referenceIntervalStart,start ).getMonths() / ((Months)(repeatingPeriod)).getMonths();
break;
case "org.joda.time.Days":
periods = Days.daysBetween(referenceIntervalStart,start).getDays() / ((Days)(repeatingPeriod)).getDays();
break;
case "org.joda.time.Hours":
periods = Hours.hoursBetween(referenceIntervalStart,start).getHours() / ((Hours)(repeatingPeriod)).getHours();
break;
default:
throw new UnsupportedOperationException();
}
return periods < 0 ? periods : periods;
}
|
151081c5-04cc-49ae-aa81-dc8d1af5be56
| 7
|
public int largestRectangleArea(int[] height) {
// Start typing your Java solution below
// DO NOT write main() function
Stack<Integer> s = new Stack<Integer>();
int i = 0;
int max = 0;
int counter = 0;
while (i <= height.length - 1) {
if (s.isEmpty() || height[i] >= s.peek()) {
s.push(height[i]);
} else {
counter = 0;
while (!s.isEmpty() && height[i] < s.peek()) {
counter++;
max = Math.max(s.pop() * counter, max);// track the maximum
// area that cause
// by those pop
}
for (int j = 1; j <= counter + 1; j++) {
s.push(height[i]);// push back the smaller element for m
// times
}
}
i++;
}
counter = 0;
for (i = 0; i <= height.length - 1; i++) {
counter++;
max = Math.max(s.pop() * counter, max);
}
return max;
}
|
c9040bd2-26fb-4cbe-b218-989ebab78824
| 5
|
public ANN(Agent owner, Genotype g) throws WeigthNumberNotMatchException {
layers = new Vector<Layer>(g.getHiddenLayerCount());
this.owner = owner;
// Input layer
Layer inp = new Layer();
// Input neurons
inp.insertNeuron(new ConstantOneInputNeuron());
inp.insertNeuron(new HungerInputNeuron(this.owner));
inp.insertNeuron(new EyeInputNeuron(this.owner));
layers.add(inp);
Layer prevLayer = inp;
List<Double> genom = g.getGenes();
// hidden layers
int currGene = 0;
for (int i = 0; i < g.getHiddenLayerCount(); i++) {
Layer hidden = new Layer();
for (int n = 0; n < g.getGenesPerHiddenLayer(); n++) {
List<Double> weigths = new Vector<Double>(
prevLayer.getNeuronCount());
for (int j = 0; j < prevLayer.getNeuronCount(); j++) {
weigths.add(genom.get(currGene));
currGene++;
}
hidden.insertNeuron(new FeedForwardNeuron(prevLayer, weigths));
layers.add(hidden);
}
prevLayer = hidden;
}
// Finally, the output layer
Layer outp = new Layer();
for (int n = 0; n < ANN.outputNeuronCount; n++) {
List<Double> weigths = new Vector<Double>(
prevLayer.getNeuronCount());
for (int j = 0; j < prevLayer.getNeuronCount(); j++) {
weigths.add(genom.get(currGene));
currGene++;
}
outp.insertNeuron(new FeedForwardNeuron(prevLayer, weigths));
}
layers.add(outp);
}
|
9a96d0ed-df3c-4e68-abee-ff8cf204de79
| 5
|
public static void main(String[] args) throws ClassNotFoundException,
JsonParseException, JsonMappingException, IOException, SQLException {
TwitterModel twitterModel = null;
HbaseConfModel hbaseConfModel;
MediaConfModel mediaConfModel;
// TODO 設定ファイルでMariaDBなどに切り替える
// Class.forName("org.sqlite.JDBC");
Class.forName("org.h2.Driver");
if (args.length != 2) {
try {
twitterModel = TwitterConfParser
.readConf("conf/twitter_conf.json");
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
} else {
try {
twitterModel = TwitterConfParser.readConf(args[1]);
Application.load(args[0]);
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
//Configuration conf = HBaseConfiguration.create();
ApplicationConfParser applicationConfParser = new ApplicationConfParser(
"./conf/application.json");
hbaseConfModel = applicationConfParser.getHbaseConfModel();
mediaConfModel = applicationConfParser.getMediaConfModel();
/*
if (hbaseConfModel.isExecute()) {
List<String> resources = hbaseConfModel.getResource();
for (String resource : resources) {
conf.addResource(resource);
}
}*/
TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
twitterStream.setOAuthConsumer(twitterModel.getConsumerKey(),
twitterModel.getConsumerSecret());
twitterStream.setOAuthAccessToken(new AccessToken(twitterModel
.getAccessToken(), twitterModel.getAccessToken_secret()));
twitterStream.addListener(new MyStatusAdapter(applicationConfParser));
ArrayList<String> track = new ArrayList<String>();
track.addAll(Arrays.asList(Application.searchKeyword.split(",")));
System.out.println((Application.searchKeyword.split(",")).length);
String[] trackArray = track.toArray(new String[track.size()]);
if(Application.locations2DArray != null) {
twitterStream.filter(new FilterQuery(0, null, trackArray, Application.locations2DArray));
} else {
// 400のキーワードが指定可能、5000のフォローが指定可能、25のロケーションが指定可能
twitterStream.filter(new FilterQuery(0, null, trackArray));
}
if (mediaConfModel.isExecute()) {
MediaDownloderThread mediaDownloderThread = new MediaDownloderThread();
mediaDownloderThread.start();
}
}
|
c1b17c61-ba54-485d-a97e-7772e706e892
| 0
|
public void matchesAnnotatedWithType()
{
assert annotatedWithType( Test.class ).matches( this.getClass() );
assert !annotatedWithType( Parameters.class ).matches( this.getClass() );
}
|
e3769f72-b7a5-46d9-bdee-9e0ec70130c1
| 8
|
private void distinto() throws Exception{
op2 = pila.pop();
if (op2.getValor().equals("null"))
throw new Exception("Una de las variables esta sin inicializar!");
op1 = pila.pop();
if (op1.getValor().equals("null"))
throw new Exception("Una de las variables esta sin inicializar!");
Elem resultado = new Elem("boolean");
if(op1.getTipo().equals("boolean"))
{
int b1 = ((Boolean)op1.getValor()).booleanValue() ? 1 : 0;
int b2 = ((Boolean)op2.getValor()).booleanValue() ? 1 : 0;
resultado.setValor(b1 != b2);
}
else if(op1.getTipo().equals("character"))
resultado.setValor((((Character)op1.getValor()).charValue() != ((Character)op2.getValor()).charValue()));
else //Real, Entero o Natural
{
double f1 = op1.getTipo().equals("float")? (Double)op1.getValor() : ((Integer)op1.getValor()).doubleValue();
double f2 = op2.getTipo().equals("float")? (Double)op2.getValor() : ((Integer)op2.getValor()).doubleValue();
resultado.setValor(f1 != f2);
}
pila.push(resultado);
}
|
94992c79-a3e3-451c-a027-407289120aea
| 4
|
private static boolean checkAuto(String s, String t){
int sindex = 0;
for(int i=0;i<t.length();i++, sindex++){
while(sindex<s.length() && s.charAt(sindex)!=t.charAt(i)) sindex++;
if(sindex >= s.length()) return false;
}
return true;
}
|
9e6de5e8-1d88-462a-8953-44d2506bc983
| 4
|
public int getDestination(String input) {
if (destinations.containsKey(input)) return destinations.get(input);
else if (isOtherPunctuation(input)) return otherPunctuationDestination;
else if (isSpace(input)) return spaceDestination;
else if (isNum(input)) return numDestination;
else return defaultDestination;
}
|
720f3667-8cff-4a41-ac3e-f7380b5e404a
| 8
|
public int characterAt(int at) throws JSONException {
int c = get(at);
if ((c & 0x80) == 0) {
return c;
}
int character;
int c1 = get(at + 1);
if ((c1 & 0x80) == 0) {
character = ((c & 0x7F) << 7) | c1;
if (character > 0x7F) {
return character;
}
} else {
int c2 = get(at + 2);
character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2;
if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF
&& (character < 0xD800 || character > 0xDFFF)) {
return character;
}
}
throw new JSONException("Bad character at " + at);
}
|
c4fd8478-f6ca-4225-990d-5abaa7a71e06
| 4
|
public static IContextBuilder getBuilder(String str)
{
if (str.equals("text"))
return new TextBuilder();
else if (str.equals("image"))
return new ImageBuilder();
else if (str.equals("list"))
return new ListBuilder();
else if (str.equals("barcode"))
return new BarCodeBuilder();
else
return new TextBuilder();
}
|
05bcfe81-48c1-490e-9b89-151b3da32648
| 9
|
@Override
public int print(Graphics g, PageFormat pageFormat, int pageIndex)
throws PrinterException {
if (pageIndex >= tripsOfDay.size())
return NO_SUCH_PAGE;
Font oldFont = g.getFont();
Graphics2D g2d = (Graphics2D) g;
double scaleX = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
double scaleY = g2d.getDeviceConfiguration().getDefaultTransform().getScaleY();
// this is just to detect, if we print to screen or to a printer output
if (((scaleX == 1.0) && (scaleY == 1.0)) || !MainWindow.setupData.getPrintOnFormSheet())
g2d.drawImage(formSheet.getImage(), 0, 0, (int)pageFormat.getWidth(), (int)pageFormat.getHeight(), 0, 0, formSheet.getIconWidth(), formSheet.getIconHeight(), null);
putText (g2d, tripsOfDay.get(pageIndex).getGroupNumber().toString(), PrintElementSetupList.FONT_GROUP_NUMBER);
putText (g2d, tripsOfDay.get(pageIndex).getTotalGroupSize().toString(), PrintElementSetupList.FONT_GROUP_SIZE);
putText (g2d, tripsOfDay.get(pageIndex).getRiver().getRiverName(), PrintElementSetupList.FONT_RIVERNAME);
putText (g2d, new SimpleDateFormat("EEEE").format(dayToPrint) , PrintElementSetupList.FONT_GROUP_DAY);
putText (g2d, new SimpleDateFormat("dd.MM").format(dayToPrint) , PrintElementSetupList.FONT_GROUP_DATE);
putText (g2d, tripsOfDay.get(pageIndex).getRiver().getWwLevel(), PrintElementSetupList.FONT_WW_LEVEL);
if (tripsOfDay.get(pageIndex).getIsEducation())
putText (g2d, "X", PrintElementSetupList.FONT_EDUCATION);
else
putText (g2d, "X", PrintElementSetupList.FONT_TOUR);
putText (g2d, tripsOfDay.get(pageIndex).getRiver().getTripFrom(), PrintElementSetupList.FONT_FROM);
putText (g2d, tripsOfDay.get(pageIndex).getRiver().getTripTo(), PrintElementSetupList.FONT_TO);
putText (g2d, "" + tripsOfDay.get(pageIndex).getRiver().getTripLength(), PrintElementSetupList.FONT_TRIP_LENGTH);
putText (g2d, new SimpleDateFormat("HH:mm").format(tripsOfDay.get(pageIndex).getTripStartTime()) , PrintElementSetupList.FONT_TIME);
putText (g2d, "" + tripsOfDay.get(pageIndex).getRiver().getDistanceToStart(), PrintElementSetupList.FONT_DISTANCE);
putComment (g2d, "" + tripsOfDay.get(pageIndex).getComment(), PrintElementSetupList.FONT_COMMENT);
int d = tripsOfDay.get(pageIndex).getDriverCount();
if (d < 1) {
xout_car (g2d, PrintElementSetupList.PARA_XOUT_CAR_1);
}
if (d < 2) {
xout_car (g2d, PrintElementSetupList.PARA_XOUT_CAR_2);
}
if (d < 3) {
xout_car (g2d, PrintElementSetupList.PARA_XOUT_CAR_3);
}
if (tripsOfDay.get(pageIndex).getIsKidsTour()) {
xout_participants (g2d, PrintElementSetupList.PARA_XOUT_PARTICIPANTS_1,
PrintElementSetupList.PARA_XOUT_PARTICIPANTS_2,
tripsOfDay.get(pageIndex).getGroupSize());
// FIXME: patch driver label
}
else {
xout_participants (g2d, PrintElementSetupList.PARA_XOUT_PARTICIPANTS_1,
PrintElementSetupList.PARA_XOUT_PARTICIPANTS_2,
tripsOfDay.get(pageIndex).getGroupSize()- tripsOfDay.get(pageIndex).getDriverCount());
}
g.setFont(oldFont);
return PAGE_EXISTS;
}
|
55d8e49b-0525-4206-986e-b616b2b2f538
| 1
|
public OutputStream getOutputStream(){
try {
return socket.getOutputStream();
} catch (IOException e){}
return null;
}
|
b22a14e6-5619-4f7d-9de1-8faf6b28ae46
| 3
|
public Relojito() {
initComponents();
//aqui dentro del constructor programaremos.
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Calendar cal=Calendar.getInstance();
int hora=cal.get(Calendar.HOUR);
int minuto=cal.get(Calendar.MINUTE);
int segundo=cal.get(Calendar.SECOND);
String tiempo=hora+":"+minuto+":"+segundo;
if(segundo>10)Cuenta.setEditable(false);
else Cuenta.setEditable(true);
Etiqueta.setText(tiempo);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Relojito.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
t1.start();
}
|
b8346270-9602-4a0d-9899-2f454b912dee
| 9
|
public void start() throws IOException {
Set<SelectionKey> keys;
Iterator<SelectionKey> keyIterator;
this.keepGoing = true;
while (keepGoing) {
int readyChannels = this.selector.select();
if (readyChannels == 0) continue;
keys = this.selector.selectedKeys();
keyIterator = keys.iterator();
while (keyIterator.hasNext())
{
SelectionKey currentKey = keyIterator.next();
if (currentKey.isValid() && currentKey.isAcceptable())
addClient(currentKey);
if (currentKey.isValid() && currentKey.isReadable())
receivePacket(currentKey);
if (currentKey.isValid() && currentKey.isWritable())
{
// write data to the buffer and remove OP_WRITE
}
// Remove the key from the selected-set
keyIterator.remove();
}
}
}
|
1b6c8c69-b129-400f-91f2-361db428c65a
| 4
|
public boolean isOptOut() {
synchronized(optOutLock) {
try {
// Reload the metrics file
configuration.load(getConfigFile());
} catch (IOException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
} catch (InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
}
return configuration.getBoolean("opt-out", false);
}
}
|
8c298dff-c226-43a4-aa3f-2f5959c732d1
| 1
|
@AfterMethod(alwaysRun = true)
public void tearDown() throws Exception {
// Killing existing instances
if (driver != null) {
driver.quit();
}
}
|
6497a444-18ca-4595-b010-60947bb35b93
| 8
|
public void disconnect(){
if(MFServer.DEBUG_CONNECTIONS){
System.out.print("==> [CONNECTION] '"+name+"' disconnected, trying to close socket...");
}
try {
socket.close();
if(MFServer.DEBUG_CONNECTIONS){
System.out.println("[DONE]");
}
} catch (IOException ex) {
if(MFServer.DEBUG_CONNECTIONS){
System.out.println("[X]");
}
}
switch (state){
case OUT_GAME:
MFServer.SERVER.onDisconnectClient(this);
break;
case LOADING:
game.connectionIsReady(this);
MFServer.SERVER.onDisconnectClient(this);
case QUEUE:
MFServer.SERVER.quitQueue(game_type_joining, this);
MFServer.SERVER.onDisconnectClient(this);
break;
case IN_GAME:
//game.disconnect(this);
MFServer.SERVER.onDisconnectClient(this);
}
state = ConnectionState.DISCONNECTED;
}
|
ac85750f-9cff-449a-a196-c23cd7b00d57
| 3
|
private void saveTarget(final ExprInfo exprInfo, final VarExpr tmp,
final Expr real, final SSAConstructionInfo consInfo) {
if (SSAPRE.DEBUG) {
System.out.println("SAVE TARGET: " + real + " to " + tmp
+ "--------------------------------");
}
Assert.isTrue(real instanceof MemRefExpr);
// Replace
// a.b := c
// with:
// a.b := (t := c);
final VarExpr t = (VarExpr) tmp.clone();
t.setValueNumber(real.valueNumber());
final StoreExpr store = (StoreExpr) real.parent();
final Expr rhs = store.expr();
final StoreExpr rhsStore = new StoreExpr(t, rhs, rhs.type());
rhsStore.setValueNumber(real.valueNumber());
store.visit(new ReplaceVisitor(rhs, rhsStore));
consInfo.addReal(t);
if (SSAPRE.DEBUG) {
System.out.println("save target " + store);
}
if (SSAPRE.DEBUG) {
System.out.println("END SAVE TARGET------------------------------");
}
}
|
dc60eaee-7902-47cc-a862-c6d0015d6fb8
| 5
|
public void action() {
ACLMessage message = null;
switch (state) {
case SENDING:
message = new ACLMessage(ACLMessage.REQUEST);
message.addReceiver(aid);
try {
message.setContentObject(agentDataContainer);
} catch (IOException e) {
e.printStackTrace();
}
myAgent.send(message);
state++;
break;
case RECEIVING:
message = myAgent.receive();
if(message != null) {
try {
agentDataContainer = (AgentDataContainer) message.getContentObject();
} catch (UnreadableException e) {
e.printStackTrace();
}
AgentData agentData = (AgentData) ((ClientAgent) myAgent).getAgentInterface();
AID aid = new AID(myAgent.getName(), AID.ISLOCALNAME);
agentData.onData(aid, agentDataContainer);
done = true;
} else {
block();
}
break;
}
}
|
c0b2ccec-9ed4-47ce-a4ba-4f3ad7e0656c
| 9
|
public void paint(Graphics g2) {
if (applet != null) return;
int w = getWidth() / 2;
int h = getHeight() / 2;
if ((img == null) || (img.getWidth() != w) || (img.getHeight() != h)) {
img = createVolatileImage(w, h);
}
Graphics g = img.getGraphics();
g.drawImage(bgImage, 0, 0, null);
if (gameUpdater.pauseAskUpdate) {
if (!hasMouseListener) {
hasMouseListener = true;
addMouseListener(this);
}
g.setColor(Color.LIGHT_GRAY);
String msg = "Доступно новое обновление";
g.setFont(new Font(null, 1, 20));
FontMetrics fm = g.getFontMetrics();
g.drawString(msg, w / 2 - fm.stringWidth(msg) / 2, h / 2 - fm.getHeight() * 2);
g.setFont(new Font(null, 0, 12));
fm = g.getFontMetrics();
g.fill3DRect(w / 2 - 56 - 8, h / 2, 56, 20, true);
g.fill3DRect(w / 2 + 8, h / 2, 56, 20, true);
msg = "Загрузить сейчас?";
g.drawString(msg, w / 2 - fm.stringWidth(msg) / 2, h / 2 - 8);
g.setColor(Color.BLACK);
msg = "Да";
g.drawString(msg, w / 2 - 56 - 8 - fm.stringWidth(msg) / 2 + 28, h / 2 + 14);
msg = "Нет";
g.drawString(msg, w / 2 + 8 - fm.stringWidth(msg) / 2 + 28, h / 2 + 14);
}
else
{
g.setColor(Color.LIGHT_GRAY);
String msg = "Updating Minecraft";
if (gameUpdater.fatalError) {
msg = "Failed to launch";
}
g.setFont(new Font(null, 1, 20));
FontMetrics fm = g.getFontMetrics();
g.drawString(msg, w / 2 - fm.stringWidth(msg) / 2, h / 2 - fm.getHeight() * 2);
g.setFont(new Font(null, 0, 12));
fm = g.getFontMetrics();
msg = gameUpdater.getDescriptionForState();
if (gameUpdater.fatalError) {
msg = gameUpdater.fatalErrorDescription;
}
g.drawString(msg, w / 2 - fm.stringWidth(msg) / 2, h / 2 + fm.getHeight() * 1);
msg = gameUpdater.subtaskMessage;
g.drawString(msg, w / 2 - fm.stringWidth(msg) / 2, h / 2 + fm.getHeight() * 2);
if (!gameUpdater.fatalError) {
g.setColor(Color.black);
g.fillRect(64, h - 64, w - 128 + 1, 5);
g.setColor(new Color(32768));
g.fillRect(64, h - 64, gameUpdater.percentage * (w - 128) / 100, 4);
g.setColor(new Color(2138144));
g.fillRect(65, h - 64 + 1, gameUpdater.percentage * (w - 128) / 100 - 2, 1);
}
}
g.dispose();
g2.drawImage(img, 0, 0, w * 2, h * 2, null);
}
|
ffca02ae-4871-4523-8b8f-4d12828247e3
| 0
|
public AboutAction() {
super("About...", null);
}
|
6c70d06d-43f1-466a-bc8a-94d8084429d0
| 8
|
public static String factions(MOB E, HTTPRequest httpReq, java.util.Map<String,String> parms)
{
for(final Enumeration e=E.factions();e.hasMoreElements();)
{
final String strip=(String)e.nextElement();
E.removeFaction(strip);
}
if(httpReq.isUrlParameter("FACTION1"))
{
int num=1;
String whichFaction=httpReq.getUrlParameter("FACTION"+num);
String howMuch=httpReq.getUrlParameter("FACTDATA"+num);
while((whichFaction!=null)&&(howMuch!=null))
{
if(whichFaction.length()>0)
{
final Faction F=CMLib.factions().getFaction(whichFaction);
if(F!=null)
{
int amt=Integer.valueOf(howMuch).intValue();
if(amt<F.minimum())
amt=F.minimum();
if(amt>F.maximum())
amt=F.maximum();
E.addFaction(F.factionID(),amt);
}
}
num++;
whichFaction=httpReq.getUrlParameter("FACTION"+num);
howMuch=httpReq.getUrlParameter("FACTDATA"+num);
}
}
return "";
}
|
81bcc89e-44c5-4d0f-9459-1bac70afaeb5
| 1
|
public void testGetShortName_berlin() {
DateTimeZone berlin = DateTimeZone.forID("Europe/Berlin");
assertEquals("CET", berlin.getShortName(TEST_TIME_WINTER, Locale.ENGLISH));
assertEquals("CEST", berlin.getShortName(TEST_TIME_SUMMER, Locale.ENGLISH));
if (JDK6) {
assertEquals("MEZ", berlin.getShortName(TEST_TIME_WINTER, Locale.GERMAN));
assertEquals("MESZ", berlin.getShortName(TEST_TIME_SUMMER, Locale.GERMAN));
} else {
assertEquals("CET", berlin.getShortName(TEST_TIME_WINTER, Locale.GERMAN));
assertEquals("CEST", berlin.getShortName(TEST_TIME_SUMMER, Locale.GERMAN));
}
}
|
ea71e934-ed1c-49af-a058-d3792a8c65a8
| 7
|
private void initGameBoard(Piece[][] contents) {
_gameboard = new JPanel();
_gameboard.setLayout(new GridLayout(8, 8));
_gameboard.setPreferredSize(BOARDSIZE);
_gameboard.setBounds(0, 0, BOARDSIZE.width, BOARDSIZE.height);
for (int i = 0; i < 8 * 8; i++) {
JPanel square = new JPanel(new BorderLayout());
_gameboard.add(square);
int row = (i / 8) % 2;
if (row == 1) {
square.setBackground(i % 2 == 0 ? PieceGUI.DARKBROWN :
PieceGUI.LIGHTBROWN);
} else {
square.setBackground(i % 2 == 0 ? PieceGUI.LIGHTBROWN :
PieceGUI.DARKBROWN);
}
}
for (int i = 1; i < 9; i++) {
for (int j = 1; j < 9; j++) {
if (contents[i - 1][j - 1] != Piece.EMP) {
PieceGUI newPiece = new PieceGUI(
contents[i - 1][j - 1].side(), (j - 1) + 8 * (8 - i));
((JPanel) _gameboard.getComponent(j - 1 + 8 * (8 - i))).add(
newPiece);
}
}
}
}
|
6e5b2005-2b1b-4968-94dc-f457556feabb
| 1
|
@Override
public void map(
LongWritable key, Text text,
OutputCollector<Text, IntWritable> textIntWritableOutputCollector,
Reporter reporter) throws IOException {
try {
Row row = (Row) unmarshaller.unmarshal(new StringReader(text.toString()));
textIntWritableOutputCollector.collect(new Text(row.toCsv()), null);
} catch (JAXBException e) {
System.err.println("Could not parse line: ");
System.err.println(text);
}
}
|
c29615b6-2713-440a-be32-00374a81bbe0
| 0
|
@Override
public Message toMessage(Session session) throws JMSException {
BlobMessage message = ((ActiveMQSession) session)
.createBlobMessage(image);
setMessageProperties(message);
message.setJMSType(TYPE);
return message;
}
|
a57f16fe-9d21-4ef1-86ed-9aacbb88780d
| 9
|
public String nextToken() throws JSONException {
char c;
char q;
StringBuilder sb = new StringBuilder();
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();
}
}
|
eb714d3f-1a79-4454-b9a6-e455edbef28d
| 6
|
public static void chargerFichierDonnees() {
// Lecture des donnees des etudiants
try {
FileInputStream fstream = new FileInputStream("etudiants.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String ligne;
while ((ligne = br.readLine()) != null) {
String[] donnees = ligne.split("\\|");
Etudiant e = new Etudiant(donnees[0], donnees[1], donnees[2], Integer.parseInt(donnees[3]), Integer.parseInt(donnees[4]), Double.parseDouble(donnees[5]));
ListeEtudiants.getInstance().getListe().add(e);
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
// Lecture des donnees des cours
try {
FileInputStream fstream = new FileInputStream("cours.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String ligne;
while ((ligne = br.readLine()) != null) {
String[] donnees = ligne.split("\\|");
Cours c = new Cours(donnees[0], donnees[1], Integer.parseInt(donnees[2]));
ListeCours.getInstance().getListe().add(c);
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
// Lecture des donnees des inscriptions
try {
FileInputStream fstream = new FileInputStream("inscriptions.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String ligne;
while ((ligne = br.readLine()) != null) {
String[] donnees = ligne.split("\\|");
Etudiant e = ListeEtudiants.getInstance().chercherEtudiant(donnees[0]);
Cours c = ListeCours.getInstance().chercherCours(donnees[1]);
Inscription i = new Inscription(e, c);
e.ajouterCours(i);
c.ajouterEtudiant(i);
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
|
8587a3b2-f783-463c-82d1-c0e957e67ee8
| 8
|
public static void updateBankVowelPurchase() {
PlayerTurn playerTurn = new PlayerTurn();
playerTurn.updatePlayersTurn();
try {
if (getBankPlayerUp() >= 250) {
setHasEnough(true);
long bank = 0;
long updateBank;
int control = 0;
if (PlayerTurn.getPlayerUp() == 0) {
bank = getBankNumberPlayer1();
control = 1;
} else if (PlayerTurn.getPlayerUp() == 1) {
bank = getBankNumberPlayer2();
control = 2;
} else if (PlayerTurn.getPlayerUp() == 2) {
bank = getBankNumberPlayer3();
control = 3;
}
updateBank = bank - 250;
if (control == 1) {
setBankNumberPlayer1(updateBank);
} else if (control == 2) {
setBankNumberPlayer2(updateBank);
} else if (control == 3) {
setBankNumberPlayer3(updateBank);
}
Bank.updateBankPlayer();
}
else {
Bank.setHasEnough(false);
ErrorType.ERROR102.displayErrorType();
}
} catch (Throwable ex) {
ErrorType.ERROR101.displayErrorType();
}
}
|
462dd93f-0985-4e56-9b88-0b7db4ea0125
| 2
|
private boolean isOver() {
int end = tracksize -1;
return (posFido >= end || posSpot >= end || posRover >= end);
}
|
2b040ebd-4829-404c-b2d5-0eb0148209a4
| 5
|
public boolean inArea(int x, int z, String worldname)
{
boolean isInArea = false;
if(world.equalsIgnoreCase(worldname)) {
if(minX <= x && x <= maxX) {
if(minZ <= z && z <= maxZ) {
isInArea = true;
}
}
}
return isInArea;
}
|
237c7b7e-96a9-4875-907a-6c3ce18d866e
| 1
|
private String toByteString(byte b) {
String s = "" + Integer.toBinaryString(b & 0xFF);
while(s.length() < 8)
s = "0" + s;
return s;
}
|
252a82ea-1ec4-4549-ab33-ac4cad5e1614
| 9
|
public String getNickname(){
switch(this){
case LAWFUL_GOOD: return "Crusader";
case NEUTRAL_GOOD: return "Benefactor";
case CHAOTIC_GOOD: return "Rebel";
case LAWFUL_NEUTRAL: return "Judge";
case TRUE_NEUTRAL: return "Undecided";
case CHAOTIC_NEUTRAL: return "Free Spirit";
case LAWFUL_EVIL: return "Dominator";
case NEUTRAL_EVIL: return "Malefactor";
case CHAOTIC_EVIL: return "Destroyer";
}
return null;
}
|
8423791a-1c5c-4dcf-ab77-3600cc393bdb
| 1
|
public void visit_invokespecial(final Instruction inst) {
final MemberRef method = (MemberRef) inst.operand();
final Type type = method.nameAndType().type();
stackHeight -= type.stackHeight() + 1;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += type.returnType().stackHeight();
}
|
bb8fe014-d50c-4137-a06f-2408c3266261
| 9
|
public static final Class<?> getClass(final Type type) {
final Class<?> result;
if (type instanceof Class<?>) {
result = (Class<?>) type;
} else if (type instanceof ParameterizedType) {
final Type rawType = ((ParameterizedType) type).getRawType();
result = getClass(rawType);
} else if (type instanceof GenericArrayType) {
final Type componentType = ((GenericArrayType) type).getGenericComponentType();
final Class<?> componentClass = getClass(componentType);
if (componentClass != null) {
result = Array.newInstance(componentClass, 0).getClass();
} else {
result = null;
}
} else {
result = null;
}
return result;
}
|
5be4f8a9-d7aa-4008-b0b9-57526c9eabd9
| 6
|
public void cargarArchivoTXT(String ruta) {
File archivoAutomata = null;
FileReader fr = null;
BufferedReader br = null;
JFileChooser selector = null;
try {
if (ruta == null) { // si no se pasa una ruta, hay que selecionar el archivo
JOptionPane.showMessageDialog(null, "Por favor, seleccione el archivo TXT que contiene la descripci\u00f3n del automata");
selector = new JFileChooser();
int resultado = selector.showOpenDialog(null);
if (resultado == JFileChooser.APPROVE_OPTION) {
archivoAutomata = selector.getSelectedFile();
}
} else { // si se pasa una ruta, se carga el archivo inmediatamente
archivoAutomata = new File(ruta);
}
fr = new FileReader(archivoAutomata);
br = new BufferedReader(fr);
// Lectura del fichero
String linea;
System.out.println("Cargando automata... ");
while ((linea = br.readLine()) != null) {
System.out.println(linea);
automata.add(linea);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != fr) {
fr.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
|
bb620ac7-7c4c-4ec8-94af-2d94c911246b
| 5
|
@Override
public void actionPerformed(ActionEvent arg0) {
String s = (String) categories.getSelectedItem();
DetailsPanelController pc = DetailsPanelController.getInstance();
if (s.equals("")) {
//If the "no category" category is chosen, create a new dummy category and set
//that as the currentTasks() category
if (pc.getCurrentTask() != null) {
pc.getCurrentTask().setCategory(new Category("", tl.getColor("black")));
pc.updateTask(pc.getCurrentTask());
}
}
else {
//If any other category is chosen, find the correct category and set it as the tasks
//category
for (Category c : PanicController.getInstance().getCategories()) {
if (c.getName().equals(s)) {
if (pc.getCurrentTask() != null) {
pc.getCurrentTask().setCategory(c);
pc.updateTask(pc.getCurrentTask());
}
break;
}
}
}
}
|
28e0d194-147d-4c73-9aec-cc43c31cfb12
| 6
|
public void createIndexes() {
personIndex = new HashMap<String, Person>();
for (Person person : getPeople()) {
personIndex.put(person.getId(), person);
}
familyIndex = new HashMap<String, Family>();
for (Family family : getFamilies()) {
familyIndex.put(family.getId(), family);
}
mediaIndex = new HashMap<String, Media>();
for (Media m : getMedia()) {
mediaIndex.put(m.getId(), m);
}
noteIndex = new HashMap<String, Note>();
for (Note note : getNotes()) {
noteIndex.put(note.getId(), note);
}
sourceIndex = new HashMap<String, Source>();
for (Source source : getSources()) {
sourceIndex.put(source.getId(), source);
}
repositoryIndex = new HashMap<String, Repository>();
for (Repository repository : getRepositories()) {
repositoryIndex.put(repository.getId(), repository);
}
}
|
23cc1c0f-bf11-4acc-b178-70e86b745cd3
| 3
|
private static String readIntegerString() { // read chars from input following syntax of integers
skipWhitespace();
if (lookChar() == EOF)
return null;
if (integerMatcher == null)
integerMatcher = integerRegex.matcher(buffer);
integerMatcher.region(pos,buffer.length());
if (integerMatcher.lookingAt()) {
String str = integerMatcher.group();
pos = integerMatcher.end();
return str;
}
else
return null;
}
|
8fd9fab9-14cc-4e25-8335-e1ba7927868c
| 2
|
public final synchronized long readLong(){
this.inputType = true;
String word="";
long ll=0L;
if(!this.testFullLineT) this.enterLine();
word = nextWord();
if(!eof)ll = Long.parseLong(word.trim());
return ll;
}
|
52ae4c4b-00ad-4dc2-b7fb-276d717b60ce
| 5
|
public int getColor(String part)
{
if(part.equals("head"))
{
return handsColor;
}
if(part.equals("hands"))
{
return handsColor;
}
if(part.equals("body"))
{
return bodyColor;
}
if(part.equals("legs"))
{
return legsColor;
}
if(part.equals("feet"))
{
return feetColor;
}
return 0;
}
|
5eef7771-aa74-4317-8eb8-64c9e77f7000
| 3
|
public String getAlfrescoTicket(String username, String password) {
String url = "http://phaedrus.scss.tcd.ie/CS3BC2/group6/tomcat/alfresco" + "/service/api/login?u=" + username + "&pw=" + password;
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(url);
String response = null;
try {
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
byte[] responseBody = method.getResponseBody();
response = new String(responseBody);
System.out.println(response);
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
method.releaseConnection();
}
response = response.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
response = response.replace("\n<ticket>", "");
response = response.replace("</ticket>\n", "");
return response;
}
|
0538043f-56bb-4b82-aa5d-5cf6c93eb7fb
| 0
|
@Override
public void setIdleTimeout(long idleTimeout) {
this.idleTimeout = idleTimeout;
}
|
705d2534-1b4f-4505-88ad-d96142786e0a
| 7
|
public void info(){
try{
if( file.exists() ){
System.out.println("Nombre: " + file.getName());
System.out.println("Path: " + file.getPath());
System.out.println("Absoluto: " + file.getAbsolutePath());
System.out.println("PAPA: " + file.getAbsoluteFile().getParent());
if( file.isDirectory() )
System.out.println("Es Directorio");
if( file.isFile() )
System.out.println("ES un Archivo");
if( file.isHidden() )
System.out.println("Esta Escondido");
if( file.isAbsolute() )
System.out.println("Creado con Direccion Absoluta");
Date fecha = new Date( file.lastModified() );
System.out.println("Ultima Fecha de Modificacion: " + fecha);
System.out.println("Size en Bytes: " + file.length());
}
else{
System.out.println("NO EXISTE AUN");
try {
System.out.println("Canonical: " + file.getCanonicalPath());
} catch (IOException ex) {
System.out.println("Error Canonical NO PUEDE USAR ESTA DIRECCION: " + ex.getMessage());
}
}
}
catch(NullPointerException e){
System.out.println("Primero hay que configurar un archivo");
}
}
|
444b1f8f-ce9d-456b-ac38-7dc7497256f8
| 3
|
private MaskValue findFlag()
{
for (MaskValue mask : mMasks)
if (mask.isFlag() && !mask.isOpen()) return mask;
Log.exception("No Flag Mask Defined!");
Sweeper.forceStop();
return null;
}
|
fff472d7-bfdb-4a09-bc60-32026771846b
| 7
|
@Override
public void executeMsg(Environmental host, CMMsg msg)
{
if((invoker()!=null)
&&(!unInvoked)
&&(affected==invoker())
&&(msg.amISource(invoker()))
&&(msg.target() instanceof Armor)
&&(msg.targetMinor()==CMMsg.TYP_WEAR))
{
if(msg.source().location()!=null)
msg.source().location().show(msg.source(),null,CMMsg.MSG_NOISE,L("<S-NAME> stop(s) dancing."));
unInvoke();
}
super.executeMsg(host,msg);
}
|
f8955704-8971-4aaf-8f75-b1980d09b3ce
| 3
|
public void generaCentros()
{
Iterator listaElementos = listaElementos();
Nodo n;
while(listaElementos.hasNext())
{
Elemento next = (Elemento) ((Map.Entry)listaElementos.next()).getValue();
n = new Nodo(new double[]{0,0,0});
for(int nodo : next.vertices())
{
Nodo nodo1 = getNodo(nodo);
for (int i = 0; i < 3;i++)
{
n.vertices[i] += nodo1.vertices[i]/nodo1.vertices.length;
}
}
next.centro(n);
}
}
|
5a15eb42-2753-4aab-a8f7-7885620f4525
| 1
|
public void eval(EvalContext context) {
int stmtId = context.newStmtId();
context.logEntering("Evaluating If@"+stmtId + " ctx@" + context.id);
predicate.eval(context);
boolean value = context.popBoolean();
context.log("If@"+stmtId + " - Predicate: " + value);
if(value) {
context.log("If@"+stmtId + " - consequent");
consequent.eval(context);
}
else {
context.log("If@"+stmtId + " - alternative");
alternative.eval(context);
}
context.logLeaving("If@"+stmtId + " - done!");
}
|
e6a759bc-2b75-470b-a3ed-443f60ef3e1b
| 5
|
public static void parseNaturals(String str, int[] numbers){
int len = str.length();
int numberIndex = 0;
int maxIndex = numbers.length;
int currentNumber = 0;
boolean numberStarted = false;
for(int i = 0; i < len; i++){
char c = str.charAt(i);
if(c >= '0' && c <= '9') {
numberStarted = true;
currentNumber = currentNumber *10+(c-'0');
numbers[numberIndex] = currentNumber;
} else if (numberStarted) {
numberStarted = false;
currentNumber = 0;
numberIndex++;
if(numberIndex == maxIndex) return;
}
}
}
|
b1e240fa-caa9-45dc-9cfa-e6a89ffc2221
| 7
|
private Object decodeValue(){
JsonLexer.Token token = lexer.next();
switch (token.type){
case NULL : return null;
case TRUE :
case FALSE : return token.asBoolean();
case STRING : return token.asString();
case NUMBER : return token.asNumber();
case OBJECT_START : return decodeObject();
case ARRAY_START : return decodeArray();
default : throw new RuntimeException("invalid value token "+token);
}
}
|
6cb23d90-edac-49c2-9a4d-dfb87bd10103
| 1
|
public DefExpr def() {
if (isDef()) {
return this;
}
return super.def();
}
|
977258ae-3024-4b71-a7dd-4faff12dc16a
| 6
|
public void undisguise(Player player)
{
if(this.players.containsKey(player.getName()))
{
DisguisedPlayer dp = this.players.remove(player.getName());
if(dp != null && dp.lastBlock != null)
{
for(Player p : player.getWorld().getPlayers())
{
p.sendBlockChange(dp.lastBlock.getLocation(), dp.lastBlock.getType(), dp.lastBlock.getData());
}
}
if(plugin.MAKE_PLAYERS_INVISIBLE)
{
for(Player pShowTo: plugin.getServer().getOnlinePlayers())
{
pShowTo.showPlayer(player);
}
}
}
}
|
39b50a8a-2606-4793-b590-bacb14e0577d
| 1
|
public Object next() {
if (next == null) {
throw new NoSuchElementException();
}
AbstractInsnNode result = next;
prev = result;
next = result.next;
return result;
}
|
3b66fb4f-551c-40ce-8e81-5d17b9bedc19
| 7
|
public static Stella_Object clTranslateSqlTypeSpecifier(Stella_Object stellatype) {
{ Stella_Object result = null;
if ((stellatype == null) ||
(stellatype == Sdbc.SYM_STELLA_NULL)) {
}
else {
{ GeneralizedSymbol testValue000 = ((GeneralizedSymbol)(stellatype));
if (testValue000 == Sdbc.SGT_STELLA_CALENDAR_DATE) {
}
else if (testValue000 == Sdbc.SGT_STELLA_STRING) {
}
else if (testValue000 == Sdbc.SGT_STELLA_INTEGER) {
}
else if (testValue000 == Sdbc.SGT_STELLA_LONG_INTEGER) {
}
else if (testValue000 == Sdbc.SGT_STELLA_DOUBLE_FLOAT) {
}
else {
}
}
}
return (result);
}
}
|
6384719f-8bdd-4d1d-b6f8-e8bd25819634
| 9
|
public String inputs( String type, String [] attr, String name ) {
if ( name != null ) {
type += " name='"+name+"'";
}
boolean hasValue = false;
if ( attr != null )
for( int i=0 ; i<attr.length ; i+=2 )
if ( attr[i] != null && attr[i+1] != null ) {
if ( "value".equals( attr[i] ) )
hasValue = true;
type += " " + attr[i]+"='"+escapeHTML(attr[i+1])+"'";
}
if ( name != null && !hasValue ) {
String param = param( name );
if ( param != null )
type += " value='"+escapeHTML(param)+"'";
}
return "<input type="+type+">";
}
|
155b8361-558c-468a-b6b0-e8d835cb4279
| 0
|
protected void fireServerStart(ServerStartEvent evt) {
sync.clear();
conns.clear();
prevCallId = Long.MIN_VALUE;
}
|
01244436-16df-44ba-b113-84a2fc34ea64
| 8
|
public static void main(String[] ops) {
int n = Integer.parseInt(ops[0]);
if(n<=0)
n=10;
long seed = Long.parseLong(ops[1]);
if(seed <= 0)
seed = 45;
RandomVariates var = new RandomVariates(seed);
double varb[] = new double[n];
try {
System.out.println("Generate "+n+" values with std. exp dist:");
for(int i=0; i<n; i++){
varb[i] = var.nextExponential();
System.out.print("["+i+"] "+varb[i]+", ");
}
System.out.println("\nMean is "+Utils.mean(varb)+
", Variance is "+Utils.variance(varb)+
"\n\nGenerate "+n+" values with"+
" std. Erlang-5 dist:");
for(int i=0; i<n; i++){
varb[i] = var.nextErlang(5);
System.out.print("["+i+"] "+varb[i]+", ");
}
System.out.println("\nMean is "+Utils.mean(varb)+
", Variance is "+Utils.variance(varb)+
"\n\nGenerate "+n+" values with"+
" std. Gamma(4.5) dist:");
for(int i=0; i<n; i++){
varb[i] = var.nextGamma(4.5);
System.out.print("["+i+"] "+varb[i]+", ");
}
System.out.println("\nMean is "+Utils.mean(varb)+
", Variance is "+Utils.variance(varb)+
"\n\nGenerate "+n+" values with"+
" std. Gamma(0.5) dist:");
for(int i=0; i<n; i++){
varb[i] = var.nextGamma(0.5);
System.out.print("["+i+"] "+varb[i]+", ");
}
System.out.println("\nMean is "+Utils.mean(varb)+
", Variance is "+Utils.variance(varb)+
"\n\nGenerate "+n+" values with"+
" std. Gaussian(5, 2) dist:");
for(int i=0; i<n; i++){
varb[i] = var.nextGaussian()*2.0+5.0;
System.out.print("["+i+"] "+varb[i]+", ");
}
System.out.println("\nMean is "+Utils.mean(varb)+
", Variance is "+Utils.variance(varb)+"\n");
} catch (Exception e) {
e.printStackTrace();
}
}
|
d7618bef-8812-47c7-92f2-51b3c20cf1dd
| 4
|
public CardCheckResult check() {
CardCheckResult result = CardCheckResult.OK;
if(super.check() != CardCheckResult.OK) {
result = super.check();
} else {
Calendar calendar = Calendar.getInstance();
int today = calendar.get(Calendar.DAY_OF_WEEK);
if (today < Calendar.MONDAY || today > Calendar.FRIDAY) {
result = CardCheckResult.NOT_WORKING_DAY;
} else if (liftsLeft <= 0) {
result = CardCheckResult.NO_LIFTS_LEFT;
}
}
return result;
}
|
18479474-ae01-4e27-93f1-47a627f3b396
| 2
|
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//vastaanotetaan palaute String-muodossa
String palauteIDStr = request.getParameter("palauteID");
int palauteID;
try {
//luodaan olio businessluokasta
PalauteService service = new PalauteService();
//parsitaan palaute Stringistä integeriksi
palauteID = Integer.parseInt(palauteIDStr);
//luodaan palaute-olio
Palaute palaute = new Palaute();
palaute.setPalauteID(palauteID);
//lähetetään service-luokan metodille
service.poistaPalaute(palaute);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (DAOPoikkeus p) {
System.out.println(p.getMessage());
}
//Palautteen poistamisen jälkeen ladataan sivu uudestaan
response.sendRedirect("palautteet?poista=true");
}
|
73bff746-3132-4f67-bace-af415876155d
| 0
|
public static void main(String[] args) {
//DoubleLetters dl = new DoubleLetters();
//dl.DoDoubling();
UpByN ubn = new UpByN();
ubn.upByThrees(4);
}
|
ff119ce8-80f5-4f3a-862b-c6a9335c0027
| 8
|
public int compare(String o1, String o2)
{
String s1 = (String)o1;
String s2 = (String)o2;
int thisMarker = 0;
int thatMarker = 0;
int s1Length = s1.length();
int s2Length = s2.length();
while (thisMarker < s1Length && thatMarker < s2Length)
{
String thisChunk = getChunk(s1, s1Length, thisMarker);
thisMarker += thisChunk.length();
String thatChunk = getChunk(s2, s2Length, thatMarker);
thatMarker += thatChunk.length();
// If both chunks contain numeric characters, sort them numerically
int result = 0;
if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0)))
{
// Simple chunk comparison by length.
int thisChunkLength = thisChunk.length();
result = thisChunkLength - thatChunk.length();
// If equal, the first different number counts
if (result == 0)
{
for (int i = 0; i < thisChunkLength; i++)
{
result = thisChunk.charAt(i) - thatChunk.charAt(i);
if (result != 0)
{
return result;
}
}
}
} else
{
result = thisChunk.compareTo(thatChunk);
}
if (result != 0)
return result;
}
return s1Length - s2Length;
}
|
808e761d-ea33-4025-b278-17eaa85f2aae
| 7
|
@Override
protected byte[] load_from_current_position(String frameId, int dataLength, RandomAccessFile openFile)
throws IOException {
byte[] frameData=super.load_from_current_position(frameId, dataLength, openFile);
if(frameData==null)
return null;
if(frameData.length<4) {
log(Level.WARNING,"playcount frame too short: "+frameData.length);
return frameData;
}
if(frameData.length>8 || (frameData.length==8 && (frameData[0] & 0x80) != 0) ) {
//oh come on
log(Level.WARNING,"playcount frame too long: "+frameData.length);
return frameData;
}
this.playCounter = 0L;
if(frameData.length>4) {
for(int yeahRightMoreThanFourBillionPlays=0;yeahRightMoreThanFourBillionPlays<frameData.length-4 ; yeahRightMoreThanFourBillionPlays++) {
this.playCounter = this.playCounter << 8;
this.playCounter += (0xff & frameData[yeahRightMoreThanFourBillionPlays]);
}
this.playCounter = this.playCounter << 32;
}
this.playCounter += MediaFileUtil.convert32bitsToUnsignedInt(frameData, frameData.length-4);
return frameData;
}
|
fa20eb10-6e30-44b9-be3c-b7b7e29a967b
| 2
|
public static String getStreamID(String streamerName) {
for (int i = 0 ; i < streamName.size(); i++) {
if (streamName.get(i).equalsIgnoreCase(streamerName)) {
return streamList.get(i);
}
}
return null;
}
|
1b754c52-8509-4797-9a6e-86e9226c9744
| 6
|
public List<List<Integer>> helper(int[] c, int start, int end, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (start < end) {
if (target > c[start]) {
int pick = c[start];
List<List<Integer>> r = helper(c, start + 1, end, target - pick);
for (List<Integer> l : r) {
l.add(0, pick);
result.add(l);
}
int nextStart = start + 1;
while (nextStart < end && c[nextStart] == pick) {
nextStart++;
}
result.addAll(helper(c, nextStart, end, target));
} else if (target == c[start]) {
List<Integer> rr = new ArrayList<Integer>();
rr.add(c[start]);
result.add(rr);
}
}
return result;
}
|
09dbb7c0-570e-4e5b-9a13-182a8c551a36
| 8
|
@Override
public boolean onCommand(CommandSender sender, Command command,
String lable, String[] args) {
if (master.getConfig().getBoolean("enable-adventure", false)) {
sender.sendMessage("This feature is not fully implemented! "
+ "If you want to try this feature out, set 'enable-adventure' in the config file to true.");
return true;
}
String worldName = "";
boolean resetDone = false;
if (args.length < 2) {
sender.sendMessage("This function needs exactly two (2) arguments.");
sender.sendMessage("/adventure [create|reset] <worldname>");
return false;
}
if (args[0].equals("create")) {
worldName = args[1];
// WorldDuplicator.DuplicateWorld(master.getMVCore().getMVWorldManager().getMVWorld(worldName).getCBWorld(),
// master, worldName + ".template");
if (!master.getMBAdventureManager().addAdventureWorld(
master.getMVCore().getMVWorldManager().getMVWorld(worldName).getCBWorld())) {
sender.sendMessage("Could not create adventure world!");
return false;
} else {
sender.sendMessage("Adventure world created.");
master.getLogManager().info(
"Created adventure world: " + worldName);
return true;
}
} else
if (args[0].equals("reset")) {
worldName = args[1];
for (MBAdventureWorld advW : master.getMBAdventureManager().getAdventureWorlds()) {
if (advW.getName().equals(worldName)) {
resetDone = advW.Reset();
}
}
if (resetDone) {
sender.sendMessage("World reset successfully.");
master.getLogManager().info(
"Reset adventure world: " + worldName);
return true;
} else {
sender.sendMessage("Failed to reset world. Does the world exist? - Is it marked as an advenure world?");
return false;
}
}
return true;
}
|
3cb0f710-6265-4f30-8f74-5c7abef05434
| 9
|
public updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) {
this.plugin = plugin;
this.type = type;
this.announce = announce;
this.file = file;
this.id = id;
this.updateFolder = plugin.getServer().getUpdateFolder();
final File pluginFile = plugin.getDataFolder().getParentFile();
final File updaterFile = new File(pluginFile, "Updater");
final File updaterConfigFile = new File(updaterFile, "config.yml");
if (!updaterFile.exists()) {
updaterFile.mkdir();
}
if (!updaterConfigFile.exists()) {
try {
updaterConfigFile.createNewFile();
} catch (final IOException e) {
plugin.getLogger().severe("The updater could not create a configuration in " + updaterFile.getAbsolutePath());
e.printStackTrace();
}
}
this.config = YamlConfiguration.loadConfiguration(updaterConfigFile);
this.config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n'
+ "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n'
+ "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration.");
this.config.addDefault("api-key", "PUT_API_KEY_HERE");
this.config.addDefault("disable", false);
if (this.config.get("api-key", null) == null) {
this.config.options().copyDefaults(true);
try {
this.config.save(updaterConfigFile);
} catch (final IOException e) {
plugin.getLogger().severe("The updater could not save the configuration in " + updaterFile.getAbsolutePath());
e.printStackTrace();
}
}
if (this.config.getBoolean("disable")) {
this.result = UpdateResult.DISABLED;
return;
}
String key = this.config.getString("api-key");
if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) {
key = null;
}
this.apiKey = key;
try {
this.url = new URL(updater.HOST + updater.QUERY + id);
} catch (final MalformedURLException e) {
plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid.");
this.result = UpdateResult.FAIL_BADID;
e.printStackTrace();
}
this.thread = new Thread(new UpdateRunnable());
this.thread.start();
}
|
51cad220-d2f7-483a-b6e9-f7b725f3017a
| 9
|
@Override
public boolean mayICraft(final Item I)
{
if(I==null)
return false;
if(!super.mayBeCrafted(I))
return false;
if(((I.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_METAL)
&&((I.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_MITHRIL))
return false;
if(CMLib.flags().isDeadlyOrMaliciousEffect(I))
return false;
if(!masterCraftCheck(I))
return (isANativeItem(I.Name()));
if(!(I instanceof Weapon))
return false;
final Weapon W=(Weapon)I;
if((W instanceof AmmunitionWeapon)&&((AmmunitionWeapon)W).requiresAmmunition())
return false;
return true;
}
|
52ac6a4c-24d4-4310-8d0c-e58db2c008e6
| 6
|
public void removeListener(IoFutureListener listener) {
if (listener == null) {
throw new NullPointerException("listener");
}
synchronized (lock) {
if (!ready) {
if (listener == firstListener) {
if (otherListeners != null && !otherListeners.isEmpty()) {
firstListener = otherListeners.remove(0);
} else {
firstListener = null;
}
} else if (otherListeners != null) {
otherListeners.remove(listener);
}
}
}
}
|
d3d98ee3-6008-4861-9345-201cef5326fb
| 3
|
@Override
public void paint(Graphics g) {
super.paint(g);
Node travelNode;
for (int i = 0; i < GameConstants.HEIGHT; i++) {
for (int j = 0; j < GameConstants.WIDTH; j++) {
travelNode = ship.nodeMap.get(new Coordinates(i, j));
drawLines(travelNode, g);
}
}
drawControlRoom(Engine.controlNode, g);
if (Engine.scannerNode != null) {
drawScanner(Engine.scannerNode, g);
}
drawAlien(Engine.ship.getAlienNode(), null, g);
drawPredator(Engine.ship.getPredatorNode(), null, g);
//*********************************************************
// Uncomment for Karma
// draws a path between two nodes for testing purposes
// drawPath(ship.getPath(ship.getNodeAt(0, 0),
// ship.getNodeAt(15,15)),g);
}
|
1d7e6702-f96e-4ab8-8074-b9b2cf73e42a
| 7
|
private boolean isFourOfKnd(){
int cnt=0,rID=0,sID=0;
boolean first=true;
for (int i = 0; i < crds.size()-1; i++) {
rID=crds.get(i).getRankID();
if(crds.get(i).getRankID()==crds.get(i+1).getRankID()){
System.out.println("matched "+crds.get(i+1).getRankID() );
if(sID!=crds.get(i).getRankID()){
first=true;
cnt=0;
}
if(first||(rID==crds.get(i).getRankID()&&sID==crds.get(i).getRankID())){
cnt++;
sID=crds.get(i).getRankID();
System.out.println("cnt ="+cnt);
first=false;
}
if(cnt==3){
System.out.println("Four of kind matched*********************************");
return true;
}
}
}
return false;
}
|
f01ec40a-e35a-479e-8f22-3df2fe7e1685
| 8
|
private void loadMesh( String filename ) {
String[] splitArray = filename.split( "\\." );
String ext = splitArray[ splitArray.length - 1 ];
if( !ext.equals( "obj" ) ) {
System.err.println( "Error: File formate not supported for mesh data: " + ext );
new Exception( ).printStackTrace( );
System.exit( 1 );
}
ArrayList< Vertex > vertices = new ArrayList< Vertex >( );
ArrayList< Integer > indices = new ArrayList< Integer >( );
BufferedReader meshReader = null;
try {
meshReader = new BufferedReader( new FileReader( "./resource/models/" + filename ) );
String line;
while( ( line = meshReader.readLine( ) ) != null ) {
String[] tokens = line.split( " " );
tokens = RenderingUtil.removeEmptyString( tokens );
if( tokens.length == 0 || tokens[ 0 ].equals( '#' ) ) {
continue;
} else if( tokens[ 0 ].equals( "v" ) ) {
vertices.add( new Vertex( new Vector3f(
Float.valueOf( tokens[ 1 ] ),
Float.valueOf( tokens[ 2 ] ),
Float.valueOf( tokens[ 3 ] ) ) ) );
} else if( tokens[ 0 ].equals( "f" ) ) {
indices.add( Integer.parseInt( tokens[ 1 ].split( "/" )[ 0 ] ) - 1 );
indices.add( Integer.parseInt( tokens[ 2 ].split( "/" )[ 0 ] ) - 1 );
indices.add( Integer.parseInt( tokens[ 3 ].split( "/" )[ 0 ] ) - 1 );
if( tokens.length > 4 ) {
indices.add( Integer.parseInt( tokens[ 1 ].split( "/" )[ 0 ] ) - 1 );
indices.add( Integer.parseInt( tokens[ 3 ].split( "/" )[ 0 ] ) - 1 );
indices.add( Integer.parseInt( tokens[ 4 ].split( "/" )[ 0 ] ) - 1 );
}
}
}
meshReader.close( );
} catch( Exception exception ) {
exception.printStackTrace( );
System.exit( 1 );
}
Vertex[] vertexData = new Vertex[ vertices.size( ) ];
vertices.toArray( vertexData );
Integer[] indexData = new Integer[ indices.size( ) ];
indices.toArray( indexData );
this.addVertices( vertexData, RenderingUtil.toIntArray( indexData ) );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.