text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public void calculateLineStatistics() {
if (codeLineCount == 0) {
for (int i = 1; i < lines.size(); i++)
if (lines.get(i) != null) {
codeLineCount++;
if (lines.get(i) > 0)
codeLinesCoveredCount++;
}
}
} | 4 |
public static double estimateCardinalityOfExtension(NamedDescription description) {
if ((description == null) ||
(!NamedDescription.relationSupportsExtensionP(description))) {
return (Stella.NULL_FLOAT);
}
{ int estimate = Description.accessObservedCardinality(description);
if ((estimate == Stella.NULL_INTEGER) &&
(description.extension != null)) {
estimate = description.extension.estimatedLength();
}
if (estimate == Stella.NULL_INTEGER) {
estimate = 0;
}
return (((double)(Stella.integer_max(estimate, (NamedDescription.classDescriptionP(description) ? ((int)(Logic.ESTIMATED_SIZE_OF_CLASS_EXTENSION)) : ((int)(Logic.ESTIMATED_NUMBER_OF_PREDICATE_BINDINGS * Logic.ESTIMATED_NUMBER_OF_PREDICATE_BINDINGS * Logic.ESTIMATED_NUMBER_OF_PREDICATE_BINDINGS)))))));
}
} | 6 |
private static int[] merge(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
int indexA = 0, indexB = 0;
for (int indexC = 0; indexC < c.length; indexC++) {
if (indexA < a.length && (indexB == b.length || a[indexA] <= b[indexB]))
c[indexC] = a[indexA++];
else if (indexB < b.length && (indexA == a.length || a[indexA] > b[indexB]))
c[indexC] = b[indexB++];
}
return c;
} | 7 |
static final private AbsValueNode possible_infixed_expression() throws ParseException, CompilationException {
Token t;
AbsValueNode v;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case NUMBER:
t = jj_consume_token(NUMBER);
v = infixed_expression(new NumberVNode(t.image,currentLine));
{if (true) return v;}
break;
case TOKENWORD:
t = jj_consume_token(TOKENWORD);
v = infixed_expression(new ThingVNode(t.image,currentLine));
{if (true) return v;}
break;
default:
jj_la1[14] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
} | 5 |
private void createEnderPortal(int par1, int par2)
{
byte var3 = 64;
BlockEndPortal.bossDefeated = true;
byte var4 = 4;
for (int var5 = var3 - 1; var5 <= var3 + 32; ++var5)
{
for (int var6 = par1 - var4; var6 <= par1 + var4; ++var6)
{
for (int var7 = par2 - var4; var7 <= par2 + var4; ++var7)
{
double var8 = (double)(var6 - par1);
double var10 = (double)(var7 - par2);
double var12 = (double)MathHelper.sqrt_double(var8 * var8 + var10 * var10);
if (var12 <= (double)var4 - 0.5D)
{
if (var5 < var3)
{
if (var12 <= (double)(var4 - 1) - 0.5D)
{
this.worldObj.setBlockWithNotify(var6, var5, var7, Block.bedrock.blockID);
}
}
else if (var5 > var3)
{
this.worldObj.setBlockWithNotify(var6, var5, var7, 0);
}
else if (var12 > (double)(var4 - 1) - 0.5D)
{
this.worldObj.setBlockWithNotify(var6, var5, var7, Block.bedrock.blockID);
}
else
{
this.worldObj.setBlockWithNotify(var6, var5, var7, Block.endPortal.blockID);
}
}
}
}
}
this.worldObj.setBlockWithNotify(par1, var3 + 0, par2, Block.bedrock.blockID);
this.worldObj.setBlockWithNotify(par1, var3 + 1, par2, Block.bedrock.blockID);
this.worldObj.setBlockWithNotify(par1, var3 + 2, par2, Block.bedrock.blockID);
this.worldObj.setBlockWithNotify(par1 - 1, var3 + 2, par2, Block.torchWood.blockID);
this.worldObj.setBlockWithNotify(par1 + 1, var3 + 2, par2, Block.torchWood.blockID);
this.worldObj.setBlockWithNotify(par1, var3 + 2, par2 - 1, Block.torchWood.blockID);
this.worldObj.setBlockWithNotify(par1, var3 + 2, par2 + 1, Block.torchWood.blockID);
this.worldObj.setBlockWithNotify(par1, var3 + 3, par2, Block.bedrock.blockID);
this.worldObj.setBlockWithNotify(par1, var3 + 4, par2, Block.dragonEgg.blockID);
BlockEndPortal.bossDefeated = false;
} | 8 |
@Override
public int numberOfLivingNeighbors(int x, int y) {
int numberOfLivingNeighbors = 0;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
if (!(i == 0 && j == 0)) {
int xCoordinate = x + i;
int yCoordinate = y + j;
if (cellExists(xCoordinate, yCoordinate) && board[xCoordinate][yCoordinate].isAlive()) {
numberOfLivingNeighbors++;
}
}
}
}
return numberOfLivingNeighbors;
} | 6 |
public static String formatTime3(long secs) {
int seconds = (int) secs;
int minutes = 0;
int hours = 0;
int days = 0;
days = seconds / (60 * 60 * 24);
hours = seconds / (60 * 60) % 24;
minutes = (seconds / 60) % 60;
seconds %= 60;
StringBuffer buf = new StringBuffer();
if (days > 0) {
buf.append(days).append(days != 1 ? " days, " : " day, ");
}
if (days > 0 || hours > 0) {
buf.append(hours).append(hours != 1 ? " hours, " : " hour, ");
}
if (hours > 0 || minutes > 0) {
buf.append(minutes).append(minutes != 1 ? " minutes, " : " minute, ");
}
buf.append(seconds).append(seconds != 1 ? " seconds" : " second");
return buf.toString();
} | 9 |
private static double _targetFromDistance(Distance distance) {
if(distance == Distance.NEAR) {
return StringPot.VAL_NEAR;
} else if(distance == Distance.CENTER) {
return StringPot.VAL_CENTER;
} else if(distance == Distance.OPPONENT_AUTO) {
return StringPot.VAL_OPPAUTO;
} else if(distance == Distance.FEEDER) {
return StringPot.VAL_FEEDER;
}
return -1;
} | 4 |
private BufferedImage getDiceImage(int size) {
if (diceImages == null)
return null;
switch(size) {
case 4: return diceImages[0];
case 6: return diceImages[1];
case 8: return diceImages[2];
case 10: return diceImages[3];
case 12: return diceImages[4];
case 20: return diceImages[5];
}
return null; // no image for that size
} | 7 |
private File forres(String nm) {
File res = base;
String[] comp = nm.split("/");
for(int i = 0; i < comp.length - 1; i++) {
res = new File(res, comp[i]);
}
return(new File(res, comp[comp.length - 1] + ".cached"));
} | 1 |
public static void getLongestSubString() {
// 两个需要对比的字符串
String x = "abcdehpoi";
String y = "bcdehfpoidfdegsfet";
int substringLength1 = x.length();
int substringLength2 = y.length();
// 第一步:构造需要遍历的二位数组
int opt[][] = new int[substringLength1 + 1][substringLength2 + 1];
// 定义三个临时变量:最大值,最大值横坐标和竖坐标
int max = opt[0][0];
int xCoordinate = 0, yCoordinate = 0;
// 第二步:横向竖向对比字符,填充上面构造的二位数组。
for (int i = 1; i <= substringLength1; i++) {
for (int j = 1; j <= substringLength2; j++) {
if (x.charAt(i - 1) == y.charAt(j - 1)) {
// 横向和竖向的字符相同,改变改位置的值为左上角的值加1。
opt[i][j] = opt[i - 1][j - 1] + 1;
// 这里需要记录下最大值的值和坐标
if (max < opt[i][j]) {
max = opt[i][j];
xCoordinate = i;
yCoordinate = j;
}
}
}
}
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("max = " + max);
// 第四步:取出最大子串序列,并且展示。。。
StringBuffer sb = new StringBuffer();
for (int i = xCoordinate, j = yCoordinate; i >= 1 && j >= 1; i--, j--) {
if (opt[i][j] > 0) {
sb.append(x.charAt(i - 1));
}
}
String result = sb.toString();
// 上面的字符串是反的,这里反转输出结果
for (int i = result.length() - 1; i >= 0; i--) {
System.out.print(result.charAt(i));
}
} | 8 |
public boolean canBePillaged(Unit attacker) {
return !hasStockade()
&& attacker.hasAbility("model.ability.pillageUnprotectedColony")
&& !(getBurnableBuildingList().isEmpty()
&& getShipList().isEmpty()
&& (getLootableGoodsList().isEmpty()
|| !attacker.getType().canCarryGoods()
|| !attacker.hasSpaceLeft())
&& !canBePlundered());
} | 7 |
public void addItemsToSupplierCombobox(ArrayList<Person> list) {
supplierComboboxItems.clear();
String item = "<html><font color='red'>Add New Supplier</font></html>";
supplierComboboxItems.add(item);
if (driver.getPersonDB().getSupplierList().size() > 0) {
for (Person person : list) {
item = "\t" + person.getId() + " \t - \t " + person.getName();
supplierComboboxItems.add(item);
}
supplierComboBox.setSelectedIndex(driver.getPersonDB().getSupplierList().size());
}
else {
supplierComboBox.setSelectedItem(null);
}
revalidate();
repaint();
} | 2 |
public static void main(String argv[]) throws Exception {
PORT = Integer.parseInt(argv[0]);
FILENAME = argv[1];
WINDOW = Integer.parseInt(argv[2]);
serverSocket = new DatagramSocket(PORT);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
boolean eof = false;
ArrayList<byte[]> packet_buffer = new ArrayList<byte[]>();
PacketReceptor receptor = new PacketReceptor(packet_buffer, 0, WINDOW);
Thread receiver = new Thread(receptor);
receiver.start();
/**
* Checks to the write buffer in the receptor thread can be managed
* through the introduction of a thread sleep within this loop
*/
ArrayList<byte[]> write_to_baos = new ArrayList<byte[]>();
do {
/**
* Pop the write buffer from the receptor thread so that the main
* thread can write the data to memory
*/
write_to_baos = receptor.popWriteBuffer();
for (byte[] x : write_to_baos) {
//IF WINDOW IS LARGER THAN NUM OF EOF
if(Utilities.isEOF(x)){
if(receptor.getSOW() > Utilities.getPacketNum(x)){
eof = true;
}
}
baos.write(Utilities.getData(x));
}
} while (eof == false);
receptor.stop();
FileOutputStream writeToFile = new FileOutputStream(FILENAME);
System.out.println("Transmission complete! Writing to file...");
writeToFile.write(baos.toByteArray());
} | 4 |
@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 TaxonObservationDownloadStatisticsPK)) {
return false;
}
TaxonObservationDownloadStatisticsPK other = (TaxonObservationDownloadStatisticsPK) object;
if (this.filterID != other.filterID) {
return false;
}
if ((this.datasetKey == null && other.datasetKey != null) || (this.datasetKey != null && !this.datasetKey.equals(other.datasetKey))) {
return false;
}
return true;
} | 6 |
public void disconnect(){
try {
instream.close();
outstream.close();
} catch(IOException e) {
}
} | 1 |
protected Integer coerceToInteger(Object value) {
if (value == null || "".equals(value)) {
return Integer.valueOf(0);
}
if (value instanceof Integer) {
return (Integer)value;
}
if (value instanceof Number) {
return Integer.valueOf(((Number)value).intValue());
}
if (value instanceof String) {
try {
return Integer.valueOf((String)value);
} catch (NumberFormatException e) {
throw new ELException(LocalMessages.get("error.coerce.value", value, value.getClass(), Integer.class));
}
}
if (value instanceof Character) {
return Integer.valueOf((short)((Character)value).charValue());
}
throw new ELException(LocalMessages.get("error.coerce.type", value, value.getClass(), Integer.class));
} | 7 |
public int getColsCount() {
return m_colsCount;
} | 0 |
private List<String> getImageNames(boolean sameSize) {
List<String> imagens = new ArrayList<String>();
for (JInternalFrame frame : getDskCenter().getAllFrames())
if (frame instanceof ImagemIFrame) {
if (sameSize) {
BufferedImage selected = getSelectedFrame().getImage();
BufferedImage other = ((ImagemIFrame) frame).getImage();
if (other.getWidth() != selected.getWidth()
|| other.getHeight() != selected.getHeight())
continue;
}
imagens.add(frame.getTitle());
}
return imagens;
} | 5 |
@Basic
@Column(name = "sale_estado")
public String getEstadoMovimiento() {
return estadoMovimiento;
} | 0 |
public Configuration[] getSelected() {
return (Configuration[]) selected.toArray(new Configuration[0]);
} | 0 |
private static byte[] joinQuartetsToBytes(byte[] quartets) {
byte[] block = new byte[quartets.length / 2];
for (int i = 0; i < quartets.length; i += 2) {
block[i/2] = ByteHelper.joinBlocks(quartets[i], quartets[i + 1]);
}
return block;
} | 1 |
public void allDFS(Graph G)
{
// find a vertex to serve as the starting point for a DFS search in each
// component. 'componentCount' will not only keep a count of the
// components but will
// also serve as the id to use for all vertices of that component
for (int v = 0; v < G.V(); v++)
{
dfs(G, v);
postEachSourceDFS(v);
}
} | 1 |
private void boutonDeumeureDesElfesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_boutonDeumeureDesElfesMouseClicked
// TODO add your handling code here:
if (partie.getDde().isActif()) {
if (!partie.getDieuActuel().isaJoueurEnDeumeureDesElfes()
|| ((partie.getDieuActuel().getNom().compareTo("Freyja") == 0 && ((Freyja) partie.getDieuActuel()).getaJoueurEnDeumeureDesElfes() < 2)&&Dieu.pouvoirDieu)) {
partie.jouerEnDemeureDesElfes(page);
verifFinTour();
} else {
JOptionPane.showMessageDialog(page, "Vous avez déjà joué dans ce monde", "Yggdrasil", JOptionPane.INFORMATION_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(page, "Un géant bloc l'accés à ce monde", "Yggdrasil", JOptionPane.INFORMATION_MESSAGE);
}
}//GEN-LAST:event_boutonDeumeureDesElfesMouseClicked | 5 |
protected void layout(List<Object> parallels)
{
Object edge = parallels.get(0);
mxIGraphModel model = graph.getModel();
mxGeometry src = model.getGeometry(model.getTerminal(edge, true));
mxGeometry trg = model.getGeometry(model.getTerminal(edge, false));
// Routes multiple loops
if (src == trg)
{
double x0 = src.getX() + src.getWidth() + this.spacing;
double y0 = src.getY() + src.getHeight() / 2;
for (int i = 0; i < parallels.size(); i++)
{
route(parallels.get(i), x0, y0);
x0 += spacing;
}
}
else if (src != null && trg != null)
{
// Routes parallel edges
double scx = src.getX() + src.getWidth() / 2;
double scy = src.getY() + src.getHeight() / 2;
double tcx = trg.getX() + trg.getWidth() / 2;
double tcy = trg.getY() + trg.getHeight() / 2;
double dx = tcx - scx;
double dy = tcy - scy;
double len = Math.sqrt(dx * dx + dy * dy);
double x0 = scx + dx / 2;
double y0 = scy + dy / 2;
double nx = dy * spacing / len;
double ny = dx * spacing / len;
x0 += nx * (parallels.size() - 1) / 2;
y0 -= ny * (parallels.size() - 1) / 2;
for (int i = 0; i < parallels.size(); i++)
{
route(parallels.get(i), x0, y0);
x0 -= nx;
y0 += ny;
}
}
} | 5 |
@Override
public boolean activateProfile(Profile profile) {
// Save the directories
String dataDir = getDir();
String saveDir = dataDir + getGameSaveDir();
String profilesDir = dataDir + getSave() + File.separator;
// Find the currently active profile
ProfileFactory pf = ProfileFactory.getInstance();
Profile[] profiles = pf.getProfiles(getId());
Profile currentProfile = null;
for(int x=0; x<profiles.length; x++){
if(profiles[x].isActive()){
currentProfile = profiles[x];
break;
}
}
// Create the Files that need to be renamed
File saveFolder = new File(saveDir);
File profileSaves = new File(profilesDir + profile.getSaveDir());
// See if there is an active profile
if(currentProfile == null){
// No profile is active delete the saves folder
if( saveFolder.exists() && !saveFolder.delete()){
Main.handleException("Unable to activate the profile because the save folder contains saves from an unkown or de-activated profile.",
null, Main.WARN_LEVEL);
return false;
}
} else {
// Rename the saved games folder to the previous profile's saveDir
if( !saveFolder.renameTo(
new File(profilesDir + currentProfile.getSaveDir())) )
{
Main.handleException("Unable to move the saved game folder.",
null, Main.WARN_LEVEL);
return false;
}
}
// Rename the profile's save game directory to the morrowind save directory
if( profileSaves.renameTo(new File(saveDir)) ) {
pf.setActive(profile);
return true;
} else {
Main.handleException("Unable to move the profile's saved games into the save game folder.",
null, Main.WARN_LEVEL);
return false;
}
} | 7 |
public JList<String> getListUsuarios() {
if (listUsuarios == null) {
listUsuarios = new JList<String>();
}
return listUsuarios;
} | 1 |
private void setupWorldWind() {
BasicModel model = new BasicModel();
globeRound = model.getGlobe();
wwCanvas.setModel(model);
// highlightController = new HighlightController(wwCanvas, SelectEvent.ROLLOVER);
// ttController = new ToolTipController(wwCanvas);
// Register a rendering exception listener that's notified when
// exceptions occur during rendering.
wwCanvas.addRenderingExceptionListener(new RenderingExceptionListener() {
public void exceptionThrown(Throwable t) {
if (t instanceof WWAbsentRequirementException) {
StringBuilder message = new StringBuilder(
"Computer does not meet minimum graphics requirements.\n");
message.append("Please install up-to-date graphics driver and try again.\n");
message.append("Reason: ").append(t.getMessage());
message.append("\nThis program will end when you press OK.");
JOptionPane.showMessageDialog(MainFrame.this, message, "Unable to Start Program",
JOptionPane.ERROR_MESSAGE);
System.exit(-1);
} else {
System.err.println("WorldWind library rendering problem!");
t.printStackTrace();
}
}
});
// add a StatusLayer
StatusLayer slayer = new StatusLayer();
slayer.setEventSource(wwCanvas);
slayer.setDefaultFont(chPlaces.getFont());
wwCanvas.getModel().getLayers().add(slayer);
// add the shape drawing layer
wwCanvas.getModel().getLayers().add((Layer) gmlLayer);
} | 1 |
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
System.out.println("Please key in number for following algorithms:");
System.out.println("[1] Depth-First-Search");
System.out.println("[2] Breadth-First-Search");
System.out.println("[3] Best-First-Search");
System.out.println("[4] Hill Climbing Search");
System.out.println("[5] A* Search");
System.out.println("[6] Custom Search");
int input = scanIn.nextInt();
if (input==1) {
DFS dfs = new DFS("maze.txt");
dfs.compute();
}
else if (input==2) {
BFS bfs = new BFS("maze.txt");
bfs.compute();
}
else if (input==3) {
Best best = new Best("maze.txt");
best.compute();
}
else if (input==4) {
HillClimbing hill = new HillClimbing("maze.txt");
hill.compute();
}
else if (input==5) {
AStar a = new AStar("maze.txt");
a.compute();
}
else if (input==6) {
Custom aheadTwoSteps = new Custom("maze.txt");
aheadTwoSteps.compute();
}
} | 6 |
public void checkCoupon(Service service, int position) {
Calendar today = Calendar.getInstance();
long todaysTime = this.expiryDate.getTimeInMillis();
long serviceTime = service.serviceDate.getTimeInMillis();
long oneDay = 1000 * 60 * 60 * 24;
int difference = (int) ((todaysTime - serviceTime) / oneDay);
if (service instanceof EngineOil) { // 5 Months
if (difference >= 150) {
System.out.println("-----------------------------");
System.out.println("Service #: " + position);
System.out.println("Date of last service: "
+ service.serviceDate.get(service.serviceDate.MONTH) + "/"
+ service.serviceDate.get(service.serviceDate.DAY_OF_MONTH) + "/"
+ service.serviceDate.get(service.serviceDate.YEAR));
System.out.println("Days since last service: " + difference);
System.out.println("Days needed to qualify for coupon: " + 150);
service.coupon = new EngineServiceCoupon(5); }
}
if (service instanceof RadiatorFlush) { // 5 Years
if (difference >= 1825) {
System.out.println("-----------------------------");
System.out.println("Service #: " + position);
System.out.println("Date of last service: "
+ service.serviceDate.get(service.serviceDate.MONTH) + "/"
+ service.serviceDate.get(service.serviceDate.DAY_OF_MONTH) + "/"
+ service.serviceDate.get(service.serviceDate.YEAR));
System.out.println("Days since last service: " + difference);
System.out.println("Days needed to qualify for coupon: " + 1825);
service.coupon = new RadiatorFlushCoupon(15); }
}
if (service instanceof TireService) { // 3 Years
if (difference >= 1095) {
System.out.println("-----------------------------");
System.out.println("Service #: " + position);
System.out.println("Date of last service: "
+ service.serviceDate.get(service.serviceDate.MONTH) + "/"
+ service.serviceDate.get(service.serviceDate.DAY_OF_MONTH) + "/"
+ service.serviceDate.get(service.serviceDate.YEAR));
System.out.println("Days since last service: " + difference);
System.out.println("Days needed to qualify for coupon: " + 1095);
service.coupon = new TireServiceCoupon(); }
}
if (service instanceof BrakeService) { // 3 Years
if (difference >= 1095) {
System.out.println("-----------------------------");
System.out.println("Service #: " + position);
System.out.println("Date of last service: "
+ service.serviceDate.get(service.serviceDate.MONTH) + "/"
+ service.serviceDate.get(service.serviceDate.DAY_OF_MONTH) + "/"
+ service.serviceDate.get(service.serviceDate.YEAR));
System.out.println("Days since last service: " + difference);
System.out.println("Days needed to qualify for coupon: " + 1095);
service.coupon = new BrakeServiceCoupon(30); }
}
} | 8 |
public void destroy() {
for(BaseComponent bc : components.values()) {
bc.destroy();
}
components.clear();
} | 1 |
@Override
public PermissionType getType() {
return PermissionType.WORLD;
} | 0 |
@SuppressWarnings("deprecation")
@EventHandler
public void click(InventoryClickEvent event)
{
Player player = (Player) event.getView().getPlayer();
OpenQuestLog oql = getOpenQuestLog(player);
if(oql == null)return;
event.setCancelled(true);
if(event.getView() != oql.getInventoryView())
{
player.updateInventory();
return;
}
if(event.getCurrentItem() == null)
{
player.updateInventory();
return;
}
Quest sel = oql.getSelected();
if(sel == null)
{
if(event.getSlot() == 27)
{
oql.setViewingCompleted(!oql.isViewingCompleted());
oql.update();
}
else
{
int index = (oql.getPage() - 1)*27 + event.getSlot();
Quest[] q = oql.isViewingCompleted() ? oql.getCurrentCompletedList() : oql.getCurrentQuestList();
if(index < q.length)
{
oql.setSelected(q[index]);
oql.update();
}
}
}
else if(event.getSlot() == 27)
{
oql.setSelected(null);
oql.update();
}
player.updateInventory();
} | 8 |
public static void main(String[] args) throws InterruptedException {
final int numberOfTrees = 20;
final int numberOfDucks = 20;
final int numberOfHunters = 20;
HuntField f = new HuntField(21, 70);
for (int i = 0; i < numberOfTrees; i++) new Tree(f);
for (int i = 0; i < numberOfDucks; i++) new Duck(f).start();
for (int i = 0; i < numberOfHunters; i++) new Hunter(f).start();
while(f.getNumberOfItems('D')>0){
Thread.sleep(200);
printField(f);
}
printField(f);
} | 4 |
public void ge_relation(TextArea area,SimpleNode node,String prefix,int cur_end_num,int if_or_while,int con)throws SemanticErr{
if(node.toString().equals("Relation_expression")) {
SimpleNode left = (SimpleNode) node.jjtGetChild(0).jjtGetChild(0).jjtGetChild(0);
SimpleNode rel = (SimpleNode) node.jjtGetChild(1);
SimpleNode right = (SimpleNode) node.jjtGetChild(2).jjtGetChild(0).jjtGetChild(0);
//if()
if (and_last == 0 || and_last == 1) {
String sub_prefix = prefix.substring(0, prefix.length() - 2);
String instr = sub_prefix + "land.lhs.true" + String.valueOf(true_num) + ":\n";
true_num = true_num + 1;
area.append(instr);
}
pair left_pair = ge_add_expression(area, left, prefix);
pair right_pair = ge_add_expression(area, right, prefix);
ge_cmp(area, rel.jjtGetFirstToken().toString(), left_pair.var, right_pair.var, prefix,con);
}
else if(node.toString().equals("Function_call_expression"))
{
pair func = ge_call(area,node,prefix);
ge_cmp(area, "!=", func.var, "0", prefix,con);
}
if (if_or_while == 0) {
ge_if_jump(area, prefix, cur_end_num);
} else {
ge_while_jump(area, prefix, cur_end_num);
}
} | 5 |
public String getCurrentPuzzle()
{
String currentPuzzle = "";
int i = 0, j = 0;
for(i = 0; i < 16; i++)
{
for(j = 0; j < 16; j++)
{
if(entries[i][j].isEditable())
{
currentPuzzle = currentPuzzle +"E ";
}
else
{
currentPuzzle = currentPuzzle +"N ";
}
if(entries[i][j].getText().equals(""))
{
currentPuzzle = currentPuzzle + "0 ";
}
else
{
currentPuzzle = currentPuzzle + entries[i][j].getText() + " ";
}
}
}
System.out.println("Current Puzzle is" + currentPuzzle);
return currentPuzzle;
} | 4 |
private static void checkForBlackjack(Dealer dealer, Player player) {
boolean playerHasBlackjack = player.getHasBlackjack();
boolean dealerHasBlackjack = dealer.getHasBlackjack();
// End round if both have blackjack. Tie situation.
if(playerHasBlackjack && dealerHasBlackjack) {
System.out.println("Both have 21, but both dealer and player have blackjack so tie!");
tieSituation(player);
continueRound=false;
}
// If player has blackjack, then declare player the winner.
else if(playerHasBlackjack) {
System.out.println("Both have 21, but dealer doesn't have blackjack so player wins!");
playerWon(player);
continueRound=false;
}
// This means that the player doesn't have blackjack, so the dealer will win.
else if(dealerHasBlackjack){
System.out.println("Both have 21, but player doesn't have blackjack so dealer wins!");
dealerWon(dealer);
continueRound=false;
}
// Both don't have blackjack, but they both have 21, so they will tie.
else {
System.out.println("Both have 21, but neither one has blackjack so tie!");
tieSituation(player);
continueRound=false;
}
} | 4 |
public JSONObject putOnce(String key, Object value) throws JSONException {
if (key != null && value != null) {
if (this.opt(key) != null) {
throw new JSONException("Duplicate key \"" + key + "\"");
}
this.put(key, value);
}
return this;
} | 3 |
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args)
{
if(plugin.hasPermission(sender, "authy")){
if(args.length==0){
}else{
if(args[0].equalsIgnoreCase("register")){
this.register(sender, cmd, commandLabel, args);
}
}
}
return true;
} | 3 |
private ArrayList<String> getValidationErrors() {
ArrayList<String> errors = new ArrayList<String>();
String username = txtUsername.getText();
if (username.isEmpty()) { errors.add("Username field is blank"); }
return errors;
} | 1 |
public void nextQuestion(){
Scanner input = new Scanner(System.in);
question=new Test();
Random random = new Random();
number = random.nextInt(4);
while(check.contains(number))
{
number = random.nextInt(4);
}
check.add(number);
switch(number)
{
case 0:
System.out.println(question.question1(questions));
break;
case 1:
System.out.println(question.question2(questions));
break;
case 2:
System.out.println(question.question3(questions));
break;
case 3:
System.out.println(question.question4(questions));
break;
}
String answer = input.nextLine();
if(answer.equalsIgnoreCase("a"))
userAnswer = 0;
else if(answer.equalsIgnoreCase("b"))
userAnswer = 1;
else if(answer.equalsIgnoreCase("c"))
userAnswer = 2;
else if(answer.equalsIgnoreCase("d"))
userAnswer = 3;
checkTrue();
} | 9 |
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0 || JsfUtil.isDummySelectItem(component, value)) {
return null;
}
return this.ejbFacade.find(getKey(value));
} | 3 |
@Override
public Movement getMove(Board b) {
List<PosibleWord> movements = b.getPosibleWords();
Dictionary dic = b.getDic();
SortedSet<WordInfo> words = new TreeSet<WordInfo>();
for (PosibleWord pw : movements) {
Iterator<String> it = dic.iterator(pw.getPattern());
while (it.hasNext()) {
String word = it.next();
if (pw.matches(word, dic) && compatibleWithHand(b,word,pw)) {
words.add(new WordInfo(word,pw,b.scoreWord(word, letters, pw.i, pw.j, pw.direction)));
}
}
}
if (words.isEmpty()) {
throw new RuntimeException("No moves D:");
}
WordInfo finalWord = words.last();
return new Movement(finalWord.pw.i, finalWord.pw.j, finalWord.pw.direction, finalWord.word);
} | 5 |
@Get
public Set<Intervention> readAll() {
Set<Intervention> interventions = null;
String userkey = (String) getRequest().getAttributes().get("userid");
if (userkey == null)
return null;
User target = null;
try {
long userid = Long.valueOf(userkey);
EntityManager em = emf.createEntityManager();
target = em.find(User.class, userid);
if (target != null) {
interventions = target.getIntervention();
} else {
return null;
}
} catch (Exception e) {
System.out.println(e);
}
return interventions;
} | 3 |
public static boolean isString(String line){
if(line.charAt(0) == '"' && line.charAt(line.length()-1) == '"'){
return true;
}
return false;
} | 2 |
public boolean matches(Operator loadop) {
return loadop instanceof GetFieldOperator
&& ((GetFieldOperator) loadop).ref.equals(ref);
} | 1 |
public void registerCommand(Object obj) {
Method methods[] = obj.getClass().getDeclaredMethods();
for(Method m: methods) {
if(m.isAnnotationPresent(DBCommand.class)) {
Class<?> params[] = m.getParameterTypes();
if(params.length == 2 && params[0] == CommandSender.class && params[1]
== Iterator.class && m.getReturnType() == Boolean.TYPE) {
String name = m.getName().toLowerCase();
commands.put(name, obj);
}
}
}
} | 7 |
public void respawn(final boolean force) {
if (force) {
final int numShouldSpawn = monsterSpawn.size() - spawnedMonstersOnMap.get();
if (numShouldSpawn > 0) {
int spawned = 0;
for (Spawns spawnPoint : monsterSpawn) {
spawnPoint.spawnMonster(this);
spawned++;
if (spawned >= numShouldSpawn) {
break;
}
}
}
} else {
if (getCharactersSize() <= 0) {
return;
}
final int numShouldSpawn = maxRegularSpawn - spawnedMonstersOnMap.get();
if (numShouldSpawn > 0) {
int spawned = 0;
final List<Spawns> randomSpawn = new ArrayList<Spawns>(monsterSpawn);
Collections.shuffle(randomSpawn);
for (Spawns spawnPoint : randomSpawn) {
if (spawnPoint.shouldSpawn()) {
spawnPoint.spawnMonster(this);
spawned++;
}
if (spawned >= numShouldSpawn) {
break;
}
}
}
}
} | 9 |
@Override
public void fill(Parameter parameter, Type type, Annotation[] annotations)
{
Class clazz;
Class reader;
if (type instanceof Class)
{
reader = ((Class)type);
clazz = ((Class)type);
}
else if (type instanceof ParameterizedType)
{
reader = ((Class)((ParameterizedType)type).getRawType());
Type[] typeArgs = ((ParameterizedType)type).getActualTypeArguments();
if (typeArgs.length != 1)
{
throw new UnsupportedOperationException("Only exactly one generic Parameter Type is supported");
}
clazz = ((Class)typeArgs[0]);
}
else
{
throw new UnsupportedOperationException("Type is not supported: " + type);
}
if (reader == type && Enum.class.isAssignableFrom(clazz))
{
reader = Enum.class; // Use default enum reader
}
for (Annotation annotation : annotations)
{
if (annotation instanceof Reader)
{
reader = ((Reader)annotation).value();
}
}
parameter.offer(Properties.TYPE, clazz);
parameter.offer(Properties.READER, reader);
} | 7 |
private void expand1(byte[] src, byte[] dst) {
for (int i = 1, n = dst.length; i < n; i += 8) {
int val = src[1 + (i >> 3)] & 255;
switch (n - i) {
default:
dst[i + 7] = (byte) ((val) & 1);
case 7:
dst[i + 6] = (byte) ((val >> 1) & 1);
case 6:
dst[i + 5] = (byte) ((val >> 2) & 1);
case 5:
dst[i + 4] = (byte) ((val >> 3) & 1);
case 4:
dst[i + 3] = (byte) ((val >> 4) & 1);
case 3:
dst[i + 2] = (byte) ((val >> 5) & 1);
case 2:
dst[i + 1] = (byte) ((val >> 6) & 1);
case 1:
dst[i] = (byte) ((val >> 7));
}
}
} | 8 |
private void showAllNodesOnTree(UrlNode node , int i ){
System.out.println("Level : " + i + " , Path : " + node.selfUrl + " , parentUrl : " + node.parentUrl + " , childNum :" + node.childNodes.size() );
if( node.childNodes == null || node.childNodes.size() == 0)
return ;
for(UrlNode nodes : node.childNodes){
showAllNodesOnTree(nodes , i + 1) ;
}
} | 3 |
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String cmd = request.getParameter(CMD_PARAM);
UserGame game = (UserGame) request.getSession().getAttribute(USER_GAME);
boolean refresh = false;
if (REFRESH_CMD.equals(cmd)) {
refresh = true;
game.refresh();
} else if (FLIGHT_LEVEL_CMD.equals(cmd)) {
String planeId = request.getParameter(PLANE_PARAM);
String flightLevelId = request.getParameter(FLIGHT_LEVEL_PARAM);
game.sendFlightLevel(planeId, flightLevelId);
} else if (HOLD_CMD.equals(cmd)) {
String planeId = request.getParameter(PLANE_PARAM);
String condId = request.getParameter(CONDITION_PARAM);
game.sendHold(planeId, condId);
} else if (LAND_CMD.equals(cmd)) {
String planeId = request.getParameter(PLANE_PARAM);
String locationId = request.getParameter(LOCATION_PARM);
game.sendClearToLand(planeId, locationId);
} else if (TURN_CMD.equals(cmd)) {
String planeId = request.getParameter(PLANE_PARAM);
String locationId = request.getParameter(LOCATION_PARM);
String condId = request.getParameter(CONDITION_PARAM);
game.sendTurnTo(planeId, locationId, condId);
} else if (EXIT_CMD.equals(cmd)) {
game.exitGame();
} else {
log.error("Unrecognized command cmd=" + cmd);
}
// Prepare response
RefreshData refreshData = new RefreshData();
if (refresh)
refreshData.setCommand(game.isGameOver() ? "setGameOver()"
: "refreshLater()");
refreshData.setPlanePane(game.getPlaneListLog());
refreshData.setLogPane(game.getLogRows());
List<JsonPlane> planes = refreshData.getPlaneList();
planes.clear();
for (Plane plane : game.getPlaneList()) {
JsonPlane jPlane = new JsonPlane();
jPlane.setId(plane.getId());
jPlane.setFlightLevel(plane.getFlightLevelId());
jPlane.setHeading(plane.getHeading());
jPlane.setX(plane.getPosition().getX());
jPlane.setY(plane.getPosition().getY());
jPlane.setSpeed(plane.getSpeed());
jPlane.setClassId(plane.getClassId());
planes.add(jPlane);
}
// Output reponse
Gson gson = new Gson();
response.setContentType("application/json");
response.getWriter().write(gson.toJson(refreshData));
} | 9 |
public void Update(double timeDelta)
{
m_collidedLastFrame = false;
if (m_interType == InteractionType.Kinetic || m_interType == InteractionType.Ghost || m_velocityX != 0.0 || m_velocityY != 0.0)
m_physicsModel.PerformCollisionFor(this);
double dX = m_velocityX * timeDelta + m_accelX * timeDelta * timeDelta * 0.5, dY = m_velocityY * timeDelta + m_accelY * timeDelta * timeDelta * 0.5,
friction = Math.pow(m_physicsModel.m_friction, timeDelta);
if (m_bounds.m_boundsType == BoundsType.Circle)
{
m_bounds.m_circle.X += dX;
m_bounds.m_circle.Y += dY;
}
else
{
m_bounds.m_rect.m_x += dX;
m_bounds.m_rect.m_y += dY;
m_bounds.m_rect.m_right = m_bounds.m_rect.m_x + m_bounds.m_rect.m_width;
m_bounds.m_rect.m_bottom = m_bounds.m_rect.m_y + m_bounds.m_rect.m_height;
}
m_posX += dX;
m_posY += dY;
m_velocityX = m_velocityX * friction + m_accelX * timeDelta;
m_velocityY = m_velocityY * friction + m_accelY * timeDelta;
m_accelX = m_accelY = 0;
} | 5 |
public static void AddIndividualReport(String TestPath, String Testname)
{
FileWriter fstream =null;
BufferedWriter out =null;
try
{
fstream = new FileWriter(TestPath);
out = new BufferedWriter(fstream);
out.write("<html>");
out.write("<head>");
out.write("<title>");
out.write(Testname + " Detailed Reports");
out.write("</title>");
out.write("</head>");
out.write("<body>");
out.write("<h4> <FONT COLOR=660000 FACE=Arial SIZE=4.5>" +Testname + " Detailed Report :</h4>");
out.write("<table border=1 cellspacing=1 cellpadding=1 width=100%>");
out.write("<tr> ");
//out.write("<td align=center width=10% align=center bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE=Arial SIZE=2><b>Step/Row#</b></td>");
out.write("<td align=center width=60% align=center bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE=Arial SIZE=2><b>Description</b></td>");
out.write("<td align=center width=10% align=center bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE=Arial SIZE=2><b>Keyword</b></td>");
out.write("<td align=center width=15% align=center bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE=Arial SIZE=2><b>Result</b></td>");
out.write("<td align=center width=15% align=center bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE=Arial SIZE=2><b>Screen Shot</b></td>");
out.write("</tr>");
out.write("</table>\n");
out.write("</body>\n");
out.write("</html>\n");
out.close();
}
catch(Throwable t)
{
}
} | 1 |
private static void mergeSort(Branch[] src, Branch[] dest,
int low, int high, int off) {
int length = high - low;
// Insertion sort on smallest arrays
if (length < INSERTIONSORT_THRESHOLD) {
for (int i = low; i < high; i++)
for (int j = i; j > low
&& (dest[j - 1]).compareTo(dest[j].getC()) > 0; j--)
swap(dest, j, j - 1);
return;
}
// Recursively sort halves of dest into src
int destLow = low;
int destHigh = high;
low += off;
high += off;
int mid = (low + high) >>> 1;
mergeSort(dest, src, low, mid, -off);
mergeSort(dest, src, mid, high, -off);
// If list is already sorted, just copy from src to dest. This
// is an
// optimization that results in faster sorts for nearly ordered
// lists.
if (src[mid - 1].compareTo(src[mid].getC()) <= 0) {
System.arraycopy(src, low, dest, destLow, length);
return;
}
// Merge sorted halves (now in src) into dest
for (int i = destLow, p = low, q = mid; i < destHigh; i++) {
if (q >= high || p < mid && src[p].compareTo(src[q].getC()) <= 0)
dest[i] = src[p++];
else
dest[i] = src[q++];
}
} | 9 |
@Deprecated
private static String checkNFE(String operation, String[] arguments)
{
if(!operationNFEArgs.containsKey(operation))
{
return "VALID";
}
String[] argsNums = operationNFEArgs.get(operation).split("&");
for(String s : argsNums)
{
if(s.contains("..."))
{
for(int x = Integer.valueOf(s.substring(0,1)); x < arguments.length; x++)
{
if(!isInteger(arguments[x]))
{
return "Error: Expected argument " + x + " to be a number.";
}
}
}
if(!isInteger(arguments[Integer.valueOf(s)]))
{
return "Error: Expected argument " + s + " to be a number.";
}
}
return "VALID";
} | 6 |
public Worker(int workerPriority,BlockingQueue<Worker> idleWorkers){
Integer bufferSize = Config.getInt(READ_BUFFER);
if(bufferSize == null){
bufferSize = 10;
}
this.charBuffer = ByteBuffer.allocateDirect(1024 * bufferSize);// 创建读取缓冲区
this.idleWorkers = idleWorkers;
handoffBox = new ArrayBlockingQueue<Object>(1);
noStopRequested = true;
Runnable r = new Runnable(){
public void run(){
try{
runWork();
}catch(Exception e){
e.printStackTrace();
}
}
};
this.internalThread = new Thread(r);
this.internalThread.setName("请求参数读取线程" + threadIndex.getAndIncrement());
this.internalThread.setPriority(workerPriority);
this.internalThread.start();
} | 2 |
public Field() {
Point[][] res = new Point[FIELD_SIZE][FIELD_SIZE];
Scanner sc = new Scanner(System.in);
char letter;
while (true) {
System.out.println("Please, enter one letters from matrix:");
for (int i = 0; i < FIELD_SIZE; i++) {
for (int j = 0; j < FIELD_SIZE; j++) {
try {
System.out.println("a[" + i + "][" + j + "] = ");
letter = sc.next().charAt(0);
res[i][j] = new Point(letter, i, j);
} catch (Exception e) {
e.printStackTrace();
}
}
}
for (int i = 0; i < FIELD_SIZE; i++) {
for (int j = 0; j < FIELD_SIZE; j++) {
System.out.print(res[i][j].getLetter());
}
System.out.println();
}
System.out.println("Matrix is OK? (y/n)");
letter = sc.next().charAt(0);
if (letter == 'y'){
this.points = res;
return;
}
}
} | 7 |
private int getEhtoX(Pelihahmo h){
if (h==h1){
return ehtoh1x;
} else {
return ehtoh2x;
}
} | 1 |
public SharingPeer(String ip, int port, ByteBuffer peerId,
SharedTorrent torrent) {
super(ip, port, peerId);
this.torrent = torrent;
this.listeners = new HashSet<PeerActivityListener>();
this.availablePieces = new BitSet(this.torrent.getPieceCount());
this.exchangeLock = new Object();
this.reset();
this.requestedPiece = null;
} | 0 |
private double findChange(Expr old, Expr nu) {
if (old == null || nu == null)
return 0;
if (old.type != nu.type)
return 0;
if (nu instanceof ExprNumber) {
return Math.abs(((ExprNumber) old).doubleValue() -
((ExprNumber) nu).doubleValue());
}
if (nu instanceof ExprArray) {
Expr[] oldA = ((ExprArray) old).getInternalArray();
Expr[] nuA = ((ExprArray) nu).getInternalArray();
double change = 0;
for (int i = 0; i < oldA.length && i < nuA.length; i++) {
double c = findChange(oldA[i], nuA[i]);
if (c > change)
change = c;
}
return change;
}
return 0;
} | 8 |
void init(){
if(volume<200){
days=0;
}else{
days=Math.min(5,volume/200);
}
} | 1 |
public String getDefinition() {
return definition;
} | 0 |
private boolean binarySearch(int[] num, int target, int s, int e) {
int mid = 0;
while (s <= e) {
mid = s + ((e - s) >> 1);
if (num[mid] == target) {
return true;
} else if (num[mid] > target) {
e = mid - 1;
} else {
s = mid + 1;
}
}
return false;
} | 3 |
public ArrayList<Node> successors()
{
ArrayList<Node> temp = new ArrayList<Node>();
State left = state.goLeft();
State up = state.goUp();
State right = state.goRight();
State down = state.goDown();
if(up != null)
{
temp.add(new Node(up, this, cost+1, Grid.Direction.UP));
}
if(down != null)
{
temp.add(new Node(down, this, cost+1, Grid.Direction.DOWN));
}
if(left != null)
{
temp.add(new Node(left, this, cost+1, Grid.Direction.LEFT));
}
if(right != null)
{
temp.add(new Node(right, this, cost+1, Grid.Direction.RIGHT));
}
return temp;
} | 4 |
public RemoteClientConnection(String serverIP, int port) {
this.serverIP = serverIP;
this.port = port;
} | 0 |
public void visitInnerClass(final String name, final String outerName,
final String innerName, final int access) {
checkState();
CheckMethodAdapter.checkInternalName(name, "class name");
if (outerName != null) {
CheckMethodAdapter.checkInternalName(outerName, "outer class name");
}
if (innerName != null) {
CheckMethodAdapter.checkIdentifier(innerName, "inner class name");
}
checkAccess(access, Opcodes.ACC_PUBLIC + Opcodes.ACC_PRIVATE
+ Opcodes.ACC_PROTECTED + Opcodes.ACC_STATIC
+ Opcodes.ACC_FINAL + Opcodes.ACC_INTERFACE
+ Opcodes.ACC_ABSTRACT + Opcodes.ACC_SYNTHETIC
+ Opcodes.ACC_ANNOTATION + Opcodes.ACC_ENUM);
cv.visitInnerClass(name, outerName, innerName, access);
} | 2 |
void checaColision() {
//System.out.println("Entro checaColision");
if(oro.getPosY() - oro.getAlto() > getHeight()) { //Colision de oro con borde
clickOro = false;
oro.setPosX(0);
oro.setPosY(ALTO - oro.getAlto());
if(suena)
borde.play();
if (auxvidas == 2){
if (vidas > 0){
vidas--;
velocidadDragon--;
auxvidas = 0;
if (vidas == 0){
gameover = !gameover;
}
}
else{
gameover = !gameover;
}
}
auxvidas++;
}
else if(dragon.intersecta(oro)) { //colision de dragon con oro
clickOro = false;
if(suena)
cBueno.play();
mensDESAPARECE = true;
contVDesap = 0;
score += 2;
oro.setPosX(0); //posision x
oro.setPosY(getHeight() - oro.getAlto()-10); //posision y
}
} | 7 |
public Reading() {
// TODO Auto-generated constructor stub
try {
doc = Jsoup.connect(DOKUMENT_ADRESSE).get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 1 |
public byte[] read_multiple(short address, int length) throws IOException {
if ((this.mode==0) || (this.mode==SET_MODE_I2C_SERIAL)) this.set_mode(SET_MODE_I2C_100);
byte[] data=new byte[3];
data[0]=(byte)RW_MULTIPLE;
data[1]=(byte)address;
data[2]=(byte)length;
byte[] result = this.sendAndReceive(data, COM_TIMEOUT, length);
if (result.length!=length) throw new IOException("no answer from device");
return result;
} | 3 |
public boolean jumpMayBeChanged() {
return subBlock.jump != null || subBlock.jumpMayBeChanged();
} | 1 |
private void getRootInfo() {
new Thread() {
@Override
public void run() {
setName("Root Info Thread");
setPriority(Thread.MIN_PRIORITY);
while (getDeviceInfo) {
// if (debug)
// logger.log(Level.DEBUG, "Loading device root info...");
SU su = selectedDevice.getSU();
BusyBox busybox = selectedDevice.getBusybox();
boolean su_isInstalled = false; // Generally assume that this is false!
String su_version = null;
boolean busybox_isInstalled = false; // Same rules apply here!
String busybox_version = null;
try {
su_isInstalled = su.isInstalled();
su_version = su.getSUVersion();
busybox_isInstalled = busybox.isInstalled();
busybox_version = busybox.getVersion();
} catch (IOException ex) {
logger.log(Level.ERROR, "An error occurred while loading the device's root information: " + ex.toString() + "\n"
+ "The error stack trace will be printed to the console...");
ex.printStackTrace(System.err);
interrupt();
}
if (su_isInstalled) {
superUserStatus_rootLabel.setText(parser.parse("superUserLabel") + " " + parser.parse("true"));
superUserVersion_rootLabel.setText(parser.parse("suVersionLabel") + " " + su_version);
} else {
superUserStatus_rootLabel.setText(parser.parse("superUserLabel") + " " + parser.parse("false"));
superUserVersion_rootLabel.setText(parser.parse("suVersionLabel") + " ---");
}
if (busybox_isInstalled) {
busyboxStatus_rootLabel.setText(parser.parse("busyboxLabel") + " " + parser.parse("true"));
busyboxVersion_rootLabel.setText(parser.parse("busyboxVersionLabel") + " " + busybox_version);
} else {
busyboxStatus_rootLabel.setText(parser.parse("busyboxLabel") + " " + parser.parse("false"));
busyboxVersion_rootLabel.setText(parser.parse("busyboxVersionLabel") + " ---");
}
}
}
}.start();
} | 4 |
public void doHDMA() {
if (frameDisabled || !hdmaEnabled) return;
if (doTransfer) {
if (direction == false) hdmaWritePPU();
else hdmaReadPPU();
}
rlc = Util.limit(Size.BYTE, rlc-1);
doTransfer = isRepeat();
if (getLineCounter() == 0) {
rlc = Core.mem.get(Size.BYTE, srcBank, tableAddr);
tableAddr++;
if (addressMode == true) { // Indirect
transferSize = Core.mem.get(Size.SHORT, srcBank, tableAddr);
tableAddr += 2;
}
// Handle special case if rlc == 0(rlc is $43xA)
// SEE: http://wiki.superfamicom.org/snes/show/DMA+%26+HDMA
if (rlc == 0) {
frameDisabled = true;
}
doTransfer = true;
}
} | 7 |
public void Read(RandomAccessFile raf) throws Exception
{
this.id = raf.readInt();
this.Name = raf.readUTF();
this.height = raf.readDouble();
} | 0 |
public static double power(double number, int power) {
if (power < 0) {
throw new IllegalArgumentException("Error: int cannot be < 0!");
}
double answer = 1;
for (int j = 0; j < power; j++) {
answer *= number;
}
return answer;
} | 2 |
private void freePlayerAction(Player user, FreePlayerData data) {
if(user.getPosition() instanceof Jail) {
if(data.isUseJailbreak() && user.hasJailbreak()) {
user.useJailbreak();
} else {
((Jail) user.getPosition()).payFine(user);
}
}
} | 3 |
public static void addConnection(String nom, String hashtag) {
Connection con = null;
try {
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:" + Parametre.workspace + "/bdd_models");
Statement stmt = con.createStatement();
ResultSet rs;
ResultSet rs2;
ResultSet rs3;
rs = stmt.executeQuery("select nom from modeles where nom='" + nom + "'");
if (rs.next() != false && rs.getString("nom").equals(nom)) {
insertTag(hashtag);
rs3 = stmt.executeQuery("select nom from correspondances where nom='" + nom + "' and tag='" + hashtag + "'");
if (rs3.next() != false && rs3.getString("nom").equals(nom)) {
System.out.println("cette correspondace existe deja");
} else {
System.out.println("insertion dan la table de correspondances");
stmt.executeUpdate("insert into correspondances values('" + hashtag + "', '" + nom + "')");
}
} else {
System.out.println("ce modele n'existe pas");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} | 6 |
public final synchronized void close(){
if(fileFound){
try{
input.close();
}catch(java.io.IOException e){
System.out.println(e);
}
}
} | 2 |
private static void doImportFromXML() throws MVDException
{
try
{
if ( xmlFile != null && new File(xmlFile).exists()
&& textFile == null && !new File(mvdFile).exists() )
{
// importing from XML to MVD
File xml = new File( xmlFile );
MVD m = MVDXMLFile.internalise( xml );
MVDFile.externalise( m, new File(mvdFile),
folderId, Utilities.loadDBProperties(dbConn) );
}
}
catch ( Exception e )
{
throw new MVDToolException( e );
}
} | 5 |
public boolean equals(Object object)
{
if(object == this) {
return true;
}
if(!(object instanceof Persoon)) {
return false;
}
Persoon cobj = (Persoon) object;
return (
cobj.bsn==this.bsn &&
cobj.voornaam.equals(this.voornaam) &&
cobj.achternaam.equals(this.achternaam) &&
cobj.dag == this.dag &&
cobj.maand == this.maand &&
cobj.jaar == this.jaar &&
cobj.geslacht == this.geslacht &&
cobj.dienblad == this.dienblad
);
} | 9 |
public List<String> readBdbLogFile(String bdbLogFilePath) throws LogAnalyseException {
if (StringUtils.isBlank(bdbLogFilePath)) {
throw new LogAnalyseException("bdb log file path is null");
}
File bdbLogFile = new File(bdbLogFilePath);
if (!bdbLogFile.exists()) {
throw new LogAnalyseException(String.format("bdb log file(path:%s) is not exist!", bdbLogFilePath));
}
BufferedReader fis = null;
try {
fis = new BufferedReader(new FileReader(bdbLogFile));
String line = null;
List<String> bdbFileLogContentList = new ArrayList<String>();
while ((line = fis.readLine()) != null) {
String hadoopLogFileLine = transferBdbToHadoopLine(line);
if (hadoopLogFileLine != null) {
bdbFileLogContentList.addAll(Arrays.asList(hadoopLogFileLine.split(AnalyseConstants.MULTI_LINE_SPLITTER)));
}
}
mergeReachedBdbLogData(bdbFileLogContentList);
return bdbFileLogContentList;
} catch (FileNotFoundException e) {
throw new LogAnalyseException(e);
} catch (IOException e) {
throw new LogAnalyseException(e);
} finally {
try {
fis.close();
} catch (IOException e) {
}
}
} | 7 |
@Override
public Object clone()
{
mxCellState clone = new mxCellState(view, cell, style);
if (label != null)
{
clone.label = label;
}
if (absolutePoints != null)
{
clone.absolutePoints = new ArrayList<mxPoint>();
for (int i = 0; i < absolutePoints.size(); i++)
{
clone.absolutePoints.add((mxPoint) absolutePoints.get(i)
.clone());
}
}
if (origin != null)
{
clone.origin = (mxPoint) origin.clone();
}
if (absoluteOffset != null)
{
clone.absoluteOffset = (mxPoint) absoluteOffset.clone();
}
if (labelBounds != null)
{
clone.labelBounds = (mxRectangle) labelBounds.clone();
}
if (boundingBox != null)
{
clone.boundingBox = (mxRectangle) boundingBox.clone();
}
clone.terminalDistance = terminalDistance;
clone.segments = segments;
clone.length = length;
clone.x = x;
clone.y = y;
clone.width = width;
clone.height = height;
return clone;
} | 7 |
@Override
public boolean equals(Object obj)
{
if(obj instanceof Item)
{
Item i = (Item) obj;
if(this.name.equals(i.name))
if(this.weight == i.weight)
return true;
}
return false;
} | 3 |
protected void setUp() throws Exception{
super.setUp();
unAuto = new Auto();
unTodoTerreno = new TodoTerreno();
unaMoto = new Moto();
unControlPolicial = new ControlPolicial();
if (unControlPolicial.numeroActual()<50){puntosAuto = 3;}
if (unControlPolicial.numeroActual()<30){puntosTodoTerreno =3;}
if (unControlPolicial.numeroActual()<80){puntosMoto =3;}
} | 3 |
public void copyToPencilMode() {
for(int i = 0; i < 16; i++) {
for(int j = 0; j < 16; j++) {
if((pencilEntries[i][j].isEditable()) && (pencilEntries[i][j].getText().equals(""))) {
pencilEntries[i][j].setText(entries[i][j].getText());
}
}
}
} | 4 |
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(tickID==Tickable.TICKID_MOB)
{
if((affected!=null)
&&(affected instanceof MOB)
&&(invoker!=null))
{
final MOB mob=(MOB)affected;
if(((mob.amFollowing()!=invoker)
||(mob.amDead())
||(mob.amFollowing().getGroupMembers(new HashSet<MOB>()).size()>2)
||(mob.charStats().getMyRace() != invoker.charStats().getMyRace())
||(mob.location()!=invoker.location())))
unInvoke();
}
}
return super.tick(ticking,tickID);
} | 9 |
public String preCreateAssignment() {
topics = topicModel.getAll(false);
classs = classModel.getAll();
boolean check = true;
if (topics.isEmpty()) {
addFieldError("asmo.topicId", "Topic List is empty");
check = false;
}
if (classs.isEmpty()) {
addFieldError("asmo.classname", "Class List is empty");
check = false;
}
if (check) {
for (TopicObj topicObj : topics) {
mTopic.put(topicObj.getTopicId(), topicObj.getName());
}
for (ClassObj classObj : classs) {
mClass.put(classObj.getClassname(), classObj.getClassname());
}
}
return SUCCESS;
} | 5 |
@Override
public long sizeOf() {
return mContent.length();
} | 0 |
public static BigDecimal toDecimal(int precision, int scale, byte[] value) {
//
final boolean positive = (value[0] & 0x80) == 0x80;
value[0] ^= 0x80;
if (!positive) {
for (int i = 0; i < value.length; i++) {
value[i] ^= 0xFF;
}
}
//
final int x = precision - scale;
final int ipDigits = x / DIGITS_PER_4BYTES;
final int ipDigitsX = x - ipDigits * DIGITS_PER_4BYTES;
final int ipSize = (ipDigits << 2) + DECIMAL_BINARY_SIZE[ipDigitsX];
int offset = DECIMAL_BINARY_SIZE[ipDigitsX];
BigDecimal ip = offset > 0 ? BigDecimal.valueOf(CodecUtils.toInt(value, 0, offset)) : BigDecimal.ZERO;
for(; offset < ipSize; offset += 4) {
final int i = CodecUtils.toInt(value, offset, 4);
ip = ip.movePointRight(DIGITS_PER_4BYTES).add(BigDecimal.valueOf(i));
}
//
int shift = 0;
BigDecimal fp = BigDecimal.ZERO;
for (; shift + DIGITS_PER_4BYTES <= scale; shift += DIGITS_PER_4BYTES, offset += 4) {
final int i = CodecUtils.toInt(value, offset, 4);
fp = fp.add(BigDecimal.valueOf(i).movePointLeft(shift + DIGITS_PER_4BYTES));
}
if(shift < scale) {
final int i = CodecUtils.toInt(value, offset, DECIMAL_BINARY_SIZE[scale - shift]);
fp = fp.add(BigDecimal.valueOf(i).movePointLeft(scale));
}
//
return positive ? POSITIVE_ONE.multiply(ip.add(fp)) : NEGATIVE_ONE.multiply(ip.add(fp));
} | 7 |
protected String makeIndentStr(int indent) {
String tabSpaceString = /* (tab x 20) . (space x 20) */
"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ";
if (indent < 0)
return "NEGATIVEINDENT" + indent;
int tabs = indent / tabWidth;
indent -= tabs * tabWidth;
if (tabs <= 20 && indent <= 20) {
/* The fast way. */
return tabSpaceString.substring(20 - tabs, 20 + indent);
} else {
/* the not so fast way */
StringBuffer sb = new StringBuffer(tabs + indent);
while (tabs > 20) {
sb.append(tabSpaceString.substring(0, 20));
tabs -= 20;
}
sb.append(tabSpaceString.substring(0, tabs));
while (indent > 20) {
sb.append(tabSpaceString.substring(20));
indent -= 20;
}
sb.append(tabSpaceString.substring(40 - indent));
return sb.toString();
}
} | 5 |
static public ObjectFlag fromLetter(final char c) {
switch (c) {
case 'B': return BANK;
case 'D': return DARK;
case 'G': return GUEST;
case 'F': return FORGE;
case 'H': return HOUSE;
case 'M': return MERCHANT;
case 'S': return SILENT;
case 'Q': return QUIET;
case 'V': return VENDOR;
default: throw new IllegalArgumentException("Invalid ObjectFlag letter: " + c);
}
} | 9 |
public static String changeXY(String str) {
if(str.length()==0){
return str;
}
else if(str.length()==1 && str.equals("x")){
String s=str.replace(str.substring(str.length()-1),"y");
return s;
}
else if(str.length()==1 && ! str.equals("x")){
return str;
}
else{
if(str.substring(str.length()-1).equals("x")){
String s=str.replace(str.substring(str.length()-1),"y");
return changeXY(s)+ str.substring(str.length()-1);
}
else{
return changeXY(str.substring(0,str.length()-1))+str.substring(str.length()-1);
}
}
} | 6 |
public SystemUI()
{
_instance = this;
_timeSheetCtrl = new TimeSheetCtrl();
_clientCtrl = new ClientCtrl();
_searchCtrl = new SearchCtrl();
setIconImage(Toolkit.getDefaultToolkit().getImage(SystemUI.class.getResource("/icons/48x48/app.png")));
setTitle(SystemInformation.systemInformation(1) + " (" + SystemInformation.systemInformation(2) +
" - build " + SystemInformation.systemInformation(3) + ")");
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
WindowListener exitListener = new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
applicationExit();
}
};
addWindowListener(exitListener);
setBounds(0,0,1024,768);
setLocationRelativeTo(null);
setMinimumSize(new Dimension(1024,768));
setResizable(false);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFiles = new JMenu("Filer");
mnFiles.setFont(new Font("Dialog", Font.PLAIN, 12));
menuBar.add(mnFiles);
JMenuItem mntmPrint = new JMenuItem("Udskriv");
mntmPrint.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
printSheet();
}
});
mnFiles.add(mntmPrint);
JSeparator separator = new JSeparator();
mnFiles.add(separator);
JMenuItem mntmLogout = new JMenuItem("Logud");
mntmLogout.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
applicationLogout();
}
});
mnFiles.add(mntmLogout);
JMenuItem mntmExit = new JMenuItem("Afslut");
mntmExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
applicationExit();
}
});
mnFiles.add(mntmExit);
JMenu mnTimeSheet = new JMenu("Time-sag");
mnTimeSheet.setFont(new Font("Dialog", Font.PLAIN, 12));
menuBar.add(mnTimeSheet);
JMenuItem mntmNewTimeSheet = new JMenuItem("Ny time-sag");
mntmNewTimeSheet.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CreateTimeSheetUI.createWindow();
}
});
mnTimeSheet.add(mntmNewTimeSheet);
JMenu mnClient = new JMenu("Klient");
mnClient.setFont(new Font("Dialog", Font.PLAIN, 12));
menuBar.add(mnClient);
JMenuItem mntmNewClient = new JMenuItem("Ny klient");
mntmNewClient.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CreateClientUI.createWindow();
}
});
mnClient.add(mntmNewClient);
JMenuItem mntmEditClient = new JMenuItem("Rediger klient");
mntmEditClient.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
}
});
mnClient.add(mntmEditClient);
JMenu mnSettings = new JMenu("Indstillinger");
mnSettings.setFont(new Font("Dialog", Font.PLAIN, 12));
menuBar.add(mnSettings);
JMenuItem mntmPrintSettings = new JMenuItem("Udskrift");
mntmPrintSettings.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
PrintSettingsUI.createWindow();
}
});
mnSettings.add(mntmPrintSettings);
JMenu mnAbout = new JMenu("Om");
mnAbout.setFont(new Font("Dialog", Font.PLAIN, 12));
menuBar.add(mnAbout);
JMenuItem mntmAboutThis = new JMenuItem("Applikationen");
mntmAboutThis.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
AboutUI.createWindow();
}
});
mnAbout.add(mntmAboutThis);
pnlSystemLayout = new JPanel();
pnlSystemLayout.setBorder(new EmptyBorder(5,5,5,5));
setContentPane(pnlSystemLayout);
pnlSystemLayout.setLayout(null);
JPanel pnlQuickAccess = new JPanel();
pnlQuickAccess.setBounds(5,0,1014,37);
pnlSystemLayout.add(pnlQuickAccess);
pnlQuickAccess.setLayout(null);
JLabel lblNewTimeSheet = new JLabel("Ny time-sag");
lblNewTimeSheet.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
CreateTimeSheetUI.createWindow();
}
});
lblNewTimeSheet.setFont(new Font("Dialog", Font.PLAIN, 12));
lblNewTimeSheet.setCursor(new Cursor(Cursor.HAND_CURSOR));
lblNewTimeSheet.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/new_timesheet.png")));
lblNewTimeSheet.setBounds(5,12,95,16);
pnlQuickAccess.add(lblNewTimeSheet);
JLabel lblNewDataEntry = new JLabel("Ny registrering");
lblNewDataEntry.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
newDataEntry();
}
});
lblNewDataEntry.setFont(new Font("Dialog", Font.PLAIN, 12));
lblNewDataEntry.setCursor(new Cursor(Cursor.HAND_CURSOR));
lblNewDataEntry.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/new_dataentry.png")));
lblNewDataEntry.setBounds(115,12,114,16);
pnlQuickAccess.add(lblNewDataEntry);
JLabel lblNewClient = new JLabel("Ny klient");
lblNewClient.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
CreateClientUI.createWindow();
}
});
lblNewClient.setFont(new Font("Dialog", Font.PLAIN, 12));
lblNewClient.setCursor(new Cursor(Cursor.HAND_CURSOR));
lblNewClient.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/new_client.png")));
lblNewClient.setBounds(244,12,75,16);
pnlQuickAccess.add(lblNewClient);
JLabel lblPrintOverview = new JLabel("Udskriv");
lblPrintOverview.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
printSheet();
}
});
lblPrintOverview.setFont(new Font("Dialog", Font.PLAIN, 12));
lblPrintOverview.setCursor(new Cursor(Cursor.HAND_CURSOR));
lblPrintOverview.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/print_overview.png")));
lblPrintOverview.setBounds(333,12,68,16);
pnlQuickAccess.add(lblPrintOverview);
JLabel lblSortOverview = new JLabel("Sort" + "\u00e9" + "r");
lblSortOverview.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
SortUI.createWindow();
}
});
lblSortOverview.setFont(new Font("Dialog", Font.PLAIN, 12));
lblSortOverview.setCursor(new Cursor(Cursor.HAND_CURSOR));
lblSortOverview.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/sort_overview.png")));
lblSortOverview.setBounds(416,12,60,16);
pnlQuickAccess.add(lblSortOverview);
JLabel lblPermission = new JLabel("Rettigheder");
lblPermission.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
editRights();
}
});
lblPermission.setFont(new Font("Dialog", Font.PLAIN, 12));
lblPermission.setCursor(new Cursor(Cursor.HAND_CURSOR));
lblPermission.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/permission_timesheet.png")));
lblPermission.setBounds(493,12,114,16);
pnlQuickAccess.add(lblPermission);
JLabel lblSearchOverview = new JLabel();
lblSearchOverview.setCursor(new Cursor(Cursor.HAND_CURSOR));
lblSearchOverview.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/search_overview.png")));
lblSearchOverview.setBounds(833,12,16,16);
pnlQuickAccess.add(lblSearchOverview);
txtSearchOverview = new JTextField();
txtSearchOverview.addFocusListener(new FocusAdapter()
{
@Override
public void focusGained(FocusEvent e)
{
txtSearchOverview.setText("");
}
@Override
public void focusLost(FocusEvent e)
{
txtSearchOverview.setText("S\u00F8g");
}
});
txtSearchOverview.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
try
{
SearchUI.createWindow(_searchCtrl.search(txtSearchOverview.getText()));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
});
txtSearchOverview.setText("S\u00F8g");
txtSearchOverview.setBounds(854,9,155,22);
pnlQuickAccess.add(txtSearchOverview);
txtSearchOverview.setColumns(10);
JPanel pnlOverviewSelection = new JPanel();
pnlOverviewSelection.setBounds(5,36,215,675);
pnlSystemLayout.add(pnlOverviewSelection);
pnlOverviewSelection.setLayout(null);
// START OF TIMESHEETS PANEL
pnlTimeSheet = new JPanel();
pnlTimeSheet.setBounds(220,36,799,675);
pnlSystemLayout.add(pnlTimeSheet);
pnlTimeSheet.setLayout(null);
// START OF TS_INFO PANEL
JPanel pnlTimeSheetInfo = new JPanel();
pnlTimeSheetInfo.setBorder(new LineBorder(Color.LIGHT_GRAY));
pnlTimeSheetInfo.setBackground(Color.WHITE);
pnlTimeSheetInfo.setBounds(3,2,790,86);
pnlTimeSheet.add(pnlTimeSheetInfo);
pnlTimeSheetInfo.setLayout(null);
lblClientName_ts = new JLabel();
lblClientName_ts.setForeground(UIManager.getColor("CheckBoxMenuItem.acceleratorForeground"));
lblClientName_ts.setFont(new Font("Dialog", Font.PLAIN, 18));
lblClientName_ts.setBounds(5,5,500,20);
pnlTimeSheetInfo.add(lblClientName_ts);
lblCaseId_ts = new JLabel();
lblCaseId_ts.setHorizontalAlignment(SwingConstants.RIGHT);
lblCaseId_ts.setForeground(UIManager.getColor("CheckBoxMenuItem.acceleratorForeground"));
lblCaseId_ts.setFont(new Font("Dialog", Font.PLAIN, 18));
lblCaseId_ts.setBounds(535,5,250,20);
pnlTimeSheetInfo.add(lblCaseId_ts);
lblClientAddress_ts = new JLabel();
lblClientAddress_ts.setForeground(Color.GRAY);
lblClientAddress_ts.setFont(new Font("Dialog", Font.PLAIN, 12));
lblClientAddress_ts.setBounds(5,25,500,15);
pnlTimeSheetInfo.add(lblClientAddress_ts);
lblClientPhoneNo_ts = new JLabel();
lblClientPhoneNo_ts.setFont(new Font("Dialog", Font.PLAIN, 12));
lblClientPhoneNo_ts.setBounds(5,52,450,15);
pnlTimeSheetInfo.add(lblClientPhoneNo_ts);
lblClientEmail_ts = new JLabel();
lblClientEmail_ts.setFont(new Font("Dialog", Font.PLAIN, 12));
lblClientEmail_ts.setBounds(5,66,450,15);
pnlTimeSheetInfo.add(lblClientEmail_ts);
lblTimeSheetOwner_ts = new JLabel();
lblTimeSheetOwner_ts.setHorizontalAlignment(SwingConstants.RIGHT);
lblTimeSheetOwner_ts.setFont(new Font("Dialog", Font.PLAIN, 12));
lblTimeSheetOwner_ts.setBounds(485,66,300,15);
pnlTimeSheetInfo.add(lblTimeSheetOwner_ts);
// END OF TS_INFO PANEL
// START OF NOTE PANEL
JPanel pnlTimeSheetNote = new JPanel();
pnlTimeSheetNote.setBackground(Color.WHITE);
pnlTimeSheetNote.setBorder(new LineBorder(Color.LIGHT_GRAY));
pnlTimeSheetNote.setBounds(3,99,790,65);
pnlTimeSheet.add(pnlTimeSheetNote);
pnlTimeSheetNote.setLayout(null);
txtNoteField = new JTextArea();
txtNoteField.setBounds(5,5,780,55);
txtNoteField.setEditable(false);
pnlTimeSheetNote.add(txtNoteField);
// END OF NOTE PANEL
// START OF SHEETGRID
JPanel pnlTimeSheetOverview = new JPanel();
pnlTimeSheetOverview.setBounds(3,170,790,498);
pnlTimeSheet.add(pnlTimeSheetOverview);
sheetColumn = new String[]{"P" + "\u00e5" + "begyndt", "Afsluttet", "Opgave", "Registrator", "Bem" + "\u00e6" + "rkning", " "};
sheetTable = new JTable()
{
public boolean isCellEditable(int data, int columns)
{
if(columns == 5 || columns == 6)
return true;
return false;
}
};
sheetModel = new DefaultTableModel();
sheetTable.setModel(sheetModel);
sheetTable.setFillsViewportHeight(true);
JScrollPane sheetDataScroll = new JScrollPane(sheetTable);
sheetTable.setBorder(new LineBorder(Color.LIGHT_GRAY));
sheetTable.setPreferredScrollableViewportSize(new Dimension(790,493));
sheetDataScroll.setPreferredSize(new Dimension(790,493));
sheetDataScroll.setBorder(BorderFactory.createEmptyBorder());
pnlTimeSheetOverview.add(sheetDataScroll);
// END OF SHEETGRID
// END OF TIMESHEETS PANEL
// START OF CLIENTS PANEL
pnlClients = new JPanel();
pnlClients.setBounds(220,36,799,675);
pnlSystemLayout.add(pnlClients);
pnlClients.setLayout(null);
// START OF CL_INFO PANEL
JPanel pnlClientInfo = new JPanel();
pnlClientInfo.setLayout(null);
pnlClientInfo.setBorder(new LineBorder(Color.LIGHT_GRAY));
pnlClientInfo.setBackground(Color.WHITE);
pnlClientInfo.setBounds(3,2,790,86);
pnlClients.add(pnlClientInfo);
lblClientName_cl = new JLabel();
lblClientName_cl.setForeground(UIManager.getColor("CheckBoxMenuItem.acceleratorForeground"));
lblClientName_cl.setFont(new Font("Dialog", Font.PLAIN, 18));
lblClientName_cl.setBounds(5,5,500,20);
pnlClientInfo.add(lblClientName_cl);
lblClientAddress_cl = new JLabel();
lblClientAddress_cl.setForeground(Color.GRAY);
lblClientAddress_cl.setFont(new Font("Dialog", Font.PLAIN, 12));
lblClientAddress_cl.setBounds(5,25,500,15);
pnlClientInfo.add(lblClientAddress_cl);
lblClientPhoneNo_cl = new JLabel();
lblClientPhoneNo_cl.setFont(new Font("Dialog", Font.PLAIN, 12));
lblClientPhoneNo_cl.setBounds(5,52,450,15);
pnlClientInfo.add(lblClientPhoneNo_cl);
lblClientEmail_cl = new JLabel();
lblClientEmail_cl.setFont(new Font("Dialog", Font.PLAIN, 12));
lblClientEmail_cl.setBounds(5,66,450,15);
pnlClientInfo.add(lblClientEmail_cl);
// END OF CL_INFO PANEL
// START OF CLIENTGRID
JPanel pnlClientOverview = new JPanel();
pnlClientOverview.setBounds(3,94,790,574);
pnlClients.add(pnlClientOverview);
clientColumn = new String[]{"Sags nr", "Oprettet", "Ansvarlig", "Note", " "};
clientTable = new JTable()
{
public boolean isCellEditable(int data, int columns)
{
if(columns == 4 || columns == 5)
return true;
return false;
}
};
clientModel = new DefaultTableModel();
clientTable.setModel(clientModel);
clientTable.setFillsViewportHeight(true);
JScrollPane clientDataScroll = new JScrollPane(clientTable);
clientTable.setBorder(new LineBorder(Color.LIGHT_GRAY));
clientTable.setPreferredScrollableViewportSize(new Dimension(790,569));
clientDataScroll.setPreferredSize(new Dimension(790,569));
clientDataScroll.setBorder(BorderFactory.createEmptyBorder());
pnlClientOverview.add(clientDataScroll);
// END OF CLIENTGRID
// END OF CLIENTS PANEL
// START OF TAB SECTION
JTabbedPane tabSelection = new JTabbedPane(JTabbedPane.TOP);
tabSelection.setFont(new Font("Dialog", Font.PLAIN, 12));
tabSelection.setBounds(5, 0, 202, 668);
tabSelection.addChangeListener(this);
pnlOverviewSelection.add(tabSelection);
// START OF CASE TAB
JPanel pnlTimeSheetTab = new JPanel();
tabSelection.addTab("Time-sager", null, pnlTimeSheetTab, null);
pnlTimeSheetTab.setLayout(null);
JPanel pnlSheetList = new JPanel();
pnlSheetList.setBounds(5,5,187,605);
pnlSheetList.setLayout(null);
pnlTimeSheetTab.add(pnlSheetList);
lstTimeSheets = new JList<String>();
lstTimeSheets.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
dbInfo.setVisible(true);
addSheetData();
}
});
lstTimeSheets.setListData(populateSheetList());
lstTimeSheets.setFont(new Font("Dialog", Font.PLAIN, 12));
lstTimeSheets.setBorder(new LineBorder(Color.LIGHT_GRAY));
lstTimeSheets.setBounds(0,0,187,605);
JScrollPane sheetListScroll = new JScrollPane(lstTimeSheets);
pnlSheetList.add(sheetListScroll);
pnlSheetList.add(lstTimeSheets);
chkUsersSheetsOnly = new JCheckBox("Vis kun mine sager");
chkUsersSheetsOnly.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
checkUserSheetsOnly();
}
});
chkUsersSheetsOnly.setFont(new Font("Dialog", Font.PLAIN, 12));
chkUsersSheetsOnly.setBounds(5,614,160,23);
pnlTimeSheetTab.add(chkUsersSheetsOnly);
JLabel lblRefreshTs = new JLabel();
lblRefreshTs.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
refreshList();
}
});
lblRefreshTs.setCursor(new Cursor(Cursor.HAND_CURSOR));
lblRefreshTs.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/list_refresh.png")));
lblRefreshTs.setBounds(170,617,16,16);
pnlTimeSheetTab.add(lblRefreshTs);
// END OF CASE TAB
// START OF CLIENT TAB
JPanel pnlClientTab = new JPanel();
tabSelection.addTab("Klienter", null, pnlClientTab, null);
pnlClientTab.setLayout(null);
JPanel pnlClientList = new JPanel();
pnlClientList.setBounds(5,5,187,605);
pnlClientList.setLayout(null);
pnlClientTab.add(pnlClientList);
lstClients = new JList<String>();
lstClients.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
dbInfo.setVisible(true);
addClientData();
}
});
lstClients.setListData(populateClientList());
lstClients.setFont(new Font("Dialog", Font.PLAIN, 12));
lstClients.setBorder(new LineBorder(Color.LIGHT_GRAY));
lstClients.setBounds(0,0,187,605);
JScrollPane clientListScroll = new JScrollPane(lstClients);
pnlClientList.add(clientListScroll);
pnlClientList.add(lstClients);
JLabel lblRefreshCli = new JLabel();
lblRefreshCli.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
refreshList();
}
});
lblRefreshCli.setCursor(new Cursor(Cursor.HAND_CURSOR));
lblRefreshCli.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/list_refresh.png")));
lblRefreshCli.setBounds(170,617,16,16);
pnlClientTab.add(lblRefreshCli);
// END OF CLIENT TAB
// END OF TAB SECTION
} | 6 |
public String numeroALetra(String numero, boolean mayusculas) {
String literal = "";
String parte_decimal;
//si el numero utiliza (.) en lugar de (,) -> se reemplaza
numero = numero.replace(".", ",");
//si el numero no tiene parte decimal, se le agrega ,00
if (numero.indexOf(",") == -1) {
numero = numero + ",00";
}
//se valida formato de entrada -> 0,00 y 999 999 999,00
if (Pattern.matches("\\d{1,9},\\d{1,2}", numero)) {
//se divide el numero 0000000,00 -> entero y decimal
String Num[] = numero.split(",");
//de da formato al numero decimal
parte_decimal = "con " + (Num[1].length() <= 1 ? Num[1] + "0" : Num[1]) + "/100 Nuevos Soles.";
//se convierte el numero a literal
if (Integer.parseInt(Num[0]) == 0) {//si el valor es cero
literal = "cero ";
} else if (Integer.parseInt(Num[0]) > 999999) {//si es millon
literal = getMillones(Num[0]);
} else if (Integer.parseInt(Num[0]) > 999) {//si es miles
literal = getMiles(Num[0]);
} else if (Integer.parseInt(Num[0]) > 99) {//si es centena
literal = getCentenas(Num[0]);
} else if (Integer.parseInt(Num[0]) > 9) {//si es decena
literal = getDecenas(Num[0]);
} else {//sino unidades -> 9
literal = getUnidades(Num[0]);
}
//devuelve el resultado en mayusculas o minusculas
if (mayusculas) {
return (literal).toUpperCase();
} else {
return (literal);
}
} else {//error, no se puede convertir
return literal = null;
}
} | 9 |
public String getUpdate(String appKey, String userKey, String version) {
try {
appKey = URLEncoder.encode(appKey, "UTF-8");
userKey = URLEncoder.encode(userKey, "UTF-8");
version = URLEncoder.encode(version, "UTF-8");
} catch (UnsupportedEncodingException e) {
BmLog.error(e);
}
return String.format("%s/api/rest/blazemeter/jmeter_plugin_update/?app_key=%s&user_key=%s¤t_version=%s", SERVER_URL, appKey, userKey, version);
} | 1 |
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
final User user = (User) o;
return !(username != null ? !username.equals(user.getUsername()) : user.getUsername() != null);
} | 3 |
public MapleCustomQuest(int id) {
try {
this.id = id;
startActs = new LinkedList<MapleQuestAction>();
completeActs = new LinkedList<MapleQuestAction>();
startReqs = new LinkedList<MapleQuestRequirement>();
completeReqs = new LinkedList<MapleQuestRequirement>();
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("SELECT * FROM questrequirements WHERE questid = ?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
MapleQuestRequirement req;
MapleCustomQuestData data;
while (rs.next()) {
Blob blob = rs.getBlob("data");
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(blob.getBytes(1, (int) blob.length())));
data = (MapleCustomQuestData) ois.readObject();
req = new MapleQuestRequirement(this, MapleQuestRequirementType.getByWZName(data.getName()), data);
final byte status = rs.getByte("status");
if (status == 0) {
startReqs.add(req);
} else if (status == 1) {
completeReqs.add(req);
}
}
rs.close();
ps.close();
ps = DatabaseConnection.getConnection().prepareStatement("SELECT * FROM questactions WHERE questid = ?");
ps.setInt(1, id);
rs = ps.executeQuery();
MapleQuestAction act;
while (rs.next()) {
Blob blob = rs.getBlob("data");
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(blob.getBytes(1, (int) blob.length())));
data = (MapleCustomQuestData) ois.readObject();
act = new MapleQuestAction(MapleQuestActionType.getByWZName(data.getName()), data, this);
final byte status = rs.getByte("status");
if (status == 0) {
startActs.add(act);
} else if (status == 1) {
completeActs.add(act);
}
}
rs.close();
ps.close();
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("Error loading custom quest from SQL." + ex);
}
} | 7 |
public int FantasmaX(int n){
Query q2;
Variable a = new Variable("X");
Variable b = new Variable("Y");
switch(n){
case 0:
q2 = new Query("blinky", new Term[]{a,b});
return java.lang.Integer.parseInt(q2.oneSolution().get("X").toString());
case 1:
q2 = new Query("clyde", new Term[]{a,b});
return java.lang.Integer.parseInt(q2.oneSolution().get("X").toString());
case 2:
q2 = new Query("inky", new Term[]{a,b});
return java.lang.Integer.parseInt(q2.oneSolution().get("X").toString());
case 3:
q2 = new Query("pinky", new Term[]{a,b});
return java.lang.Integer.parseInt(q2.oneSolution().get("X").toString());
default:
return 0;
}
} | 4 |
public static Term fromString(String str){
String temp = new String(str);
TermImp result = null;
if (temp.contains("x^")){
// handle term with the form ax^n
StringTokenizer strTok = new StringTokenizer(temp, "x^");
List<String> list = new ArrayList<String>(2);
while(strTok.hasMoreElements()){
list.add((String) strTok.nextElement());
}
if (list.size() == 0){
throw new IllegalArgumentException("Argument string is formatter illegally.");
}
else if (list.size() == 1){
// term if of the form x^n, where n is the exponent
Integer expo = Integer.parseInt(list.get(0));
result = new TermImp(1, expo);
}
else {
// term if of the form ax^n, where a, (a != 1) is the coefficient and n is the exponent
Double coeff = Double.parseDouble(list.get(0));
Integer expo = Integer.parseInt(list.get(1));
result = new TermImp(coeff, expo);
}
}
else if (temp.contains("x")){
// handle value with exponent == 1
StringTokenizer strTok = new StringTokenizer(temp, "x");
List<String> list = new ArrayList<String>(2);
while(strTok.hasMoreElements()){
list.add((String) strTok.nextElement());
}
if (list.size() == 0){
// term is of the form x, with coefficient = 1 and exponent = 1
result = new TermImp(1.0, 1);
}
else {
// term is of the form ax, with coefficient = a and exponent = 1
Double coeff = Double.parseDouble(list.get(0));
result = new TermImp(coeff, 1);
}
}
else {
// handle numeric value
result = new TermImp(Double.parseDouble(temp), 0);
}
return result;
} | 7 |
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
txt2 = new javax.swing.JTextField();
txt3 = new javax.swing.JTextField();
txt4 = new javax.swing.JTextField();
txt5 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
btnCerrar = new javax.swing.JButton();
btnRegistrar = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
txt1 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel5.setText("Precio Unitario:");
jLabel4.setText("Cantidad:");
jLabel3.setText("Descripcion:");
jLabel2.setText("Nombre:");
btnCerrar.setText("Cerrar");
btnCerrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCerrarActionPerformed(evt);
}
});
btnRegistrar.setText("Registrar");
btnRegistrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRegistrarActionPerformed(evt);
}
});
jLabel1.setText("Codigo:");
txt1.setEditable(false);
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(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel1))
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txt2)
.addComponent(txt3)
.addComponent(txt4)
.addComponent(txt5, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)
.addComponent(txt1))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnRegistrar)
.addComponent(btnCerrar))
.addContainerGap(27, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txt1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnRegistrar)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(txt3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnCerrar)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(txt5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.