text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public String toString() {
String str = "";
switch (align) {
case TOP: str = ",align=top"; break;
case CENTER: str = ",align=center"; break;
case BOTTOM: str = ",align=bottom"; break;
case LEADING: str = ",align=leading"; break;
case TRAILING: str = ",align=trailing"; break;
}
return getClass().getName() + "[hgap=" + hgap + ",vgap=" + vgap + str + "]";
} | 5 |
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String currentTime = df.format(new Date());
try {
Date d1 = df.parse("2014-04-11 09:26");
Date d2 = df.parse(currentTime);
long l=24*60*60*1000-(d2.getTime()-d1.getTime());
System.out.println(l);
long hour = l/(60*60*1000);
String timeLeft = "";
if (hour < 10) {
timeLeft += "0" + hour;
} else {
timeLeft += hour;
}
long minuts = (l/(60*1000))-hour*60;
if (minuts < 10) {
timeLeft += ":0" + minuts;
} else {
timeLeft += ":" + minuts;
}
System.out.println(timeLeft);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 3 |
private void setState() {
if (bittorrent != null) {
type = Type.TORRENT;
} else {
type = Type.HTTP;
}
if (type.equals(Type.TORRENT)) {
if (bittorrent.info.get("name") != null) {
name = bittorrent.info.get("name");
} else {
name = bittorrent.comment;
}
} else {
//TODO: Find another way of naming downloads
if ((files != null) && (!files.isEmpty())) {
name = files.get(0).path.replaceFirst(Pattern.quote(dir) + "/", "");
//Logger.getInstance().info("File name is: "+ name);
}
}
} | 5 |
public LinkedHandlerBuilder ifMatches( final Filter filter )
{
if ( filter == null )
{
throw new IllegalArgumentException( "Filter must not be null" );
}
return new LinkedHandlerBuilder()
{
public void handleWith( final ClassPathEntryHandler... entryHandlers )
{
if ( entryHandlers == null || entryHandlers.length == 0 )
{
throw new IllegalArgumentException( "At least one ClassPathEntryHandler must be specified" );
}
MatcherImpl.this.handlers.add( new ClassPathHandler( filter, entryHandlers ) );
}
};
} | 3 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Delivery)) {
return false;
}
Delivery other = (Delivery) object;
if ((this.deliveryPK == null && other.deliveryPK != null) || (this.deliveryPK != null && !this.deliveryPK.equals(other.deliveryPK))) {
return false;
}
return true;
} | 5 |
@Override
public void setDefaultActions() {
this.addAction(new ActionInitial("look") {
@Override
public Result execute(Actor actor) {
this.incrementCount();
// no limit on how many times this can be executed
return new ResultGeneric(true, ItemGeneric.this.look());
}
}
);
this.addAction(new ActionInitial("read") {
@Override
public Result execute(Actor actor) {
// alias to "look"
return ItemGeneric.this.getInitialAction("look").execute(actor);
}
}
);
this.addAction(new ActionInitial("get") {
@Override
public Result execute(Actor actor) {
// no limit on how many times this can be executed
if (actor instanceof Player) {
try {
((Player) actor).pickUp(ItemGeneric.this);
this.incrementCount();
return new ResultGeneric(true, "OK, you got the "+ItemGeneric.this.getName());
} catch (ActionException e) {
return new ResultGeneric(false, e.getMessage());
}
} else {
return new ResultGeneric(false, "You can't pick up an item!");
}
}
});
this.addAction(new ActionInitial("drop") {
@Override
public Result execute(Actor actor) {
// no limit on how many times this can be executed
if (actor instanceof Player) {
try {
((Player) actor).drop(ItemGeneric.this);
this.incrementCount();
return new ResultGeneric(true, "The "+ItemGeneric.this.getName()+" is on the "+((Player) actor).getLocation().getName()+" floor");
} catch (ActionException e) {
return new ResultGeneric(false, e.getMessage());
}
} else {
return new ResultGeneric(false, "You can't drop an item!");
}
}
});
this.addAction("throw", this.getAction("drop")); // "throw" = alias for "drop"
this.addAction(new ActionInitial("hit") {
@Override
public Result execute(Actor actor) {
if (actor instanceof Player) {
if (((Player) actor).getLocation().hasOne(ItemGeneric.this)) {
// default for hitting something is that nothing happens
return new ResultGeneric(false, "Nothing happened");
} else {
if (ItemGeneric.this.getName() != null) {
return new ResultGeneric(false, "I don't see any "+ItemGeneric.this.getName());
} else {
return new ResultGeneric(false, "I don't see one of those");
}
}
} else {
return new ResultGeneric(false, "You can't hit an item!");
}
}
});
} | 7 |
public DataFrame<MultiClassLabel> processInput(Iterable<String> input, boolean train) throws IOException {
int readNFirstRows = train? readFirstNTrainRows : readFirstNTestRows;
int row = 0;
OffHeapSparseMatrix words = new OffHeapSparseMatrix(readNFirstRows>0?readNFirstRows:6000000, 100000);
// SparseMatrix words = new SparseMatrix();
Predictors<MultiClassLabel> predictors = new Predictors<MultiClassLabel>();
for(String line : input) {
if (readNFirstRows >0 && row > readNFirstRows) break;
if (row % 1000 == 0) {
getContext().getProgressReporter().reportProgress("DataProcessor", row);
}
String[] spl = SPLIT_PATTERN.split(line);
TIntSet classes = new TIntHashSet();
boolean initialized = false;
for(int i=0; i<spl.length; i++) {
if (spl[i].contains(":")){
if (!initialized){
words.init(row, spl.length-i);
initialized = true;
}
int idx = spl[i].indexOf(':');
words.set(row, Integer.parseInt(spl[i].substring(0, idx)), Integer.parseInt(spl[i].substring(idx + 1)));
} else {
classes.add(Integer.parseInt(spl[i]));
}
}
predictors.add(new MultiClassLabel(classes.toArray()));
row++;
}
return new DataFrame<MultiClassLabel>(predictors, words);
} | 9 |
public boolean hasTwoSamePlayerRoads(int activePlayer) {
int player = -1;
for (Road r: roadNeighbours) {
if (r.isBuilt()) {
if (r.getPlayer() != activePlayer) {
if (player == -1) {
player = r.getPlayer();
} else {
if (player == r.getPlayer()) return true;
}
}
}
}
return false;
} | 5 |
static ROM Generate ()
{
final int length = 2;
final int width = 69;
final int height = 3;
final int currentLife = 15;
Block temp;
ROM template = new ROM (height, width, length); //This is tileable 60 times in X. Indexed YZX
temp = new Air (); //Filling in space.
for (int Y = 0; Y < height; Y++)
{
for (int Z = 0; Z < width; Z++)
{
template.block [Y] [Z] [0] = temp; //Fill in air between wires.
}
}
for (int Z = 0; Z < width; Z++)
{
template.block [height-1] [Z] [1] = temp; //Fill in air above the wire.
}
//Start building the stone / wool bar bits and wire sit on.
template.block [0] [0] [1] = new Stone (); //Stone blocks sit in between wool sections.
template.block [0] [0] [0] = new CTorch ('N'); //All stone barriers have lights on them.
BuildBar (template, new Wool('W'), 1, 8); //condition selector is white.
BuildBar (template, new Wool('p'), 9, 20); //Save address is pink.
BuildBar (template, new Wool('L'), 21, 32); //Load address is green.
BuildBar (template, new Wool('N'), 33, 44); //ALU GPU command is black.
BuildBar (template, new Wool('R'), 45, 56); //if0 address is red.
BuildBar (template, new Wool('l'), 57, 68); //If>0 address is lime green.
//Place wire on bar.
temp = new Wire ((byte)15);
for (int Z = 0; Z < width; Z++)
{
template.block [1] [Z] [1] = temp;
}
//Place repeaters as needed.
temp = new Repeater('S');
for (int Z = 11; Z < width; Z += currentLife)
{
template.block [1] [Z] [1] = temp;
}
//return structure; //This is normal mode. Returns a full RedGame 2 program ROM.
return template; //Debug version. Returns one bar, representing one command.
} | 5 |
public List<Task> merge(List<Task> left, List<Task> right) {
if (left.isEmpty()) {
return right;
} else {
if (right.isEmpty()) {
return left;
} else {
int contFirstArray = 0;
int contSecondArray = 0;
List<Task> arrayToReturn = new ArrayList<Task>();
int total = left.size() + right.size();
for (int i = 0; i < total; i++) {
if (contFirstArray == left.size()) {
for (int j = i; j < total; j++) {
arrayToReturn.add(right.get(contSecondArray));
contSecondArray++;
}
return arrayToReturn;
} else {
if (contSecondArray == right.size()) {
for (int j = i; j < total; j++) {
arrayToReturn.add(left.get(contFirstArray));
contFirstArray++;
}
return arrayToReturn;
} else {
if (isLeft(left, right, contFirstArray,
contSecondArray)) {
arrayToReturn.add(left.get(contFirstArray));
contFirstArray++;
} else {
arrayToReturn.add(right.get(contSecondArray));
contSecondArray++;
}
}
}
}
return arrayToReturn;
}
}
} | 8 |
public void remove(Comparable rowKey, Comparable columnKey) {
// defer null argument checks
int r = getRowIndex(rowKey);
int c = getColumnIndex(columnKey);
this.data.removeObject(rowKey, columnKey);
// if this cell held a maximum and/or minimum value, we'll need to
// update the cached bounds...
if ((r == this.maximumRangeValueRow && c
== this.maximumRangeValueColumn) || (r
== this.maximumRangeValueIncStdDevRow && c
== this.maximumRangeValueIncStdDevColumn) || (r
== this.minimumRangeValueRow && c
== this.minimumRangeValueColumn) || (r
== this.minimumRangeValueIncStdDevRow && c
== this.minimumRangeValueIncStdDevColumn)) {
// iterate over all data items and update mins and maxes
updateBounds();
}
fireDatasetChanged();
} | 8 |
protected Object invokeMethod(String methodName, Object[] args, Class<?>[] argsType)
throws UnknownHostException, IOException, RemoteException440, Exception {
InvokeMessage message = new InvokeMessage(ror, methodName, args, argsType);
String inetAddr = ror.getIP();
int port = ror.getPort();
Socket clientToServer = null;
try {
clientToServer = new Socket(inetAddr, port);
} catch (IOException e) {
throw new ServerException440("Cannot connect to remote object");
}
/* Send method invocation message to proxy dispatcher */
ObjectOutputStream objectOut = new ObjectOutputStream(clientToServer.getOutputStream());
/* Check and replace exported remote object with its stub */
RMIParamCheck.paramSendCheck(message.getArgs());
try{
objectOut.writeObject(message);
} catch (IOException e) { //an error accessing the socket
throw new ServerException440("An error occurred while sending remote message");
}
/* read return message from proxy dispatcher */
ObjectInputStream objectIn = new ObjectInputStream(clientToServer.getInputStream());
RetMessage retMessage = null;
try {
retMessage = (RetMessage) objectIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
throw new ServerException440("An error occurred on server side");
}
objectOut.close();
objectIn.close();
clientToServer.close();
/* both checked and unchecked exception in RMI are thrown here */
if (retMessage.getCode() == MessageCode.EXCEPTION) {
Exception e = ((RetMessage)retMessage).getException();
throw e;
}
return retMessage.getRet();
} | 6 |
public static void stackSort (Stack<Integer> s) {
Stack<Integer> helper = new Stack<>();
// follow the rountine of bubble sort,
// smaller elements go down and bigger elements go up
int size = s.size();
for (int i=0 ; i != size-1; ++i ) {
Integer min = s.pop();
for (int j = size-i-1; j >0 ; j-- ) {
Integer cur = s.pop();
if ( cur > min ) {
helper.push( cur );
} else {
Integer tmp = cur;
cur = min;
min = tmp;
helper.push( cur );
}
}
s.push( min );
// pop all elements from helper stack and
// push them back into s
while ( !helper.isEmpty() ) {
s.push ( helper.pop() );
}
}
} | 4 |
@Override
public void handle(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
//Get the correct DynmapServer
for (DynmapServer dynmapServer : Main.getDynmapServers()) {
AbstractFile file = dynmapServer.getFile(request.getUri());
if (file.exists()) {
if (file.isHidden() || !file.exists()) {
HandlerUtil.sendError(ctx, NOT_FOUND);
return;
}
if (!file.isFile()) {
HandlerUtil.sendError(ctx, FORBIDDEN);
return;
}
// Cache Validation
String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(HandlerUtil.HTTP_DATE_FORMAT, Locale.US);
Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
// Only compare up to the second because the datetime format we send to the client
// does not have milliseconds
long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
long fileLastModifiedSeconds = file.lastModified() / 1000;
if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
HandlerUtil.sendNotModified(ctx);
return;
}
}
ReadableByteChannel channel = Channels.newChannel(file.getInputStream());
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
HandlerUtil.setContentTypeHeader(response, file.getName());
HandlerUtil.setDateAndCacheHeaders(response, file.lastModified());
response.headers().set(CONTENT_LENGTH, file.length());
response.headers().set(CONNECTION, HttpHeaders.Values.CLOSE);
response.headers().set(VARY, ACCEPT_ENCODING);
// Write the initial line and the header.
ctx.write(response);
// Write the content.
ctx.write(new ChunkedStream(file.getInputStream()));
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
return;
}
}
HandlerUtil.sendError(ctx, NOT_FOUND);
} | 8 |
public void run()
{
try
{
GuiConnecting.setNetClientHandler(this.connectingGui, new NetClientHandler(this.mc, this.ip, this.port));
if (GuiConnecting.isCancelled(this.connectingGui))
{
return;
}
GuiConnecting.getNetClientHandler(this.connectingGui).addToSendQueue(new Packet2Handshake(this.mc.session.username, this.ip, this.port));
}
catch (UnknownHostException var2)
{
if (GuiConnecting.isCancelled(this.connectingGui))
{
return;
}
this.mc.displayGuiScreen(new GuiDisconnected("connect.failed", "disconnect.genericReason", new Object[] {"Unknown host \'" + this.ip + "\'"}));
}
catch (ConnectException var3)
{
if (GuiConnecting.isCancelled(this.connectingGui))
{
return;
}
this.mc.displayGuiScreen(new GuiDisconnected("connect.failed", "disconnect.genericReason", new Object[] {var3.getMessage()}));
}
catch (Exception var4)
{
if (GuiConnecting.isCancelled(this.connectingGui))
{
return;
}
var4.printStackTrace();
this.mc.displayGuiScreen(new GuiDisconnected("connect.failed", "disconnect.genericReason", new Object[] {var4.toString()}));
}
} | 7 |
public boolean isConnected(){
try {
if (xmlRpcClient!=null){
xmlRpcClient.execute("LookUpTableHandler.getVersion", new Vector());
return true;
} else {
return false;
}
} catch (XmlRpcException e){
return false;
}
} | 2 |
public boolean blockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer)
{
if (par1World.isRemote)
{
return true;
}
else
{
ItemStack var6 = par5EntityPlayer.inventory.getCurrentItem();
if (var6 == null)
{
return true;
}
else
{
int var7 = par1World.getBlockMetadata(par2, par3, par4);
if (var6.itemID == Item.bucketWater.shiftedIndex)
{
if (var7 < 3)
{
if (!par5EntityPlayer.capabilities.isCreativeMode)
{
par5EntityPlayer.inventory.setInventorySlotContents(par5EntityPlayer.inventory.currentItem, new ItemStack(Item.bucketEmpty));
}
par1World.setBlockMetadataWithNotify(par2, par3, par4, 3);
}
return true;
}
else
{
if (var6.itemID == Item.glassBottle.shiftedIndex && var7 > 0)
{
ItemStack var8 = new ItemStack(Item.potion, 1, 0);
if (!par5EntityPlayer.inventory.addItemStackToInventory(var8))
{
par1World.spawnEntityInWorld(new EntityItem(par1World, (double)par2 + 0.5D, (double)par3 + 1.5D, (double)par4 + 0.5D, var8));
}
--var6.stackSize;
if (var6.stackSize <= 0)
{
par5EntityPlayer.inventory.setInventorySlotContents(par5EntityPlayer.inventory.currentItem, (ItemStack)null);
}
par1World.setBlockMetadataWithNotify(par2, par3, par4, var7 - 1);
}
return true;
}
}
}
} | 9 |
public Map<PersonalInfo, String> getAllUserInfo() {
if(info != null) {
return info;
} else {
try {
String query = "SELECT COUNT(*) FROM datingsite.UserData WHERE UserID = ?";
ResultSet rs = executeQueryWithParams(query, userID);
rs.next();
int count = rs.getInt(1);
if(count < 1) {
query = "INSERT INTO datingsite.UserData (UserID) VALUES (?)";
executeQueryWithParamsWithoutResults(query, userID);
}
} catch(SQLException e) {
e.printStackTrace();
}
try {
String query = "SELECT * FROM datingsite.UserData WHERE UserID = ?;";
ResultSet rs = executeQueryWithParams(query, userID);
rs.next();
Map<PersonalInfo, String> info = new HashMap<PersonalInfo, String>();
for(PersonalInfo pi : PersonalInfo.values()) {
String columnName = pi.getVarName();
String data = rs.getString(columnName);
if(pi == PersonalInfo.Gender) data = (data.equals("1") ? "Female" : "Male");
info.put(pi, data);
}
return info;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
} | 7 |
public void delete(String whereString){
StringBuffer sql = new StringBuffer("");
sql.append("Delete from `Section`");
if (whereString.trim() != "") {
sql.append(" where " + whereString);
}
SQLHelper sQLHelper = new SQLHelper();
sQLHelper.sqlConnect();
sQLHelper.runUpdate(sql.toString());
sQLHelper.sqlClose();
} | 1 |
public static ErrorLogs DAOController(Generator generator,
TransactionSet transactionSet, RuleSet ruleSet) {
System.out.println("Starting DAO Controller");
ErrorLogs errorLogs = new ErrorLogs();
VendorPersistenceController vpc = new VendorPersistenceController();
TransactionPersistenceController tpc = new TransactionPersistenceController();
RulePersistenceController rpc = new RulePersistenceController();
TransactionSetPersistenceController tspc = new TransactionSetPersistenceController();
RuleSetPersistenceController rspc = new RuleSetPersistenceController();
GeneratorPersistenceController gpc = new GeneratorPersistenceController();
int errorCount = 0;
String daoString = "MySQL";
gpc.setDAO(daoString);
vpc.setDAO(daoString);
tspc.setDAO(daoString);
tpc.setDAO(daoString);
rspc.setDAO(daoString);
rpc.setDAO(daoString);
//System.out.println("Starting Persist Vendor");
for (int i = 0; i < transactionSet.getVendorSet().size(); i++) {
Vendor vendor = transactionSet.getVendorSet().get(i);
vpc.persistVendor(vendor);
System.out
.println("vendor " + i + " is " + vendor.getVendor_name());
}
int vpc_errors = vpc.getErrorLogs().getErrorMsgs().size();
//System.out.println("Finished Persist Vendor");
errorCount += vpc_errors;
if (errorCount != 0) {
errorLogs.add("DATABASE ERROR: VENDOR TABLE");
errorLogs.add(vpc.getErrorLogs());
System.out.println("size: " + errorLogs.getErrorMsgs().size());
return errorLogs;
}
// iterate through tranactionset to get individual transactions
//int i = 0;
//System.out.println("Starting Persist TransactionSet");
tspc.persistTransactionSet(transactionSet);
int tspc_errors = tspc.getErrorLogs().getErrorMsgs().size();
errorCount += tspc_errors;
//System.out.println("Finished Persist TransactionSet");
if (errorCount != 0) {
errorLogs.add("DATABASE ERROR: TRANSACTIONSET TABLE");
errorLogs.add(tspc.getErrorLogs());
//System.out.println("size: " + errorLogs.getErrorMsgs().size());
return errorLogs;
}
//System.out.println("errorCount: " + errorCount);
//tpc.connect();
int i =0;
int size = transactionSet.getTransactionSet().size();
for (Transaction transaction : transactionSet.getTransactionSet()) {
System.out.println("Size: "
+ transactionSet.getTransactionSet().size());
// for(int i = 0; i < transactionSet.getTransactionSet().size();
// i++){
//System.out.println("Starting Persist Transaction: #" + i);
// tpc.persistTransaction(transactionSet.getTransactionSet().get(i));
tpc.persistTransaction(transaction, i, size);
i++;
//System.out.println("Finished Persist Transaction: #" + i);
}
System.out.println("Finished Persisting Transactions");
int tpc_errors = tpc.getErrorLogs().getErrorMsgs().size();
errorCount += tpc_errors;
//System.out.println("errorCount: " + errorCount);
if (errorCount != 0) {
//errorLogs.add("DATABASE ERROR: TRANSACTION TABLE");
errorLogs.add(tpc.getErrorLogs());
//System.out.println("size: " + errorLogs.getErrorMsgs().size());
return errorLogs;
}
//tpc.disconnect();
System.out.println("Starting Persist Generator");
gpc.persistGenerator(generator.getGenerator_minSupportLevel(),
generator.getGenerator_minConfidenceLevel());
//System.out.println("Finished Persist Generator");
int gpc_errors = gpc.getErrorLogs().getErrorMsgs().size();
errorCount += gpc_errors;
if (errorCount != 0) {
errorLogs.add("DATABASE ERROR: GENERATOR TABLE");
errorLogs.add(gpc.getErrorLogs());
return errorLogs;
}
// }
int j = 0;
// iterate through ruleset to get individual rules
System.out.println("Starting Persist RuleSet");
rspc.persistRuleSet(ruleSet);
int rspc_errors = rspc.getErrorLogs().getErrorMsgs().size();
errorCount += rspc_errors;
System.out.println("errorCount: " + errorCount);
if (errorCount != 0) {
errorLogs.add("DATABASE ERROR: RULESET TABLE");
errorLogs.add(rspc.getErrorLogs());
System.out.println("size: " + errorLogs.getErrorMsgs().size());
return errorLogs;
}
System.out.println("Finished Persist RuleSet");
for (Rule rule : ruleSet.getRuleSet()) {
System.out.println("Starting Persist Rule: #" + j);
rpc.persistRule(rule);
System.out.println("Finished Persist Rule: #" + j);
}
int rpc_errors = rpc.getErrorLogs().getErrorMsgs().size();
errorCount += rpc_errors;
System.out.println("errorCount: " + errorCount);
if (errorCount != 0) {
errorLogs.add("DATABASE ERROR: RULE TABLE");
errorLogs.add(rpc.getErrorLogs());
System.out.println("size: " + errorLogs.getErrorMsgs().size());
return errorLogs;
}
System.out.println("Final errorCount: " + errorCount);
System.out.println("Finished DAO Controller");
System.out.println("size: " + errorLogs.getErrorMsgs().size());
return errorLogs;
} | 9 |
private static Rectangle determineCropRect(BufferedImage image)
{
// Loop through all the pixels, ignoring transparent ones.
Rectangle rect = null;
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
int color = image.getRGB(x, y);
if (color != TRANSPARENT && (color & 0xFF000000) != 0) {
if (rect == null) {
rect = new Rectangle(x, y, 0, 0);
} else {
rect.add(x, y);
}
}
}
}
return rect;
} | 5 |
private static void addToSpanMap(int span, TreeMap<Integer, ArrayList<FlexGridData>> map, FlexGridData data) {
if (span > 1) {
Integer key = new Integer(span);
ArrayList<FlexGridData> set = map.get(key);
if (set == null) {
set = new ArrayList<>();
map.put(key, set);
}
set.add(data);
}
} | 2 |
public Behaviour jobFor(Actor actor) {
if ((! structure.intact()) || (! personnel.onShift(actor))) return null ;
I.sayAbout(actor, "GETTING NEXT EXCAVATION TASK") ;
final Delivery d = Deliveries.nextDeliveryFor(
actor, this, services(), 5, world
) ;
if (d != null) return d ;
final Choice choice = new Choice(actor) ;
for (Smelter s : smelters) {
choice.add(new OreProcessing(actor, s, s.output)) ;
}
if (structure.upgradeLevel(ARTIFACT_ASSEMBLY) > 0) {
choice.add(new OreProcessing(actor, this, ARTIFACTS)) ;
}
final Target face = Mining.nextMineFace(this, underFaces) ;
if (face != null) {
choice.add(new Mining(actor, face, this)) ;
}
return choice.weightedPick() ;
} | 6 |
final protected synchronized void setup() throws SQLException {
Statement st = null;
try {
st = conn.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS `ffa_leaderboards` ("
+ "`player_id` int(11) NOT NULL AUTO_INCREMENT,"
+ "`player_name` varchar(255) NOT NULL,"
+ "`killcount` int(11) DEFAULT '0',"
+ "`killstreak` int(11) DEFAULT '0',"
+ "`times_played` int(11) DEFAULT '0',"
+ "`deaths` int(11) DEFAULT '0',"
+ "PRIMARY KEY (`player_id`),"
+ "UNIQUE KEY `Name` (`player_name`) USING BTREE"
+ ") ENGINE=InnoDB DEFAULT CHARSET=latin1;");
} finally {
if (st != null) {
try {
st.close();
} catch (SQLException ex) {
}
}
}
} | 2 |
private void foundFullHouse() {
rank = Rank.FULLHOUSE;
Card.Rank tripRank = null;
// Find the biggest trips
for (int i = ranks.length - 1; i >= 0; i--) {
Card[] value = ranks[i];
if (value == null) continue;
if (numRanks[i] == 3) {
tripRank = RANKS[i];
break;
}
}
// Remove this trip and find the biggest match for the house
final int tripOrd = tripRank.ordinal();
for (int j = 0; j < numRanks[tripOrd]; j++)
fiveCardHand.add(ranks[tripOrd][j]);
ranks[tripOrd] = null;
Card.Rank pairRank = null;
// Find the next biggest pair
for (int i = ranks.length - 1; i >= 0; i--) {
Card[] value = ranks[i];
if (value == null) continue;
if (numRanks[i] >= 2) {
pairRank = RANKS[i];
break;
}
}
Card[] pairCards = ranks[pairRank.ordinal()];
// Just add the first two cards from the match
for (int i = 0; i < 2; i++) {
fiveCardHand.add(pairCards[i]);
}
} | 8 |
public String convert(Pos p){
switch (p) {
case EARTH:
return ".";
case ROBOT:
return "R";
case LIFT_O:
return "O";
case LIFT_C:
return "C";
case WALL:
return "#";
case DIAMOND:
return "x";
case EMPTY:
return " ";
case ROCK:
return "*";
default:
break;
}
return "?";
} | 8 |
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
// Evaluate the arguments
AttributeValue [] argValues = new AttributeValue[inputs.size()];
EvaluationResult result = evalArgs(inputs, context, argValues);
if (result != null)
return result;
// Now that we have real values, perform the divide operation
// in the manner appropriate for the type of the arguments.
switch (getFunctionId()) {
case ID_INTEGER_DIVIDE: {
long dividend = ((IntegerAttribute) argValues[0]).getValue();
long divisor = ((IntegerAttribute) argValues[1]).getValue();
if (divisor == 0) {
result = makeProcessingError("divide by zero");
break;
}
long quotient = dividend / divisor;
result = new EvaluationResult(new IntegerAttribute(quotient));
break;
}
case ID_DOUBLE_DIVIDE: {
double dividend = ((DoubleAttribute) argValues[0]).getValue();
double divisor = ((DoubleAttribute) argValues[1]).getValue();
if (divisor == 0) {
result = makeProcessingError("divide by zero");
break;
}
double quotient = dividend / divisor;
result = new EvaluationResult(new DoubleAttribute(quotient));
break;
}
}
return result;
} | 5 |
@Override
public void validate() {
if("".equals(username)) //Empty username
this.addFieldError("username", "Username required");
else { //Username is good
if("".equals(account)) //Empty account
this.addFieldError("account", "You Must Input A Account");
else{ //Account is not empty
if(service.findUserByAccount(account) != null) //Already Existed Account
this.addFieldError("account", "This Account Has Been Used,Please Change Another One");
else { //Account is good
if("".equals(password)) //Empty password
this.addFieldError("password", "Please Input Password!");
else { //Password is good
if(password.length() < 6 || password.length() > 20) //Bad length
this.addFieldError("password", "The Length Of Password Is Not Allowed!");
else { //Length is good
if("".equals(password_cfm)) //No confirm password
this.addFieldError("password_cfm", "Please Confirm Your Password");
else if(!password_cfm.equals(password)) //Password Confirm Failed
this.addFieldError("password_cfm", "Reconfirm Your Password");
}
}
}
}
}
} | 8 |
@Override
public boolean isWebDriverType(String type)
{
return StringUtils.equalsIgnoreCase("chrome", type);
} | 0 |
public void setVue(VueConnexion vue) {
this.vue = vue;
} | 0 |
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == addEmp){
for (int i = 0; i < 6; i++){
int n = 0;
int x = 0;
int y = 0;
if (i == 0){
n = 5;
x = 0;
y = 2;
newTextField = new JTextField(n);
g.anchor = GridBagConstraints.LINE_START;
g.gridx = x;
g.gridy = y;
empAssignP.add(newTextField, g);
} else if (i == 1){
n = 10;
x = 1;
y = 2;
newTextField = new JTextField(n);
g.anchor = GridBagConstraints.LINE_START;
g.gridx = x;
g.gridy = y;
empAssignP.add(newTextField, g);
} else if (i == 2){
n = 10;
x = 2;
y = 2;
newTextField = new JTextField(n);
g.anchor = GridBagConstraints.LINE_START;
g.gridx = x;
g.gridy = y;
empAssignP.add(newTextField, g);
} else if (i == 3){
n = 3;
x = 3;
y = 2;
newTextField = new JTextField(n);
g.anchor = GridBagConstraints.CENTER;
g.gridx = x;
g.gridy = y;
empAssignP.add(newTextField, g);
} else if (i == 4){
n = 3;
x = 4;
y = 2;
newTextField = new JTextField(n);
g.anchor = GridBagConstraints.CENTER;
g.gridx = x;
g.gridy = y;
empAssignP.add(newTextField, g);
} else if (i == 5){
n = 8;
x = 5;
y = 2;
newTextField = new JTextField(n);
g.anchor = GridBagConstraints.LINE_START;
g.gridx = x;
g.gridy = y;
empAssignP.add(newTextField, g);
addEmp2 = new JButton("+");
addEmp2.setBackground(Color.GREEN);
g.anchor = GridBagConstraints.LINE_START;
g.gridx = 6;
g.gridy = 2;
empAssignP.add(addEmp2, g);
delEmp = new JButton("-");
delEmp.setBackground(Color.RED);
g.anchor = GridBagConstraints.LINE_START;
g.gridx = 7;
g.gridy = 2;
empAssignP.add(delEmp, g);
}
empAssignP.revalidate();
}
}
} | 8 |
@Override
public boolean tick() {
if (input.pressed(KeyEvent.VK_LEFT))
pos.x -= speed;
if (input.pressed(KeyEvent.VK_RIGHT))
pos.x += speed;
if (input.pressed(KeyEvent.VK_UP))
pos.y -= speed;
if (input.pressed(KeyEvent.VK_DOWN))
pos.y += speed;
return isAlive();
} | 4 |
private String msgchk(String chk, String msg) throws InterruptedException, FileNotFoundException, UnsupportedEncodingException{
String broken[];
if (chk.endsWith(ghosts)){
ghost=1;
}
if (chk.endsWith(nonstop)){
if (cnt == 0){
dataOut.print("n\b");
dataOut.flush();
}
cnt++;
}
if (chk.endsWith("Room error")){
return "Room error";
}
if (msg.endsWith("just entered the Realm.")){
broken=msg.split(" ");
for (int i=0;i<broken.length;i++ ) {
if (broken[i].equals("just")){
player=broken[i-1];
}
}
GosLink2.gb.enter(player.trim(),mynum);
}
if (chk.endsWith(hangup)){
GosLink2.dw.append("BBS shutdown detected!");
loggedin=0;
return "!OffLINE+02";
}
return null;
} | 8 |
public List children(final Node node) {
final ArrayList c = new ArrayList();
if (node instanceof StoreExpr) {
final StoreExpr store = (StoreExpr) node;
// Add the grand children of RHS. The RHS is equivalent to
// this node.
store.expr().visitChildren(new TreeVisitor() {
public void visitNode(final Node node) {
c.add(node);
}
});
// The LHS is equivalent to this node if it is a VarExpr and not
// a child.
if (!(store.target() instanceof VarExpr)) {
c.add(store.target());
}
} else if (node instanceof PhiStmt) {
final PhiStmt phi = (PhiStmt) node;
c.addAll(phi.operands());
} else {
node.visitChildren(new TreeVisitor() {
public void visitNode(final Node node) {
c.add(node);
}
});
}
return c;
} | 3 |
public static String deleteWhitespace(CharSequence str) {
StringBuilder sb = new StringBuilder(str.length());
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (i > 0 && Character.isWhitespace(c) && Character.isWhitespace(str.charAt(i-1))) continue;
if (c == '\r' || c == '\n') {
sb.append(' ');
continue;
}
sb.append(c);
}
return sb.toString();
} | 6 |
public static ArrayList<Kill> getKillMails(int charID) {
InputSource data;
ArrayList<Kill> downloaded = new ArrayList<Kill>();
ArrayList<Kill> totalBoard = new ArrayList<Kill>();
data = Download.getFromHTTPS(formURL(charID, 1));
downloaded = XMLParser.Killboard(data);
totalBoard.addAll(downloaded);
int currentPage = 1;
while (downloaded.size() >= 200 && totalBoard.size() < 3000) {
currentPage++;
data = Download.getFromHTTPS(formURL(charID, currentPage));
downloaded = XMLParser.Killboard(data);
totalBoard.addAll(downloaded);
System.out.println(totalBoard.size()
+ " is the current number of downloaded kills.");
}
return totalBoard;
} | 2 |
public boolean hasBust() {
return getScore() > BLACKJACK;
} | 0 |
public static void DoTurn(SimulatedPlanetWars simpw) {
//Retrieve environment characteristics
//Are there characteristics you want to use instead, or are there more you'd like to use? Try it out!
// int neutralPlanets = pw.NeutralPlanets().size();
// int totalPlanetSize = 0;
// for (Planet p : pw.NeutralPlanets()) {
// totalPlanetSize += p.GrowthRate();
// }
// int averagePlanetSize = Math.round(totalPlanetSize/pw.NeutralPlanets().size());
int planets = simpw.MyPlanets().size() - simpw.EnemyPlanets().size(); // myPlanets - EnemyPlanets => positive mean that I have more planets than the enemy
int ships = Helper.shipsValue(simpw); // myShips - enemyShips
int growth = Helper.growthValue(simpw); // myGrowth - enemyGrowth
int fleet = Helper.fleetValue(simpw); // The maximum fleet able to be send minus the average fleet on each planet.
int planetsL = 0; // L is for learn (to modify the if depending on victories or defeats)
int shipsL = 0;
int growthL = 0;
int fleetL = 0;
try { // Try to read values from the file
BufferedReader reader = new BufferedReader(new FileReader("learn.txt"));
String line = null;
line = reader.readLine();
planetsL = Integer.valueOf(line);
line = reader.readLine();
shipsL = Integer.valueOf(line);
line = reader.readLine();
growthL = Integer.valueOf(line);
line = reader.readLine();
fleetL = Integer.valueOf(line);
}
catch (Exception e){
// File must not exist or being inconsistent so we create it
try {
PrintWriter writer = new PrintWriter("learn.txt", "UTF-8");
writer.println(0);
writer.println(0);
writer.println(0);
writer.println(0);
writer.close();
}
catch (Exception ee){
System.out.println(ee);
}
// Finally throw an exception :
System.out.println(e);
}
// Tree selection :
if (Helper.testRand(planets,planetsL)) {
// Learn values are at 0 by default, but can be changed when stored
// Here if planets < planetsL (= 0 if nothing learned yet)
// In case of equal the value is choosen randomly
if (Helper.testRand(ships,shipsL))
defend(simpw);
else
attack(simpw,1); // 1 is for "planet attack"
}
else {
if (Helper.testRand(growth,growthL)){
if (Helper.testRand(fleet,fleetL))
defend(simpw);
else
attack(simpw,0); // 0 is for "GR attack"
}
else {
if (Helper.testRand(ships,shipsL)){
if (Helper.testRand(fleet,fleetL))
defend(simpw);
else
attack(simpw,2); // 2 is for destroying the ennemy ships to prevent him to conquer any of our planets
}
else
attack(simpw,3); // 3 is for an attack that makes an overall winning (Dcalculation + distance)
}
}
} | 8 |
private void cli(){
Scanner input = new Scanner(System.in);
ArrayList<String> commands = new ArrayList<String>(Arrays.asList("route","view_best_path","show_network","help","reload_network","modify_link"));
while (true){
System.out.println("\navailable commands: route, view_best_path, show_network, help reload_network modify_link \n");
String inputLine = input.nextLine();
int index = 0;
for(int i=0;i<commands.size();i++){
if (inputLine.contains(commands.get(i))){
index = i;
break;
}
}
switch (index){
case 0 : computeRoutingTablesParser(inputLine); break;
case 1 : viewBestPathParser(inputLine); break;
case 2 : showNetwork(); break;
case 3 : System.out.println(help); break;
case 4 : new Network(topology); break;
case 5 : modifyLinkParser(inputLine);
}
}
} | 9 |
public List<Object> getX509IssuerSerialOrX509SKIOrX509SubjectName() {
if (x509IssuerSerialOrX509SKIOrX509SubjectName == null) {
x509IssuerSerialOrX509SKIOrX509SubjectName = new ArrayList<Object>();
}
return this.x509IssuerSerialOrX509SKIOrX509SubjectName;
} | 1 |
public void mutateScope(){
if(( bulb_bar && bulb_scope) || scope_bar)
{
j += di;
int t= j*DELAY1/(100*scope.getTimeScale()), volt= (int)(10*Math.sin((double)(j*DELAY1))/scope.getCh1Scale());
if (volt<= -((scope.getDispHeight()/2)- scope.getPlotSize())|| volt>=(scope.getDispHeight()/2)-scope.getPlotSize())
di=di * -1;
if (t<= -1*scope.getDispWidth() || t>=(scope.getDispWidth()))
j=0;
dispList = scope.getPointList();
dispList.add(new Point(t,volt));
}
else{
j+=di;
int t=j*DELAY1, volt= (int)(10*Math.sin((double)(j*DELAY1)));
volt= 0;
if (t<= -1*scope.getDispWidth() || t>=(scope.getDispWidth()))
j=0;
dispList =scope.getPointList();
dispList.add(new Point(t,volt));
}
} | 9 |
private void paintInternal(Graphics2D g) {
if (smoothPosition != null) {
{
Point position = getMapPosition();
Painter painter = new Painter(this, getZoom());
painter.paint(g, position, null);
}
Point position = new Point(smoothPosition.x, smoothPosition.y);
Painter painter = new Painter(this, getZoom() + smoothOffset);
painter.setScale(smoothScale);
float t = (float) (animation == null ? 1f : 1 - animation.getFactor());
painter.setTransparency(t);
painter.paint(g, position, smoothPivot);
if (animation != null && animation.getType() == AnimationType.ZOOM_IN) {
int cx = smoothPivot.x, cy = smoothPivot.y;
drawScaledRect(g, cx, cy, animation.getFactor(), 1 + animation.getFactor());
} else if (animation != null && animation.getType() == AnimationType.ZOOM_OUT) {
int cx = smoothPivot.x, cy = smoothPivot.y;
drawScaledRect(g, cx, cy, animation.getFactor(), 2 - animation.getFactor());
}
}
if (smoothPosition == null) {
Point position = getMapPosition();
Painter painter = new Painter(this, getZoom());
painter.paint(g, position, null);
}
/** DO NOT REMOVE THIS CASE
* Since width/height of the panel initially is 0 before its painted,
* it appears to have the size "0". What was thought to be the center,
* actually becomes the top left corner of the map. This case fixes that problem.
* Though one should care for the possibility of an eternity loop as the maps
* width and height are REALLY 0. This is also handled by checking if size is legit.
**/
if (centerPosition.equals(mapPosition) && legitMapSize()) {
setCenterPosition(centerPosition);
paintInternal(g); /* calls itself, DANGEROUS. Could end up in eternal loop if setCenterPosition is buggy. */
}
} | 9 |
@Override
public BayesNode getNode(BayesNode sourceBayesNode, Object[] parents) {
Object nodeType = sourceBayesNode.type;
ArrayList<Object> allItems = new ArrayList<Object>(Arrays.asList(parents));
allItems.add(0, parents);
// generate a truth table as per http://stackoverflow.com/a/10761325/2130838
int rows = (int) Math.pow(2, allItems.size());
for (int i=0; i<rows; i++) {
int balance=0;
boolean trueSeen = false;
ArrayList<Object> falseObjects = new ArrayList<Object>();
for (int j=allItems.size()-1; j>=0; j--) {
// as we traverse each generated row from the end of the row, we keep track of
// for the balance of TRUE-FALSE items.
// Also, for each FALSE item on the row, we add that to the list of false items
// on this row.
if (j > 0){
if((i/(int) Math.pow(2, j))%2 == 1){
balance++;
} else {
balance--;
falseObjects.add(allItems.get(j));
}
} else {
Fraction probability;
// once we get to the beginning of the row, we check whether
// this row codes for the node being TRUE or FALSE
if((i/(int) Math.pow(2, j))%2 == 1){
// if this row codes for the node being TRUE and the
// balance is positive, then we set the probability of
// this row to one. if the balance is negative we set
// the probability of this row to zero, and if the balance
// is even we set the probability to .5.
if (balance > 0){
probability = Fraction.ONE;
} else if (balance < 0){
probability = Fraction.ZERO;
} else{
probability = Fraction.ONE_HALF;
}
} else {
// Similarly, if this row codes for the node being FALSE,
// we do the reverse.
falseObjects.add(nodeType);
if (balance > 0){
probability = Fraction.ZERO;
} else if (balance < 0){
probability = Fraction.ONE;
} else{
probability = Fraction.ONE_HALF;
}
}
sourceBayesNode.setProbabilityOfUntrueVariables(probability, falseObjects.toArray());
}
}
}
String description = "<html>'" + sourceBayesNode.type + "' is a <b>conditional probability variable</b><br>of type <b>majority vote</b>.<p><p>It is true if the majority of its parents are true, <br>and false if the majority of its parents are false. <br>If an equal number of parents are true and false, <br>it has a 50% chance of being true.";
sourceBayesNode.cptDescription = description;
return sourceBayesNode;
} | 9 |
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=AdventureWorks;integratedSecurity=true;";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create initial sample data.
createSampleTables(con);
// The showGetters method demonstrates how to parse the data in the
// SQLXML object by using the SAX, ContentHandler and XMLReader.
showGetters(con);
// The showSetters method demonstrates how to set the xml column
// by using the SAX, ContentHandler, and ResultSet.
showSetters(con);
// The showTransformer method demonstrates how to get an XML data
// from one table and insert that XML data to another table
// by using the SAX and the Transformer.
showTransformer(con);
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
} | 7 |
private void checkThreeConsecLetters(String number){
int[] consecLetters = new int[8];
for(char c:number.toCharArray()){
consecLetters[getIndex(c)]++;
if(consecLetters[getIndex(c)]>3){
System.err.println("The syntax of the roman number is not valid: you can only have 3 maximum consecutive letters of " + c);
System.exit(2);
}
}
} | 2 |
public int newLocal(final Type type) {
Object t;
switch (type.getSort()) {
case Type.BOOLEAN:
case Type.CHAR:
case Type.BYTE:
case Type.SHORT:
case Type.INT:
t = Opcodes.INTEGER;
break;
case Type.FLOAT:
t = Opcodes.FLOAT;
break;
case Type.LONG:
t = Opcodes.LONG;
break;
case Type.DOUBLE:
t = Opcodes.DOUBLE;
break;
case Type.ARRAY:
t = type.getDescriptor();
break;
// case Type.OBJECT:
default:
t = type.getInternalName();
break;
}
int local = newLocalMapping(type);
setLocalType(local, type);
setFrameLocal(local, t);
return local;
} | 9 |
public void run() {
//// Preconditions
assert listeners != null : "listeners must not be null";
assert cycAccess != null : "cycAccess must not be null";
/*
try {
Thread.currentThread().sleep(Long.MAX_VALUE);
} catch (InterruptedException ie) {
} finally {
if (true) {
return;
}
}
*/
Thread.currentThread().setName("Cyc API services lease manager");
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
while (!cycAccess.isClosed()) {
// SubL side gets a lease request for twice the value of the lease duration
final String script = "(with-immediate-execution (acquire-api-services-lease " +
(getLeaseDurationMilliseconds() * 2) + " \"" +
cycAccess.getCycConnection().getUuid().toString() + "\"))";
final CycList scriptList = cycAccess.makeCycList(script);
String results = null;
isLeaseRequestPending = true;
logger.fine("Requesting API services lease");
try {
DefaultSubLWorkerSynch worker = new DefaultSubLWorkerSynch(scriptList, cycAccess,
CYC_API_SERVICES_LEASE_REQUEST_TIMEOUT_MILLIS);
worker.setShouldIgnoreInvalidLeases(true);
results = (String) worker.getWork();
logger.finest(results);
} catch (TimeOutException toe) {
isLeaseRequestPending = false;
logger.fine("Cyc communications timeout encountered when attempting " + "to renew the API services lease.\n" + toe.getMessage());
notifyListeners(CYC_DOES_NOT_RESPOND_TO_LEASE_REQUEST);
try {
Thread.sleep(getLeaseDurationMilliseconds());
} catch (InterruptedException ex) {
}
continue;
} catch (Exception e) {
isLeaseRequestPending = false;
logger.fine("Cyc communications error encountered when attempting " + "to renew the API services lease.\n" + e.getMessage());
notifyListeners(CYC_COMMUNICATION_ERROR);
try {
Thread.sleep(getLeaseDurationMilliseconds());
} catch (InterruptedException ex) {
}
continue;
}
//cycAccess.getCycConnection().traceOff();
isLeaseRequestPending = false;
if (results.equals("api services lease denied")) {
logger.severe("The request to renew the API services lease was denied by the Cyc server.");
notifyListeners(CYC_DENIES_THE_LEASE_REQUEST);
} else {
String currentImageID = extractImageID(results);
if (cycImageID != null && !cycImageID.equals(currentImageID)) {
logger.info("The Cyc server image ID has changed.");
notifyListeners(CYC_IMAGE_ID_HAS_CHANGED);
} else {
logger.fine("API services lease renewed");
notifyListeners(LEASE_SUCCESSFULLY_RENEWED);
}
cycImageID = currentImageID;
}
try {
Thread.sleep(getLeaseDurationMilliseconds());
} catch (InterruptedException e) {
}
}
} | 9 |
private boolean _equals(Complex value) {
if (Complex.isNaN(this) && Complex.isNaN(value))
return true;
if (Complex.isInfinite(this) && Complex.isInfinite(value))
return true;
return this._real == value._real && this._imaginary == value._imaginary;
} | 5 |
public static boolean esCorrecta(int d, int m, int a){
int diasDelMes[]={31,29,31,30,31,30,31,31,30,31,30,31};
if(a<=0) {
return false;
}
if(d<=0 || d>31) {
return false;
}
if(m<=0 || m>12) {
return false;
}
if(d>diasDelMes[m-1]) {
return false;
}
if(m==2 && d==29 && !esBisiesto(a)) {
return false;
}
return true;
} | 9 |
public static void setGrassCreationProbability(double GRASS_CREATION_PROBABILITY)
{
if (GRASS_CREATION_PROBABILITY >= 0)
Simulator.GRASS_CREATION_PROBABILITY = GRASS_CREATION_PROBABILITY;
} | 1 |
public boolean isSeen(int index) {
State s = data.get(index);
if (s == State.seen || s == State.caught) {
return true;
}
return false;
} | 2 |
public Path<DirectedGraphNode>
search(final DirectedGraphNode source,
final DirectedGraphNode target,
final WeightFunction<DirectedGraphNode> w) {
OPEN.clear();
GSCORE.clear();
PARENT.clear();
CLOSED.clear();
OPEN.add(source, 0.0);
GSCORE.put(source, 0.0);
PARENT.put(source, null);
final int TARGET_REGION_NUMBER = firstLevelRegionMap.get(target);
final int SUB_TARGET_REGION_NUMBER = secondLevelRegionMap
.get(TARGET_REGION_NUMBER)
.get(target);
while (OPEN.isEmpty() == false) {
final DirectedGraphNode current = OPEN.extractMinimum();
if (current.equals(target)) {
return PathFinder.
<DirectedGraphNode>constructPath(target, PARENT);
}
CLOSED.add(current);
final int FIRST_LEVEL_REGION_NUMBER =
firstLevelRegionMap.get(current);
final Set<DirectedGraphNode> currentRegion =
firstLevelRegions.get(FIRST_LEVEL_REGION_NUMBER);
for (final DirectedGraphNode child : current) {
if (CLOSED.contains(child)) {
continue;
}
if (!firstLevelArcFlags.get(current, child)
.get(TARGET_REGION_NUMBER)) {
continue;
}
if (currentRegion.contains(child)) {
if (!secondLevelArcFlags.get(FIRST_LEVEL_REGION_NUMBER)
.get(current, child)
.get(SUB_TARGET_REGION_NUMBER)) {
continue;
}
}
double tmpg = GSCORE.get(current) + w.get(current, child);
if (GSCORE.containsKey(child) == false) {
GSCORE.put(child, tmpg);
PARENT.put(child, current);
OPEN.add(child, tmpg);
} else if (GSCORE.get(child) > tmpg) {
GSCORE.put(child, tmpg);
PARENT.put(child, current);
OPEN.decreasePriority(child, tmpg);
}
}
}
return Path.NO_PATH;
} | 9 |
public TileMap(int width, int height) {
tiles = new Image[width][height];
sprites = new LinkedList();
} | 0 |
public UserModel modifyAccount(HttpServletRequest request, String userId) {
String pseudo = getFieldValue(request, FIELD_PSEUDO);
UserModel user = DataStore.getUser(userId);
boolean noError = true;
try {
pseudo = pseudo.replaceAll("\\W","");
checkPseudo(pseudo);
checkExistsPseudo(pseudo);
} catch(Exception e) {
noError = false;
setError(FIELD_PSEUDO, e.getMessage());
}
if(noError && user!=null) {
user.setUser_pseudo(pseudo);
DataStore.storeUser(user);
setResult("Modification réussite.");
}
else {
setResult("La modification a échoué.");
}
return user;
} | 3 |
protected static Ptg calcTBillEq( Ptg[] operands )
{
if( operands.length < 3 )
{
PtgErr perr = new PtgErr( PtgErr.ERROR_NULL );
return perr;
}
debugOperands( operands, "calcTBILLEQ" );
GregorianCalendar sDate = (GregorianCalendar) DateConverter.getCalendarFromNumber( operands[0].getValue() );
GregorianCalendar mDate = (GregorianCalendar) DateConverter.getCalendarFromNumber( operands[1].getValue() );
double rate = operands[2].getDoubleVal();
long settlementDate = (new Double( DateConverter.getXLSDateVal( sDate ) )).longValue();
long maturityDate = (new Double( DateConverter.getXLSDateVal( mDate ) )).longValue();
if( settlementDate >= maturityDate )
{
return new PtgErr( PtgErr.ERROR_NUM );
}
if( (maturityDate - settlementDate) > 365 )
{
return new PtgErr( PtgErr.ERROR_NUM );
}
if( rate <= 0 )
{
return new PtgErr( PtgErr.ERROR_NUM );
}
double DSM = maturityDate - settlementDate;
double result;
if( DSM <= 182 )
{
result = (365 * rate) / (360 - (rate * DSM));
}
else
{
double A = DSM / 365;
double B = rate * DSM;
double C = (((2 * A) - 1) * B) / (B - 360);
double D = Math.pow( A, 2 ) - C;
result = ((-2 * A) + (2 * Math.sqrt( D ))) / ((2 * A) - 1);
}
log.debug( "Result from calcTBILLEQ= " + result );
PtgNumber pnum = new PtgNumber( result );
return pnum;
} | 5 |
public synchronized void setEnabled(boolean enabled) {
if(!enabled) {
set(0);
}
_enabled = enabled;
} | 1 |
public ArrayList< XmlStructure > read(){
XmlStructure xml = null;
try{
File xmlFile;
if(from.matches("highscores.xml")){
log.info("Reading from " + from + " file.");
String home=System.getProperty("user.home");
File prop = new File(home, ".roulettegame");
xmlFile= new File(prop,from);
}
else{
URL url = XMLReader.class.getClassLoader().getResource("testscores.xml");
xmlFile = new File(url.getPath());
}
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("highscore");
for(int i=0; i< nodes.getLength();i++){
Node node = nodes.item(i);
if(node.getNodeType()==Node.ELEMENT_NODE){
Element element = (Element) node;
String str = element.getElementsByTagName("name").item(0).getTextContent();
String tmp = element.getElementsByTagName("money").item(0).getTextContent();
int m = Integer.parseInt(tmp);
xml = new XmlStructure(str,m);
}
backList.add(xml);
}
log.info("Reading successful.");
}
catch(ParserConfigurationException e){
log.error("ParserConfigurationException caught:");
log.error(e.toString());
}
catch(IOException e){
log.error("IOException caught:");
log.error(e.toString());
}
catch(SAXException e){
log.error("SAXException caught:");
log.error(e.toString());
}
return backList;
} | 6 |
@Override
public String getName() {
String name = super.getName();
if (name == null) {
return DEFAULT_NAME;
} else {
return name;
}
} | 1 |
@Override
public boolean hasNext()
{
if ( maxLines > 0 && maxLines <= linesRead ) {
return false;
}
return nextline != null;
} | 2 |
public void setId(int id) {
if(id > 1) {
this.id = id;
}
} | 1 |
public static int[] getRangeCoords( String range )
{
int numrows;
int numcols;
int numcells;
int[] coords = new int[5];
String temprange = range;
// figure out the sheet bounds using the range string
temprange = stripSheetNameFromRange( temprange )[1];
String startcell;
String endcell;
int lastcolon = temprange.lastIndexOf( ":" );
endcell = temprange.substring( lastcolon + 1 );
if( lastcolon == -1 ) // no range
{
startcell = endcell;
}
else
{
startcell = temprange.substring( 0, lastcolon );
}
startcell = StringTool.strip( startcell, "$" );
endcell = StringTool.strip( endcell, "$" );
// get the first cell's coordinates
int charct = startcell.length();
while( charct > 0 )
{
if( !Character.isDigit( startcell.charAt( --charct ) ) )
{
charct++;
break;
}
}
String firstcellrowstr = startcell.substring( charct );
int firstcellrow = -1;
try
{
firstcellrow = Integer.parseInt( firstcellrowstr );
}
catch( NumberFormatException e )
{ // could be a whole-col-style ref
}
String firstcellcolstr = startcell.substring( 0, charct ).trim();
int firstcellcol = getIntVal( firstcellcolstr );
// get the last cell's coordinates
charct = endcell.length();
while( charct > 0 )
{
if( !Character.isDigit( endcell.charAt( --charct ) ) )
{
charct++;
break;
}
}
String lastcellrowstr = endcell.substring( charct );
int lastcellrow = -1;
try
{
lastcellrow = Integer.parseInt( lastcellrowstr );
}
catch( NumberFormatException e )
{ // could be a whole-col-style ref
}
String lastcellcolstr = endcell.substring( 0, charct );
int lastcellcol = getIntVal( lastcellcolstr );
numrows = (lastcellrow - firstcellrow) + 1;
numcols = (lastcellcol - firstcellcol) + 1;
/*
* if(numrows == 0)numrows =1; if(numcols == 0)numcols =1;
*/
numcells = numrows * numcols;
if( numcells < 0 )
{
numcells *= -1; // handle swapped cells ie: "B1:A1"
}
coords[0] = firstcellrow;
coords[1] = firstcellcol;
coords[2] = lastcellrow;
coords[3] = lastcellcol;
coords[4] = numcells;
// Trap errors in range
// if (firstcellrow < 0 || lastcellrow < 0 || firstcellcol < 0 ||
// lastcellcol < 0)
// log.error("ExcelTools.getRangeCoords: Error in Range " + range);
return coords;
} | 8 |
private int read() throws IOException {
int result = nextChar;
while (result == NL || result == ENTER) {
++lineNumber;
charPosition = 0;
result = reader.read();
}
nextChar = reader.read();
++charPosition;
return result;
} | 2 |
public static boolean isWindowsPlatform()
{
String os = System.getProperty("os.name");
if (os != null && os.startsWith(WIN_ID))
{
return true;
}
else
{
return false;
}
} | 2 |
public boolean canAddItem(Item newItem) {
//is a valid item
if(newItem == null) {
return false;
} else if(newItem.getProduct() == null) { //Product Must be non-empty.
return false;
} else if(!newItem.getBarCode().isValid()) { // Have a valid barcode
return false;
} else if(!newItem.hasValidEntryDate()) { // Have a valid entry date
return false;
} else if(newItem.getExitDate() != null) { // Can't be a removed item
return false;
} else if(!newItem.hasProductShelfLife() && newItem.getExpirationDate() != null) {
return false;
}
//Barcode Unique among all Items.
return (!itemsByBarCode.containsKey(newItem.getBarCode())
&& !removedItemsByBarCode.containsKey(newItem.getBarCode()));
} | 8 |
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
PluginWrapper pluginWrapper = plugins.get(rowIndex);
switch (columnIndex)
{
case 0:
return pluginWrapper.getPluginName();
case 1:
return pluginWrapper.getPluginDescription();
case 2:
return pluginWrapper.getPluginVersion();
case 3:
return pluginWrapper.getPluginWebsite();
case 4:
return pluginWrapper.getAuthorName();
case 5:
return pluginWrapper.getAuthorEmail();
case 6:
return pluginWrapper.isPluginInitialized();
}
return null;
} | 7 |
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException, FileNotFoundException {
AutoTotaalDienst atd = (AutoTotaalDienst) getServletContext()
.getAttribute("atdRef");
String press = req.getParameter("press");
String v1 = (String) req.getParameter("veld1");
String x = "";
int check = 1;
if (!v1.equals("leeg")) {
x = v1;
ArrayList<Gebruiker> klanten = atd.getAlleKlantenBrieven90();
Gebruiker klant = atd.zoekGebruiker(x, klanten);
atd.verwijderKlant(klant, klanten);
}
if (press.equals("Brieven aanmaken")) {
if (!x.equals("") && check != 2) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy_HHmm");
Date datum = new Date();
try {
FileWriter fw = new FileWriter("[" + sdf.format(datum)
+ "] " + x + " - Betaalherinnering +90 dagen.txt",
false);
PrintWriter pw = new PrintWriter(fw);
pw.println("Geachte " + x + ",");
pw.println("");
pw.println("U heeft al langer dan 90 dagen gewacht met het betalen van uw factuur.");
pw.println("Het is belangrijk dat u zo spoedig mogelijk deze factuur betaalt.");
pw.println("");
pw.println("Met vriendelijke groet,");
pw.println("");
pw.println("Henk Paladijn");
PrintWriter out = resp.getWriter();
out.println("<script type=\"text/javascript\">");
out.println("alert('Brief van " + x + " is aangemaakt!');");
out.println("window.location = 'herinneringsbrieven-brievenaanmaken.jsp'");
out.println("</script>");
out.close();
pw.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
} else if (check != 2) {
PrintWriter out = resp.getWriter();
out.println("<script type=\"text/javascript\">");
out.println("alert('Aanmaken mislukt, selecteer een klant!');");
out.println("window.location = 'herinneringsbrieven-brievenaanmaken.jsp'");
out.println("</script>");
out.close();
}
}
} | 6 |
private void writeOut(String ownerName, byte[] owner, byte[] key,
String prvOrPub) throws IOException {
DataOutputStream osPrv = null;
switch (prvOrPub) {
case "prv":
osPrv = new DataOutputStream(new FileOutputStream(ownerName
+ ".prv"));
case "pub":
osPrv = new DataOutputStream(new FileOutputStream(ownerName
+ ".pub"));
}
osPrv.writeInt(owner.length);
osPrv.write(owner);
osPrv.writeInt(key.length);
osPrv.write(key);
osPrv.close();
} | 2 |
void suoritaHeittely() {
vihollisnopat = luola.getVihollisnopat() + pelaaja.getViholliskorttimuutokset();
heittele(vihollisnopat);
if (!pelaaja.getClass().equals(Npc.class)){
heittelyraami = peli.getUi().luoHeittelyraami(this);
odota();
}
tallennaViholliset();
for (Kortti kortti : pelaaja.getKortit()) {
kortti.tiedotaViholliset(luuranko, orkki, lohari);
}
taistelunopat = luola.getTaistelunopat() + pelaaja.getTaistelukorttimuutokset();
heittele(taistelunopat);
if (!pelaaja.getClass().equals(Npc.class)){
heittelyraami.paivitaVaihe();
odota();
}
taistele();
if (voitto){
aarrenopat = luola.getAarrenopat() + pelaaja.getAarrekorttimuutokset();
heittele(aarrenopat);
} else {
heittele(0);
}
if (!pelaaja.getClass().equals(Npc.class)){
heittelyraami.paivitaVaihe();
odota();
}
palkitse();
} | 5 |
public Object remove(int index) {
return index >= 0 && index < this.length()
? this.myArrayList.remove(index)
: null;
} | 2 |
public static void getDirectories(String folderNameIn) {
//File folder = new File(ROOT_FOLDER + folderNameIn);
File folder = new File("C:\\Users\\Brandon194\\AppData\\Roaming\\Brandon194\\WorkCalculator");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles){
if (file.getName().endsWith(".jar")){
//JarFile.
}else {
System.out.println(file.toString());
}
}
} | 2 |
public int GetBusStopNumber()
{
//get bus stop number
return busStopNumber;
} | 0 |
public static ObjectDef getObjectDef(int i)
{
for(int j = 0; j < 20; j++)
if(cache[j].type == i)
return cache[j];
cacheIndex = (cacheIndex + 1) % 20;
ObjectDef class46 = cache[cacheIndex];
class46.type = i;
class46.setDefaults();
byte[] buffer = archive.get(i);
if(buffer != null && buffer.length > 0)
class46.readValues(new ByteStreamExt(buffer));
return class46;
} | 4 |
@SuppressWarnings("unchecked")
public final void HandlePacket(APacket aPacket, IIOHandler sender) {
log.finer("Handling Packet \n"+aPacket.getClass().toString());
Method m = null;
try {
m = getClass().getDeclaredMethod("handlePacket", aPacket.getClass(), IIOHandler.class);
m.invoke(this, aPacket, sender);
} catch(NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
if(m != null) {
System.err.println(m.getName()+":"+aPacket.getClass().getName());
}
e.printStackTrace();
}
} | 2 |
public void describeBehaviour(Description d) {
if (! prey.health.alive()) {
if (type == TYPE_FEEDS) {
d.append("Scavenging meat from ") ;
d.append(prey) ;
}
if (type == TYPE_HARVEST || type == TYPE_PROCESS) {
if (! prey.destroyed()) {
d.append("Harvesting meat from ") ;
d.append(prey) ;
}
else {
d.append("Returning meat to ") ;
d.append(depot) ;
}
}
}
else d.append("Hunting "+prey) ;
} | 5 |
public void testAdd()
{
System.out.println("hello world !");
} | 0 |
public boolean deleteElement(int x, int y) {
Element element = (Element) getLocationElement(x, y);
if (element == null) {
return false;
}
// Place
if (element instanceof Place) {
((PetriNet) graph).deletePlace(((Place) element).getName());
}
// Transition
if (element instanceof Transition) {
((PetriNet) graph).deleteTransition(((Transition) element).getName());
}
// Node
if (element instanceof Node) {
((PrecedenceGraph) graph).deleteNode(((Node) element).getName());
}
// Place
if (element instanceof Resource) {
((PetriNet) graph).deleteResource(((Resource) element).getName());
}
return true;
} | 5 |
public InheritanceChangeDescription calculateDescription()
{
InheritanceChangeDescription res = new InheritanceChangeDescription();
findDeleted(res, fromStack.getActual());
findAdded(res, toStack.getActual());
// check if any field has moved from one superclass to another
List<String> fieldNames = fromStack.getAllPropertyNames();
for (String name : fieldNames)
{
ObjectRepresentation oldRep = fromStack.getRepresentation(name);
ObjectRepresentation nuRep = toStack.getRepresentation(name);
if (nuRep != null && !oldRep.getTableName().equals(nuRep.getTableName()))
{
FieldChangeDescription fcDesc = new FieldChangeDescription();
fcDesc.setFromName(name);
fcDesc.setToName(name);
fcDesc.setFromTable(oldRep.getTableName());
fcDesc.setToTable(nuRep.getTableName());
fcDesc.setToClass(nuRep.getReturnType(name));
fcDesc.setFromClass(oldRep.getReturnType(name));
ObjectStack os = new ObjectStack(toStack.getAdapter(), nuRep.getRepresentedClass());
if (os.getRepresentation(name) == null)
{
fcDesc.setFromClass(null);
}
res.addMovedField(fcDesc);
}
}
return res;
} | 4 |
private double triLerp(double x, double y, double z, double q000, double q001, double q010, double q011, double q100, double q101, double q110, double q111, double x1, double y1, double z1, double x2, double y2, double z2) {
if (x < x1) {
throw new IllegalArgumentException("x must not be less than x1");
}
if (x > x2) {
throw new IllegalArgumentException("x must not be greater than x2");
}
if (y < y1) {
throw new IllegalArgumentException("y must not be less than y1");
}
if (y > y2) {
throw new IllegalArgumentException("y must not be greater than y2");
}
if (z < z1) {
throw new IllegalArgumentException("z must not be less than z1");
}
if (z > z2) {
throw new IllegalArgumentException("z must not be greater than z2");
}
double x00 = lerp(x, x1, x2, q000, q100);
double x10 = lerp(x, x1, x2, q010, q110);
double x01 = lerp(x, x1, x2, q001, q101);
double x11 = lerp(x, x1, x2, q011, q111);
double r0 = lerp(y, y1, y2, x00, x01);
double r1 = lerp(y, y1, y2, x10, x11);
return lerp(z, z1, z2, r0, r1);
} | 6 |
public boolean isNull(int index) {
return JSONObject.NULL.equals(this.opt(index));
} | 0 |
public void setOptions(String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption("mean-prec", options);
if (tmpStr.length() > 0)
setMeanPrec(Integer.parseInt(tmpStr));
else
setMeanPrec(getDefaultMeanPrec());
tmpStr = Utils.getOption("stddev-prec", options);
if (tmpStr.length() > 0)
setStdDevPrec(Integer.parseInt(tmpStr));
else
setStdDevPrec(getDefaultStdDevPrec());
tmpStr = Utils.getOption("col-name-width", options);
if (tmpStr.length() > 0)
setColNameWidth(Integer.parseInt(tmpStr));
else
setColNameWidth(getDefaultColNameWidth());
tmpStr = Utils.getOption("row-name-width", options);
if (tmpStr.length() > 0)
setRowNameWidth(Integer.parseInt(tmpStr));
else
setRowNameWidth(getDefaultRowNameWidth());
tmpStr = Utils.getOption("mean-width", options);
if (tmpStr.length() > 0)
setMeanWidth(Integer.parseInt(tmpStr));
else
setMeanWidth(getDefaultMeanWidth());
tmpStr = Utils.getOption("stddev-width", options);
if (tmpStr.length() > 0)
setStdDevWidth(Integer.parseInt(tmpStr));
else
setStdDevWidth(getDefaultStdDevWidth());
tmpStr = Utils.getOption("sig-width", options);
if (tmpStr.length() > 0)
setSignificanceWidth(Integer.parseInt(tmpStr));
else
setSignificanceWidth(getDefaultSignificanceWidth());
tmpStr = Utils.getOption("count-width", options);
if (tmpStr.length() > 0)
setStdDevPrec(Integer.parseInt(tmpStr));
else
setStdDevPrec(getDefaultCountWidth());
setShowStdDev(Utils.getFlag("show-stddev", options));
setShowAverage(Utils.getFlag("show-avg", options));
setRemoveFilterName(Utils.getFlag("remove-filter", options));
setPrintColNames(Utils.getFlag("print-col-names", options));
setPrintRowNames(Utils.getFlag("print-row-names", options));
setEnumerateColNames(Utils.getFlag("enum-col-names", options));
setEnumerateRowNames(Utils.getFlag("enum-row-names", options));
} | 8 |
public void run() {
while(true) {
if (isUpPressed)
translate(0.0, -0.1);
if (isDownPressed)
translate(0.0, 0.1);
if (isLeftPressed)
translate(-0.1, 0.0);
if (isRightPressed)
translate(0.1, 0.0);
if (isTurnLeftPressed)
rotate(-0.1);
if (isTurnRightPressed)
rotate(0.1);
if (isRepaintNeeded) {
repaint();
isRepaintNeeded = false;
}
}
} | 8 |
public void generate( String fileName, DBParams schema_params ) throws SQLException, IOException, ParserConfigurationException, ClassNotFoundException {
// Получим информацию о таблицах. Эта информация будет хранится в структуре типа Info
// Будет выполнено соединение со схемой и от туда считана информация
Info info = null;
try {
info = new Info(schema_params);
} catch (SQLException e) {
System.out.println("PosibleActions.generate: ошибка при получении информации из схемы");
e.printStackTrace();
throw e;
}
// Если инофрмация получена успешно то надо собрать документ
String strXML = null;
try {
// Создадим построитель xml.
XMLBuilder xmlBuilder = new XMLBuilder();
// Попросим один из вариантов xml. (Возможно позже появятся другие)
strXML = xmlBuilder.genStandartXML(info);
} catch (ParserConfigurationException e) {
System.out.println("PosibleActions.generate: ошибка при построении xml");
e.printStackTrace();
throw e;
}
// Запишем полученный XML в файл
File file = new File(fileName);
// Если файла не существует то создадим его
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
System.out.println("PosibleActions.generate: ошибка при создании файла результата");
e.printStackTrace();
throw e;
}
}
// Выполним запись в файл
try {
FileOutputStream fop = new FileOutputStream(file);
fop.write(strXML.getBytes());
fop.close();
} catch (IOException e) {
System.out.println("PosibleActions.generate: ошибка при записи в файл");
e.printStackTrace();
throw e;
}
System.out.println("Generating done");
} | 5 |
public static boolean isDiscrete(String attributeName, Set<? extends Attributable> items) {
// First collect the set of all attribute values
Set<Object> values = new HashSet<Object>();
for (Attributable item : items) {
Object value = item.getAttribute(attributeName);
if (value != null) {
values.add(value);
}
}
boolean isNumber = true;
boolean isInteger = true;
for (Object value : values) {
if (value instanceof Number) {
if (((Number)value).doubleValue() != ((Number)value).intValue()) {
isInteger = false;
}
} else {
isNumber = false;
}
}
if (isNumber && !isInteger) return false;
return true;
} | 8 |
public void setjLabelChercher(JLabel jLabelChercher) {
this.jLabelChercher = jLabelChercher;
} | 0 |
public void addSprite(Sprite sprite) {
sprites.add(sprite);
} | 0 |
protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
int x2 = x + (w);
int y2 = y + (h);
switch (tabPlacement) {
case LEFT:
paintLeftTabBorder(tabIndex, g, x, y, x2, y2, isSelected);
break;
case RIGHT:
paintRightTabBorder(tabIndex, g, x, y, x2, y2, isSelected);
break;
case BOTTOM:
if (roundedTabs) {
paintRoundedBottomTabBorder(tabIndex, g, x, y, x2, y2 - 1, isSelected);
} else {
paintBottomTabBorder(tabIndex, g, x, y, x2, y2 - 1, isSelected);
}
break;
case TOP:
default:
if (roundedTabs) {
paintRoundedTopTabBorder(tabIndex, g, x, y, x2, y2, isSelected);
} else {
paintTopTabBorder(tabIndex, g, x, y, x2, y2, isSelected);
}
}
} | 6 |
@Override
public int castingQuality(MOB mob, Physical target)
{
if(mob!=null)
{
if(mob.isInCombat())
return Ability.QUALITY_INDIFFERENT;
if(target instanceof MOB)
{
if(((MOB)target).charStats().getCurrentClass().baseClass().equals("Cleric"))
return Ability.QUALITY_INDIFFERENT;
if(CMLib.flags().isAnimalIntelligence(((MOB)target))||CMLib.flags().isGolem(target))
return Ability.QUALITY_INDIFFERENT;
if(((MOB)target).getWorshipCharID().length()==0)
return Ability.QUALITY_INDIFFERENT;
}
}
return super.castingQuality(mob,target);
} | 7 |
public static Headers readHeaders(InputStream in) throws IOException {
Headers headers = new Headers();
String line;
String prevLine = "";
int count = 0;
while ((line = readLine(in)).length() > 0) {
int first;
for (first = 0; first < line.length() &&
Character.isWhitespace(line.charAt(first)); first++);
if (first > 0) // unfold header continuation line
line = prevLine + ' ' + line.substring(first);
int separator = line.indexOf(':');
if (separator == -1)
throw new IOException("invalid header: \"" + line + "\"");
String name = line.substring(0, separator);
String value = line.substring(separator + 1).trim(); // ignore LWS
Header replaced = headers.replace(name, value);
// concatenate repeated headers (distinguishing repeat from fold)
if (replaced != null && first == 0) {
value = replaced.getValue() + ", " + value;
line = name + ": " + value;
headers.replace(name, value);
}
prevLine = line;
if (++count > 100)
throw new IOException("too many header lines");
}
return headers;
} | 8 |
protected void setSinglePreserved() {
if (parent != null)
parent.setPreserved();
} | 1 |
public String correctItem(MOB mob)
{
for(int i=0;i<mob.numItems();i++)
{
final Item I=mob.getItem(i);
if((I!=null)
&&(CMLib.flags().canBeSeenBy(I,mob))
&&(I.amWearingAt(Wearable.IN_INVENTORY))
&&(!((((I instanceof Armor)&&(I.basePhyStats().armor()>1))
||((I instanceof Weapon)&&(I.basePhyStats().damage()>1))))))
return I.Name();
}
return null;
} | 8 |
public static Professor addProfessors(Professor prof) {
boolean exist = false;
int pos = 0;
if (prof == null)
return null;
for (int i = 0; i < FileReadService.profList.size(); i++) {
if (FileReadService.profList.get(i).equals(prof)) {
exist = true;
pos = i;
}
}
if (!exist) {
FileReadService.profList.add(prof);
return prof;
}
return FileReadService.profList.get(pos);
} | 4 |
private void string(String value) throws IOException {
String[] replacements = htmlSafe ? HTML_SAFE_REPLACEMENT_CHARS : REPLACEMENT_CHARS;
out.write("\"");
int last = 0;
int length = value.length();
for (int i = 0; i < length; i++) {
char c = value.charAt(i);
String replacement;
if (c < 128) {
replacement = replacements[c];
if (replacement == null) {
continue;
}
} else if (c == '\u2028') {
replacement = "\\u2028";
} else if (c == '\u2029') {
replacement = "\\u2029";
} else {
continue;
}
if (last < i) {
out.write(value, last, i - last);
}
out.write(replacement);
last = i + 1;
}
if (last < length) {
out.write(value, last, length - last);
}
out.write("\"");
} | 8 |
public String getValue(){
return this.value;
} | 0 |
private PickVO getList45PVO(PickVO pvo, ArrayList<LineAnaVO> list45) {
if (list45.size() > 4) {
LineAnaVO v = getGap(0, list45);
if (v != null) {
pvo.add(v.getBnu());
}
v = getGap(1, list45);
if (v != null) {
pvo.add(v.getBnu());
}
v = getGap(2, list45);
if (v != null) {
pvo.add(v.getBnu());
}
v = getGap(4, list45);
if (v != null) {
pvo.add(v.getBnu());
}
} else {
LineAnaVO v = getGap(0, list45);
if (v != null) {
pvo.add(v.getBnu());
}
v = getGap(1, list45);
if (v != null) {
pvo.add(v.getBnu());
}
v = getGap(2, list45);
if (v != null) {
pvo.add(v.getBnu());
}
}
return pvo;
} | 8 |
public void loadAllPermissions() {
ResultSet data = query(QueryGen.selectAllPermissions());
while (iterateData(data)) {
HashMap<PermissionFlag, Boolean> flags = new HashMap<PermissionFlag, Boolean>();
String permId = getString(data, "PermissibleId");
String permType = getString(data, "PermissibleType");
String objectId = getString(data, "ObjectId");
String objectType = getString(data, "ObjectType");
ChunkyObject object = ChunkyManager.getObject(objectType, objectId);
ChunkyObject permObject = ChunkyManager.getObject(permType, permId);
PermissionRelationship perms = new PermissionRelationship();
perms.load(getString(data, "data"));
if (object != null && permObject != null)
ChunkyManager.putPermissions(object, permObject, perms);
}
} | 3 |
protected List<Object> addEmptyRow() {
List<Object> row = new ArrayList<Object>();
rs.add(row);
for (int i = 0, size = columnNames.size(); i < size; i++) {
row.add(null);
}
return row;
} | 1 |
public boolean contains(Point p) {
return ((this.from.x == p.x) && (this.from.y == p.y)) ||
((this.to.x == p.x) && (this.to.y == p.y));
} | 3 |
public void afficher(){
for(char elem : ligne){
System.out.print(elem + " ");
}
} | 1 |
private TreeMap<Float, Float> makeListFromPricePair(
TreeMap<Float, Point2D.Float> priceByDate, int id) {
TreeMap<Float, Float> pts = new TreeMap<Float, Float>();
for (Entry<Float, Point2D.Float> prices : priceByDate.entrySet()) {
switch (id) {
case 0:
pts.put(prices.getKey(), prices.getValue().x);
break;
case 1:// market
float date = prices.getKey();
float totalValue = prices.getValue().y;
// if market sum is less than 1000 there is a data problem so
// dont add the point
if (totalValue > 1000)
pts.put(date, totalValue);
break;
}
}
return pts;
} | 4 |
private void leerClientes(){
ArrayList<String> list = disco.leerArchivo("clientes/clientes");
String[] aux;
for(int i=0; i<list.size(); ++i){
aux = list.get(i).split("\t");
String o = new String();
ArrayList<String> ob = disco.leerArchivo("clientes/" + aux[0]);
for(int j=0; j<ob.size(); ++j){
o = o.concat(ob.get(j));
if(j+1<ob.size())
o = o.concat("\n");
}
cjtClientes.put(aux[0],new Cliente(aux[0],aux[1],aux[5],aux[2],
aux[3],aux[4],o));
}
} | 3 |
Subsets and Splits