text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public void launchContainers() throws Exception {
String noOfContainers = getJobConfiguration().getProperty(SingularConstants.KEY_NO_OF_CONTAINERS);
String containerClassName = getJobConfiguration().getProperty(SingularConstants.KEY_CONTAINER_CLASS);
String containerCores = getJobConfiguration().getProperty(SingularConstants.KEY_NO_OF_CORES);
String containerMemory = getJobConfiguration().getProperty(SingularConstants.KEY_MEM);
String stagingPath = getJobConfiguration().getProperty(SingularConstants.KEY_APPLICATION_STAGING_PATH);
System.out.println("No of container " + noOfContainers + " " + containerClassName + " " +
containerCores + " " + containerMemory);
int noOfContainersRequired = Integer.parseInt(noOfContainers);
int numberOfCompletedContainers = 0;
int noOfContainersReceived = 0;
int totalNoOfContainersReceived = 0;
int noOfContainersToAsk = noOfContainersRequired;
List<ContainerId> releasedContainers = new ArrayList<ContainerId>();
while(totalNoOfContainersReceived < noOfContainersRequired || numberOfCompletedContainers < noOfContainersRequired) {
//allocate would also act as heart beat to resource manager as well.
AllocateResponse allocateResponse = resourceAllocator.allocateContainers(noOfContainersToAsk,releasedContainers,
numberOfCompletedContainers);
List<ContainerStatus> statuses = allocateResponse.getAMResponse().getCompletedContainersStatuses();
for(ContainerStatus status : statuses) {
if(status.getState() == ContainerState.COMPLETE)
numberOfCompletedContainers++;
}
List<Container> containers = allocateResponse.getAMResponse().getAllocatedContainers();
noOfContainersReceived = containers.size();
totalNoOfContainersReceived += noOfContainersReceived;
for(Container container : containers) {
Runnable runnable = new ContainerRunnable(container,containerClassName,new Path(stagingPath));
executorService.submit(runnable);
}
releasedContainers.clear();
for(ContainerStatus containerStatus : allocateResponse.getAMResponse().getCompletedContainersStatuses()) {
ContainerId containerId = containerStatus.getContainerId();
releasedContainers.add(containerId);
}
System.out.println("Requested for " + noOfContainersToAsk + " , got " + noOfContainersReceived + " and no of completed containers " + numberOfCompletedContainers);
// not to hit RM is quick succession.
TimeUnit.SECONDS.sleep(2);
noOfContainersToAsk = (noOfContainersRequired - totalNoOfContainersReceived);
}
executorService.shutdown();
// waiting for the executor to finish all the threads.
while (!executorService.isTerminated()) {
TimeUnit.SECONDS.sleep(2);
}
} | 7 |
public boolean isDebugMode() {
return getConfig().getBoolean("angry-debug", false);
} | 0 |
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String method = request.getParameter("method");
String data = request.getParameter("data");
request.setAttribute("data", request.getParameter("data"));
if("Filter".equals(request.getParameter("method"))){
if("yahooFinance".equals(request.getParameter("data")))
request.getRequestDispatcher("/testing/filterTesting_yahoofinance.jsp").forward(request, response);
else if("SqlServer".equals(request.getParameter("data")))
request.getRequestDispatcher("/testing/filterTesting_db.jsp").forward(request, response);
}
if("MA".equals(request.getParameter("method"))){
if("yahooFinance".equals(request.getParameter("data")))
request.getRequestDispatcher("/testing/maTesting_yahoofinance.jsp").forward(request, response);
else if("SqlServer".equals(request.getParameter("data")))
request.getRequestDispatcher("/testing/maTesting_db.jsp").forward(request, response);
}
if("RSI".equals(request.getParameter("method"))){
if("yahooFinance".equals(request.getParameter("data")))
request.getRequestDispatcher("/testing/rsiTesting_yahoofinance.jsp").forward(request, response);
else if("SqlServer".equals(request.getParameter("data")))
request.getRequestDispatcher("/testing/rsiTesting_db.jsp").forward(request, response);
;
}
} | 9 |
private static int[] getMinPrefMaxSumSize(int[][] sizes) {
int[] retSizes = new int[3];
for (int i = 0; i < sizes.length;
i++) {
if (sizes[i] != null) {
int[] size = sizes[i];
for (int sType = LayoutUtil.MIN;
sType <= LayoutUtil.MAX;
sType++) {
int s = size[sType];
if (s != LayoutUtil.NOT_SET) {
if (sType == LayoutUtil.PREF) {
int bnd = size[LayoutUtil.MAX];
if (bnd != LayoutUtil.NOT_SET && bnd < s) {
s = bnd;
}
bnd = size[LayoutUtil.MIN];
if (bnd > s) {
// Includes s == LayoutUtil.NOT_SET since < 0.
s = bnd;
}
}
retSizes[sType] += s; // MAX compensated below.
}
}
// So that MAX is always correct.
if (size[LayoutUtil.MAX] ==
LayoutUtil.NOT_SET) {
retSizes[LayoutUtil.MAX] =
LayoutUtil.INF;
}
}
}
return retSizes;
} | 9 |
public byte[] decodeBytes() {
byte[] res = new byte[decodeInt()];
for (int i = 0; i < res.length; i++) {
res[i] = decodeByte();
}
return res;
} | 1 |
public boolean isEqual(LiteralLabel value1, LiteralLabel value2) {
if (value1.getDatatype() instanceof XSDBaseNumericType && value2.getDatatype() instanceof XSDBaseNumericType) {
Long n1, n2;
n1 = null;
n2 = null;
Object v1 = value1.getLexicalForm();
Object v2 = value2.getLexicalForm();
boolean v1String = false;
boolean v2String = false;
try {
n1 = new Long(Long.parseLong(v1.toString()));
} catch (NumberFormatException ex) {
v1String = true;
}
try {
n2 = new Long(Long.parseLong(v2.toString()));
} catch (NumberFormatException ex) {
v2String = true;
}
if(v1String && v2String) {
return v1.equals(v2);
}
else {
if(v1String || v2String) {
return false;
}
else {
return n1.longValue() == n2.longValue();
}
}
} else {
// At least one arg is not part of the integer hierarchy
return false;
}
} | 8 |
void createXML(String xml, int orders, int robots, int shelves,
int pickers, int maxOrder, int maxStock, boolean randOrder,
boolean randStock) {
Warehouse wh = new Warehouse();
// Creating Orders
if (orders > 0) {
this.orders = orders;
if (maxOrder <= 0) {
maxOrder = 4;
}
Orders x = new Orders(orders, maxOrder, randOrder);
wh.setOrders(x);
}
if (robots > 0) {
this.robots = robots;
Robots y = new Robots(robots);
wh.setRobots(y);
}
if (shelves > 0) {
this.shelves = shelves;
if (maxStock >= 0) {
maxStock = 100;
}
Shelves z = new Shelves(shelves, maxStock, randStock);
wh.setShelves(z);
}
if (pickers > 0) {
this.pickers = pickers;
Pickers w = new Pickers(pickers);
wh.setPickers(w);
}
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Warehouse.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);
File XMLfile = new File("conf/warehouse/" + xml);
jaxbMarshaller.marshal(wh, XMLfile);
readXML(xml);
} catch (JAXBException e) {
e.printStackTrace();
}
} | 7 |
public static double get(String util) {
double weighting = (util.matches("[+-]?\\d*(\\.\\d+)?"))? Double.parseDouble(util) : new Random().nextDouble();
if (util.equals("random") || util.equals("next")) {
weighting = new Random().nextDouble() + MIN;
}
else if (util.equals("previous")) {
weighting = PERVIOUS;
}
else if (util.equals("nextone")) {
weighting = NEXT;
}
else if (util.equals("must")) {
weighting = MUST;
}
else if (util.equals("wolframAlpha")) {
weighting = 100;
}
else if (util.equals("jmegahal")) {
weighting = new Random().nextDouble() + MIN;
}
return weighting;
} | 8 |
static void stepRK(ArrayList<Body> v, double dt) {
for (int i = 0; i < v.size(); i++) {
v.get(i).setF(Body.forces(v.get(i), v, i));
}
ArrayList<Body> supp = new ArrayList<Body>();
for (int i = 0; i < v.size(); i++) {
Body b = v.get(i);
double x = b.p.x;
double y = b.p.y;
double z = b.p.z;
double vx = b.v.x;
double vy = b.v.y;
double vz = b.v.z;
double ax = b.f.x / b.mass;
double ay = b.f.y / b.mass;
double az = b.f.z / b.mass;
double newX = x + vx * dt + ax * dt * dt / 2;
double newY = y + vy * dt + ay * dt * dt / 2;
double newZ = z + vz * dt + az * dt * dt / 2;
Point newPoint = new Point(newX, newY, newZ);
Velocity newV = new Velocity(vx + ax * dt, vy + ay * dt, vz + az
* dt);
Body b2 = new Body(b.mass, newPoint, newV, new Force(0, 0, 0));
supp.add(b2);
}
for (int i = 0; i < supp.size(); i++) {
supp.get(i).setF(Body.forces(supp.get(i), supp, i));
}
for (int i = 0; i < v.size(); i++) {
Body b = v.get(i);
Body b2 = supp.get(i);
double x = b.p.x;
double y = b.p.y;
double z = b.p.z;
b.p.x = (x + dt * (b.v.x + b2.v.x) / 2);
b.p.y = (y + dt * (b.v.y + b2.v.y) / 2);
b.p.z = (z + dt * (b.v.z + b2.v.z) / 2);
double vx = b.v.x;
double vy = b.v.y;
double vz = b.v.z;
b.v.x = (vx + dt * (b.f.x + b2.f.x) / 2);
b.v.y = (vy + dt * (b.f.y + b2.f.y) / 2);
b.v.z = (vz + dt * (b.f.z + b2.f.z) / 2);
}
} | 4 |
public static void adjustToSameSize(Component... comps) {
Dimension best = new Dimension();
for (Component comp : comps) {
Dimension size = comp.getPreferredSize();
if (size.width > best.width) {
best.width = size.width;
}
if (size.height > best.height) {
best.height = size.height;
}
}
for (Component comp : comps) {
setOnlySize(comp, best);
}
} | 4 |
public void setSecondElement( E newSecond ) {
if ( newSecond == null ) {
throw new NullPointerException();
}
this.secondElement = newSecond;
} | 1 |
public void setPendingStage( int pendingStage ) {
if ( pendingStage <= 0 || pendingStage > shipBlueprintIds.length )
throw new IndexOutOfBoundsException( "Attempted to set 1-based flagship stage "+ pendingStage +" of "+ shipBlueprintIds.length +" total" );
this.pendingStage = pendingStage;
} | 2 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CarType other = (CarType) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} | 6 |
private final void draw1(byte[] is, int[] is_74_, int i, int i_75_,
int i_76_, int i_77_, int i_78_, int i_79_,
int i_80_, int i_81_, int i_82_, int i_83_,
aa var_aa, int i_84_, int i_85_) {
aa_Sub3 var_aa_Sub3 = (aa_Sub3) var_aa;
int[] is_86_ = ((aa_Sub3) var_aa_Sub3).anIntArray5201;
int[] is_87_ = ((aa_Sub3) var_aa_Sub3).anIntArray5202;
int i_88_ = i_81_ - ((SoftwareToolkit) softwareToolkit).widthOffset;
int i_89_ = i_82_;
if (i_85_ > i_89_) {
i_89_ = i_85_;
i_76_ += (i_85_ - i_82_) * ((SoftwareToolkit) softwareToolkit).maxWidth;
i_75_ += (i_85_ - i_82_) * i_83_;
}
int i_90_ = (i_85_ + is_86_.length < i_82_ + i_78_
? i_85_ + is_86_.length : i_82_ + i_78_);
int i_91_ = i >>> 24;
int i_92_ = 255 - i_91_;
for (int i_93_ = i_89_; i_93_ < i_90_; i_93_++) {
int i_94_ = is_86_[i_93_ - i_85_] + i_84_;
int i_95_ = is_87_[i_93_ - i_85_];
int i_96_ = i_77_;
if (i_88_ > i_94_) {
int i_97_ = i_88_ - i_94_;
if (i_97_ >= i_95_) {
i_75_ += i_77_ + i_80_;
i_76_ += i_77_ + i_79_;
continue;
}
i_95_ -= i_97_;
} else {
int i_98_ = i_94_ - i_88_;
if (i_98_ >= i_77_) {
i_75_ += i_77_ + i_80_;
i_76_ += i_77_ + i_79_;
continue;
}
i_75_ += i_98_;
i_96_ -= i_98_;
i_76_ += i_98_;
}
int i_99_ = 0;
if (i_96_ < i_95_)
i_95_ = i_96_;
else
i_99_ = i_96_ - i_95_;
for (int i_100_ = -i_95_; i_100_ < 0; i_100_++) {
if (is[i_75_++] != 0) {
int i_101_ = ((((i & 0xff00ff) * i_91_ & ~0xff00ff)
+ ((i & 0xff00) * i_91_ & 0xff0000))
>> 8);
int i_102_ = is_74_[i_76_];
is_74_[i_76_++]
= ((((i_102_ & 0xff00ff) * i_92_ & ~0xff00ff)
+ ((i_102_ & 0xff00) * i_92_ & 0xff0000))
>> 8) + i_101_;
} else
i_76_++;
}
i_75_ += i_99_ + i_80_;
i_76_ += i_99_ + i_79_;
}
} | 9 |
public Card(String s) {
switch (s.charAt(0)){
case 'J':
this.value=11;
break;
case 'Q':
this.value=12;
break;
case 'K':
this.value=13;
break;
case 'A':
this.value=14;
break;
default:
this.value=(s.charAt(0)-'0');
}
switch (s.charAt(1)){
case 'S':
this.suit=0;
break;
case 'C':
this.suit=1;
break;
case 'D':
this.suit=2;
break;
case 'H':
this.suit=3;
break;
}
} | 8 |
private void initializeTransitionCycle(TabListWidget... listWidgets) {
SelectionTransition previousTransition = null;
for (int i = 0; i < listWidgets.length; i++) {
SelectionTransition transition = new SelectionTransition(listWidgets[i]);
if(previousTransition != null)
transition.setPrevious(previousTransition);
previousTransition = transition;
transitions.add(transition);
}
if(!transitions.isEmpty())
transitions.get(0).setPrevious(transitions.get(transitions.size() - 1));
} | 3 |
public void findDocumentFrequency(){
for(String uniqueToken : tokenList){
for(Text t : textList){
if(t.getTokens().contains(uniqueToken)){
if(!documentFrequency.containsKey(uniqueToken)){
documentFrequency.put(uniqueToken, 0);
}
documentFrequency.put(uniqueToken, documentFrequency.get(uniqueToken)+1);
}
}
}
} | 4 |
@Override
public void undo() {
} | 0 |
private String setBudgetType(Budget budget) {
return (budget instanceof AnnualBudget) ? ANNUAL : MONTHLY;
} | 1 |
public Object nextContent() throws JSONException {
char c;
StringBuffer sb;
do {
c = next();
} while (Character.isWhitespace(c));
if (c == 0) {
return null;
}
if (c == '<') {
return XML.LT;
}
sb = new StringBuffer();
for (;;) {
if (c == '<' || c == 0) {
back();
return sb.toString().trim();
}
if (c == '&') {
sb.append(nextEntity(c));
} else {
sb.append(c);
}
c = next();
}
} | 7 |
public static ArrivalBoardingActivityEnumeration fromString(String v) {
if (v != null) {
for (ArrivalBoardingActivityEnumeration c : ArrivalBoardingActivityEnumeration.values()) {
if (v.equalsIgnoreCase(c.toString())) {
return c;
}
}
}
throw new IllegalArgumentException(v);
} | 3 |
public static double[][] removeRowColumn(double[][] origMatrix, int row, int col){
double[][] destMatrix = new double[origMatrix.length-1][origMatrix.length-1];
int p = 0;
for( int i = 0; i < origMatrix.length; ++i)
{
if ( i == row)
continue;
int q = 0;
for( int j = 0; j < origMatrix.length; ++j)
{
if ( j == col)
continue;
destMatrix[p][q] = origMatrix[i][j];
++q;
}
++p;
}
return destMatrix;
} | 4 |
public boolean init(Sim_port output, AllocPolicy policy, int resourceID)
{
if (output == null || policy == null || resourceID < 0) {
return false;
}
outputPort_ = output;
policy_ = policy;
resourceID_ = resourceID;
resIdObj_ = new Integer(resourceID);
return true;
} | 3 |
@Override
public Iterator<Cell<V>> iterator() {
return new Iterator<Cell<V>>() {
private MutableCell<V> cell = new MutableCell<V>();
private int count;
private int current = -1;
@Override
public boolean hasNext() {
return (count < grid.size);
}
@Override
public Cell<V> next() {
if (hasNext() == false) {
throw new NoSuchElementException("No more elements");
}
current++;
for ( ; current < grid.values.length; current++) {
if (grid.values[current] != null) {
break;
}
}
V value = grid.values[current];
count++;
cell.set(current / grid.columnCount, current % grid.columnCount, value);
return cell;
}
@Override
public void remove() {
if (current < 0) {
throw new IllegalStateException("Unable to remove, next() not called yet");
}
if (grid.values[current] == null) {
throw new IllegalStateException("Unable to remove, element has been removed");
}
grid.values[current] = null;
grid.size--;
count--;
}
};
} | 5 |
public Matrix getIndentity(){
if(width == height){
float[][] values = new float[width][width];
for(int i = 0; i < width; i++){
for(int j = 0; j < width; j++){
if(i == j){
values[i][j] = 1;
}else{
values[i][j] = 0;
}
}
}
return new Matrix(values, width, width);
}else{
return null;
}
} | 4 |
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
// return immediately when selecting an item
if (selecting) {
return;
}
// insert the string into the document
super.insertString(offs, str, a);
// lookup and select a matching item
Object item = lookupItem(getText(0, getLength()));
if (item != null) {
setSelectedItem(item);
} else {
// keep old item selected if there is no match
item = comboBox.getSelectedItem();
// imitate no insert (later on offs will be incremented by str.length(): selection won't move forward)
offs = offs - str.length();
// provide feedback to the user that his input has been received but can not be accepted
comboBox.getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
}
setText(item.toString());
// select the completed part
highlightCompletedText(offs + str.length());
} | 2 |
public int getFTG() {
return ftg;
} | 0 |
void runBinGobbler() {
FileOutputStream redirectWriter = null;
running = true;
try {
// Create buffer
byte buffer[] = new byte[BUFFER_SIZE];
int num = 0;
// Create redirect file (if any)
if (redirectTo != null) redirectWriter = new FileOutputStream(redirectTo);
// Read input
while ((num = is.read(buffer)) >= 0) {
// Redirect
if (redirectWriter != null) redirectWriter.write(buffer, 0, num);
// Report progress
if (progress != null) progress.progress();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
close();
// Close redirect
try {
if (redirectWriter != null) redirectWriter.close();
} catch (IOException ioe) {
running = false;
throw new RuntimeException(ioe);
}
running = false;
}
} | 7 |
public void move()
{
int dx = 0;
int dy = 0;
switch (direction)
{
case Up:
dy = -Block.HEIGTH;
break;
case Down:
dy = Block.HEIGTH;
break;
case Left:
dx = -Block.WIDTH;
break;
case Right:
dx = Block.WIDTH;
break;
}
for (int i = body.size() - 1; i > 0; i--) {
body.get(i).setX(body.get(i - 1).getX());
body.get(i).setY(body.get(i - 1).getY());
}
body.get(0).setX(body.get(0).getX()+dx); // Head
body.get(0).setY(body.get(0).getY()+dy);
} | 5 |
private boolean canBuild(Player player, Block block) {
if (player.hasPermission(STPermission.ADMIN.getPermission())) {
return true;
}
final Town town = plugin.getTown(block.getChunk());
if (town == null) {
if (block.getLocation().getBlockY() <= new TownUtils(plugin).getMineRoofY()) {
return player.hasPermission(STPermission.BUILD_MINES.getPermission());
} else {
return player.hasPermission(STPermission.BUILD_WILDERNESS.getPermission());
}
} else {
return town.hasMember(player.getName()) && player.hasPermission(STPermission.BUILD_TOWNS.getPermission());
}
} | 4 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TradeOrder other = (TradeOrder) obj;
if (count != other.count)
return false;
if (resourceType == null) {
if (other.resourceType != null)
return false;
} else if (!resourceType.equals(other.resourceType))
return false;
return true;
} | 7 |
public static Matcher matchInFile(File f, Pattern pattern) throws FileNotFoundException {
Scanner sFile = new Scanner(f);
while (sFile.hasNextLine()) {
String line = sFile.nextLine();
Matcher m = pattern.matcher(line);
Boolean found = m.find();
if(found) {
sFile.close();
return m;
}
}
sFile.close();
return null;
} | 2 |
protected boolean xObstacleAhead(double time) {
for (StaticObject so : AppFrame.getFrameDesign().getStaticObjects()) {
if (checkXObstacle(so, time)) {
if (obstacleReaction(so)) {
if (currentHorizontalSpeed > 0) {
this.currentCoord.setX(so.getCurrentCoordinates().getX() - this.currentWidth);
} else {
this.currentCoord.setX(so.getCurrentCoordinates().getX() + so.getLength());
}
currentHorizontalSpeed = 0;
heroOwnHorizontalSpeed = 0;
return true;
}
}
}
for (MovingObject mo : AppFrame.getFrameDesign().getMovingObjects()) {
if (checkXObstacle(mo, time)) {
obstacleReaction(mo);
}
}
return false;
} | 6 |
public void createPlayersProjectile2(int x, int y, int offX, int offY, int angle, int speed, int gfxMoving, int startHeight, int endHeight, int lockon, int time, int slope) {
//synchronized(c) {
for(int i = 0; i < Config.MAX_PLAYERS; i++) {
Player p = Server.playerHandler.players[i];
if(p != null) {
Client person = (Client)p;
if(person != null) {
if(person.getOutStream() != null) {
if(person.distanceToPoint(x, y) <= 25){
person.getPA().createProjectile2(x, y, offX, offY, angle, speed, gfxMoving, startHeight, endHeight, lockon, time, slope);
}
}
}
}
} | 5 |
void rotate(Node n, Side s, boolean first) {
final Side o = (s == Side.L) ? Side.R : Side.L ;
final Side nS = n.side ;
final Node
p = n.parent,
x = kidFor(n, o),
y = n,
a = kidFor(x, o),
b = kidFor(x, s),
c = kidFor(y, s) ;
if (first && heightFor(b) > heightFor(a)) {
rotate(x, o, false) ;
rotate(n, s, false) ;
return ;
}
setParent(p, x, nS) ;
setParent(x, y, s) ;
setParent(y, c, s) ;
setParent(y, b, o) ;
setParent(x, a, o) ;
flagForUpdate(x) ;
flagForUpdate(y) ;
if (verbose) {
I.say("\n\n...AFTER ROTATION:") ;
I.say(this.toString()) ;
}
} | 4 |
public static void main(String[] args) {
CodeConfiguration conf = new CodeConfiguration(null);
conf.setAvailableHardwareThreads(2);
conf.setLoggingEnabled(true);
// DON'T SET CONFIGURATION PARAMETERS BEHIND THIS LINE !!!
IEvaluator evaluator = conf.getEvaluator();
LinkedList<IEvaluationItem> evalItems = new LinkedList<IEvaluationItem>();
EnSeverity severity = evaluator.evaluate(conf, evalItems);
for(IEvaluationItem item : evalItems)
System.out.println(item);
if(severity == EnSeverity.Error){
System.out.println("aborting execution because of configuration errors");
System.exit(-1);
}
final ThreadPool pool = new ThreadPool(conf.getAvailableHardwareThreads(), conf);
final TaskBase t1 = new TaskBase(null) {
@Override
protected void runInternal() throws IOException {
synchronized (TaskBase.class) {
cnt++;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
@Override
public String getTypeName() {
return "t1";
}
};
final TaskBase t2 = new TaskBase(null) {
@Override
protected void runInternal() throws IOException {
synchronized (TaskBase.class) {
cnt++;
}
}
@Override
public String getTypeName() {
return "t2";
}
};
final TaskBase t3 = new TaskBase(null) {
@Override
protected void runInternal() throws IOException {
synchronized (TaskBase.class) {
cnt++;
}
}
@Override
public String getTypeName() {
return "t3";
}
};
TaskBase mgmtTask = new TaskBase(null) {
private volatile boolean _kill;
private volatile boolean _firstRun = true;
@Override
protected void runInternal() throws IOException {
if (_firstRun) {
addDependency(new Dependency(t3, EnRunningStates.Completed));
_firstRun = false;
}
if (cnt < 60) {
t1.reset(null);
t2.reset(null);
t3.reset(null);
pool.pushTask(t1, 0);
pool.pushTask(t2, 1);
pool.pushTask(t3, 1);
} else {
_kill = true;
}
}
@Override
protected void afterRun() {
super.afterRun();
if (_kill) {
try {
pool.stop();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} else {
reset(null);
pool.pushTask(this, 0);
}
}
@Override
public String getTypeName() {
return "mgmt";
}
};
//mgmtTask.addDependency(new Dependency(t3, EnRunningStates.Completed));
t3.addDependency(new Dependency(t1, EnRunningStates.Completed));
t3.addDependency(new Dependency(t2, EnRunningStates.Completed));
StopWatch executionTime = StopWatch.start("executionTime");
pool.pushTask(mgmtTask, 0);
// pool.work(0);
executionTime.stop();
StopWatch.printTable();
try {
Logger.getInstance().stop();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} | 8 |
private static void transform(final MethodEditor method) {
if (CounterDecorate.VERBOSE > 1) {
System.out.println("Decorating method " + method);
}
final MemberRef rcfield = new MemberRef(Type
.getType(CounterDecorate.COUNTER_MAIN), new NameAndType(
CounterDecorate.COUNTER_RCNAME, Type
.getType(CounterDecorate.COUNTER_TYPE)));
final MemberRef aufield = new MemberRef(Type
.getType(CounterDecorate.COUNTER_MAIN), new NameAndType(
CounterDecorate.COUNTER_AUNAME, Type
.getType(CounterDecorate.COUNTER_TYPE)));
final MemberRef sufield = new MemberRef(Type
.getType(CounterDecorate.COUNTER_MAIN), new NameAndType(
CounterDecorate.COUNTER_SUNAME, Type
.getType(CounterDecorate.COUNTER_TYPE)));
final ListIterator iter = method.code().listIterator();
while (iter.hasNext()) {
final Object ce = iter.next();
if (CounterDecorate.VERBOSE > 2) {
System.out.println("Examining " + ce);
}
if (ce instanceof Instruction) {
final Instruction inst = (Instruction) ce;
if (inst.opcodeClass() == Opcode.opcx_aupdate) {
iter.remove();
iter.add(new Instruction(Opcode.opcx_getstatic, aufield));
iter.next();
iter.add(new Instruction(Opcode.opcx_ldc, new Integer(1)));
iter.next();
iter.add(new Instruction(Opcode.opcx_iadd));
iter.next();
iter.add(new Instruction(Opcode.opcx_putstatic, aufield));
iter.next();
}
if (inst.opcodeClass() == Opcode.opcx_supdate) {
iter.remove();
iter.add(new Instruction(Opcode.opcx_getstatic, sufield));
iter.next();
iter.add(new Instruction(Opcode.opcx_ldc, new Integer(1)));
iter.next();
iter.add(new Instruction(Opcode.opcx_iadd));
iter.next();
iter.add(new Instruction(Opcode.opcx_putstatic, sufield));
iter.next();
} else if (inst.opcodeClass() == Opcode.opcx_rc) {
iter.remove();
iter.add(new Instruction(Opcode.opcx_getstatic, rcfield));
iter.next();
iter.add(new Instruction(Opcode.opcx_ldc, new Integer(1)));
iter.next();
iter.add(new Instruction(Opcode.opcx_iadd));
iter.next();
iter.add(new Instruction(Opcode.opcx_putstatic, rcfield));
iter.next();
}
}
}
} | 7 |
private static void displayUserAwards(BufferedReader reader, VideoStore videoStore) {
try {
System.out.println("Please enter the max number of user you would like to see in each category");
int amount = readInt(reader, 1, -1);
System.out.println();
System.out.println("*** Most Trusted Users ***");
LinkedList<User> trustedUsers = videoStore.getMostTrustedUsers(amount);
int i = 1;
for (User user : trustedUsers) {
System.out.println(i++ + ". " + user.getUsername());
}
System.out.println();
System.out.println("*** Most Useful Users ***");
LinkedList<User> usefulUsers = videoStore.getMostUsefulUsers(amount);
i = 1;
for (User user : usefulUsers) {
System.out.println(i++ + ". " + user.getUsername());
}
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
} | 3 |
public boolean isDraw() {
return theHouse.hasBust() && player.hasBust()
|| theHouse.getScore() == player.getScore();
} | 2 |
public void printPrevPopulation(){
for(String[] d : this.prevPopulation){
for(String s : d){
System.out.print(s + ", ");
}
System.out.println();
}
} | 2 |
public boolean startDragComponent(Point p) {
// disable DnD for some cases :
// - child of a compound dockable, in hidden state
// - child of a maximized compund dockable
// - maximized dockable
DockableState.Location targetLocation = target.getDockKey().getLocation();
if(targetLocation == DockableState.Location.HIDDEN) {
if(DockingUtilities.isChildOfCompoundDockable(target)) {
// nested hidden dockables cannot be drag and dropped
return false;
}
} else if(targetLocation == DockableState.Location.DOCKED) {
boolean isChildOfMaximizedContainer = false;
if(desktop != null) {
Dockable max = desktop.getMaximizedDockable();
if(max != null && max.getComponent().getParent().isAncestorOf(this)) {
isChildOfMaximizedContainer = true;
}
}
if(isChildOfMaximizedContainer) {
return false;
}
} else if(targetLocation == DockableState.Location.MAXIMIZED) {
return false;
}
// notify our listeners that drag has begun
firePropertyChange(PROPERTY_DRAGGED, false, true);
return true;
} | 8 |
public boolean isOptOut() {
synchronized (optOutLock) {
try {
// Reload the metrics file
configuration.load(getConfigFile());
} catch (IOException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
} catch (InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
}
return configuration.getBoolean("opt-out", false);
}
} | 4 |
protected void acceptSocket() {
try {
Socket socket;
socket = serverSocket.accept();
boolean equal = false;
for (EziPeer p : peers) {
if (p.getSocket().getInetAddress().equals(socket.getInetAddress())) {
equal = true;
break;
}
}
if (!equal && (socket.getInetAddress().toString().equals(socket.getLocalAddress().toString()))) {
EziPeer peer = new EziPeer(socket, distributor);
peer.sendObject(new EziInfoPacket(indexer.getEziInfoList()));
peers.add(peer);
System.out.println("Client: Accepted: " + socket.getInetAddress().toString());
}
} catch (IOException ex) {
Logger.getLogger(EziUpload.class.getName()).log(Level.SEVERE, null, ex);
}
} | 5 |
@Override
public MovementAction testAction(Creature c) {
Direction action = this.checkForDirt(c);
if (action != null){
currentDirection = action;
return Direction.convertDirToAct(action);
}
int value = -1;
int dist = -1;
Sensor s = c.getSensor();
if (currentDirection != null){
value = (int) s.getSense(currentDirection.name() + DirtBasedAgentSenseConfig.TYPE_SUFFIX).getValue();
dist = (int) s.getSense(currentDirection.name() + DirtBasedAgentSenseConfig.DISTANCE_SUFFIX).getValue();
if (value == Environment.WALL && dist == Environment.CLOSE){
currentDirection = null;
}
}
if (currentDirection != null){
return Direction.convertDirToAct(currentDirection);
}
ArrayList<Direction> possibleDir = new ArrayList<Direction>();
for (Direction d : Direction.values()){
value = (int) s.getSense(d.name() + DirtBasedAgentSenseConfig.TYPE_SUFFIX).getValue();
dist = (int) s.getSense(d.name() + DirtBasedAgentSenseConfig.DISTANCE_SUFFIX).getValue();
if (value == Environment.WALL && dist == Environment.FAR){
possibleDir.add(d);
}
}
value = r.nextInt(possibleDir.size());
currentDirection = possibleDir.get(value);
return Direction.convertDirToAct(possibleDir.get(value));
} | 8 |
public void visitCastExpr(final CastExpr expr) {
print("((" + expr.castType() + ") ");
if (expr.expr() != null) {
expr.expr().visit(this);
}
print(")");
} | 1 |
public static void main(String[] args) throws Exception {
Thread t = new Thread(new ADaemon());
t.setDaemon(true);
t.start();
TimeUnit.MILLISECONDS.sleep(100);
} | 0 |
private void addToAdjBuffer (double in) {
double lossAverage=25.0;
if (NOISY) lossAverage=60.0;
// If the buffer average percentage difference is more than lossAverage then we have lost the signal
if (absAverage()>lossAverage) {
if (display==true) {
// Tell the user how many bits were received
String line="("+Long.toString(bitsReceived)+" bits received)";
theApp.writeLine(line,Color.BLACK,theApp.italicFont);
// Add a new line after this
theApp.newLineWrite();
}
// Is there a trigger in progress
if (activeTrigger==true) {
charactersRemaining=0;
display=false;
activeTrigger=false;
}
// Set to state 1 to try and regain a signal
setState(1);
}
else {
adjBuffer[adjCounter]=in;
adjCounter++;
if (adjCounter==adjBuffer.length) adjCounter=0;
}
} | 5 |
@Override
public void move(GameBoard board, Control control) {
int[][] overall = new int[7][4];
startState = new int[7][6];
for (int n = 0; n < 7; n++) {
for (int m=0; m<6; m++) {
startState[n][m] = board.get_state(n, m);
}
}
for (int i=0; i<4; i++) {
int[] scores = eval(board, control, startState);
int tempx = indexOfMax(scores);
int tempy = control.getY(board, tempx);
if (i%2 == 0) {
} else {
startState[tempx][tempy] = 1;
}
for (int all=0; all<7; all++) {
overall[all][i] = scores[all];
}
}
int[] values = totals(overall);
if (max(values) == 0) {
AIRandom random = new AIRandom(2);
random.move(board, control);
} else {
int highestCol = indexOfMax(values);
int y = control.getY(board, highestCol); //already been checked so ignore chance of full column
board.set_state(highestCol, y, playernum);
}
} | 6 |
* @see InitStmt
*/
public void initLocals(final Collection locals) {
final LocalExpr[] t = new LocalExpr[locals.size()];
if (t.length == 0) {
return;
}
final Iterator iter = locals.iterator();
for (int i = 0; iter.hasNext(); i++) {
t[i] = (LocalExpr) iter.next();
}
addStmt(new InitStmt(t));
} | 2 |
@Override
protected Class<?> loadClass(final String name, boolean resolve) throws ClassNotFoundException {
Class<?> clazz = null;
synchronized (this) {
clazz = findLoadedClass(name);
}
if (clazz == null) {
clazz = withClassLoaders(new AbstractClassLoaderClosure<Class<?>>() {
public boolean execute(UnmodifiableURLClassLoader classLoader) {
try {
value = classLoader.loadClass(name);
} catch (ClassNotFoundException cnfe) {
// continue
}
return value != null;
}
public void onCompletion() throws ClassNotFoundException {
if (value == null) {
throw new ClassNotFoundException(name + " not found by " + this);
}
}
});
}
if (resolve) {
resolveClass(clazz);
}
return clazz;
} | 7 |
private boolean jj_2_13(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_13(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(12, xla); }
} | 1 |
public void moveOnX(int xMoveSize) {
int casePositionX = 0, casePositionYup = 0, casePositionYdown = 0;
int caseSize = GameVue.getCaseSize();
switch(xMoveSize) {
case 10 :
casePositionX = (player.getxPosition() + caseSize + xMoveSize - 1) / caseSize;
casePositionYup = player.getyPosition() / caseSize;
casePositionYdown = (player.getyPosition() + caseSize - 1) / caseSize;
if(map.isFree(casePositionX, casePositionYup) && map.isFree(casePositionX, casePositionYdown)) {
player.moveOnX(xMoveSize);
}
break;
case -10 :
casePositionX = (player.getxPosition() + xMoveSize) / caseSize;
casePositionYup = (player.getyPosition() / caseSize);
casePositionYdown = (player.getyPosition() + caseSize - 1) / caseSize;
if(map.isFree(casePositionX, casePositionYup) && map.isFree(casePositionX, casePositionYdown) && (player.getxPosition() + xMoveSize) >= 0) {
player.moveOnX(xMoveSize);
}
break;
}
} | 7 |
public CancelInvoiceResponse(Map<String, String> map, String prefix) {
if( map.containsKey(prefix + "responseEnvelope" + ".timestamp") ) {
String newPrefix = prefix + "responseEnvelope" + '.';
this.responseEnvelope = new ResponseEnvelope(map, newPrefix);
}
if( map.containsKey(prefix + "invoiceID") ) {
this.invoiceID = map.get(prefix + "invoiceID");
}
if( map.containsKey(prefix + "invoiceNumber") ) {
this.invoiceNumber = map.get(prefix + "invoiceNumber");
}
if( map.containsKey(prefix + "invoiceURL") ) {
this.invoiceURL = map.get(prefix + "invoiceURL");
}
for(int i=0; i<10; i++) {
if( map.containsKey(prefix + "error" + '(' + i + ')'+ ".errorId") ) {
String newPrefix = prefix + "error" + '(' + i + ')' + '.';
this.error.add(new ErrorData(map, newPrefix));
}
}
} | 6 |
private static void validerReponse(Reponse reponse) throws ChampInvalideException, ChampVideException {
if (reponse.getMessage() == null || reponse.getMessage().isEmpty())
throw new ChampVideException("La réponse ne peut être vide");
if (reponse.getSujet() == null)
throw new ChampVideException("Une réponse ne peut pas ne pas avoir de sujet");
if (!reponse.getSujet().peutRepondre(reponse.getAuteur()))
throw new InterditException("Vous n'avez pas les droits requis pour publier une réponse sur ce sujet");
} | 4 |
private Connection getConnection() {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
Utilities.outputError("Could not find sqlite drivers");
return null;
}
try {
return DriverManager.getConnection("jdbc:sqlite:" + m_databaseFile.getAbsolutePath());
} catch (SQLException e) {
return null;
}
} | 2 |
public void replaceFood() {
for (int[] i : foodSpawnCells) {
getCell(i).setFood(5);
}
} | 1 |
protected Game(String cfgPath) {
try {
introduceParameterName(getClass(), "TIME_LIMIT");
setParameter("TIME_LIMIT", "0"); //infinite turn time
if(cfgPath == null) {
board = loadConfigFile(null);
if(board == null) //if a Board was not created by loadConfigFile when you passed loadConfigFile 'null'
IllegalMessageException.badInput("Board was not Loaded");
board.setGame(this);
}
else {
BufferedReader in = new BufferedReader(new InputStreamReader(Game.class.getResourceAsStream(cfgPath)));
board = loadConfigFile(in);
if(board == null) IllegalMessageException.badInput("Board was not Loaded");
board.setGame(this);
postLoadConfig(in);
}
for(GameEventListener gel : globalListeners)
registerEventListener(gel);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | 6 |
public static void setBreedingAge(int newBREEDING_AGE)
{
BREEDING_AGE = newBREEDING_AGE;
} | 0 |
public org.omg.CORBA.portable.OutputStream _invoke (String $method,
org.omg.CORBA.portable.InputStream in,
org.omg.CORBA.portable.ResponseHandler $rh)
{
org.omg.CORBA.portable.OutputStream out = null;
java.lang.Integer __method = (java.lang.Integer)_methods.get ($method);
if (__method == null)
throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
switch (__method.intValue ())
{
case 0: // HelloCorba/Hello/sayHello
{
String $result = null;
$result = this.sayHello ();
out = $rh.createReply();
out.write_string ($result);
break;
}
case 1: // HelloCorba/Hello/shutdown
{
this.shutdown ();
out = $rh.createReply();
break;
}
default:
throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
}
return out;
} // _invoke | 3 |
private void closeButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_closeButtonActionPerformed
{//GEN-HEADEREND:event_closeButtonActionPerformed
try
{
echoClient.close();
} catch (IOException ex)
{
Logger.getLogger(ChatGui.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_closeButtonActionPerformed | 1 |
public static boolean isValidXML(String path) throws IOException {
File f = new File(path);
if (f.exists() && !f.isDirectory()) {
// check if XML
String extension = "";
int i = path.lastIndexOf('.');
if (i > 0) {
extension = path.substring(i + 1);
if (extension.equalsIgnoreCase("XML")) {
return true;
}
}
return false;
} else {
return false;
}
} | 4 |
private boolean uhattuAlhaalta(int pelaajaNumero, int x, int y) {
int i = 1;
while(x+i < 8 && kentta[x+i][y].onTyhja()) i++;
if(x+i == 8) return false;
if(kentta[x+i][y].getNappula().omistajanPelinumero() != pelaajaNumero) {
if(i == 1 && kentta[x+i][y].getNappula().getClass() == new Kuningas().getClass()) return true;
if(kentta[x+i][y].getNappula().getClass() == new Kuningatar().getClass()) return true;
if(kentta[x+i][y].getNappula().getClass() == new Torni().getClass()) return true;
}
return false;
} | 8 |
public Node<Integer> mergeSort(Node<Integer> head) {
if (head == null)
return null;
if (head.next == null)
return head;
Node<Integer> slow = head;
Node<Integer> fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
Node<Integer> sec = slow.next;
slow.next = null;
return merge(mergeSort(head), mergeSort(sec));
} | 4 |
public void join() {
cleanUp();
super.join();
} | 0 |
@Override
public String encode(Response response) throws EncoderException {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
return "";
}
if (response.getResponse() == null)
return "";
char[] charArray = response.getResponse().toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
} | 5 |
public void setObjectShape(Object o){
objectShape = o;
} | 0 |
* @param options
* @return StringWrapper
*/
public static StringWrapper shellCommand(Stella_Object command, Cons options) {
if (((Boolean)(OntosaurusUtil.$BLOCK_SHELL_COMMANDp$.get())).booleanValue()) {
throw ((StellaException)(StellaException.newStellaException("Execution of `shell-command' is blocked in this context").fillInStackTrace()));
}
{ PropertyList theoptions = Logic.parseLogicCommandOptions(options, Cons.list$(Cons.cons(OntosaurusUtil.KWD_DIRECTORY, Cons.cons(OntosaurusUtil.SGT_STELLA_STRING, Cons.cons(OntosaurusUtil.KWD_INPUT, Cons.cons(OntosaurusUtil.SGT_STELLA_STRING, Cons.cons(Stella.NIL, Stella.NIL)))))), true, false);
String directory = StringWrapper.unwrapString(((StringWrapper)(theoptions.lookup(OntosaurusUtil.KWD_DIRECTORY))));
String inputstring = StringWrapper.unwrapString(((StringWrapper)(theoptions.lookup(OntosaurusUtil.KWD_INPUT))));
InputStringStream inputstream = ((!Stella.blankStringP(inputstring)) ? InputStringStream.newInputStringStream(inputstring) : ((InputStringStream)(null)));
OutputStringStream outputstream = OutputStringStream.newOutputStringStream();
OutputStringStream errorstream = OutputStringStream.newOutputStringStream();
int exit = OntosaurusUtil.executeShellCommand(command, directory, inputstream, outputstream, errorstream);
String output = outputstream.theStringReader();
String error = errorstream.theStringReader();
if (inputstream != null) {
Stream.closeStream(inputstream);
}
Stream.closeStream(outputstream);
Stream.closeStream(errorstream);
if (!Stella.blankStringP(error)) {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("shell-command: `" + error + "'");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
if (!(exit == 0)) {
{ OutputStringStream stream001 = OutputStringStream.newOutputStringStream();
stream001.nativeStream.print("shell-command: non-zero exit status=`" + exit + "'");
throw ((StellaException)(StellaException.newStellaException(stream001.theStringReader()).fillInStackTrace()));
}
}
if (Stella.blankStringP(output)) {
return (null);
}
else {
return (StringWrapper.wrapString(output));
}
}
} | 6 |
private void mapFileReAccessRequirements( HypertextAccessFile htaccess,
URI requestedURI,
File requestedFile,
Map<String,BasicType> optionalReturnSettings,
Environment<String,BasicType> session,
String authType ) {
// Finally: store some session data for the case the client tries to access the file again later?
if( authType.equalsIgnoreCase("Basic") ) {
// NOOP (Basic Authentication does not require any additional data to be stored)
} else if( authType.equalsIgnoreCase("Digest") ) {
// The nonce should be generated using a secret salt value.
// Unfortunately we do not know the username at this point of authentication, so cannot lookup the
// salt from the AuthUserFile.
String nonce_salt =
Long.toString( System.currentTimeMillis() ) + ":" +
requestedURI.getPath() + ":" +
authType + ":" +
// session.getSessionID() +
Integer.toString( (int)(Math.random()*Integer.MAX_VALUE) );
String nonce = null;
try {
byte[] nonce_bytes = MD5.md5( nonce_salt.getBytes() );
nonce = CustomUtil.bytes2hexString( nonce_bytes );
this.getHTTPHandler().getLogger().log( Level.INFO,
getClass().getName() + ".accessGranted(...)",
"Using nounce salt value: " + nonce_salt + ", generated nonce=" + nonce );
} catch( java.security.NoSuchAlgorithmException e ) {
String tmpTS = Long.toString( System.currentTimeMillis() );
nonce = CustomUtil.bytes2hexString( tmpTS.getBytes() );
this.getHTTPHandler().getLogger().log( Level.WARNING,
getClass().getName() + ".accessGranted(...)",
"Failed to encode nonce_salt value; using a timestamp based nonce instead. nonce=" + nonce );
}
String domain = requestedURI.getPath();
String algorithm = "MD5"; // Fetch from htaccess?!
// These settins will be sent to the client
optionalReturnSettings.put( Constants.KEY_AUTHENTICATION_NONCE, new BasicStringType( nonce ) );
optionalReturnSettings.put( Constants.KEY_AUTHENTICATION_DOMAIN, new BasicStringType( domain ) );
optionalReturnSettings.put( Constants.KEY_AUTHENTICATION_ALGORITHM, new BasicStringType( algorithm ) );
// These settings will be internally stored for later verification
session.put( Constants.KEY_AUTHENTICATION_NONCE, new BasicStringType( nonce ) );
session.put( Constants.KEY_AUTHENTICATION_DOMAIN, new BasicStringType( domain) );
session.put( Constants.KEY_AUTHENTICATION_ALGORITHM, new BasicStringType( algorithm ) );
} else {
// Unknown auth type. Nothing to store (unexpected case)
}
} | 3 |
public static Header createOAuthHeader(Token token) {
return new BasicHeader(AUTH.WWW_AUTH_RESP, "OAuth " +
(token == null || !token.valid() ? "invalidated" : token.access));
} | 2 |
public double removeMax() {
if ( _heap.size() == 0 )
return -1.0;
else
_size--;
//store root value for return at end of fxn
double retVal = peekMax();
//store val about to be swapped into root
double foo = _heap.get( _heap.size() - 1);
//swap last (rightmost, deepest) leaf with root
swap( 0, _heap.size() - 1 );
//lop off last leaf
_heap.remove( _heap.size() - 1);
// walk the now-out-of-place root node down the tree...
int pos = 0;
int maxChildPos;
while( pos < _heap.size() ) {
//choose child w/ max value, or check for child
maxChildPos = maxChildPos(pos);
//if no children, then i've walked far enough
if ( maxChildPos == -1 )
break;
//if i am less than my least child, then i've walked far enough
else if ( foo >= _heap.get(maxChildPos) )
break;
//if i am < max child, swap with that child
else {
swap( pos, maxChildPos );
pos = maxChildPos;
}
}
//return removed value
return retVal;
}//O(logn) | 4 |
public void testToStandardSeconds() {
Period test = new Period(0, 0, 0, 0, 0, 0, 7, 8);
assertEquals(7, test.toStandardSeconds().getSeconds());
test = new Period(0, 0, 0, 0, 0, 1, 3, 0);
assertEquals(63, test.toStandardSeconds().getSeconds());
test = new Period(0, 0, 0, 0, 0, 0, 0, 1000);
assertEquals(1, test.toStandardSeconds().getSeconds());
test = new Period(0, 0, 0, 0, 0, 0, Integer.MAX_VALUE, 0);
assertEquals(Integer.MAX_VALUE, test.toStandardSeconds().getSeconds());
test = new Period(0, 0, 0, 0, 0, 0, 20, Integer.MAX_VALUE);
long expected = 20;
expected += ((long) Integer.MAX_VALUE) / DateTimeConstants.MILLIS_PER_SECOND;
assertEquals(expected, test.toStandardSeconds().getSeconds());
test = new Period(0, 0, 0, 0, 0, 0, Integer.MAX_VALUE, 1000);
try {
test.toStandardSeconds();
fail();
} catch (ArithmeticException ex) {}
} | 1 |
private int bruteEst(GameState state, Card card) {
int est = 0;
//We see if the brute will actually knock somebody out or not
for(Player p : state.getPlayerList())
{
if(!p.getFaction().equals(card.getFaction()))
{
for(Card c : p.getHand())
{
if(c.getValue() >= card.getValue())
est++;
else
est--;
}
}
}
return est;
} | 4 |
private void handleInputFile(Object input)
{
Configuration[] configs = null;
AutomatonSimulator simulator = getSimulator(automaton);
/* if (input instanceof InputBox)
{
InputBox tt=(InputBox) input;
if (getObject() instanceof TuringMachine)
tt.addSimulator(automaton, simulator, true);
else
tt.addSimulator(automaton, simulator, false);
return;
}*/
if (input == null)
return;
// Get the initial configurations.
if (getObject() instanceof TuringMachine) {
String[] s = (String[]) input;
configs = ((TMSimulator) simulator).getInitialConfigurations(s);
} else {
String s = (String) input;
configs = simulator.getInitialConfigurations(s);
}
handleInteraction(automaton, simulator, configs, input);
} | 2 |
public void hit(Player player) {
if (player.getHand().size() < 5 && deck.size() > 0) {
deck.get(deck.size() - 1).flip();
player.getHand().add(deck.get(deck.size() - 1));
deck.remove(deck.size() - 1);
player.refreshImage();
refreshImage();
}
} | 2 |
public static void forceFocusToAccept() {
KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
Component focus = focusManager.getPermanentFocusOwner();
if (focus == null) {
focus = focusManager.getFocusOwner();
}
if (focus != null) {
FocusListener[] listeners = focus.getListeners(FocusListener.class);
FocusEvent event = new FocusEvent(focus, FocusEvent.FOCUS_LOST, false, null);
for (FocusListener listener : listeners) {
listener.focusLost(event);
}
event = new FocusEvent(focus, FocusEvent.FOCUS_GAINED, false, null);
for (FocusListener listener : listeners) {
listener.focusGained(event);
}
}
} | 4 |
public DefaultTempFile(String tempdir) throws IOException {
file = File.createTempFile("NanoHTTPD-", "", new File(tempdir));
fstream = new FileOutputStream(file);
} | 0 |
public void createTable(byte[] table)
{
boolean isSystemTable = ForemanConstants.TableIdentifier.getIdentifierFromName(table) != null;
boolean tableExists = tableExists(table);
if (!tableExists && !isSystemTable)
{
instance.hset(ForemanConstants.TableIdentifier.TABLE.getId(), table, ForemanConstants.TableIdentifierPart.CREATED.getId());
}
else if (isSystemTable)
{
log.warn("Create table ignored. Table {} is a reserved system table", new String(table));
}
else if (tableExists)
{
log.warn("Create table ignored. Table {} exists", new String(table));
}
} | 4 |
public void mergeUnsortedWithSortedList(ArrayList<node> unsorted,ArrayList<node> sorted){
if(unsorted.size()>0){
while(unsorted.size()>0){
for(int i = 0;i<=sorted.size();i++){
if(i==sorted.size()){
sorted.add(unsorted.get(0));
unsorted.remove(0);
break;
}
else if(sorted.get(i).totalCost>unsorted.get(0).totalCost){
sorted.add(i,unsorted.get(0));
unsorted.remove(0);
break;
}
}
}
}
} | 5 |
public static JulianDate jauCal2jd(int iy, int im, int id) throws JSOFAIllegalParameter
{
int ly, my;
long iypmy;
double djm0, djm;
/* Earliest year allowed (4800BC) */
final int IYMIN = -4799;
/* Month lengths in days */
final int mtab[]
= {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
/* Validate year and month. */
if (iy < IYMIN) throw new JSOFAIllegalParameter("bad year", -1);
if (im < 1 || im > 12) throw new JSOFAIllegalParameter("bad month", -2);
/* If February in a leap year, 1, otherwise 0. */
ly = ((im == 2) &&(iy%4 == 0) && (iy%100 != 0 || (iy%400 == 0)))?1:0;
/* Validate day, taking into account leap years. */
if ( (id < 1) || (id > (mtab[im-1] + ly))) {
}
/* Return result. */
my = (im - 14) / 12;
iypmy = (long) (iy + my);
djm0 = DJM0;
djm = (double)((1461L * (iypmy + 4800L)) / 4L
+ (367L * (long) (im - 2 - 12 * my)) / 12L
- (3L * ((iypmy + 4900L) / 100L)) / 4L
+ (long) id - 2432076L);
/* Return status. */
return new JulianDate(djm0, djm);
} | 9 |
public Iterator<ResultSet> getIteratorFromQuery(String query)
{
Iterator<ResultSet> ret = null;
Connection connection = null;
Statement statement = null;
try
{
Class.forName(driver);
connection = DriverManager.getConnection(url, username, passwd);
statement = connection.createStatement();
final ResultSet result = statement.executeQuery(query);
ret = new Iterator(){
Object nextObject = null;
public boolean hasNext() {
try {
if (nextObject == null) nextObject = result.next();
} catch (SQLException e) {
e.printStackTrace();
}
return nextObject != null;
}
public Object next() {
if ((nextObject == null) && (!hasNext()))
throw new NoSuchElementException();
Object ret = nextObject;
nextObject = null;
return ret;
}
public void remove() {
throw new UnsupportedOperationException("This iteractor has no remove() method.");
}
};
statement.close();
statement = null;
}
catch (Exception e)
{
System.out.println(e);
}
finally
{
if (statement != null)
{
try
{
statement.close();
}
catch (SQLException e)
{
System.out.println(e);
}
statement = null;
}
if (connection != null)
{
try
{
connection.close();
}
catch (SQLException e)
{
System.out.println(e);
}
connection = null;
}
}
return ret;
} | 9 |
private void GestionSelection() {
// Initialisation
boolean trouve = false;
ListIterator<Forme> it = model.getCalqueCourant().listIterator();
while (it.hasNext())
it.next(); // On déroule la liste pour commencer par la fin
// Vérification de la touche contrôle
if ( !model.getControlPressed() ) {
model.deselectionnerToutesLesFormes();
}
// Parcours de la liste à la recherche d'une forme correspondante si
// elle n'est pas déjà trouvée
while (it.hasPrevious() && !trouve) {
Forme f = it.previous();
// Une forme contient les coordonnées du clic
if (f.contains(this.pointDebut)) {
// Sélection/Désélection
if (f.isSelected()) {
model.deselectionner(f);
} else {
model.selectionner(f);
}
// Si le curseur est sur un marqueur de la forme ou non
if ( f.isSelected() && f.containsPointDeSelection(this.pointDebut)) {
this.resizing = f.getMarqueurs(this.pointDebut);
} else {
this.dragging = true;
}
// Définition de la modification de forme...
this.modifiedForme = f;
// Fin de boucle
trouve = true;
}
}
} | 8 |
public WikiPagePath getFullPath(WikiPage suiteSetup) {
if (suiteSetup.getName().equals(SuiteResponder.SUITE_SETUP_NAME)) {
return new WikiPagePath (SuiteResponder.SUITE_SETUP_NAME);
}
if (suiteSetup.getName().equals(SuiteResponder.SUITE_TEARDOWN_NAME)) {
return new WikiPagePath (SuiteResponder.SUITE_TEARDOWN_NAME);
}
if (suiteSetup.getName().equals("SetUp")) {
return new WikiPagePath ("SetUp");
}
if (suiteSetup.getName().equals("TearDown")) {
return new WikiPagePath ("TearDown");
}
return new WikiPagePath ("UNKNOWN");
} | 4 |
public Dimension preferredLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int totalWidth = maxWidth - insets.left - insets.right;
int height = 0;
int width = 0;
int maxHeightOfThisLine = 0;
int componentCount = parent.getComponentCount();
for(int i=0; i<componentCount; i++) {
Component c = parent.getComponent(i);
Dimension d = c.getPreferredSize();
if(width + d.width < totalWidth || width == 0) { // also accept any first component on this line
width += d.width + hGap;
maxHeightOfThisLine = Math.max(maxHeightOfThisLine, d.height);
} else { // this component must go onto the next line
if(this.exactLineHeight > 0) {
maxHeightOfThisLine = exactLineHeight;
}
height += maxHeightOfThisLine + vGap;
maxHeightOfThisLine = d.height;
width = d.width + hGap;
}
}
height += maxHeightOfThisLine;
return new Dimension(maxWidth, insets.top + insets.bottom + height);
}
} | 4 |
@Test
public void EnsureLeadingSlashIsRemoved() {
String path = "/x/y";
String newpath = Path.trimSlashes(path);
assertEquals("x/y", newpath);
} | 0 |
public final void setBounds(float var1, float var2, float var3, int var4, int var5, int var6, float var7) {
this.vertices = new Vertex[8];
this.quads = new TexturedQuad[6];
float var8 = var1 + (float)var4;
float var9 = var2 + (float)var5;
float var10 = var3 + (float)var6;
var1 -= var7;
var2 -= var7;
var3 -= var7;
var8 += var7;
var9 += var7;
var10 += var7;
if(this.mirror) {
var7 = var8;
var8 = var1;
var1 = var7;
}
Vertex var20 = new Vertex(var1, var2, var3, 0.0F, 0.0F);
Vertex var11 = new Vertex(var8, var2, var3, 0.0F, 8.0F);
Vertex var12 = new Vertex(var8, var9, var3, 8.0F, 8.0F);
Vertex var18 = new Vertex(var1, var9, var3, 8.0F, 0.0F);
Vertex var13 = new Vertex(var1, var2, var10, 0.0F, 0.0F);
Vertex var15 = new Vertex(var8, var2, var10, 0.0F, 8.0F);
Vertex var21 = new Vertex(var8, var9, var10, 8.0F, 8.0F);
Vertex var14 = new Vertex(var1, var9, var10, 8.0F, 0.0F);
this.vertices[0] = var20;
this.vertices[1] = var11;
this.vertices[2] = var12;
this.vertices[3] = var18;
this.vertices[4] = var13;
this.vertices[5] = var15;
this.vertices[6] = var21;
this.vertices[7] = var14;
this.quads[0] = new TexturedQuad(new Vertex[]{var15, var11, var12, var21}, this.u + var6 + var4, this.v + var6, this.u + var6 + var4 + var6, this.v + var6 + var5);
this.quads[1] = new TexturedQuad(new Vertex[]{var20, var13, var14, var18}, this.u, this.v + var6, this.u + var6, this.v + var6 + var5);
this.quads[2] = new TexturedQuad(new Vertex[]{var15, var13, var20, var11}, this.u + var6, this.v, this.u + var6 + var4, this.v + var6);
this.quads[3] = new TexturedQuad(new Vertex[]{var12, var18, var14, var21}, this.u + var6 + var4, this.v, this.u + var6 + var4 + var4, this.v + var6);
this.quads[4] = new TexturedQuad(new Vertex[]{var11, var20, var18, var12}, this.u + var6, this.v + var6, this.u + var6 + var4, this.v + var6 + var5);
this.quads[5] = new TexturedQuad(new Vertex[]{var13, var15, var21, var14}, this.u + var6 + var4 + var6, this.v + var6, this.u + var6 + var4 + var6 + var4, this.v + var6 + var5);
if(this.mirror) {
for(int var16 = 0; var16 < this.quads.length; ++var16) {
TexturedQuad var17;
Vertex[] var19 = new Vertex[(var17 = this.quads[var16]).vertices.length];
for(var4 = 0; var4 < var17.vertices.length; ++var4) {
var19[var4] = var17.vertices[var17.vertices.length - var4 - 1];
}
var17.vertices = var19;
}
}
} | 4 |
public synchronized Request getNextBlockRequest(Peer peer, int[] piecesFrequencies){
RequestExtended recoveredRequest = recoverRequest(peer);
if (recoveredRequest != null){
associateRequest(peer,recoveredRequest);
return recoveredRequest;
}
Integer pieceIndex = peerPiece.get(peer);
// null if not downloading, completing if piece is completing
if (pieceIndex==null || torrent.getTorrentDisk().isCompleted(pieceIndex) || completingPieces.contains(pieceIndex)){
peerPiece.remove(peer);
// get next piece
pieceIndex = choosePiece(peer,piecesFrequencies);
if (Torrent.verbose)
torrent.addEvent(new Event(this,"chosen piece " + pieceIndex,Level.FINER));
// no more pieces to download
if (pieceIndex == null)
return endGameBlockRequest(peer);
// requested piece pieceIndex to peer
peerPiece.put(peer,pieceIndex);
}
int firstMissingByte = getFirstMissingByte(pieceIndex);
if (firstMissingByte >= torrent.getTorrentDisk().getLength(pieceIndex))
throw new AssertionError("this piece is already completely requested, we should not be here.");
int pieceMissingBytes = torrent.getTorrentDisk().getLength(pieceIndex) - firstMissingByte;
int requestBlockLength = blockLength;
// we have all but the last block
if (pieceMissingBytes <= blockLength){
completingPieces.add(pieceIndex);
peerPiece.remove(peer);
requestBlockLength = pieceMissingBytes;
if (Torrent.verbose)
torrent.addEvent(new Event(this,"request piece completed " + pieceIndex + " " + firstMissingByte + " " + requestBlockLength,Level.FINER));
}
RequestExtended re = new RequestExtended(pieceIndex,firstMissingByte,requestBlockLength);
associateRequest(peer,re);
return re;
} | 9 |
private void sequentialTraverse(FineNode<T> curr, Operation<T> operation) {
if (curr != null && curr == root && curr.getLeft() == null && curr.getRight() == null) {
operation.empty(curr);
return;
}
if (curr == null || curr.getValue() == null) {
return;
}
operation.start(curr);
sequentialTraverse(curr.getLeft(), operation);
operation.middle(curr);
sequentialTraverse(curr.getRight(), operation);
operation.end(curr);
} | 6 |
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
jMenuItem2 = new javax.swing.JMenuItem();
jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
jRadioButtonMenuItem1 = new javax.swing.JRadioButtonMenuItem();
jPopupMenu1 = new javax.swing.JPopupMenu();
roomId = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jMenu1.setText("jMenu1");
jMenu2.setText("jMenu2");
jMenuItem1.setText("jMenuItem1");
jMenu3.setText("jMenu3");
jMenuItem2.setText("jMenuItem2");
jCheckBoxMenuItem1.setSelected(true);
jCheckBoxMenuItem1.setText("jCheckBoxMenuItem1");
jRadioButtonMenuItem1.setSelected(true);
jRadioButtonMenuItem1.setText("jRadioButtonMenuItem1");
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("房間名稱");
roomId.setText("請輸入房名");
roomId.setToolTipText("");
roomId.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
roomId.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
roomIdKeyPressed(evt);
}
});
jButton1.setText("確定");
jButton1.setToolTipText("");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(roomId, javax.swing.GroupLayout.DEFAULT_SIZE, 291, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(roomId, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
getAccessibleContext().setAccessibleDescription("");
pack();
}// </editor-fold>//GEN-END:initComponents | 0 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result
+ ((endereco == null) ? 0 : endereco.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
return result;
} | 4 |
private void countEdges() {
int edges = 0;
if (getState() == States.ARR_ADJ)
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
if (arr_adj[i][j] != 0)
edges++;
this.M = edges;
} | 4 |
private void readData() {
byte[] timeBuffer = new byte[8];
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
ByteArrayInputStream inStream = new ByteArrayInputStream(
outStream.toByteArray());
DataInputStream reader = new DataInputStream(inStream);
try {
for (int i = 0; i < 10; i++) {
int scripCode = reader.readInt();
reader.read(timeBuffer);
String time = new String(timeBuffer);
double bid = reader.readDouble();
double offer = reader.readDouble();
double high = reader.readDouble();
double low = reader.readDouble();
long volume = reader.readLong();
formatter.format("ScripCode: %2d" + "\tTime: %s "
+ "\tBid:$ %05.2f" + "\tOffer:$ %05.2f"
+ "\tHigh:$ %05.2f" + "\tLow:$ %05.2f"
+ "\tVolume: %d ", scripCode, time, bid, offer, high,
low, volume);
System.out.println(sb);
sb.delete(0, sb.length());
}
} catch (Exception e) {
System.out.println("Error while reading data");
}
} | 2 |
private void handleBidSubmission(TACMessage msg) {
Bid bid = (Bid) msg.getUserData();
int status = NO_ERROR;
while (msg.nextTag()) {
if (msg.isTag("bidID")) {
int id = msg.getValueAsInt(Bid.NO_ID);
bid.setID(id);
} else if (msg.isTag("bidHash")) {
String hash = msg.getValue();
bid.setBidHash(hash);
} else if (msg.isTag("rejectReason")) {
int reject = msg.getValueAsInt(Bid.NOT_REJECTED);
bid.setRejectReason(reject);
if (reject != Bid.NOT_REJECTED) {
bid.setProcessingState(Bid.REJECTED);
}
} else if (msg.isTag("commandStatus")) {
status = mapCommandStatus(msg.getValueAsInt(NO_ERROR));
}
}
if (bid.isRejected()) {
// reset the active bid!
revertBid(bid, NO_ERROR);
} else if (status == AUCTION_CLOSED) {
// reset the active bid!
revertBid(bid, status);
// Let the quote close the auction later!
} else if (status != NO_ERROR) {
fatalError("Can not handle bid submission: "
+ commandStatusToString(status), 5000);
} else {
// Request Bid info
TACMessage msg2 = new TACMessage("bidInfo");
msg2.setParameter("bidID", bid.getID());
msg2.setUserData(bid);
sendMessage(msg2, this);
// Should not do this until bidinfo arrives where the bid is
// hopefully no longer preliminary. (For backward compability!)
// agent.bidUpdated(bid);
}
} | 9 |
public void driver() {
System.out.println("benz drive");
} | 0 |
@SuppressWarnings("unchecked")
public void saveMessage(HttpServletRequest request, String msg) {
List<String> messages = (List<String>) request.getSession().getAttribute(MESSAGES_KEY);
if (messages == null) {
messages = new ArrayList<String>();
}
messages.add(msg);
request.getSession().setAttribute(MESSAGES_KEY, messages);
} | 1 |
public int getMaxSubArrayProduct(int[] a) throws IllegalArgumentException {
if (a == null || a.length == 0) { throw new IllegalArgumentException(); }
int _MAX_EndingHere = 1;
int _MIN_EndingHere = 1;
int maxSoFar = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
/*
* If current element is positive, update the maxEndingHere
* variable; update minEndingHere only if it is negative
*/
if (a[i] > 0) {
_MAX_EndingHere = _MAX_EndingHere * a[i];
_MIN_EndingHere = _MIN_EndingHere * a[i];
if (_MIN_EndingHere < 1) {
_MIN_EndingHere = 1;
}
}else {
if (a[i] == 0) {
_MAX_EndingHere = 1;
_MIN_EndingHere = 1;
}else {
int temp = _MAX_EndingHere;
_MAX_EndingHere = Math.max(_MIN_EndingHere * a[i], 1);
_MIN_EndingHere = temp * a[i];
}
}
maxSoFar = Math.max(maxSoFar, _MAX_EndingHere);
}
return maxSoFar;
} | 6 |
public void updateAll(){
try{
DocumentBuilderFactory docFac = DocumentBuilderFactory.newInstance();
DocumentBuilder docB= docFac.newDocumentBuilder();
Document doc = docB.parse("/Users/djdrty/Desktop/KaneClub/players.xml");
Node players = doc.getFirstChild();
NodeList playersList = doc.getElementsByTagName("Player");
for(int i = 0; i < playersList.getLength(); i++){
boolean changed = false;
Node thisPlayer = playersList.item(i);
Element element = (Element) thisPlayer;
NodeList pList = thisPlayer.getChildNodes();
for(int j = 0; j < pList.getLength(); j++){
Node stuff = pList.item(j);
if("up_to_date".equals(stuff.getNodeName())){
stuff.setTextContent(Boolean.toString(false));
}
if("weeks_behind".equals(stuff.getNodeName())){
int hold = Integer.parseInt(getTagValue("weeks_behind", element));
stuff.setTextContent(Integer.toString(hold+1));
}
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("/Users/djdrty/Desktop/KaneClub/players.xml"));
transformer.transform(source, result);
}
catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
} | 8 |
@Override
public String getDescription(Hero hero) {
String base = String.format("Move through a wall of blocks.");
StringBuilder description = new StringBuilder( base );
//Additional descriptive-ness of skill settings
int initCD = SkillConfigManager.getUseSetting(hero, this, Setting.COOLDOWN.node(), 0, false);
int redCD = SkillConfigManager.getUseSetting(hero, this, Setting.COOLDOWN_REDUCE.node(), 0, false) * hero.getSkillLevel(this);
int CD = (initCD - redCD) / 1000;
if (CD > 0) {
description.append( " CD:"+ CD + "s" );
}
int initM = SkillConfigManager.getUseSetting(hero, this, Setting.MANA.node(), 0, false);
int redM = SkillConfigManager.getUseSetting(hero, this, Setting.MANA_REDUCE.node(), 0, false)* hero.getSkillLevel(this);
int manaUse = initM - redM;
if (manaUse > 0) {
description.append(" M:"+manaUse);
}
int initHP = SkillConfigManager.getUseSetting(hero, this, Setting.HEALTH_COST, 0, false);
int redHP = SkillConfigManager.getUseSetting(hero, this, Setting.HEALTH_COST_REDUCE, 0, true) * hero.getSkillLevel(this);
int HPCost = initHP - redHP;
if (HPCost > 0) {
description.append(" HP:"+HPCost);
}
int initF = SkillConfigManager.getUseSetting(hero, this, Setting.STAMINA.node(), 0, false);
int redF = SkillConfigManager.getUseSetting(hero, this, Setting.STAMINA_REDUCE.node(), 0, false) * hero.getSkillLevel(this);
int foodCost = initF - redF;
if (foodCost > 0) {
description.append(" FP:"+foodCost);
}
int delay = SkillConfigManager.getUseSetting(hero, this, Setting.DELAY.node(), 0, false) / 1000;
if (delay > 0) {
description.append(" W:"+delay);
}
int exp = SkillConfigManager.getUseSetting(hero, this, Setting.EXP.node(), 0, false);
if (exp > 0) {
description.append(" XP:"+exp);
}
return description.toString();
} | 6 |
@Override
public void actionPerformed(ActionEvent e)
{
if ("bStartCasual".equals(e.getActionCommand()))
{
Main.frameMM.setVisible(false);
Main.currentGame = new OneFlower(GameMode.CASUAL);
Main.currentGame.start();
}
else if ("bStartHard".equals(e.getActionCommand()))
{
Main.frameMM.setVisible(false);
Main.currentGame = new OneFlower(GameMode.HARD);
Main.currentGame.start();
}
else if ("bAbout".equals(e.getActionCommand()))
{
JOptionPane.showMessageDialog(new JFrame(), Helper.arrayToString("\n", Refs.ABOUT), "About", JOptionPane.INFORMATION_MESSAGE);
}
else if ("bExit".equals(e.getActionCommand()))
{
System.exit(0);
}
} | 4 |
@Override
public List<Cotacao> filterGrid(String filter) {
List<Cotacao> lista = service.findAll();
if ("".equals(filter) || filter.equals("*")) {
return lista;
}
List<Cotacao> filtro = new ArrayList<Cotacao>();
for (Cotacao cotacao : lista) {
if (cotacao.solicitante.toUpperCase().startsWith(filter.toUpperCase())) {
filtro.add(cotacao);
}
}
return filtro;
} | 4 |
public Date getDeclareDate() {
return declareDate;
} | 0 |
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.