text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void info(Object... objs) {
if (LoggingLevel.INFO.value >= currentGlobalLoggingLevel.value) {
logger.info(Helpers.concat(objs));
}
} | 1 |
@Override
public void finishSpringing(MOB target)
{
if((!invoker().mayIFight(target))||(target.phyStats().weight()<5))
target.location().show(target,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> float(s) gently into the pit!"));
else
{
target.location().show(target,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> hit(s) the pit floor with a THUMP!"));
final int damage=CMLib.dice().roll(trapLevel()+abilityCode(),6,1);
CMLib.combat().postDamage(invoker(),target,this,damage,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|CMMsg.TYP_JUSTICE,-1,null);
}
final List<String> snakes=new Vector<String>();
String t=text();
int x=t.indexOf("</MOBITEM><MOBITEM>");
while(x>=0)
{
snakes.add(t.substring(0,x+10));
t=t.substring(x+10);
x=t.indexOf("</MOBITEM><MOBITEM>");
}
if(t.length()>0)
snakes.add(t);
if(snakes.size()>0)
monsters=new Vector<MOB>();
for(int i=0;i<snakes.size();i++)
{
t=snakes.get(i);
final Item I=CMClass.getItem("GenCaged");
((CagedAnimal)I).setCageText(t);
final MOB monster=((CagedAnimal)I).unCageMe();
if(monster!=null)
{
monsters.add(monster);
monster.basePhyStats().setRejuv(PhyStats.NO_REJUV);
monster.bringToLife(target.location(),true);
monster.setVictim(target);
if(target.getVictim()==null)
target.setVictim(monster);
}
}
CMLib.commands().postLook(target,true);
} | 8 |
@Override
public void run() {
startTime = System.currentTimeMillis();
while(isMatch){
if(!isPaused){
invokeTricks();
spawnEnemies();
checkPoints();
moveAll();
fireMissiles();
fireEnemiesLasers();
collisionCheck();
cheatCheck();
setHighScore();
resetter();
repaint();
try{
Thread.sleep(Math.max(1, REFRESH_INTERVAL_MS));
}catch(InterruptedException ie){
System.out.println("Thread interrupted. There will be a temporary FPS change.");
System.out.println(ie);
}
endTime = System.currentTimeMillis();
elapsedTime = endTime - startTime;
// realFPS = 1000 / (currentTime - endTime);
}
}
repaint();
} | 3 |
static int f(int i,int j){
if(i==j)return 0;
if(mem[i][j]>0)return mem[i][j];
int min=MAX_VALUE-1000000;
for(int k=(i+1)%N;k!=(j+1)%N;k=(k+1)%N){
int val1,val2;
if(k-1>=i)val1=sums[k-1]-(i>0?sums[i-1]:0);
else val1=sums[N-1]-sums[i-1]+(k>0?sums[k-1]:0);
if(j>=k)val2=sums[j]-(k>0?sums[k-1]:0);
else val2=sums[N-1]-sums[k-1]+sums[j];
min=min(min,f(i,(k+N-1)%N)+f(k,j)+max(val1,val2));
}
return mem[i][j]=min;
} | 8 |
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader(args[0]));
BufferedWriter bw = new BufferedWriter(new FileWriter("corpus.txt"));
String temp;
StringBuffer sb = new StringBuffer();
while((temp=br.readLine())!=null) {
if(temp.startsWith("<s>")){
sb = new StringBuffer();
}
else if(temp.startsWith("</s>")){
bw.write(sb.toString().toLowerCase().trim());
bw.newLine();
}
else{
String[] text = temp.split("\\t");
sb.append(text[0]);//ignoring the rest which is tags...
sb.append(" ");
}
}
br.close();
bw.close();
}catch(IOException e) {
e.printStackTrace();
}
} | 4 |
public static int[] getChuk(int x,int z){
int[] res = new int[2];
res[0] = (int)(x / 16.0);
res[1] = (int)(z / 16.0);
return res;
} | 0 |
public boolean hasStance(String playerName, String targetName) {
boolean stance = false;
if (playerName.equalsIgnoreCase(targetName))
return true;
String SQL = "SELECT *" + " FROM " + tblStances + " WHERE `player` LIKE ?" + " AND `target` LIKE ?";
// boolean found = false;
try {
Connection con = getSQLConnection();
PreparedStatement statement = con.prepareStatement(SQL);
statement.setString(1, playerName);
statement.setString(2, targetName);
ResultSet result = statement.executeQuery();
while (result.next()) {
stance = true;
break;
}
result.close();
statement.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stance;
} | 3 |
@Override
public boolean equals(Object o )
{
if(o == null)
return false;
if(!(o instanceof Bauteil))
return false;
Bauteil b = (Bauteil)o;
if(b.getNr() != this.getNr())
return false;
if(!b.getName().equals(this.getName()))
return false;
if(!b.getStueckliste().equals(this.getStueckliste()))
return false;
return true;
} | 5 |
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JLabel l = (JLabel) super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
if (hasFocus && table.isCellEditable(row, column))
return l;
if (!"".equals(value))
return l;
l.setText(toSubstitute);
return l;
} | 3 |
@Override
public void move (Fleet fleet) {
Field playField = null;
board.setQuality(fleet);
Collections.sort(remainingFields);
if (preferableFields.isEmpty() || statusChanged) {
if (statusChanged) {
statusChanged = false;
preferableFields.clear();
}
//System.out.println("random zet");
playField = remainingFields.get(0);
if (playField.getBoat()) {
putSurroundingFieldsInPreferable(playField);
prevHitX = playField.getX();
//volgende 2 regels ok??
setPrevHitX(playField.getX());
setPrevHitY(playField.getY());
}
} else {
//System.out.println("voorkeurzet");
playField = preferableFields.get(0);
if (playField.getBoat()) {
putSurroundingFieldsInPreferable(playField);
if (playField.getX() == prevHitX) {
deleteNonAxisFields(playField, "horizontal");
} else {
deleteNonAxisFields(playField, "vertical");
}
setPrevHitX(defaultValue);
setPrevHitY(defaultValue);
}
}
if (preferableFields.contains(playField)) {
preferableFields.remove(playField);
}
remainingFields.remove(playField);
board.setFieldHit(playField.getX(), playField.getY());
System.out.println("Computerzet was (" + playField.getX() + "," + (char)(playField.getY() + 65) + ")");
} | 7 |
public String getGoogleMapsXMLQuery(GeoAdresse pAdresse) throws UnsupportedEncodingException {
// http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true
// Removes whitespace between a word character and . or ,
String pattern = "(\\s+)"; // "([\\p{Space}]+)";
/*
StringBuilder vStrBuilder = new StringBuilder("xml?address=")
.append("").append((this.getHouseIdentifier() != null ? this.getHouseIdentifier().trim().replaceAll(pattern, "+") : ""))
.append("+").append(this.getStreet() != null ? this.getStreet().trim().replaceAll(pattern, "+") : "")
.append(",+").append(this.getPostalCode() != null ? this.getPostalCode().trim().replaceAll(pattern, "+") : "")
.append(",+").append(this.getLocalityName() != null ? this.getLocalityName().trim().replaceAll(pattern, "+") : "")
.append(",+").append(this.getStateOrProvinceName() != null ? ",+" + this.getStateOrProvinceName().replaceAll(pattern, "+") : "")
.append(",+").append(this.getCountryName() != null ? this.getCountryName().trim().replaceAll(pattern, "+") : "")
.append("&sensor=true");
return vStrBuilder.toString();
*/
String vCountryLongName = null;
StringBuilder vStrBuilder =
new StringBuilder("xml?address=")
// -- HausNummer Strasse
.append(
(pAdresse.getHouseIdentifier() != null ? URLEncoder.encode(pAdresse
.getHouseIdentifier().trim().replaceAll(pattern, " "), "UTF-8") : ""))
.append(
pAdresse.getStreet() != null ? URLEncoder.encode(" "
+ pAdresse.getStreet().trim().replaceAll(pattern, " "), "UTF-8") : " ")
// -- PLZ Ort
.append(",")
.append(
pAdresse.getPostalCode() != null ? URLEncoder.encode(" "
+ pAdresse.getPostalCode().trim().replaceAll(pattern, " "), "UTF-8") : "")
.append(
pAdresse.getLocalityName() != null ? URLEncoder.encode(" "
+ pAdresse.getLocalityName().trim().replaceAll(pattern, " "), "UTF-8") : "")
// -- Bundesland
.append(",")
.append(
pAdresse.getStateOrProvinceName() != null ? URLEncoder.encode(" "
+ pAdresse.getStateOrProvinceName().replaceAll(pattern, " "), "UTF-8") : "")
// -- Land
.append(",")
.append(
((pAdresse.getCountryName() != null) && ((vCountryLongName =
countryLongName(pAdresse.getCountryName().trim().replaceAll(pattern, " "))) != null)) ? URLEncoder
.encode(" " + vCountryLongName, "UTF-8") : "")
/*
.append(",").append(
pAdresse.getCountryName() != null ? URLEncoder.encode(" "
+ pAdresse.getCountryName().trim().replaceAll(pattern, " "), "UTF-8") : "")
*/
.append("&sensor=true");
//.append("&sensor=false");
System.out.println("\n" + vStrBuilder.toString());
return vStrBuilder.toString();
} | 7 |
private void asetaVKuva() {
if (noppa == 2 || noppa == 3){
ImageIcon skelly = new ImageIcon(new ImageIcon(getClass().getResource("/skellyface.jpg")).getImage());
setIcon(skelly);
} else if (noppa == 4 || noppa == 5){
ImageIcon orkki = new ImageIcon(new ImageIcon(getClass().getResource("/orkki.jpg")).getImage());
setIcon(orkki);
} else if (noppa == 6){
ImageIcon lohikaarme = new ImageIcon(new ImageIcon(getClass().getResource("/doragon.jpg")).getImage());
setIcon(lohikaarme);
}
} | 5 |
public SwingWorker getTask() {
return task;
} | 0 |
public final synchronized double readDouble(){
this.inputType = true;
String word="";
double dd=0.0D;
if(!this.testFullLineT) this.enterLine();
word = nextWord();
if(!eof)dd = Double.parseDouble(word.trim());
return dd;
} | 2 |
public Vec3D getSkyColor(Entity par1Entity, float par2)
{
float var3 = this.getCelestialAngle(par2);
float var4 = MathHelper.cos(var3 * (float)Math.PI * 2.0F) * 2.0F + 0.5F;
if (var4 < 0.0F)
{
var4 = 0.0F;
}
if (var4 > 1.0F)
{
var4 = 1.0F;
}
int var5 = MathHelper.floor_double(par1Entity.posX);
int var6 = MathHelper.floor_double(par1Entity.posZ);
BiomeGenBase var7 = this.getBiomeGenForCoords(var5, var6);
float var8 = var7.getFloatTemperature();
int var9 = var7.getSkyColorByTemp(var8);
float var10 = (float)(var9 >> 16 & 255) / 255.0F;
float var11 = (float)(var9 >> 8 & 255) / 255.0F;
float var12 = (float)(var9 & 255) / 255.0F;
var10 *= var4;
var11 *= var4;
var12 *= var4;
float var13 = this.getRainStrength(par2);
float var14;
float var15;
if (var13 > 0.0F)
{
var14 = (var10 * 0.3F + var11 * 0.59F + var12 * 0.11F) * 0.6F;
var15 = 1.0F - var13 * 0.75F;
var10 = var10 * var15 + var14 * (1.0F - var15);
var11 = var11 * var15 + var14 * (1.0F - var15);
var12 = var12 * var15 + var14 * (1.0F - var15);
}
var14 = this.getWeightedThunderStrength(par2);
if (var14 > 0.0F)
{
var15 = (var10 * 0.3F + var11 * 0.59F + var12 * 0.11F) * 0.2F;
float var16 = 1.0F - var14 * 0.75F;
var10 = var10 * var16 + var15 * (1.0F - var16);
var11 = var11 * var16 + var15 * (1.0F - var16);
var12 = var12 * var16 + var15 * (1.0F - var16);
}
if (this.lightningFlash > 0)
{
var15 = (float)this.lightningFlash - par2;
if (var15 > 1.0F)
{
var15 = 1.0F;
}
var15 *= 0.45F;
var10 = var10 * (1.0F - var15) + 0.8F * var15;
var11 = var11 * (1.0F - var15) + 0.8F * var15;
var12 = var12 * (1.0F - var15) + 1.0F * var15;
}
return Vec3D.createVector((double)var10, (double)var11, (double)var12);
} | 6 |
private int countConfs(int numMutable, int numRes, /*boolean ligPresent,*/
int strandMut[][], int numRotForRes[], int numRotForResNonPruned[]){
int numTotalRotRed = 0;
numConfsTotal = BigInteger.valueOf(1);
numConfsAboveLevel = new BigInteger[numRes];
int curNumRot;
//Store the number of rotamers for each AA in the current mutation
//The ligand (if present) is in the last level
for (int curLevel=0; curLevel<numRes; curLevel++){
int str = mutRes2Strand[curLevel];
int strResNum = strandMut[str][mutRes2StrandMutIndex[curLevel]];
int molResNum = m.strand[str].residue[strResNum].moleculeResidueNumber;
/*if ((ligPresent)&&(curLevel==(numRes-1))) //the ligand level
curNumRot = grl.getNumRotForAAtype(curLigAANum);
else*/
curNumRot = getNumRot( str, strResNum, curAANum[molResNum] );
numRotForRes[curLevel] = curNumRot;
numRotForResNonPruned[curLevel] = numRotForRes[curLevel];
numTotalRotRed += numRotForRes[curLevel];
numConfsTotal = numConfsTotal.multiply(BigInteger.valueOf(numRotForRes[curLevel]));
}
BigInteger numPruned = BigInteger.ZERO;
int numPrunedThisLevel;
//Count the number of rotamers pruned by MinDEE
for (int curLevel=0; curLevel<numRes; curLevel++){
numPrunedThisLevel = 0;
int str = mutRes2Strand[curLevel];
int strResNum = strandMut[str][mutRes2StrandMutIndex[curLevel]];
int molResNum = m.strand[str].residue[strResNum].moleculeResidueNumber;
for (int curRot=0; curRot<numRotForRes[curLevel]; curRot++){
//int curIndex;
/*if ((ligPresent)&&(curLevel==(numRes-1))) //the ligand level
curIndex = numInAS*numTotalRotamers + curRot;
else*/
//TODO: fix rotamerIndexOffset so that it works for multiple strands/multiple rotamer libraries
//curIndex = curLevel*numTotalRotamers + rotamerIndexOffset[curAANum[molResNum]] + curRot;
if (eliminatedRotAtRes.get(curLevel,curAANum[molResNum],curRot)){
numPruned = numPruned.add(compPrunedConfsByRot(numRotForResNonPruned,numRes,curLevel));
numPrunedThisLevel++;
}
}
numRotForResNonPruned[curLevel] -= numPrunedThisLevel;
}
//Count the number of conformations below each level (flexible residue)
if (numRes>0)
numConfsAboveLevel[numRes-1] = new BigInteger("1"); //the last level
if (numRes>1){
for (int curLevel=numRes-2; curLevel>=0; curLevel--){
numConfsAboveLevel[curLevel] = numConfsAboveLevel[curLevel+1].multiply(BigInteger.valueOf(numRotForResNonPruned[curLevel+1]));
}
}
numConfsPrunedByMinDEE = numPruned; //set the number of confs pruned by MinDEE
numConfsLeft = numConfsTotal.subtract(numConfsPrunedByMinDEE);
numConfsPrunedByS = BigInteger.valueOf(0);
return numTotalRotRed;
} | 7 |
private boolean findNewCombinations(Combination combination) {
boolean somethingChanged = false;
Combination newCombination = null;
for (int i = 0; i < combination.pitchers.size(); i++) {
// ***** leerkippen
if (combination.pitchers.get(i).isNotEmpty()) {
newCombination = combination.clone();
newCombination.pitchers.get(i).filling = 0;
somethingChanged |= tryToAdd(newCombination);
}
// ***** vollkippen wenn unlimited water
if (unlimitedWater && combination.pitchers.get(i).isNotFull()) {
newCombination = combination.clone();
newCombination.pitchers.get(i).filling = newCombination.pitchers.get(i).volumen;
somethingChanged |= tryToAdd(newCombination);
}
// ***** umkippen zu allen anderen ...
for (int j = 0; j < combination.pitchers.size(); j++) {
if (i == j) continue;
if (combination.pitchers.get(i).isNotEmpty() && combination.pitchers.get(j).isNotFull()) {
newCombination = combination.clone();
moveWater(newCombination.pitchers.get(i), newCombination.pitchers.get(j));
somethingChanged |= tryToAdd(newCombination);
}
}
}
return somethingChanged;
} | 8 |
public void updateBookText(Player p, ItemStack item) {
ItemStack i = item == null ? p.getItemInHand() : item;
if(!i.getType().equals(Material.WRITTEN_BOOK)) return;
if(!i.getItemMeta().hasDisplayName()) return;
if(!i.getItemMeta().getDisplayName().equals(ConfigHandler.prayItemName)) return;
if(!(i.getItemMeta() instanceof BookMeta)) return;
AGPlayer agp = getAGPlayer(p.getName());
if(agp == null)
agp = addAGPlayer(p.getName());
BookMeta book = (BookMeta) i.getItemMeta();
List<String> pages = new ArrayList<String>();
pages.add(ChatColor.BOLD+"\n\n\n\n\n\n "+stripColorCodes(ConfigHandler.prayItemName));
pages.add("\n\n\n\n\n\nDu hast bereits "+agp.getFoundShrines().size()+" von "+AGManager.getShrineHandler().getShrines().size()+" Schreinen gefunden.");
for(God god : AGManager.getGodHandler().getGodList()) {
pages.add(ChatColor.BOLD+stripColorCodes(god.getDisplayname())+"\n\n"+ChatColor.RESET+stripColorCodes(god.getDescription()));
for(Praying praying : god.getPrayings()) {
pages.add(ChatColor.BOLD+stripColorCodes(praying.getDisplayname())+"\n\n"+ChatColor.RESET+stripColorCodes(praying.getDescription()));
}
}
book.setPages(pages);
i.setItemMeta(book);
} | 8 |
private static void chiSquareTestOnFile(Path path, HashFunction func) {
Vector<Double> values = new Vector<Double>();
for (String w : new WordReader(path))
values.add((double) func.hashString(w) );
// Convert the Vector<Double> into an array of doubles
int i = 0;
double[] tab = new double[values.size()];
for (Double d : values) {
tab[i] = d.doubleValue();
i++;
}
// Number of bins in the histogram
int bins = 100;
// Frequencies of the hash values (doubles)
double[] freq = histogram(tab, min(tab), max(tab), bins);
// Array of longs. To cast from freq.
long[] frequencies = new long[bins];
// Expected frequencies.
double[] expected = new double[bins];
for (int j = 0; j < bins; j++) {
// Cast
frequencies[j] = (long) freq[j];
// Expected frequencies for a uniform distribution on the hash
// values
expected[j] = tab.length / bins;
}
// Chi2 test from the Apache commons math package.
ChiSquareTest chi = new ChiSquareTest();
System.out.println("Result of a chi-square test with confidence level of 95% :");
// Returns true if the null hypothesis (that the observed counts
// conform
// to the frequency
// distribution described by the expected counts) can be
// rejected with
// 100 * (1 - alpha)
// percent confidence. We choose alpha = 0.05.
System.out.println(" " + Boolean.toString(!chi.chiSquareTest(expected, frequencies, 0.05)));
System.out.println("The p-value is");
System.out.println(" " + chi.chiSquareTest(expected, frequencies));
} | 3 |
private void loadPreviousFonts() {
this.previousFonts = new ArrayList<Font>();
for (int i = this.startFrom; i <= this.endAt; i++) {
this.previousFonts
.add(this.document.getChildren().get(i).getFont());
}
} | 1 |
private void saveResults()
throws ClusterException {
ObjectFactory obf= new ObjectFactory();
ClusterDataType cdt= obf.createClusterDataType();
//set the creation date
try {
cdt.setXMLFileCreation(DateConverter.CurrentDateToXMLGregorianCalendar());
} catch (DateConverterException e) {
throw new ClusterException(e.getMessage(), e);
}
ClusterListType clusters= obf.createClusterListType();
clusters.setK(BigInteger.valueOf(this.clusterNumber));
clusters.setIter(BigInteger.valueOf(this.iter));
Iterator<Cluster> iterC= this.clusterList.iterator();
while(iterC.hasNext()) {
Cluster c= iterC.next();
ClusterType ct= obf.createClusterType();
ct.setId(BigInteger.valueOf(c.getId()));
ct.setCount(BigInteger.valueOf(c.getSongCount()));
Iterator<Song> iterS= c.getSongListCopy().iterator();
while(iterS.hasNext()) {
Song s= iterS.next();
ct.getSongPath().add(s.getPath());
}
clusters.getCluster().add(ct);
}
cdt.setClusterList(clusters);
File output= null;
try {
//marshall this JaxbElement
JAXBContext jc= JAXBContext.newInstance("clusterArtifacts");
JAXBElement<ClusterDataType> je= obf.createClusterData(cdt);
Marshaller m= jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
SchemaFactory sf= SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
InputStream is= LowLevelSongFeature.class.getClassLoader().getResourceAsStream("MetadataSchema/cluster.xsd");
Schema schema= sf.newSchema(new StreamSource(is));
m.setSchema(schema);
m.setEventHandler(new ValidationEventHandler() {
@Override
public boolean handleEvent(ValidationEvent event) {
return false;
}
});
output= new File("KMEANS "+new Date().toString()+".xml");
m.marshal(je, output);
} catch (JAXBException e) {
if(output != null) {
this.log.warning("Error "+output.getName()+" "+e.getMessage());
output.delete();
} else {
this.log.warning("Error to create kmeans file result. "+e.getMessage());
}
throw new ClusterException("JAXBException "+e.getMessage(), e);
} catch (SAXException e) {
this.log.warning("Error in kemans. "+e.getMessage());
throw new ClusterException("SAXException "+e.getMessage(), e);
} catch (Exception e) {
this.log.warning("Error in kemans. "+e.getMessage());
throw new ClusterException("Exception "+e.getMessage(), e);
}
} | 7 |
@Override
public CuentaBancaria findByCodigo(String CodigoCuentaCliente) {
Session session = sessionFactory.openSession();
session.beginTransaction();
Query query = session.createQuery("SELECT cuentaBancaria FROM CuentaBancaria cuentaBancaria WHERE cuentaBancaria.sucursalBancaria.codigoSucursal=? AND cuentaBancaria.sucursalBancaria.entidadBancaria.codigoEntidadBancaria=? AND cuentaBancaria.dc=? AND cuentaBancaria.numeroCuenta=?");
query.setString(0, CodigoCuentaCliente.substring(0, 4));
query.setString(1, CodigoCuentaCliente.substring(4, 8));
query.setString(2, CodigoCuentaCliente.substring(8, 10));
query.setString(3, CodigoCuentaCliente.substring(10, 20));
List<CuentaBancaria> listaCuentaBancaria = query.list();
session.getTransaction().commit();
if (listaCuentaBancaria != null) {
if (listaCuentaBancaria.size() == 1) {
CuentaBancaria cuentaBancaria = listaCuentaBancaria.get(0);
return cuentaBancaria;
} else {
return null;
}
} else {
return null;
}
} | 2 |
public Direction getOpposite() {
switch (this) {
case BOTTOM:
return TOP;
case LEFT:
return RIGHT;
case RIGHT:
return LEFT;
case TOP:
return BOTTOM;
case CENTER:
default:
return null;
}
} | 5 |
@Override
public void modifyGenAbility(MOB mob, Ability me, int showFlag) throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
if((showFlag == -1) && (CMProps.getIntVar(CMProps.Int.EDITORTYPE)>0))
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().isStopped())&&(!ok))
{
int showNumber=0;
// id is bad to change.. make them delete it.
//genText(mob,me,null,++showNumber,showFlag,"Enter the class","CLASS");
promptStatStr(mob,me,null,++showNumber,showFlag,"Ability/Skill name","NAME",false);
promptStatStr(mob,me,CMParms.toListString(Ability.ACODE_DESCS)+","+CMParms.toListString(Ability.DOMAIN_DESCS),++showNumber,showFlag,"Type, Domain","CLASSIFICATION",false);
promptStatStr(mob,me,null,++showNumber,showFlag,"Command Words (comma sep)","TRIGSTR",false);
promptStatStr(mob,me,CMParms.toListString(Ability.RANGE_CHOICES),++showNumber,showFlag,"Minimum Range","MINRANGE",false);
promptStatStr(mob,me,CMParms.toListString(Ability.RANGE_CHOICES),++showNumber,showFlag,"Maximum Range","MAXRANGE",false);
promptStatStr(mob,me,null,++showNumber,showFlag,"Ticks Between Casts","TICKSBETWEENCASTS",false);
promptStatStr(mob,me,null,++showNumber,showFlag,"Duration Override (0=NO)","TICKSOVERRIDE",false);
promptStatStr(mob,me,null,++showNumber,showFlag,"Affect String","DISPLAY",true);
promptStatBool(mob,me,++showNumber,showFlag,"Is Auto-invoking","AUTOINVOKE");
promptStatStr(mob,me,"0,"+CMParms.toListString(Ability.FLAG_DESCS),++showNumber,showFlag,"Skill Flags (comma sep)","FLAGS",true);
promptStatInt(mob,me,"-1,x,"+Integer.MAX_VALUE+","+Integer.MAX_VALUE+"-(1 to 100)",++showNumber,showFlag,"Override Cost","OVERRIDEMANA");
promptStatStr(mob,me,CMParms.toListString(Ability.USAGE_DESCS),++showNumber,showFlag,"Cost Type","USAGEMASK",false);
promptStatStr(mob,me,"0,"+CMParms.toListString(Ability.CAN_DESCS),++showNumber,showFlag,"Can Affect","CANAFFECTMASK",true);
promptStatBool(mob,me,++showNumber,showFlag,"Tick/Periodic Affects","TICKAFFECTS");
promptStatStr(mob,me,"0,"+CMParms.toListString(Ability.CAN_DESCS),++showNumber,showFlag,"Can Target","CANTARGETMASK",true);
promptStatStr(mob,me,CMParms.toListString(Ability.QUALITY_DESCS),++showNumber,showFlag,"Quality Code","QUALITY",true);
promptStatStr(mob,me,"The parameters for this field are LIKE the parameters for this property:\n\r\n\r"+
CMLib.help().getHelpText("Prop_HereAdjuster",mob,true).toString(),++showNumber,showFlag,"Affect Adjustments","HERESTATS",true);
promptStatStr(mob,me,CMLib.masking().maskHelp("\n","disallow"),++showNumber,showFlag,"Caster Mask","CASTMASK",true);
promptStatStr(mob,me,CMLib.help().getHelpText("Scriptable",mob,true).toString(),++showNumber,showFlag,"Scriptable Parm","SCRIPT",true);
promptStatStr(mob,me,CMLib.masking().maskHelp("\n","disallow"),++showNumber,showFlag,"Target Mask","TARGETMASK",true);
promptRawStatStr(mob,me,null,++showNumber,showFlag,"Fizzle Message","FIZZLEMSG",true);
promptRawStatStr(mob,me,null,++showNumber,showFlag,"Auto-Cast Message","AUTOCASTMSG",true);
promptRawStatStr(mob,me,null,++showNumber,showFlag,"Normal-Cast Message","CASTMSG",true);
promptRawStatStr(mob,me,null,++showNumber,showFlag,"Post-Cast Message","POSTCASTMSG",true);
promptStatStr(mob,me,CMParms.toListString(CMMsg.TYPE_DESCS),++showNumber,showFlag,"Attack-Type","ATTACKCODE",true);
promptStatStr(mob,me,"The parameters for this field are LIKE the parameters for this property:\n\r\n\r"+
CMLib.help().getHelpText("Prop_HereSpellCast",mob,true).toString(),++showNumber,showFlag,"Silent affects","POSTCASTAFFECT",true);
promptStatStr(mob,me,"The parameters for this field are LIKE the parameters for this property:\n\r\n\r"+
CMLib.help().getHelpText("Prop_HereSpellCast",mob,true).toString(),++showNumber,showFlag,"Extra castings","POSTCASTABILITY",true);
promptStatStr(mob,me,"Enter a damage or healing formula. Use +-*/()?. @x1=caster level, @x2=target level. Formula evaluates >0 for damage, <0 for healing. Requires Can Target!",++showNumber,showFlag,"Damage/Healing Formula","POSTCASTDAMAGE",true);
promptStatStr(mob,me,null,++showNumber,showFlag,"Help Text","HELP",true);
if (showFlag < -900)
{
ok = true;
break;
}
if (showFlag > 0)
{
showFlag = -1;
continue;
}
showFlag=CMath.s_int(mob.session().prompt(L("Edit which? "),""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
}
}
} | 9 |
public static boolean fileprocess(String downloadpath, String filepath, String []paras, String sn){
int errorcode=0;// print error code in the final output file;
int errornum=17; // feature number
String result="";
File downloadfile_r = new File(downloadpath+"\\emmc_test.txt");
File outputfile = new File(filepath);
try {
String line="";
ArrayList<String> content_r = new ArrayList<String>();
BufferedReader br_r = new BufferedReader(new FileReader(downloadfile_r));
while ((line=br_r.readLine())!=null){
content_r.add(line);
}
br_r.close();
downloadfile_r.delete();
if (content_r.size()==paras.length){
if (content_r.get(0).equals(paras[0])){
result = "PASS";
}
else {
result = "FAILED";
errorcode = 2;
}
}
else {
result = "FAILED";
errorcode = 1;
}
} catch (IOException e) {
result = "FAILED";
errorcode = 0;
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(outputfile,true));
bw.write("RW_EMMC_Result="+result+"\r\n");
System.out.println("RW_EMMC_Result="+result);
if (result.equals("FAILED")){
NumberFormat nf = NumberFormat.getIntegerInstance();
nf.setMinimumIntegerDigits(2);
bw.write("Error_Code= "+nf.format(errornum)+nf.format(errorcode)+"\r\n");
}
bw.flush();
bw.close();
}catch (Exception e){
e.printStackTrace();
}
return true;
} | 6 |
private static boolean handleTrue(String string) {
switch (string.toLowerCase()) {
case "on":
case "true":
case "yes":
case "enable":
return true;
}
// Otherwise if something is wrong, just assume we need it
return false;
} | 4 |
public boolean ColliderWithPodiumUp(){
if((x>=0 && x<=Podium.WIDTH - WIDTH/2)
&& (y<=GameMain.GAME_HEIGHT_ASSUM - GameMain.DistanceBottomAndPodiumUp- HEIGHT/1.2 && y>= GameMain.GAME_HEIGHT_ASSUM - GameMain.DistanceBottomAndPodiumUp- HEIGHT)){
return true;
}
if((x>=GameMain.GAME_WIDTH + WIDTH/2 - Podium.WIDTH - Character.WIDTH && x<=GameMain.GAME_WIDTH)
&& (y<=GameMain.GAME_HEIGHT_ASSUM - GameMain.DistanceBottomAndPodiumUp- HEIGHT/1.2 && y>= GameMain.GAME_HEIGHT_ASSUM - GameMain.DistanceBottomAndPodiumUp- HEIGHT)){
return true;
}
return false;
} | 8 |
@Override
public void insertNext(T i, T j) {
if (j.getParent() != null)
throw new PromiscuousItemException(j, i.getParent());
if ((j.getNext() != null) || (j.getPrev() != null))
throw new PromiscuousItemException(j);
if (i == null) {
// insert as head
j.setPrev(null);
j.setNext(_firstItem);
j.setParent(this);
if (_firstItem != null) {
_firstItem.setPrev(j);
_firstItem = j;
} else {
_firstItem = _lastItem = j;
}
++size;
} else {
if (i.getParent() != this)
throw new PromiscuousItemException(i, i.getParent());
T next = i.getNext();
if (next == null) {
if (i != _lastItem)
throw new VirginItemException(i);
_lastItem = j;
} else
next.setPrev(j);
j.setNext(next);
i.setNext(j);
j.setPrev(i);
j.setParent(this);
++size;
}
} | 8 |
public ClueGame(String layout, String legend) {
layoutFile = layout;
legendFile = legend;
try {
board = new Board(layoutFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadConfigFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 2 |
public void makeThreeSamplesRandomized() {
samples.clear();
samples.add(new ArrayList<Integer>());
samples.add(new ArrayList<Integer>());
samples.add(new ArrayList<Integer>());
int countInitialSample = datas.size();
int countTrainingSample = (int) (countInitialSample * p_train_pattern);
int countTestSample = (int) (countInitialSample * p_test_pattern);
List<Integer> allNumbers = new ArrayList<Integer>();
for (int i = 0; i < countInitialSample; i++) {
allNumbers.add(i);
}
int restInInitialSample = countInitialSample;
for (int i = 0; i < countTrainingSample; i++) {
int rand = (int) (Math.random() * restInInitialSample);
samples.get(0).add(allNumbers.remove(rand));
restInInitialSample--;
}
for (int i = 0; i < countTestSample; i++) {
int rand = (int) (Math.random() * restInInitialSample);
samples.get(1).add(allNumbers.remove(rand));
restInInitialSample--;
}
for (int i = 0; i < allNumbers.size(); i++) {
samples.get(2).add(allNumbers.get(i));
}
} | 4 |
@Override
public void onTurnStarted(TurnStartedEvent e) {
if(missile != null && !missile.isActive()) {
missile = null;
}
} | 2 |
private void configFindExtension(Method method) throws DaoGenerateException {
MongoLimit mongoLimit = method.getAnnotation(MongoLimit.class);
if (mongoLimit != null && mongoLimit.value() != -1) {
limit = mongoLimit.value();
}
MongoSkip mongoSkip = method.getAnnotation(MongoSkip.class);
if (mongoSkip != null && mongoSkip.value() != -1) {
skip = mongoSkip.value();
}
MongoSort sort = method.getAnnotation(MongoSort.class);
if (sort != null) {
try {
sortObject = (DBObject) JSON.parse(sort.value());
} catch (Exception e) {
throw new DaoGenerateException("方法[" + method + "]配置错误:@MongoSort注解配置的表达式 不符合BSON格式");
}
}
} | 6 |
private String replaceDate(final String log) {
String formattedLog = new String(log);
String regex = "(.*)(%d\\{)([^\\}]*)(\\})(.*)";
Date date = new Date();
while (formattedLog.matches(regex)) {
String pattern = formattedLog.replaceFirst(regex, "$3");
SimpleDateFormat format = new SimpleDateFormat(pattern);
String dateStr = format.format(date);
String patron = "%d\\{" + pattern + "\\}";
formattedLog = formattedLog.replaceAll(patron, dateStr);
}
return formattedLog;
} | 1 |
@Override
public void update(Observable o, Object arg) {
if (presenter.getState().getStatus().equals("Rolling") && presenter.isPlayersTurn() && !timerStarted) {
rollView.showModal();
rollView.startTimer();
timerStarted = true;
}
} | 3 |
@EventHandler
public void onSignDestroy(BlockBreakEvent e) {
if(e.isCancelled())
return;
Player p = e.getPlayer();
for(ServerSign rs : ServerSigns.getInstance().getSigns()) {
if(rs.getSignLocation().getBlockX() == e.getBlock().getLocation().getBlockX()) {
if(rs.getSignLocation().getBlockY() == e.getBlock().getLocation().getBlockY()) {
if(rs.getSignLocation().getBlockZ() == e.getBlock().getLocation().getBlockZ()) {
if(!p.isOp() && !p.hasPermission("serversigns.destroy")) {
e.setCancelled(true);
p.sendMessage(ChatColor.GREEN + "[ServerSigns] " + ChatColor.GOLD + ServerSigns.getLangManager().getLocaleMessage("lang.global.nopermission"));
return;
}
List<ServerSign> signs = DataStore.getInstance().getSigns();
int index = 0;
for(int i = 0; i < signs.size(); i++) {
ServerSign sign = signs.get(i);
if(sign.equals(rs)) {
index = i;
break;
}
}
signs.remove(index);
DataStore.getInstance().setSigns(signs);
ServerSigns.getInstance().reloadSigns();
p.sendMessage(ChatColor.GREEN + "[ServerSigns] " + ChatColor.GOLD + ServerSigns.getLangManager().getLocaleMessage("lang.creation.destroyed"));
break;
}
}
}
}
} | 9 |
@Override
protected void setzeZustand(Graphics2D g)
{
if ((this.zMuster == 2) && (this.zFarbe.getTransparency() != 3))
{
this.zFarbe = new Color(this.zFarbe.getRed(), this.zFarbe.getGreen(), this.zFarbe.getBlue(), 128);
}
else if ((this.zMuster != 2) && (this.zFarbe.getTransparency() != 1))
{
this.zFarbe = new Color(this.zFarbe.getRed(), this.zFarbe.getGreen(), this.zFarbe.getBlue());
}
if (this.zSchreibModus == 1)
{
g.setPaint(this.kenntPrivatschirm.hintergrundfarbe());
g.setPaintMode();
}
else if (this.zSchreibModus == 0)
{
g.setPaint(this.zFarbe);
g.setPaintMode();
}
else
{
g.setPaint(this.zFarbe);
g.setXORMode(this.kenntPrivatschirm.hintergrundfarbe());
}
this.zSchriftArt = new Font(this.zAktuellFont, this.zSchriftStil, this.zSchriftGroesse);
g.setFont(this.zSchriftArt);
} | 6 |
@Override
public String execute() throws Exception {
try {
Map session = ActionContext.getContext().getSession();
Campaign camp = (Campaign) session.get("campa");
CampaignDevice campdev = new CampaignDevice(camp, getPlatform());
getMyDao().getDbsession().save(campdev);
CampaignLocation camploc = new CampaignLocation(camp, getLocation());
getMyDao().getDbsession().save(camploc);
CampaignDemography campdemo = new CampaignDemography();
campdemo.setCampaign(camp);
campdemo.setSex(gender);
campdemo.setAge(getAge());
getMyDao().getDbsession().save(campdemo);
return "success";
} catch (HibernateException e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
} catch (NullPointerException ne) {
addActionError("Server Error Please Recheck All Fields ");
ne.printStackTrace();
return "error";
} catch (Exception e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
}
} | 3 |
public static int guessAWTFontStyle(String name) {
name = name.toLowerCase();
int decorations = 0;
if (name.indexOf(AWT_STYLE_BOLD_ITAL) > 0 ||
name.indexOf(AWT_STYLE_DEMI_ITAL) > 0) {
decorations |= java.awt.Font.BOLD | java.awt.Font.ITALIC;
} else if (name.indexOf(STYLE_BOLD) > 0 ||
name.indexOf(STYLE_BLACK) > 0 ||
name.indexOf(STYLE_DEMI) > 0) {
decorations |= java.awt.Font.BOLD;
} else if (name.indexOf(AWT_STYLE_ITAL) > 0 ||
name.indexOf(AWT_STYLE_OBLI) > 0) {
decorations |= java.awt.Font.ITALIC;
} else {
decorations |= java.awt.Font.PLAIN;
}
return decorations;
} | 7 |
public void saveProjectAs(LayeredPanelList panelListIn){
fc = new JFileChooser(strProjectsDir);
fc.showSaveDialog(compParent);
try{
if(fc.getSelectedFile() != null){
this.strCurrentProject = fc.getSelectedFile().toString();
FileOutputStream fos = new FileOutputStream(fc.getSelectedFile());
//FileOutputStream fos = new FileOutputStream(System.getProperty("user.home")+ "/testing" + "/projects/" + "test.pnt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(System.getProperty("user.home")+ "/Paintimator" + "/projects");
oos.writeObject(panelListIn);
oos.close();
}
}catch(IOException ex){
System.err.print(ex);
}finally{
}
} | 2 |
public List<String> getBestViterbiPath() {
Iterator<String> myIt=ViterbiEndpoint.keySet().iterator();
String myStr, bestStr="";
double bestVal=0;
boolean entered=false;
while (myIt.hasNext()) {
myStr=myIt.next();
if (!entered || bestVal< ViterbiEndpoint.get(myStr))
{bestVal=ViterbiEndpoint.get(myStr);bestStr=myStr;entered=true;}
}
if (!entered) { return (new ArrayList<String>()); }
return ViterbiPath.get(bestStr);
} | 4 |
public boolean isSurroundClicked(int x, int y) {
//first check the square is actually non-mine
if (board[x][y].isMine()) return false;
//the square must also have at least 1 adjacent mine
for (int i = x - 1; i <= x + 1; i++) {
for (int j = y - 1; j <= y + 1; j++) {
//position must exist, and we don't count centre square
if (!positionExists(i, j) || (i == x && j == y)) continue;
if (!board[i][j].isRevealed()) return false;
}
}
return true;
} | 7 |
private boolean delete(int i) {
checkInvariants();
final E[] elements = this.elements;
final int mask = elements.length - 1;
final int h = head;
final int t = tail;
final int front = (i - h) & mask;
final int back = (t - i) & mask;
// Invariant: head <= i < tail mod circularity
if (front >= ((t - h) & mask))
throw new ConcurrentModificationException();
// Optimize for least element motion
if (front < back) {
if (h <= i) {
System.arraycopy(elements, h, elements, h + 1, front);
} else { // Wrap around
System.arraycopy(elements, 0, elements, 1, i);
elements[0] = elements[mask];
System.arraycopy(elements, h, elements, h + 1, mask - h);
}
elements[h] = null;
head = (h + 1) & mask;
return false;
} else {
if (i < t) { // Copy the null tail as well
System.arraycopy(elements, i + 1, elements, i, back);
tail = t - 1;
} else { // Wrap around
System.arraycopy(elements, i + 1, elements, i, mask - i);
elements[mask] = elements[0];
System.arraycopy(elements, 1, elements, 0, t);
tail = (t - 1) & mask;
}
return true;
}
} | 4 |
public void addAbsenta(SituatieMaterieBaza sit, Node node) {
TipAbsenta tip = null;
Date data = null;
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node cNode = childNodes.item(i);
if (cNode instanceof Element) {
String content = cNode.getLastChild().getTextContent().trim();
switch (cNode.getNodeName()) {
case "status":
if (content.equals("motivata")) {
tip = TipAbsenta.motivata;
} else if (content.equals("nemotivata")) {
tip = TipAbsenta.nemotivata;
} else if (content.equals("nedeterminat")) {
tip = TipAbsenta.nedeterminat;
}
break;
case "data":
try {
SimpleDateFormat form = new SimpleDateFormat(
"yyyy-MM-dd");
Date d;
d = form.parse(content);
data = d;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
sit.addAbsenta(tip, data);
} | 8 |
private static Collection<Word> readWords(File file) throws IOException{
String ruWord = "";
String engWord = "";
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
Collection<Word> lWord = new ArrayList<Word>();
while((line = reader.readLine())!=null){
int i = 0;
// for(int i = 0; i<line.length(); i++){
if(line.contains(":"))
while(line.charAt(i)!=':'){
engWord = engWord+line.charAt(i);
i++;
}
i++;
while(i<line.length()){
ruWord = ruWord+line.charAt(i);
i++;
}
// if( (line.charAt(i)>=65)&&(line.charAt(i)<=122))
// engWord = engWord+line.charAt(i);
// if((line.charAt(i)>=1040)&&(line.charAt(i)<=1102))
// ruWord = ruWord+line.charAt(i);
// }
lWord.add(new Word(engWord, ruWord));
ruWord = "";
engWord = "";
}
reader.close();
return lWord;
} | 4 |
protected void forkJavaVM(String[] args)
throws MojoExecutionException {
try {
final Commandline commandLine = new Commandline();
commandLine.setExecutable(getJavaExecutable().getAbsolutePath());
commandLine.setWorkingDirectory(workingDirectory.getAbsolutePath());
commandLine.addArguments(args);
final StreamConsumer stdout = new StreamConsumer() {
public void consumeLine(String line) {
getLog().info(line);
}
};
final StreamConsumer stderr = new StreamConsumer() {
public void consumeLine(String line) {
getLog().error(line);
}
};
int ret = CommandLineUtils.executeCommandLine(commandLine, stdout, stderr);
if (ret != 0) {
throw new MojoExecutionException("RubyRunMain exited with status code: " + ret);
}
} catch (CommandLineException ex) {
throw new MojoExecutionException(ex.getMessage(), ex);
}
} | 2 |
public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
} | 6 |
protected void awaitTermination() {
try {
this.completionLatch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} | 1 |
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
// Top line
sb.append('+');
for (int x = 0; x < width; ++x) {
sb.append("-+");
}
sb.append('\n');
// Other lines
for (int y = 0; y < height; ++y) {
sb.append('|');
// Row content
for (int x = 0; x < width; ++x) {
Cell cell = getCell(x, y);
sb.append(cell.isAccessible() ? cell.getContent() : '#');
sb.append(cell.isBarrierRight() || x == width - 1 ? '|' : ' ');
}
sb.append('\n');
// Bottom line
sb.append('+');
for (int x = 0; x < width; ++x) {
Cell cell = getCell(x, y);
sb.append(cell.isBarrierBottom() || y == height - 1 ? '-' : ' ');
sb.append('+');
}
sb.append('\n');
}
return sb.toString();
} | 9 |
public boolean collectCourseInfo() {
courseInfo.clear();
for (int i = 0; i < typeInfo.size(); i++) {
int rowPoint = 0;
while (true) {
String line = "";
for (int j = 0; j < 5; j++) {
String cell = null;
if (couTable[i].getValueAt(rowPoint, j) == null
|| couTable[i].getValueAt(rowPoint, j).equals("")) {
if (rowPoint == 0) {
cell = "null";
line += cell + ";";
} else {
line = null;
}
} else {
cell = (String) couTable[i].getValueAt(rowPoint, j);
line += cell + ";";
}
}
if (line != null) {
System.out.println("Get Course Info:"
+ new String(typeInfo.get(i)) + line);
courseInfo.add(new String(typeInfo.get(i)) + line);
} else {
break;
}
rowPoint++;
}
}
return true;
} | 7 |
public void tick() {
if (inputDelay > 0)
inputDelay--;
else if (input.attack.clicked || input.menu.clicked) {
game.setMenu(new TitleMenu());
}
} | 3 |
@Override
public V put(K key, V value) {
V oldValue = null;
int index = Math.abs(key.hashCode()) % SIZE;
if(buckets[index] == null) {
buckets[index] = new LinkedList<MapEntry<K, V>>();
}
LinkedList<MapEntry<K, V>> bucket = buckets[index];
MapEntry<K, V> pair = new MapEntry<K, V>(key, value);
boolean found = false;
ListIterator<MapEntry<K, V>> it = bucket.listIterator();
int probes = 0;
while(it.hasNext()) {
MapEntry<K, V> iPair = it.next();
++probes;
if(iPair.getKey().equals(key)) {
System.out.println("Collision at " + iPair + ": " + probes +
" probe" + ((probes == 1) ? "" : "s") + " needed");
oldValue = iPair.getValue();
it.set(pair); // Replace old with new
found = true;
break;
}
}
if(!found) {
buckets[index].add(pair);
}
return oldValue;
} | 5 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final Item I=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_UNWORNONLY);
if(I==null)
return false;
if(((I.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_VEGETATION)
&&((I.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_WOODEN))
{
mob.tell(L("Your plant knowledge can tell you nothing about @x1.",I.name(mob)));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(!success)
mob.tell(L("Your plant senses fail you."));
else
{
final CMMsg msg=CMClass.getMsg(mob,I,null,CMMsg.MSG_DELICATE_SMALL_HANDS_ACT|CMMsg.MASK_MAGIC,null);
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
final StringBuffer str=new StringBuffer("");
str.append(L("@x1 is a kind of @x2. ",I.name(mob),RawMaterial.CODES.NAME(I.material()).toLowerCase()));
if(isPlant(I))
str.append(L("It was summoned by @x1.",I.rawSecretIdentity()));
else
str.append(L("It is either processed by hand, or grown wild."));
mob.tell(str.toString());
}
}
return success;
} | 7 |
public static LvalExpression addTempLocalVar(String name, Type type) {
LvalExpression lvalExp = vars.getVar(name);
if (lvalExp == null) {
Lvalue lvalue = new VarLvalue(new Variable(name, type), false);
vars.add(lvalue, false);
lvalExp = vars.getVar(name);
// add only the bit variables
Vector<Lvalue> derivedLvalues = lvalue.getDerivedLvalues();
for (int i = 0; i < derivedLvalues.size(); i++) {
lvalue = derivedLvalues.elementAt(i);
if (! (lvalue.hasDerives())) {
int lvalSize = lvalue.size();
// add bits only
for (int j = 0; j < lvalSize; j++) {
vars.add(new BitLvalue(lvalue, j), false);
}
}
}
}
return lvalExp;
} | 4 |
public static ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> resultLists = new ArrayList<ArrayList<Integer>>();
if (root == null) {
return resultLists;
}
Stack<TreeNode> currentLevel = new Stack<TreeNode>();
currentLevel.push(root);
while (!currentLevel.isEmpty()) {
Stack<TreeNode> nextLevel = new Stack<TreeNode>();
ArrayList<Integer> newList = new ArrayList<Integer>();
Stack<TreeNode> helperStack = new Stack<TreeNode>();
while(!currentLevel.isEmpty()){
TreeNode node = currentLevel.pop();
newList.add(node.val);
helperStack.add(node);
}
while(!helperStack.isEmpty()){
TreeNode node = helperStack.pop();
if(node.right != null) nextLevel.add(node.right);
if(node.left != null) nextLevel.add(node.left);
}
resultLists.add(newList);
currentLevel = nextLevel;
}
return resultLists;
} | 6 |
public ArrayList<RentTransaction> getAllRentTransaction(){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<RentTransaction> rentTransactionList = new ArrayList<RentTransaction>();
try {
Statement stmnt = conn.createStatement();
String sql = "SELECT * FROM RentTransactions";
ResultSet res = stmnt.executeQuery(sql);
while(res.next()) {
rentalList = RentalDAO.getRentalById(res.getInt("rent_trans_id"));
for (int i = 0; i < rentalList.size(); i++) {
if (rentalList.get(i).getType() == "boek"){
bookList.add(BookDAO.getBookCopyByBookCopyID(rentalList.get(i).getProductId()));
}
if (rentalList.get(i).getType() == "dvd" || rentalList.get(i).getType() == "cd"){
mediaList.add(MediaDAO.getMediaCopyByMediaCopyID(rentalList.get(i).getProductId()));
}
}
rentTransaction = new RentTransaction(res.getBoolean("closed"),bookList,mediaList,res.getInt("rent_trans_id"),res.getInt("member_id"),res.getString("date_out"),res.getString("date_in"),res.getString("staff_id"));
rentTransactionList.add(rentTransaction);
bookList = null;
mediaList = null;
rentalList = null;
}
}
catch(SQLException e) {
System.out.println("PROBLEM");
e.printStackTrace();
}
return rentTransactionList;
} | 9 |
private HashMap<String, Integer> NGramTiling(ArrayList<String> parsedSnippets) {
HashMap<String, Integer> term_Freq_Map = new HashMap<String, Integer>();
String split[] = null;
String complete = "";
//split into individual words
for(String list_item: parsedSnippets){
complete = complete + " " + list_item;
}
split = complete.split(" ");
if(split == null){
return null;
}
String key = "";
//uni-gram tiling and frequency
for(int i = 0; i < split.length; i++) {
key = split[i];
key = key.trim();
key = key.toLowerCase(Locale.ENGLISH);
if(!term_Freq_Map.containsKey(key)){
term_Freq_Map.put(key, 1);
}
else {
Integer freq = term_Freq_Map.get(key);
freq = freq + 1;
term_Freq_Map.put(key, freq);
}
}
//bi-gram tiling and frequency
for( int i = 0 ; i < split.length - 1; i++){
key = split[i] + " " + split[i+1];
key = key.trim();
key = key.toLowerCase(Locale.ENGLISH);
if(!term_Freq_Map.containsKey(key)){
term_Freq_Map.put(key, 1);
}
else {
Integer freq = term_Freq_Map.get(key);
freq = freq + 1;
term_Freq_Map.put(key, freq);
}
}
//tri-gram tiling and frequency
for( int i = 0 ; i < split.length - 2; i++){
key = split[i] + " " + split[i+1] + " " + split[i+2];
key = key.trim();
key = key.toLowerCase(Locale.ENGLISH);
if(!term_Freq_Map.containsKey(key)){
term_Freq_Map.put(key, 1);
}
else {
Integer freq = term_Freq_Map.get(key);
freq = freq + 1;
term_Freq_Map.put(key, freq);
}
}
return term_Freq_Map;
} | 8 |
public double square() throws TypeOverflowException {
double p = perimeter();
p /= 2;
double s = p;
try {
Iterator<Line> it = lineIterator();
while(it.hasNext()) {
s *= p - it.next().distance();
}
} catch (OverflowException e) {
throw new TypeOverflowException();
}
if (Double.isInfinite(s) || Double.isNaN(s))
throw new TypeOverflowException();
return Math.sqrt(s);
} | 4 |
public CommandHandler getCommandHandler() {
return commands;
} | 0 |
public static void main(String[] args) {
// TODO code application logic here
long NOK = 2;
for (int i = 3; i < 21; i++) {
NOK = Evclid(NOK, i);
}
System.out.println(NOK);
} | 1 |
@Override
public String toString() {
return "LABEL " + label;
} | 0 |
public int popAt(int i) {
if (stacks.size() == 0)
return Integer.MIN_VALUE;
if (stacks.get(i).isEmpty()) {
stacks.remove(i);
current--;
return Integer.MAX_VALUE;
}
int elem = stacks.get(i).pop();
if (stacks.get(i).isEmpty()) {
stacks.remove(i);
current--;
}
return elem;
} | 3 |
public void setCHST(int nr, boolean value) {
switch(nr){
case(1):
if (value)
CHST1.setBackground(Color.red);
else
CHST1.setBackground(Color.green);
break;
case(2):
if (value)
CHST2.setBackground(Color.red);
else
CHST2.setBackground(Color.green);
break;
case(3):
if (value)
CHST3.setBackground(Color.red);
else
CHST3.setBackground(Color.green);
break;
}
} | 6 |
@Id
@Column(name = "name")
public String getName() {
return name;
} | 0 |
@Override
public Clip getSoundClip(ActionResult actionResult) {
if (moveClip == null) {
moveClip = openClip(WavPlayer.SOUND_MOVE);
}
if (treasureClip == null) {
treasureClip = openClip(WavPlayer.SOUND_TREASURE);
}
if (winClip == null) {
winClip = openClip(WavPlayer.SOUND_WIN);
}
if (treeClip == null) {
treeClip = openClip(WavPlayer.SOUND_TREE);
}
switch (actionResult) {
case MOVE: {
return moveClip;
}
case HIDE_IN_TREE: {
return treeClip;
}
case COLLECT_TREASURE: {
return treasureClip;
}
case DIE: {
return super.getDieClip();
}
case WIN: {
return winClip;
}
}
return null;
} | 9 |
private void checkStatementMap() throws DataException {
for (final Map.Entry<Statement, Statement> statementEntry: statementMap.entrySet()) {
final Statement parameterStatement = statementEntry.getKey();
final Statement statement = statementEntry.getValue();
final Matcher matcher = expressionFactory.createMatcher();
// check hypotheses
final List<Expression> parameterHypotheses = parameterStatement.getHypotheses();
final List<Expression> hypotheses = statement.getHypotheses();
final int size = hypotheses.size();
if (parameterHypotheses.size() != size) {
logger.error("Statement " + statement + " has wrong number of hypotheses");
logger.debug("Expected number of hypotheses: " + parameterHypotheses.size());
logger.debug("Actual number of hypotheses: " + size);
throw new DataException("Statement has wrong number of hypotheses");
}
try {
for (int i = 0; i != size; ++i)
if (!matcher.checkVEquality(translator.translate(parameterHypotheses.get(i)),
hypotheses.get(i))) {
logger.error("Hypothesis in " + statement + " does not match");
logger.debug("Expected hypothesis: "
+ translator.translate(parameterHypotheses.get(i)));
logger.debug("Actual hypothesis: " + hypotheses.get(i));
logger.debug("Current assignment map: " + matcher.getAssignmentMap());
throw new DataException("Hypothesis does not match");
}
// check consequent
if (!matcher.checkVEquality(translator.translate(parameterStatement.getConsequent()),
statement.getConsequent())) {
logger.error("Consequent of " + statement + " does not match");
logger.debug("Expected consequent: "
+ translator.translate(parameterStatement.getConsequent()));
logger.debug("Actual consequent: " + statement.getConsequent());
logger.debug("Current assignment map: " + matcher.getAssignmentMap());
throw new DataException("Consequent does not match");
}
// check DV constraints
final Map<Variable, Variable> assignmentMap = matcher.getAssignmentMap();
final DVConstraints dvConstraints = dataFactory.createDVConstraints();
for (final Variable[] constraint: parameterStatement.getDVConstraints()) {
assert (constraint.length == 2): "Invalid constraint length";
dvConstraints.add(assignmentMap.get(translator.translate(constraint[0])),
assignmentMap.get(translator.translate(constraint[1])));
}
if (!dvConstraints.contains(statement.getDVConstraints())) {
logger.error("Statement " + statement + " has more DV constraints than "
+ parameterStatement);
throw new DataException("Statement has too many DV constraints");
}
} catch (ExpressionException e) {
logger.error("Unable to translate statement " + parameterStatement, e);
throw new DataException("Unable to translate statement", e);
} catch (NullPointerException e) {
throw new AssertionError("Unrestricted DV constraints");
}
}
} | 9 |
private void contactServer(InetAddress server, Transition transition) {
Socket socket = null;
try {
socket = new Socket(server, Statics.INTER_SERVER_COM_PORT);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
Map<String, Object> datagramContent = new HashMap<String, Object>();
datagramContent.put(Statics.CONTENT_TRANSITION, transition);
try {
out.writeObject(new Datagram(Statics.DATA, datagramContent));
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
Thread.sleep(500);
// TODO currently we don't care what's coming back
Object readObject = in.readObject();
System.out.println("[ISC] <received: " + readObject);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if(socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | 6 |
protected void notifyReceivedHandlers(Message message, IMessageReceivedHandler caller)
{
if (receivedHandlers.size() > 0)
for(IMessageReceivedHandler imrh: receivedHandlers)
if (imrh != caller){
try{
imrh.onMessageReceived(message);
}
catch(Exception e){
}
}
} | 4 |
@Override
public String getToolTipText(MouseEvent e)
{
String tip = getSelectionCellsHandler().getToolTipText(e);
if (tip == null)
{
Object cell = getCellAt(e.getX(), e.getY());
if (cell != null)
{
if (hitFoldingIcon(cell, e.getX(), e.getY()))
{
tip = mxResources.get("collapse-expand");
}
else
{
tip = graph.getToolTipForCell(cell);
}
}
}
if (tip != null && tip.length() > 0)
{
return tip;
}
return super.getToolTipText(e);
} | 5 |
private static void growSeedAdd(Cluster cluster,
Map<String, ArrayList<String>> adjList, Set<String> seedsToProcess) {
List<String> borderMembList = ClusterServices.getBordMemb(adjList,
cluster);
Queue<String> nodesToTryBorder = new LinkedList<>();
nodesToTryBorder.addAll(borderMembList);
while (!nodesToTryBorder.isEmpty()) {
String currBorderNode = nodesToTryBorder.poll();
if (currBorderNode == null) {
break;
}
List<String> outNodes = NodeService.getBordChildren(cluster,
adjList.get(currBorderNode));
Queue<String> bordNodeOutChildren = new LinkedList<>();
bordNodeOutChildren.addAll(outNodes);
while (!bordNodeOutChildren.isEmpty()) {
String nodeToAdd = bordNodeOutChildren.poll();
if (currBorderNode == null) {
break;
}
/**
* Add vertex and recompute entropy if decreased keep vertex
*/
cluster.addMember(nodeToAdd);
borderMembList = ClusterServices.getBordMemb(adjList, cluster);
Double entropy = computeEntropyGraph(cluster, adjList,
borderMembList);
if (entropy < cluster.getEntropy()) {
cluster.setEntropy(entropy); // update cluster entropy
/**
* Add another border node When adding new vertex to the
* cluster, check if it is already a seed first.
*/
if (seedsToProcess.contains(nodeToAdd)) {
/**
* Remove the seed for the current compute cluster from
* the seeds to process, so that other clusters can grow
* into this cluster.
*/
seedsToProcess.remove(cluster.seed);
/**
* Clear the cluster, so that it members could be seed
* candidates for the next iteration.
*/
cluster.getAllMembers().clear();
/**
* Terminate cluster computation for this seed.
*/
return;
}
nodesToTryBorder.offer(nodeToAdd);
} else {
cluster.getAllMembers().remove(nodeToAdd);
}
}
}
} | 6 |
public void remove(int i, int j) throws BadLocationException {
int k = getSelectionStart();
if (k > 0)
k--;
String s = getMatch(getText(0, k));
if (!isStrict && s == null) {
super.remove(i, j);
} else {
super.remove(0, getLength());
super.insertString(0, s, null);
}
try {
setSelectionStart(k);
setSelectionEnd(getLength());
} catch (Exception exception) {
}
} | 4 |
private void showMatchingBodyparts(UpgradeType type){
this.bodypartPanel.removeAll();
ArrayList<BodyPart> bodyparts = this.game.getUpgradeManager().getBodypartsByType(type);
for(BodyPart b : bodyparts){
BodypartIconPanel bpip = new BodypartIconPanel(b);
bpip.addMouseListener(this);
if(b.isUsed()){
this.activeBodypartIconPanel = bpip;
showMatchingUpgrades(b.getType());
}
bodypartPanel.add(bpip);
}
this.bodypartPanel.paintAll(bodypartPanel.getGraphics());
} | 2 |
public static final void populateConfigData (AnalyticsConfigData data) {
data.setEncoding(System.getProperty("file.encoding"));
String region = System.getProperty("user.region");
if (region == null) {
region = System.getProperty("user.country");
}
data.setUserLanguage(System.getProperty("user.language") + "-" + region);
try {
int screenHeight = 0;
int screenWidth = 0;
GraphicsEnvironment ge;
GraphicsDevice[] gs;
ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
gs = ge.getScreenDevices();
for (GraphicsDevice g : gs) {
DisplayMode dm = g.getDisplayMode();
screenWidth += dm.getWidth();
screenHeight += dm.getHeight();
}
if (screenHeight != 0 && screenWidth != 0) {
data.setScreenResolution(screenWidth + "x" + screenHeight);
}
if (gs[0] != null) {
String colorDepth = gs[0].getDisplayMode().getBitDepth() + "";
for (int i = 1; i < gs.length; i++) {
colorDepth += ", " + gs[i].getDisplayMode().getBitDepth();
}
data.setColorDepth(colorDepth);
}
} catch (HeadlessException e) {
data.setScreenResolution("NA");
data.setColorDepth("NA");
}
} | 7 |
public void validate(Property terminologyProperty) {
if (this.type != null && !this.type.isEmpty()) {
if (!this.type.equalsIgnoreCase(terminologyProperty.getType())) {
logger.warn("Value type (" + this.type
+ ") does not match the one given in the terminology("
+ terminologyProperty.getType()
+ ")! To guarantee interoperability please ckeck. However, kept provided type.");
}
} else {
try {
checkDatatype(this.content, terminologyProperty.getType());
this.setType(terminologyProperty.getType());
logger.info("Added type information to value.");
} catch (Exception e) {
logger
.warn("Value is not compatible with the type information the terminology suggests ("
+ terminologyProperty.getType()
+ "). Did not change anything, but please check");
}
}
if (this.unit != null && !this.unit.isEmpty()) {
if (!this.unit.equalsIgnoreCase(terminologyProperty.getUnit(0))) {
logger.warn("Value unit (" + this.unit
+ ") does not match the one given in the terminology("
+ terminologyProperty.getUnit()
+ ")! To guarantee interoperability please ckeck. However, kept provided unit.");
}
} else {
if (terminologyProperty.getUnit() != null && !terminologyProperty.getUnit(0).isEmpty()) {
this.setUnit(terminologyProperty.getUnit(0));
logger.info("Added unit " + terminologyProperty.getUnit() + " information to value.");
}
}
} | 9 |
private void toggleRemoveSelection(TreePath path){
Stack<TreePath> stack = new Stack<TreePath>();
TreePath parent = path.getParentPath();
while(parent!=null && !isPathSelected(parent)){
stack.push(parent);
parent = parent.getParentPath();
}
if(parent!=null)
stack.push(parent);
else{
_removeSelectionPath(path);
return;
}
while(!stack.isEmpty()){
TreePath temp = (TreePath)stack.pop();
TreePath peekPath = stack.isEmpty() ? path : (TreePath)stack.peek();
Object node = temp.getLastPathComponent();
Object peekNode = peekPath.getLastPathComponent();
int childCount = model.getChildCount(node);
for(int i = 0; i<childCount; i++){
Object childNode = model.getChild(node, i);
if(childNode!=peekNode)
super.addSelectionPaths(new TreePath[]{temp.pathByAddingChild(childNode)});
}
}
super.removeSelectionPaths(new TreePath[]{parent});
} | 7 |
public void setCam(int xCam, int yCam)
{
xCam /= distance;
yCam /= distance;
int xCamD = this.xCam - xCam;
int yCamD = this.yCam - yCam;
this.xCam = xCam;
this.yCam = yCam;
g.setComposite(AlphaComposite.Src);
g.copyArea(0, 0, width, height, xCamD, yCamD);
if (xCamD < 0)
{
if (xCamD < -width) xCamD = -width;
updateArea(width + xCamD, 0, -xCamD, height);
}
else if (xCamD > 0)
{
if (xCamD > width) xCamD = width;
updateArea(0, 0, xCamD, height);
}
if (yCamD < 0)
{
if (yCamD < -width) yCamD = -width;
updateArea(0, height + yCamD, width, -yCamD);
}
else if (yCamD > 0)
{
if (yCamD > width) yCamD = width;
updateArea(0, 0, width, yCamD);
}
} | 8 |
@Override
public GameState[] allActions(GameState state, Card card, int time) {
GameState[] states = new GameState[1];
states[0] = state;
if(time == Time.DAY)
{
//Do nothing
}
else if(time == Time.DUSK)
{
PickTreasure temp = new PickTreasure();
states = temp.allActions(state, card, time);
}
else if(time == Time.NIGHT)
{
states = waitressNightChoices(state, card);
}
return states;
} | 3 |
private void volgendeOnderdeel() throws IOException {
spel.volgendeOnderdeel();
huidigeOnderdeel = spel.getHuidigeOnderdeel();
if (huidigeOnderdeel != null) {
middenvlak.removeAll();
ImagePanel plaatje = new ImagePanel(huidigeOnderdeel.getPlaatje());
plaatje.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
plaatje.setAutoResize(true);
middenvlak.add(plaatje);
}
middenvlak.revalidate();
middenvlak.repaint();
} | 1 |
public WeaponList() {
setTitle("Weapon List");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setBounds(100, 100, 325, 500);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new BorderLayout(0, 0));
{
JScrollPane scrollPane = new JScrollPane();
contentPanel.add(scrollPane, BorderLayout.CENTER);
{
list = new JList<String>();
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() == 2 && !e.isConsumed()) {
makeSelection();
}
}
});
list.setModel(buildList());
scrollPane.setViewportView(list);
}
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
makeSelection();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
setModalityType(ModalityType.APPLICATION_MODAL);
setVisible(true);
} | 2 |
public synchronized DataInputStream getChunkDataInputStream(int var1, int var2) {
if(this.outOfBounds(var1, var2)) {
this.debugln("READ", var1, var2, "out of bounds");
return null;
} else {
try {
int var3 = this.getOffset(var1, var2);
if(var3 == 0) {
return null;
} else {
int var4 = var3 >> 8;
int var5 = var3 & 255;
if(var4 + var5 > this.sectorFree.size()) {
this.debugln("READ", var1, var2, "invalid sector");
return null;
} else {
this.dataFile.seek((long)(var4 * 4096));
int var6 = this.dataFile.readInt();
if(var6 > 4096 * var5) {
this.debugln("READ", var1, var2, "invalid length: " + var6 + " > 4096 * " + var5);
return null;
} else {
byte var7 = this.dataFile.readByte();
byte[] var8;
DataInputStream var9;
if(var7 == 1) {
var8 = new byte[var6 - 1];
this.dataFile.read(var8);
var9 = new DataInputStream(new GZIPInputStream(new ByteArrayInputStream(var8)));
return var9;
} else if(var7 == 2) {
var8 = new byte[var6 - 1];
this.dataFile.read(var8);
var9 = new DataInputStream(new InflaterInputStream(new ByteArrayInputStream(var8)));
return var9;
} else {
this.debugln("READ", var1, var2, "unknown version " + var7);
return null;
}
}
}
}
} catch (IOException var10) {
this.debugln("READ", var1, var2, "exception");
return null;
}
}
} | 7 |
public ArrayList<String> getBannedAltAccounts( String player ) throws SQLException {
ArrayList<String> accounts = getAltAccounts( player );
boolean check = false;
for ( String p : getAltAccounts( player ) ) {
if ( isPlayerBanned( p ) ) {
check = true;
String newPlayer = ChatColor.DARK_RED + "[Banned] " + p;
p = newPlayer;
}
}
if ( check ) {
return accounts;
} else {
return null;
}
} | 3 |
private boolean noMoreTableCards() {
/*
* Stage 8 (6 Marks)
*/
// TODO: i suck at this game, so no chance to test if this methos works
// or not. maybe some other day
for (int i = 0; i < cards.length; i++)
for (int j = 0; j < cards[i].length; j++)
if (cards[i][j] != null && !cards[i][j].getHasBeenRemoved())
return false;
return true;
} | 4 |
private void fillInTaskOnAssetList(Asset asset) {
listOfTasks.clear();
listTasksList.repaint();
ResultSet tasksOnAssetListResultSet = null;
Statement statement;
try {
statement = connection.createStatement();
tasksOnAssetListResultSet = statement.executeQuery("SELECT * FROM Task WHERE assetID = " + asset.getAssetID() + ";");
randSQL.loadAllUsers();
SetOfUsers allusers = randSQL.getAllUsers();
while (tasksOnAssetListResultSet.next()){
int taskID;
int projectID;
User responsible = null;
int taskPriority;
String status;
String taskName;
String taskType;
taskID = tasksOnAssetListResultSet.getInt("taskID");
projectID = tasksOnAssetListResultSet.getInt("projectID");
for(int i=0; i<allusers.size();i++){
if(tasksOnAssetListResultSet.getInt("responsiblePerson")==allusers.get(i).getUserID());
{
responsible = allusers.get(i);
break;
}
}
taskPriority = tasksOnAssetListResultSet.getInt("taskPriority");
status = tasksOnAssetListResultSet.getString("status");
taskName = tasksOnAssetListResultSet.getString("taskName");
taskType = tasksOnAssetListResultSet.getString("type");
Task newTask = new Task(taskID, responsible,taskName, taskPriority , status,projectID, asset, taskType);
listOfTasks.add(newTask);
listTasksList.setListData(listOfTasks);
TasksListCellRenderer renderer = new TasksListCellRenderer(); //custom cell renderer to display property rather than useless object.toString()
listTasksList.setCellRenderer(renderer);
}
asset.setSetOfTasks(listOfTasks);
} catch (SQLException ex) {
Logger.getLogger(ManagerUI.class.getName()).log(Level.SEVERE, null, ex);
}
} | 4 |
public void checkSign(String file, String encrypted_file) throws Exception {
RandomAccessFile PGP_file = new RandomAccessFile(encrypted_file, "r");
int len = -1;
byte[] arr = new byte[2];
while ((len = PGP_file.read(arr)) != -1 && (arr[0] & 0xff) != SP_TAG) {
//System.out.println("checkSign: skip packet for SP");
PGP_file.seek(arr[1] & 0xff);
}
if (len > 0) {
PGP_file.seek(PGP_file.getFilePointer() - 2);
SP sp = new SP(PGP_file);
//byte[] sign = sp.signature.MPI_string;
byte[] sign = (RSA.RSAoperation(Utilities.getHexString(sp.signature.MPI_string),
pub_exp, mod));
if (sign[0] == (byte) 0x01) {
int padding = 1;
for (; sign[padding] != (byte) 0x00; padding++) ;
byte[] hash = new byte[sign.length - padding - 16];
System.arraycopy(sign, padding + 16, hash, 0, hash.length);
System.out.println("Decrypted Hash:: " + Utilities.getHexString(hash));
System.out.println("Hash of decrypted file:: " + Utilities.getHexString(sp.getHash(file)));
} else
System.out.println("Wrong padding");
} else
System.out.println("checkSign: can't find SP packet");
PGP_file.close();
} | 5 |
public boolean isClicked() {
return !wasDown && isDown;
} | 1 |
public int sincronizaTodo(){
try {
// logger.info(" ======== ITEM ACTUALIZADO =========================== ");
System.out.println(" =============== CLIENTES ========================================== ");
logger.info(" ======================================================= ");
sincronizaClientes();
System.out.println(" =============== ARTICULOS ========================================= ");
sincronizaArticulos();
System.out.println(" =============== VENTAS ============================================ ");
sincronizaVentas();
System.out.println(" =============== SOLICITUDES ======================================= ");
solicitudes();
return 1;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
} | 1 |
private String getBinaryFromCell(int row, int column)
{
String binary = "";
int newValue;
for (int r = -1; r < 2; r++) {
for (int c = -1; c < 2; c++) {
newValue = cellsValue[row + r][column + c] < 0 ? 1 : 0;
binary = binary + newValue;
}
}
return binary;
} | 3 |
@Override
public boolean match(PathInput input) {
if (input.end()) {
return isOptional();
} else {
if (input.isBind()) {
bind(input, input.value());
}
input.next();
return true;
}
} | 2 |
public VertexSet getVertexSetNeighbourhood(VertexSet S){
VertexSet vertexSetNeighbourhood = new VertexSet();
VertexSet vertexSetTemp = null;
Iterator<City> cityIterator = S.iterator();
while (cityIterator.hasNext()){
vertexSetTemp = getNeighbourhood(cityIterator.next());
Iterator<City> vertexSetTempIterator = vertexSetTemp.iterator();
while (vertexSetTempIterator.hasNext()){
City nextCity = vertexSetTempIterator.next();
if (!vertexSetNeighbourhood.containsID(nextCity.getID()))
vertexSetNeighbourhood.addVertex(nextCity);
}
}
// added by johannes (remove elements from S)
for(City c : S){
if(vertexSetNeighbourhood.containsID(c.getID())){
vertexSetNeighbourhood.removeID(c.getID());
}
}
return vertexSetNeighbourhood;
} | 5 |
protected Element invokeWriteToXML(Element parent, Object o, String name) throws Exception {
Method method;
Class[] methodClasses;
Object[] methodArgs;
boolean array;
Element node;
boolean useDefault;
node = null;
method = null;
useDefault = false;
m_CurrentNode = parent;
// default, if null
if (o == null)
useDefault = true;
try {
if (!useDefault) {
array = o.getClass().isArray();
// display name?
if (m_CustomMethods.write().contains(name))
method = (Method) m_CustomMethods.write().get(o.getClass());
else
// class?
if ( (!array) && (m_CustomMethods.write().contains(o.getClass())) )
method = (Method) m_CustomMethods.write().get(o.getClass());
else
method = null;
useDefault = (method == null);
}
// custom
if (!useDefault) {
methodClasses = new Class[3];
methodClasses[0] = Element.class;
methodClasses[1] = Object.class;
methodClasses[2] = String.class;
methodArgs = new Object[3];
methodArgs[0] = parent;
methodArgs[1] = o;
methodArgs[2] = name;
node = (Element) method.invoke(this, methodArgs);
}
// standard
else {
node = writeToXML(parent, o, name);
}
}
catch (Exception e) {
if (DEBUG)
e.printStackTrace();
if (m_CurrentNode != null) {
System.out.println("Happened near: " + getPath(m_CurrentNode));
// print it only once!
m_CurrentNode = null;
}
System.out.println("PROBLEM (write): " + name);
throw (Exception) e.fillInStackTrace();
}
return node;
} | 9 |
public void checkCollisions(){
// loop all pickables
for (Iterator<Pickable> iterator = meds.iterator(); iterator.hasNext(); ) {
Pickable p = iterator.next();
if(Character.getBounds().intersects(p.getBounds())){ // pickup med
Sounds.pickPill.play();
iterator.remove();
timer = 10000;
alpha = 0;
}
}
} | 2 |
public Entity getEntityAt(int dir, int x, int y) {
for(Entity e : entities) {
if(e.x == x && e.y == y && ((e instanceof NPC) || (e instanceof Door))) return e;
}
for(Entity e : entities) {
if(e.x == x && e.y == y && !(e instanceof Player)) return e;
}
return null;
} | 9 |
public U1A7_PowersView(SingleFrameApplication app) {
super(app);
initComponents();
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
} | 7 |
@Override
public void paintComponent(Graphics g) {
if (point != null) {
if (tool == Tool.COLORWHEEL && colorWheel != null) {
if (icon) {
g.drawImage(colorWheel, point.x - 10, point.y - 10, 20, 20, null);
} else {
g.drawImage(colorWheel, point.x - 100, point.y - 100, 200, 200, null);
}
} else if (tool == Tool.ERASER) {
g.drawImage(eraser, point.x - 15, point.y - 15, 30, 30, null);
} else if (tool == Tool.PAINTBUCKET) {
g.drawImage(bucket, point.x - 15, point.y - 15, 30, 30, null);
} else {
g.setColor(cursorColor);
if (fullCursor) {
g.fillOval(point.x - 10, point.y - 10, 20, 20);
} else {
g.drawOval(point.x - 10, point.y - 10, 20, 20);
}
}
}
g.setColor(cursorColor);
g.fillRect(26, 567, 30, 30);
} | 7 |
public void pastCrowl2(){
DatastoreService datastore = DatastoreServiceFactory
.getDatastoreService();
Entity past_string = null;
try {
Key key = KeyFactory.createKey("past_string", "onlyOne");
past_string = datastore.get(key);
} catch (Throwable t) {
}
past_string.setProperty("text",new Text(new Past().getPastString()));
try{
//if(false)
datastore.put(past_string);
}catch(Throwable t){}
Queue queue = QueueFactory.getDefaultQueue();
queue.add(Builder.withUrl("/back").param("op","pastCrowl2").method(Method.POST).countdownMillis(60000*60));
queue.add(Builder.withUrl("/ranking").param("c","this").method(Method.GET).countdownMillis(60000*50));
queue.add(Builder.withUrl("/pair").param("c","this").method(Method.GET).countdownMillis(60000*40));
} | 2 |
static int kmpSearch(String pat, String text) {
int n = text.length();
int m = pat.length();
int[] trans = new int[m + 1]; // オートマトンの遷移テーブルを作る
trans[0] = -1;
for (int i = 2; i <= m; i++) {
char c = pat.charAt(i - 1);
int fall = trans[i - 1];
while (fall != -1 && c != pat.charAt(fall))
fall = trans[fall]; // 次の位置が見つかるまで戻る
trans[i] = fall + 1;
}
int st = 0; // 現在のステート
int count = 0;
for (int i = 0; i < n; i++) {
// オートマトンの文字と一致するまで戻り続ける
while (st >= 0 && text.charAt(i) != pat.charAt(st))
st = trans[st];
if (++st >= m) { // 受理状態
// ここで何か処理する
count++;
st = trans[st];
}
}
return count;
} | 7 |
public static void runServer() throws IOException {
ServerSocket chatServer = null;
try {
System.out.println("Waiting for clients on port: "
+ local_port);
chatServer = new ServerSocket(local_port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + local_port);
System.err.println(e);
}
Socket client = null;
try {
int x = 0;
for (x = 0; x < 8; x++) {
client = chatServer.accept();
new clientThread(client, chatServer).start();
System.out.println("Peer connection Estahblished");
}
} catch (IOException e) {
}
try {
chatServer.setSoTimeout(20000);
} catch (SocketException se) {
}
} | 4 |
public void close() {
boolean isUnderlyingConnectionClosed;
try {
isUnderlyingConnectionClosed = !conn.isConnected();
} catch (Exception e) {
try {
pool.invalidateObject(this); // XXX should be guarded to happen at most once
} catch (IllegalStateException ise) {
// pool is closed, so close the connection
conn.close();
} catch (Exception ie) {
// DO NOTHING the original exception will be rethrown
}
throw new RedisException("Cannot close connection (isClosed check failed)");
}
if (!isUnderlyingConnectionClosed) {
// Normal close: underlying connection is still open, so we
// simply need to return this proxy to the pool
try {
pool.returnObject(this); // XXX should be guarded to happen at most once
} catch (IllegalStateException e) {
// pool is closed, so close the connection
conn.close();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RedisException("Cannot close connection (return to pool failed)", e);
}
} else {
// Abnormal close: underlying connection closed unexpectedly, so we
// must destroy this proxy
try {
pool.invalidateObject(this); // XXX should be guarded to happen at most once
} catch (IllegalStateException e) {
// pool is closed, so close the connection
conn.close();
} catch (Exception ie) {
// DO NOTHING, "Already closed" exception thrown below
}
throw new RedisException("Already closed.");
}
} | 9 |
public void SortPlayerPoints() {
Collections.sort(playerVector, (Player p1, Player p2) -> {
if (p1.getPosition().getPosID() == Position.PosID.GOALIE) {
if (p2.getPosition().getPosID() == Position.PosID.GOALIE) {
int shots = p1.getAssists() + p1.getGoals();
float perc1 = (shots == 0 ? 0 : (100 - (float) 100
/ shots * p1.getGoals()));
shots = p2.getAssists() + p2.getGoals();
float perc2 = (shots == 0 ? 0 : (100 - (float) 100
/ shots * p2.getGoals()));
if (perc1 > perc2) {
return -1;
} else if (perc2 > perc1) {
return 1;
}
return 0;
} else {
return -1;
}
} else if (p2.getPosition().getPosID() == Position.PosID.GOALIE) {
return 1;
} else {
return p2.getAssists() + p2.getGoals() - p1.getAssists()
- p1.getGoals();
}
}
);
} | 7 |
public void actionPerformed(ActionEvent arg0)
{
if(arg0.getSource() == cancel)
{
setVisible(false);
clear();
}
else if(arg0.getSource() == save)
{
if(parent == util.quest.sp)
{
if(loaded == null)
{
util.quest.slist.getSelectedValue().addAction(create());
util.quest.sp.delete.setEnabled(true);
}
else edit();
util.quest.sp.loadData(util.quest.slist.getSelectedValue());
setVisible(false);
clear();
}
else if(parent == util.quest.op.rewards)
{
if(loaded == null)
{
util.quest.op.rwcp.addAction(create());
util.quest.op.rewards.delete.setEnabled(true);
}
else edit();
util.quest.op.rewards.loadData(util.quest.op.rewards.loaded);
setVisible(false);
clear();
}
util.markFileChanged();
}
} | 6 |
protected boolean setTerrain(int cellId, TerrainTypes terrain) {
if ((cellId >= 0) && (cellId < countCells())) {
if (this.terrain[cellId] != terrain) {
this.terrain[cellId] = terrain;
return true;
}
}
return false;
} | 3 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.