text stringlengths 14 410k | label int32 0 9 |
|---|---|
public Result fire(int ...coords) throws BadCoordinate {
if (coords.length != 3)
throw new BadCoordinate();
for (int d=0; d<3; d++) {
if (coords[d] < 0 || coords[d] >= 10) {
throw new BadCoordinate();
} else {
coords[d] = pos[d] - coords[d];
}
}
for (Result r : Result.values()) {
if (r.isValidFor(coords))
return r;
}
throw new BadCoordinate();
} | 6 |
public void setUpdatedTime(Date time)
{
if (time == null) throw new IllegalArgumentException("Time cannot be null");
this.time = time;
} | 1 |
private static float reservedForCollection(
Batch <Behaviour> doing, Service goodType
) {
float sum = 0 ;
for (Behaviour b : doing) {
if (b instanceof Delivery) for (Item i : ((Delivery) b).items) {
if (i.type == goodType) sum += i.amount ;
}
}
return sum ;
} | 4 |
public MainMenuWindow() {
super();
getContentPane().setLayout(null);
JLabel lblVersion = new JLabel(Constants.NAVALBATTLE_VERSION_TITLE);
lblVersion.setForeground(Color.WHITE);
JLabel lblNavalBattle = new JLabel("NavalBattle");
JButton btnSingleplayer = new JButton("Singleplayer");
JButton btnHelp = new JButton("Help");
btnRoketGamer = new JButton("RoketGamer");
JButton btnQuit = new JButton("Quit");
JButton btnCredits = new JButton("Credits");
final JButton btnMultiplayer = new JButton("Multiplayer");
lblNavalBattle.setBounds(10, 13, 466, 51);
lblVersion.setBounds(10, 287, 238, 14);
btnSingleplayer.setBounds(194, 74, 100, 30);
btnHelp.setBounds(194, 141, 100, 30);
btnRoketGamer.setBounds(194, 175, 100, 30);
btnQuit.setBounds(194, 209, 100, 30);
btnCredits.setBounds(375, 267, 100, 30);
btnMultiplayer.setBounds(194, 107, 100, 30);
lblNavalBattle.setForeground(Color.WHITE);
lblNavalBattle.setFont(Helper.GUI_MENU_TITLE_FONT);
lblNavalBattle.setHorizontalAlignment(SwingConstants.CENTER);
btnMultiplayer.setEnabled(true);
getContentPane().add(lblVersion);
getContentPane().add(lblNavalBattle);
getContentPane().add(btnSingleplayer);
getContentPane().add(btnHelp);
getContentPane().add(btnRoketGamer);
getContentPane().add(btnQuit);
getContentPane().add(btnCredits);
getContentPane().add(btnMultiplayer);
btnSingleplayer.setFocusable(false);
btnMultiplayer.setFocusable(false);
btnHelp.setFocusable(false);
btnRoketGamer.setFocusable(false);
btnQuit.setFocusable(false);
btnCredits.setFocusable(false);
btnMultiplayer.setEnabled(false);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon(MainMenuWindow.class.getResource("/com/jpii/navalbattle/res/drawable-gui/menu_background.png")));
label.setBounds(-83, -62, 569, 374);
getContentPane().add(label);
class SPGS implements Runnable {
public SPGS() {
}
public void run() {
spg = new SinglePlayerGame();
spg.setGameVars();
spg.setVisible(true);
//nextWindow("SinglePlayerGame");
}
}
btnSingleplayer.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
//SwingUtilities.invokeLater(new SPGS());
Thread immediate = new Thread(new SPGS());
immediate.start();
try {
Thread.sleep(200);
}
catch (Throwable t) {
}
NavalBattle.getWindowHandler().disposeContained();
}
});
btnHelp.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// nextWindow("HelpWindow");
URLUtils.openURL("http://jpii.github.io/NavalBattle/help.html");
}
});
btnRoketGamer.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(!NavalBattle.getGameState().isOffline()) {
URLUtils.openURL("http://roketgamer.com/viewgame.php?id=3");
}
}
});
btnQuit.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
WindowCloser.close();
}
});
btnCredits.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
nextWindow("CreditsWindow");
}
});
btnMultiplayer.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(btnMultiplayer.isEnabled()){
JOptionPane.showMessageDialog(null,"Warning: Multiplayer is experiemental." +
"\nProceed with caution.","NavalBattle",JOptionPane.WARNING_MESSAGE);
spg = new SinglePlayerGame();
boolean valid = false;
String ip = NavalBattleIO.getAttribute("lastGoodIP");
while (!valid) {
ip = JOptionPane.showInputDialog(null,(Object)"Enter IP address to connect to:",(Object)ip);
if (ip == null)
return;
if (ip.equals(""))
valid = false;
else
valid = validate(ip);
}
NavalBattleIO.saveAttribute("lastGoodIP", ip);
spg.setGameVars();
nextWindow("SinglePlayerGame");
NavalBattle.getWindowHandler().disposeContained();
}
}
});
} | 6 |
public static long read32bitLittleEndianUnsignedInt(RandomAccessFile f) throws IOException {
Integer d0,d1,d2,d3;
d0=0xff & read_sure(f);
d1=0xff & read_sure(f);
d2=0xff & read_sure(f);
d3=0xff & read_sure(f);
return (long)(d3<<24) + (d2<<16) + (d1<<8) + d0;
} | 0 |
public void move(int direction) {
boolean temp = this.moveBoolean(direction);
if (this.moveBoolean(direction) == true) {
switch (direction) {
case 2:
this.row++;
break;
case 4:
this.col--;
break;
case 6:
this.col++;
break;
case 8:
this.row--;
break;
}
}
} | 5 |
public Sentence (CoreMap annotatedSentence, int index, int docnum)
{
this.sentence = annotatedSentence.get(TextAnnotation.class);
this.terms = new ArrayList<String>();
this.posTags = new ArrayList<String>();
this.index = index;
this.docnum = docnum;
for (CoreLabel token: annotatedSentence.get(TokensAnnotation.class)) {
String term = token.get(TextAnnotation.class);
String pos = token.get(PartOfSpeechAnnotation.class);
this.terms.add(term.toLowerCase());
this.posTags.add(pos);
}
this.uniqueTerms = new HashSet<String>(terms);
this.phrases = new Phrases();
if (this.posTags.size() > 0 && this.posTags.get(0) != null) {
setPhrases();
}
} | 3 |
private static boolean is4Prime(int n){
if (didThis[n] == true) return is4Prime[n];
didThis[n] = true;
Set<Integer> used = new HashSet<Integer>();
int t = n;
for(Integer p : primes){
if (t%p==0){
t/=p;
used.add(p);
if(used.size()==4) break;
}
}
while(t!=1){
boolean found = false;
for(Integer pp : used){
if (t%pp==0){
t/=pp;
found = true;
break;
}
}
if (found == false && t!=1){
is4Prime[n]=false;
return false;
}
}
boolean answer = used.size()==4;
is4Prime[n]=answer;
// if (is4Prime[n]){ System.out.println(n+" is ");
// for(Integer i : used) System.out.println(" "+i+" ");}
return answer;
} | 9 |
public int size() {
return exceptions.size();
} | 0 |
public String[][] searchProgrammsLinux() {
//
// These method searches for some standard programs
// with are usually installed on a linux system.
// The return String[] includes:
// [0] - FileBrowser
// [1] - WebBrowser
// [2] - mp3/ogg Player
// [3] - streamripper
//
String[][] programNames = {
/*[0]*/ {"thunar","konqueror","nautilus","dolphin"},
/*[1]*/ {"firefox","firefox-bin","iceweasel","opera","epiphany","galeon"},
/*[2]*/ {"audacious","qmmp","beep-media-player","xmms","amarok","mplayer"},
/*[3]*/ {"streamripper"}};
String[] binPath = getPathBinLinux();
//catch an empty array for wrong installed java systems
if(binPath == null) {
SRSOutput.getInstance().logE("No executable bin path found on the linux system");
return null;
}
String[][] foundPrograms = new String[programNames.length][6];
for(int i=0;i<programNames.length;i++) {
int k=0;
for(int l=0;l<programNames[i].length;l++) {
for(int j=0;j<binPath.length;j++) {
File temp = new File(binPath[j]+"/"+programNames[i][l]);
if(temp.exists()) {
foundPrograms[i][k]=binPath[j]+"/"+programNames[i][l];
k++;
}
}
}
}
return foundPrograms;
} | 5 |
@SuppressWarnings("unchecked")
public static Entry<String, Object> getEntry(Object obj)
{
if (obj instanceof Entry)
{
Entry<?,?> e = (Entry<?,?>) obj;
if (e.getKey() instanceof String)
return (Entry<String, Object>) e;
}
return null;
} | 6 |
public boolean inferenceCheckerHelper(LinkedList<String> curQueue,ArrayList<LinkedList<String>> Queues) throws IllegalInferenceException
{
String curSymbol = (String) curQueue.pop();
if(curSymbol.equals("=>"))
{
boolean bol1 = inferenceCheckerHelper(curQueue,Queues);
boolean bol2 = inferenceCheckerHelper(curQueue,Queues);
return implies(bol1,bol2);
}
if(curSymbol.equals("~"))
{
boolean restBool = inferenceCheckerHelper(curQueue,Queues);
return !restBool;
}
for(LinkedList<String> Q : Queues)
{
if(Q.size() == 1)
{
if(curSymbol.equals(Q.getFirst()))
{
return true;
}
}
if(Q.size()==2)
{
if(curSymbol.equals(Q.get(1)))
{
return false;
}
}
}
throw new IllegalInferenceException("Bad");
} | 7 |
@SuppressWarnings("unchecked")
private void disableMash() {
// one source of references to PySystemState
Py.getSystemState().cleanup();
Py.setSystemState(null);
Py.defaultSystemState = null;
// another reference, the ThreadLocal - doesn't get cleaned up *ever*
Object threadStateMapping = Reflection.getPrivateValue(Py.class, null, "threadStateMapping");
Object cachedThreadState = Reflection.getPrivateValue(threadStateMapping, "cachedThreadState");
ThreadLocal<ThreadState> local = (ThreadLocal<ThreadState>) cachedThreadState;
//System.out.println("ThreadLocal was: 0x" + Integer.toHexString(local.get().hashCode()));
local.set(null);
// Take out the Python/Google finalizer thread
// It is supposed to die on its own when its class loader is reclaimed, but it appears
// as though it is keeping the class loader alive itself
ThreadGroup group = Thread.currentThread().getThreadGroup();
Thread[] threads = new Thread[group.activeCount() + 3];
group.enumerate(threads, true);
boolean killed = false;
for (Thread th : threads) {
if (th == null) continue;
// "instanceof Finalizer" cannot be used because the thread's class uses a different
// class loader than the one we are using here - so the toString is checked instead
if (th.toString().contains(Finalizer.class.getName())) {
killed = true;
th.stop();
break;
}
}
if (!killed) {
getLogger().warning("Failed to kill Jython finalizer thread - there may be PermGen leaks");
}
// Remove our PluginClassLoader from java.lang.Proxy.loaderToCache - the map is supposed to be weak
// but this apparently isn't good enough
Map<ClassLoader, Map<List<String>, Object>> loaderToCache = (Map<ClassLoader, Map<List<String>, Object>>)
Reflection.getPrivateValue(Proxy.class, null, "loaderToCache");
Object o = loaderToCache.remove(getClassLoader());
int i = 0;
Map<Class<?>, Void> proxyClasses = (Map<Class<?>, Void>) Reflection.getPrivateValue(Proxy.class, null, "proxyClasses");
Iterator<Class<?>> iter = proxyClasses.keySet().iterator();
while (iter.hasNext()) {
if (iter.next().getClassLoader() == getClassLoader()) {
iter.remove();
++i;
}
}
System.out.println("Removed " + i + " classes and loaderToCache[" + (o != null) + "]");
} | 9 |
public void Top100(String Top100Sort) throws IOException {
if (!Top100Sort.equals(TOP100REALTIME) && !Top100Sort.equals(TOP100WEEKLY)) {
try {
throw new Top100SearchException("You Must use TOP100REALTIME or TOP100WEEKLY");
} catch (Top100SearchException e) {
e.printStackTrace();
return;
}
}
ClearArrayList();
JSONParser parser = new JSONParser();
try {
URL url = new URL(Top100Sort);
url.openStream();
Scanner scanner = new Scanner(url.openStream(), "UTF-8");
String out = scanner.useDelimiter("\\A").next();
Object obj = parser.parse(out);
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("CONTENTS");
for (int i = 0; i < 100; i++) {
JSONObject j = (JSONObject) array.get(i);
String TOP100 = (String) j.get("SONGID");
String TOP100name = (String) j.get("SONGTITLE");
String TOP100artist = (String) j.get("ARTISTNAME");
String TOP100Albumart = (String) j.get("ALBUMIMGPATH");
SongSIDList.add(TOP100);
TitleList.add(TOP100name);
SingerList.add(TOP100artist);
AlbumartList.add(TOP100Albumart);
}
CombineData();
} catch (ParseException e) {
e.printStackTrace();
}
} | 5 |
private int getPriority(String priority) {
if (priority.equals(m_settings.getLocalizedMessage("priority.vlow")))
return 1;
else if (priority.equals(m_settings.getLocalizedMessage("priority.low")))
return 2;
else if (priority.equals(m_settings.getLocalizedMessage("priority.medium")))
return 3;
else if (priority.equals(m_settings.getLocalizedMessage("priority.high")))
return 4;
else if (priority.equals(m_settings.getLocalizedMessage("priority.vhigh")))
return 5;
else
return 3; // default
} | 5 |
protected PlayerStartPosition getPlayerStartPosition(Grid grid, Player player) {
if (grid == null || player == null)
throw new IllegalArgumentException("The given arguments are invalid!");
return new PlayerStartPosition(grid, player);
} | 2 |
protected double getNumericValue(Cell cell) throws InvalidCellException {
int cellType = cell.getCellType();
if (cellType != Cell.CELL_TYPE_STRING && cellType != Cell.CELL_TYPE_NUMERIC) {
throw new InvalidCellException(cell);
} else if (cellType == Cell.CELL_TYPE_STRING) {
try {
double value = Double.parseDouble(cell.getStringCellValue());
if (isCellValueValid(value)) {
return value;
} else {
throw new InvalidCellException(cell, value);
}
} catch (NumberFormatException ex) {
throw new InvalidCellException(cell, cell.getStringCellValue());
}
} else if (cellType == Cell.CELL_TYPE_NUMERIC) {
double value = cell.getNumericCellValue();
if (isCellValueValid(value)) {
return value;
} else {
throw new InvalidCellException(cell, value);
}
}
throw new InvalidCellException(cell);
} | 7 |
public void mouseExited(MouseEvent event) {
} | 0 |
public final static Opponent getById(String id) throws NotFound {
Opponent o = new Opponent();
String profilePage = Utils.getString("characters/profile/" + id);
int pos = profilePage.indexOf("href=\"/fights/start/");
if (pos == -1) {
throw new NotFound();
}
String page = profilePage.substring(pos);
page = page.substring(0, page.indexOf("<img"));
Pattern p = Pattern.compile("/fights/start/([0-9]+)\"",
Pattern.MULTILINE);
Matcher m = p.matcher(page);
if (!m.find()) {
throw new NotFound();
}
o.setAttack("/fights/start/" + m.group(1));
pos = profilePage.indexOf("<center><b>");
if (pos == -1) {
throw new NotFound();
}
page = profilePage.substring(pos + "<center><b>".length());
page = page.substring(0, page.indexOf("</b></center>")).trim();
o.setName(page);
return o;
} | 3 |
public synchronized static void configure(File... files) {
if (INSTANCE == null) {
INSTANCE = new LaunchProxy(files);
try {
// Give it a chance to terminate this run...
Thread.sleep(1500);
} catch (Exception exception) {
// Ignore
}
} else {
Log.error("Can only call configure once."); //$NON-NLS-1$
}
} | 2 |
public void func_50032_g(int par1)
{
int var2 = this.text.length();
if (par1 > var2)
{
par1 = var2;
}
if (par1 < 0)
{
par1 = 0;
}
this.field_50048_p = par1;
if (this.fontRenderer != null)
{
if (this.field_50041_n > var2)
{
this.field_50041_n = var2;
}
int var3 = this.func_50019_l();
String var4 = this.fontRenderer.trimStringToWidth(this.text.substring(this.field_50041_n), var3);
int var5 = var4.length() + this.field_50041_n;
if (par1 == this.field_50041_n)
{
this.field_50041_n -= this.fontRenderer.trimStringToWidth(this.text, var3, true).length();
}
if (par1 > var5)
{
this.field_50041_n += par1 - var5;
}
else if (par1 <= this.field_50041_n)
{
this.field_50041_n -= this.field_50041_n - par1;
}
if (this.field_50041_n < 0)
{
this.field_50041_n = 0;
}
if (this.field_50041_n > var2)
{
this.field_50041_n = var2;
}
}
} | 9 |
private Tile getTile(int x, int y){
return x >= 0 && y >= 0 && x < width && y < height ? grid[x][y] : null;
} | 4 |
@Override
public boolean execute(CommandSender sender, String identifier,
String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (DonorTitles.chat.getPlayerPrefix(player) != null
&& DonorTitles.chat.getPlayerPrefix(player) != "") {
DonorTitles.chat.setPlayerPrefix(player, "");
sender.sendMessage("Your title has been cleared.");
return true;
}
sender.sendMessage("You do not have a title set.");
return false;
}
sender.sendMessage("Only players can use this command");
return false;
} | 3 |
public void setValue(Object value){
int currentValue = (Integer) getValue();
int v = (Integer) value;
int result = v;
if(v > getMaximum()){
result = getMaximum();
}
else if(v < getMinimum()){
result = getMinimum();
}
if(result != currentValue){
super.setValue(result);
checkUpDownButtonsEnabled();
}
JTextField textField = ((JSpinner.DefaultEditor)getEditor()).getTextField();
textField.setText(String.valueOf(getValue()));
} | 3 |
public void drawProps(Graphics g){
if( number % 4 == 0 ){
for(Prop p : PropsContainer.getValidProps()){
if( p.getStatus() == PropStatus.ALIVE)
switch( p.getType()){
case PropType.mime :
g.drawImage(this.prop_mime, p.getX(), p.getY(), Constant.PROP_WIDTH_HEIGHT, Constant.PROP_WIDTH_HEIGHT, this);
break ;
case PropType.hat :
g.drawImage(this.prop_hat, p.getX(), p.getY(), Constant.PROP_WIDTH_HEIGHT, Constant.PROP_WIDTH_HEIGHT, this);
break ;
case PropType.life :
g.drawImage(this.prop_life, p.getX(), p.getY(), Constant.PROP_WIDTH_HEIGHT, Constant.PROP_WIDTH_HEIGHT, this);
break ;
case PropType.star :
g.drawImage(this.prop_star, p.getX(), p.getY(), Constant.PROP_WIDTH_HEIGHT, Constant.PROP_WIDTH_HEIGHT, this);
break ;
}
}
}
} | 7 |
public static void main(String[] args) {
TotalOrder g;
String arg;
long timeout=200;
int num_fields=3;
int field_size=80;
String props=null;
int num=0;
props="udp.xml";
for(int i=0; i < args.length; i++) {
arg=args[i];
if("-timeout".equals(arg)) {
timeout=Long.parseLong(args[++i]);
continue;
}
if("-num_fields".equals(arg)) {
num_fields=Integer.parseInt(args[++i]);
continue;
}
if("-field_size".equals(arg)) {
field_size=Integer.parseInt(args[++i]);
continue;
}
if("-help".equals(arg)) {
System.out.println("\nTotalOrder [-timeout <value>] [-num_fields <value>] " +
"[-field_size <value>] [-props <properties (can be URL)>] [-num <num requests>]\n");
return;
}
if("-props".equals(arg)) {
props=args[++i];
continue;
}
if("-num".equals(arg)) {
num=Integer.parseInt(args[++i]);
}
}
try {
g=new TotalOrder("Total Order Demo on " + InetAddress.getLocalHost().getHostName(),
timeout, num_fields, field_size, props, num);
g.setVisible(true);
}
catch(Exception e) {
System.err.println(e);
}
} | 8 |
public NioSocketServer() {
try {
// Create an AsynchronousServerSocketChannel that will listen on port 5000
final AsynchronousServerSocketChannel listener =
AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(5000));
// Listen for a new request
listener.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
@Override
public void completed(AsynchronousSocketChannel ch, Void att) {
// Accept the next connection
listener.accept(null, this);
// Greet the client
ch.write(ByteBuffer.wrap("Hello, I am Echo Server 2020, let's have an engaging conversation!\n".getBytes()));
// Allocate a byte buffer (4K) to read from the client
ByteBuffer byteBuffer = ByteBuffer.allocate(4096);
try {
// Read the first line
int bytesRead = ch.read(byteBuffer).get(20, TimeUnit.SECONDS);
boolean running = true;
while (bytesRead != -1 && running) {
System.out.println("bytes read: " + bytesRead);
// Make sure that we have data to read
if (byteBuffer.position() > 2) {
// Make the buffer ready to read
byteBuffer.flip();
// Convert the buffer into a line
byte[] lineBytes = new byte[bytesRead];
byteBuffer.get(lineBytes, 0, bytesRead);
String line = new String(lineBytes);
// Debug
System.out.println("Message: " + line);
// Echo back to the caller
ch.write(ByteBuffer.wrap(line.getBytes()));
// Make the buffer ready to write
byteBuffer.clear();
// Read the next line
bytesRead = ch.read(byteBuffer).get(20, TimeUnit.SECONDS);
} else {
// An empty line signifies the end of the conversation in our protocol
running = false;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
// The user exceeded the 20 second timeout, so close the connection
ch.write(ByteBuffer.wrap("Good Bye\n".getBytes()));
System.out.println("Connection timed out, closing connection");
}
System.out.println("End of conversation");
try {
// Close the connection if we need to
if (ch.isOpen()) {
ch.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
@Override
public void failed(Throwable exc, Void att) {
///...
}
});
} catch (IOException e) {
e.printStackTrace();
}
} | 9 |
public void addCircle(Circle circle) {
if (this.next == start) {
this.next = circle;
circle.next = start;
} else {
this.next.addCircle(circle);
}
} | 1 |
public static void stopPlayback() {
try {
if(currentPlayback != null) {
currentPlayback.stop();
}
} catch (MediaException e) {
System.out.println("Invalid media type.");
}
} | 2 |
private byte[] insertGapCore0w(byte[] code, int where, int gapLength, boolean exclusive,
ExceptionTable etable, CodeAttribute ca, Gap newWhere)
throws BadBytecode
{
if (gapLength <= 0)
return code;
ArrayList jumps = makeJumpList(code, code.length);
Pointers pointers = new Pointers(currentPos, mark, where, etable, ca);
byte[] r = insertGap2w(code, where, gapLength, exclusive, jumps, pointers);
currentPos = pointers.cursor;
mark = pointers.mark;
int where2 = pointers.mark0;
if (where2 == currentPos && !exclusive)
currentPos += gapLength;
if (exclusive)
where2 -= gapLength;
newWhere.position = where2;
newWhere.length = gapLength;
return r;
} | 4 |
public static JnlpCache create() {
try {
Class<? extends ServiceManager> cl = Class.forName("javax.jnlp.ServiceManager").asSubclass(ServiceManager.class);
Method m = cl.getMethod("lookup", String.class);
BasicService basic = (BasicService)m.invoke(null, "javax.jnlp.BasicService");
PersistenceService prs = (PersistenceService)m.invoke(null, "javax.jnlp.PersistenceService");
return(new JnlpCache(prs, basic.getCodeBase()));
} catch(Exception e) {
return(null);
}
} | 2 |
private MapSquare getMapSquare(int x, int y)
{
ArrayList<MapSquare> d_map = dp.getDisplay();
for (int i = 0; i < d_map.size(); i++)
{
//find which square was clicked
if(d_map.get(i).getDisplayX() * GlobalSettings.SQUARE_SIZE <= x &&
d_map.get(i).getDisplayX() * GlobalSettings.SQUARE_SIZE + GlobalSettings.SQUARE_SIZE >= x &&
d_map.get(i).getDisplayY() * GlobalSettings.SQUARE_SIZE <= y &&
d_map.get(i).getDisplayY() * GlobalSettings.SQUARE_SIZE + GlobalSettings.SQUARE_SIZE >= y)
{
return d_map.get(i);
}
}
return null;
} | 5 |
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {try {
//GEN-FIRST:event_jButton1ActionPerformed
list = new DessertDao();
} catch (SAXException ex) {
Logger.getLogger(addItemToDessertMenu.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(addItemToDessertMenu.class.getName()).log(Level.SEVERE, null, ex);
}
Name = getItemName();
Description = getItemDescriptionName();
Price = getItemPrice();
PictureName = getPictureName();
if(Name.equals("") || Description.equals("") || Price.equals("") || PictureName.equals("")){
JOptionPane.showMessageDialog(this,
"YOU MUST ENTER ALL INFORMATION",
"CHECK VALUES AGAIN",
JOptionPane.ERROR_MESSAGE);
}
else{
list.addDessert(Name,Description, 1,Price,PictureName);
System.out.println(getItemName()+' '+getItemDescriptionName()+" " + getItemPrice()+" "+getPictureName());
JOptionPane.showMessageDialog(this,
"YOUR ITEM HAS BEEN ADDED!!!",
"CONFIRMATION DIALOG",
JOptionPane.WARNING_MESSAGE);
itemNameValue.setText("");
itemDescriptionValue.setText("");
itemPriceValue.setText("0");
itemPictureValue.setText("Click Here To Select Image");
adminLogInDialog.dessertMenu.removeAll();
try {
adminLogInDialog.dessertMenu.setUpComponents();
} catch (SAXException ex) {
Logger.getLogger(addItemToDessertMenu.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(addItemToDessertMenu.class.getName()).log(Level.SEVERE, null, ex);
}
adminLogInDialog.dessertEditPane.revalidate();
}
}//GEN-LAST:event_jButton1ActionPerformed | 8 |
public double kurtosisExcess_as_double() {
boolean hold = Stat.nFactorOptionS;
if (nFactorReset) {
if (nFactorOptionI) {
Stat.nFactorOptionS = true;
} else {
Stat.nFactorOptionS = false;
}
}
double kurtosis = 0.0D;
switch (type) {
case 1:
double[] dd = this.getArray_as_double();
kurtosis = Stat.kurtosisExcess(dd);
break;
case 12:
BigDecimal[] bd = this.getArray_as_BigDecimal();
kurtosis = (Stat.kurtosisExcess(bd)).doubleValue();
bd = null;
break;
case 14:
throw new IllegalArgumentException("Complex kurtosis is not supported");
default:
throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!");
}
Stat.nFactorOptionS = hold;
return kurtosis;
} | 5 |
public void setEmail(String email) {
this.email = email;
} | 0 |
public void testFactory_monthsBetween_RPartial_YearMonth() {
YearMonth start1 = new YearMonth(2011, 1);
for (int i = 0; i < 6; i++) {
YearMonth start2 = new YearMonth(2011 + i, 1);
YearMonth end = new YearMonth(2011 + i, 3);
assertEquals(i * 12 + 2, Months.monthsBetween(start1, end).getMonths());
assertEquals(2, Months.monthsBetween(start2, end).getMonths());
}
} | 1 |
public boolean isMaximized() {
return ((OutlinerDesktopManager) getDesktopManager()).isMaximized();
} | 0 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Tag other = (Tag) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
} | 9 |
public static void saveDataToFile(File file, String content) throws IOException {
File storage = getStorageFolder();
if(!storage.exists()) {
if(!storage.mkdir()) {
throw new IOException("Can not create a storage folder " + storage.getAbsolutePath());
}
}
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(file, false)));
out.println(content);
} finally {
if(out != null) {
out.close();
}
}
} | 3 |
public static void confirmationNouvellePartie(int lignes, int colonnes) {
fenetrePrincipale = new WindowPrincipale(lignes, colonnes);
fenetreNouvellePartie.dispose();
} | 0 |
public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
} | 6 |
private String getTestName(int no) {
return name != null ? name : ("test-" + no);
} | 1 |
@Override
public Object clone( ){// Clone an IntTreeBag object.
IntTreeBag answer = null;
try{
answer = (IntTreeBag) super.clone();
}catch(CloneNotSupportedException e){
System.out.println(e.toString());
}
answer.root = IntBTNode.treeCopy(root);
return answer;
} | 1 |
public void setRange(Map m)
{
tilesInRange = new ArrayList<Tile>();
Tile[][] grid = m.getGrid();
//grab which tiles are in range
int xMin = location.getX() - attacks.get(0).getHorizontalRange();
int xMax = location.getX() + attacks.get(0).getHorizontalRange();
int yMin = location.getY() - attacks.get(0).getVerticalRange();
int yMax = location.getY() + attacks.get(0).getVerticalRange();
int x;
int y;
//Calculates range boundaries, based on attack range and map boundaries
if(xMin <0)
{
xMin = 0;
}
if(yMin < 0)
{
yMin = 0;
}
if(xMax > m.getWidth())
{
xMax = m.getWidth();
}
if(yMax > m.getHeight())
{
yMax = m.getHeight();
}
//Adds tiles in range to the range array
for(x = xMin; x <= xMax; x++)
{
for(y = yMin; y <= yMax; y++)
{
if (x < m.getWidth() && y < m.getHeight()) {
tilesInRange.add(grid[x][y]);
}
}
}
} | 8 |
public void stop() {
if(this.thread != null) {
this.cont = false;
try {
logger.info("Stopping monitor thread.");
this.thread.join(JOIN_TIME);
} catch(Exception e) {
logger.info("Error in thread processing.", e);
} finally {
logger.info("Thread is destroyed.");
this.thread = null;
}
}
} | 2 |
public static void addGolden(JSONObject fight) {
if (isHtmlOutput()) {
try {
// Dateinamen generieren
String filename = String.valueOf(new Date().getTime())
+ fight.getJSONObject("opponent").getString("name")
.replaceAll("[^a-zA-Z0-9]", "_") + ".html";
// Kampf-Daten schreiben
add(new GoldenFile(fight, getInstance().htmlPath
+ Output.DIR_HTML + filename));
// Log generieren
JSONObject log = LogFile.getLog("Golden", fight.getJSONObject(
"opponent").getString("name"));
log.put("file", "." + DIR_HTML + filename);
log.put("good", fight.getJSONObject("results").getBoolean(
"fightWasWon"));
// Log schreiben
Output.addLog(log);
} catch (JSONException e) {
}
}
} | 2 |
private void managePeerConnection() throws Exception{
//Send/ receive handshake
if(!manageHandshake()){
//handshake failed - quit connection to this peer.
return;
}
//After handshake, instantiates a message sender;
this.messageSender = new MessageSender(peer, out);
Thread thread = new Thread(this.messageSender);
thread.start();
//Keep connection with peer up sending/receiving messages until the user initiates the shutdown sequence
while(!manager.stopThreads){
try{
if(!peer.amConnected()){
disposeCurrPiece();
closeConnections();
return;
}
processMessage(Message.decode(in), peer);
Thread.sleep(10);
} catch (EOFException eofe){
System.err.println("EOFException from peer " + this.peer + "... disconnecting from peer.");
disposeCurrPiece();
closeConnections();
return;
}
}
//close streams/ Socket
System.out.println("Closing streams and socket for Peer: " + peer.toString());
closeConnections();
} | 4 |
public boolean contains(StructuredBlock child) {
while (child != this && child != null)
child = child.outer;
return (child == this);
} | 2 |
void close ()
throws USBException
{
if (fd < 0)
return;
try {
// make sure this isn't usable any more
int status = closeNative (fd);
if (status < 0)
throw new USBException (
"error closing device",
-status);
} finally {
// make sure nobody else sees the device
usb.removeDev (this);
hub = null;
fd = -1;
}
} | 2 |
@Override
public TreeModel getTreeModel() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Threats");
List<Archive> archives = new ArrayList<Archive>();
archives.add(FileManager.getRuntimeArchive());
archives.addAll(FileManager.getPlugins());
for (Archive archive : archives)
for (ClassNode classNode : archive)
root.add(new TreeNodeThreat(classNode.name, classNode));
return new DefaultTreeModel(root);
} | 2 |
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
Contestant contestant = contestants.get(rowIndex);
switch (columnIndex) {
case COLUMN_USERNAME:
contestant.setUsername(value.toString());
break;
case COLUMN_PASSWORD:
contestant.setPassword(value.toString());
break;
}
DbAdapter.updateContestant(contestant, false);
this.fireTableDataChanged(); // update JTable
} | 2 |
public final synchronized Complex readComplex(){
this.inputType = true;
String word="";
Complex cc = null;
if(!this.testFullLineT) this.enterLine();
word = nextWord();
if(!eof)cc = Complex.parseComplex(word.trim());
return cc;
} | 2 |
public boolean test(int i){
return (datamap[i>>5] & (1<<(i & 0x1F))) != 0;
} | 0 |
private int[] extractSameValues(ArrayList<Card> cards) {
int[] valueCount = new int[VALUE.values().length];
for (int i = 0; i < valueCount.length; i++) {
valueCount[i] = 0;
}
// sort highest first
for (int i = 0; i < cards.size(); ++i) {
valueCount[cards.get(i).value.ordinal()]++;
}
return valueCount;
} | 2 |
private Class<?> createRelated(Class<?> type, Class<?> relatedType) {
if (relatedType == null && type.isArray()) {
relatedType = Array.newInstance(type, 0).getClass();
}
if (!type.equals(relatedType)) {
return type.getSuperclass();
}
return null;
} | 6 |
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
} | 0 |
private void setupLiseners()
{
addHipsterButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
sendHipsterInfoToController();
updateHipsterComboBox();
blankFields(false);
}
});
showSelfButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
Hipster selfHipster = baseController.getSelfHipster();
populateFields(selfHipster);
}
});
showSpecificButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
Hipster selectedHipster = baseController.getSpecifiedHipster(0);
if (selectedHipster != null)
{
populateFields(selectedHipster);
}
else
{
blankFields(true);
}
}
});
showRandomButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
Hipster randomHipster = baseController.getRandomHipster();
if(randomHipster != null)
{
populateFields(randomHipster);
}
else
{
blankFields(true);
}
}
});
selectedHipsterComboBox.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent itemSelected)
{
int currentSelection = selectedHipsterComboBox.getSelectedIndex();
if(currentSelection >=0)
{
Hipster selectedHipster = baseController.getSpecifiedHipster(currentSelection);
if(selectedHipster != null)
{
populateFields(selectedHipster);
}
else
{
blankFields(true);
}
}
}
});
} | 4 |
public static void main(String[] args) throws Exception{
//ColorDisplay is a frame. 1,1 in arguments mean 7*7. 2,1 is 14*7 and so on.
ColorDisplay d = new ColorDisplay(1,1,Color.RED, Color.CYAN);
//An object with all possible characters
ArrayChars chars = new ArrayChars();
//An input window asking for a string
String txt = JOptionPane.showInputDialog(
"Ange en text, bara STORA bokstäver, siffror och tecken");
//An array of Array7x7 object to hold the graphical string
Array7x7[] txtArrays = new Array7x7[txt.length()];
//Inserts the graphical counterpart for each character
for(int i = 0; i < txt.length(); i++){
txtArrays[i] = chars.getChar(txt.charAt(i));
}
JFrame frame = new JFrame("Test Arrays");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(d);
frame.pack();
frame.setVisible(true);
//New Timer object to delay each char 1 second
Timer timer = new Timer();
//TimerTask is an object, and requires a written class
timer.schedule(new TimerTask() { // Here starts the class
int counter = 0;
// A run() method is required
@Override
public void run() {
// if there's more characters to show, the timer will keep on going
if(counter < txt.length()){
//the elements which contains value 1 changes to a int-value representing a color.
for(int row = 0; row < 7; row++) {
for(int col = 0; col < 7; col++) {
if(txtArrays[counter].getElement(row, col) == 1) {
txtArrays[counter].setElement(row, col, Color.BLACK);
}
}
}
//setDisplay argument is a 2D array
d.setDisplay(txtArrays[counter].getArray());
d.updateDisplay();
counter++;
// If there's no more characters, the timer will stop
}else{
timer.cancel();
}
}
// Initial delay and period in milliseconds
}, 1000, 1000);
} | 5 |
public static void main(String[] args) throws IOException {
int height = 15;
int[][] triangle = new int[height][height];
File file = new File("0018/triangle.txt");
List<String> lines = FileUtils.readLines(file);
int y = 0;
for (String line : lines) {
String[] numbers = line.split(" ");
int x = 0;
for (String number : numbers) {
triangle[x++][y] = Integer.valueOf(number);
}
y++;
}
y = height - 1;
while (y > 0) {
y -= 1;
for (int x = 0; x <= y; x++) {
int value = triangle[x][y];
triangle[x][y] = value + Math.max(triangle[x][y + 1], triangle[x + 1][y + 1]);
System.out.println(triangle[x][y]);
}
}
} | 4 |
public void render(GameContainer gc, StateBasedGame sbg, Graphics g)throws SlickException
{
if(!isGameOver)
{
if(!isPause)
{
}
else
{
}
}
else
{
}
} | 2 |
private void draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
// antialiasing ON
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
//enable user input
if(fleetEditorModel.getVehicles().size() > 0){
saveVehicleJB.setEnabled(true);
deleteVehicleJB.setEnabled(true);
enableUserInput();
//for all vehicles
Vehicle vehicle = fleetEditorModel.getVehicles().get(fleetEditorModel.getVehiclePos());
vehicleIDJTF.setText(String.valueOf(vehicle.getId()));
vehicleNameJTF.setText(vehicle.getName());
vehicleSpeedJCB.setSelectedItem(new Integer(vehicle.getMaxSpeed()));
//if car
if(vehicle instanceof Car){
Car c = (Car) vehicle;
vehicleGasUsageLowJCB.setSelectedItem(new Float(c.getGasConsumptionLow()));
vehicleGasUsageLowJCB.setEnabled(true);
vehicleGasUsageMediumJCB.setSelectedItem(new Float(c.getGasConsumptionMedium()));
vehicleGasUsageMediumJCB.setEnabled(true);
vehicleGasUsageHighJCB.setSelectedItem(new Float(c.getGasConsumptionHigh()));
vehicleGasUsageHighJCB.setEnabled(true);
//if bicycle
}else if(vehicle instanceof Bicycle){
vehicleGasUsageLowJCB.setSelectedIndex(-1);
vehicleGasUsageLowJCB.setEnabled(false);
vehicleGasUsageMediumJCB.setSelectedIndex(-1);
vehicleGasUsageMediumJCB.setEnabled(false);
vehicleGasUsageHighJCB.setSelectedIndex(-1);
vehicleGasUsageHighJCB.setEnabled(false);
}
}else{
saveVehicleJB.setEnabled(false);
deleteVehicleJB.setEnabled(false);
}
// draw vehicles in fleetSelection
if(fleetEditorModel.getVehicles().size() > 2){
if(fleetEditorModel.getVehiclePos() - 1 == -1){
fleetPreviousVehicleII = new ImageIcon(fleetEditorModel.getVehicles().get(fleetEditorModel.getVehicles().size()-1).getVehicleTypes().getUrlVehicle());
fleetPreviousVehicleII.setImage(fleetPreviousVehicleII.getImage().getScaledInstance(150, 150,Image.SCALE_DEFAULT));
fleetPreviousVehicleJL.setIcon(fleetPreviousVehicleII);
}else {
fleetPreviousVehicleII = new ImageIcon(fleetEditorModel.getVehicles().get(fleetEditorModel.getVehiclePos()-1).getVehicleTypes().getUrlVehicle());
fleetPreviousVehicleII.setImage(fleetPreviousVehicleII.getImage().getScaledInstance(150, 150,Image.SCALE_DEFAULT));
fleetPreviousVehicleJL.setIcon(fleetPreviousVehicleII);
}
fleetCurrentVehicleII = new ImageIcon(fleetEditorModel.getVehicles().get(fleetEditorModel.getVehiclePos()).getVehicleTypes().getUrlVehicle());
fleetCurrentVehicleII.setImage(fleetCurrentVehicleII.getImage().getScaledInstance(250, 250,Image.SCALE_DEFAULT));
fleetCurrentVehicleJL.setIcon(fleetCurrentVehicleII);
if(fleetEditorModel.getVehiclePos() +1 == fleetEditorModel.getVehicles().size()){
fleetNextVehicleII = new ImageIcon(fleetEditorModel.getVehicles().get(0).getVehicleTypes().getUrlVehicle());
fleetNextVehicleII.setImage(fleetNextVehicleII.getImage().getScaledInstance(150, 150,Image.SCALE_DEFAULT));
fleetNextVehicleJL.setIcon(fleetNextVehicleII);
}else {
fleetNextVehicleII = new ImageIcon(fleetEditorModel.getVehicles().get(fleetEditorModel.getVehiclePos()+1).getVehicleTypes().getUrlVehicle());
fleetNextVehicleII.setImage(fleetNextVehicleII.getImage().getScaledInstance(150, 150,Image.SCALE_DEFAULT));
fleetNextVehicleJL.setIcon(fleetNextVehicleII);
}
}else if(fleetEditorModel.getVehicles().size() > 1){
fleetCurrentVehicleII = new ImageIcon(fleetEditorModel.getVehicles().get(fleetEditorModel.getVehiclePos()).getVehicleTypes().getUrlVehicle());
fleetCurrentVehicleII.setImage(fleetCurrentVehicleII.getImage().getScaledInstance(250, 250,Image.SCALE_DEFAULT));
fleetCurrentVehicleJL.setIcon(fleetCurrentVehicleII);
if(fleetEditorModel.getVehiclePos() +1 == fleetEditorModel.getVehicles().size()){
fleetNextVehicleII = new ImageIcon(fleetEditorModel.getVehicles().get(0).getVehicleTypes().getUrlVehicle());
fleetNextVehicleII.setImage(fleetNextVehicleII.getImage().getScaledInstance(150, 150,Image.SCALE_DEFAULT));
fleetNextVehicleJL.setIcon(fleetNextVehicleII);
}else {
fleetNextVehicleII = new ImageIcon(fleetEditorModel.getVehicles().get(fleetEditorModel.getVehiclePos()+1).getVehicleTypes().getUrlVehicle());
fleetNextVehicleII.setImage(fleetNextVehicleII.getImage().getScaledInstance(150, 150,Image.SCALE_DEFAULT));
fleetNextVehicleJL.setIcon(fleetNextVehicleII);
}
fleetPreviousVehicleJL.setIcon(null);
}else if(fleetEditorModel.getVehicles().size() > 0){
fleetCurrentVehicleII = new ImageIcon(fleetEditorModel.getVehicles().get(fleetEditorModel.getVehiclePos()).getVehicleTypes().getUrlVehicle());
fleetCurrentVehicleII.setImage(fleetCurrentVehicleII.getImage().getScaledInstance(250, 250,Image.SCALE_DEFAULT));
fleetCurrentVehicleJL.setIcon(fleetCurrentVehicleII);
fleetNextVehicleJL.setIcon(null);
fleetPreviousVehicleJL.setIcon(null);
}else{
fleetCurrentVehicleJL.setIcon(null);
fleetNextVehicleJL.setIcon(null);
fleetPreviousVehicleJL.setIcon(null);
}
// draw vehicle in vehicleSelection
vehicleSelectionII = new ImageIcon(fleetEditorModel.getVehicleSelection().get(fleetEditorModel.getVehicleSelectionPos()).getVehicleTypes().getUrlVehicle());
vehicleSelectionII.setImage(vehicleSelectionII.getImage().getScaledInstance(200, 200,Image.SCALE_DEFAULT));
vehicleSelectionJL.setIcon(vehicleSelectionII);
} | 9 |
public CanonicalizationMethodType createCanonicalizationMethodType() {
return new CanonicalizationMethodType();
} | 0 |
@Override
public boolean keyUp(int keycode) {
switch(keycode) {
case Keys.W:
direction.y = 0;
animationTime = 0;
break;
case Keys.A:
direction.x = 0;
animationTime = 0;
break;
case Keys.S:
direction.y = 0;
animationTime = 0;
break;
case Keys.D:
direction.x = 0;
animationTime = 0;
break;
}
return true;
} | 4 |
public String readField(String fields[], int fieldNum) {
if (fields.length > fieldNum) {
if (fields[fieldNum].equals(MISSING)) return EMPTY;
return fields[fieldNum];
}
return EMPTY;
} | 2 |
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking,tickID))
return false;
if(affected==null)
return false;
if(!(affected instanceof MOB))
return true;
final MOB mob=(MOB)affected;
if((!mob.amDead())&&((--diseaseTick)<=0))
{
diseaseTick=DISEASE_DELAY();
final List<Ability> offensiveEffects=returnOffensiveAffects(mob);
for(int a=offensiveEffects.size()-1;a>=0;a--)
offensiveEffects.get(a).unInvoke();
mob.location().show(mob,null,CMMsg.MSG_NOISYMOVEMENT,DISEASE_AFFECT());
MOB diseaser=invoker;
if(diseaser==null)
diseaser=mob;
if(mob.curState().getHitPoints()>2)
{
mob.maxState().setHitPoints(mob.curState().getHitPoints()-1);
CMLib.combat().postDamage(diseaser,mob,this,1,CMMsg.MASK_ALWAYS|CMMsg.TYP_DISEASE,-1,null);
}
return true;
}
return true;
} | 8 |
public static void main(String[] args) throws Throwable{
long[] arr = new long[30001];
int[] costos = new int[]{10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5};
arr[0]=1;
for (int i = 0; i < costos.length; i++)
for (int j = costos[i]; j < arr.length; j++)
arr[j]+=arr[j-costos[i]];
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (int c; ; ) {
StringTokenizer st = new StringTokenizer(in.readLine().trim(), ".");
c = parseInt(st.nextToken()) * 100 + parseInt(st.nextToken());
if(c==0)break;
for (int i = ("" + c).length() + (c<100?1:0) + (c<10?1:0); i < 5; i++)
System.out.print(" ");
System.out.printf(Locale.US, "%.2f", c/100.0);
for (int i = ("" + arr[c]).length(); i < 17; i++)
System.out.print(" ");
System.out.println(arr[c]);
}
} | 8 |
public int getXSize() {
return xSize;
} | 0 |
public static void cleanUp () {
Map map = Map.getMap(LaunchFrame.getSelectedMapIndex());
File tempFolder = new File(OSUtils.getCacheStorageLocation(), MAPS.replace("/",sep) + map.getMapName() + sep);
for (String file : tempFolder.list()) {
if (!file.equals(map.getLogoName()) && !file.equals(map.getImageName()) && !file.equalsIgnoreCase("version")) {
try {
FTBFileUtils.delete(new File(tempFolder, file));
} catch (IOException e) {
Logger.logError(e.getMessage(), e);
}
}
}
} | 5 |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/javascript");
String voornaam = request.getParameter("voornaam");
String username = request.getParameter("username");
String wachtwoord = request.getParameter("wachtwoord");
String tussenvoegsel = request.getParameter("tussenvoegsel");
String achternaam = request.getParameter("achternaam");
String adresregel1 = request.getParameter("adresregel1");
String adresregel2 = request.getParameter("adresregel2");
String telefoonnummer = request.getParameter("telefoonnummer");
String postcode = request.getParameter("postcode");
String woonplaats = request.getParameter("woonplaats");
String email = request.getParameter("email");
if (voornaam == null || username == null || wachtwoord == null
|| achternaam == null || adresregel1 == null
|| telefoonnummer == null || woonplaats == null
|| postcode == null) {
response.getWriter().write("{\"response\" : \"Niet alle verplichte velden ingevuld\"}");
} else {
if(register(voornaam,achternaam,username,wachtwoord,tussenvoegsel,achternaam,adresregel1,adresregel2,telefoonnummer,email, postcode,woonplaats)){
response.getWriter().write("{\"response\" : \"OK\"}");
} else {
response.getWriter().write("{\"response\" : \"Username is al bezet\"}");
}
}
} | 9 |
public ImageIcon getFrame() {
return frame;
} | 0 |
public void setAnd(TAnd node)
{
if(this._and_ != null)
{
this._and_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._and_ = node;
} | 3 |
private static void startTheGame() {
System.out.println("Консольные крестики-нолики");
System.out.println("Разработка, дизайн и саундтрек: Илья Серебряков (aka Lungo)");
System.out.println("Все права защищены");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Загрузка");
System.out.print("0%");
for (int i = 0; i < 50; i++){
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("|");
}
System.out.println("100%");
System.out.println("Ходить по полю нужно, выбирая ряд и столбец, вводя числа от 0 до 2");
System.out.println("Победит игрок, поставивший три крестика или три нолика в ряд или по диагонали");
System.out.println(" 0 1 2");
System.out.println("0 " + RowA.cell0 + RowA.cell1 + RowA.cell2);
System.out.println("1 " + RowB.cell0 + RowB.cell1 + RowB.cell2);
System.out.println("2 " + RowC.cell0 + RowC.cell1 + RowC.cell2);
} | 3 |
@Override
public boolean matches(String[] input) {
for (String word: input) {
matcher.reset(word);
if (matcher.find()) {
return true;
}
}
return false;
} | 2 |
public JPanel getShutdownmenuMenu() {
if (!isInitialized()) {
IllegalStateException e = new IllegalStateException("Call init first!");
throw e;
}
return this.shutdMenu;
} | 1 |
public String suitToString() {
switch(suit) {
case DIAMONDS:
return "Diamonds";
case CLUBS:
return "Clubs";
case HEARTS:
return "Hearts";
case SPADES:
return "Spades";
default:
return null;
}
} | 4 |
private void scanDirectory(String directoryName, String fileNameFilter)
{
File dir = new File(directoryName);
FilenameFilter filter = new FilenameFilterImpl(fileNameFilter);
if(DEBUG) System.out.println("Scanning '" +directoryName +"' for file matching '" +fileNameFilter +"'");
String[] files = dir.list(filter);
if(files != null) {
for(String file : files) {
String completeFilename = directoryName +"\\" +file;
try {
InputStream pluginxml = getFileFromJar(completeFilename, "plugin.xml");
if(pluginxml != null) {
// extract xml structure from plugin.xml
Document pluginDescr = parseXml(pluginxml);
// cache entries
if(DEBUG) System.out.println("Searching for extensions in " +completeFilename);
extractExtensionPoints(pluginDescr);
} else {
if(DEBUG) System.out.println("No plugin.xml in " +completeFilename);
}
}
catch(Exception exc) {
if(DEBUG) {
System.err.println("Errors while operating with " +completeFilename +" (" +exc +")");
exc.printStackTrace(System.err);
}
}
}
}
} | 8 |
public String getEmail(String username)
{
Connection connection = null;
String email = null;
String query = null;
PreparedStatement statement = null;
try
{
connection = dataSource.getConnection();
query = "SELECT email FROM users WHERE username = ?;";
statement = (PreparedStatement)connection.prepareStatement(query);
statement.setString(1, username);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next())
{
email = resultSet.getString("email");
}
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
finally
{
try
{
statement.close();
connection.close();
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
}
return email;
} | 3 |
@GET
@Produces(MediaType.LIBROS_API_RESENA_COLLECTION)
public ResenaCollection getResenas(@PathParam("idlibro") String idlibro) {
ResenaCollection resenas = new ResenaCollection();
Connection conn = null;
Statement stmt = null;
String sql;
try {
conn = ds.getConnection();
} catch (SQLException e) {
throw new ServiceUnavailableException(e.getMessage());
}
try {
stmt = conn.createStatement();
sql = "SELECT resenas.*, users.name FROM users INNER JOIN resenas ON(idlibro= '"
+ idlibro + "' and users.username=resenas.username) ";
ResultSet rs = stmt.executeQuery(sql);
if (!rs.next()) {
throw new ResenaNotFoundException();
}
//rs.previous();
while (rs.next()) {
Resena resena = new Resena();
resena.setUsername(rs.getString("username"));
resena.setName(rs.getString("name"));
resena.setFecha(rs.getDate("fecha"));
resena.setTexto(rs.getString("texto"));
resena.setIdlibro(rs.getInt("idlibro"));
resena.setIdres(rs.getInt("idres"));
resena.add(LibrosAPILinkBuilder.buildURIResenaId(uriInfo, "self",rs.getInt("idres"),idlibro));
resenas.add(resena);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return resenas;
} | 5 |
public void getInput() {
if(Keyboard.isKeyDown(Keyboard.KEY_W))
move(0,1);
if(Keyboard.isKeyDown(Keyboard.KEY_S))
move(0,-1);
if(Keyboard.isKeyDown(Keyboard.KEY_A))
move(-1,0);
if(Keyboard.isKeyDown(Keyboard.KEY_D))
move(1,0);
if(Keyboard.isKeyDown(Keyboard.KEY_SPACE) && attackDelay.isOver())
attack();
if(Keyboard.isKeyDown(Keyboard.KEY_H))
getData();
} | 7 |
private void establishCanvas() {
alloyWindow = new JPanel();
alloyWindow.setLayout(new BorderLayout());
drawing = new BufferedImage(alloy.getWidth(), alloy.getHeight(), BufferedImage.TYPE_INT_ARGB);
int color = (Color.decode("#770077")).getRGB();
for (int x = 0; x < drawing.getWidth(); x++) {
for (int y = 0; y < drawing.getHeight(); y++) {
drawing.setRGB(x, y, color);
}
}
canvas = new JLabel();
canvas.setLayout(new BorderLayout());
canvas.setIcon(new ImageIcon(drawing));
JScrollPane sp = new JScrollPane(canvas);
alloyWindow.add(sp, BorderLayout.CENTER);
this.add(alloyWindow, BorderLayout.CENTER);
} | 2 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
else if (!(obj instanceof GenericList))
return false;
GenericList gl = (GenericList) obj;
return (quotes == gl.quotes) && varname.equals(gl.varname) && list.equals(gl.list);
} | 4 |
public String NetSpanProcess(String url,String data,String tagName){
try{
URL oURL = new URL(url);
HttpURLConnection soapConnection = (HttpURLConnection) oURL.openConnection();
System.out.println("connect to server...");
//prop= new PropertiesConfiguration("NetSpanIntegrator.properties");
// Send SOAP Message to SOAP Server
soapConnection.setRequestMethod("POST");
soapConnection.setRequestProperty("Host", prop.getString("host_address"));
soapConnection.setRequestProperty("Content-Length", String.valueOf(data.length()));
soapConnection.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
soapConnection.setRequestProperty("SoapAction", "");
soapConnection.setDoOutput(true);
OutputStream reqStream = soapConnection.getOutputStream();
System.out.println("Sending Soap Request is: "+data);
System.out.println("sending data to server");
reqStream.write(data.getBytes());
System.out.println("output receive from server");
BufferedReader br = new BufferedReader(new InputStreamReader(soapConnection.getInputStream()));
StringBuilder responseSB = new StringBuilder();
String line;
String statusResult = null;
while ( (line = br.readLine()) != null){
responseSB.append(line);
MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
SOAPMessage message = mf.createMessage(new MimeHeaders(), new ByteArrayInputStream(responseSB.toString().getBytes(Charset.forName("UTF-8"))));
NodeList returnList=message.getSOAPBody().getElementsByTagName(tagName);
NodeList innerResultList = returnList.item(0).getChildNodes();
if (innerResultList.item(0).getNodeName()
.equalsIgnoreCase("ReturnCode")) {
int isSucces = Integer.valueOf(innerResultList.item(0)
.getTextContent().trim());
if(isSucces==0){
statusResult="Success";
System.out.println(statusResult);
}else{
if (innerResultList.item(1).getNodeName()
.equalsIgnoreCase("ReturnString")) {
String resulterror = innerResultList.item(1).getTextContent().trim();
statusResult="failure :"+resulterror;
System.out.println(statusResult);
}
}
}
}
// Close streams
br.close();
reqStream.close();
return statusResult;
}catch(MalformedURLException e){
return null;
}catch(IOException e){
return null;
}catch(Exception e){
return null;
}
} | 7 |
public String getUserInfo(String appKey, String userKey) {
try {
appKey = URLEncoder.encode(appKey, "UTF-8");
userKey = URLEncoder.encode(userKey, "UTF-8");
} catch (UnsupportedEncodingException e) {
BmLog.error(e);
}
return String.format("%s/api/rest/blazemeter/getUserInfo/?app_key=%s&user_key=%s", SERVER_URL, appKey, userKey);
} | 1 |
@Override
public void draw(Graphics2D drawScreen, int offsetX, int offsetY) {
for (Entity entity : entityList) {
Spatial spatial = entity.getComponent(Spatial.class);
Health health = entity.getComponent(Health.class);
HealthBar healthBarInfo = entity.getComponent(HealthBar.class);
// Draw the red
drawScreen.setColor(Color.red);
drawScreen.fillRect((int) ((spatial.x + spatial.width / 2 - healthBarInfo.healthBarWidth / 2) - viewport.getX()),
(int) ((spatial.y - spatial.height / 2 + healthBarInfo.healthBarYOffset) - viewport.getY()),
healthBarInfo.healthBarWidth, healthBarInfo.healthBarHeight);
// Draw the green
if (health.currentHealth > 0) {
float healthPercentage = (float) health.currentHealth / health.startingHealth;
int greenWidth = (int) (healthBarInfo.healthBarWidth * healthPercentage);
drawScreen.setColor(Color.green);
drawScreen.fillRect((int) ((spatial.x + spatial.width / 2 - healthBarInfo.healthBarWidth / 2) - viewport.getX()),
(int) ((spatial.y - spatial.height / 2 + healthBarInfo.healthBarYOffset) - viewport.getY()),
greenWidth, healthBarInfo.healthBarHeight);
}
// Draw the border
drawScreen.setColor(Color.black);
drawScreen.drawRect((int) ((spatial.x + spatial.width / 2 - healthBarInfo.healthBarWidth / 2) - viewport.getX()),
(int) ((spatial.y - spatial.height / 2 + healthBarInfo.healthBarYOffset) - viewport.getY()),
healthBarInfo.healthBarWidth, healthBarInfo.healthBarHeight);
}
} | 2 |
private void buildTree(TeaClassifier tc, TeaNode parent, String[] valueCombo, int level, List<Integer> usedAttributes, double sugar) {
if (length < level + 1) {
length = level + 1;
}
if (parent.getAttributeNum() == 0) {
for (String val : Tea.TEA_TYPE_VALUES) {
buildForStringFeature(tc, parent, valueCombo, level, usedAttributes, sugar, val, 0);
}
} else if (parent.getAttributeNum() == 2) {
for (String val : Tea.ADDITION_VALUES) {
buildForStringFeature(tc, parent, valueCombo, level, usedAttributes, sugar, val, 1);
}
} else if (parent.getAttributeNum() == 1) {
buildForDoubleFeature(tc, parent, valueCombo, level, usedAttributes, sugar, 1);
}
} | 6 |
public IntelligenceArtificielle getIntelligenceArtificielle(Parametre parametre) {
IntelligenceArtificielle intelligenceArtificielle = null;
switch (parametre.getDifficulte()) {
case "Facile":
intelligenceArtificielle = new IntelligenceArtificielleFacile(parametre);
break;
case "Normal":
intelligenceArtificielle = new IntelligenceArtificielleMoyen(parametre);
break;
case "Difficile":
intelligenceArtificielle = new IntelligenceArtificielleDifficile(parametre);
break;
}
return intelligenceArtificielle;
} | 3 |
@Override
public void unInvoke()
{
// undo the affects of this spell
if(!(affected instanceof MOB))
return;
super.unInvoke();
if((canBeUninvoked())&&(clan1!=null)&&(clan2!=null))
{
final Clan C1=clan1;
final Clan C2=clan2;
if((C1!=null)&&(C2!=null))
{
if(C1.getClanRelations(C2.clanID())==Clan.REL_WAR)
{
C1.setClanRelations(C2.clanID(),Clan.REL_HOSTILE,System.currentTimeMillis());
C1.update();
}
if(C2.getClanRelations(C1.clanID())==Clan.REL_WAR)
{
C2.setClanRelations(C1.clanID(),Clan.REL_HOSTILE,System.currentTimeMillis());
C2.update();
}
final List<String> channels=CMLib.channels().getFlaggedChannelNames(ChannelsLibrary.ChannelFlag.CLANINFO);
for(int i=0;i<channels.size();i++)
CMLib.commands().postChannel(channels.get(i),CMLib.clans().clanRoles(),L("There is now peace between @x1 and @x2.",C1.name(),C2.name()),false);
}
}
} | 9 |
@Override
public void actionPerformed(ActionEvent e) {
OutlinerDocument doc = (OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched();
OutlinerCellRendererImpl textArea = doc.panel.layout.getUIComponent(doc.tree.getEditingNode());
if (textArea == null) {
return;
}
Node node = textArea.node;
JoeTree tree = node.getTree();
OutlineLayoutManager layout = tree.getDocument().panel.layout;
if (doc.tree.getComponentFocus() == OutlineLayoutManager.TEXT) {
ToggleExpansionAction.toggleExpansionText(node, tree, layout, false);
} else if (doc.tree.getComponentFocus() == OutlineLayoutManager.ICON) {
ToggleExpansionAction.toggleExpansion(node, tree, layout, false);
}
} | 3 |
public boolean setPWfieldHeight(int height) {
boolean ret = true;
if (height <= 10) {
this.pwfield_Height = UISizeInits.PWFIELD.getHeight();
ret = false;
} else {
this.pwfield_Height = height;
}
somethingChanged();
return ret;
} | 1 |
@Override
public void simpleInitApp() {
flyCam.setMoveSpeed(2); /** Translucent/transparent cube. Uses Texture from jme3-test-data library! */
ContentManager.getInstance().setAssetManager(assetManager);
ContentManager.getInstance().setMinecraft(this);
Block.assetManager = assetManager;
ContentManager.getInstance().registerContent(new Vanilla());
//TODO: Modloading
ContentManager.getInstance().init();
;
} | 0 |
Entry insert(int key, int value) {
Entry node = new Entry(key, value);
node.degree = 0;
node.marked = false;
node.left = node.right = node;
node.parent = null;
node.child = null;
// Podpinamy pod korzen
// ++
access += 1;
if (minimum == null) {
// ++ ++
access += 2;
minimum = node;
} else {
// Wstawianie w liste korzenia
// ++ ++ ++ ++
access += 4;
minimum.right.left = node;
// ++ ++ ++ ++
access += 4;
node.right = minimum.right;
// ++ ++ ++
access += 3;
minimum.right = node;
// ++ ++ ++
access += 3;
node.left = minimum;
// nowe minimum
// ++ ++
access += 2;
if (node.getValue() < minimum.getValue()) {
// ++ ++
access += 2;
minimum = node;
}
}
size++;
return node;
} | 2 |
private void btn_buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_buscarActionPerformed
ocultarMensaje();
try{
// buscar por numero de factura
if((!campo_buscar1.getText().equals(""))&&(!campo_buscar1.getText().equals(""))&&(!campo_buscar1.getText().equals(""))){
int num1,num2,num3;
num1=Integer.parseInt(campo_buscar1.getText());
num2=Integer.parseInt(campo_buscar2.getText());
num3=Integer.parseInt(campo_buscar3.getText());
ResultSet rsAux1=r_con.Consultar("select ef_encabezado_factura_id from encabezado_factura where ef_tipo_comprobante="+num1+" and ef_punto_venta="+num2+" and ef_num_ptoVenta_tipoComp="+num3);
if(rsAux1.next()){
facturaActual=rsAux1.getInt(1);
rs=r_con.Consultar("select * from encabezado_factura where ef_encabezado_factura_id="+facturaActual);
if(rs.next())
cargarFactura();
}
else{
mostrarMensaje("La factura no existe");
}
}
// buscar por numero de control
if(!field_buscar3.getText().equals("")){
int numControl=Integer.parseInt(field_buscar3.getText());
ResultSet rsAux=r_con.Consultar("select ef_encabezado_factura_id from encabezado_factura where ef_numero_control="+numControl);
if(rsAux.next()){
facturaActual=rsAux.getInt(1);
rs=r_con.Consultar("select * from encabezado_factura where ef_encabezado_factura_id="+facturaActual);
if(rs.next())
cargarFactura();
}
else{
mostrarMensaje("El numero de control no existe");
}
}
borrarBuscar();
}
catch(Exception e){}
}//GEN-LAST:event_btn_buscarActionPerformed | 9 |
public static void load(File par1File) {
InputStreamReader isr = null;
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try {
isr = new InputStreamReader(new FileInputStream(par1File));
br = new BufferedReader(isr);
while(br.ready()){
sb.append(br.readLine());
sb.append('\n');
}
moneyMap = deserializeMoneyMap(sb.toString());
LunaConomyCore.log.info(String.format("Loaded %d Player(s) Data.", moneyMap.size()));
} catch (FileNotFoundException e) {
try {
par1File.createNewFile();
return;
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(br != null) br.close();
if(isr != null) isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} | 7 |
public void setAttributeValue(String value) {
if (value == null || value.length() < 7 || value.length() > 15)
throw new IllegalArgumentException("bad IP number");
StringTokenizer tok = new StringTokenizer(value, ".");
if (tok.countTokens() != 4)
throw new IllegalArgumentException("bad IP number: 4 numbers required");
byte[] data = new byte[4];
for (int i = 0; i < 4; i++) {
int num = Integer.parseInt(tok.nextToken());
if (num < 0 || num > 255)
throw new IllegalArgumentException("bad IP number: num out of bounds");
data[i] = (byte)num;
}
setAttributeData(data);
this.cachedValue = value;
this.cachedHash = data.hashCode();
} | 7 |
public void addLightSource(int x, int y, int r, int br) {
x -= xOff;
y -= yOff;
for (int yy = -r; yy < r; yy++) {
if ((yy + y) < 0 || (yy + y) >= height)
continue;
for (int xx = -r; xx < r; xx++) {
if ((xx + x) < 0 || (xx + x) >= width)
continue;
int d = (xx * xx) + (yy * yy);
if (d > r * r)
continue;
int i = (xx + x) + (yy + y) * width;
pixelLighting[i] += br - d * br / (r * r);
if (pixelLighting[i] >= 255) {
pixelLighting[i] = 255;
}
}
}
} | 8 |
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(GUI_mp3player.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI_mp3player.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI_mp3player.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI_mp3player.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
PlayerCreater creater = new PlayerCreater();
// creater.createComponents();
GUI_mp3player guiPlayer = new GUI_mp3player();
// creater.createListeners(guiPlayer);
guiPlayer.setVisible(true);
}
});
} | 6 |
public double standardizedStandardDeviationCorrelationCoefficientsWithTotals(){
if(!this.dataPreprocessed)this.preprocessData();
if(!this.covariancesCalculated)this.covariancesAndCorrelationCoefficients();
return this.standardizedStandardDeviationRhoWithTotals;
} | 2 |
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final Transaction another = (Transaction) obj;
if (getTransactor().equals(another.getTransactor())) {
if (getReceiver().equals(another.getReceiver())) {
if (getDescription().equals(another.getDescription())) {
return true;
}
}
}
return false;
} | 6 |
private void onopen() {
logger.fine("open");
this.cleanup();
this.readyState = ReadyState.OPEN;
this.emit(EVENT_OPEN);
final com.github.nkzawa.engineio.client.Socket socket = this.engine;
this.subs.add(On.on(socket, Engine.EVENT_DATA, new Listener() {
@Override
public void call(Object... objects) {
Object data = objects[0];
if (data instanceof String) {
Manager.this.ondata((String)data);
} else if (data instanceof byte[]) {
Manager.this.ondata((byte[])data);
}
}
}));
this.subs.add(On.on(this.decoder, Parser.Decoder.EVENT_DECODED, new Listener() {
@Override
public void call(Object... objects) {
Manager.this.ondecoded((Packet) objects[0]);
}
}));
this.subs.add(On.on(socket, Engine.EVENT_ERROR, new Listener() {
@Override
public void call(Object... objects) {
Manager.this.onerror((Exception)objects[0]);
}
}));
this.subs.add(On.on(socket, Engine.EVENT_CLOSE, new Listener() {
@Override
public void call(Object... objects) {
Manager.this.onclose((String)objects[0]);
}
}));
} | 2 |
private static boolean formQueryStay(Criteria crit, List params, StringBuilder sb, StringBuilder sbw, Boolean f234) {
List list = new ArrayList<>();
StringBuilder str = new StringBuilder(" ( ");
String qu = new QueryMapper() {
@Override
public String mapQuery() {
Appender.appendArr(DAO_DIRSTAY_ID_HOTEL, DB_DIRSTAY_ID_HOTEL, crit, list, str, OR);
return str.toString() + " ) ";
}
}.mapQuery();
if (list.isEmpty()) {
return false;
} else {
if (!f234) {
sb.append(LOAD_QUERY_DIRECT);
}
sb.append(LOAD_QUERY_STAY);
if (!params.isEmpty()) {
sbw.append(AND);
}
sbw.append(qu);
params.addAll(list);
return true;
}
} | 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.