text stringlengths 14 410k | label int32 0 9 |
|---|---|
public Network(Layer[] layers) {
// проверки
if (layers == null || layers.length == 0) throw new IllegalArgumentException();
// проверим детально
final int size = layers.length;
for (int i = 0; i < size; i++)
if (layers[i] == null || (i > 1 && layers[i].getInputSize() != layers[i - 1].getSize()))
throw new IllegalArgumentException();
// запомним слои
this.layers = layers;
} | 6 |
public void draw(Graphics surface) {
// Draw the object
surface.setColor(color);
surface.fillRect(x - SIZE / 2, y - SIZE / 2, SIZE, SIZE);
surface.setColor(Color.BLACK);
((Graphics2D) surface).setStroke(new BasicStroke(3.0f));
surface.drawRect(x - SIZE / 2, y - SIZE / 2, SIZE, SIZE);
// Move the center of the object each time we draw it
x += xDirection;
y += yDirection;
// If we have hit the edge and are moving in the wrong direction,
// reverse direction
// We check the direction because if a box is placed near the wall, we
// would get "stuck"
// rather than moving in the right direction
if ((x - SIZE / 2 <= 0 && xDirection < 0)
|| (x + SIZE / 2 >= SimpleDraw.WIDTH && xDirection > 0)) {
xDirection = -xDirection;
}
if ((y - SIZE / 2 <= 0 && yDirection < 0)
|| (y + SIZE / 2 >= SimpleDraw.HEIGHT && yDirection > 0)) {
yDirection = -yDirection;
}
} | 8 |
public static Vault getPlayerVault(String player, int id)
{
if(hasCachedVault(player, id))
{
return getCachedVault(player, id);
}
Vault vault = new Vault(Config.getConfig().getInt("vault-rows"), player, id);
if(BackendType.equals(Backends.MySQL))
{
ResultSet results = sqlConnection.dbStm("SELECT * FROM " + Config.getConfig().getString("backend.mysql.table") + " WHERE Player='" + player + "' AND InventoryID='" + id + "'");
try {
while (results.next())
{
vault.setInventoryFromString(StringConvertion.numericToString(results.getString(3)));
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
results.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
else
{
try {
ItemStack items[] = SerializationUtil.loadInventory(VaultsConfig.getConfigurationSection(player + "." + id));
if(items != null)
{
for (ItemStack item : items)
{
if(item != null)
{
vault.getInventory().addItem(item);
}
}
}
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
}
return vault;
} | 9 |
@Override
public int count() {
return _source.length;
} | 0 |
private static void writeBestOrganism() throws Exception {
String path = "bestOrganism.txt";
EcritureTXTfichier toFile = new EcritureTXTfichier(path);
toFile.writeToFile(path);
List< List<Double>> answers_results = new ArrayList<>();
answers_results = neatANN.getBestOrganismAnswers();
for (int i = 0; i < answers_results.size(); i++) {
for (int j = 0; j < answers_results.get(i).size(); j++) {
toFile.appendToFile(true, answers_results.get(i).get(j));
}
toFile.appendToFile(true, "\n");
}
} | 2 |
public void seeQuizScore(User user){
List<Quiz> quizes = new ArrayList<Quiz>();
// initialise quiz model
QuizModel quizM = new QuizModel();
// list of all user quizes
quizes = quizM.getUserList(user.getId());
int i = 1;
try{
if(quizes.get(0).getId()>0){
UserInputManager inpM = new UserInputManager("INTIGER_PATTERT");
for(Quiz quiz:quizes){
inpM.setOption(Integer.toString(i));
System.out.println(i+" "+quiz.getName()+" status: "+((quiz.getStatus()>0)? "active": "disabled"));
i++;
}
List<Result> results = new ArrayList<Result>();
UserModel userM = new UserModel();
// get all results for that quiz
inpM.setMessage("");
results = userM.getUserResultsByQuizId(quizes.get(Integer.parseInt(inpM.askAction())-1).getId());
// show all players score
try{
if(results.get(0).getId()>0){
for(Result res:results){
System.out.println("score: "+res.getScore()+" Username: "+res.getUsername());
}
}
}// if no players were found
catch(IndexOutOfBoundsException e){
System.out.println("There are no players to show!");
}
}
}
catch(IndexOutOfBoundsException e){
System.out.println("There are no quizez to show!");
}
} | 7 |
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("USAGE: wc file");
System.exit(1);
}
Reader reader = null;
try {
reader = new FileReader(args[0]);
int nl = 0, nw = 0, nc = 0;
int data;
boolean inWord = false;
while ((data = reader.read()) != -1) {
char c = (char) data;
nc++;
if (c == '\n') nl++;
if (Character.isWhitespace(c)) {
inWord = false;
} else if (!inWord) {
nw++;
inWord = true;
}
}
System.out.format("%d %d %d %s\n", nl, nw, nc, args[0]);
} catch (FileNotFoundException nfe) {
System.err.println("ERROR: unable to open \"" + args[0] + "\" file");
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
}
}
} | 9 |
private void updateKeys()
{
for (int key = 0; key < keys.length; key++)
{
lastKeys[key] = keys[key];
keys[key] = Keyboard.isKeyDown(key);
}
} | 1 |
private JList<FolderConfig> buildLeftSideList(final JPanel left) {
final DefaultListModel<FolderConfig> listModel = new DefaultListModel<FolderConfig>();
final JList<FolderConfig> list = new JList<>(listModel);
if (!GuiUtils.syncConfig.getConfigs().isEmpty()) {
for (final FolderConfig folder : GuiUtils.syncConfig.getConfigs()) {
listModel.addElement(folder);
}
list.setSelectedIndex(0);
}
list.setCellRenderer(new FolderConfigRenderer());
list.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
final JPopupMenu menu = new JPopupMenu();
final JMenuItem add = new JMenuItem("Add");
add.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
GuiUtils.currentFolderConfig = new FolderConfig();
GuiUtils.currentFolderConfig.setArtistUrl("Artist URL");
GuiUtils.syncConfig.getConfigs().add(GuiUtils.currentFolderConfig);
listModel.addElement(GuiUtils.currentFolderConfig);
}
});
menu.add(add);
menu.addSeparator();
final int index = list.getSelectedIndex();
if (index >= 0) {
final JMenuItem remove = new JMenuItem("Remove");
remove.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
GuiUtils.syncConfig.getConfigs().remove(index);
listModel.remove(index);
}
});
menu.add(remove);
}
menu.show(list, e.getX(), e.getY());
}
}
});
left.add(list, BorderLayout.CENTER);
return list;
} | 4 |
private void doCloseCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(sender instanceof Player) {
ItemStack item = ((Player) sender).getItemInHand();
BookMeta meta = null;
Matcher titleMatcher = null;
if(item.getType() == Material.WRITTEN_BOOK) {
meta = (BookMeta) item.getItemMeta();
titleMatcher = TITLE_REGEX.matcher(meta.getTitle());
}
if(meta != null && titleMatcher != null && titleMatcher.matches()) {
String title = titleMatcher.group(1);
PetitionData petition = plugin.getPetitionStorage().getPetitionData(title);
if(petition != null) {
if(petition.addCloser((Player) sender)) {
sender.sendMessage("§aSuccessfully added added your mark to close the petition!");
} else {
sender.sendMessage("§3You have already marked that petition as closed!");
}
} else {
sender.sendMessage("§4Couldn't find petition (probably has been deleted)");
}
} else {
sender.sendMessage("§4You must have the petition you want to mark as closed in your hand!");
}
} else {
sender.sendMessage("§4Please log onto the server as a player to mark a petition as closed");
}
} | 7 |
void sortList(List<Integer> list, int k)
{
if(k == 0) return;
int val = list.get(0);
List<Integer> leftList = new ArrayList<Integer>();
List<Integer> rightList = new ArrayList<Integer>();
int left = 0;
int right = 0;
for(int i = 1; i<list.size(); i++){
if(list.get(i)<val){
leftList.add(list.get(i));
left++;
}
if(list.get(i) >= val){
rightList.add(list.get(i));
right++;
}
}
if(right == k){
maxList.addAll(rightList);
return;
}
if(right > k){
sortList(rightList, k);
return;
}
if(right < k){
maxList.addAll(rightList);
maxList.add(val);
k = k-right-1;
sortList(leftList, k);
return;
}
} | 7 |
public void putAll( Map<? extends K, ? extends Character> map ) {
Iterator<? extends Entry<? extends K,? extends Character>> it = map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends K,? extends Character> e = it.next();
this.put( e.getKey(), e.getValue() );
}
} | 8 |
@Override
public String getElementAt(int index) {
if(getSize() <= 0 || getSize() <= index) {
return "Ups,not that many Entries!";
}
return FW.getObjectNames().get(index);
} | 2 |
public void startmaingame() {
if (k != 10 && k >= 1) {
k--;
}
else if (k == 0 && introduction == 0) {
k = 10;
getWorld().removeObjects(getWorld().getObjects(Blowfish.class));
getWorld().removeObjects(getWorld().getObjects(Jellyfish.class));
getWorld().removeObjects(getWorld().getObjects(Shark.class));
getWorld().removeObjects(getWorld().getObjects(Eel.class));
getWorld().removeObjects(getWorld().getObjects(Swordfish.class));
getWorld().removeObjects(getWorld().getObjects(Ray.class));
getWorld().removeObjects(getWorld().getObjects(check.class));
getWorld().removeObjects(getWorld().getObjects(introduction.class));
getWorld().removeObjects(getWorld().getObjects(controlsicon.class));
//Greenfoot.setWorld(new world());
getWorld().addObject(new rockcounter(), 60, 100);
getWorld().addObject(new rocksleft(), 70, 20);
getWorld().addObject(new rocksleftcount(), 155, 20);
getWorld().addObject(new score(), 670, 20);
getWorld().addObject(new scorecounter(), 720, 20);
getWorld().addObject(new health(), 370, 20);
getWorld().addObject(new display(), 435, 20);
getWorld().addObject(new Dolphin(), 400, 300);
world dolphinworld = (world) getWorld();
maingame++;
bevorestart.stop();
dolphinworld.musicplay(); // starts the mainmusic
getWorld().removeObject(this);
}
else if (k == 0 && introduction == 1) {
getWorld().addObject(new turtle(), 0, 450);
getWorld().removeObjects(getWorld().getObjects(Blowfish.class));
getWorld().removeObjects(getWorld().getObjects(Jellyfish.class));
getWorld().removeObjects(getWorld().getObjects(Shark.class));
getWorld().removeObjects(getWorld().getObjects(Eel.class));
getWorld().removeObjects(getWorld().getObjects(Swordfish.class));
getWorld().removeObjects(getWorld().getObjects(Ray.class));
getWorld().removeObjects(getWorld().getObjects(check.class));
getWorld().removeObjects(getWorld().getObjects(introduction.class));
getWorld().removeObjects(getWorld().getObjects(controlsicon.class));
getWorld().removeObject(this);
}
} | 6 |
private void updateLists() {
for (int i = 0; i < spaceJunk.size(); i++) {
spaceJunk.get(i).update();
}
for (int i = 0; i < planets.size(); i++) {
planets.get(i).update();
}
for (int i = 0; i < bullets.size(); i++) {
bullets.get(i).update();
if (bullets.get(i).remove()) {
bullets.remove(i);
}
}
for (int i = 0; i < debris.size(); i++) {
debris.get(i).update();
if (debris.get(i).remove()) {
debris.remove(i);
}
}
} | 6 |
public MessageBuilder build() {
for (String sender : this.senders) {
String message = this.message;
Config messages_config = this.message_config;
String finalmessage;
if (messages_config != null) {
if (messages_config.getFile().get(message) != null) {
finalmessage = (String) messages_config.getFile().get(
message);
} else {
finalmessage = "&9[" + AdminEye.pdfFile.getName()
+ "] &cERROR: Message string &e" + message
+ "&c has not been found in the &e"
+ messages_config.name + ".yml&c config.";
}
} else {
finalmessage = message;
}
for (Map.Entry<String, String> replacement_pairs : this.replacements
.entrySet()) {
finalmessage = finalmessage.replaceAll("%"
+ replacement_pairs.getKey(),
replacement_pairs.getValue());
}
finalmessage = MessageHandler.replacePrefixes(finalmessage);
finalmessage = MessageHandler.replaceColours(finalmessage);
if (!finalmessage.startsWith("-")) {
if (sender == "*") {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(finalmessage);
}
} else if (sender == "$") {
Bukkit.getConsoleSender().sendMessage(finalmessage);
} else {
Player player = Bukkit.getPlayer(sender);
if (player != null) {
player.sendMessage(finalmessage);
}
}
}
}
this.replacements = new HashMap<String, String>();
return this;
} | 9 |
private void checkForPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
int tabNumber = pane.getUI().tabForCoordinate(pane, e.getX(), e.getY());
if (tabNumber >= 0) {//must be a tab
Component c = e.getComponent();
menu.setCurrentTab(tabNumber);//set the selected tab
menu.show(c, e.getX(), e.getY());
}
}
} | 2 |
public static double frechetCDF(double mu, double sigma, double gamma, double lowerlimit, double upperlimit) {
double arg1 = (lowerlimit - mu) / sigma;
double arg2 = (upperlimit - mu) / sigma;
double term1 = 0.0D, term2 = 0.0D;
if (arg1 >= 0.0D) term1 = Math.exp(-Math.pow(arg1, -gamma));
if (arg2 >= 0.0D) term2 = Math.exp(-Math.pow(arg2, -gamma));
return term2 - term1;
} | 2 |
public void setSex(String sex) {
this.sex = sex;
} | 0 |
private boolean jj_3R_34() {
if (jj_3R_23()) return true;
return false;
} | 1 |
public void processEvent(AWTEvent paramAWTEvent)
{
super.processEvent(paramAWTEvent);
if (((paramAWTEvent instanceof MouseEvent)) && (this.EventTransparent))
{
MouseEvent localMouseEvent1 = (MouseEvent)paramAWTEvent;
Container localContainer = getParent();
Component[] arrayOfComponent = localContainer.getComponents();
int i = -1;
for (int j = 0; j < arrayOfComponent.length; j++)
{
Component localComponent = localContainer.getComponent(j);
if (localComponent == this)
{
i = j;
}
else
{
int k = localMouseEvent1.getX() + getLocation().x - localComponent.getLocation().x;
int m = localMouseEvent1.getY() + getLocation().y - localComponent.getLocation().y;
if (i > -1)
if (localComponent.contains(k, m))
{
localMouseEvent1.translatePoint(getLocation().x - localComponent.getLocation().x, getLocation().y - localComponent.getLocation().y);
localComponent.dispatchEvent(localMouseEvent1);
if (!this.EventChildren.contains(localComponent)) {
this.EventChildren.addElement(localComponent);
}
j = arrayOfComponent.length;
}
else
{
if (!this.EventChildren.contains(localComponent)) {
continue;
}
MouseEvent localMouseEvent2 = new MouseEvent(localComponent,
505,
System.currentTimeMillis(),
0,
k,
m,
0,
false);
localComponent.dispatchEvent(localMouseEvent2);
this.EventChildren.removeElement(localComponent);
}
}
}
}
} | 8 |
public static String unescape(String in) {
StringBuilder out = new StringBuilder();
char last = 0;
for (char c : in.toCharArray()) {
if (c == ESC) {
if (last != 0 && last == ESC)
out.append(c);
}
else
out.append(c);
last = c;
}
return out.toString();
} | 4 |
public void paintComponent(Graphics g)
{
// Get the Graphics2D version of the Graphics g by casting
Graphics2D g2 = (Graphics2D) g;
// Represents the width and the x coordinate of drawing the red and white
// rectangles in the panel. Initially set to the value of drawing the
// rectangles to the right of the union.
double rectWidth = .6*width;
double xCoord = .4*width;
// Draw the Union on the panel
g2.setPaint(Color.BLUE);
g2.fill(new Rectangle2D.Double(0,0,.4*width,.53846*height));
// Draw the thirteen red and white rectangular stripes on the panel
for(int i=0; i<13; i++)
{
// Change the x coordinate and the width of the stripes when it is
// time to draw the eigth stripe on the flag as it should be drawn
// below the union
if(i==7)
{
xCoord = 0;
rectWidth = width;
}
// Alternate the color for each stripe between red and white
if(i%2==0)
g2.setPaint(Color.RED);
else
g2.setPaint(Color.WHITE);
// Draw the rectangle on the panel. It will be added with the specified color.
// Keeps changing the yCoord of the stripes to be down number of rectangles
// already drawn * (.0769 * height) which represents the height of each stripe
g2.fill(new Rectangle2D.Double(xCoord,i*.0769*height,rectWidth,.0769*height));
}
// Set up the general coordinates of the star based on height and width such that a
// line can be drawn from each set of x and y points to be formed into a new star
// shape with five points
double x[] = {.0002105*width, .0126*width, .0163*width, .02*width, .0324*width,
.0217*width, .02574*width, .0163*width, .0069*width, .0109*width};
double y[] = {.02*height, .02*height, 0, .02*height, .02*height, .03*height,
.05*height, .04*height, .05*height, .03*height};
// Initialize a general path object that helps in drawing the line of the points
// designated in the array of x and y
GeneralPath star = new GeneralPath();
// Move the star to point to the initial point to start the drawing of the star
star.moveTo((float)x[0],(float)y[0]);
// Draws the general line for the star
for(int i=1; i<x.length; i++)
{
star.lineTo((float)x[i],(float)y[i]);
}
// Close the path to the star and thus a star with 5 points shape is form
star.closePath();
// Set up the initial point of the corner of the left square where the star will be
// drawn and let the g2 draw the inital star.
g2.translate(.017*width,.0232*height);
g2.setPaint(Color.WHITE);
g2.fill(star);
// Add the first row of stars to the flag by adding the rest of 5 stars
// in the first row
for(int i=0; i<5; i++)
{
g2.translate(.066316*width,0);
g2.fill(star);
}
// Draw the remaining 8 rows of stars in sets of two rows each
for(int i=0; i<4; i++)
{
// Set up the initial point of the corner of the left square where
// the star will be drawn
g2.translate(-.03316*width,.054*height);
g2.fill(star);
// Draw the rest of the 4 stars in that row
for(int j=0; j<4; j++)
{
g2.translate(-.066316*width,0);
g2.fill(star);
}
// Go to next row...
// Set up the initial point of the corner of the left square where
// the star will be drawn
g2.translate(-.03316*width,.054*height);
g2.fill(star);
// Draw the rest of the 5 stars in that row
for(int k=0; k<5; k++)
{
g2.translate(.066316*width,0);
g2.fill(star);
}
}
} | 8 |
public boolean createDirToLocal(String parentPath, String dirName) {
try {
String dirPath;
if (parentPath.length() == user.getUsername().length() + 1) { // username\
dirPath = parentPath + dirName;
} else { // username\***
dirPath = parentPath + "\\" + dirName;
}
//System.out.println(dirPath);
// create on local machine
File newDir = new File(dirPath);
if (!newDir.exists()) {
newDir.mkdirs();
} else {
System.out.println("The directory exits in local, " + dirPath);
}
// record in user's account
Map<String, Map<SafeFile, Vector<SafeFile>>> m = user.getFileMap();
SafeFile newSafeDir = new SafeFile(1, dirPath, user.getUsername());
if (!m.containsKey(newSafeDir)) {
// make sure to create each directory in parentPath in user's account
if(parentPath.length() != user.getUsername().length() + 1) {
checkPath(parentPath); // check parent path
SafeFile parentSafeDir = new SafeFile(1, parentPath, user.getUsername());
// add the friend info
Set<SafeFile> files = m.get(user.getUsername()).keySet();
for (SafeFile sf : files) {
if (sf.equals(parentSafeDir) && !sf.getFriendList().isEmpty()) {
newSafeDir.setFriendList(sf.getFriendList());
break;
}
}
if (m.get(user.getUsername()).get(parentSafeDir).add(newSafeDir)) { // add new file to parent
//System.out.println("New directory added in parent's list, " + dirPath);
}
}
// add the directory to the map
m.get(user.getUsername()).put(newSafeDir, new Vector<SafeFile>());
//System.out.println("New directory created in local successfully, " + newSafeDir.getFilePath());
return true;
} else {
System.out.println("Directory exists in user's account, " + newSafeDir.getFilePath());
return true;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
} | 9 |
protected static int toUByte(final byte b) {
return b < 0 ? b + 0x100 : b;
} | 1 |
void saveFile() {
if (fileName != null) {
FileWriter file = null;
try {
file = new FileWriter(fileName);
file.write(styledText.getText());
file.close();
} catch (IOException e) {
showError(getResourceString("Error"), e.getMessage());
} finally {
try {
if (file != null) file.close();
} catch (IOException e) {
showError(getResourceString("Error"), e.getMessage());
}
}
}
} | 4 |
@Override
public void onPlayerCommandPreprocess (PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
String command = event.getMessage();
String[] split = command.split(" ");
if (!event.isCancelled() && split[0].equalsIgnoreCase("/backup")) {
event.setCancelled(true);
// only Player which has the Permissions by the plugin Permission can backup
// only Player can backup when the properties only ops can backup is set by the server AND the player is an operator
if (Main.Permissions != null && !Main.Permissions.has(player, "backup.canbackup"))
return;
if (pSystem.getBooleanProperty(BOOL_ONLY_OPS) && !player.isOp()) {
player.sendMessage("You dont have the rights to backup the server!");
return;
}
if (split.length == 1) {
backupTask.setAsManuelBackup();
player.getServer().getScheduler().scheduleSyncDelayedTask(plugin, backupTask);
}
else if (split.length == 2) {
backupTask.setBackupName(split[1]);
player.getServer().getScheduler().scheduleSyncDelayedTask(plugin, backupTask);
}
else
player.sendMessage("/backup OPTIONALNAME");
}
} | 8 |
public Boolean doubleRotation(privAVLNode r,int dir)
{
//Check valid inputs
if(!(dir == 1 || dir == 0))
return false;
if(r == null)
return false;
privAVLNode save1 = r.getChild(dir);
if(save1 == null)
return false;
privAVLNode save2 = save1.getChild((dir+1)%2);
if(save2 == null)
return false;
if(save2.getChild(dir) != null)
save2.getChild(dir).setParent(save1);
else
save1.removeChild((dir+1)%2);
save2.setParent(r);
save1.setParent(save2);
Boolean temp = singleRotation(r,dir);
save1.setHeight();
return temp;
} | 6 |
public String getOrdGroopString()
{
// Construct the groop string
Collection<String> main = getMainGroops();
Iterator<String> gIt = main.iterator();
StringBuffer groop = new StringBuffer("");
while (gIt.hasNext())
groop.append(gIt.next() + " & ");
// Remove the trailing & or replace with various
String grp = null;
if (groop.length() > 0)
grp = groop.substring(0, groop.length() - 3);
else
grp = "Various";
return grp;
} | 2 |
public void run(){
if (!armChannel.getAnimationName().equals("ArmRun") && !hasSwung){
armChannel.setAnim("ArmRun");
}
if (!legChannel.getAnimationName().equals("LegRun")){
legChannel.setAnim("LegRun");
}
} | 3 |
public void scanFileCollection(File src){
if (src.isDirectory()){
for (File child: src.listFiles())
scanFileCollection(child);
}
else{
try {
//Deal with artist tag
String artist = MetadataParser.getArtist(src);
if(artist!=null){
int origSize=artistNames.size();
artistNames.add(artist);
//If new artist
if(artistNames.size()>origSize){
artists.add(new Artist(artist));
progress.addInfo("Found artist: "+artist);
}
//Add album name to artist
String albumName = MetadataParser.getAlbum(src);
if (albumName!=null){
for (Artist a : artists){
if (a.getMetadataName().equals(artist)){
boolean newalb = a.addOwnedAlbumName(albumName);
if (newalb)
progress.addInfo("Found album: "+albumName);
}
}
}
}
} catch (Exception e) {
progress.addWarning("Couldn't parse metadata for file: "+src.getName());
}
}
} | 9 |
private void logPage(){
logPane = new JPanel();
logPane.setBackground(SystemColor.activeCaption);
logPane.setLayout(null);
JLabel lblTreatmentLog = new JLabel("Treatment Log");
lblTreatmentLog.setHorizontalAlignment(SwingConstants.CENTER);
lblTreatmentLog.setFont(new Font("Arial", Font.BOLD, 30));
lblTreatmentLog.setBounds(349, 20, 286, 47);
logPane.add(lblTreatmentLog);
TLTa_table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
@Override
public void valueChanged(ListSelectionEvent arg0) {
int beforehand=0;
TLL_model.removeAllElements();
if (TLTa_table.getSelectedRow()!=-1){
for (int x=findRec()-1;x>=0;x--){
beforehand += patient.getTreatmentRec(x).getTreatmentSize();
}
for (int i=0; i<patient.getTreatmentRec(findRec()).getTreatment(TLTa_table.getSelectedRow()-beforehand).getPartsSize(); i++){
TLL_model.add(i, patient.getTreatmentRec(findRec()).getTreatment(TLTa_table.getSelectedRow()-beforehand).getParts(i));
}
TLTP_remarks.setText(patient.getTreatmentRec(findRec()).getRemarks());
}
}});
if (patient!=null){
int rowCount=TLTa_model.getRowCount();
for(int i=rowCount-1;i>=0;i--){
TLTa_model.removeRow(i);
}
TLTP_remarks.setText(null);
Patient.addTable(patient, TLTa_model);
}
} | 5 |
private void findNeighbors(BKTree<? extends T> root, List<? super T> neighbors) {
T rhs = root.getValue();
int crntDistance = distance.compare(center, rhs);
if (crntDistance < tolerance) {
neighbors.add(rhs);
}
for (int x = crntDistance - tolerance; x <= crntDistance + tolerance; x++) {
if (root.children.containsKey(x)) {
findNeighbors(root.children.get(x), neighbors);
}
}
} | 5 |
private void createAndShowTipWindow(final MouseEvent e, final String text) {
Window owner = SwingUtilities.getWindowAncestor(textArea);
tipWindow = new TipWindow(owner, this, text);
tipWindow.setHyperlinkListener(hyperlinkListener);
// Give apps a chance to decorate us with drop shadows, etc.
PopupWindowDecorator decorator = PopupWindowDecorator.get();
if (decorator!=null) {
decorator.decorate(tipWindow);
}
// TODO: Position tip window better (handle RTL, edges of screen, etc.).
// Wrap in an invokeLater() to work around a JEditorPane issue where it
// doesn't return its proper preferred size until after it is displayed.
// See http://forums.sun.com/thread.jspa?forumID=57&threadID=574810
// for a discussion.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// If a new FocusableTip is requested while another one is
// *focused* and visible, the focused tip (i.e. "tipWindow")
// will be disposed of. If this Runnable is run after the
// dispose(), tipWindow will be null. All of this is done on
// the EDT so no synchronization should be necessary.
if (tipWindow==null) {
return;
}
tipWindow.fixSize();
ComponentOrientation o = textArea.getComponentOrientation();
Point p = e.getPoint();
SwingUtilities.convertPointToScreen(p, textArea);
// Ensure tool tip is in the window bounds.
// Multi-monitor support - make sure the completion window (and
// description window, if applicable) both fit in the same
// window in a multi-monitor environment. To do this, we decide
// which monitor the rectangle "p" is in, and use that one.
Rectangle sb = TipUtil.getScreenBoundsForPoint(p.x, p.y);
//Dimension ss = tipWindow.getToolkit().getScreenSize();
// Try putting our stuff "below" the mouse first.
int y = p.y + Y_MARGIN;
if (y+tipWindow.getHeight()>=sb.y+sb.height) {
y = p.y - Y_MARGIN - tipWindow.getHeight();
}
// Get x-coordinate of completions. Try to align left edge
// with the mouse first (with a slight margin).
int x = p.x - X_MARGIN; // ltr
if (!o.isLeftToRight()) {
x = p.x - tipWindow.getWidth() + X_MARGIN;
}
if (x<sb.x) {
x = sb.x;
}
else if (x+tipWindow.getWidth()>sb.x+sb.width) { // completions don't fit
x = sb.x + sb.width - tipWindow.getWidth();
}
tipWindow.setLocation(x, y);
tipWindow.setVisible(true);
computeTipVisibleBounds(); // Do after tip is visible
textAreaListener.install(textArea);
lastText = text;
}
});
} | 6 |
public void decrementFood() {
if (this.food > 0) {
this.food--;
}
} | 1 |
public void testCopyRecursivelyFromJar() throws IOException {
Debug.println("fileio", " my tmpdir = " + tmpDir);
File targetFoo = null, targetBar = null,
newDestDir = null;
File jarFile = new File(tmpDir, "test.jar");
try {
JarOutputStream jf =
new JarOutputStream(new FileOutputStream(jarFile));
ZipEntry ze = new ZipEntry("foo");
jf.putNextEntry(ze);
jf.write("Hello\n".getBytes());
ZipEntry zBar = new ZipEntry("bar");
jf.putNextEntry(zBar);
jf.write("Hello II\n".getBytes());
jf.close();
newDestDir = new File(tmpDir, "testTo");
newDestDir.mkdir();
targetFoo = new File(newDestDir, "foo");
assertFalse(targetFoo.exists());
targetBar = new File(newDestDir, "bar");
assertFalse(targetBar.exists());
// Should be empty at this point
assertEquals(0, newDestDir.listFiles().length);
FileIO.copyRecursively(new JarFile(jarFile),
new JarEntry("/"), newDestDir);
assertTrue(targetFoo.exists());
assertEquals(6, targetFoo.length());
assertTrue(targetBar.exists());
assertEquals(9, targetBar.length());
assertEquals(2, newDestDir.listFiles().length);
} finally {
if (jarFile != null) jarFile.delete();
if (targetFoo != null) targetFoo.delete();
if (targetBar != null) targetBar.delete();
// Must be after we delete the files in it.
if (newDestDir != null) newDestDir.delete();
}
} | 4 |
public void printAnalysisResultsEP() {
String string = "";
for (int i = 0; i < bestSequenceAlternativesEnergyPoint.size(); i++)
string += i + ": " + bestSequenceAlternativesEnergyPoint.get(i) + "CONSUMPTION:" + consumptionEnergyPoints[i] + "EP\n";
System.out.println(string);
} | 1 |
public static int phi(int num) {
if (num == 1)
return 1;
if (isPrime(num))
return num-1;
if (num % 2 == 0) { //using 2 identity
num /= 2;
return (num % 2 == 0 ? 2 : 1) * phi(num);
}
//this is the identity: phi(m * n) = phi(m) * phi(n) * gcd(m, n) / phi(gcd(m, n)).
int m = findMeADivisor(num), n = num / m;
int g = gcd(m, n);
return phi(m) * phi(n) * g / phi(g);
} | 4 |
private int scanLongstring()
{int count = 0, countaux = 0;
//Neste ponto ja verificou que esta usando colchete e ja aceitou para diferenciar em scanToken() o =
while(currentChar == '=')
{
takeIt();
count++;
}
take('[');
while(currentChar != SourceFile.EOT) //A condicao de parada de encontrar colchete fechando de mesmo nivel e aceitar o resto esta dentro
{
if(currentChar == ']')
{
takeIt();
countaux = count;
while(countaux > 0)
{
if(currentChar == '=')
{
takeIt();
countaux--;
}
else
break; //Nivel de comentario e menor que o necessario para fechar o bloco de comentario
}
if((countaux == 0) && (currentChar == ']')) //Se nao entrar nessa condicao o nivel de parenteses nao e o mesmo do de abertura
{
takeIt();
return Token.LONGSTRING;
}
}
else if(currentChar=='\\')
{
if(scanEscapeSequence() == Token.ERROR)
return Token.ERROR;
}
else
takeIt(); //entao e uma letra qualquer que pertence a long string
}
return Token.ERROR; //Chegou ao fim do arquivo sem fechar string longa, retorne erro
} | 9 |
private FileWatcherService(List<String> watchedFiles,EventBus eventBus)
{
try
{
watcher = FileSystems.getDefault().newWatchService();
this.eventBus = eventBus;
register(watchedFiles);
INSTANCE = this;
}
catch (Exception e)
{
System.out.println("Exception in creation of watch service ");
e.printStackTrace();
}
} | 1 |
public void setColor(Color color) {
this.color = color;
} | 0 |
public void listenUsersHands() throws InvalidSubscriptionException,
IOException {
waitHandsSub = elvin.subscribe(NOT_TYPE + " == '" + BROADCAST_HAND
+ "' && " + GAME_ID + " == '" + gameHost.getID() + "'");
waitHandsSub.addListener(new NotificationListener() {
public void notificationReceived(NotificationEvent e) {
ByteArrayInputStream bis;
ObjectInput in;
User tmpUser;
byte[] tmpBytes = (byte[]) e.notification.get(USER_HAND);
try {
bis = new ByteArrayInputStream(tmpBytes);
in = new ObjectInputStream(bis);
tmpUser = (User) in.readObject();
bis.close();
in.close();
if (findUserByID(tmpUser.getID()) == null) {
return;
}
if (sigServ.validateVerifiedSignature(
(byte[]) e.notification.get(SIGNATURE),
tmpUser.getPublicKey(), SigService.RAW_HAND_NONCE)) {
usersHands.add(tmpUser);
return;
} else {
// sig failed!
callCheat(SIGNATURE_FAILED);
System.exit(0);
}
} catch (Exception e1) {
shutdown();
System.exit(0);
}
}
});
} | 3 |
@Basic
@Column(name = "PRP_ESTADO")
public String getPrpEstado() {
return prpEstado;
} | 0 |
public ServletManager(CWConfig config)
{
servlets = new Hashtable<String,Class<? extends SimpleServlet>>();
servletStats = new Hashtable<Class<? extends SimpleServlet>, RequestStats>();
servletInit = new Hashtable<Class<? extends SimpleServlet>, Boolean>();
for(final String context : config.getServlets().keySet())
{
String className=config.getServlets().get(context);
if(className.indexOf('.')<0)
className="com.planet_ink.coffee_web.servlets."+className;
try
{
@SuppressWarnings("unchecked")
final
Class<? extends SimpleServlet> servletClass=(Class<? extends SimpleServlet>) Class.forName(className);
registerServlet(context, servletClass);
}
catch (final ClassNotFoundException e)
{
config.getLogger().severe("Servlet Manager can't load "+className);
}
}
} | 8 |
public void addUnit(core.GroupOfUnits unit, List<core.GroupOfUnits> list, QListWidget widget)
{
boolean found = false;
int i=0;
for (core.GroupOfUnits u: list) {
if (u.type == unit.type) {
u.setNumber(u.getNumber() + unit.getNumber());
widget.item(i).setText(u.type.name + " ("+u.getNumber()+")");
found = true;
break;
}
++i;
}
if (!found) {
list.add(unit);
widget.addItem(unit.type.name + " ("+unit.getNumber()+")");
}
} | 3 |
private boolean jj_3R_31() {
if (jj_3R_72()) return true;
return false;
} | 1 |
private void Update()
{
if(timeForNextFrame <= System.currentTimeMillis())
{
// Next frame.
currentFrameNumber++;
// If the animation is reached the end, we restart it by seting current frame to zero. If the animation isn't loop then we set that animation isn't active.
if(currentFrameNumber >= numberOfFrames)
{
currentFrameNumber = 0;
// If the animation isn't loop then we set that animation isn't active.
if(!loop)
active = false;
}
// Starting and ending coordinates for cuting the current frame image out of the animation image.
startingXOfFrameInImage = currentFrameNumber * frameWidth;
endingXOfFrameInImage = startingXOfFrameInImage + frameWidth;
// Set time for the next frame.
startingFrameTime = System.currentTimeMillis();
timeForNextFrame = startingFrameTime + frameTime;
}
} | 3 |
private boolean camposCompletos (){
if((combo_tipo.getSelectedIndex()>=0)&&
(fecha.isFechaValida(field_desdee.getText()))&&
(fecha.isFechaValida(field_hasta.getText()))&&
(!field_tasa.getText().equals(""))&&
(!field_sobretasa.getText().equals(""))
){
return true;
}
else{
return false;
}
} | 5 |
private void statementBlock()
{
expect(Token.Kind.OPEN_BRACE);
statementList();
expect(Token.Kind.CLOSE_BRACE);
} | 0 |
public static void DisplayLogin(Login login,ServerAccountConfig accountconfig){
System.out.println("--------------------------");
System.out.println("New Client Login");
System.out.println("--------------------------");
System.out.println("Account : " + login.Account);
System.out.println("SPNum : " + accountconfig.getSPNum(login.Account));
System.out.println("Version : " + login.Version);
System.out.println("LoginMode : " + login.LoginMode);
System.out.println("IpAddress : " + login.ipaddress);
System.out.println("--------------------------");
} | 0 |
public static void updateCommercial(int id, int idservice, int idville, String nom, String prenom, String adresse1, String adresse2) throws SQLException {
int result;
String query;
try {
query = "UPDATE COMMERCIAL set ID_VILLE=?,COMMNOM=?,COMMPRENOM=?,COMMADRESSE1=?,COMMADRESSE2=? where ID_COMMERCIAL=? ";
PreparedStatement pStatement = (PreparedStatement) ConnectionBDD.getInstance().getPreparedStatement(query);
pStatement.setInt(6, id);
pStatement.setInt(1, idville);
pStatement.setString(2, nom);
pStatement.setString(3, prenom);
pStatement.setString(4, adresse1);
pStatement.setString(5, adresse2);
pStatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(RequetesCommercial.class.getName()).log(Level.SEVERE, null, ex);
}
} | 1 |
public boolean on( int x, int y )
{
return !(x < 0 || y < 0 || x >= width || y >= height) && (mask[y][x] == _);
} | 4 |
public void body()
{
// Gets the PE's rating for each Machine in the list.
// Assumed one Machine has same PE rating.
MachineList list = super.resource_.getMachineList();
int size = list.size();
machineRating_ = new int[size];
for (int i = 0; i < size; i++) {
machineRating_[i] = super.resource_.getMIPSRatingOfOnePE(i, 0);
}
// a loop that is looking for internal events only
Sim_event ev = new Sim_event();
while ( Sim_system.running() )
{
super.sim_get_next(ev);
// if the simulation finishes then exit the loop
if (ev.get_tag() == GridSimTags.END_OF_SIMULATION ||
super.isEndSimulation())
{
break;
}
// Internal Event if the event source is this entity
if (ev.get_src() == super.myId_ && gridletInExecList_.size() > 0)
{
updateGridletProcessing(); // update Gridlets
checkGridletCompletion(); // check for finished Gridlets
}
// Internal Event if the event source is this entity
if (ev.get_src() == super.myId_ && gridletQueueList_.size() > 0)
{
updateGridletProcessing(); // update Gridlets
checkGridletCompletion(); // check for finished Gridlets
allocateQueueGridlet(); // check for new Gridlet allocation
}
}
// CHECK for ANY INTERNAL EVENTS WAITING TO BE PROCESSED
while (super.sim_waiting() > 0)
{
// wait for event and ignore since it is likely to be related to
// internal event scheduled to update Gridlets processing
super.sim_get_next(ev);
logger.log(Level.INFO,super.resName_ +
".PerfectCheckPointing.body(): ignore internal events");
}
} | 9 |
private void validerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_validerMouseClicked
// TODO add your handling code here:
if (jrbHel.isSelected()) {
choix = 0;
} else if (jrbSurt.isSelected()) {
choix = 1;
} else if (jrbJormungand.isSelected()) {
choix = 2;
} else if (jrbLoki.isSelected()) {
choix = 3;
} else if (jrbNidhogg.isSelected()) {
choix = 4;
} else if (jrbFenrir.isSelected()) {
choix = 5;
}
this.dispose();
}//GEN-LAST:event_validerMouseClicked | 6 |
private int paethPredictor(byte[] line, byte[] previousLine, int x, int xp) {
int a = 0xFF & ((xp < 0) ? 0 : line[xp]);
int b = 0xFF & previousLine[x];
int c = 0xFF & ((xp < 0) ? 0 : previousLine[xp]);
int p = a + b - c;
int pa = (p >= a) ? (p - a) : -(p - a);
int pb = (p >= b) ? (p - b) : -(p - b);
int pc = (p >= c) ? (p - c) : -(p - c);
if (pa <= pb && pa <= pc) {
return a;
}
return (pb <= pc) ? b : c;
} | 8 |
public static Stella_Object accessBacklinksIndexSlotValue(BacklinksIndex self, Symbol slotname, Stella_Object value, boolean setvalueP) {
if (slotname == Logic.SYM_LOGIC_DEPENDENT_PROPOSITIONS_LIST) {
if (setvalueP) {
self.dependentPropositionsList = ((SequenceIndex)(value));
}
else {
value = self.dependentPropositionsList;
}
}
else if (slotname == Logic.SYM_LOGIC_DEPENDENT_ISA_PROPOSITIONS_LIST) {
if (setvalueP) {
self.dependentIsaPropositionsList = ((SequenceIndex)(value));
}
else {
value = self.dependentIsaPropositionsList;
}
}
else if (slotname == Logic.SYM_LOGIC_PREDICATE_PROPOSITIONS_TABLE) {
if (setvalueP) {
self.predicatePropositionsTable = ((HashTable)(value));
}
else {
value = self.predicatePropositionsTable;
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + slotname + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
return (value);
} | 6 |
@Override
public boolean isMoveValid(int srcRow, int srcCol, int destRow, int destCol) {
// TODO Auto-generated method stub
boolean result = false;
if(
((destCol == (srcCol - (srcCol - destCol))) && (destRow == (srcRow + (srcCol - destCol)))) || // down left diagonal
((destCol == (srcCol + (destCol - srcCol))) && (destRow == (srcRow + (destCol - srcCol)))) || // down right diagonal
((destCol == (srcCol - (srcCol - destCol))) && (destRow == (srcRow - (srcCol - destCol)))) || // up left diagonal ) || // up left diagonal
((destCol == (srcCol + (destCol - srcCol))) && (destRow == (srcRow - (destCol - srcCol)))) // up right diagonal
){result = true;}
else{result = false;}
return result;
} | 8 |
public void setSortByName(boolean sort) {
if (!sortByName) {
Collections.sort(listPhoneBook, new SortedByFirstName());
sortByName = true;
} else {
Collections.sort(listPhoneBook, Collections.reverseOrder(new SortedByFirstName()));
sortByName = false;
}
} | 1 |
public Account create() {
UUID accountId = UUID.randomUUID();
AccountImpl accountImpl = new AccountImpl(accountId);
Account newAccount = null;
try{
org.omg.CORBA.Object objRef = rootpoa.servant_to_reference(accountImpl);
newAccount = AccountHelper.narrow(objRef);
accounts.put(UUID.fromString(newAccount.getID()), newAccount);
}
catch (Exception e) {
System.err.println("ERROR: " + e);
e.printStackTrace(System.out);
}
return newAccount;
} | 1 |
@Override
public void paint(Graphics g1) {
Graphics2D g = (Graphics2D) g1;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
if (Universal.testing)
return;
if (data == null) {
if (Script.holdExecution()) {
return;
}
data = new SkillData();
}
Queue<SkillGain> order = new PriorityQueue<SkillGain>();
for (int i : skillIds) {
order.add(new SkillGain(i, data.experience(i)));
}
long time = Script.getElapsed();
long mult = 60 * 60;
int loc = -1;
Point start = new Point(SPACING, SPACING);
while (!order.isEmpty()) {
SkillGain cur = order.poll();
int gained = cur.getGained();
int skill = cur.getSkill();
if (gained == 0)
break;
if (++loc >= numSkills)
break;
int xp = Skills.getExperience(skill);
int level = Skills.getLevelAt(xp);
int xpnl = Skills.getExperienceRequired(level + 1);
int xpcl = Skills.getExperienceRequired(level);
long tleft = (xpnl - xp) * time / gained;
int maxWidth = MainPaint.MAIN_WIDTH - SPACING * 2;
int pleft = (Skills.getExperience(skill) - xpcl) * maxWidth / (xpnl - xpcl);
g.setColor(MainPaint.BACKGROUND);
g.fillRoundRect(start.x, start.y, maxWidth, BAR_HEIGHT, 2, 2);
g.setColor(progressBar);
g.fillRoundRect(start.x, start.y, pleft, BAR_HEIGHT, 2, 2);
g.setColor(MainPaint.TEXT_COLOR);
g.setFont(FONT);
String str = String.format("%s %3d (+%2d): %4dK (%3dK) %s", SKILL_ABBREVS[skill], level,
data.level(skill), gained / 1000, gained * mult / time, (tleft / mult / 1000 < 10 ? " ("
+ Time.format(tleft) + ")" : ""));
TextUtil.drawTextFromPoint(g, new Point(start.x + 4, start.y), str, Anchor.TOP_LEFT);
start.y += BAR_HEIGHT + SPACING;
}
} | 8 |
public static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
} else if (o instanceof Float) {
if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
}
}
} | 7 |
public void searchMenu()
{
System.out.println("Search by what?");
System.out.println("1:Stock Number");
System.out.println("2:Category");
System.out.println("3:Manufactuer");
System.out.println("4:Model Number");
System.out.println("5:Description");
System.out.println("6:Accessory");
int input = scanner.nextInt();
switch (input)
{
case 1:
System.out.println("Input Stock Number:");
String str = scanner.next();
searchStockNumber(str);
break;
case 2:
System.out.println("input Category");
searchCategory(scanner.next());
break;
case 3:
System.out.println("input Manufacturer");
searchManufacturer(scanner.next());
break;
case 4:
System.out.println("input Model Number");
searchModelNumber(scanner.next());
break;
case 5:
System.out.println("input Attribute");
scanner.nextLine();
String att = scanner.nextLine();
System.out.println(att);
System.out.println("input Value");
String val = scanner.nextLine();
searchDescription(att, val);
break;
case 6:
System.out.println("Input stock Number");
searchAccessory(scanner.next());
}
if (searchResult.size() > 0)
{
System.out.println("Add which item to cart? 0 for nope");
int nn = scanner.nextInt();
if (nn!= 0)
{
System.out.println("How many?");
addItemToCart(nn, scanner.nextInt());
}
}
mainMenu();
} | 8 |
public static void kill() {
runGC = false;
for (int i = 0; i < 200; i++) {} // Just wait a bit
gc.interrupt();
} | 1 |
@SuppressWarnings("unchecked")
public String loadEvents() {
PreparedStatement st = null;
ResultSet rs = null;
JSONArray json = new JSONArray();
try {
conn = dbconn.getConnection();
st = conn.prepareStatement("SELECT * FROM events");
rs = st.executeQuery();
while (rs.next()) {
JSONObject o = new JSONObject();
o.put("id", rs.getInt("id"));
o.put("name", rs.getString("name"));
o.put("location", rs.getString("location"));
if (rs.getDate("start_date") != null) {
o.put("start_date", rs.getDate("start_date").toString());
} else {
o.put("start_date", "");
}
if (rs.getDate("end_date") != null){
o.put("end_date", rs.getDate("end_date").toString());
} else {
o.put("end_date", "");
}
json.add(o);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try{
conn.close();
st.close();
rs.close();
}catch (SQLException e) {
System.out.println("Error closing query");
}
}
return json.toString();
} | 5 |
public float getindiTakings(Date date, Movie movie) {
indiTakings = 0;
for(ShowTime st : movie.getShowTimes()) {
calendar.setTime(date);
int cDay = calendar.get(Calendar.DATE);
int cMonth = calendar.get(Calendar.MONTH);
int cYear = calendar.get(Calendar.YEAR);
calendar.setTime(st.getTime());
int sDay = calendar.get(Calendar.DATE);
int sMonth = calendar.get(Calendar.MONTH);
int sYear = calendar.get(Calendar.YEAR);
if(st.getMovie() == movie && sDay == cDay && sMonth == cMonth && sYear == cYear) {
for(MovieTicket ticket : st.getMovieTickets())
indiTakings += (ticket.getPrice() + 1.5) * 1.07;
}
}
return indiTakings;
} | 6 |
public String toString()
{
String res = "";
for (int i = 0; i < this.hauteur; i++)
{// Parcours le premier tableau
for (int j = 0; j < this.largeur; j++)
{// Parcours le second tableau
switch (this.background[i][j])
{
case MUR : res = res +"M"; break;
case HERBE : res = res +"H"; break;
case ROUTE : res = res +"R"; break;
case TERRE : res = res +"T"; break;
case TOWER : res = res +"O"; break;
case UNITE : res = res +"X"; break;
case QG : res = res + "G"; break;
}
res = res + " ";
}
res = res + "\n"; // Permet de revenir à la ligne au moment de passer à la ligne suivante du tableau
}
return res;
} | 9 |
private void startThread() throws Exception {
if (secureInstance.getInstance() != null) {
// Initialize a new Thread with a random ThreadGroup and a new Name
ownThread = new Thread(CodeSupSecurityManager.getInstance()
.getThreadGroup(securityKey), this,
secureInstance.getClassName() + "." + methodName);
// Observe the Thread in the WatchDog
WatchDog.getInstance()
.setThread(ownThread, maxRealTime, maxCPUTime);
// Search for the right Method in the Class
for (final Method method : secureInstance.getInstance().getClass()
.getMethods()) {
// if it isn't the right we go straight forward
if ((!method.getName().equals(methodName))) {
continue;
}
// we found the right method, now search for the right
// parameters
parameterTypes = method.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++) {
if (!parameterTypes[i].getClass().isAssignableFrom(
parameters[i].getClass())) {
found = false;
break;
}
}
}
if (found == true || parameterTypes != null) {
ownThread.start();
ownThread.join();
// Tell the WatchDog that the thread finished already
WatchDog.getInstance().interrupt();
}
}
} | 7 |
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Timelog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Timelog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Timelog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Timelog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
new Timelog().setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(Timelog.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
} | 7 |
@EventHandler
public void SpiderFastDigging(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getSpiderConfig().getDouble("Spider.FastDigging.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getSpiderConfig().getBoolean("Spider.FastDigging.Enabled", true) && damager instanceof Spider && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, plugin.getSpiderConfig().getInt("Spider.FastDigging.Time"), plugin.getSpiderConfig().getInt("Spider.FastDigging.Power")));
}
} | 6 |
private void init() {
if (titleStyle == null) {
titleStyle = page.addStyle(null, null);
StyleConstants.setBold(titleStyle, true);
StyleConstants.setFontSize(titleStyle, Page.getDefaultFontSize() + 10);
StyleConstants.setFontFamily(titleStyle, Page.getDefaultFontFamily());
}
if (subtitleStyle == null) {
subtitleStyle = page.addStyle(null, null);
StyleConstants.setBold(subtitleStyle, true);
StyleConstants.setFontSize(subtitleStyle, Page.getDefaultFontSize() + 5);
StyleConstants.setFontFamily(subtitleStyle, Page.getDefaultFontFamily());
}
if (questionStyle == null) {
questionStyle = page.addStyle(null, null);
StyleConstants.setItalic(questionStyle, true);
StyleConstants.setFontSize(questionStyle, Page.getDefaultFontSize() + 1);
StyleConstants.setFontFamily(questionStyle, Page.getDefaultFontFamily());
StyleConstants.setBold(questionStyle, true);
}
if (answerStyle == null) {
answerStyle = page.addStyle(null, null);
StyleConstants.setFontSize(answerStyle, Page.getDefaultFontSize());
StyleConstants.setFontFamily(answerStyle, Page.getDefaultFontFamily());
}
if (highlightStyle == null) {
highlightStyle = page.addStyle(null, null);
StyleConstants.setFontSize(highlightStyle, Page.getDefaultFontSize());
StyleConstants.setForeground(highlightStyle, Color.red);
StyleConstants.setBold(highlightStyle, true);
StyleConstants.setFontFamily(highlightStyle, Page.getDefaultFontFamily());
}
if (linkStyle == null) {
linkStyle = page.addStyle(null, answerStyle);
StyleConstants.setForeground(linkStyle, Page.getLinkColor());
StyleConstants.setUnderline(linkStyle, true);
}
if (tinyStyle == null) {
tinyStyle = page.addStyle(null, null);
StyleConstants.setFontSize(tinyStyle, Page.getDefaultFontSize() - 4);
StyleConstants.setFontFamily(tinyStyle, Page.getDefaultFontFamily());
StyleConstants.setForeground(tinyStyle, Color.gray);
}
} | 7 |
public void initialize(boolean flag) {
int i;
int a, b, c, d, e, f, g, h;
a = b = c = d = e = f = g = h = RATIO;
for(i = 0; i < 4; ++i) {
a ^= b << 11;
d += a;
b += c;
b ^= c >>> 2;
e += b;
c += d;
c ^= d << 8;
f += c;
d += e;
d ^= e >>> 16;
g += d;
e += f;
e ^= f << 10;
h += e;
f += g;
f ^= g >>> 4;
a += f;
g += h;
g ^= h << 8;
b += g;
h += a;
h ^= a >>> 9;
c += h;
a += b;
}
for(i = 0; i < SIZE; i += 8) {
if(flag) {
a += results[i];
b += results[i + 1];
c += results[i + 2];
d += results[i + 3];
e += results[i + 4];
f += results[i + 5];
g += results[i + 6];
h += results[i + 7];
}
a ^= b << 11;
d += a;
b += c;
b ^= c >>> 2;
e += b;
c += d;
c ^= d << 8;
f += c;
d += e;
d ^= e >>> 16;
g += d;
e += f;
e ^= f << 10;
h += e;
f += g;
f ^= g >>> 4;
a += f;
g += h;
g ^= h << 8;
b += g;
h += a;
h ^= a >>> 9;
c += h;
a += b;
memory[i] = a;
memory[i + 1] = b;
memory[i + 2] = c;
memory[i + 3] = d;
memory[i + 4] = e;
memory[i + 5] = f;
memory[i + 6] = g;
memory[i + 7] = h;
}
if(flag) {
for(i = 0; i < SIZE; i += 8) {
a += memory[i];
b += memory[i + 1];
c += memory[i + 2];
d += memory[i + 3];
e += memory[i + 4];
f += memory[i + 5];
g += memory[i + 6];
h += memory[i + 7];
a ^= b << 11;
d += a;
b += c;
b ^= c >>> 2;
e += b;
c += d;
c ^= d << 8;
f += c;
d += e;
d ^= e >>> 16;
g += d;
e += f;
e ^= f << 10;
h += e;
f += g;
f ^= g >>> 4;
a += f;
g += h;
g ^= h << 8;
b += g;
h += a;
h ^= a >>> 9;
c += h;
a += b;
memory[i] = a;
memory[i + 1] = b;
memory[i + 2] = c;
memory[i + 3] = d;
memory[i + 4] = e;
memory[i + 5] = f;
memory[i + 6] = g;
memory[i + 7] = h;
}
}
generateResults();
count = SIZE;
} | 5 |
public StructuredBlock findCase(FlowBlock destination) {
for (int i = 0; i < caseBlocks.length; i++) {
if (caseBlocks[i].subBlock != null
&& caseBlocks[i].subBlock instanceof EmptyBlock
&& caseBlocks[i].subBlock.jump != null
&& caseBlocks[i].subBlock.jump.destination == destination)
return caseBlocks[i].subBlock;
}
return null;
} | 5 |
public Selector selector() {
return new SequenceSelector();
} | 0 |
public static String createNewNameMessage(String myNewName) {
JSONObject jsonMsg = new JSONObject()
.element( "code", "4" )
.element( "name", myNewName )
;
return jsonMsg.toString();
} | 0 |
public boolean contains(int[] cycle, int size, Main m){
boolean result = false;
for(int i=0; i<cycle.length; i++){
if(graphNodes.get(cycle[i]).getType()==_MOLECULE_){
if( m.getLibrary().get( graphNodes.get(cycle[i]).getID() ).getNumNodes() > size*10 ){
result = true;
}
}
}
return result;
} | 3 |
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object process(Object value) {
// we're processing things which are either PhpObjects or which could contain PhpObjects.
if (value instanceof PhpObject) {
PhpObject tmpPHP = (PhpObject) value;
value = tmpPHP.getRealObject();
} else if (value instanceof ArrayList) {
ArrayList tmpArr = (ArrayList) value;
for (int i = 0; i < tmpArr.size(); i++) {
Object tmpObj = tmpArr.get(i);
if (needsProcessing(tmpObj)) {
tmpObj = process(tmpObj);
tmpArr.set(i,tmpObj);
}
}
} else if (value instanceof LinkedHashMap) {
LinkedHashMap lhm = (LinkedHashMap) value;
Map<String,Object> tmpMap = lhm;
for (Map.Entry<String,Object> entry : tmpMap.entrySet()) {
String key = entry.getKey();
Object tmpObj = entry.getValue();
if (needsProcessing(tmpObj)) {
tmpObj = process(tmpObj);
lhm.put(key,tmpObj);
}
}
}
return value; // this ought to reflect any changes;
} | 7 |
public ReportForeignAffairPanel(FreeColClient freeColClient, GUI gui) {
super(freeColClient, gui, Messages.message("reportForeignAction.name"));
// Display Panel
reportPanel.removeAll();
reportPanel.setLayout(new MigLayout("wrap 2", "[]push[]", "[align top]"));
for (Player enemy : getGame().getLiveEuropeanPlayers()) {
NationSummary ns = getController().getNationSummary(enemy);
if (ns == null) continue;
JPanel enemyPanel = new JPanel(new MigLayout("gapy 0", "[][]20[align right]0[]", ""));
enemyPanel.setOpaque(false);
JLabel coatLabel = new JLabel();
final ImageIcon coatOfArms = getLibrary()
.getCoatOfArmsImageIcon(enemy.getNation());
if (coatOfArms != null) {
coatLabel.setIcon(coatOfArms);
}
enemyPanel.add(coatLabel, "spany, aligny top");
enemyPanel.add(localizedLabel(enemy.getNationName()), "wrap 12");
enemyPanel.add(new JLabel(Messages.message("report.stance")), "newline");
enemyPanel.add(new JLabel(Messages.message(Messages.getStanceAsString(ns.getStance()))));
enemyPanel.add(new JLabel(Messages.message("report.numberOfColonies")), "newline");
enemyPanel.add(new JLabel(ns.getNumberOfSettlements()));
enemyPanel.add(new JLabel(Messages.message("report.numberOfUnits")), "newline");
enemyPanel.add(new JLabel(ns.getNumberOfUnits()));
enemyPanel.add(new JLabel(Messages.message("report.militaryStrength")), "newline");
enemyPanel.add(new JLabel(ns.getMilitaryStrength()));
enemyPanel.add(new JLabel(Messages.message("report.navalStrength")), "newline");
enemyPanel.add(new JLabel(ns.getNavalStrength()));
enemyPanel.add(new JLabel(Messages.message("goldTitle")), "newline");
enemyPanel.add(new JLabel(Integer.toString(ns.getGold())));
String s = ns.getFoundingFathers();
if (s != null) {
enemyPanel.add(new JLabel(Messages.message("report.continentalCongress.title")), "newline 8");
enemyPanel.add(new JLabel(s));
}
if ((s = ns.getTax()) != null) {
enemyPanel.add(new JLabel(Messages.message("tax")), "newline");
enemyPanel.add(new JLabel(s));
enemyPanel.add(new JLabel("%"));
}
if ((s = ns.getSoL()) != null) {
enemyPanel.add(new JLabel(Messages.message("report.sonsOfLiberty")), "newline");
enemyPanel.add(new JLabel(s));
enemyPanel.add(new JLabel("%"));
}
reportPanel.add(enemyPanel);
}
reportPanel.add(getDefaultTextArea(Messages.message("report.foreignAffairs.notice"), 40),
"newline 20, span 8");
reportPanel.doLayout();
} | 6 |
public void test_add_long_long() {
assertEquals(567L, iField.add(567L, 0L));
assertEquals(567L + 1234L * 90L, iField.add(567L, 1234L));
assertEquals(567L - 1234L * 90L, iField.add(567L, -1234L));
try {
iField.add(LONG_MAX, 1L);
fail();
} catch (ArithmeticException ex) {}
try {
iField.add(1L, LONG_MAX);
fail();
} catch (ArithmeticException ex) {}
} | 2 |
protected void configConnection(HttpURLConnection conn) {
conn.setReadTimeout(DownloadUtils.READ_TIMEOUT);
conn.setConnectTimeout(DownloadUtils.CONNECT_TIMEOUT);
Set<Entry<String, String>> entrySet = DownloadUtils.ORIGIN_EXTRA_HEADER.entrySet();
for (Entry<String, String> entry : entrySet) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
if (EXTRA_HEADER != null) {
entrySet = EXTRA_HEADER.entrySet();
for (Entry<String, String> entry : entrySet) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
} | 3 |
public Player(Point position, int baseSpeed, int baseForce, int healt,
int maxhealth, World currentWorld, String name, Color color,
int energy) {
super(position, baseSpeed, baseForce, healt, maxhealth, currentWorld,
name, color, energy);
} | 0 |
public void applyPreserveRule(IdentifierMatcher preserveRule) {
if (preserveRule.matches(this)) {
System.err.println("preserving: " + this);
setReachable();
Identifier ident = this;
while (ident != null) {
ident.setPreserved();
ident = ident.getParent();
}
}
for (Iterator i = getChilds(); i.hasNext();)
((Identifier) i.next()).applyPreserveRule(preserveRule);
} | 3 |
public boolean jumpNeighbour(Hexpos other) {
if (jumpNeighbours().contains(other))
return true;
return false;
} | 1 |
public SimplexNoise2D(long seed) {
Random random = new Random(seed);
for (int i = 0; i < 256; i++) {
mTable[i + 256] = mTable[i] = random.nextInt(256);
mTableMod12[i + 256] = mTableMod12[i] = mTable[i] % 12;
}
} | 1 |
protected String replaceCallsToRgb(String line) {
if (line.contains("rgb(") && line.contains(")")) {
// simplify text like rgb(35,32,32)
int start = line.indexOf("rgb(") + 4;
int end = line.indexOf(")");
String sub = line.substring(start, end); // gets a string that looks like: 0,0,0
String comp[] = sub.split(",");
// Code to ensure we don't try and turn calls containing percentages into hex colours e.g. rgb(100%, 0%, 10)
// TODO: code for percentages inside rgb() see http://en.wikipedia.org/wiki/Web_colors#CSS_colors
boolean containsPercent = false;
for (String s : comp) {
if (s.contains("%")) {
containsPercent = true;
break;
}
}
if (!containsPercent) {
int r, g, b;
r = Integer.parseInt(comp[0]);
g = Integer.parseInt(comp[1]);
b = Integer.parseInt(comp[2]);
Color c = new Color(r, g, b);
String hexString = Integer.toHexString(c.getRGB() & 0xFFFFFF);
if (hexString.length() < 6) {
for (int i = 0; i <= 6 - hexString.length(); i++) {
hexString = "0" + hexString;
}
}
// System.out.println(hexString + " = " + sub);
line = line.replace(line.substring(start - 4, end + 1), "#" + hexString);
}
}
return line;
} | 7 |
private static double getLambda(double clock) {
switch ((int) clock) {
case 0:
return 58.0;
case 1:
return 50.0;
case 2:
return 70.0;
case 3:
return 80.0;
case 4:
return 40.0;
case 5:
return 60.0;
case 6:
return 50.0;
case 7:
return 70.0;
default:
return 0;
}
} | 8 |
public void loadElev(Node node) throws ParseException {
Elev el = new Elev();
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node cNode = childNodes.item(i);
if (cNode instanceof Element) {
String content = cNode.getLastChild().getTextContent().trim();
switch (cNode.getNodeName()) {
case "numeUtilizator":
el.setNumeUtil(content);
break;
case "parola":
el.setParola(content);
break;
case "nume":
el.setNume(content);
break;
case "prenume":
el.setPrenume(content);
break;
case "CNP":
el.setCNP(content);
break;
case "dataNastere":
el.setDate(content);
break;
default:
break;
}
}
}
elevi.add(el);
} | 8 |
public void removeSelected()
{
layout.takeAt(selectedNo).widget().dispose();
objects.remove(selectedNo);
if (checkable) {
selectedNo = 0;
((WidgetChooserButton)(layout.itemAt(selectedNo).widget())).setChecked(true);
selected(objects.get(selectedNo));
}
} | 1 |
protected void drawHands(){
Card[] shelf = tm.getP1().getShelf();
for(int index=0; index<shelf.length; index++){
if(shelf[index]!=null){
shelf[index].drawCard(main, 50+index*50, 500);
}
}
Card[] flop = tm.getP1().getFlop();
for(int index=0; index<flop.length; index++){
if(flop[index]!=null){
flop[index].setVisible(true);
flop[index].drawCard(main, 50+index*50, 450);
}
}
ArrayList<Card> hand = tm.getP1().getHand();
for(int index=0; index<hand.size(); index++){
int spaceing = 300/hand.size();
if(!tm.getP1().isSelected(hand.get(index)))
hand.get(index).drawCard(main,400+index*spaceing,500);
else
hand.get(index).drawCard(main,400+index*spaceing,450);
}
} | 6 |
public synchronized void decisionMessage(int senderID, DecisionMessage dm) {
console.displayMessage(senderID + " voted for " + dm.getDecision());
if (dm.getVotingID() != id) {
console.displayMessage("Got decision message with invalid voting id. Dropping message...");
return;
}
System.out.println(123);
for (int i = 0; i < votes.length; i++) {
if (votes[i].getID() == senderID) {
try {
int decision = dm.getDecision();
if (decision >= options.length) {
console.displayMessage("Error, decision out of range");
return;
}
votes[i].setDecision(decision);
} catch (ServerException ex) {
console.displayMessage(ex.getMessage());
}
return;
}
}
//Reaching this part of the method it is sure that the senderID is not in the list of voters
console.displayMessage("Got decision message by someone that is not in the list of voters.");
} | 5 |
public void decodeAndRender(int id, String message) throws JSONException {
switch (id) {
case 100: // Chat message
Message chatMessage = enc.chattMessageDecode(message);
tg.chat.chatUpdate(chatMessage.message, chatMessage.user);
break;
case 201: // Move message
TiarUserMessage mess = enc.tiarUserMessageDecode(message);
if (this.started) {
if (mess.isValid == 1) {
tg.updateGameBoard(mess.Gameboard);
tg.gl.changeTurn();
} else
tg.updateGameBoard(mess.Gameboard);
if(mess.HasWon != 0){
JOptionPane.showMessageDialog(null, "Player: " + Integer.toString(mess.HasWon) + " has won!", "Winner!", JOptionPane.INFORMATION_MESSAGE);
tg.clearBoard();
}
if (mess.IsDraw ==1 ){
JOptionPane.showMessageDialog(null, "The game is a draw!", "Draw!", JOptionPane.INFORMATION_MESSAGE);
tg.clearBoard();
}
}
break;
case 202:
StartableMessage tsm = enc.startebleMessageDecode(message);
this.startable = tsm.isStartable;
break;
case 203:
StartedMessage startedGame = enc.startedMessageDecode(message);
this.started = startedGame.started;
this.Player = startedGame.playerID;
break;
case 404:
this.saveMsg = new StageFlipper(enc.kickMessageDecode(message));
this.loop = false;
break;
default:
System.out.println(id + "\nstring: " + message);
break;
}
} | 9 |
public static void main(String[] args) throws Exception {
String arffFile = "/home/abrari/Tesis/GP-Experiment/data/Gm01.arff";
CSVReader reader = new CSVReader(new FileReader(arffFile), ',', '\'', 21);
String[] line;
double[] d;
// 0 = true, 1 = false
int predicted;
int actual;
int i = 0;
int[][] confMatrix = new int[2][2];
while ((line = reader.readNext()) != null) {
d = mapToDouble(line);
actual = line[line.length-1].equals("true") ? 0 : 1;
// RULE: FP2
if (d[idx_allele_balance] >= 0.047743 && d[idx_total_depth] <= 123.902467 && d[idx_max_q_minor] > 61.171927) {
predicted = 0;
} else if (d[idx_nuc_diversity] < 0.508747 && d[idx_max_q_minor] < 60.277954) {
predicted = 1;
} else {
predicted = 1;
}
confMatrix[actual][predicted]++;
// if (i++ > 500) break;
}
System.out.println(confMatrix[0][0] + "\t" + confMatrix[0][1]);
System.out.println(confMatrix[1][0] + "\t" + confMatrix[1][1]);
} | 7 |
public boolean add(Order order)
{
Session s = sessionManager.getSession();
try
{
if (!s.executeNonQuery("insert into Orders (VendorID, BaseID, OrderTime, Amount) values(?, ?, ?, ?)"
, order.getVendor().getId(), order.getPizzaBase().getId(), order.getOrderTime().getTime(), ((Float)order.getAmount()).doubleValue()))
throw new Exception();
QueryResult qs = s.executeQuery("SELECT last_insert_rowid() as ID");
int id = 0;
for(Object obj : qs)
{
Map<String, Object> row = (Map<String, Object>)obj;
id = (Integer)row.get("ID");
break;
}
qs.close();
PizzaTopping[] toppings = order.getPizzaToppings();
for(PizzaTopping t : toppings)
{
if (!s.executeNonQuery("insert into ToppingOrders (OrderID, ToppingID, Amount) values(?, ?, ?)", id, t.getId(), ((Float)t.getPrice()).doubleValue()))
throw new Exception();
}
return true;
}
catch(Exception e)
{
return false;
}
finally
{
s.close();
}
} | 5 |
protected AutomatonDrawer getDrawer() {
return drawer;
} | 0 |
public SystemLogger() {
super(fileOut);
System.setOut(this);
System.setErr(this);
} | 0 |
public static ConnectionManager Instance()
{
if (ConnectionManager.manager == null)
{
ConnectionManager.manager = init();
}
return ConnectionManager.manager;
} | 1 |
static void nativeLF() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
String osName = System.getProperty("os.name");
if ((osName != null) && osName.toLowerCase().startsWith("lin")) {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
}
} catch (Exception E) {
log.warning("Cannot set native L&F.");
}
} | 3 |
public boolean isVertical() {
return isVertical;
} | 0 |
@Override
public int compareTo(Element o) {
Integer size = this.value;
Integer osize = o.getValue();
return size.compareTo(osize);
} | 0 |
private int GetLogicActionSmrad(WumpusPolje[][] wumpusWorld){
if(tmpPolje.m_smrad){
//Down
if(tmpPolje.m_x + 1 < wumpusWorld.length && tmpPolje.m_y - 1 >= 0){
if(obiskanaPolja.contains(wumpusWorld[tmpPolje.m_x + 1][tmpPolje.m_y - 1]) && !wumpusWorld[tmpPolje.m_x + 1][tmpPolje.m_y - 1].m_smrad){
return WumpusActions.down;
}
}
//Right
if(tmpPolje.m_x - 1 >= 0 && tmpPolje.m_y + 1 < wumpusWorld[0].length){
if(obiskanaPolja.contains(wumpusWorld[tmpPolje.m_x - 1][tmpPolje.m_y + 1]) && !wumpusWorld[tmpPolje.m_x - 1][tmpPolje.m_y + 1].m_smrad){
return WumpusActions.right;
}
}
}
return WumpusActions.back;
} | 9 |
public String getFeatureValue(String featureType) throws FeatureTypeNotFoundException {
String featureValue = "";
String[] singleFeatureTypes = featureType.split(Const.splitChar);
for (String singleFeatureType : singleFeatureTypes) {
if (features.containsKey(singleFeatureType)) {
if (featureValue.isEmpty()) {
featureValue = features.get(singleFeatureType);
} else {
featureValue += Const.splitChar + features.get(singleFeatureType);
}
} else {
throw new FeatureTypeNotFoundException("FeatureType: " + singleFeatureType
+ " is missing on current FeatureVector. "
+ this.toString());
}
}
return featureValue;
} | 3 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.