text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void addToValue(double term) {
value += term;
} | 0 |
@Override
void update() {
super.update();
angle = angle + ((2 * Math.PI) / ROTATION_SPEED);
if (!remove && Player.x + Player.SIZE > x && Player.x < x + SIZE && Player.y + Player.SIZE > y && Player.y < y + SIZE) {
explosionBuffer.add(new Explosion(x, y, SIZE));
explosionBuffer.add(new Explosion(Player.x, Player.y, Player.SIZE));
Player.takeDamage(20);
remove = true;
}
} | 5 |
public void run() {
try {
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String client_input;
// Read input from client and execute on commands
while ((client_input = in.readLine()) != null) {
if (client_input.equalsIgnoreCase("JOIN")) {
if (players.contains(player_name)) {
out.println("You are already on the list!");
} else {
System.out.println("New player: "+ player_name +" ("+ socket.getLocalAddress() +") has joined the list of players.");
players.add(player_name);
out.println("Successfully joined list of players.");
}
} else if (client_input.equalsIgnoreCase("LEAVE")) {
if (players.contains(player_name)) {
System.out.println(player_name +" ("+ socket.getLocalAddress() +") has left the list of players.");
players.remove(player_name);
out.println("You've left the list of players.");
} else {
out.println("You are not on the list, please JOIN first.");
}
} else if (client_input.equalsIgnoreCase("LIST")) {
out.println(players.toString());
} else {
System.out.println(client_input);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally { //In case anything goes wrong we need to close our I/O streams and sockets.
try {
socket.close();
out.close();
in.close();
} catch(Exception e) {
System.out.println("Couldn't close I/O streams");
}
}
} | 8 |
public ParameterizedTypeImpl(Type ownerType, Type rawType, Type... typeArguments) {
// require an owner type if the raw type needs it
if (rawType instanceof Class<?>) {
Class<?> rawTypeAsClass = (Class<?>) rawType;
checkArgument(ownerType != null || rawTypeAsClass.getEnclosingClass() == null);
checkArgument(ownerType == null || rawTypeAsClass.getEnclosingClass() != null);
}
this.ownerType = ownerType == null ? null : canonicalize(ownerType);
this.rawType = canonicalize(rawType);
this.typeArguments = typeArguments.clone();
for (int t = 0; t < this.typeArguments.length; t++) {
checkNotNull(this.typeArguments[t]);
checkNotPrimitive(this.typeArguments[t]);
this.typeArguments[t] = canonicalize(this.typeArguments[t]);
}
} | 8 |
private void saveExperiment() {
int returnVal = m_FileChooser.showSaveDialog(this);
if (returnVal != JFileChooser.APPROVE_OPTION) {
return;
}
File expFile = m_FileChooser.getSelectedFile();
// add extension if necessary
if (m_FileChooser.getFileFilter() == m_ExpFilter) {
if (!expFile.getName().toLowerCase().endsWith(Experiment.FILE_EXTENSION))
expFile = new File(expFile.getParent(), expFile.getName() + Experiment.FILE_EXTENSION);
}
else if (m_FileChooser.getFileFilter() == m_KOMLFilter) {
if (!expFile.getName().toLowerCase().endsWith(KOML.FILE_EXTENSION))
expFile = new File(expFile.getParent(), expFile.getName() + KOML.FILE_EXTENSION);
}
else if (m_FileChooser.getFileFilter() == m_XMLFilter) {
if (!expFile.getName().toLowerCase().endsWith(".xml"))
expFile = new File(expFile.getParent(), expFile.getName() + ".xml");
}
try {
Experiment.write(expFile.getAbsolutePath(), m_Exp);
System.err.println("Saved experiment:\n" + m_Exp);
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Couldn't save experiment file:\n"
+ expFile
+ "\nReason:\n" + ex.getMessage(),
"Save Experiment",
JOptionPane.ERROR_MESSAGE);
}
} | 8 |
@Autowired
public void setMongoTemplate(MongoTemplate mongoTemplate) {
this.mongoImageTemplate = mongoTemplate;
db = mongoTemplate.getDb();
} | 0 |
public void writTwitterStreamToCSV(Status status) {
try {
bufferedWriter.write(status.getId()
+ "," + StringEscapeUtils.escapeCsv(status.getUser().getScreenName())
+ "," + StringEscapeUtils.escapeCsv(status.getText())
+ "," + StringEscapeUtils.escapeCsv(status.getSource())
+ "," + status.getRetweetCount()
+ "," + status.getFavoriteCount()
+ "," + status.getCreatedAt()
);
if (status.getGeoLocation() != null) {
bufferedWriter.write("," + String.valueOf(status.getGeoLocation().getLatitude()) // 緯度
+ "," + String.valueOf(status.getGeoLocation().getLongitude()));//経度
} else {
bufferedWriter.write(",,");
}
MediaEntity[] arrMedia = status.getMediaEntities();
for (MediaEntity media : arrMedia) {
bufferedWriter.write("," + media.getMediaURL());
}
// mediaのMAXは4
int blanknum = 4 - arrMedia.length;
for (int i=1 ; i <= blanknum ; i++) {
bufferedWriter.write(",");
}
bufferedWriter.write("," + String.valueOf(status.getCreatedAt().getTime() / 1000L));
bufferedWriter.newLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 4 |
public static final void UseHiredMerchant(final SeekableLittleEndianAccessor slea, final MapleClient c) {
// slea.readInt(); // TimeStamp
if (c.getPlayer().getMap().allowPersonalShop()) {
final byte state = checkExistance(c.getAccID());
switch (state) {
case 1:
c.getPlayer().dropMessage(1, "Please claim your items from Fredrick first.");
break;
case 0:
boolean merch = true;
try {
merch = c.getChannelServer().getWorldInterface().hasMerchant(c.getAccID());
} catch (RemoteException re) {
c.getChannelServer().reconnectWorld();
}
if (!merch) {
// c.getPlayer().dropMessage(1, "The Hired Merchant is temporary disabled until it's fixed.");
c.getSession().write(PlayerShopPacket.sendTitleBox());
} else {
c.getPlayer().dropMessage(1, "Please close the existing store and try again.");
}
break;
default:
c.getPlayer().dropMessage(1, "An unknown error occured.");
break;
}
} else {
c.getSession().close();
}
} | 5 |
private boolean checkALError()
{
switch( AL10.alGetError() )
{
case AL10.AL_NO_ERROR:
return false;
case AL10.AL_INVALID_NAME:
errorMessage( "Invalid name parameter." );
return true;
case AL10.AL_INVALID_ENUM:
errorMessage( "Invalid parameter." );
return true;
case AL10.AL_INVALID_VALUE:
errorMessage( "Invalid enumerated parameter value." );
return true;
case AL10.AL_INVALID_OPERATION:
errorMessage( "Illegal call." );
return true;
case AL10.AL_OUT_OF_MEMORY:
errorMessage( "Unable to allocate memory." );
return true;
default:
errorMessage( "An unrecognized error occurred." );
return true;
}
} | 6 |
private void initEntries() {
if (entriesInited) {
return;
}
if (!zipFileIndex.readFromIndex) {
int from = -Arrays.binarySearch(zipFileIndex.entries,
new Entry(dirName, ZipFileIndex.MIN_CHAR)) - 1;
int to = -Arrays.binarySearch(zipFileIndex.entries,
new Entry(dirName, MAX_CHAR)) - 1;
for (int i = from; i < to; i++) {
entries.add(zipFileIndex.entries[i]);
}
} else {
File indexFile = zipFileIndex.getIndexFile();
if (indexFile != null) {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(indexFile, "r");
raf.seek(writtenOffsetOffset);
for (int nFiles = 0; nFiles < numEntries; nFiles++) {
// Read the name bytes
int zfieNameBytesLen = raf.readInt();
byte [] zfieNameBytes = new byte[zfieNameBytesLen];
raf.read(zfieNameBytes);
String eName = new String(zfieNameBytes, "UTF-8");
// Read isDir
boolean eIsDir = raf.readByte() == (byte)0 ? false : true;
// Read offset of bytes in the real Jar/Zip file
int eOffset = raf.readInt();
// Read size of the file in the real Jar/Zip file
int eSize = raf.readInt();
// Read compressed size of the file in the real Jar/Zip file
int eCsize = raf.readInt();
// Read java time stamp of the file in the real Jar/Zip file
long eJavaTimestamp = raf.readLong();
Entry rfie = new Entry(dirName, eName);
rfie.isDir = eIsDir;
rfie.offset = eOffset;
rfie.size = eSize;
rfie.compressedSize = eCsize;
rfie.javatime = eJavaTimestamp;
entries.add(rfie);
}
} catch (Throwable t) {
// Do nothing
} finally {
try {
if (raf != null) {
raf.close();
}
} catch (Throwable t) {
// Do nothing
}
}
}
}
entriesInited = true;
} | 9 |
public String getLibelle() {
return libelle;
} | 0 |
public static boolean isJava1_3_1() {
String javaVersion = System.getProperty("java.version");
if (javaVersion.startsWith("1.3.1")) {
return true;
} else {
return false;
}
} | 1 |
private void setData(String[] data){
String option = null;
String inputValue = null;
long id;
try{
option = data[1].toLowerCase();
inputValue = data[2];
id = Long.parseLong(data[3]);
} catch(Exception e){
System.out.println("Invalid command! Try to input command once more!");
return;
}
switch(option){
case "birthday":
setBirthdayData(inputValue, id);
break;
case "address":
setAddress(inputValue, id);
break;
case "phone":
setPhone(inputValue, id);
break;
case "department":
setDepartment(inputValue, id);
break;
case "bonus":
setBonus(inputValue, id);
break;
case "coefficient":
setCoefficient(inputValue, id);
break;
default:
System.out.println("Invalid command! Try to input command once more!");
break;
}
} | 7 |
public static void main(String[] args) {
A a = new A();
Class<A> clazz = A.class;
Method[] methods = clazz.getDeclaredMethods();
for(Method method : methods) {
method.setAccessible(true);
try {
method.invoke(a);
} catch(IllegalAccessException e) {
e.printStackTrace();
} catch(IllegalArgumentException e) {
e.printStackTrace();
} catch(InvocationTargetException e) {
e.printStackTrace();
}
}
} | 4 |
public ArrayList<ArrayList<String>> parseData(ArrayList<String> rawdata){
ArrayList<ArrayList<String>> bigdata = new ArrayList<ArrayList<String>>();
for(String line : rawdata){
ArrayList<String> smalldata = new ArrayList<String>();
String[] minidata = line.split("\\|");
for(int i = 0;i < minidata.length;i++){
String split = minidata[i];
if(i == 1){ // Location
split = "(X=" + split;
int index2 = split.indexOf(",");
split = split.substring(0, index2 + 1) + "Y=" + split.substring(index2 + 1);
index2 = split.indexOf(",", index2 + 1);
split = split.substring(0, index2 + 1) + "Z=" + split.substring(index2 + 1);
split += ")";
}else if(i == 2){ // Rotation
split = "(Pitch=" + split;
int index2 = split.indexOf(",");
split = split.substring(0, index2 + 1) + "Yaw=" + split.substring(index2 + 1);
index2 = split.indexOf(",", index2 + 1);
split = split.substring(0, index2 + 1) + "Roll=" + split.substring(index2 + 1);
split += ")";
}else if(i == 3){ //DrawScale3D
split = "(X=" + split + ",Y=" + split + ",Z=" + split + ")";
}
smalldata.add(split);
}
bigdata.add(smalldata);
}
return bigdata;
} | 5 |
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(OperasiBilanganGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OperasiBilanganGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OperasiBilanganGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OperasiBilanganGui.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() {
new OperasiBilanganGui().setVisible(true);
}
});
} | 6 |
public static ArrayList<Player> selectPlayersExact(String target) throws EssentialsCommandException {
ArrayList<Player> matchedPlayers = new ArrayList<Player>();
if(target.equals("*")) {
matchedPlayers = new ArrayList<Player>(Arrays.asList(Bukkit.getServer().getOnlinePlayers()));
}
else if(target.startsWith("world:")) {
// split it into half
String[] parts = target.split(";", 2);
if(parts.length != 2) {
throw new EssentialsCommandException("Player-in-world selection format: world:<worldname>;<player[s]>");
}
// ok, get the world name
String[] worldParts = parts[0].split(":", 2);
if(worldParts.length != 2) {
throw new EssentialsCommandException("Player-in-world selection format: world:<worldname>;<player[s]>");
}
// try to get the world
World targetWorld = Bukkit.getServer().getWorld(worldParts[1]);
if(targetWorld == null) {
throw new EssentialsCommandException("I couldn't find the world '%s' to select from!", worldParts[1]);
}
// ok, world exists
// get all players that we're targeting
ArrayList<Player> players = selectPlayersExact(parts[1]);
// go through and make sure that the players are in the correct world
for(Player player: players) {
if(player.getWorld().equals(targetWorld)) {
matchedPlayers.add(player);
}
}
}
else {
String[] playerTargets = target.split(",");
// now add online players
for(int i = 0; i < playerTargets.length; i++) {
Player player = Bukkit.getServer().getPlayer(playerTargets[i]);
if(player != null) {
matchedPlayers.add(player);
}
}
}
/*if(matchedPlayers.isEmpty()) {
throw new EssentialsCommandException("I couldn't find the player[s] '%s'! For information on player selecting, type /helpess playerselecting", target);
}*/
return matchedPlayers;
} | 9 |
public double[] std(double x[][]) {
if (x.length <= 1) {
return null;
}
int n = x[0].length;
double mean[] = new double[n];
double var[] = new double[n];
for (int i = 0; i < n; i++) {
mean[i] = 0;
for (int j = 0; j < x.length; j++) {
mean[i] += x[j][i];
}
mean[i] /= n;
}
for (int i = 0; i < n; i++) {
var[i] = 0;
for (int j = 0; j < x.length; j++) {
var[i] += (mean[i] - x[j][i]) * (mean[i] - x[j][i]);
}
var[i] = Math.sqrt(var[i]) / (n - 1);
}
return var;
} | 5 |
private void loadOnlinePlayers(MainClass mainClass) {
for(Player o : Bukkit.getOnlinePlayers()) {
FileUtil.checkPlayerDat(o);
PlayerUtil pu = new PlayerUtil(o);
pu.updateName();
}
} | 1 |
@Override
public void gridletSubmit(Gridlet gridlet, boolean ack) {
if(!gridlet.hasReserved()) {
super.gridletSubmit(gridlet, ack);
}
else {
if(!handleReservationJob(gridlet)) {
try {
gridlet.setGridletStatus(Gridlet.FAILED);
} catch (Exception e) {
// should not happen
logger.log(Level.WARNING, "Error submitting gridlet", e);
}
super.sendFinishGridlet(gridlet);
}
else {
if (ack) {
// sends back an ack
super.sendAck(GridSimTags.GRIDLET_SUBMIT_ACK, true,
gridlet.getGridletID(), gridlet.getUserID());
}
}
}
} | 4 |
public String getPersonId() {
return personId;
} | 0 |
private void setTitle(String title, boolean check){
if(!check){
this.title[0] = title;
this.nTitle++;
this.titleCheck = check;
}
else{
if(!this.titleCheck){
this.title[0] = title;
this.nTitle++;
this.titleCheck = check;
}
else{
this.titleCheck = check;
this.title[this.nTitle] = title;
this.nTitle++;
}
}
} | 2 |
public long getTemp() {
return sa.temps[sa.stable][indexI][indexJ];
} | 0 |
public void setNameIsSet(boolean value) {
if (!value) {
this.name = null;
}
} | 1 |
private static DistributionType resolvedtype(int s){
switch(s){
case 1: return DistributionType.BETA;
case 2: return DistributionType.NORMAL;
case 3: return DistributionType.CAUCHY;
case 4: return DistributionType.CHISQUARED;
case 5: return DistributionType.EXPONENTIAL;
case 6: return DistributionType.F;
case 7: return DistributionType.GAMMA;
case 8: return DistributionType.LOGNORMAL;
default: return DistributionType.INVALID;
}
} | 8 |
public void consumirInsumo() throws IOException, SQLException{
boolean bandera = true;
do{
System.out.println("ingrese id del insumo a consumir:");
String insuId = bf.readLine();
Long insumoId = null;
try {
insumoId = new Long(insuId);
} catch (NumberFormatException exception) {
exception.printStackTrace();
}
Insumo nuevoObjeto = new Insumo();
nuevoObjeto.setId(insumoId);
System.out.println("cuantos desea consumir");
String insuNum = bf.readLine();
Integer insumoNum = null;
try {
insumoNum = new Integer(insuNum);
} catch (NumberFormatException exception) {
exception.printStackTrace();
}
nuevoObjeto.setCantidad(insumoNum);
List<Insumo> lista = insumoDao.select(nuevoObjeto);
if (lista.isEmpty()){
System.out.println("no se encontraron resultados");
bandera = false;
} else{
Insumo dbInsumo = lista.get(0);
Integer cantidad = dbInsumo.getCantidad();
if(insumoNum <= cantidad){
cantidad = cantidad.intValue() - nuevoObjeto.getCantidad().intValue();
dbInsumo.setCantidad(cantidad);
insumoDao.update(dbInsumo);
bandera = false;
}else{
System.out.println("es imposible realizar esta operacion, el valor ingresado es superior a la cantidad de insumos.");
}
}
}while(bandera);
} | 5 |
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
if (debug) {
log("LoginFilter:doFilter()");
}
String contextPath = filterConfig.getServletContext().getRealPath("/WEB-INF/login_attempts.log");
File loginLog = new File(contextPath);
FileWriter fw = new FileWriter(loginLog, true);
String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
String logStr = timeStamp + " " + request.getRemoteAddr() + " " + request.getParameter("username") + "\n";
fw.append(logStr);
fw.close();
Throwable problem = null;
try {
chain.doFilter(request, response);
} catch (Throwable t) {
// If an exception is thrown somewhere down the filter chain,
// we still want to execute our after processing, and then
// rethrow the problem after that.
problem = t;
t.printStackTrace();
}
// If there was a problem, we want to rethrow it if it is
// a known type, otherwise log it.
if (problem != null) {
if (problem instanceof ServletException) {
throw (ServletException) problem;
}
if (problem instanceof IOException) {
throw (IOException) problem;
}
sendProcessingError(problem, response);
}
} | 5 |
public void signFile(String person, String path, String sign) {
try {
ArrayList<User> users = DataBase.getInstance().getUsers();
for (Iterator it = users.iterator(); it.hasNext();) {
User user = (User) it.next();
if (user.getLogin().equals(person)) {
ArrayList<SignatureFile> files = user.getFiles();
for (Iterator iti = files.iterator(); iti.hasNext();) {
SignatureFile file = (SignatureFile) iti.next();
if (file.getFile().getAbsolutePath().equals(path)) {
SignatureGenerator generator = new SignatureGenerator();
generator.setSignatureListener(new GeneratorListener(file));
file.setAlgorithm(sign);
generator.execute(file, user.getKeys().getPrivateKey());
DataBase.getInstance().save();
}
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
Logger.getLogger(SignFile.class.getName()).log(Level.SEVERE, null, e);
}
} | 5 |
public Entry find(Object key) {
try{
int hash_code = key.hashCode();
int comp_code = this.compFunction(hash_code);
if (this.table[comp_code]==null){
return null;
}
else{
SList list_at_code = this.table[comp_code];
int list_size = list_at_code.length();
if (list_size == 1){
Object entry_object = list_at_code.front().item();
Entry entry = (Entry) entry_object;
if(entry.key().equals(key)){
return entry;
}
else{
return null;
}
}
else if (list_size == 0){
return null;
}
else{
ListNode current = list_at_code.front();
while(current != list_at_code.back()){
Object current_entry_object = current.item();
Entry current_entry = (Entry) current_entry_object;
if (current_entry.key().equals(key)){
return current_entry;
}
else{
current = current.next();
}
}
Object back_entry_object = current.item();
Entry back_entry = (Entry) back_entry_object;
if (back_entry.key().equals(key)){
return back_entry;
}
}
}
}
catch (InvalidNodeException | NullPointerException e){
return null;
}
return null;
} | 8 |
@Override
public double[] computeValue(final char refBase, FastaWindow window, AlignmentColumn col) {
values[ref] = 0.0;
values[alt] = 0.0;
Set<Pair> refPairs = new HashSet<Pair>();
Set<Pair> altPairs = new HashSet<Pair>();
if (col.getDepth() > 0) {
Iterator<MappedRead> it = col.getIterator();
while(it.hasNext()) {
MappedRead read = it.next();
if (read.hasBaseAtReferencePos(col.getCurrentPosition())) {
byte b = read.getBaseAtReferencePos(col.getCurrentPosition());
if (b == 'N'
|| (!read.getRecord().getProperPairFlag())
|| read.getRecord().getMateUnmappedFlag())
continue;
int mateStart = read.getRecord().getMateAlignmentStart();
int readStart = read.getRecord().getAlignmentStart();
int first = Math.min(mateStart, readStart);
int end = Math.max(mateStart, readStart);
Pair p = new Pair(first, end);
if (b == refBase) {
refPairs.add(p); // will clobber old one if it exists
}
else {
altPairs.add(p);
}
}
}
}
int grainSize = 1000;
values[ref] = Math.min(grainSize, refPairs.size());
values[alt] = Math.min(grainSize, altPairs.size());
values[ref] = values[ref] / (double)grainSize * 2.0 - 1.0;
values[alt] = values[alt] / (double)grainSize * 2.0 - 1.0;
return values;
} | 7 |
public void addDepthIndex() {
List<HierarchyArea> sorted = new ArrayList<HierarchyArea>();
Stack<HierarchyArea> start = new Stack<HierarchyArea>();
// initialize start group
for(HierarchyArea ha : hierarchy) {
if( ha.front.size() == 0 ) {
start.push(ha);
ha.depth = 0.0;
}
}
// topological sort
int loopCount = 0;
while( !start.empty() ) {
loopCount ++;
HierarchyArea area = start.pop();
sorted.add(area);
while( area.back.size() > 0 ) {
HierarchyArea next = area.back.get(0);
area.back.remove(next);
next.front.remove(area);
if( next.front.size() == 0 ) {
start.add(next);
next.depth = (double)loopCount;
}
}
}
// check the loop
for(HierarchyArea ha : hierarchy) {
if( ha.front.size() > 0 || ha.back.size() > 0 ) {
System.out.println("Loop!!");
}
}
// append depth index
for(HierarchyArea ha : sorted) {
ha.depth = 1.0 - ha.depth / (double)loopCount;
}
/*
// prepare stack
List<HierarchyArea> remain = new ArrayList<HierarchyArea>();
for(HierarchyArea ha : hierarchy) {
remain.add(ha);
}
while( remain.size() > 0 ) {
// choose most front area
for( HierarchyArea ha : remain ) {
if( ha.isDecided() ) {
remain.remove(ha);
break;
}
if( ha.getUndecidedFront() == null ) {
double frontDepth, backDepth;
frontDepth = ha.getFrontDepth();
backDepth = ha.getBackDepth();
List<HierarchyArea> save = new ArrayList<HierarchyArea>();
save.add(ha);
// DFS
HierarchyArea back = ha.getUndecidedBack();
while( back != null ) {
save.add(back);
backDepth = back.getBackDepth();
back = back.getUndecidedBack();
}
// decide depth
double interval = (frontDepth - backDepth) / (double)(save.size()+1);
for(int i=0; i<save.size(); i++) {
save.get(i).depth = frontDepth - interval * (i+1);
remain.remove(save.get(i));
}
break;
}
}
}
*/
} | 9 |
@Override
public void updateView() {
Model m = controller.getModel();
includeListModel.removeAllElements();
excludeListModel.removeAllElements();
for (File p : m.getFilesToExclude()) {
excludeListModel.addElement(p);
}
excludedList.setModel(excludeListModel);
for (File p : m.getFilesToInclude()) {
includeListModel.addElement(p);
}
includedList.setModel(includeListModel);
} | 2 |
@Override
public void dragGestureRecognized(DragGestureEvent dge) {
if (DragSource.isDragImageSupported()) {
Point offset = new Point(dge.getDragOrigin());
offset.x = -offset.x;
offset.y = -offset.y;
dge.startDrag(null, UIUtilities.getImage(this), offset, new DockableTransferable(mDockable), null);
}
} | 1 |
public Thead(HtmlMidNode parent, HtmlAttributeToken[] attrs){
super(parent, attrs);
for(HtmlAttributeToken attr:attrs){
String v = attr.getAttrValue();
switch(attr.getAttrName()){
case "align":
align = Align.parse(this, v);
break;
case "char":
charr = Char.parse(this, v);
break;
case "charoff":
charoff = Charoff.parse(this, v);
break;
case "valign":
valign = Valign.parse(this, v);
break;
}
}
} | 5 |
public boolean withinField(double x, double y){
if ( x > 15 && x < 1014 && y >= 25 && y < 518) {
return true;
}
return false;
} | 4 |
public void mouseClicked(MouseEvent e)
{
JTableHeader h = (JTableHeader) e.getSource();
TableColumnModel columnModel = h.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = columnModel.getColumn(viewColumn).getModelIndex();
if (column != -1)
{
int status = getSortingStatus(column);
if (!e.isControlDown())
{
cancelSorting();
}
// Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
// {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
status = status + (e.isShiftDown() ? -1 : 1);
status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
setSortingStatus(column, status);
}
} | 3 |
public static BufferedImage obrot(BufferedImage in,int param) {
BufferedImage out = new BufferedImage(in.getWidth(),in.getHeight(),in.getType());
int width,height;
width = out.getWidth();
height = out.getHeight();
int r,g,b;
double x,y;
double minX,maxX,minY,maxY;
minX=minY=0;
maxX=width-1;
maxY=height-1;
for (int i = 1; i < width-1; i++) {
for (int j = 1; j < height-1; j++) {
// Tu wypełnij właściwym kodem
x = Math.cos(Math.toRadians(param))*i-Math.sin(Math.toRadians(param))*j;
y = Math.sin(Math.toRadians(param))*i+Math.cos(Math.toRadians(param))*j;
if(x<minX) minX=x;
if(x>maxX) maxX=x;
if(y<minY) minY=y;
if(y>maxY) maxY=y;
}
}
System.out.println("X od "+minX+" do "+maxX);
System.out.println("Y od "+minY+" do "+maxY);
int wymiarX = (int)maxX+Math.abs((int)minX)+10; //zaokraglenia
int wymiarY = (int)maxY+Math.abs((int)minY)+10; //zaokraglenia
System.out.println("Wymiar obrazka :"+wymiarX+"x"+wymiarY);
out = new BufferedImage(wymiarX,wymiarY,in.getType());
int roznicaX = wymiarX - in.getWidth()+5;
int roznicaY = wymiarY - in.getHeight()+5;
for (int i = 1; i < width-1; i++) {
for (int j = 1; j < height-1; j++) {
// Tu wypełnij właściwym kodem
x = Math.cos(Math.toRadians(param))*i-Math.sin(Math.toRadians(param))*j;
y = Math.sin(Math.toRadians(param))*i+Math.cos(Math.toRadians(param))*j;
out.setRGB(Math.abs((int)(x)),Math.abs((int)(y)),in.getRGB(i, j));
}
}
return out;
} | 8 |
public void addText(String text) {
if(text.startsWith(";")) {
lines.add(new TextLine(text.substring(1)));
}
} | 1 |
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityDamage(EntityDamageEvent e){
if(e.getEntity() instanceof Player){
Player p = (Player) e.getEntity();
if(ArenaManager.getArenaManager().isInArena(p)){
if(e.getCause() != DamageCause.PROJECTILE && e.getCause() != DamageCause.ENTITY_ATTACK){
e.setCancelled(true);
}
}
}
} | 4 |
@Override
public void kpic_SIBEventHandler( String xml_received)
{
final String xml = xml_received;
new Thread(
new Runnable() {
public void run() {
String id = "";
SSAP_XMLTools xmlTools = new SSAP_XMLTools();
boolean isunsubscription = xmlTools.isUnSubscriptionConfirmed(xml);
if(!isunsubscription)
{
String k = xmlTools.getSSAPmsgIndicationSequence(xml);
id = xmlTools.getSubscriptionID(xml);
if(xmlTools.isRDFNotification(xml))
{
Vector<Vector<String>> triples_n = new Vector<Vector<String>>();
triples_n = xmlTools.getNewResultEventTriple(xml);
Vector<Vector<String>> triples_o = new Vector<Vector<String>>();
triples_o = xmlTools.getObsoleteResultEventTriple(xml);
String temp = "Notif. " + k + " id = " + id +"\n";
for(int i = 0; i < triples_n.size(); i++ )
{
temp+="New triple s =" + triples_n.elementAt(i).elementAt(0) + " + predicate" + triples_n.elementAt(i).elementAt(1) + "object =" + triples_n.elementAt(i).elementAt(2) +"\n";
}
for(int i = 0; i < triples_o.size(); i++ )
{
temp+="Obsolete triple s =" + triples_o.elementAt(i).elementAt(0) + " + predicate" + triples_o.elementAt(i).elementAt(1) + "object =" + triples_o.elementAt(i).elementAt(2) + "\n";
}
System.out.println(temp);
}
else
{
System.out.println("Notif. " + k + " id = " + id +"\n");
SSAP_sparql_response resp_new = xmlTools.get_SPARQL_indication_new_results(xml);
SSAP_sparql_response resp_old = xmlTools.get_SPARQL_indication_obsolete_results(xml);
if (resp_new != null)
{
System.out.println("new: \n " + resp_new.print_as_string());
}
if (resp_old != null)
{
System.out.println("obsolete: \n " + resp_old.print_as_string());
}
}
}
}
}).start();
} | 6 |
public String where(int p)
{
int ln = 1; // Line number
int ls = -1; // Line start (position of preceding newline)
int nextnl; // Position of next newline or end
while (true)
{
nextnl = text.indexOf('\n',ls+1);
if (nextnl<0) nextnl = text.length();
if (ls<p && p<=nextnl)
return ("line " + ln + " col. " + (p-ls));
ls = nextnl;
ln++;
}
} | 4 |
@Override
public boolean equals (Object other){
if(other == null)
return false;
if (!(other instanceof Set))
return false;
Set otherSet = (Set) other;
if(this.tiles.size() != otherSet.tiles.size())
return false;
for(int i=0; i<this.getNumTiles(); i++)
if(!this.tiles.get(i).equals(otherSet.tiles.get(i)))
return false;
return true;
} | 5 |
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
BigDecimal num;
while (scan.hasNext()) {
num = scan.nextBigDecimal();
num = cubeRoot(num);
String ans = num.toString();
int index = ans.indexOf(".");
ans = ans.substring(0,index+11);
char[] a =ans.toCharArray();
long sum = 0;
for (int i = 0; i < a.length; i++)
if (Character.isDigit(a[i]))
sum += (a[i] - '0');
System.out.println(sum % 10 + " " + ans);
}
} | 3 |
protected void doOnTerminate(StateEnum state, final C context) {
if (!context.isTerminated()) {
try {
if (isTrace())
log.info("terminating context %s", context);
context.setTerminated();
handlers.callOnFinalState(state, context);
} catch (Exception e) {
log.error("Execution Error in [whenTerminate] handler", e);
}
}
} | 3 |
private static String parseFilesAndCompare(ArrayList<String> logFilenames, ArrayList<String> greppedFilenames, String command, String[] hosts) {
boolean isMatch = true;
String result = "";
String tempCommand = command;
//get the grepped results from each server and compare to local grep results
for(int i=0;i<hosts.length;i++) {
ArrayList<String> localGrepResults = new ArrayList<String>();
ArrayList<String> remoteGrepResults = new ArrayList<String>();
//do a local grep on logFilenames and compare lineNumbers
command = tempCommand + logFilenames.get(i);
try {
Process p = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", command});
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = "";
// read the output from the command
//get the line number for exact comparison
while ((s = stdInput.readLine()) != null) {
localGrepResults.add(s.split("#LINE_NUMBER#")[1]);
}
stdInput.close();
//get all the line numbers for the same server (the remote page)
BufferedReader br = new BufferedReader(new FileReader(greppedFilenames.get(i)));
String line;
while ((line = br.readLine()) != null) {
remoteGrepResults.add(line.split("#LINE_NUMBER#")[1]);
}
br.close();
//sort results for comparison
Collections.sort(remoteGrepResults);
Collections.sort(localGrepResults);
//compare each element
for(int j=0;j<Math.min(remoteGrepResults.size(), localGrepResults.size());j++) {
if(!remoteGrepResults.get(j).equals(localGrepResults.get(j))) {
isMatch = false;
result = "FAIL**Test Failed Matching Elements From The Remote grep And Local grep**FAIL";
}
}
//fail if they are not the same size
if(remoteGrepResults.size()!=localGrepResults.size()) {
isMatch = false;
result = "FAIL**Results inconclusive. Number of Results Do Not Match**FAIL";
}
//break immediately
if(!isMatch)
break;
} catch (IOException e) {
System.out.println("Exception thrown getting reply from server.");
}
}
//if all files match then mission successful
if(isMatch)
result = "SUCCESS**Local and Remote Greps Match!**SUCCESS";
return result;
} | 9 |
public synchronized void actualiza(long tiempoTranscurrido){
if (cuadros.size() > 1){
tiempoDeAnimacion += tiempoTranscurrido;
if (tiempoDeAnimacion >= duracionTotal){
tiempoDeAnimacion = tiempoDeAnimacion % duracionTotal;
indiceCuadroActual = 0;
}
while (tiempoDeAnimacion > getCuadro(indiceCuadroActual).tiempoFinal){
indiceCuadroActual++;
}
}
} | 3 |
@SuppressWarnings("unchecked")
public void saveError(HttpServletRequest request, String error) {
List<String> errors = (List<String>) request.getSession().getAttribute(ERRORS_KEY);
if (errors == null) {
errors = new ArrayList<String>();
}
errors.add(error);
request.getSession().setAttribute(ERRORS_KEY, errors);
} | 1 |
private void setNextActivePlayer() {
this.players.add(players.poll());
getActivePlayer().incrementActionsWithMaxActions();
Position positionActivePlayer = grid.getElementPosition(getActivePlayer());
for (Element e : grid.getElementsOnPosition(positionActivePlayer))
if (e instanceof StartObstacle)
((StartObstacle) e).startObstacle(grid.getElementsOnPosition(positionActivePlayer), getActivePlayer());
if (getActivePlayer().getRemainingActions() <= 0)
setNextActivePlayer();
// Player boxed in (no directions to move to), set player status op lost
if (getActivePlayer().getDirectionsToMoveTo().size() == 0)
getActivePlayer().setPlayerStatus(PlayerStatus.LOST);
} | 4 |
private void run() {
isRunning = true;
int frames = 0;
long frameCounter = 0;
final double frameTime = 1.0 / FRAME_CAP;
long lastTime = Time.getTime();
double unprocessedTime = 0;
while(isRunning) {
boolean render = false;
long startTime = Time.getTime();
long passedTime = startTime - lastTime;
lastTime = startTime;
unprocessedTime += passedTime / (double)Time.SECOND;
frameCounter += passedTime;
while(unprocessedTime > frameTime) {
render = true;
unprocessedTime -= frameTime;
if(Window.isCloseRequested())
stop();
Time.setDelta(frameTime);
Input.update();
game.input();
game.update();
if(frameCounter >= Time.SECOND) {
System.out.println(frames);
frames = 0;
frameCounter = 0;
}
}
if(render) {
render();
frames++;
}
else {
try {
Thread.sleep(1);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
cleanUp();
} | 6 |
@Override
public final D apply(S source) {
long ts = 0;
D res = null;
if (!initialized) {
synchronized (this) {
if (!initialized) {
init();
}
}
}
if (log.isDebugEnabled()) {
ts = System.nanoTime();
}
try {
res = mapper.apply(source);
} catch (Exception e) {
log.warn("Failed to map the source");
log.warn(buildExceptionMessage(e));
}
if (log.isDebugEnabled()) {
long te = System.nanoTime();
log.debug(String.format("Mapped %s, took %.2f ms",
rootEntity.getSimpleName(), (double) (te - ts) / 1E6));
}
return res;
} | 5 |
private boolean checkBottom(int x, int y, int z){
int dy = y + 1;
if(dy > CHUNK_HEIGHT - 1){
return false;
}else if(chunk[x][dy][z] != 0){
return true;
}else{
return false;
}
} | 2 |
public String getGPSDateTime(){
final String[] dt = {"", ""};
final GpsDirectory gps = md.getDirectory(GpsDirectory.class);
if (gps == null) {
return null;
}
for (final Tag t:gps.getTags()) {
if (t.getTagName().equals("GPS Date Stamp")) {
dt[0] = t.getDescription();
}
if (t.getTagName().equals("GPS Time-Stamp")) {
dt[1] = t.getDescription();
}
}
if (dt[0].isEmpty()) {
return null;
}
final Matcher m = pat.matcher(dt[1]);
// TODO: fix this in metadata extractor code
if (m.find()) {
dt[1] = m.group(1) + m.group(2) + " " + m.group(3) + "0";
}
dt[0] = dt[0].replace(":", "/");
return dt[0] + " " + dt[1];
} | 6 |
@Override
public void readIn(String filename) {
System.out.println("Path : " + filename);
String sep = File.separator;
File path = new File(filename.substring(0, filename.lastIndexOf(sep)));
String prjName = filename.substring(filename.lastIndexOf('/') + 1, filename.lastIndexOf('.'));
System.out.println("Project name : " + prjName);
System.out.println("Searching for other project components ...");
int start = Integer.parseInt(filename.substring(filename.lastIndexOf('.') + 3));
System.out.println("Startindex for files to search for : " + start);
for (File f : path.listFiles()) {
for (int i = start; i < 17; i++) {
if (f.getAbsolutePath().endsWith(prjName + ".gm" + i) || f.getAbsolutePath().endsWith(prjName + ".Gm" + i) || f.getAbsolutePath().endsWith(prjName + ".gM" + i)
|| f.getAbsolutePath().endsWith(prjName + ".GM" + i)) {
System.out.println("Another Layer found : " + f.getName());
files.add(new gmFile(f.getAbsolutePath()));
}
}
}
} | 6 |
@SuppressWarnings("unchecked")
private void sundayCheckActionPerformed(java.awt.event.ActionEvent evt) {
// SWAP 1, TEAM 5
/*
* SMELL: data clumps - these actionperformed have chunks of data that is used over
* and over again.
*/
if(this.dayChecks[0].isSelected()) {
this.numSelected++;
if(this.firstSelection) {
stretch();
}
this.models[0] = new DefaultListModel<Object>();
this.sundayJobList.setModel(this.models[0]);
this.sundayScrollPane.setViewportView(this.sundayJobList);
this.sundayJobName.setColumns(20);
this.sundayLabel.setText("Job Name:");
this.sundayAddJob.setText("Add Job");
// SWAP 1, TEAM 5
/*
* SMELL: Speculative Generality - A lot of cases and hooks for things that are not
* required. The whole method is too complex.
*/
this.sundayAddJob.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
if(!Config.this.sundayJobName.getText().isEmpty()) {
Config.this.models[0].addElement(Config.this.sundayJobName.getText());
Config.this.sundayJobList.setModel(Config.this.models[0]);
Config.this.sundayJobName.setText("");
}
}
});
this.sundayDeleteJob.setText("Delete Job");
this.sundayDeleteJob.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
while(!Config.this.sundayJobList.isSelectionEmpty()) {
int n = Config.this.sundayJobList.getSelectedIndex();
Config.this.models[0].remove(n);
}
}
});
javax.swing.GroupLayout sundayTabLayout = new javax.swing.GroupLayout(this.sundayTab);
this.sundayTab.setLayout(sundayTabLayout);
sundayTabLayout.setHorizontalGroup(
sundayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sundayTabLayout.createSequentialGroup()
.addContainerGap()
.addComponent(this.sundayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(sundayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sundayTabLayout.createSequentialGroup()
.addComponent(this.sundayLabel)
.addGroup(sundayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sundayTabLayout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(this.sundayAddJob))
.addGroup(sundayTabLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(this.sundayJobName, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(this.sundayDeleteJob))
.addContainerGap(431, Short.MAX_VALUE))
);
sundayTabLayout.setVerticalGroup(
sundayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sundayTabLayout.createSequentialGroup()
.addContainerGap()
.addGroup(sundayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(sundayTabLayout.createSequentialGroup()
.addGroup(sundayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(this.sundayJobName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(this.sundayLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(this.sundayAddJob)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(this.sundayDeleteJob))
.addComponent(this.sundayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
this.dayTabs.addTab("Sunday", this.sundayTab);
} else {
this.numSelected--;
stretch();
this.dayTabs.remove(this.sundayTab);
}
} | 4 |
public static void addDependentPropositionToSpecializedIndex(BacklinksIndex index, Proposition proposition, Stella_Object argument) {
{ HashTable table = index.predicatePropositionsTable;
if (table == null) {
table = HashTable.newHashTable();
index.predicatePropositionsTable = table;
{ Proposition prop = null;
Iterator iter000 = index.dependentPropositionsList.allocateIterator();
while (iter000.nextP()) {
prop = ((Proposition)(iter000.value));
BacklinksIndex.addDependentPropositionToSpecializedIndex(index, prop, argument);
}
}
}
if (proposition.kind == Logic.KWD_ISA) {
if (index.dependentIsaPropositionsList == null) {
index.dependentIsaPropositionsList = Logic.createSequenceIndex(((Module)(Stella.$MODULE$.get())), Cons.cons(Logic.KWD_ISA, Cons.cons(((Stella.NIL == null) ? Stella.NIL : Stella.NIL), Cons.cons(argument, Stella.NIL))));
}
index.dependentIsaPropositionsList.insert(proposition);
}
else {
{ Surrogate surrogate = ((Surrogate)(proposition.operator));
SequenceIndex bucket = null;
bucket = ((SequenceIndex)(table.lookup(surrogate)));
if (bucket == null) {
bucket = Logic.createSequenceIndex(((Module)(Stella.$MODULE$.get())), Cons.cons(Logic.KWD_RELATION, Cons.cons(((Stella.NIL == null) ? Stella.NIL : Stella.NIL), Cons.cons(surrogate, Cons.cons(argument, Stella.NIL)))));
table.insertAt(surrogate, bucket);
}
bucket.insert(proposition);
}
}
}
} | 7 |
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SerializableLocation loc = (SerializableLocation) o;
if (x != loc.x)
return false;
if (y != loc.y)
return false;
if (z != loc.z)
return false;
return true;
} | 6 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto)|CMMsg.MASK_MALICIOUS,auto?"":L("^S<S-NAME> inflict(s) an unholy plague at <T-NAMESELF>.^?"));
final CMMsg msg2=CMClass.getMsg(mob,target,this,CMMsg.MASK_MALICIOUS|CMMsg.TYP_DISEASE,null);
if(mob.location().okMessage(mob,msg)||mob.location().okMessage(mob,msg2))
{
mob.location().send(mob,msg);
mob.location().send(mob,msg2);
if((msg.value()<=0)&&(msg2.value()<=0))
{
final Ability A=CMClass.getAbility("Disease_Plague");
if(A!=null)
return A.invoke(mob,target,true,asLevel);
}
}
}
else
return maliciousFizzle(mob,target,L("<S-NAME> attempt(s) to inflict a plague at <T-NAMESELF>, but flub(s) it."));
// return whether it worked
return success;
} | 9 |
public void exec() {
try {
ArrayList<String> erg = util.networkCommand("ifconfig eth0");
for (int i = 0; i < erg.size(); i++) {
if(erg.get(i).contains("inet Adresse:")){
String[] buffer = erg.get(i).split(":");
ip = buffer[1].substring(0, 14).trim();
bcast = buffer[2].substring(0, 14).trim();
mask = buffer[3].trim();
break;
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
} | 3 |
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here: SAVE
if (APPLET.currentlyLoggedIn)
{
String post = "";
for (int y = 0; y < 5; y++)
{
post+=Spell.passives.indexOf(app.passiveList[y])+",";
}
for (int y = 0; y < 5; y++)
{
for (int i = 0; i < app.spellList[app.spellBook].length; i++)
{
post+=Spell.spells.indexOf(app.spellList[y][i]);
post+=(i==app.spellList[y].length-1)&&(y==4)?"":",";
}
}
// System.out.println(post+","+app.jtb.getText());
app.CTD.postSpells(post,APPLET.jtb.getText());
}
}//GEN-LAST:event_jButton2ActionPerformed | 6 |
public static int bin(int [] arr, int s, int e, int value){
int m=(s+e)/2;
if(s>e||s<e){
return -1; //value not found
}
else{
if(value>arr[m]){
s=m+1;
return bin(arr,s,e, value);
}
else if(value<arr[m]){
e=m;
return bin(arr, s, e, value);
}
else{ //value=arr[m]
return m;
}
}
} | 4 |
static void zelfdeWeekdag
(int jaarBegin, int jaarEind, int dag, int maand, String dagVanDeWeek) {
System.out.println(dag + " " + maandToString(maand) +
" is een " + dagVanDeWeek + " in de volgende jaren:");
for(int i = jaarBegin; i <= jaarEind; i++)
if(weekdag(dag, maand, i) == dagVanDeWeek) {
if(!schrikkelJaar(i) && maand == 2 && dag == 29)
System.out.print("");
else
System.out.print(i + " ");
}
} | 5 |
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(CreateUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CreateUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CreateUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CreateUser.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() {
new CreateUser().setVisible(true);
}
});
} | 6 |
public void method360(int i, int j, int k)
{
for(int i1 = 0; i1 < anIntArray1451.length; i1++)
{
int j1 = anIntArray1451[i1] >> 16 & 0xff;
j1 += i;
if(j1 < 0)
j1 = 0;
else
if(j1 > 255)
j1 = 255;
int k1 = anIntArray1451[i1] >> 8 & 0xff;
k1 += j;
if(k1 < 0)
k1 = 0;
else
if(k1 > 255)
k1 = 255;
int l1 = anIntArray1451[i1] & 0xff;
l1 += k;
if(l1 < 0)
l1 = 0;
else
if(l1 > 255)
l1 = 255;
anIntArray1451[i1] = (j1 << 16) + (k1 << 8) + l1;
}
} | 7 |
public double pow(double x, int n) {
double result = 1;
if (n>1||n<-1){
result = pow(x*x,n/2);
if(n%2 == 1){
result *=x;
}
else if(n%2 == -1){
result /=x;
}
}
else if (n==1){
return x;
}
else if (n==-1){
return 1/x;
}
return result;
} | 6 |
public void update(Map map){
x += speedX;
y += speedY;
if(IsCollision(map)){
this.canbeShoot = true;
this.restartShooting();
}
} | 1 |
public Map<String, Class<?>> filtrateControllerClass() throws ClassNotFoundException {
Map<String, Class<?>> annotationControllerMap = new HashMap<String, Class<?>>();
//遍历筛选出controller修饰的class, 并单独存入容器
Map<Class<?>, Annotation> annotationFiltrateClassMap = AnnotationHelper.filtrateClassAnnotation(Controller.class);
for(Entry<Class<?>, Annotation> entry: annotationFiltrateClassMap.entrySet()) {
Class<?> tempClass = entry.getKey();
Controller controller = (Controller)entry.getValue();
String controllerName = getDefaultControllerName(controller.value(), tempClass.getSimpleName());
//已包含相同的Controller名
if(annotationControllerMap.containsKey(controllerName)) {
throw new RuntimeException("controller " + controllerName + " has already exists, please check it again!");
}
annotationControllerMap.put(controllerName, tempClass);
}
return annotationControllerMap;
} | 8 |
@Override
public void onCommand(Network src, Command com) throws IOException {
switch (com.getType()) {
case MESSAGE:
Message msg = (Message) com;
if (msg.source.isEmpty()) {
System.out.println(" " + msg.message);
window.pushToWindow(msg.message);
} else {
System.out.println(msg.source + ": " + msg.message);
window.pushToWindow(msg.source + ": " + msg.message);
}
break;
case PRIVATEMESSAGE:
PrivateMessage pm = (PrivateMessage) com;
System.out.printf(" Private message from %s:%n %s%n", pm.src, pm.msg);
if (!pm.tar.equals(name)) {
System.out.println(" Contact an admin. This pm was meant for " + pm.tar + ".");
}
break;
case NETWORKSHUTDOWN:
System.out.println(" Network connection lost.");
System.exit(0);
break;
default:
break;
}
} | 5 |
public void allBids(){
auctions.removeAll(auctions);
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
}
PreparedStatement ps = null;
Connection con = null;
ResultSet rs;
try {
con = DriverManager.getConnection("jdbc:mysql://mysql2.cs.stonybrook.edu:3306/mlavina", "mlavina", "108262940");
if (con != null) {
con.setAutoCommit(false);
try {
String sql = "SELECT * FROM Auctions WHERE AccountNo = ? AND AirlineID = ? AND FlightNo = ? AND Class = ? ORDER BY `Date` DESC";
ps = con.prepareStatement(sql);
ps.setInt(1, accountNo);
ps.setString(2, selectedAuction.airlineId);
ps.setInt(3, selectedAuction.flightNo);
ps.setString(4, selectedAuction.seatClass);
ps.execute();
rs = ps.getResultSet();
while (rs.next()) {
auctions.add(new Auction(rs.getString("AirlineID"), rs.getInt("FlightNo"), rs.getString("Class"), rs.getTimestamp("Date"), rs.getDouble("NYOP"), rs.getInt("Accepted")));
}
con.commit();
} catch (Exception e) {
con.rollback();
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
con.setAutoCommit(true);
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} | 6 |
public void setDescription(String description) {
this.description = description;
} | 0 |
@Override
public W<DeltaPT> delta(DC obj)
{ if(obj instanceof PT)
{ PT that=(PT)obj;
if(this.t.equals(that.t))
{ return new W(new Equality(true), new Similarity(0.0),new DeltaPT.Id(this));
}
else
{ return new W(new Equality(false), new Similarity(1.0),new DeltaPT(this,that));
}
}
else
{ throw new RuntimeException(obj+" is NOT type of PT.");
}
} | 2 |
@POST
@Timed
@Path("login")
@Consumes("application/x-www-form-urlencoded")
@Produces({"application/json"})
public Response login(@CookieParam("authUser") String existingUserCookie, @FormParam("destination") String destination, @FormParam("username") String username, @FormParam("password") String password) {
try {
if (!Strings.isNullOrEmpty(username) && !Strings.isNullOrEmpty(password)) {
UserAccount user = dataStore.getUser(username);
if (user != null && user.hashedPassword != null && user.hashedPassword.equalsIgnoreCase(UserAccount.hashPassword(password, salt))) {
try {
//Create a new token for this session
String token = UUID.randomUUID().toString();
//Save a new UserToken for this session
UserToken userToken = new UserToken();
userToken.token = token;
userToken.userAccount = user;
userToken.created = System.currentTimeMillis();
userToken = dataStore.newUserToken(userToken);
return Response.seeOther(((!Strings.isNullOrEmpty(destination))?new URI(destination):LANDING_HTML)).cacheControl(NO_CACHE_CONTROL).cookie(newUserCookie(userToken.token)).build();
} catch(Exception e) {
e.printStackTrace();
//fall through to fail code
}
}
}
//If login fails, log them out just in case were already logged in previously
logoutUserToken(existingUserCookie);
return Response.seeOther(new URI(serviceBaseURL + "login.html?" + "destination=" + ((!Strings.isNullOrEmpty(destination))?URLEncoder.encode(destination, "UTF-8"):"") +
"&message="+URLEncoder.encode("Login unsuccessful", "UTF-8") )).cacheControl(NO_CACHE_CONTROL).cookie(newEmptyExpiredCookie()).build();
} catch (Exception e) {
L.error("Unable to login user: " + username, e);
}
throw new WebApplicationException(Response.serverError().cacheControl(NO_CACHE_CONTROL).cookie(newEmptyExpiredCookie()).build());
} | 9 |
@Override
public List<Funcionario> listByNome(String nome) {
Connection con = null;
PreparedStatement pstm = null;
ResultSet rs = null;
List<Funcionario> funcionarios = new ArrayList<>();
try {
con = ConnectionFactory.getConnection();
pstm = con.prepareStatement(LISTBYNOME);
pstm.setString(1, "%" + nome + "%");
rs = pstm.executeQuery();
while (rs.next()) {
//(nome, login, senha, telefone, celular, endereco, cidade, estado)
Funcionario f = new Funcionario();
f.setCodigo(rs.getInt("codigo"));
f.setNome(rs.getString("nome"));
f.setLogin(rs.getString("login"));
f.setSenha(rs.getString("senha"));
f.setTelefone(rs.getString("telefone"));
f.setCelular(rs.getString("celular"));
f.setCargo(rs.getString("cargo"));
f.setDataNascimento(rs.getDate("data_nascimento"));
f.setRg(rs.getString("rg"));
f.setEndereco(rs.getString("endereco"));
f.setCidade(rs.getString("cidade"));
f.setEstado(rs.getString("estado"));
funcionarios.add(f);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro ao pesquisar funcionarios: " + e.getMessage());
} finally {
try {
ConnectionFactory.closeConnection(con, pstm, rs);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro ao fechar conexão de pesquisar funcionarios: " + e.getMessage());
}
}
return funcionarios;
} | 3 |
public String getName(int i) {
return (String) this.names.get(i);
} | 0 |
public DocumentDTO findById(int id) throws RemindMeException {
DocumentDTO documentDTO = null;
try {
DocumentEntity documentEntity = documentDao.findById(id);
documentDTO = dtoCreatorUtil.createDocumentDto(documentEntity);
} catch (IndexOutOfBoundsException exp) {
throw new RemindMeException("No Data Found", exp);
}
return documentDTO;
} | 1 |
public static Dificultad getDificultadById(int d) {
if(d == FACIL.VALUE)return FACIL;
if(d == PRO.VALUE)return PRO;
return MEDIO;
} | 2 |
public static Collection<Class<? extends Critter>> getAvailableCritterTypes() {
if (availableCritterTypes == null) {
availableCritterTypes = new ArrayList<Class<? extends Critter>>(0);
String typePackageStr = System.getProperty("critters.typePackageName");
String typeStr = System.getProperty("critters.availableCritterTypes");
String[] types = DEFAULT_TYPES;
String typePackage = DEFAULT_TYPE_PACKAGE;
if (typeStr != null) {
types = typeStr.split(",");
}
if (typeStr != null) {
typePackage = typePackageStr;
}
for (String clazz : types) {
String className = typePackage + "." + clazz;
try {
@SuppressWarnings("unchecked")
Class<? extends Critter> c = (Class<? extends Critter>) Class.forName(className);
availableCritterTypes.add(c);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return availableCritterTypes;
} | 9 |
public static void main(String [] args) throws java.net.UnknownHostException, java.io.IOException {
System.out.println("java.library.path="+System.getProperty("java.library.path"));
JtunDevice tunDev = JtunDevice.getTunDeviceInstance();
byte [] buf = new byte[1600];
byte [] _no_eth_frame;
if(tunDev.open()) {
System.out.println("The TAP device was opened successfully");
System.out.println("TAP device name : " + tunDev.getDevName());
System.out.println("TAP device status : " + tunDev.isInitialized());
}
tunDev.setMTU(1350);
java.net.InetAddress address = Inet4Address.getByName("10.0.0.4");
if (!tunDev.addAddress(address, 8)) {
System.out.println("Failed to set up the address " + address.toString());
}
tunDev.setUseSelectTimeout(true);
tunDev.setReceiveTimeout(10);
System.out.println("TUN MAC address : " + Converter.__toHexString(tunDev.getMACAddress(), ":"));
//tunDev.setSendTimeout(10);
long start = System.currentTimeMillis();
long now = System.currentTimeMillis();
int err = 0;
IPPacket __icmp;
ARPPacket __arp = new ARPPacket(1);
ARPPacket __arpResponse;
byte [] __snd_mca = new byte[6];
byte [] __full_frame;
byte [] __src = new byte[4];
byte [] __dst = new byte[4];
while (now - start < 60000000) {
now = System.currentTimeMillis();
try {
if ((err = tunDev.read(buf)) > 0) {
buf = Converter.__toUnsignedByteArray(buf);
_no_eth_frame = new byte[err - 14]; //Remove the Ethernet frame and CRC field
System.arraycopy(buf, 14, _no_eth_frame, 0, err - 14);
if (__isARPRequest(buf)) {
System.out.println("Packet is ARP_REQUEST");
__full_frame = new byte[_no_eth_frame.length + 14];
__arp.setData(_no_eth_frame);
__arp.getSenderHdwAddr(__snd_mca);
__arp.setDestHdwAddr(__snd_mca);
__arp.setOpCode(2);
__arp.getDestProtoAddr(__src);
__arp.getSourceProtoAddr(__dst);
__arp.setDestProtoAddr(__dst);
__arp.setSourceProtoAddr(__src);
__setEthHeader(__full_frame, _no_eth_frame, __snd_mca, __snd_mca, (short)0x0806);
try {
System.out.println(tunDev.write(__full_frame) + " bytes were sent");
}catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println(Converter.__toHexString(__full_frame, " "));
} else if (__isIPPacket(buf)) {
__icmp = new IPPacket(1);
__icmp.setData(_no_eth_frame);
System.out.println("IP version : " + __icmp.getIPVersion());
}
}
} catch (java.io.InterruptedIOException ex) {
//System.out.println(ex.getMessage());
}
}
tunDev.close();
System.out.println("The TAP device was closed successfully");
System.out.println("TAP device status : " + tunDev.isInitialized());
} | 8 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Term other = (Term) obj;
if (field == null) {
if (other.field != null)
return false;
} else if (!field.equals(other.field))
return false;
if (bytes == null) {
if (other.bytes != null)
return false;
} else if (!bytes.equals(other.bytes))
return false;
return true;
} | 9 |
private StateTree generate(
TicTacToeBoard state,
Position move) throws Exception
{
LinkedList<StateTree> successors = new LinkedList<StateTree>();
if (!state.isGameOver()) {
for (int row = 0; row < TicTacToeBoard.SIZE; row++) {
for (int col = 0; col < TicTacToeBoard.SIZE; col++) {
int player = state.getPlayerIndexOfSquare(row, col);
if (player == TicTacToeBoard.PLAYER_NONE) {
TicTacToeBoard next = (TicTacToeBoard)state.clone();
next.setState(row, col, state.getTurn());
if (state.getTurn() == TicTacToeBoard.PLAYER_O) {
next.setTurn(TicTacToeBoard.PLAYER_X);
} else if (state.getTurn() == TicTacToeBoard.PLAYER_X) {
next.setTurn(TicTacToeBoard.PLAYER_O);
} else {
throw new Exception("Invalid player turn");
}
Position position = new Position(row, col);
successors.add(this.generate(next, position));
}
}
}
}
return new StateTree(move, state, successors);
} | 6 |
private void blackPixel(Pixel pixel, BufferedImage image){
if(image.getRGB(pixel.x + 1, pixel.y) == Color.WHITE.getRGB() && edgePixels.contains(new Pixel(pixel.x + 1, pixel.y))){
pixel.label = "" + counter;
} else if(image.getRGB(pixel.x - 1, pixel.y) == Color.WHITE.getRGB() && edgePixels.contains(new Pixel(pixel.x - 1, pixel.y))){
pixel.label = "" + counter;
} else if(image.getRGB(pixel.x, pixel.y + 1) == Color.WHITE.getRGB() && edgePixels.contains(new Pixel(pixel.x, pixel.y + 2))){
pixel.label = "" + counter;
} else if(image.getRGB(pixel.x, pixel.y - 1) == Color.WHITE.getRGB() && edgePixels.contains(new Pixel(pixel.x, pixel.y - 1))){
pixel.label = "" + counter;
} else counter++;
} | 8 |
private static boolean insertDrug(Drug bean, PreparedStatement stmt) throws SQLException{
stmt.setString(1, bean.getDrugName());
stmt.setString(2, bean.getDescription());
stmt.setInt(3, bean.getQuantity());
stmt.setBoolean(4, bean.isControlFlag());
stmt.setString(5, bean.getSideEffect());
stmt.setBigDecimal(6, bean.getPrice());
int affected = stmt.executeUpdate();
if(affected == 1){
System.out.println("new drug added successfully");
}else{
System.out.println("error adding drug");
return false;
}
return true;
} | 1 |
private void programmerRunButton(java.awt.event.ActionEvent evt)
{
hidePanels(manualPanel);
// Resetting step log
world.resetStepThrough();
// Resetting speed
currSpeed = 5;
world.setSpeed(currSpeed);
speedCounter.setText("Speed: " + currSpeed);
// Resetting the pause button
Pause.setText("Pause");
try {
Image img = ImageIO.read(getClass().getResource("/karel/guipics/pause.png"));
Pause.setIcon(new ImageIcon(img));
} catch (IOException ex) {}
programmerThread.stop();
final List<String> userInput = Arrays.asList(programmerText.getText().split("\n"));
Runnable r1 = new Runnable()
{
public void run()
{
world.doScript(0, 0, userInput); // Running
}
};
programmerThread = new Thread(r1);
programmerThread.start();
} | 1 |
private Display createDisplay(Class cl) {
try {
String className = cl.getName();
Class dcl = Class.forName(className + "Display");
if (Display.class.isAssignableFrom(dcl)) {
Display display = (Display) dcl.newInstance();
map.put(cl, display);
return display;
}
} catch (Exception e) {
// oh well...
}
try {
ImageDisplay display;
if (PathedImage.class.isAssignableFrom(cl)) {
display = new MyImageDisplay(cl);
} else {
display = new ImageDisplay(cl);
}
map.put(cl, display);
return display;
} catch (Exception e) {
// oh well...
}
return null;
} | 4 |
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
if (!this.isEmptyTable(this.table_trans)) {
if (this.getDataTable(this.table_trans)) {
frmSetupTrans obj = new frmSetupTrans(s, dataTable);
obj.setVisible(true);
jDes.add(obj);
}
} else {
this.msg("Tabla incompleta");
}
}//GEN-LAST:event_jButton2ActionPerformed | 2 |
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(VtnOpcionesXbox.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VtnOpcionesXbox.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VtnOpcionesXbox.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VtnOpcionesXbox.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() {
new VtnOpcionesXbox().setVisible(true);
}
});
} | 6 |
public static void save(String filename, double[] input) {
// assumes 44,100 samples per second
// use 16-bit audio, mono, signed PCM, little Endian
AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, 1, true, false);
byte[] data = new byte[2 * input.length];
for (int i = 0; i < input.length; i++) {
int temp = (short) (input[i] * MAX_16_BIT);
data[2*i + 0] = (byte) temp;
data[2*i + 1] = (byte) (temp >> 8);
}
// now save the file
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
AudioInputStream ais = new AudioInputStream(bais, format, input.length);
if (filename.endsWith(".wav") || filename.endsWith(".WAV")) {
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(filename));
}
else if (filename.endsWith(".au") || filename.endsWith(".AU")) {
AudioSystem.write(ais, AudioFileFormat.Type.AU, new File(filename));
}
else {
throw new RuntimeException("File format not supported: " + filename);
}
}
catch (Exception e) {
System.out.println(e);
System.exit(1);
}
} | 6 |
private static BufferedImage readOrWriteNextImage(PixImage image)
throws IOException, ClassNotFoundException {
if (WRITE_MODE) {
os.writeInt(image.getWidth());
os.writeInt(image.getHeight());
os.writeObject(stringOfPixImage(image));
return ImageUtils.pixImage2buffer(image);
} else {
return imageOfString(is.readInt(), is.readInt(),
(String) is.readObject());
}
} | 1 |
public boolean alone( int x, int y )
{
return (
(!exists( x - 1, y ) || board[y][x - 1] == EMPTY) &&
(!exists( x + 1, y ) || board[y][x + 1] == EMPTY) &&
(!exists( x, y - 1 ) || board[y - 1][x] == EMPTY) &&
(!exists( x, y + 1 ) || board[y + 1][x] == EMPTY)
);
} | 7 |
protected @Override Token getNewToken() throws ScannerException {
try {
final String s = in.readLine();
if (s == null) {
logger.error("Unexpected end of input");
throw new ScannerException("Unexpected end of input", this);
}
if ("(".equals(s))
return BEGIN_EXP;
if (")".equals(s))
return END_EXP;
if (!Token.VALID_ATOM.matcher(s).matches()) {
logger.error("Invalid token: " + s);
throw new ScannerException("Invalid token", this);
}
return new TokenImpl(s, Token.Class.ATOM);
} catch (IOException e) {
logger.error("I/O error while reading input");
throw new ScannerException("I/O error while reading input", this, e);
}
} | 5 |
private double getRingSize(int currIndex, int branchSize, double fullSize)
{
if (currIndex < 1 || currIndex > branchSize || branchSize < 1 || fullSize < 0)
{
throw new IllegalArgumentException();
}
int middleIndex = 0;
boolean isBranchSizeEven = ((branchSize) % 2 == 0);
middleIndex = (int) Math.ceil(branchSize / 2f);
if (currIndex == middleIndex || (isBranchSizeEven && currIndex == middleIndex + 1))
{
//full size
return fullSize;
}
else if (currIndex >= middleIndex)
{
//after middle
currIndex = branchSize - currIndex + 1;
}
return (((float) Math.pow(currIndex, 0.75) / (float) Math.pow(middleIndex, 0.75)) * fullSize);
}; | 8 |
public UserProfile fetchUserProfile(GoogleDocs googleDocs)
{
MetadataEntry entry = null;
try
{
entry = this.getUserMetadata(googleDocs);
}
catch (ServiceException error)
{
throw new ApiException(error.getMessage(), error);
}
if (entry != null){
return new UserProfileBuilder().setName(entry.getAuthors().get(0).getName())
.setEmail(entry.getAuthors().get(0).getEmail())
.setUsername(entry.getAuthors().get(0).getName()).build();
} else {
return null;
}
} | 2 |
void parseContentspec(String name) throws java.lang.Exception
{
if (tryRead("EMPTY")) {
setElement(name, CONTENT_EMPTY, null, null);
return;
} else if (tryRead("ANY")) {
setElement(name, CONTENT_ANY, null, null);
return;
} else {
require('(');
dataBufferAppend('(');
skipWhitespace();
if (tryRead("#PCDATA")) {
dataBufferAppend("#PCDATA");
parseMixed();
setElement(name, CONTENT_MIXED, dataBufferToString(), null);
} else {
parseElements();
setElement(name, CONTENT_ELEMENTS, dataBufferToString(), null);
}
}
} | 3 |
public boolean replaceSubBlock(StructuredBlock oldBlock,
StructuredBlock newBlock) {
for (int i = 0; i < subBlocks.length; i++) {
if (subBlocks[i] == oldBlock) {
subBlocks[i] = newBlock;
return true;
}
}
return false;
} | 2 |
public static void main(String[] args) throws IOException {
BufferedReader in;
StringBuilder out = new StringBuilder();
File f = new File("entrada");
if (f.exists()) {
in = new BufferedReader(new FileReader(f));
} else
in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
for (int i = 0; i < n; i++) {
int s = Integer.parseInt(in.readLine());
int arr[] = readInts(in.readLine());
int max = -100000;
int max2 = -100000;
int acum = max;
int acum2 = max;
for (int j = 0; j < arr.length; j++) {
if (arr[j] > 0) {
if (acum < 0)
acum = 0;
acum += arr[j];
max = Math.max(max, acum);
} else {
max = Math.max(max, arr[j]);
}
if (arr[j] < 0 && acum2 + arr[j] < 0) {
max2 = Math.max(max2, arr[j]);
acum2 = 0;
} else {
if (acum2 < 0)
acum2 = 0;
acum2 += arr[j];
max2 = Math.max(max2, acum2);
}
}
out.append(max2 + " " + max + "\n");
}
System.out.print(out);
} | 8 |
public boolean hasPit(int x, int y)
{
for (Point p:pits)
{
if (p.x == x && p.y == y)
{
return true;
}
}
return false;
} | 3 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Person))
return false;
Person other = (Person) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} | 6 |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Usuario other = (Usuario) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (username == null) {
if (other.username != null) {
return false;
}
} else if (!username.equals(other.username)) {
return false;
}
return true;
} | 9 |
public static final void register(String prefix, HashMap<String, String> map, Path appFile, Path iconDir) {
String appPath = appFile.normalize().toAbsolutePath().toString();
WindowsRegistry reg = new WindowsRegistry(true);
for (String extension : map.keySet()) {
// Make the entry that points to the app's information for the extension
String key = SOFTWARE_CLASSES + "." + extension;
reg.deleteKey(key);
reg.createKey(key);
String appKey = prefix + "_" + extension.toUpperCase();
reg.writeStringValue(key, "", appKey);
// Make the entry for the extension
String baseKey = SOFTWARE_CLASSES + appKey;
reg.deleteKey(baseKey);
reg.createKey(baseKey);
reg.writeStringValue(baseKey, "", map.get(extension));
key = baseKey + "\\DefaultIcon";
reg.deleteKey(key);
reg.createKey(key);
reg.writeStringValue(key, "", "\"" + iconDir.resolve(extension + ".ico").normalize().toAbsolutePath().toString() + "\"");
key = baseKey + "\\shell";
reg.deleteKey(key);
reg.createKey(key);
reg.writeStringValue(key, "", "open");
key += "\\open";
reg.deleteKey(key);
reg.createKey(key);
reg.writeStringValue(key, "", "&Open");
key += "\\command";
reg.deleteKey(key);
reg.createKey(key);
reg.writeStringValue(key, "", "\"" + appPath + "\" \"%1\"");
}
} | 1 |
public ArrayList<String> getTrackList(){
JsonParser jp = null;
boolean leadingKEY = false;
String ldKEY = null;
ArrayList<String> trackID = new ArrayList<String>();
try {
jp = Json.createParser(new FileReader(DaemonMainController.getDatabasePath()));
while(jp.hasNext()){
JsonParser.Event event = jp.next();
switch(event){
case START_OBJECT:
while(event.toString() != "END_OBJECT"){
event = jp.next();
switch(event){
case KEY_NAME:
if(!leadingKEY){
trackID.add(jp.getString()) ;
leadingKEY = true;
}
break;
case START_OBJECT:
break;
}
}
break;
case KEY_NAME:
trackID.add(jp.getString()) ;
break;
case END_OBJECT:
break;
default:
break;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jp.close();
return trackID;
} | 9 |
@EventHandler
public void onMove(PlayerMoveEvent event) {
if (this.target.get(event.getPlayer()) != null) event.getPlayer().setCompassTarget(((Player) this.target.get(event.getPlayer())).getLocation());
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
Player ct = (Player) this.target.get(p);
if (ct == event.getPlayer())
if (p.getWorld() == event.getPlayer().getWorld()) {
if (p.getLocation().distance(event.getPlayer().getLocation()) <= this.distance) {
Bukkit.getServer().getPluginManager().callEvent(new TargetLoseEvent(p, target.get(p)));
this.target.remove(p);
p.setCompassTarget(p.getWorld().getSpawnLocation());
}
p.setCompassTarget(event.getPlayer().getLocation());
}
else {
p.sendMessage(prefix + convertConfig(noplayer, p, null, 0));
Bukkit.getServer().getPluginManager().callEvent(new TargetLoseEvent(p, target.get(p)));
this.target.remove(p);
}
}
} | 5 |
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.