method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
52e90380-b34c-44dc-a6a3-acaa13a6dc8b | 4 | private Compiler(URLClassLoader parent) {
// If not running on JDK, compiler will be null
if (compiler == null) {
throw new Error("Compiler not available. This may happen if "
+ "running on JRE instead of JDK. Please use a full JDK 1.6."
+ "javax.tools.ToolProvider.getSystemJavaCompiler() returned null.");
}
log.debug("Instantiating new compiler " + parent);
fileManager = new MemoryOutputJavaFileManager(compiler.getStandardFileManager(null, null, null));
loader = new JavaFileManagerClassLoader(fileManager, parent);
// create a classpath for the compiler
StringBuilder b = new StringBuilder();
URL[] cp = parent.getURLs();
for (int i = 0; i < cp.length; i++) {
b.append(File.pathSeparatorChar);
b.append(cp[i].getFile());
}
/*
* This is necessary to add all jars of an app when running inside a
* container
*/
try {
URL[] cl = ((URLClassLoader) Thread.currentThread().getContextClassLoader()).getURLs();
for (URL url : cl) {
b.append(File.pathSeparatorChar).append(url.getFile());
}
} catch (ClassCastException e) {
log.error("Context class loader is not a URLClassLoader");
}
// set compiler's classpath to be same as the runtime's
compilerOptions.addAll(Arrays.asList("-cp", System.getProperty("java.class.path") + b.toString()));
} |
532872ea-dc08-4899-9e30-c7f0a34b0d42 | 8 | private void createWalls()
{
for (int i = 140; i <= 200; i += Object.size) {
for (int j = 100; j <= 160; j += Object.size) {
gameObjects.put(createCoordinateKey(new Coordination(j, i)), new Brick(j, i));
}
}
for (int i = 140; i <= 200; i += Object.size) {
for (int j = 320; j <= 380; j += Object.size) {
gameObjects.put(createCoordinateKey(new Coordination(j, i)), new Brick(j, i));
}
}
for (int i = 360; i <= 420; i += Object.size) {
for (int j = 100; j <= 160; j += Object.size) {
gameObjects.put(createCoordinateKey(new Coordination(j, i)), new Brick(j, i));
}
}
for (int i = 360; i <= 420; i += Object.size) {
for (int j = 320; j <= 380; j += Object.size) {
gameObjects.put(createCoordinateKey(new Coordination(j, i)), new Brick(j, i));
}
}
//gameObjects.put(createCoordinateKey(new Coordination(100, 520)), new Brick(100, 520));
} |
b5aadea2-4aac-4f8c-b5b5-1ff6f4ad27ca | 5 | private static boolean checkTile(Level level, int x, int y) {
// get the tile at the location
Tile t = level.getTile(x >> 3, y >> 3);
// trees can't grow on solids or water
if (t instanceof BasicSolidTile || t instanceof AnimatedTile) {
return false;
}
// don't place a tree in a building
for (Entity e : level.getEntities()) {
if (e instanceof SolidEntity) {
if (e.getBounds().intersects(new Rectangle(x, y, HORIZONTAL_SPACING, treeHeight))) {
return false;
}
}
}
return true;
} |
1c9615d5-d7a7-4790-a388-c87cb9fbcdd2 | 7 | static void dradf2(int ido,int l1,float[] cc, float[] ch, float[] wa1, int index){
int i,k;
float ti2,tr2;
int t0,t1,t2,t3,t4,t5,t6;
t1=0;
t0=(t2=l1*ido);
t3=ido<<1;
for(k=0;k<l1;k++){
ch[t1<<1]=cc[t1]+cc[t2];
ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
t1+=ido;
t2+=ido;
}
if(ido<2)return;
if(ido!=2){
t1=0;
t2=t0;
for(k=0;k<l1;k++){
t3=t2;
t4=(t1<<1)+(ido<<1);
t5=t1;
t6=t1+t1;
for(i=2;i<ido;i+=2){
t3+=2;
t4-=2;
t5+=2;
t6+=2;
tr2=wa1[index+i-2]*cc[t3-1]+wa1[index+i-1]*cc[t3];
ti2=wa1[index+i-2]*cc[t3]-wa1[index+i-1]*cc[t3-1];
ch[t6]=cc[t5]+ti2;
ch[t4]=ti2-cc[t5];
ch[t6-1]=cc[t5-1]+tr2;
ch[t4-1]=cc[t5-1]-tr2;
}
t1+=ido;
t2+=ido;
}
if(ido%2==1)return;
}
t3=(t2=(t1=ido)-1);
t2+=t0;
for(k=0;k<l1;k++){
ch[t1]=-cc[t2];
ch[t1-1]=cc[t3];
t1+=ido<<1;
t2+=ido;
t3+=ido;
}
} |
a1752bb9-4fdb-42b1-8853-716a40dfe9cd | 2 | @Override
public void Consultar() throws SQLException
{
try
{
Conexion.GetInstancia().Conectar();
ResultSet rs = Conexion.GetInstancia().EjecutarConsulta("");
while(rs.next())
{
// ObProducto.setProductoBodega(null);
// ObProducto.setId_Producto(0);
// ObProducto.setId_Bodega(rs.getString(""));
// ObProducto.setId_Proveedor(rs.getString(""));
// ObProducto.setId_Descuento(rs.getString(""));
ObProducto.setNom_Producto(rs.getString(""));
ObProducto.setDes_Producto(rs.getString(""));
ObProducto.setEst_Producto(rs.getString(""));
ObProducto.setStock_Producto(rs.getString(""));
ObProducto.setPVP_Producto(rs.getDouble(""));
ObProducto.setMar_Producto(rs.getString(""));
ObProducto.setTam_Producto(rs.getString(""));
}
}
catch(SQLException ex)
{
throw ex;
}
finally
{
Conexion.GetInstancia().Desconectar();
}
} |
1f4fa1e7-4216-4c68-a7eb-1034ee0a39a0 | 0 | public Boolean contains(DrawableItem di, Point p) {
return di.getShape().contains(p);
} |
d1c4618c-4573-4e27-bddc-f3f6da2fe9b3 | 6 | private static boolean b4(int i, int j, BufferedImage image) {
Boolean right = ((image.getRGB(i+1, j-1) == BLACK) ||
(image.getRGB(i+1, j ) == BLACK) ||
(image.getRGB(i+1, j+1) == BLACK));
Boolean with = ((image.getRGB(i-1, j-1) == WHITE) &&
(image.getRGB(i-1, j ) == BLACK) &&
(image.getRGB(i , j ) == BLACK) &&
(image.getRGB(i , j+1) == WHITE));
return ( right && with );
} |
66f71438-0dc4-4194-b3c7-73a1b4721a06 | 9 | private void thermallyDeexciteAtoms() {
if (thermalDeexcitor == null)
thermalDeexcitor = new ThermalDeexcitor(this);
double sig;
for (int i = 0; i < numberOfAtoms - 1; i++) {
rxi = atom[i].rx;
ryi = atom[i].ry;
for (int j = i + 1; j < numberOfAtoms; j++) {
if (atom[i].isExcitable() || atom[j].isExcitable()) {
rxij = rxi - atom[j].rx;
ryij = ryi - atom[j].ry;
rijsq = rxij * rxij + ryij * ryij;
// 0.55 < 0.5*2^(1/6)~0.56 --- allow a bit penetration
sig = 0.55 * (atom[i].sigma + atom[j].sigma);
sig *= sig;
if (rijsq < sig) {
Photon p = thermalDeexcitor.deexcite(atom[i], atom[j]);
if (p != null) {
p.setModel(this);
p.setAngle((float) (Math.random() * 2 * Math.PI));
Electron e = thermalDeexcitor.getElectron();
if (e != null) {
Atom a = e.getAtom();
if (a != null) {
double x = a.sigma * 0.51 * Math.cos(p.getAngle());
double y = a.sigma * 0.51 * Math.sin(p.getAngle());
p.setX(p.getX() + (float) x);
p.setY(p.getY() + (float) y);
}
}
addPhoton(p);
// notifyModelListeners(new ModelEvent(this, "Photon emitted", null, p));
// postone to be handled by RectangularBoundary when the photon exits
}
}
}
}
}
} |
a1a98413-96bf-4961-8067-6fd73ad14deb | 7 | private Posicion probarPorFila(int filaTerreno, int[][] terreno,
int[][] casa, Orientacion orientacion) {
// asumo que entra
boolean entra = true;
// variables auxiliares
int anchoTerreno = terreno[0].length;
int altoCasa = casa.length;
int anchoCasa = casa[0].length;
for (int columnaTerreno = 0; columnaTerreno <= anchoTerreno - anchoCasa; columnaTerreno++) {
// cada posicion de la casa
for (int filaCasa = 0; filaCasa < altoCasa; filaCasa++) {
for (int columnaCasa = 0; columnaCasa < anchoCasa; columnaCasa++) {
// si no entra
if (entra
&& (terreno[filaTerreno + filaCasa][columnaTerreno
+ columnaCasa] == 1)
&& (casa[filaCasa][columnaCasa] == 1)) {
entra = false;
}
}
}
// si entra
if (entra) {
return new Posicion(true, filaTerreno, columnaTerreno,
orientacion);
} else {
entra = true;
}
}
// si no puede hacerse entrar
return null;
} |
91ec8ba6-be5e-41e3-bc0c-1042d88642f9 | 9 | @Override
public String List_file_url(String id) {
String texto_html = "";
try {
this.conn = FactoryConnectionDB.open(FactoryConnectionDB.ORACLE);
String sql = "select a.NO_FILE,a.NO_ORIGINAL from RHTV_ARCHIVO_DOCUMENTO a , RHTV_DOCUMENTO_ADJUNTO d where d.ID_DOCUMENTO_ADJUNTO = a.ID_DOCUMENTO_ADJUNTO and a.id_documento_adjunto='" + id + "' and a.ES_FILE='1'";
ResultSet rs = this.conn.query(sql);
while (rs.next()) {
String tipo = rs.getString("NO_FILE").substring(rs.getString("NO_FILE").length() - 3, rs.getString("NO_FILE").length());
if (tipo.trim().equals("PDF") || tipo.equals("OCX") || tipo.equals("DOC")) {
if (tipo.equals("OCX") || tipo.equals("DOC")) {
texto_html = texto_html + "<a class='mustang-gallery' title='" + rs.getString("NO_ORIGINAL") + "' href='" + Url_Archivo + "Archivo/" + rs.getString("NO_FILE") + "'><img src='../../Dgp/Documento/Archivo/word.png' style='width:100px;height:100px;' class='borde'><br>" + rs.getString("NO_ORIGINAL") + "</a>";
} else {
texto_html = texto_html + "<a class='mustang-gallery' title='" + rs.getString("NO_ORIGINAL") + "' href='" + Url_Archivo + "Archivo/" + rs.getString("NO_FILE") + "'><img src='../../Dgp/Documento/Archivo/pdf.png' style='width:100px;height:100px;' class='borde'><br>" + rs.getString("NO_ORIGINAL") + "</a>";
}
} else {
texto_html = texto_html + "<a class='mustang-gallery' title='" + rs.getString("NO_ORIGINAL") + "' href='" + Url_Archivo + "Archivo/" + rs.getString("NO_FILE") + "'><img src='" + Url_Archivo + "Archivo/" + rs.getString("NO_FILE") + "' style='width:100px;height:100px;' class='borde'></a>";
}
}
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
} catch (Exception e) {
throw new RuntimeException("ERROR : " + e.getMessage());
} finally {
try {
this.conn.close();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
return texto_html;
} |
514db470-4003-4cad-9f1c-489aedf2c8e1 | 1 | Message receive() {
try {
return this.logs.remove(0);
} catch (Exception e) {
return null;
}
} |
25a4b226-3f52-46be-9f2d-b251c0a2cdc2 | 5 | private void validateTime(String t) {
try{
timeInt = Integer.parseInt(t);
}catch(NumberFormatException e){
throw new IllegalArgumentException("Input("+ t + ") Time-String must be a valid time 0000-2359");
}
if(Integer.parseInt(t.substring(2,4)) >= 60){
throw new IllegalArgumentException("Input("+ t + ") Time must be a valid time, one hour lasts 60 seconds!");
}
if((Integer.parseInt(t.substring(0,1)) == 2 && Integer.parseInt(t.substring(1,2)) > 3) || Integer.parseInt(t.substring(0,1)) >2){
throw new IllegalArgumentException("Input("+ t + ") must be a valid time, 23 is the last hour!");
}
} |
b6f4af14-041d-4584-a6e5-9e1307d0ba05 | 0 | public static ModelClassDesc tableParseToMode(TableDesc tableDesc) {
ModelClassDesc modelClassDesc = new ModelClassDesc();
modelClassDesc.setClassName(getClassName(tableDesc.getTableName()));
modelClassDesc.setFileds(getModelFiledByTableColumn(tableDesc));
return modelClassDesc;
} |
c8a5e638-6891-4f7c-b0fa-f352aeba9843 | 7 | File[] getRoots() {
/*
* On JDK 1.22 only...
*/
// return File.listRoots();
/*
* On JDK 1.1.7 and beyond...
* -- PORTABILITY ISSUES HERE --
*/
if (System.getProperty ("os.name").indexOf ("Windows") != -1) {
Vector /* of File */<File> list = new Vector<File>();
list.add(new File(DRIVE_A));
list.add(new File(DRIVE_B));
for (char i = 'c'; i <= 'z'; ++i) {
File drive = new File(i + ":" + File.separator);
if (drive.isDirectory() && drive.exists()) {
list.add(drive);
if (initial && i == 'c') {
currentDirectory = drive;
initial = false;
}
}
}
File[] roots = (File[]) list.toArray(new File[list.size()]);
sortFiles(roots);
return roots;
}
File root = new File(File.separator);
if (initial) {
currentDirectory = root;
initial = false;
}
return new File[] { root };
} |
5c46d731-a157-4581-b07b-84afcb7a862d | 6 | public static boolean is_array(Object object) {
// OK
if (object == null) return false;
if (object instanceof Map) return true;
if (object instanceof LinkedHashMap) return true;
if (object instanceof HashMap) return true;
if (object instanceof ArrayList) return true;
if (object instanceof List) return true;
return false;
} |
61f7b41f-4eab-4db6-a76b-46cffecfa1d1 | 3 | public void handleRemoveTapeAlphabetButton() {
Object alphabet = startView.getTapeAlphabetList().getSelectedValue();
if(startView.getTapeAlphabetList().getSelectedIndex() > 0){
startView.getTapeAlphabetItems().removeElement(alphabet);
if(startView.getInputAlphabetItems().contains(alphabet)){
startView.getInputAlphabetItems().removeElement(alphabet);
}
}
if(startView.getTapeAlphabetItems().getSize() < 2){
startView.getNextButton().setEnabled(false);
}
} |
9c46e002-467c-43a2-a029-1bae61d3ea6e | 1 | public void setMaxBill(double maxBill) {
if(maxBill < 0) {
throw new IllegalArgumentException(
"error: bill max must be greater than or equal to zero");
}
this.maxBill = maxBill;
} |
6e6f20aa-9808-461d-84b2-34d04d70ab76 | 7 | public void draw(Graphics g) {
View view = this.getView();
int point[] = view.getTilePosition(tower.getTile());
MagicGem gem = tower.getMagicGem();
if (gem!=null)
{
if (gem.getType().equals("hobbit")) this.setImage("/textures/constructs/tower/tower_hobbit.png");
else if (gem.getType().equals("human")) this.setImage("/textures/constructs/tower/tower_human.png");
else if (gem.getType().equals("elf")) this.setImage("/textures/constructs/tower/tower_elf.png");
else if (gem.getType().equals("dwarf")) this.setImage("/textures/constructs/tower/tower_dwarf.png");
else if (gem.getType().equals("range")) this.setImage("/textures/constructs/tower/tower_range.png");
else if (gem.getType().equals("firerate")) this.setImage("/textures/constructs/tower/tower_firerate.png");
}
g.drawImage(getImage() , point[0] , point[1], 30, 30, null);
} |
5d74bd29-615d-497a-999e-05b096c89470 | 4 | public synchronized void setWindowPosition(int x, int y) {
if (this.visible == false) {
throw new MinuetoWindowInvalidStateException("Window is invisible");
}
if(this.isClosed()) {
throw new MinuetoWindowInvalidStateException("Window is closed!");
}
if ( x < 0 )
throw new MinuetoOutOfBoundException(x, 0, 999999);
if ( y < 0 )
throw new MinuetoOutOfBoundException(y, 0, 999999);
this.jFrame.setLocation(x, y);
} |
22f3ab00-fee0-41ae-86c3-38c63794f351 | 5 | private boolean versionCheck(String title) {
if (this.type != UpdateType.NO_VERSION_CHECK) {
final String version = this.plugin.getDescription().getVersion();
if (title.split(" v").length == 2) {
final String remoteVersion = title.split(" v")[1].split(" ")[0]; // Get the newest file's version number
if (this.hasTag(version) || version.equalsIgnoreCase(remoteVersion)) {
// We already have the latest version, or this build is tagged for no-update
this.result = Updater.UpdateResult.NO_UPDATE;
return false;
}
} else {
// The file's name did not contain the string 'vVersion'
final String authorInfo = this.plugin.getDescription().getAuthors().size() == 0 ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")";
this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system");
this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'");
this.plugin.getLogger().warning("Please notify the author of this error.");
this.result = Updater.UpdateResult.FAIL_NOVERSION;
return false;
}
}
return true;
} |
bc1883fb-9d19-458f-8451-28e9ea4b889d | 0 | @Test
public void testMultipleFilters() throws Exception {
final Properties[] configs = new Properties[] { new Properties(), new Properties() };
configs[0].setProperty("type", "Zero");
configs[1].setProperty("type", "Wan");
configs[1].setProperty("median_latency", "250");
final FilterFactory ff = new FilterFactory(configs);
final Filter[] filters = ff.getInstances(new MockConnectionProcessor());
Assert.assertEquals(configs.length, filters.length);
Assert.assertEquals(filters[0].getClass().getName(), ZeroFilter.class.getName());
configs[1].setProperty("median_latency", "200");
Assert.assertEquals(filters[1].getClass().getName(), WanFilter.class.getName());
} |
a66f6288-7b89-4cc0-9cda-376461bc5300 | 5 | public Wave22(){
super();
MobBuilder m = super.mobBuilder;
for(int i = 0; i < 550; i++){
if(i % 5 == 0)
add(m.buildMob(MobID.ODDISH));
else if(i % 4 == 0)
add(m.buildMob(MobID.BELLSPROUT));
else if(i % 3 == 0)
add(m.buildMob(MobID.MEOWTH));
else if(i % 2 == 0)
add(m.buildMob(MobID.MANKEY));
else
add(m.buildMob(MobID.VULPIX));
}
} |
edf2ddcc-761d-457b-a558-f408c278fb1c | 2 | public static boolean isGameSytstemPath(String path) {
path = path.trim().toLowerCase();
return path.endsWith(DataConstants.GAME_SYSTEM_FILE_EXTENSION)
|| path.endsWith(DataConstants.GAME_SYSTEM_COMPRESSED_FILE_EXTENSION)
|| path.endsWith(DataConstants.GAME_SYSTEM_COMPRESSED_FILE_EXTENSION_OLD);
} |
f8dd5002-14b4-485c-ab57-14c5078e4192 | 1 | public void remove(int index) {
RangeCheck(index);
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(data, index + 1, data, index, numMoved);
}
data[--size] = null;
} |
d79eb485-b7b1-45bd-b5cc-6e1406eeb706 | 0 | @Override
public int attack(double agility, double luck) {
System.out.println("I tried to do a special attack but I haven't set it so I failed at this turn...");
return 0;
} |
21cfecdb-910a-4a30-b54d-7c20cb883daf | 4 | protected void updateDrillYard() {
if (drillYard == null || drillYard.destroyed()) {
final DrillYard newYard = new DrillYard(this) ;
final Tile o = origin() ;
final int S = this.size ;
for (int n : TileConstants.N_ADJACENT) {
n = (n + 2) % 8 ;
newYard.setPosition(o.x + (N_X[n] * S), o.y + (N_Y[n] * S), world) ;
if (newYard.canPlace()) {
newYard.doPlace(newYard.origin(), null) ;
drillYard = newYard ;
break ;
}
}
}
} |
60b272b1-b0e3-49cc-93b2-9bf900f49334 | 6 | @Override
public Handler createHandler(Class<?> type) {
if (type == World.class) {
return new WorldHandler();
} else if (type == Country.class) {
return new CountryHandler();
} else if (type == Continent.class) {
return new ContinentHandler();
} else if (type == Neighbour.class) {
return new NeighbourHandler();
} else if (type == Player.class) {
return new PlayerHandler();
}
return null;
} |
4ddecfc4-e289-4f07-a400-1be67ffc0314 | 0 | @Override
public String toString() {
return ToStringBuilder.reflectionToString(this,ToStringStyle.MULTI_LINE_STYLE);
} |
ebc09535-bf97-4d90-9d5f-6c8bf9fde8aa | 8 | public synchronized int available()
throws IOException
{
int avail = super.available();
int unencoded = precount - prepos + in.available();
if (encoder.getEncoder().getVbr()) {
switch (mode) {
case 0: // Narrowband
// ogg header size = 27 + packetsPerOggPage
// count 1 byte (min 5 bits) for each block available
return avail + (27 + 2 * packetsPerOggPage) *
(unencoded / (packetsPerOggPage*framesPerPacket*320));
case 1: // Wideband
// ogg header size = 27 + packetsPerOggPage
// count 2 byte (min 9 bits) for each block available
return avail + (27 + 2 * packetsPerOggPage) *
(unencoded / (packetsPerOggPage*framesPerPacket*640));
case 2: // Ultra wideband
// ogg header size = 27 + packetsPerOggPage
// count 2 byte (min 13 bits) for each block available
return avail + (27 + 3 * packetsPerOggPage) *
(unencoded / (packetsPerOggPage*framesPerPacket*1280));
default:
return avail;
}
}
else {
// Calculate size of a packet of Speex data.
int spxpacketsize = encoder.getEncoder().getEncodedFrameSize();
if (channels > 1) {
spxpacketsize += 17; // 1+4(14=inband)+4(9=stereo)+8(stereo data)
}
spxpacketsize *= framesPerPacket;
spxpacketsize = (spxpacketsize + 7) >> 3; // convert bits to bytes
// Calculate size of an Ogg packet containing X Speex packets.
// Ogg Packet = Ogg header + size of each packet + Ogg packets
int oggpacketsize = 27 + packetsPerOggPage * (spxpacketsize + 1);
int pcmframesize; // size of PCM data necessary to encode 1 Speex packet.
switch (mode) {
case 0: // Narrowband
// 1 frame = 20ms = 160ech * channels = 320bytes * channels
pcmframesize = framesPerPacket * 320 * encoder.getChannels();
avail += oggpacketsize *
(unencoded / (packetsPerOggPage * pcmframesize));
return avail;
case 1: // Wideband
// 1 frame = 20ms = 320ech * channels = 640bytes * channels
pcmframesize = framesPerPacket * 640 * encoder.getChannels();
avail += oggpacketsize *
(unencoded / (packetsPerOggPage * pcmframesize));
return avail;
case 2: // Ultra wideband
// 1 frame = 20ms = 640ech * channels = 1280bytes * channels
pcmframesize = framesPerPacket * 1280 * encoder.getChannels();
avail += oggpacketsize *
(unencoded / (packetsPerOggPage * pcmframesize));
return avail;
default:
return avail;
}
}
} |
1aab92da-156c-4e34-abaf-05352ae9fbd9 | 8 | @Override
public Object getValueAt(int row, int col)
{
Order o = info.get(row);
switch (col)
{
case 0 : return o.getOrderName();
case 1 : return o.printDate(o.getDueDate());
case 2 : return o.getSleeve().getMaterial().getName();
case 3 : return o.getSleeve().getCircumference();
case 4 : return o.getWidth();
case 5 : return o.getQuantity();
case 6 : return o.getConductedQuantity();
case 7 : return o.getStatus();
}
return null;
} |
971f7902-9bf2-4aab-9d1e-d7591435e0cd | 5 | public void switchLabels() {
// Only to switch Labels if necessary
if (tabbedPane.getSelectedIndex() == 0) {
if (fieldleft.hasFocus() || comboboxleft.hasFocus()) {
label_l.setText("Von:");
label_r.setText("In:");
arrow.setVisible(true);
arrow_o.setVisible(false);
} else {
label_r.setText("Von:");
label_l.setText("In:");
arrow.setVisible(false);
arrow_o.setVisible(true);
}
} else {
if (fieldleft_2.hasFocus() || comboboxleft_2.hasFocus()) {
label_l2.setText("Von:");
label_r2.setText("In:");
arrow2.setVisible(true);
arrow_o2.setVisible(false);
} else {
label_r2.setText("Von:");
label_l2.setText("In:");
arrow2.setVisible(false);
arrow_o2.setVisible(true);
}
}
} |
cb199b21-c8c5-406c-9927-3822f8d3389e | 4 | public RSA(BigInteger N, int E, BigInteger D, BigInteger P, BigInteger Q, BigInteger DP, BigInteger DQ, BigInteger C)
{
this.n = N;
this.Exponent = E;
this.Private = D;
this.p = P;
this.q = Q;
this.dmp1 = DP;
this.dmq1 = DQ;
this.coeff = C;
// adjust a few flags.
Encryptable = (n != null && n != Zero && Exponent != 0);
Decryptable = (Encryptable && Private != Zero && Private != null);
} |
a43cdfaf-5e17-4dbd-9ac5-fd4492f35407 | 4 | public void visit(final EditorVisitor visitor) {
// First visit ourself
visitor.visitClassEditor(this);
final EditorContext context = this.context();
// Visit each field
final FieldInfo[] fields = this.fields();
for (int i = 0; i < fields.length; i++) {
final FieldEditor fieldEditor = context.editField(fields[i]);
visitor.visitFieldEditor(fieldEditor);
context.release(fields[i]);
}
// Visit each method
final ArrayList regularMethods = new ArrayList();
final MethodInfo[] methods = this.methods();
for (int i = 0; i < methods.length; i++) {
final MethodEditor methodEditor = context.editMethod(methods[i]);
if (methodEditor.name().charAt(0) != '<') {
regularMethods.add(methods[i]);
} else {
visitor.visitMethodEditor(methodEditor);
}
context.release(methods[i]);
}
final Iterator iter = regularMethods.iterator();
while (iter.hasNext()) {
final MethodInfo info = (MethodInfo) iter.next();
final MethodEditor me = context.editMethod(info);
visitor.visitMethodEditor(me);
context.release(info);
}
} |
4077a38a-4fa6-4c02-9ea2-511df70a835f | 8 | @Override
public void learnFromInstance(Instance inst, HoeffdingOptionTree ht) {
this.observedClassDistribution.addToValue((int) inst.classValue(),
inst.weight());
if (this.listAttributes == null) {
this.numAttributes = (int) Math.floor(Math.sqrt(inst.numAttributes()));
this.listAttributes = new int[this.numAttributes];
for (int j = 0; j < this.numAttributes; j++) {
boolean isUnique = false;
while (isUnique == false) {
this.listAttributes[j] = ht.classifierRandom.nextInt(inst.numAttributes() - 1);
isUnique = true;
for (int i = 0; i < j; i++) {
if (this.listAttributes[j] == this.listAttributes[i]) {
isUnique = false;
break;
}
}
}
}
}
for (int j = 0; j < this.numAttributes - 1; j++) {
int i = this.listAttributes[j];
int instAttIndex = modelAttIndexToInstanceAttIndex(i, inst);
AttributeClassObserver obs = this.attributeObservers.get(i);
if (obs == null) {
obs = inst.attribute(instAttIndex).isNominal() ? ht
.newNominalClassObserver() : ht
.newNumericClassObserver();
this.attributeObservers.set(i, obs);
}
obs.observeAttributeClass(inst.value(instAttIndex), (int) inst
.classValue(), inst.weight());
}
} |
a08cb4f1-a1ac-439c-a748-665b225ea2a8 | 2 | private void drawGrid(Graphics2D g2) {
for (int y = 0; y < grid.height; y++) {
for (int x = 0; x < grid.width; x++) {
g2.setColor(Color.DARK_GRAY);
g2.drawRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
}
}
} |
b443e74c-0aad-45c8-acb2-57a8578c5f19 | 4 | public void createReport(File newFile) {
PrintWriter writer;
try {
writer = new PrintWriter(newFile);
writer.write("Eagle Creek SiteMap Analyzer Report for: " + getFileName() + "\n");
writer.write(" ,Summary:, Total, Pages, Documents, Media" + "\n");
writer.write(" , , " + sumTotal + "," + sumPages + "," + sumDocuments + "," + sumMedia + "\n");
if (sumPages > 0) {
writer.write("********************************************\n");
writer.write("Page URLS: \n");
writer.write("********************************************\n");
writer.write(Arrays.asList(getURLsOfType(URLType.Page)).toString().replace(",", "").replace("[", "").replace("]", "") + "\n");
}
if (sumDocuments > 0) {
writer.write("********************************************\n");
writer.write("Document URLS: \n");
writer.write("********************************************\n");
writer.write(Arrays.asList(getURLsOfType(URLType.Document)).toString().replace(",", "").replace("[", "").replace("]", "") + "\n");
}
if (sumMedia > 0) {
writer.write("********************************************\n");
writer.write("Media URLs: \n");
writer.write("********************************************\n");
writer.write(Arrays.asList(getURLsOfType(URLType.Media)).toString().replace(",", "").replace("[", "").replace("]", "") + "\n");
}
writer.close();
} catch (SecurityException | FileNotFoundException se ) {
System.out.println(se);
}
} |
a51f91a8-6d0e-41d9-ad42-8513dbc2911a | 6 | Space getForkSpace(Piece piece) {
Space[] oppSpaceArray = getSpacesWithPiece(piece);
Space[][] openSetsLast = getOpenSets(lastSpaceMoved);
for (Space oppSpace : oppSpaceArray) {
if (oppSpace != lastSpaceMoved) {
Space[][] openOppSets = getOpenSets(oppSpace);
for (Space[] oppSet : openOppSets) {
for (Space[] setLast : openSetsLast) {
Space space = getCommonSpace(setLast, oppSet);
if (space != null && space.piece == N)
return space;
}
}
}
}
return null;
} |
a8138622-cfc2-4687-a9cf-45c8eadd35b0 | 1 | public String display() {
String theMessages = "Welcome to the Message Board\n\n";
for(int i = 0; i < messages.size(); i++) {
theMessages = theMessages + this.messages.get(i).getMessage();
}
return theMessages;
} |
a4edcc60-7121-4a5f-86f0-4339f64d88a3 | 5 | public void addSettings(String date, String background1, String background2, String background3, String logo, String button)
{
Element settingsModule = doc.createElement("settings");
gameModule.appendChild(settingsModule);
Element startdateElement = doc.createElement("startdate");
startdateElement.appendChild(doc.createTextNode(date));
settingsModule.appendChild(startdateElement);
if(!background1.equals(""))
{
Path path = Paths.get(background1);
Element background1Element = doc.createElement("backGround1");
background1Element.appendChild(doc.createTextNode(path.getFileName().toString()));
settingsModule.appendChild(background1Element);
}
if(!background2.equals(""))
{
Path path = Paths.get(background2);
Element background2Element = doc.createElement("backGround2");
background2Element.appendChild(doc.createTextNode(path.getFileName().toString()));
settingsModule.appendChild(background2Element);
}
if(!background3.equals(""))
{
Path path = Paths.get(background3);
Element background3Element = doc.createElement("backGround3");
background3Element.appendChild(doc.createTextNode(path.getFileName().toString()));
settingsModule.appendChild(background3Element);
}
if(!logo.equals(""))
{
Path path = Paths.get(logo);
Element logoElement = doc.createElement("logo1");
logoElement.appendChild(doc.createTextNode(path.getFileName().toString()));
settingsModule.appendChild(logoElement);
}
if(!button.equals(""))
{
Path path = Paths.get(button);
Element buttonElement = doc.createElement("button1");
buttonElement.appendChild(doc.createTextNode(path.getFileName().toString()));
settingsModule.appendChild(buttonElement);
}
} |
5164f7df-a0a4-42cd-b357-be803aaf7170 | 2 | private int nextStake(int i) {
int nextStake = lastStakePlusSmax(i);
if (leftOvers > 0.0) return leftoversPlusSmax(i);
if (nextStake > endStake) return endStake;
return nextStake;
} |
4ff8f926-ae93-4ffb-bab0-ab632393adea | 2 | public static String getScore(){
rover = head;
String blank = "";
while(rover!=null){
if(rover.status == 1){
blank = blank + rover.name + " - " + rover.score + "\n";
}
rover = rover.next;
}
return blank;
} |
8771900c-36b6-49d5-ae8b-0c19734d3157 | 6 | @Override
public OreLookup lookup(String player, Integer time, List<Integer> restrict) {
OreLookup ore = new OreLookup(player);
for (String w : plugin.getConfiguration().getWorlds()) {
QueryParameters parameters = new QueryParameters();
parameters.addActionType("block-break",MatchRule.INCLUDE);
parameters.setWorld(w);
String dateFrom = null;
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, -1 * time);
SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFrom = form.format(cal.getTime());
parameters.setSinceTime(dateFrom);
parameters.addPlayerName(player);
parameters.setLimit(-1);
parameters.setAllowNoRadius(true);
for (int value : restrict){
parameters.addBlockFilter(value, (byte) 0);
}
try {
ActionsQuery aq = new ActionsQuery(this.prism);
QueryResult lookupResult = aq.lookup( parameters );
if(!lookupResult.getActionResults().isEmpty()){
List<Handler> results = lookupResult.getActionResults();
if (results != null) {
for (Handler a: results) {
ore.add(a.getBlockId(), a.getAggregateCount());
}
}
}
}
catch(NullPointerException ex) {
plugin.log("Unexpected Exception while fetching Data from Prism: "+ex.getMessage());
}
}
return ore;
} |
479e24b2-80e7-4ba9-9c75-c1e180d63067 | 9 | private boolean localPeak(int i, int j, int hw, int hh, int neighbourhood) {
int dt, dr;
long peak = houghAccumulator[i][j];
for (int k = -neighbourhood; k <= neighbourhood; k++) {
for (int l = -neighbourhood; l <= neighbourhood; l++) {
if (k == 0 && l == 0)
continue;
dt = i+k;
dr = j+l;
if (dr < 0 || dr >= 2*hh)
continue;
if (dt < 0)
dt = dt + hw;
if (dt >= hw)
dt = dt - hw;
if (houghAccumulator[dt][dr] > peak) {
return false;
}
}
}
return true;
} |
d5b88f95-db55-4e13-ab0e-0ffe02d3b6d4 | 3 | public boolean isNonsquareSymmetrical(Matrix m) {
MatrixIterator tr_itr = new MatrixIterator(m, TOPRIGHT);
MatrixIterator bl_itr = new MatrixIterator(m, BOTTOMLEFT);
while(tr_itr.hasNext() && bl_itr.hasNext()) {
if(tr_itr.next() != bl_itr.next()) {
return false;
}
}
return true;
} |
186f4313-f3aa-4b00-ab47-56eba7f18502 | 6 | public boolean saveLevel(File levelFile, PXLE_Level levelToSave)
{
try
{
// THESE WILL US BUILD A DOC
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// FIRST MAKE THE DOCUMENT
Document doc = docBuilder.newDocument();
// THEN THE LEVEL (i.e. THE ROOT) ELEMENT
Element levelElement = doc.createElement(LEVEL_NODE);
doc.createAttribute(NAME_ATT);
levelElement.setAttribute(NAME_ATT, levelToSave.getLevelName());
doc.appendChild(levelElement);
doc.createAttribute(IMAGE_ATT);
levelElement.setAttribute(IMAGE_ATT, levelToSave.getBackgroundImageFileName());
// THEN THE INTERSECTIONS
Element intersectionsElement = makeElement(doc, levelElement, INTERSECTIONS_NODE, "");
// AND LET'S ADD EACH INTERSECTION
int id = 0;
doc.createAttribute(ID_ATT);
doc.createAttribute(X_ATT);
doc.createAttribute(Y_ATT);
doc.createAttribute(OPEN_ATT);
for (Intersection i : levelToSave.getIntersections())
{
// MAKE AN INTERSECTION NODE AND ADD IT
Element intersectionNodeElement = makeElement(doc, intersectionsElement,
INTERSECTION_NODE, "");
// NOW LET'S FILL IN THE INTERSECTION'S DATA. FIRST MAKE THE ATTRIBUTES
intersectionNodeElement.setAttribute(ID_ATT, "" + id);
intersectionNodeElement.setAttribute(X_ATT, "" + i.x);
intersectionNodeElement.setAttribute(Y_ATT, "" + i.y);
intersectionNodeElement.setAttribute(OPEN_ATT, "" + i.open);
}
Element zombieListElement = makeElement(doc, levelElement, ZOMBIE_LIST_NODE, "");
for (Zombie z : levelToSave.getZombies())
{
Element zombieElement = makeElement(doc, zombieListElement, ZOMBIE_NODE, "");
zombieElement.setAttribute(ID_ATT, "" + id);
zombieElement.setAttribute(X_ATT, "" + z.x);
zombieElement.setAttribute(Y_ATT, "" + z.y);
}
Element policeListElement = makeElement(doc, levelElement, POLICE_LIST_NODE, "");
for (Police p : levelToSave.getPolices())
{
Element policeElement = makeElement(doc, policeListElement, POLICE_NODE2, "");
policeElement.setAttribute(ID_ATT, "" + id);
policeElement.setAttribute(X_ATT, "" + p.x);
policeElement.setAttribute(Y_ATT, "" + p.y);
}
Element banditListElement = makeElement(doc, levelElement, BANDIT_LIST_NODE, "");
for (Bandit b : levelToSave.getBandits())
{
Element policeElement = makeElement(doc, banditListElement, BANDIT_NODE, "");
policeElement.setAttribute(ID_ATT, "" + id);
policeElement.setAttribute(X_ATT, "" + b.x);
policeElement.setAttribute(Y_ATT, "" + b.y);
}
// AND NOW ADD ALL THE ROADS
Element roadsElement = makeElement(doc, levelElement, ROADS_NODE, "");
doc.createAttribute(INT_ID1_ATT);
doc.createAttribute(INT_ID2_ATT);
doc.createAttribute(SPEED_LIMIT_ATT);
doc.createAttribute(ONE_WAY_ATT);
ArrayList<Intersection> intersections = levelToSave.getIntersections();
for (Road r : levelToSave.getRoads())
{
// MAKE A ROAD NODE AND ADD IT TO THE LIST
Element roadNodeElement = makeElement(doc, roadsElement, ROAD_NODE, "");
int intId1 = intersections.indexOf(r.getNode1());
roadNodeElement.setAttribute(INT_ID1_ATT, "" + intId1);
int intId2 = intersections.indexOf(r.getNode2());
roadNodeElement.setAttribute(INT_ID2_ATT, "" + intId2);
roadNodeElement.setAttribute(SPEED_LIMIT_ATT, "" + r.getSpeedLimit());
roadNodeElement.setAttribute(ONE_WAY_ATT, "" + r.isOneWay());
}
// NOW THE START INTERSECTION
Element startElement = makeElement(doc, levelElement, START_INTERSECTION_NODE, "");
int startId = intersections.indexOf(levelToSave.getStartingLocation());
startElement.setAttribute(ID_ATT, "" + startId);
startElement.setAttribute(IMAGE_ATT, levelToSave.getStartingLocationImageFileName());
// AND THE DESTINATION
Element destElement = makeElement(doc, levelElement, DESTINATION_INTERSECTION_NODE, "");
int destId = intersections.indexOf(levelToSave.getDestination());
destElement.setAttribute(ID_ATT, "" + destId);
destElement.setAttribute(IMAGE_ATT, levelToSave.getDestinationImageFileName());
// NOW THE MONEY
Element moneyElement = makeElement(doc, levelElement, MONEY_NODE, "");
doc.createAttribute(AMOUNT_ATT);
moneyElement.setAttribute(AMOUNT_ATT, "" + levelToSave.getMoney());
// AND THE POLICE COUNT
Element policeElement = makeElement(doc, levelElement, POLICE_NODE, "");
doc.createAttribute(NUM_ATT);
policeElement.setAttribute(NUM_ATT, "" + levelToSave.getNumPolice());
// AND THE BANDIT COUNT
Element banditElement = makeElement(doc, levelElement, BANDITS_NODE, "");
banditElement.setAttribute(NUM_ATT, "" + levelToSave.getNumBandits());
// AND FINALLY THE ZOMBIES COUNT
Element zombiesElement = makeElement(doc, levelElement, ZOMBIES_NODE, "");
zombiesElement.setAttribute(NUM_ATT, "" + levelToSave.getNumZombies());
// THE TRANSFORMER KNOWS HOW TO WRITE A DOC TO
// An XML FORMATTED FILE, SO LET'S MAKE ONE
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, YES_VALUE);
transformer.setOutputProperty(XML_INDENT_PROPERTY, XML_INDENT_VALUE);
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(levelFile);
// SAVE THE POSE TO AN XML FILE
transformer.transform(source, result);
// SUCCESS
return true;
}
catch(TransformerException | ParserConfigurationException | DOMException | HeadlessException ex)
{
// SOMETHING WENT WRONG
return false;
}
} |
fd32b7dd-8406-4ddd-a3f4-a8881b7707f6 | 7 | public static void makethefile(String infile, String outfile, int rootnote, String temperamentstring, double maxpitchbend, Boolean writemaxpitchbend, int selectProgram, int tuningroot, double tuningfrequency, int transposeamt, Boolean overwrite) throws MidiUnavailableException, InvalidMidiDataException, IOException {
// open up the input midi file
Sequence midiIn = null;
try {
midiIn = MidiSystem.getSequence(new File(infile));
} catch (Exception e) {
displayerror("Error opening midi file "+infile+" for reading");
return;
}
// make a new midi sequence to store the modified midi stream
Sequence newMidi = RetuneMIDI.retunedSequence(midiIn,rootnote,temperamentstring,maxpitchbend,writemaxpitchbend,selectProgram,false,tuningroot,tuningfrequency, transposeamt,0);
if(newMidi == null){
displayerror("Error generating new midi sequence");
return;
}
// Now write the new midi file
try{
File f = new File(outfile);
if(!overwrite){
if(f.exists() && !f.isDirectory()){
if(!getYesNo("File "+outfile+" exists. Overwrite it?")){
displayerror("No file written");
return;
}
}
}
MidiSystem.write(newMidi,1,f);
} catch (IOException e) {
displayerror("Problem writing to file "+outfile);
return;
}
displaymessage("Done! New midi file written to "+outfile);
} |
07099a9b-f0cf-4c16-a520-7c82256ddc31 | 4 | @Override
public boolean[][] generateMaze() {
List<Point> list = new ArrayList<Point>();
int last;
this.maze[1][1] = false;
last = this.addNeighbours(new Point(1,1), list);
while(!list.isEmpty()){
int curi = this.rnd.nextInt() % last;
curi = list.size() - ((curi < 0 ? -curi : curi) +1);
Point cur = this.getTargetBlock(list.get(curi));
if(cur != null){
this.maze[cur.x][cur.y] = false;
this.maze[list.get(curi).x][list.get(curi).y] = false;
last = this.addNeighbours(cur, list);
if(last == 0)
last ++;
}
list.remove(curi);
}
return this.maze;
} |
7f56687a-e572-4fd7-8ac7-ce9d6b39ca9b | 6 | protected void changeListActiveOrNon() {
showList.clear();
if (cmbActiveNonActivePersons.getSelectedItem().equals(ACTIVE_PERSON)) {
for (DBPerson dbPerson : DatabaseList.listOfStockHolders) {
if (dbPerson.getAllStocks() != 0) {
showList.add(dbPerson);
}
}
}
if (cmbActiveNonActivePersons.getSelectedItem().equals(
NON_ACTIVE_PERSON)) {
for (DBPerson dbPerson : DatabaseList.listOfStockHolders) {
if (dbPerson.getAllStocks() == 0) {
showList.add(dbPerson);
}
}
}
} |
bccbf71f-5a94-4b5a-abd6-752d01162cfd | 4 | private void boardSetup() {
String[] colour = {"Black","White"};
int[] printRows = {0,1,2};
boolean offset = true;
for(int i=0;i<2;i++) // loop for each player
{
for(int k=0; k<3;k++) // loop for each row (&^)
{
for(int j = (offset) ? 1 : 0 ; j<=7; j+=2) // loop for each disc, (&^^)
{
ref.getGame().getBoard().addDisc(printRows[k], j , new Disc(colour[i]));
}
// inverse the positioning offset
offset = !offset;
// inverse the row to print on
printRows[k] = 7 - printRows[k];
}
}
} |
02280dc3-3678-4c5c-a3f1-1790f1da5bb4 | 0 | public AnimalInfo() {
/**
* Instantiates an animal object for each animal selection
*/
final Animal lion = new lion();
final Animal tiger = new tiger();
final Animal bear = new bear();
/**
* Sets parameters for the JFrame
*/
setResizable(false);
setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\Adam\\Eclipse\\Web_General_WS\\AnimalInfo\\resources\\lion_app_icon.png"));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 325, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final TextArea txtInfoDisplay = new TextArea();
txtInfoDisplay.setEditable(false);
txtInfoDisplay.setBounds(20, 66, 265, 160);
contentPane.add(txtInfoDisplay);
JButton btnLion = new JButton("Lion");
btnLion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//sets the text in the text area to the value returned by the overridden lion.dispalyInfo() method.
txtInfoDisplay.setText(lion.displayInfo());
}
});
btnLion.setBounds(10, 11, 89, 39);
contentPane.add(btnLion);
JButton btnTiger = new JButton("Tiger");
btnTiger.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//sets the text in the text area to the value returned by the overridden lion.dispalyInfo() method.
txtInfoDisplay.setText(tiger.displayInfo());
}
});
btnTiger.setBounds(109, 11, 89, 39);
contentPane.add(btnTiger);
JButton btnBear = new JButton("Bear");
btnBear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//sets the text in the text area to the value returned by the overridden lion.dispalyInfo() method.
txtInfoDisplay.setText(bear.displayInfo());
}
});
btnBear.setBounds(208, 11, 89, 39);
contentPane.add(btnBear);
} |
5bc9cf7f-8b43-4681-98a5-3e9a7b5dbfba | 0 | @Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
//System.out.println("repainting");
this.drawFields(g);
this.drawDate(g);
} |
504fb1ec-344b-41d4-8519-26709c42eb0d | 0 | public int getX() {
return x;
} |
62edb53f-3d6d-4834-bee0-d93feebd67f3 | 2 | public int compare(Atom a1, Atom a2) {
// TODO: something like return Integer.compare(a1.layer,a2.layer)
// would be more efficient
if (a1.layer < a2.layer) return -1;
else if(a1.layer > a2.layer) return 1;
else return 0;
} |
107b1763-d8a7-4463-9572-d35dc66abcfe | 1 | public long read7bytes() throws IOException {
long b0 = read();
long b1 = read();
long b2 = read();
long b3 = read();
long b4 = read();
long b5 = read();
long b6 = read();
if (le)
return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24) | (b4 << 32) | (b5 << 40) | (b6 << 48);
else
return b6 | (b5 << 8) | (b4 << 16) | (b3 << 24) | (b2 << 32) | (b1 << 40) | (b0 << 48);
} |
753ad51d-af92-418f-958b-408d7ec4ece2 | 2 | private static int clamp(int p) {
return p > 255 ? 255 : (p < 0 ? 0 : p);
} |
b36c1e9c-8f2f-4419-bfd8-a4b6a45c11c4 | 0 | public void setButton(String text, int iD, int loc, boolean disabled)
{
buttonArray[loc].set(text, iD, disabled);
} |
d6eb5311-67d3-46a2-9cbf-483e43468f64 | 8 | @Override
public void e(float sideMot, float forMot) {
if (this.passenger == null || !(this.passenger instanceof EntityHuman)) {
super.e(sideMot, forMot);
this.W = 0.5F; // Make sure the entity can walk over half slabs,
// instead of jumping
return;
}
EntityHuman human = (EntityHuman) this.passenger;
if (!RideThaMob.control.contains(human.getBukkitEntity().getName())) {
// Same as before
super.e(sideMot, forMot);
this.W = 0.5F;
return;
}
this.lastYaw = this.yaw = this.passenger.yaw;
this.pitch = this.passenger.pitch * 0.5F;
// Set the entity's pitch, yaw, head rotation etc.
this.b(this.yaw, this.pitch); // https://github.com/Bukkit/mc-dev/blob/master/net/minecraft/server/Entity.java#L163-L166
this.aO = this.aM = this.yaw;
this.W = 1.0F; // The custom entity will now automatically climb up 1
// high blocks
sideMot = ((EntityLiving) this.passenger).bd * 0.5F;
forMot = ((EntityLiving) this.passenger).be;
if (forMot <= 0.0F) {
forMot *= 0.25F; // Make backwards slower
}
sideMot *= 0.75F; // Also make sideways slower
float speed = 0.35F; // 0.2 is the default entity speed. I made it
// slightly faster so that riding is better than
// walking
this.i(speed); // Apply the speed
super.e(sideMot, forMot); // Apply the motion to the entity
try {
Field jump = null;
jump = EntityLiving.class.getDeclaredField("bc");
jump.setAccessible(true);
if (jump != null && this.onGround) { // Wouldn't want it jumping
// while
// on the ground would we?
if (jump.getBoolean(this.passenger)) {
double jumpHeight = 0.5D;
this.motY = jumpHeight; // Used all the time in NMS for
// entity jumping
}
}
} catch (Exception e) {
e.printStackTrace();
}
} |
c169e138-9b5b-47ae-bf67-3fbc9b713d25 | 2 | public static void main(String[] args) {
final String user;
final String pass;
if (args.length != 2) {
user = "";
pass = "";
}
else
{
user = args[0];
pass = args[1];
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Model model = new Model(user, pass);
new WBView(model);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} |
e92a2609-de4a-46ec-b2d1-5d5aaf6a55e0 | 6 | 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(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login.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 Login().setVisible(true);
}
});
} |
b55a0570-d8f2-4d89-b19f-e0c257ef9b15 | 8 | public static boolean searchinRotatedArrayWithDup(int[] A, int target) {
int start = 0;
int end=A.length-1;
int mid;
while(start<=end)
{
mid=(start+end)/2;
if(A[mid]==target) return true;
if(A[start]<A[mid])
{
if(target >= A[start] && target < A[mid])
end = mid-1;
else
start = mid+1;
}else if(A[start]>A[mid])
{
if(target > A[mid] && target <= A[end])
start = mid+1;
else
end = mid-1;
}else
{
start++;
}
}
return false;
} |
6d2b6c74-0201-48b4-bef4-f32e9fe9ba6a | 7 | private boolean executeCommand(String cmd, CommandSender sender, Iterator<String> args) {
try {
return (Boolean)commands.get(cmd).getClass().getMethod(cmd, CommandSender.class,
Iterator.class).invoke(commands.get(cmd), sender, args);
} catch(SecurityException ex) {
plug.getLogger().log(Level.SEVERE, null, ex);
} catch(IllegalAccessException ex) {
plug.getLogger().log(Level.SEVERE, null, ex);
} catch(IllegalArgumentException ex) {
plug.getLogger().log(Level.SEVERE, null, ex);
} catch(InvocationTargetException ex) {
plug.getLogger().log(Level.SEVERE, null, ex);
} catch(NullPointerException ex) {
plug.getLogger().log(Level.SEVERE, null, ex);
} catch(ClassCastException ex) {
plug.getLogger().log(Level.SEVERE, null, ex);
} catch(NoSuchMethodException ex) {
plug.getLogger().log(Level.SEVERE, null, ex);
}
return false;
} |
b02b0e50-b120-4027-8da4-cfa8c1a9593b | 1 | public boolean enregistrerDepartVehicule(int numeroLocation){
System.out.println("ModeleLocations::enregistrerDepartVehicule()") ;
Location location = rechercherLocation(numeroLocation) ;
if(location != null){
location.setEtat(Location.EN_COURS) ;
location.setDateDepart(new GregorianCalendar()) ;
location.getVehicule().setSituation(Vehicule.LOUE) ;
return true ;
}
else {
return false ;
}
} |
7c751021-b660-4e3e-8459-bb4a56a237d5 | 9 | public void setResponseCode(int responseCode) throws MessageAttributeException {
switch (responseCode) {
case 400: reason = "Bad Request"; break;
case 401: reason = "Unauthorized"; break;
case 420: reason = "Unkown Attribute"; break;
case 430: reason = "Stale Credentials"; break;
case 431: reason = "Integrity Check Failure"; break;
case 432: reason = "Missing Username"; break;
case 433: reason = "Use TLS"; break;
case 500: reason = "Server Error"; break;
case 600: reason = "Global Failure"; break;
default: throw new MessageAttributeException("Response Code is not valid");
}
this.responseCode = responseCode;
} |
3078378b-7c96-4084-8335-41c77e525868 | 8 | protected int validateInput(String input, int numDigits)
{
if(input.equals(""))
{
return 0;
}
boolean negative = false;
input = input.trim();
if(input.charAt(0) == '-')
{
negative = true;
}
//Goes through the input string and converts any non-digit characters to
// 0.
for(int count = 0; count < input.length(); count++)
{
if(!Character.isDigit(input.charAt(count)))
{
input = input.replace(input.charAt(count), '0');
}
}
//After changing all characters to digits, trims leading 0's from the
// string.
if(Integer.parseInt(input) != 0)
{
while(input.charAt(0) == '0')
{
input = input.substring(1);
}
}
//If the resulting string is too long, truncate until only the 3 left
// most digits remain.
while(input.length() > numDigits)
{
input = input.substring(0, input.length() - 1);
}
if(negative)
{
return Integer.parseInt(input) * -1;
}
else
{
return Integer.parseInt(input);
}
} |
5be7611c-be8d-4700-922b-ecaa0a447dd0 | 4 | @Test
public void testReceiveMultipleTimeout() {
int noOfMessages = 5;
try {
consumer = new AbstractMessageConsumer(mockTopic) {
};
assertNotNull(mockTopic.getTopicSubscriber());
HashSet<Message> messages = new HashSet<Message>();
for (int i = 0; i < noOfMessages; i++) {
Message msg = new MockMessage("TestMessage" + i);
messages.add(msg);
}
for (Message msg : messages) {
FutureTask<Message> future = getMessageFuture(consumer, 50);
Thread.sleep(20);
mockTopic.getTopicSubscriber().onMessage(msg);
Message received = future.get(6, TimeUnit.MILLISECONDS);
assertNotNull("Received message is null ", received);
assertTrue("Unexpected message found",
messages.contains(received));
}
} catch (TimeoutException e) {
fail("Did not receive message in time");
} catch (Exception e) {
logger.error("Error while calling receiving message", e);
fail("Error while calling onMessage:" + e.getMessage());
}
} |
2282412e-5fa1-4fe1-8881-2ae78892e88d | 7 | public int searchInsert(int[] A, int target) {
//边界条件判断
if ( A.length==0 ) return 0;
int end = A.length-1;
int start = 0 ;
if (A[start] >= target) return start;
else if (A[end]< target ) return A.length;
//二分查找
int mid = (end-start)/2;
while ( end>=start)
{
if( A[mid] > target){
end = mid-1;
}
else if( A[mid] < target){
start = mid+1;
}
else if( A[mid] == target)
{
return mid;
}
mid = (end+start)/2;
}
return end+1;
} |
ec7c567b-c146-44ef-8d86-985831588476 | 6 | private List<MorrisLineAdjacent> getRowLineAdjacent() {
List<MorrisLineAdjacent> lines = new ArrayList<MorrisLineAdjacent>();
boolean bl = this.hasLeft();
boolean br = this.hasRight();
MorrisLineAdjacent oneLine = null;
if (bl && br) { //this is in the middle
oneLine = new MorrisLineAdjacent(this, this.left(), this.right());
lines.add(oneLine);
}
else {
if (bl) { //this is in the most right
MorrisIntersection l = this.left();
if (l.hasLeft()) {
oneLine = new MorrisLineAdjacent(this, l, l.left());
lines.add(oneLine);
}
}
if (br) { //this is in the most left
MorrisIntersection r = this.right();
if (r.hasRight()) {
oneLine = new MorrisLineAdjacent(this, r, r.right());
lines.add(oneLine);
}
}
}
return lines;
} |
d48f3d45-6a2d-43b1-8dea-352c02fba863 | 2 | private void findDeviceParser(String type) throws SAXException {
if (type != null) {
logger.info(String.format(
Messages.getString("device_found"), type)); //$NON-NLS-1$
currentParser = parserFactory.getParser(type);
if (currentParser != null) {
logger.info(String.format(Messages.getString("parser_found"), currentParser //$NON-NLS-1$
.getClass().getSimpleName()));
currentParser.init();
} else {
throw new SAXException(String.format(
Messages.getString("unable_to_parse_device"), type)); //$NON-NLS-1$
}
} else {
throw new SAXException(String.format(
Messages.getString("empty_device_name"))); //$NON-NLS-1$
}
} |
27a92749-d3d4-4931-b6a3-67b4f74eb0b5 | 0 | public BodyPart getBodypart(){
return bodypart;
} |
1d5b8441-46b0-48d3-955b-18bb896db871 | 3 | public GaussianDialog(final Panel panel) {
setTitle("Gaussian");
setBounds(0, 0, 350, 200);
Dimension size = getToolkit().getScreenSize();
setLocation(size.width / 3 - getWidth() / 3, size.height / 3
- getHeight() / 3);
this.setResizable(false);
setLayout(null);
JPanel paramPanel = new JPanel();
paramPanel.setBorder(BorderFactory.createTitledBorder("Parameters"));
paramPanel.setBounds(0, 0, 350, 120);
JLabel avgLabel = new JLabel("Average = ");
final JTextField avgTextField = new JTextField("0");
avgTextField.setColumns(3);
JLabel devLabel = new JLabel("Deviation = ");
final JTextField devTextField = new JTextField("1");
devTextField.setColumns(3);
JLabel pLabel = new JLabel("Probability = %");
final JTextField pTextField = new JTextField("50");
pTextField.setColumns(3);
JButton okButton = new JButton("OK");
okButton.setSize(300, 40);
okButton.setBounds(0, 120, 350, 40);
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double avg = 0;
double dev = 1;
double p = 20;
try {
avg = Double.valueOf(avgTextField.getText());
dev = Double.valueOf(devTextField.getText());
p = Double.valueOf(pTextField.getText());
} catch (NumberFormatException ex) {
new MessageFrame("Invalid values");
return;
}
if (p < 0 || p > 100) {
new MessageFrame("Invalid values");
return;
}
Image image = panel.getImage();
panel.setImage(NoiseUtils.gaussianNoise(image, avg, dev,
p * 0.01));
panel.repaint();
dispose();
}
});
paramPanel.add(avgLabel);
paramPanel.add(avgTextField);
paramPanel.add(devLabel);
paramPanel.add(devTextField);
paramPanel.add(pLabel);
paramPanel.add(pTextField);
this.add(paramPanel);
this.add(okButton);
} |
86ebe3de-eb73-4558-a56d-72130cddd76c | 6 | 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(VerPrecios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VerPrecios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VerPrecios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VerPrecios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the dialog
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
VerPrecios dialog = new VerPrecios(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} |
83136fa1-239c-453c-bf9a-561b39798768 | 7 | public static String[] traitDesc(String trait)
{
/*
* Traits for civs:
* 3 Aggressive > +10% when attacking, 1 free promotion per unit
* 3 Imperialistic > 2 health per city, > 1 extra trade route per city
* 2 Refined > 2 culture per city, > +10% research speed
* 4 Prosperous > +15% food per city, > +25% speed on Settler
* 3 Defensive > +15% when defending, +25% speed on fortifications
* 3 Traditional +25% speed on unique unit, > +15% food per city
* 2 Industrious > +10% production/metal, +25% on wonders
*/
if (trait.equals("Aggressive"))
return new String[]{"+10% when attacking","1 free promotion per unit"};
else if (trait.equals("Defensive"))
return new String[]{"+15% when defending","+25% speed on fortifications"};
else if (trait.equals("Imperialistic"))
return new String[]{"2 health per city","1 extra trade route per city"};
else if (trait.equals("Industrious"))
return new String[]{"+10% production/metal","+25% on wonders "};
else if (trait.equals("Prosperous"))
return new String[]{"+15% food per city","+25% speed on Settler "};
else if (trait.equals("Refined"))
return new String[]{"2 culture per city","+10% research speed"};
else if (trait.equals("Traditional"))
return new String[]{"+25% speed on unique unit","+15% food per city"};
else
{
System.out.println("Invalid trait: " + trait);
return null;
}
} |
29964a86-5ddf-4f78-ad44-9191496e577d | 5 | public Action choose(LightsOut.Player actor, Set<Action> options) {
if(presses == null) {
presses = new HashSet<Location>();
// linear algebra solution
boolean[][] state = actor.state();
boolean[] s = stateVector(state);
boolean[][] M = stateMatrix(state[0].length, state.length);
gauss(M, s);
// translate to locations
Location[][] locations = actor.locations();
for(int x = 0; x < s.length; x++) {
if(s[x]) { presses.add(locations[x / state.length][x % state[0].length]); }
}
}
Location next = Groups.first(presses);
presses.remove(next);
for(Action action : Groups.ofType(LightsOut.Move.class, options)) {
if(((LightsOut.Move)action).target.location().equals(next)) { return action; }
}
return null;
} |
6f6c6f31-33cb-4795-a05c-60c1fc47d73d | 8 | public void actionPerformed(ActionEvent ae)
{
try
{
if (ae.getSource() == this.tmrReadLine)
{
try
{
if ((!this.continueRun) || (this.killThread) || (this.sktMyConnection_ConnectedAgent.isClosed()))
{
closeThread();
}
}
catch (Exception localException1) {
}
if ((this.alReceivedLine != null) && (this.alReceivedLine.size() > 0))
{
this.processInterrupt = false;
readLineFromSocket();
}
}
}
catch (Exception e)
{
Driver.eop("AE", this.strMyClassName, e, e.getLocalizedMessage(), false);
}
} |
52b3ddf3-12d5-4e0c-8802-d3e3f34c66a8 | 9 | public double HCRR(Instances train,Classifier[] cfsArray,List<Integer>[] classifyResult,List<Double> correctRateArray,double initCorrectRate,List<Double> currentResult,List<Integer> ClassifierNo){
double diversity;//差异性(差异性度量是κ度量,κ值越小,差异性越大)
double tempDiversity;
double correctRate;//正确率
double voteCorrectRate;//vote集成得到的正确率
//
int count=cfsArray.length;//循环次数(循环次数为分类器的个数)
int i=0,j,k;
int r;
int maxNo;
Random random=new Random();
//如果列表为空,说明是第一轮循环,那么就将正确率最高的分类器选为第一个分类器,否则就只要将正确率替换成前一轮循环得到的正确率
if (ClassifierNo.size() == 0) {
//
diversity=currentResult.get(0);
//
if (bestBegin == false) {
r = random.nextInt(cfsArray.length);
correctRate = correctRateArray.get(r);
ClassifierNo.add(r);
} else {
correctRate = Collections.max(correctRateArray);
maxNo = correctRateArray.indexOf(correctRate);
ClassifierNo.add(maxNo);
}
} else {
diversity=currentResult.get(0);
correctRate=currentResult.get(1);
}
//
while (i < count) {
//
if (correctRate >= initCorrectRate) {
break;
} else {
// 随机产生一个分类器的编号,然后将得到该分类器和之前选择的分类器的分类结果一起计算差异性
r = random.nextInt(cfsArray.length);
List<Integer>[] tempList = new List[ClassifierNo.size() + 1];
for (k = 0; k < ClassifierNo.size(); k++) {
tempList[k] = classifyResult[ClassifierNo.get(k)];
}
tempList[ClassifierNo.size()] = classifyResult[r];
tempDiversity = CalculateK(tempList);
// κ度量的值越小,说明差异性越大
if (tempDiversity <= diversity) {
//
ClassifierNo.add(r);
//
Classifier[] newCfsArray = new Classifier[ClassifierNo.size()];
//
for (j = 0; j < newCfsArray.length; j++) {
newCfsArray[j] = cfsArray[ClassifierNo.get(j)];
}
//
voteCorrectRate = ensembleVote(train, /* test, */newCfsArray);
// 如果当前集成得到的正确率比之前的正确率高,那么就将差异性和正确率替换成该轮的值,否则将最后一个分类器编号删除(新加的分类器编号)
if (voteCorrectRate > correctRate) {
diversity = tempDiversity;
correctRate = voteCorrectRate;
setBestMatrixString(tempMatrixString);
setBestClassDetailsString(tempClassDetailsString);
} else {
ClassifierNo.remove(ClassifierNo.size() - 1);
}
}
i++;
}
}
// 说明只有一个分类器,差异性为0
if (diversity == Double.MAX_VALUE) {
diversity = 0;
}
//对于循环集成,每一次循环结束必须记录当前的差异性、正确率和所选分类器个数,对于所选择的分类编号训练由ClassifierNo保存
currentResult.clear();
currentResult.add(diversity);
currentResult.add(correctRate);
currentResult.add((double)ClassifierNo.size());
return correctRate;
} |
be07a2d0-a391-437e-abef-aa598083a765 | 9 | private int checkCross(int i, int j, Board b)
{
int points = 0;
//ONLY IF "X" IS FOUND ASSUMING X IS COMPUTER
if(b.board[i][j].equals("X"))
{
if(i==0)
{
if(j==0)
{
points+=checkConsecutiveX('r',i,j,b);
points+=checkConsecutiveX('d',i,j,b);
points+=checkConsecutiveONextToX('r',i,j,b);
points+=checkConsecutiveONextToX('d',i,j,b);
}
else if(j==7)
{
points+=checkConsecutiveX('d',i,j,b);
points+=checkConsecutiveX('l',i,j,b);
points+=checkConsecutiveONextToX('d',i,j,b);
points+=checkConsecutiveONextToX('l',i,j,b);
}
else
{
points+=checkConsecutiveX('r',i,j,b);
points+=checkConsecutiveX('d',i,j,b);
points+=checkConsecutiveX('l',i,j,b);
points+=checkConsecutiveONextToX('r',i,j,b);
points+=checkConsecutiveONextToX('d',i,j,b);
points+=checkConsecutiveONextToX('l',i,j,b);
}
//points=0;
}
else if(i==7)
{
if(j==0)
{
points+=checkConsecutiveX('u',i,j,b);
points+=checkConsecutiveX('r',i,j,b);
points+=checkConsecutiveONextToX('u',i,j,b);
points+=checkConsecutiveONextToX('r',i,j,b);
}
else if(j==7)
{
points+=checkConsecutiveX('u',i,j,b);
points+=checkConsecutiveX('l',i,j,b);
points+=checkConsecutiveONextToX('u',i,j,b);
points+=checkConsecutiveONextToX('l',i,j,b);
}
else
{
points+=checkConsecutiveX('u',i,j,b);
points+=checkConsecutiveX('r',i,j,b);
points+=checkConsecutiveX('l',i,j,b);
points+=checkConsecutiveONextToX('u',i,j,b);
points+=checkConsecutiveONextToX('r',i,j,b);
points+=checkConsecutiveONextToX('l',i,j,b);
}
//points=0;
}
//i = 1 ---> 6
else
{
if(j==0)
{
points+=checkConsecutiveX('u',i,j,b);
points+=checkConsecutiveX('r',i,j,b);
points+=checkConsecutiveX('d',i,j,b);
points+=checkConsecutiveONextToX('u',i,j,b);
points+=checkConsecutiveONextToX('r',i,j,b);
points+=checkConsecutiveONextToX('d',i,j,b);
}
else if(j==7)
{
points+=checkConsecutiveX('u',i,j,b);
points+=checkConsecutiveX('d',i,j,b);
points+=checkConsecutiveX('l',i,j,b);
points+=checkConsecutiveONextToX('u',i,j,b);
points+=checkConsecutiveONextToX('d',i,j,b);
points+=checkConsecutiveONextToX('l',i,j,b);
}
else
{
points+=checkConsecutiveX('u',i,j,b);
points+=checkConsecutiveX('r',i,j,b);
points+=checkConsecutiveX('d',i,j,b);
points+=checkConsecutiveX('l',i,j,b);
points+=checkConsecutiveONextToX('u',i,j,b);
points+=checkConsecutiveONextToX('r',i,j,b);
points+=checkConsecutiveONextToX('d',i,j,b);
points+=checkConsecutiveONextToX('l',i,j,b);
}
//points=0;
}
}
return points;
} |
72fac64f-2a59-47d3-a8bd-270183377c3d | 0 | public void addDocumentRepositoryListener(DocumentRepositoryListener l) {
documentRepositoryListeners.add(l);
} |
a04e4524-66ad-4a1c-8435-d17f8a8598c2 | 6 | 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(Frm_EnviarEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frm_EnviarEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frm_EnviarEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frm_EnviarEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Frm_EnviarEmail().setVisible(true);
}
});
} |
8017e6cf-0387-4a15-a375-fdc4f95207d2 | 2 | @Override
public void removeStock(Stock stock) {
tx.begin();
for (SubProcess sp : stock.getSubProcesses()) {
stock.removeSubProcess(sp);
}
for (StorageUnit su : stock.getStorageUnits()) {
stock.removeStorageUnit(su);
}
em.merge(stock);
em.remove(stock);
tx.commit();
} |
de65d986-408c-4a4f-a4f4-b56eeea396f7 | 0 | public byte[] getEncoded() {
return this.encoded;
} |
55976c02-f0da-480c-94fa-ec070ea75466 | 9 | public double logScore(int nType, int nCardinality) {
double fScore = 0.0;
switch (nType) {
case (Scoreable.BAYES): {
for (int iSymbol = 0; iSymbol < m_nSymbols; iSymbol++) {
fScore += Statistics.lnGamma(m_Counts[iSymbol]);
}
fScore -= Statistics.lnGamma(m_SumOfCounts);
if (m_fPrior != 0.0) {
fScore -= m_nSymbols * Statistics.lnGamma(m_fPrior);
fScore += Statistics.lnGamma(m_nSymbols * m_fPrior);
}
}
break;
case (Scoreable.BDeu): {
for (int iSymbol = 0; iSymbol < m_nSymbols; iSymbol++) {
fScore += Statistics.lnGamma(m_Counts[iSymbol]);
}
fScore -= Statistics.lnGamma(m_SumOfCounts);
//fScore -= m_nSymbols * Statistics.lnGamma(1.0);
//fScore += Statistics.lnGamma(m_nSymbols * 1.0);
fScore -= m_nSymbols * Statistics.lnGamma(1.0/(m_nSymbols * nCardinality));
fScore += Statistics.lnGamma(1.0/nCardinality);
}
break;
case (Scoreable.MDL):
case (Scoreable.AIC):
case (Scoreable.ENTROPY): {
for (int iSymbol = 0; iSymbol < m_nSymbols; iSymbol++) {
double fP = getProbability(iSymbol);
fScore += m_Counts[iSymbol] * Math.log(fP);
}
}
break;
default: {}
}
return fScore;
} |
d7b3c32c-c7cc-4fe4-9b1b-79ee4e8660a2 | 2 | public OdigoiList() {
con = new Mysql();
setTitle("Lista Odigwn");
/* vgazei to para8uro sto kedro tis othonis me diastaseis 355x40 */
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setBounds(dim.width/2-150, dim.height/2-125, 355, 400);
/*--------------*/
this.setResizable(false);
getContentPane().setBackground(Color.WHITE);
getContentPane().setLayout(null);
listModel = new DefaultListModel<String>();
odigoiList = new JList<String>(listModel);
getContentPane().add(odigoiList);
JScrollPane scrollPane = new JScrollPane(odigoiList);
scrollPane.setBounds(0, 0, 355, 340);
getContentPane().add(scrollPane);
JButton editButton = new JButton("Epe3ergasia");
editButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
try{
/*
* anoigei to parathiro epexergasias gia ton epilegmeno odigo
*/
odigoiInfo=odigoi.get(odigoiList.getSelectedIndex());
OdigoiAdd frame = new OdigoiAdd(Integer.parseInt(odigoiInfo.get("id")));
frame.setVisible(true);
}catch(Exception e){
e.printStackTrace();
}
}
});
editButton.setBounds(0, 338, 175, 34);
getContentPane().add(editButton);
JButton deleteButton = new JButton("Diagrafh");
deleteButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
/*
* diagrafi ton epilegmeno odigo epeita apo erwthsh
*/
int dialogResult = JOptionPane.showConfirmDialog (null, "Eiste sigouri oti thelete na diagrapsete ton sigkekrimeno odigo?","Diagrafh",JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
delete(Integer.parseInt(odigoiId.get(odigoiList.getSelectedIndex())),odigoiList.getSelectedIndex());
}
}
});
deleteButton.setBounds(175, 338, 175, 34);
getContentPane().add(deleteButton);
addOdigous();
} |
a923176d-6051-454b-888c-03cd65814e6b | 3 | private void init(final Stage primaryStage) {
thisStage = primaryStage;
thisStage.setTitle("Sliding Puzzle");
StackPane sPane = new StackPane();
Label label = new Label("Name: ");
final TextField nameField = new TextField();
final Button setNameField = new Button("OK");
final int i5 = 5;
final int i10 = 10;
final int i20 = 20;
final int i100 = 100;
nameField.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(final KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
setNameField.fire();
}
}
});
setNameField.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(final ActionEvent actionEvent) {
if (nameField.getText() != "" && nameField.getText() != null) {
userName = nameField.getText();
}
SlidingPuzzlePiece.setPuzzleSize(i100);
newGame();
}
});
VBox welcomeBox = new VBox(i5);
Text welcomeText = new Text(i100, i100,
"Welcome to the Sliding Puzzle\n\nWhats your name?\n");
welcomeText.setFont(new Font(i20));
welcomeText.setTextAlignment(TextAlignment.CENTER);
welcomeBox.getChildren().add(welcomeText);
welcomeBox.setPadding(new Insets(i10, i10, i10, i10));
HBox displayBox = new HBox(i5);
displayBox.getChildren().addAll(label, nameField, setNameField);
displayBox.setAlignment(Pos.CENTER);
welcomeBox.getChildren().add(displayBox);
sPane.getChildren().add(welcomeBox);
thisStage.centerOnScreen();
thisStage.toFront();
thisStage.setScene(new Scene(sPane));
thisStage.show();
} |
a6e7850a-b9b8-4121-a3e7-55bb49ca0add | 0 | public void updateUptime(int uptime) {
lastUptime = uptime;
} |
52285e8d-9bc4-436f-8480-02cc631efc8a | 0 | public boolean requiresPolygonIDs() {
// not needed in this case...
return false;
} |
b6231d0a-3ee6-4769-a56f-825593d7ba69 | 3 | protected boolean validaCampos(){
boolean valida = true;
if(txtCpf.getText().isEmpty() || txtDataNascimento.getText().isEmpty() ||
txtNome.getText().isEmpty()){
valida = false;
}else {
valida = true;
}
return valida;
} |
0f5930bc-ff0b-4fd2-8abc-7d68d377511e | 5 | @Override
public void valueChanged(TreeSelectionEvent e) {
if(component != null)
editor.remove(component);
DialogNode node = getSelectedNode();
if(node == null)
return;
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
if(node.type == EnumNodeType.CATEGORY){
DialogCategory category = (DialogCategory) node.getUserObject();
editor.add(BorderLayout.CENTER, component = new GuiCategoryEdit((DefaultTreeModel)tree.getModel(), node, category));
}
else if(node.type == EnumNodeType.DIALOG){
Dialog dialog = (Dialog) node.getUserObject();
editor.add(BorderLayout.CENTER, component = new GuiDialogEdit((DefaultTreeModel)tree.getModel(), node, dialog));
}
else if(node.type == EnumNodeType.OPTION){
DialogOption option = (DialogOption) node.getUserObject();
editor.add(BorderLayout.CENTER, component = new GuiOptionEdit(tree, node, option));
}
editor.getContentPane().validate();
editor.repaint();
} |
fc79c699-6605-4db5-90ee-4c4ff6cd8069 | 8 | public void forceKillProt()
{
tmr.cancel();
if(runningServer != null)
runningServer.kThread();
if(runningClient != null)
runningClient.kThread();
forceKill = true;
if(socket1 != null)
{
try
{
socket1.close();
}
catch(IOException e){}
}
if(server != null)
{
try
{
server.close();
}
catch(IOException e){}
}
if(client != null)
{
try
{
client.close();
}
catch(IOException e){}
}
} |
4d1eeb77-2c2c-4bcc-9624-8c10bacf47e5 | 7 | public Date getNextArena()
{
Date returnDate = null;
InaccurateTime newMax = Time.currentInnacurateTime();
ArrayList<Integer> ints = new ArrayList<>();
for (Date date : arenaMap.keySet())
{
ints.add((int) date.getInaccurateTime().toNumberValue());
}
int currentTime = getLargest(ints.toArray(new Integer[arenaMap.keySet().size()]));
for (Date date : arenaMap.keySet())
{
if (date.getDay() == Day.valueOf(java.util.Calendar.getInstance().get(java.util.Calendar.DAY_OF_WEEK)))
{
//System.out.println("curr iter " + date.getInaccurateTime().toNumberValue());
//System.out.println("max " + newMax.toNumberValue());
//System.out.println("current " + currentTime);
if (date.getInaccurateTime().toNumberValue() >= Time.currentInnacurateTime().toNumberValue())
{
if (date.getInaccurateTime().toNumberValue() <= currentTime)
{
if (date.getInaccurateTime().toNumberValue() <= newMax.toNumberValue())
{
System.out.println("curr iter " + date.getInaccurateTime().toNumberValue());
System.out.println("max " + newMax.toNumberValue());
System.out.println("current " + currentTime);
newMax = date.getInaccurateTime();
returnDate = date;
System.out.println(returnDate);
}
}
}
}
System.out.println(returnDate);
}
System.out.println(returnDate);
if (returnDate == null)
{
Date date = new Date(null, null);
date.setTomorrow();
returnDate = date;
}
return returnDate;
} |
1e8e6b2a-d417-4fc4-80bc-131adee9f10a | 3 | public Image getImage(){
switch(anim){
case 0: return bang0;
case 1: return bang1;
case 2: return bang2;
default: return bang1;
}
} |
dd5a869a-8922-4042-a4c9-5cb2188a5a67 | 1 | public void setLocked(boolean locked) {
if (mLocked != locked) {
notifyOfLockedStateWillChange();
mLocked = locked;
notifyOfLockedStateDidChange();
}
} |
199d3ed2-b011-444d-8791-e2a3bd5fac1a | 4 | public static void main(String[] args)
{
//Scanner initialisieren
scanner = new Scanner(System.in);
hero = new Hero();
System.out.println("Options: attack, arbitraryOption, quit");
//fancy Version einer Dauerschleife
while(scanner.hasNext())
{
//siehe getString()
String scannerString = getString();
if(scannerString.equals("attack"))
hero.attack();
if(scannerString.equals("arbitraryOption"))
//execute arbitrary action
System.out.println("Arbitrary Option executed");
if(scannerString.equals("quit"))
break;
}
} |
6fc67234-668b-4428-9c77-bd0d7faf1436 | 2 | public Texture getTexture(String tex) {
if(!textures.containsKey(tex)) {
try {
loadTexture(tex);
} catch(Exception e) {
System.out.println("Couldn't create texture!");
}
}
return textures.get(tex);
} |
f83bf255-6944-417f-a444-8e208c00672b | 3 | private static long toMillis(String value, TimeUnit unit) {
if(value != null && !value.isEmpty()) {
Matcher matcher = Pattern.compile("[0-9]+").matcher(value);
if(!matcher.find())
return 0;
return unit.toMillis(Integer.parseInt(matcher.group()));
}
return 0;
} |
bfea2c18-f7be-4b7a-8d18-e0754499ac7c | 8 | public boolean makeLocalBackup(String fileName)
{
//Copy local file to back-up location
try
{
String backupDirectory = this.downloadLocation + File.separator + "Local_Backup";
if(this.fileSystemManager.getDirectory(backupDirectory) == null)
{
this.fileSystemManager.createDirectory(backupDirectory);
}
//Check if copied file already exist in backup location
int i = 0;
boolean match = true;
String copylocationName = this.downloadLocation + File.separator + "Local_Backup" + File.separator + fileName;
while(match)
{
if(i == 0)
{
if(!this.fileSystemManager.fileExist(this.downloadLocation + File.separator + "Local_Backup", fileName))
{
match = false;
}
}
else
{
if(!this.fileSystemManager.fileExist(this.downloadLocation + File.separator + "Local_Backup", "(" + i + ")_" + fileName))
{
copylocationName = this.downloadLocation + File.separator + "Local_Backup" + File.separator + "(" + i + ")_" + fileName;
match = false;
}
}
i++;
}
if(this.fileSystemManager.copyFile(this.downloadLocation + File.separator + fileName , copylocationName))
{
try
{
deleteSystemFile(fileName);
}
catch(IOException e)
{
System.err.println("Could not delete file: " + e.getMessage());
return false;
}
}
else
{
System.err.println("Local file '" + fileName + "' can not be copied to backup location.");
return false;
}
}
catch(IOException e)
{
System.err.println("Local file '" + fileName + "' can not be backed up: " + e.getMessage());
return false;
}
return true;
} |
49fb6eee-ad18-40c1-be12-990ac86f985a | 2 | private void getFloorPlanGetXY(String line, CellDescription cellDescription) {
int startIndex;
int endIndex;
/*get x*/
startIndex = line.indexOf("xs") + 4;
endIndex = line.indexOf('\'', startIndex);
try {
cellDescription.locX(Integer.parseInt(line.substring(startIndex, endIndex)));
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Invalid File, x not an int", e);
}
/*get Y*/
startIndex = line.indexOf("ys") + 4;
endIndex = line.indexOf('\'', startIndex);
try {
cellDescription.locY(Integer.parseInt(line.substring(startIndex, endIndex)));
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Invalid File, Y not an int", e);
}
} |
4aee3a99-0b37-408a-82c9-6037ac434800 | 9 | @EventHandler(priority = EventPriority.LOW)
public void playerLogout( final PlayerDisconnectEvent e ) {
int dcTime = MainConfig.playerDisconnectDelay;
final BSPlayer p = PlayerManager.getPlayer( e.getPlayer() );
if ( dcTime > 0 ) {
BungeeSuite.proxy.getScheduler().schedule( BungeeSuite.instance, new Runnable() {
@Override
public void run() {
if ( PlayerManager.isPlayerOnline( p.getName() ) && ProxyServer.getInstance().getPlayer( e.getPlayer().getName() ) == null ) {
if ( !PlayerManager.kickedPlayers.contains( e.getPlayer() ) ) {
if ( MainConfig.broadcastProxyConnectionMessages ) {
PlayerManager.sendBroadcast( Messages.PLAYER_DISCONNECT_PROXY.replace( "{player}", p.getDisplayingName() ) );
}
} else {
PlayerManager.kickedPlayers.remove( e.getPlayer() );
}
PlayerManager.unloadPlayer( e.getPlayer().getName() );
}
}
}, MainConfig.playerDisconnectDelay, TimeUnit.SECONDS );
} else {
if ( PlayerManager.isPlayerOnline( p.getName() ) && ProxyServer.getInstance().getPlayer( e.getPlayer().getName() ) == null ) {
if ( !PlayerManager.kickedPlayers.contains( e.getPlayer() ) ) {
if ( MainConfig.broadcastProxyConnectionMessages ) {
PlayerManager.sendBroadcast( Messages.PLAYER_DISCONNECT_PROXY.replace( "{player}", p.getDisplayingName() ) );
}
} else {
PlayerManager.kickedPlayers.remove( e.getPlayer() );
}
PlayerManager.unloadPlayer( e.getPlayer().getName() );
}
}
} |
fa048813-5fd8-4c09-b477-74fc8a080804 | 9 | public void next(int width, int height) {
rotationAngle = (rotationAngle+10)%360;
// scaleVal goes from 0 to 1, then 1 to 0, then starts over
scaleArg = (float)((scaleArg == 1) ? scaleArg - 0.1 : scaleArg + 0.1);
scale = (float)Math.cos(scaleArg);
movClubX += inc_club;
movDiamondX += inc_diamond;
movHeart += inc_hearts;
movSpade += inc_spade;
scaleWidth = (float) ((movClubY/height)*0.35 + 0.15);
movClubY = 2*height/5 * (float)Math.sin(0.01*movClubX - 90) + 2*height/5;
movDiamondY = 2*height/5 * (float)Math.cos(0.01*movDiamondX) + 2*height/5;
if (movClubX + clubWidth*scaleWidth > width) {
movClubX = width - clubWidth*scaleWidth;
inc_club = -inc_club;
}
if (movClubX < 0) {
movClubX = 0;
inc_club = -inc_club;
}
if (movDiamondX + diamondWidth*scaleWidth > width) {
movDiamondX = width - diamondWidth*scaleWidth;
inc_diamond = -inc_diamond;
}
if (movDiamondX < 0) {
movDiamondX = 0;
inc_diamond = -inc_diamond;
}
if (movHeart + heartWidth*heartScale > width) {
movHeart = width - heartWidth*heartScale;
inc_hearts = -inc_hearts;
}
if (movHeart < 0) {
movHeart = 0;
inc_hearts = -inc_hearts;
}
if (movSpade + spadeHeight*spadeScale > height) {
movSpade = height - spadeHeight*spadeScale;
inc_spade = -inc_spade;
}
if (movSpade < 0) {
movSpade = 0;
inc_spade = -inc_spade;
}
} |
5fd53834-fe4d-4d41-a194-37799321d23d | 8 | private boolean isKingInCheck(Position kingPosition)
{
boolean inCheck = false;
String colorCheck = whitePlayerTurn() ? "Black" : "White";
// System.out.println("\nPieces that can move for " + colorCheck + "'s Team");
for(int y = 0; y < maxWidth; y++)
{
for(int x = 0; x < maxHeight; x++)
{
Piece currentPiece = board.getChessBoardSquare(x, y).getPiece();
if(currentPiece != board.getBlankPiece() && currentPiece.getPieceColor().equals(colorCheck))
{
Position positionCheck = new Position(x, y);
possibleMovesForPiece(currentPiece, positionCheck);
ArrayList<Position> pieceMoves = currentPiece.getPossibleMoves();
for(int i = 0; !inCheck && i < pieceMoves.size(); i++)
{
Position indexPosition = pieceMoves.get(i);
if(indexPosition.equals(kingPosition))
{
inCheck = true;
}
}
}
}
}
return inCheck;
} |
22bb67a9-70f2-481c-af80-23e3f477c45b | 8 | private void resubstitute(StringBuilder buffer) {
for (int c = 0; c < buffer.length(); c++) {
if (buffer.charAt(c) == '*') {
char x = buffer.charAt(c - 1);
buffer.setCharAt(c, x);
} else if (buffer.charAt(c) == '$') {
buffer.setCharAt(c, 's');
buffer.insert(c + 1, new char[]{'c', 'h'}, 0, 2);
} else if (buffer.charAt(c) == '§') {
buffer.setCharAt(c, 'c');
buffer.insert(c + 1, 'h');
} else if (buffer.charAt(c) == '%') {
buffer.setCharAt(c, 'e');
buffer.insert(c + 1, 'i');
} else if (buffer.charAt(c) == '&') {
buffer.setCharAt(c, 'i');
buffer.insert(c + 1, 'e');
} else if (buffer.charAt(c) == '#') {
buffer.setCharAt(c, 'i');
buffer.insert(c + 1, 'g');
} else if (buffer.charAt(c) == '!') {
buffer.setCharAt(c, 's');
buffer.insert(c + 1, 't');
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.