method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
81a2c4c2-044c-42c5-b8e8-d7c2715b211b
| 9
|
private void postPlugin(final boolean isPing) throws IOException {
// The plugin's description file containg all of the plugin data such as name, version, author, etc
final PluginDescriptionFile description = plugin.getDescription();
// Construct the post data
final StringBuilder data = new StringBuilder();
data.append(encode("guid")).append('=').append(encode(guid));
encodeDataPair(data, "version", description.getVersion());
encodeDataPair(data, "server", Bukkit.getVersion());
encodeDataPair(data, "players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length));
encodeDataPair(data, "revision", String.valueOf(REVISION));
// If we're pinging, append it
if (isPing) {
encodeDataPair(data, "ping", "true");
}
// Acquire a lock on the graphs, which lets us make the assumption we also lock everything
// inside of the graph (e.g plotters)
synchronized (graphs) {
final Iterator<Graph> iter = graphs.iterator();
while (iter.hasNext()) {
final Graph graph = iter.next();
for (Plotter plotter : graph.getPlotters()) {
// The key name to send to the metrics server
// The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top
// Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME
final String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName());
// The value to send, which for the foreseeable future is just the string
// value of plotter.getValue()
final String value = Integer.toString(plotter.getValue());
// Add it to the http post data :)
encodeDataPair(data, key, value);
}
}
}
// Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, encode(plugin.getDescription().getName())));
// Connect to the website
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY);
} else {
connection = url.openConnection();
}
connection.setDoOutput(true);
// Write the data
final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data.toString());
writer.flush();
// Now read the response
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
final String response = reader.readLine();
// close resources
writer.close();
reader.close();
if (response == null || response.startsWith("ERR")) {
throw new IOException(response); //Throw the exception
} else {
// Is this the first update this hour?
if (response.contains("OK This is your first update this hour")) {
synchronized (graphs) {
final Iterator<Graph> iter = graphs.iterator();
while (iter.hasNext()) {
final Graph graph = iter.next();
for (Plotter plotter : graph.getPlotters()) {
plotter.reset();
}
}
}
}
}
}
|
d827e60e-e3c2-4f1d-b746-e6c102761e33
| 3
|
@EventHandler
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
if (event.getPlayer().getItemInHand().getType() == Material.STRING) {
if (event.getRightClicked() instanceof Wolf) {
Wolf wolf = (Wolf) event.getRightClicked();
plugin.debugMessage("Is tamed: " + wolf.isTamed());
plugin.debugMessage("Owner: " + wolf.getOwner());
wolf.setTamed(wolf.isTamed() ? false : true);
plugin.debugMessage("Is tamed: " + wolf.isTamed());
plugin.debugMessage("Owner: " + wolf.getOwner());
}
event.getPlayer().setItemInHand(null);
}
plugin.cancelEvent(event);
plugin.debugMessage(event);
plugin.godMode(event);
}
|
f8d0727a-085a-4cf3-8adb-ff25d1697a73
| 3
|
@Override
public MedTypeDTO getMedTypeById(Long id) throws SQLException {
Session session = null;
MedTypeDTO medType = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
medType = (MedTypeDTO) session.load(MedTypeDTO.class, id);
} catch (Exception e) {
System.err.println("Error while getting medType!");
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return medType;
}
|
a5a8c3bc-37c1-4a15-b138-535902140cb3
| 8
|
public static double GetTrainingLikelyhood(int i, int j, int f, boolean isFaceClass)
{
if(f == 1 && isFaceClass)
{
return isFaceProbilities[i][j];
}
else if(f == 0 && isFaceClass)
{
return 1 - isFaceProbilities[i][j];
}
else if(f == 1 && !isFaceClass)
{
return nonFaceProbilities[i][j];
}
else if(f == 0 && !isFaceClass)
{
return 1 - nonFaceProbilities[i][j];
}
return -1.0;
}
|
db219ee1-2ab6-4529-a46c-6a218e042c02
| 3
|
private void addNeighbors(int i, int j) {
for (int k = i - 1; k <= i + 1; k++)
for (int m = j - 1; m <= j + 1; m++)
if (existNeighbor(k, m))
board[i][j].addNeighbor(board[k][m]);
}
|
f1c5309d-4384-44d8-b607-e888282742ba
| 5
|
public Gestion()
{
Restaurant r = new Restaurant();
Table gestion[] = r.restaurantCreate();
do
{
System.out.println("If you want to sit down press 1, to leave press 2, to display the restaurant state press 3,to close the programm press 4");
choice = scan.nextInt();
switch(choice)
{
case 1:
sitDown(gestion, r);
break;
case 2:
leave(gestion, r);
break;
case 3:
display(gestion, r);
case 4:
System.out.println("Programm is shutting donw!");
System.exit(0);
break;
}
}while(choice != 4);
display(gestion, r);
sitDown(gestion, r);
leave(gestion, r);
display(gestion, r);
}
|
c4aae314-8257-4531-bedd-95770a6df14c
| 7
|
protected StandardTile[][][] makeTiles(JSONObject dataRoot)
throws JSONException, DataFormatException {
JSONObject dataSize = dataRoot.getJSONObject("size");
int sizeZ = dataSize.getInt("z");
int sizeX = dataSize.getInt("x");
int sizeY = dataSize.getInt("y");
if (sizeZ <= 0 || sizeX <= 0 || sizeY <= 0) {
throw new DataFormatException("Invalid size");
}
StandardTile[][][] tiles = new StandardTile[sizeZ][sizeX][sizeY];
JSONArray dataTiles = dataRoot.getJSONArray("tiles");
JSONObject dataTileValues = dataRoot.getJSONObject("tile-values");
for (int z = 0; z < sizeZ; z++) {
JSONArray dataTilesZ = dataTiles.getJSONArray(z);
for (int x = 0; x < sizeX; x++) {
JSONArray dataTilesX = dataTilesZ.getJSONArray(x);
for (int y = 0; y < sizeY; y++) {
String tileId = dataTilesX.getString(y);
tiles[z][x][y] = this.getTile(tileId, dataTileValues);
if (tiles[z][x][y] instanceof CharacterTile) {
this.startCoord = new Coordinate(z, x, y);
this.startTile = (CharacterTile) tiles[z][x][y];
}
}
}
}
return tiles;
}
|
a4628c3a-b789-4c30-95a0-9d3a969b99ef
| 8
|
public Mesh(Vector3d[] verts, Triangle[] tris, Color3f a, Color3f d, Color3f s, Color3f e, float shininess, Shape3D shape) {
this.shape = shape;
vertices = new ArrayList<Vector3d>(verts.length);
edges = new ArrayList<Edge>(verts.length);
triangles = new ArrayList<Triangle>(tris.length);
for (int i = 0; i < verts.length; i++) {
vertices.add(verts[i]);
}
for (int i = 0; i < tris.length; i++) {
if (tris[i].v0 >= vertices.size() || tris[i].v1 >= vertices.size()
|| tris[i].v2 >= vertices.size()) {
throw new ArrayIndexOutOfBoundsException(
"One or more vertices do not exist. " + tris[i]);
}
Edge e0 = new Edge(tris[i].v0, tris[i].v1);
if (!edges.contains(e0)) {
edges.add(e0);
}
Edge e1 = new Edge(tris[i].v1, tris[i].v2);
if (!edges.contains(e1)) {
edges.add(e1);
}
Edge e2 = new Edge(tris[i].v2, tris[i].v0);
if (!edges.contains(e2)) {
edges.add(e2);
}
triangles.add(tris[i]);
}
signedDistanceFieldMin = new Vector3d();
signedDistanceFieldMax = new Vector3d();
signedDistanceFieldSize = new Vector3d();
calcSignedDistanceField();
}
|
465f7771-855b-4354-bd90-d457bbaebc2c
| 8
|
private void setEvents(){
dataTf.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent focusEvent) {
if(!controlDate){
JOptionPane.showMessageDialog(centerPanel, "Por favor, digite uma data no formato Brasileiro dia/mês/ano, sendo ano com 4 dígitos.");
controlDate = true;
}
}
@Override
public void focusLost(FocusEvent focusEvent) {
if(controlDate){
try{
String[] date_split = dataTf.getText().split("/");
Date data = new Date(Integer.parseInt(date_split[2]),(Integer.parseInt(date_split[1])-1),Integer.parseInt(date_split[0]));
controlDate = true;
}catch (Exception e){
JOptionPane.showMessageDialog(centerPanel, "Você digitou uma data inválida.");
dataTf.requestFocus();
controlDate = false;
}
}
}
});
cancelButtom.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(centerPanel, "Deseja realmente cancelar o cadastro de medias?", "Cadastro de Medias - Locafix",2);
if(result == 0){
dispose();
}
}
});
saveButtom.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Integer id = Integer.parseInt(idTf.getText());
String titulo = tituloTf.getText();
String[] date_split = dataTf.getText().split("/");
GregorianCalendar g = new GregorianCalendar();
g.set(Integer.parseInt(date_split[2]), Integer.parseInt(date_split[1])-1, Integer.parseInt(date_split[0]));
Date data_lanc = g.getTime();
String genero = generoTf.getText();
Integer classificacao = Integer.parseInt(classificacaoTf.getText());
Double preco = Double.parseDouble(precoTf.getText());
Object objDisponivel = disponivelTf.getSelectedObjects();
Boolean disponivel;
if(objDisponivel != null){
disponivel = true;
}else{
disponivel = false;
}
if(media == null){
media = new Media(titulo, data_lanc, genero, classificacao, preco, disponivel, id);
}else{
media.copy(new Media(titulo, data_lanc, genero, 12, preco, disponivel, media.getId()));
}
media.save();
Integer result = JOptionPane.showConfirmDialog(centerPanel,"Media Salva com sucesso!\nDeseja salvar outra media?","Cadastrar Media - Locafix", 0);
System.out.println(result);
if(result == 0){
dispose();
controller.createDialog(null);
}else {
if (result == 1) MediaSaveDialog.this.dispose();
}
}
});
}
|
875fce8b-d943-4a8e-b851-d874c6f82fe0
| 5
|
public boolean checkReset(){
int counter = 0;
for (int i=0; i < model.getWidth(); i++){
for (int j=0; j < model.getHeight(); j++){
if (buttons[i][j].isEnabled()){
counter++;
}
}
}
log.fine("Resetting of the gamefield is " + ((counter == 0) ? "valid" : "invalid" )+ ".");
System.out.println(counter);
if (counter == 0){
update();
counterForValue = 0;
return true;
}
return false;
}
|
0c54dfea-b318-4fb8-8f06-e1604ec94ec6
| 9
|
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = null;
if(sender instanceof Player){
player = (Player)sender;
if(args.length >= 1){
if(player.hasPermission("")){
player = _plugin.getServer().getPlayer(args[0]);
if(player == null){
sender.sendMessage(String.format("Unable to find player %s", args[0]));
return false;
}
}else{
sender.sendMessage("Permission denied");
return false;
}
}
}else{
if(args.length >= 1){
player = _plugin.getServer().getPlayer(args[0]);
if(player == null){
sender.sendMessage(String.format("Unable to find player %s", args[0]));
return false;
}
}else{
sender.sendMessage("You must be a player");
return false;
}
}
PlayerHome home = _plugin.getPlayerHome(player);
Location loc = null;
Location bedSpawn = player.getBedSpawnLocation();
if(home.contains(bedSpawn)){
loc = bedSpawn;
}else {
loc = home.getViableSpawnLocation(_plugin.getWorld());
}
if(loc != null){
player.teleport(loc);
}else{
if(sender == player){
sender.sendMessage("There is no valid spawn location in your home");
}else{
sender.sendMessage(String.format("There is no valid spawn location in %s's home", player.getName()));
}
return false;
}
return true;
}
|
306274ac-f9b4-4c95-905b-43670e9915b9
| 3
|
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(paused) {
g.setColor(Color.BLACK);
g.fillRect(1, 1, getWidth()-1, getHeight()-6);
g.setColor(Color.WHITE);
g.setFont(new Font("Monospaced", Font.BOLD, 15));
g.drawString("Click to resume", 100, 200);
} else if(gameOver) {
// Do game over animation
animateGameOver();
} else if (drawOver){
gameOver = true;
drawScreen(g);
drawOver = false;
g.setColor(Color.BLACK);
g.fillRect(45, 175, 250, 150);
g.setColor(Color.WHITE);
g.drawRect(45, 175, 250, 150);
g.setFont(new Font("Monospaced", Font.BOLD, 15));
g.drawString("Click to play again!", 75, 250);
} else {
drawScreen(g);
}
}
|
75a74d6c-f8ae-4803-952d-fd94b5004a62
| 1
|
@Override
public void push(T item) {
if (first == null) {
first = new Node<T>(null, item);
last = first;
} else {
last = setToNext(first, item);
}
size++;
}
|
d22f6bb4-e7f3-4990-8eb9-00880c390923
| 6
|
public static void shortPrintStackTrace(final Throwable main, final Throwable throwable, final Object cause)
{
final StackTraceElement[] causedTrace = main.getStackTrace();
final StackTraceElement[] trace = throwable.getStackTrace();
int m = trace.length - 1, n = causedTrace.length - 1;
while (m >= 0 && n >= 0 && trace[m].equals(causedTrace[n]))
{
m--;
n--;
}
final int framesInCommon = trace.length - 1 - m;
System.err.println(throwable);
for (int i = 0; i <= m; i++)
System.err.println("\tat " + trace[i]);
if (framesInCommon != 0)
System.err.println("\t... " + framesInCommon + " more");
// Recurse if we have a cause
final Throwable ourCause = throwable.getCause();
if (ourCause != null)
shortPrintStackTrace2(ourCause, trace, cause);
}
|
f42316c5-0f70-4aa8-bebb-a29fb7271f79
| 8
|
private void jBListarIncidentesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBListarIncidentesActionPerformed
// TODO add your handling code here:
int comuna = combo_comuna_reportetriple.getSelectedIndex();
int tipo = combo_tipo_reportetriple.getSelectedIndex();
int barrio = combo_barrio_reportetriple.getSelectedIndex();
if (comuna != 0 && tipo != 0 && barrio != 0) {
Comuna codigocomuna = controlador.buscarComuna(combo_comuna_reportetriple.getSelectedItem().toString());
TipoInscidente codigotipo = controlador.buscarTipoIncidente(combo_tipo_reportetriple.getSelectedItem().toString());
Barrio codigobarrio = controlador.buscarBarrio(combo_barrio_reportetriple.getSelectedItem().toString());
getControlador().cargarIncidentesPorComunaTipoYBarrio(codigocomuna.getCom_codigo(), codigotipo.getTipinc_codigo(), codigobarrio.getBar_codigo());
DefaultTableModel lstIncidente = (DefaultTableModel) tableListaIncidente.getModel();
if (!getControlador().getListaIncicomunatipoybarrio().isEmpty()) {
JOptionPane.showMessageDialog(null, "Se tienen " + getControlador().getListaIncicomunatipoybarrio().size()
+ " Incidentes Registrados en el barrio " + codigobarrio.getBar_nombre() + " de la Comuna " + codigocomuna.getCom_nombre() + " Y con el tipo de incidente "
+ codigotipo.getTipinc_descripcion());
tableListaIncidente.removeAll();
int rowCount = lstIncidente.getRowCount();
for (int i = 0; i < rowCount; i++) {
lstIncidente.removeRow(i);
}
for (int i = 0; i < getControlador().getListaIncicomunatipoybarrio().size(); i++) {
lstIncidente.addRow(new Object[]{getControlador().getListaIncicomunatipoybarrio().get(i).getComuna().getCom_nombre(),
getControlador().getListaIncicomunatipoybarrio().get(i).getBarrio().getBar_nombre(),
getControlador().getListaIncicomunatipoybarrio().get(i).getTipo_incidente().getTipinc_descripcion(),
getControlador().getListaIncicomunatipoybarrio().get(i).getInc_codigoIncidente(),
getControlador().getListaIncicomunatipoybarrio().get(i).getInc_descripcionIncidente(),
getControlador().getListaIncicomunatipoybarrio().get(i).getInc_fechaIncidente(),
getControlador().getListaIncicomunatipoybarrio().get(i).getUsuario().getTelefono()
});
}
} else {
JOptionPane.showMessageDialog(null, "No tiene Se Tienen Incidentes en el barrio " + codigobarrio.getBar_nombre() + " de la Comuna " + codigocomuna.getCom_nombre() + " Y con el tipo de incidente "
+ codigotipo.getTipinc_descripcion());
int rowCount = lstIncidente.getRowCount();
for (int i = 0; i < rowCount; i++) {
lstIncidente.removeRow(i);
}
if (lstIncidente.getRowCount() > 0) {
lstIncidente.removeRow(tableListaIncidente.getSelectedRow());
}
}
} else {
JOptionPane.showMessageDialog(null, "Debe Seleccionar Una Comuna, un Barrio y un Tipo de Incidente");
}
}//GEN-LAST:event_jBListarIncidentesActionPerformed
|
86114ef7-d87b-4274-b6bb-e69a84c70ec6
| 7
|
Class367_Sub2(NativeOpenGlToolkit class377, IndexLoader class45, Class269 class269) {
super(class377);
try {
aClass377_7296 = class377;
aClass269_7294 = class269;
if (class45 == null || !aClass269_7294.method2039(100)
|| !((NativeOpenGlToolkit) aClass377_7296).aBoolean9923)
aClass193_7293 = null;
else
aClass193_7293
= za_Sub2.method3442(34336,
class45.getChildArchive("gl",
"transparent_water"),
aClass377_7296, 4);
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929
(runtimeexception,
("ov.<init>(" + (class377 != null ? "{...}" : "null")
+ ',' + (class45 != null ? "{...}" : "null") + ','
+ (class269 != null ? "{...}" : "null") + ')'));
}
}
|
8f9a2eee-2792-412d-a626-519088b1c0a3
| 0
|
@Test
public void twoVerticesCompareCorrectly() {
Vertex v = new Vertex(0, 1);
Vertex w = new Vertex(0, 1);
Vertex u = new Vertex(0, 2);
assertTrue(v.compareTo(u) < 0);
assertTrue(u.compareTo(v) > 0);
assertTrue(w.compareTo(v) == 0);
}
|
c2d5ad45-1ea3-4427-b37a-a51169a080ca
| 4
|
static void plot() {
//Simulating a service running in the background
//It can force plot the calculator after a timer runs out!
while(true) {
try{Thread.sleep(1);}catch(Exception e){}
if(delayInt>0){
delayInt--;
if(delayInt==0){
GraphingCalculator.gui.plot();
}
}
}
}
|
9912b81c-8827-4a82-8ac1-de60196647b5
| 1
|
@Override
public boolean contains(int x, int y) {
int radbor = getSelect() ? CIRCLE_BORDER_RAD_SELECT : CIRCLE_BORDER_RAD_NOSELECT;
int xx = x - radbor, yy = y - radbor;
return (xx * xx) + (yy * yy) <= (radbor * radbor);
}
|
2dd12f50-ff58-430c-bdbb-25e5943ba55a
| 5
|
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Survey)) {
return false;
}
Survey other = (Survey) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
|
e9bc8d60-951c-4202-8b5e-b1cc6490dca2
| 3
|
static boolean isUniueCharBitVector(String s) {
if (s.length() > 256) {
return false;
}
int checker = 0;
for (int i=0; i<s.length(); i++) {
int val = s.charAt(i) - 'a';
if ((checker & (1 << val)) > 0) {
return false;
}
checker |= (1 << val);
}
return true;
}
|
1882ab8c-9b80-4b44-90d3-66aee3e6a661
| 6
|
private void loadProperties() {
properties = new HashMap<String, String>();
try {
BufferedReader reader = new BufferedReader(new FileReader(configFilePath));
String line = reader.readLine();
while(line != null) {
if (line.length()>0 && (! line.startsWith("#"))) {
String[] toks= line.split("=");
if (toks.length != 2) {
System.err.println("Warning: Could not read config property: " + line);
}
else {
properties.put(toks[0], toks[1]);
}
}
line = reader.readLine();
}
reader.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
System.err.println("Error : Could not read config file " + configFilePath);
}
}
|
fe3b4696-4942-4ee7-8882-316b330426e8
| 9
|
@Override
public void computeShortestPath() throws IllegalStateException
{
PriorityQueue<CostPath> nextCostPathQueue = new PriorityQueue<CostPath>();
if (startID == -1 || graph == null || weighing == null)
throw new IllegalStateException();
costMap = new HashMap<Integer, CostPath>();
CostPath startCostPath = new CostPath(startID, -1, -1, true, 0.0);
costMap.put(startID, startCostPath);
int curVID = startID;
boolean finished = false;
while (!finished)
{
Set<Integer> edgesOut = graph.getEdgesOf(curVID);
Iterator<Integer> itr = edgesOut.iterator();
CostPath curVIDCostPath = costMap.get(curVID);
while (itr.hasNext())
{//calculate and update costMap for all the targets of the edges
int eID = itr.next();
double curEdgeWeight = weighing.weight(graph.getAttribute(eID));
int nextVID = graph.getTarget(eID);
if (nextVID == curVID)
nextVID = graph.getSource(eID);
CostPath costPathToNextVertex = costMap.get(nextVID);
if (costPathToNextVertex == null)//create it
{
costPathToNextVertex = new CostPath(nextVID, curVID, eID, false, curEdgeWeight + curVIDCostPath.costToGetHere);
costMap.put(nextVID, costPathToNextVertex);
nextCostPathQueue.add(costPathToNextVertex);
}
else
{
//update as neccessary
double costToGetHere = curVIDCostPath.costToGetHere + curEdgeWeight;
if (costPathToNextVertex.costToGetHere > costToGetHere)
{
nextCostPathQueue.remove(costPathToNextVertex);
costPathToNextVertex.srcVID = curVID;
costPathToNextVertex.connectingEID = eID;
costPathToNextVertex.costToGetHere = costToGetHere;
nextCostPathQueue.add(costPathToNextVertex);
}
}
}
//find smallest cost non-completed costPath
if (nextCostPathQueue.isEmpty())
{
finished = true;
break;
}
CostPath smallest = nextCostPathQueue.remove();
smallest.complete = true;
curVID = smallest.vID;
}
needToCallComputeShortestPath = false;
}
|
8ac9bc85-d6fb-4103-ada0-d53193da66c3
| 6
|
@EventHandler
public void EnderDragonSlow(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getEnderDragonConfig().getDouble("EnderDragon.Slow.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getEnderDragonConfig().getBoolean("EnderDragon.Slow.Enabled", true) && damager instanceof EnderDragon && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, plugin.getEnderDragonConfig().getInt("EnderDragon.Slow.Time"), plugin.getEnderDragonConfig().getInt("EnderDragon.Slow.Power")));
}
}
|
4adffaac-760b-4843-b1d9-61b28aa4817a
| 9
|
public static void deleteResource(int resourceID) {
// Find in list
int listIndex = 0;
int listSize = resourceList.size();
for (int i = 1; i <= listSize; i++) {
if (resourceList.get(i - 1).intID == resourceID) {
listIndex = i - 1;
}
}
Resource resourceToDelete = resourceList.get(listIndex);
// Find creator
int creator = resourceToDelete.creatorProcess;
int listIndex2 = 0;
listSize = processList.size();
for (int i = 1; i <= listSize; i++) {
if (processList.get(i - 1).intID == creator) {
listIndex2 = i - 1;
}
}
Process creatorProcess = processList.get(listIndex2);
// remove from creator's list
int listIndex3 = 0;
listSize = creatorProcess.createdResList.size();
for (int i = 1; i <= listSize; i++) {
if (creatorProcess.createdResList.get(i - 1).intID == resourceID) {
listIndex3 = i - 1;
}
}
creatorProcess.createdResList.remove(listIndex3);
// Remove resource from all resource list
resourceList.remove(listIndex);
// Remove resource from current owners list
Process owner = findProcessByIntIdInList(processList,resourceToDelete.user.intID);
if (owner != null) {
int listIndex4 = 0;
listSize = owner.ownedResList.size();
for (int i = 1; i <= listSize; i++) {
if (owner.ownedResList.get(i - 1).intID == resourceToDelete.intID) {
listIndex4 = i - 1;
}
}
owner.ownedResList.remove(listIndex4);
}
}
|
100fc8d5-61fb-485f-b9f1-3013b0a9fc68
| 3
|
public void close() {
try{
if(connection!=null && !connection.isClosed())
{
connection.close();
connection=null;
}
}catch(SQLException ex)
{
ex.printStackTrace();
}
}
|
988a8b1e-f610-44d9-ad83-d6ce22eb1376
| 7
|
public String AddCart() {
ProductService service = new ProductService();
try {
// if quantity mentioned on checkout.jsp is 0 display error message
// without adding item to the shopping cart.
if (item.getQuantity() != 0) {
Item item_temp = service.getItem(item.getCategory(),
item.getTitle(), item.getLeadSinger(),
item.getQuantity());
if (item_temp != null) {
this.errorMessage = item_temp.getErrorMessage();
totalprice = (item_temp.getPrice() * item_temp
.getQuantity()) + totalprice;
Item temp = hasItem(shoppingcart, item_temp);
if (temp != null) {
shoppingcart.remove(temp);
temp.setQuantity(temp.getQuantity()
+ item_temp.getQuantity());
shoppingcart.add(temp);
} else
shoppingcart.add(item_temp);
} else {
this.errorMessage = "No Item Found ";
}
} else {
this.errorMessage = " No Item Added . Please Specify Quantity More than 0";
}
} catch (ConnectException e) {
this.errorMessage = e.getMessage();
e.printStackTrace();
} catch (SQLException e) {
this.errorMessage = e.getMessage();
} catch (TooManyItemsFoundException e) {
this.errorMessage = e.getMessage();
} catch (NoStockException e) {
this.errorMessage = "Requested Quantity Not Available. Quantity set to Available stock";
}
return "Add";
}
|
7f06f3d1-d08c-4de8-94f1-eead1bf2c043
| 9
|
public Bullet updateControl(final Input input) {
if (input.isKeyDown(Input.KEY_A) || input.isKeyDown(Input.KEY_LEFT)) {
this.angle -= Constants.THRUST_ANGLE;
} else if (input.isKeyDown(Input.KEY_D) || input.isKeyDown(Input.KEY_RIGHT)) {
this.angle += Constants.THRUST_ANGLE;
}
if (input.isKeyDown(Input.KEY_W) || input.isKeyDown(Input.KEY_UP)) {
this.acceleration.x = (int)(Math.sin(angle) * Constants.THRUST);
this.acceleration.y = -(int)(Math.cos(angle) * Constants.THRUST);
} else if (input.isKeyDown(Input.KEY_S) || input.isKeyDown(Input.KEY_DOWN)) {
this.acceleration.x = -(int)(Math.sin(angle) * Constants.THRUST);
this.acceleration.y = (int)(Math.cos(angle) * Constants.THRUST);
}
if (input.isKeyDown(Input.KEY_SPACE)) {
return new Bullet();
}
return null;
}
|
2cecaf20-792a-4459-b25f-abd2f49df0f3
| 5
|
public boolean populate(OggPacket packet) {
// TODO Finish the flac support properly
if (type == OggStreamIdentifier.OGG_FLAC) {
if (tags == null) {
tags = new FlacTags(packet);
return true;
} else {
// TODO Finish FLAC support
return false;
}
}
OggStreamPacket sPacket = createNext(packet);
if (sPacket instanceof OggAudioTagsHeader) {
tags = (OggAudioTagsHeader)sPacket;
// Are there more headers to come?
if (type == OggStreamIdentifier.OGG_VORBIS) {
return true;
} else {
return false;
}
}
if (sPacket instanceof OggAudioSetupHeader) {
setup = (OggAudioSetupHeader)sPacket;
// Setup is always last
return false;
}
throw new IllegalArgumentException("Expecting header packet but got " + sPacket);
}
|
e68e4c1e-e22f-4851-888b-bc31acc44f24
| 7
|
private synchronized void messageReceivedWithTimestamp(int node, Message msg, long timestamp, boolean plot) {
if (slave != null && msg instanceof SnoopBCMsg) {
SnoopBCMsg sm = (SnoopBCMsg) msg;
//Logger.getLogger(Datasource.class.getName()).log(Level.INFO, String.format("Msg from %d", sm.get_nodeid()));
for (int i = 0; i < 10; i++) {
LinkInfo li = new LinkInfo(i + 1, sm.get_nodeid(), sm.get_othernodes()[i], timestamp);
if (plot == false) {
li.getMetaData().put("DoNotPlot", null);
}
slave.recvLinkInfo(li);
}
}
synchronized (outSync) {
if (out != null && msg instanceof SnoopBCMsg) {
try {
out.writeObject(new Packet(System.nanoTime() - startTime, node, msg));
} catch (IOException ex) {
//Logger.getLogger(Datasource.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
|
8aa9aa92-0a99-46aa-91bf-4dcf3d63dfed
| 9
|
public void compile() throws IOException {
GlobalAppHandler.getInstance().disableBackButton();
File folder = new File(FileUtilities.getUnintegratedDirectory() + File.separator + "notes");
Logger.getInstance().log("Folder path: " + folder.getAbsolutePath());
List<File> files = new ArrayList<File>();
FileUtilities.listFilesInDirectory(folder, files);
File notesToCheck = new File(FileUtilities.getNonsyncedDirectory() + File.separator + "event" + File.separator + "notes_to_check.txt");
if (!notesToCheck.exists()) {
notesToCheck.getParentFile().mkdirs();
notesToCheck.createNewFile();
}
BufferedWriter toCheck = new BufferedWriter(new FileWriter(notesToCheck, true));
if (files != null) {
for (File unintegratedFile : files) {
File compiledFile = new File(FileUtilities.getSyncedDirectory() + File.separator + "notes" + File.separator + unintegratedFile.getName());
if (!compiledFile.getParentFile().exists()) {
compiledFile.getParentFile().mkdir();
}
if (!compiledFile.exists()) {
compiledFile.createNewFile();
}
bw = new BufferedWriter(new FileWriter(compiledFile, true));
br = new BufferedReader(new FileReader(unintegratedFile));
String line;
boolean firstLine = false;
if (compiledFile.length() == 0) {
firstLine = true;
}
while ((line = br.readLine()) != null) {
if (!firstLine) {
bw.newLine();
}
firstLine = false;
bw.write(line);
}
if (unintegratedFile.length() != 0) {
toCheck.write(unintegratedFile.getName());
toCheck.newLine();
}
toCheck.flush();
bw.flush();
bw.close();
br.close();
unintegratedFile.delete();
}
}
toCheck.close();
GlobalAppHandler.getInstance().enableBackButton();
setMode(new MainMenu());
}
|
e5007f3f-ef09-47e5-9f12-a3707aafb9ba
| 3
|
public Type pop() {
size--;
if (size < 0)
throw new IndexOutOfBoundsException("No more items in the stack!");
Type data = stack[size];
stack[size] = null;
if (size > 0 && size == stack.length / 4)
resize(stack.length / 2);
return data;
}
|
0651b01e-973b-4ead-b8af-ce5c1151884a
| 0
|
public void setCache(Cache cache) {
this.cache = cache;
}
|
e0ba96ac-8943-4ded-b3e1-0637786e182a
| 9
|
private int numKings( int player ) {
int total = 0;
if( player == 1 ){
//counts how many pieces are player ones
for( int row = 0 ; row < 8 ; row++ )
{
for( int column = (row + 1) % 2 ; column < MAX_COLUMNS ; column += 2 )
{
if( isPlayerOne( new Coordinate( column, row) ) ){
if( board[ row ][ column ].toString().equals(Checker.ONE_KING.toString()) ){
total++;
}
}
}
}
return total;
}
//counts how many pieces are player twos
for( int row = 0 ; row < 8 ; row++ )
{
for( int column = (row + 1) % 2 ; column < MAX_COLUMNS ; column += 2 )
{
if( isPlayerTwo( new Coordinate( column, row) ) ){
if( board[ row ][ column ].toString().equals(Checker.TWO_KING.toString()) ){
total++;
}
}
}
}
return total;
}
|
a0070bfa-2ef0-4bc3-a384-e3c86005ed77
| 7
|
public void valueChanged(ListSelectionEvent __event) {
try {
Object source = __event.getSource();
ListModel listmodel;
Vector contents;
Class selection;
int val;
int _MAX;
if (source == _classes) {
listmodel = _classes.getModel();
selection = (Class) listmodel.getElementAt(_classes.getSelectedIndex());
contents = new Vector();
listmodel = _players.getModel();
_MAX = listmodel.getSize();
for (int i=0; i < _MAX; i++) {
contents.add(listmodel.getElementAt(i));
}
if (!contents.contains(selection)) {
contents.add(selection);
_players.setListData(contents);
_numplayers.setText(Integer.toString(contents.size()));
repaint();
}
}
if (source == _players) {
val = _players.getSelectedIndex();
contents = new Vector();
listmodel = _players.getModel();
_MAX = listmodel.getSize();
for (int i=0; i < _MAX; i++) {
if (i != val) {
contents.add(listmodel.getElementAt(i));
}
}
_players.setListData(contents);
_numplayers.setText(Integer.toString(contents.size()));
repaint();
}
} catch (Exception EXC) {
System.out.println(EXC.getMessage());
EXC.printStackTrace();
}
}
|
97f5999a-2ccd-4bd7-bf5a-593d67718646
| 9
|
public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) {
this.plugin = plugin;
this.type = type;
this.announce = announce;
this.file = file;
this.id = id;
this.updateFolder = plugin.getServer().getUpdateFolder();
final File pluginFile = plugin.getDataFolder().getParentFile();
final File updaterFile = new File(pluginFile, "Updater");
final File updaterConfigFile = new File(updaterFile, "config.yml");
if (!updaterFile.exists()) {
updaterFile.mkdir();
}
if (!updaterConfigFile.exists()) {
try {
updaterConfigFile.createNewFile();
} catch (final IOException e) {
plugin.getLogger().severe("The updater could not create a configuration in " + updaterFile.getAbsolutePath());
e.printStackTrace();
}
}
this.config = YamlConfiguration.loadConfiguration(updaterConfigFile);
this.config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n'
+ "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n'
+ "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration.");
this.config.addDefault("api-key", "PUT_API_KEY_HERE");
this.config.addDefault("disable", false);
if (this.config.get("api-key", null) == null) {
this.config.options().copyDefaults(true);
try {
this.config.save(updaterConfigFile);
} catch (final IOException e) {
plugin.getLogger().severe("The updater could not save the configuration in " + updaterFile.getAbsolutePath());
e.printStackTrace();
}
}
if (this.config.getBoolean("disable")) {
this.result = UpdateResult.DISABLED;
return;
}
String key = this.config.getString("api-key");
if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) {
key = null;
}
this.apiKey = key;
try {
this.url = new URL(Updater.HOST + Updater.QUERY + id);
} catch (final MalformedURLException e) {
plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid.");
this.result = UpdateResult.FAIL_BADID;
e.printStackTrace();
}
this.thread = new Thread(new UpdateRunnable());
this.thread.start();
}
|
8f146d87-4935-48f9-a11b-725d87b0feb5
| 9
|
public static void parse(String filename, int n) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
String line = null;
// drop the header line
line = br.readLine();
int abs_min = Integer.MAX_VALUE, abs_max = Integer.MIN_VALUE, tmp0, tmp1;
double avg_min = Double.MAX_VALUE, avg_max = Double.MIN_VALUE, avg_avg = 0, tmp2;
String tab[];
int counter = 0;
LinkedList<Integer> max_times = new LinkedList<Integer>();
LinkedList<Integer> min_times = new LinkedList<Integer>();
LinkedList<Double> avg_times = new LinkedList<Double>();
while ((line = br.readLine()) != null) {
if (line.matches("\\s*")) {
continue;
}
counter++;
tab = line.split("\\s+");
// Max
tmp0 = Integer.parseInt(tab[0]);
max_times.add(tmp0);
// Min
tmp1 = Integer.parseInt(tab[1]);
min_times.add(tmp1);
// Avg
tmp2 = Double.parseDouble(tab[2]);
avg_times.add(tmp2);
// Update the absolute maximum
if (abs_max < tmp0) {
abs_max = tmp0;
}
// Update the absolute minimum
if (abs_min > tmp1) {
abs_min = tmp1;
}
// Update the average sum
avg_avg += tmp2;
// Update the maximum average
if (tmp2 > avg_max) {
avg_max = tmp2;
}
// Update the minimum average
if (tmp2 < avg_min) {
avg_min = tmp2;
}
}
br.close();
// sort lists
Collections.sort(max_times);
Collections.sort(min_times);
Collections.sort(avg_times);
double avg = 0;
int toRemove = 12 * counter / 100;
for (int i = 0; i < toRemove; i++) {
max_times.removeFirst();
max_times.removeLast();
min_times.removeFirst();
min_times.removeLast();
avg_times.removeFirst();
avg_times.removeLast();
}
avg_avg /= counter;
FileWriter fw = new FileWriter(filename + "_merge.txt");
int size = min_times.size();
fw.write("max \t min \t avg\n");
for (int i = 0; i < size; i++) {
int x_max = max_times.get(i);
int x_min = min_times.get(i);
double x_avg = avg_times.get(i);
avg += x_avg;
fw.write(x_max + " \t " + x_min + " \t " + x_avg + "\n");
}
avg /= size;
fw.write("-------------- STATS --------------\n");
fw.write("ABS MAX: " + max_times.getLast() + " ms\n");
fw.write("ABS MIN: " + min_times.getFirst() + " ms\n");
fw.write("AVG MAX: " + avg_times.getLast() + " ms\n");
fw.write("AVG MIN: " + avg_times.getFirst() + " ms\n");
fw.write("AVG AVG: " + avg + " ms\n");
fw.flush();
fw.close();
// ---------------------------
String homeDir = System.getProperty("user.home");
File file = new File(homeDir + File.separatorChar + "stats.txt");
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
FileLock lock = null;
try {
lock = channel.lock();
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
buffer.put((n + "\t" + avg + "\n").getBytes()).flip();
long pos = channel.size();
channel.write(buffer, pos);
} catch (Exception exp) {
exp.printStackTrace();
} finally {
lock.release();
}
channel.close();
// Print out the average max, min and avg
System.err.println("\n\nAVG MAX: " + avg_times.getLast() + " ms");
System.err.println("AVG MIN: " + avg_times.getFirst() + " ms");
System.err.println("AVG AVG: " + avg + " ms\n\n");
}
|
ba159757-1bfb-41e2-bf41-6efdcb3b7b36
| 7
|
public Vector<String> enumDatabases () {
Vector<String> instances = new Vector<String>();
Connection session = null;
try {
// connect to management database
session = connect ("postgres", "postgres", "postgres");
if (session == null) {
errMsg = "Can't connect to management database";
return instances;
}
Statement stmt = session.createStatement();
// select all available database instances
if (stmt.execute ("select datname from pg_database;")) {
ResultSet r = stmt.getResultSet();
if (r != null) {
while (r.next()) {
// add instance name to list
String name = r.getString ("datname");
instances.add (name);
}
}
}
errMsg = null;
} catch (SQLException e) {
errMsg = e.getMessage();
}
finally {
// close opened session
if (session != null)
try { session.close(); } catch (SQLException e) { }
}
// return list of visible databases.
return instances;
}
|
768fa883-cefb-4343-982d-59b840593122
| 4
|
public static void printSpiral(int[][] spiral) {
for (int y = 0; y < spiral.length; y++) {
for (int x = 0; x < spiral.length; x++) {
int value = spiral[x][y];
String start = "";
if (value < 100) {
start += " ";
}
if (value < 10) {
start += " ";
}
System.out.print(start + value + " ");
}
System.out.println();
}
}
|
78be8bbf-2ac0-4fec-a0f0-ef7c74487c81
| 1
|
void moveY(boolean down) {
if (down)
y += speed;
else y -= speed;
}
|
14e1b779-01e1-46a1-834e-9c63f761ffdb
| 4
|
@Override
protected boolean isProgramRunning(String programName) throws IOException, InterruptedException {
logger.detailedTrace("Obtaining information about running instances of " + programName);
Process process = new ProcessBuilder("wmic", "Path", "win32_process", "Where",
commandLike(programName)).start();
BufferedReader outputReader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String outputMessage;
while ((outputMessage = outputReader.readLine()) != null) {
if (!outputMessage.isEmpty() && !outputMessage.startsWith("Caption")
&& !outputMessage.startsWith("WMIC.exe"))
return true;
}
return false;
}
|
3ac918d9-92cc-4a0c-a511-8917342ea640
| 4
|
private int indexOf(Vertex v) {
Vertex r;
if (v != null) {
for (int i = 0; i < adjacencyList.getSize(); i++) {
r = adjacencyList.get(i).min();
if (r != null) {
if (r.equals(v)) {
return i;
}
}
}
}
return adjacencyList.getSize();
}
|
00a3dd76-743d-4e6d-ad53-3b64d6f7ee40
| 0
|
public MyStatusAdapter(ApplicationConfParser applicationConfParser) throws FileNotFoundException, UnsupportedEncodingException{
//hbaseConfModel = applicationConfParser.getHbaseConfModel();
mediaConfModel = applicationConfParser.getMediaConfModel();
newBuffer();
}
|
b762c4d0-8ce4-481d-b9ea-2bfc6c30b04a
| 4
|
@Override
public void startElement(String uri, String localName, String name,
Attributes atts) throws SAXException {
super.startElement(uri, localName, name, atts);
if (numLayers > 0) {
if (secondElementName.equalsIgnoreCase(localName)) {
if (shouldRecord(uri, localName, name, atts)) {
numLayersForRecording = 1;
} else if (numLayersForRecording > 0) {
++numLayersForRecording;
}
}
}
}
|
747e2d21-9f7b-429e-9fd7-4a3e041cf9b5
| 9
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FPSectionNode other = (FPSectionNode) obj;
if (node == null) {
if (other.node != null)
return false;
} else if (!node.equals(other.node))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
|
2ca5d9d6-0548-48f8-8743-6b18b9557be3
| 8
|
public void processEvent(Event event)
{
if (event.getType() == Event.COMPLETION_EVENT)
{
System.out.println(_className + ": Receive a COMPLETION_EVENT, " + event.getHandle());
return;
}
System.out.println(_className + ".processEvent: Received Login Response... ");
if (event.getType() != Event.OMM_ITEM_EVENT)
{
System.out.println("ERROR: " + _className + " Received an unsupported Event type.");
_mainApp.cleanup(-1);
return;
}
OMMItemEvent ie = (OMMItemEvent)event;
OMMMsg respMsg = ie.getMsg();
if (respMsg.getMsgModelType() != RDMMsgTypes.LOGIN)
{
System.out.println("ERROR: " + _className + " Received a non-LOGIN model type.");
_mainApp.cleanup(-1);
return;
}
if (respMsg.isFinal())
{
System.out.println(_className + ": Login Response message is final.");
GenericOMMParser.parse(respMsg);
_mainApp.processLogin(false);
return;
}
if ((respMsg.getMsgType() == OMMMsg.MsgType.STATUS_RESP) && (respMsg.has(OMMMsg.HAS_STATE))
&& (respMsg.getState().getStreamState() == OMMState.Stream.OPEN)
&& (respMsg.getState().getDataState() == OMMState.Data.OK))
{
System.out.println(_className + ": Received Login STATUS OK Response");
GenericOMMParser.parse(respMsg);
_mainApp.processLogin(true);
}
else
{
System.out.println(_className + ": Received Login Response - "
+ OMMMsg.MsgType.toString(respMsg.getMsgType()));
GenericOMMParser.parse(respMsg);
}
}
|
c541299d-c943-4e4f-957a-c008172a387d
| 0
|
public static GeneralValidator isLessThan() {
return LESS_THAN_VALIDATOR;
}
|
4c4d5c26-fe03-4a40-a1db-ec29ed59baf1
| 8
|
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
MOB target=mob;
if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
if(!CMLib.flags().canSpeak(mob))
{
mob.tell(L("You can't speak!"));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
// now see if it worked
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSG_QUIETMOVEMENT,L("<S-NAME> concentrate(s) <S-HIS-HER> strength."));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,mob.isInCombat()?2:4);
}
}
else
return beneficialVisualFizzle(mob,null,L("<S-NAME> lose(s) concentration."));
// return whether it worked
return success;
}
|
04593b46-6275-4816-a6de-d919fb5ed793
| 5
|
public List<PaidVo> getUnPaidOutDetail(int oid, Date from, Date to, int uid) {
List<InDetail> result = inDetailDao.queryInDetail(-1, oid, -1, -1, from, to, uid);
//Collections.sort(result);
//Collections.reverse(result);
Map<Integer, Double> shouldPaid = new HashMap<Integer, Double>();
Map<Integer, Double> hadPaid = new HashMap<Integer, Double>();
Map<Integer, String> dateMap = new HashMap<Integer, String>();
Map<Integer, String> fruitMap = new HashMap<Integer, String>();
Map<Integer, String> ownerMap = new HashMap<Integer, String>();
for (InDetail inDetail : result) {
int id = inDetail.getId();
if (shouldPaid.get(id) != null) {
shouldPaid.put(id, shouldPaid.get(id) + inDetail.getMoney());
} else {
shouldPaid.put(id, inDetail.getMoney());
dateMap.put(id, inDetail.getCreateAt());
fruitMap.put(id, inDetail.getFruitName());
ownerMap.put(id, inDetail.getOwnerName());
}
if (hadPaid.get(id) != null) {
hadPaid.put(id, hadPaid.get(id) + inDetail.getPaidMoney());
} else {
hadPaid.put(id, inDetail.getPaidMoney());
}
}
List<PaidVo> list = new ArrayList<PaidVo>();
for (Map.Entry<Integer, Double> m : shouldPaid.entrySet()) {
int key = m.getKey();
if (hadPaid.get(key) - m.getValue() < 0) {
PaidVo paidVo = new PaidVo();
paidVo.setOid(key);
paidVo.setFruitName(fruitMap.get(key));
paidVo.setName(ownerMap.get(key));
paidVo.setShouldPaid(m.getValue());
paidVo.setHadPaid(hadPaid.get(key));
paidVo.setCreateAt(dateMap.get(key));
list.add(paidVo);
}
}
return list;
}
|
743c8e29-4530-4bb4-946b-9b36588ef1ba
| 5
|
public static void resetTimer(String timerName, JProgressBar bar) {
for (Timer t : timerList) {
if (t.getName().equals(timerName)) {
if (t.isNormalTimer()){
t.setStartingTime(System.currentTimeMillis());
bar.setForeground(Color.black);
} else if (t.getDurationTotal() == DAY_LENGTH){
t.setStartingTime(Math.floor(System.currentTimeMillis()/DAY_LENGTH)*DAY_LENGTH);
} else if (t.getDurationTotal() == WEEK_LENGTH){
t.setStartingTime((((Math.floor((System.currentTimeMillis()+DAY_LENGTH)/WEEK_LENGTH))*WEEK_LENGTH)-DAY_LENGTH));
}
saveTimers();
break;
}
}
}
|
8e1bc1e2-45f5-4630-abf6-98b15e2b4ece
| 1
|
@Override
protected void setReaction(Message message) {
String result = executeCmd(message.text.replaceAll(" ", ""), message.author);
if(result != null)
reaction.add(result);
}
|
d88c8252-e121-44f6-a947-6a66a55dee49
| 7
|
public void atualizar() {
jComboBoxEdicao.removeAllItems();
jComboBoxAnoPublicacao.removeAllItems();
jComboBoxAutor.removeAllItems();
jComboBoxEditora.removeAllItems();
jComboBoxCategoria.removeAllItems();
jComboBoxPublico.removeAllItems();
jComboBoxFormato.removeAllItems();
jTextFieldTitulo.setText(null);
jTextFieldDescricao.setText(null);
for (Edicao edicao : listaView.getMaterialComboBox().getEdicoes()) {
jComboBoxEdicao.addItem(edicao);
}
for (AnoPublicacao anoPublicacao : listaView.getMaterialComboBox().getAnosPublicacoes()) {
jComboBoxAnoPublicacao.addItem(anoPublicacao);
}
for (Autor autor : listaView.getMaterialComboBox().getAutores()) {
jComboBoxAutor.addItem(autor);
}
for (Editora editora : listaView.getMaterialComboBox().getEditoras()) {
jComboBoxEditora.addItem(editora);
}
for (Categoria categoria : listaView.getMaterialComboBox().getCategorias()) {
jComboBoxCategoria.addItem(categoria);
}
for (Publico publico : listaView.getMaterialComboBox().getPublicos()) {
jComboBoxPublico.addItem(publico);
}
for (Formato formato : listaView.getMaterialComboBox().getFormatos()) {
jComboBoxFormato.addItem(formato);
}
}
|
458e58c4-5510-4d1f-b033-936ef533f264
| 7
|
protected static List<Class> getSupers(Class type) {
if (type.isAssignableFrom(Model.class))
throw new IllegalArgumentException(EXC_NOTAMODEL);
Class[] interfaces = type.getInterfaces();
List<Class> sC = new ArrayList<Class>();
boolean subclass = true;
for (Class i : interfaces)
if (i.equals(Model.class)) subclass = false;
if (subclass)
for (Class i : interfaces) {
if (Model.class.isAssignableFrom(i) &&
!i.equals(type)) sC.add(i);
}
return sC;
}
|
99819bc5-ee32-4935-9e6b-f10c9a8c21ce
| 3
|
private void fireActionListeners(ActionEvent e) {
if (this.listeners == null) {
return;
}
for (int a = 0; a < this.listeners.size(); a++) {
ActionListener l = this.listeners.get(a);
try {
l.actionPerformed(e);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
|
730bb0b9-f22b-4fb9-a854-fbdd0fdd1cc5
| 5
|
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
int nCases = Integer.parseInt(in.readLine().trim());
for (int nCase = 0; nCase < nCases; nCase++) {
in.readLine();
int[] mn = readInts(in.readLine());
m = mn[0];
n = mn[1];
a = new char[m][n];
if (nCase != 0)
out.append('\n');
for (int i = 0; i < m; i++) {
char[] row = in.readLine().trim().toCharArray();
for (int j = 0; j < n; j++)
a[i][j] = Character.toLowerCase(row[j]);
}
int queries = Integer.parseInt(in.readLine().trim());
for (int i = 0; i < queries; i++) {
String word = in.readLine().trim().toLowerCase();
ans = new Point(m, n);
solve(word);
out.append(++ans.x + " " + ++ans.y + "\n");
}
}
System.out.print(out);
}
|
481d8bbd-eee0-4a41-8505-121a56736cb5
| 2
|
public static String doCensor(String input) {
System.currentTimeMillis();
char dest[] = input.toCharArray();
Censor.method495(dest);
String censoredInput = new String(dest).trim();
dest = censoredInput.toLowerCase().toCharArray();
String s2 = censoredInput.toLowerCase();
Censor.method505(dest);
Censor.method500(dest);
Censor.method501(dest);
Censor.method514(dest);
for (String exception : Censor.exceptions) {
for (int i = -1; (i = s2.indexOf(exception, i + 1)) != -1;) {
char exceptions[] = exception.toCharArray();
System.arraycopy(exceptions, 0, dest, i, exceptions.length);
}
}
Censor.method498(censoredInput.toCharArray(), dest);
Censor.method499(dest);
System.currentTimeMillis();
return new String(dest).trim();
}
|
2a6bb4c2-a6e4-40f2-bba3-d561226fc667
| 1
|
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((dateTime == null) ? 0 : dateTime.hashCode());
return result;
}
|
6c42e770-023e-4560-8e69-0a71ee08f52b
| 0
|
public Queue() {}
|
b722ca39-c217-44e5-82ee-4f44c44b6e69
| 1
|
public void updateTable()
{
myXYZPanel.remove(myXYZDisplay);
myXYZDisplay = new JTable(1, myLemma.getW().length());
myXYZDisplay.setEnabled(false);
String s = myLemma.getW();
for(int i = 0; i < s.length(); i++)
myXYZDisplay.setValueAt(s.substring(i, i + 1), 0, i);
myXYZPanel.add(myXYZDisplay, BorderLayout.CENTER);
}
|
211717c4-0ac7-4cef-a400-5088bfdccf5a
| 3
|
@SuppressWarnings("unchecked")
private Map<OrderField, String> getMarketOrderPaths(Document doc)
{
Map<OrderField, String> toReturn = new HashMap<OrderField, String>();
for (OrderField f : OrderField.values())
{
String path = f.getPath();
if (path != null)
{
List<DefaultElement> list = doc.selectNodes(path);
for (Iterator<DefaultElement> iter = list.iterator(); iter.hasNext();)
{
DefaultElement attribute = iter.next();
String url = attribute.getText();
toReturn.put(f, url);
}
}
}
return toReturn;
}
|
25516261-91e6-4692-b4c5-b064635ba55b
| 0
|
public void addAttempt(String attempt)
{
myAttempts.add(attempt);
}
|
f90cf0c0-6d2c-454b-9e5e-06241257e562
| 4
|
public static Team getTeamFromJson(JSONObject obj){
if(obj ==null)
return null;
Team team = new Team();
Object value;
JSONArray jsonArray;
JSONObject tmpObj;
User tmpUser;
value = obj.get("id_team");
if(value!=null)
{
team.setId_team(Integer.parseInt(value.toString()));
}
jsonArray =(JSONArray) obj.get("members");
for(int i=0;i<jsonArray.size();i++)
{
tmpObj = (JSONObject)jsonArray.get(i);
tmpUser =User.getUserFromJson(tmpObj);
if(tmpUser.getId()!=null)
team.put(tmpUser.getId(), tmpUser);
}
return team;
}
|
ae1a0c85-9805-4ea3-b40b-d5336047a239
| 0
|
public String getNumber() {
return number;
}
|
dd7926c1-4ce9-4806-b03b-d9e5aea28425
| 5
|
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
switch (cmd){
case CMD_LOGIN:
String login = loginField.getText();
String pass = getHash(new String(passwordField.getPassword()));
if (login.isEmpty() || pass.isEmpty()){
return;
}else if (logicSystem.login(login, pass) != null){
JFrame mainUI = new MainUI(logicSystem);
centerFrame(mainUI);
LoginUI.this.setVisible(false);
mainUI.setVisible(true);
} else {
alertMessage.setText("Invalid login/pass!");
}
break;
case CMD_REGISTRATION:
JFrame regFrame = new RegUI(logicSystem);
centerFrame(regFrame);
LoginUI.this.setVisible(false);
regFrame.setVisible(true);
break;
}
}
|
37525e2d-288c-4c29-9c36-8c718cfb62ff
| 0
|
public MandelbrotPanel()
{
left = BigDecimal.valueOf(-2.5);
right = BigDecimal.valueOf(1);
top = BigDecimal.valueOf(-1);
bottom = BigDecimal.valueOf(1);
}
|
88e34941-3c59-454a-8684-0483fe9bf95c
| 1
|
public List<Rectangle> generate() {
data.getMainRectangle().setX(100);
data.getMainRectangle().setY(100);
rectanglesToDraw.add(data.getMainRectangle());
data.sort();
data.getSecondaryRectangles().get(0).setX(data.getMainRectangle().getX());
data.getSecondaryRectangles().get(0).setY(data.getMainRectangle().getY());
for (int i = 1; i < data.getSecondaryRectangles().size(); i++) {
put(data.getMainRectangle(), data.getSecondaryRectangles().get(i -1), data.getSecondaryRectangles().get(i) );
}
rectanglesToDraw.addAll(data.getSecondaryRectangles());
return rectanglesToDraw;
}
|
20098e17-d60f-4d21-ba6b-a314a37a464e
| 0
|
public final int getCurrentServerIndex() {
return serverBox.getSelectedIndex();
}
|
0625a6c2-b73d-4a6a-8ce3-9e838275fecd
| 6
|
public String stComposeEmailForGmailEmailService(int dataId,int ExpVal,String flow )
{
int actVal=1000;
String returnVal=null;
hm.clear();
hm=STFunctionLibrary.stMakeData(dataId, "ExternalEmail");
String to = hm.get("To");
String subject = hm.get("Subject");
// String message = hm.get("Message");
STCommonLibrary comLib=new STCommonLibrary();
Vector<String> xPath=new Vector<String>();
Vector<String> errorMsg=new Vector<String>();
String emailSubjectField="";
String emailMessageBox="";
try {
xPath.add(SIGNIN_GOOGLE_TO_FIELD);
errorMsg.add("To field is not present");
xPath.add(SIGNIN_GOOGLE_MESSAGE_BODY);
errorMsg.add("Message field is not present");
xPath.add(SIGNIN_GOOGLE_SUBJECT_FIELD);
errorMsg.add("Cancel button is not present");
xPath.add(SIGNIN_GOOGLE_SEND_BUTTON);
errorMsg.add("Share Button is not present");
comLib.stVerifyObjects(xPath, errorMsg, "STOP");
xPath.clear();
errorMsg.clear();
emailSubjectField = browser.getValue(SIGNIN_GOOGLE_SUBJECT_FIELD);
System.out.println(emailSubjectField);
//emailMessageBox = browser.getText(SIGNIN_GOOGLE_MESSAGE_BODY);
//System.out.println(emailMessageBox);
Block:
{
/*Typing Receipient */
if(!"".equals(to))
{
browser.focus(SIGNIN_GOOGLE_TO_FIELD);
browser.click(SIGNIN_GOOGLE_TO_FIELD);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
browser.type(SIGNIN_GOOGLE_TO_FIELD, to );
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/* Comparing Subject and message body values */
if(emailSubjectField.contains(subject))
{
//browser.isTextPresent("http://shar.es/");
actVal= 0; /*Email is Composed successfully for Google service */
System.out.println("Values matched");
browser.click(SIGNIN_GOOGLE_SEND_BUTTON);
break Block;
}
else
{
actVal= 1; /*Failed to Compose email for Google service.*/
System.out.println("Values Not matched");
break Block;
}
}
}
catch (SeleniumException sexp)
{
Reporter.log(sexp.getMessage());
}
returnVal=STFunctionLibrary.stRetValDes(ExpVal, actVal, "stComposeEmailForGmailEmailService",flow, hm);
if(flow.contains("STOP")){
assertEquals("PASS",returnVal);
}
return returnVal;
}
|
03753ad2-8b08-4bab-a40f-f943242f1e80
| 2
|
public ArithmeticDecompress (String inputFileName, boolean codeCbCr) throws IOException {
this.codeCbCr = codeCbCr;
binList = new ArrayList<>();
for (int color = 0; color < 3; color++) {
binList.add(new LinkedList<Byte>());
}
arithmeticDecompressProcess(binList.get(0), inputFileName+"Y.bin");
if (codeCbCr) {
arithmeticDecompressProcess(binList.get(1), inputFileName+"Cb.bin");
arithmeticDecompressProcess(binList.get(2), inputFileName+"Cr.bin");
}
listToArr();
}
|
4fffd3f0-53c6-4e4c-8ee6-440d9117dc91
| 2
|
public void mouseClicked(MouseEvent e) {
//Запоминаем событие для обработки кнопки
ev = e;
//Получаем выбраную строку в таблице
int selectedRowIndex = creditProgramTable.getSelectedRow();
if (selectedRowIndex != -1) {
//Получаем значения
for (int i = 0; i < creditProgramTable.getColumnCount(); i++) {
values[i] = creditProgramTable.getValueAt(selectedRowIndex, i);
}
//Заполняем поля
textFieldName.setText(String.valueOf(values[0]));
textFieldMinAmount.setText(String.valueOf(values[1]));
textFieldMaxAmount.setText(String.valueOf(values[2]));
textFieldDuration.setText(String.valueOf(values[3]));
textFieldStartPay.setText(String.valueOf(values[4]));
textFieldPercent.setText(String.valueOf(values[5]));
textAreaDescription.setText(String.valueOf(values[6]));
}
}
|
13b5dd8b-b171-4e8f-bcba-b022db8663ba
| 0
|
public CheckResultMessage checkF07(int day) {
return checkReport.checkF07(day);
}
|
5fca3dc1-7320-49c4-8b4c-90972c6c8408
| 0
|
public PagePinnedException(Exception e, String name){
super(e, name);
}
|
dedcf3a1-b9ff-47ac-8cbf-141db80202ca
| 8
|
public static synchronized void geneject(Class<? extends GenejectorProblem> problem)
{
byte[] mortalBytes;
if (instanceRole == InstanceRole.PROJECT)
{
// Finalize settings
Settings.getSettings().setProblemClassName(problem.getCanonicalName());
Settings.getSettings().addClass(problem.getCanonicalName(), false);
Settings.getSettings().addDefaults();
// Go! Go! Go!
mortalBytes = ProjectInstanceManager.getSolution();
}
else if (instanceRole == InstanceRole.RISEN)
{
mortalBytes = RisenInstanceManager.getMortal();
}
else
{
throw new GenejectorIllegalStateException("Method called from illegal instance of type " + instanceRole);
}
// Bind a mortal to this instance
try
{
// [ListingStart][L6]
DynamicByteClassLoader mortalClassLoader = new DynamicByteClassLoader("GenejectorMortal", mortalBytes);
Class<?> genejectedClass = Class.forName("GenejectorMortal", true, mortalClassLoader);
genejectedMortal = (GenejectedMortal) genejectedClass.newInstance();
executeMethod = genejectedClass.getMethod("execute", problem);
// [ListingEnd][L6]
scoreSubmitted = false;
executeIsRunning = false;
geneticExceptionThrown = false;
}
catch (ClassNotFoundException ex)
{
throw new ReflectionException(ex);
}
catch (InstantiationException ex)
{
throw new ReflectionException(ex);
}
catch (IllegalAccessException ex)
{
throw new ReflectionException(ex);
}
catch (NoSuchMethodException ex)
{
throw new ReflectionException(ex);
}
}
|
804f2e2e-961c-4519-8573-037472dc8d18
| 3
|
public void mouseClick(Point point) {
if(exitButton.getBounds().contains(point) || !window.contains(point)) {
setVisible(false); return;
} else if(moneyButton.contains(point)) {
log.logp(Level.FINE, getClass().getSimpleName(), "mouseClick()", "Setting money to add...");
setMoneyToAdd(50000);
log.logp(Level.FINE, getClass().getSimpleName(), "mouseClick()", "Set money to add.");
}
}
|
dd75463f-edb6-4d70-be85-2e00dad60181
| 0
|
@Override
public String getServletInfo() {
System.out.println("a");
return "Short description";
}
|
ea3dbd52-3f7d-4477-b4a1-755b28fe5ee5
| 2
|
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
ProdutoDAO dao = new ProdutoDAO();
Produto editado = null;
try {
editado = dao.Abrir(this.idDoProdutoSelecionado );
} catch (ErroValidacaoException ex) {
Logger.getLogger(frmListarProduto.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(frmListarProduto.class.getName()).log(Level.SEVERE, null, ex);
}
frmEditarProduto janela = new frmEditarProduto(editado,true);
janela.setVisible(true);
this.getParent().add(janela);
this.dispose();
}//GEN-LAST:event_jButton2ActionPerformed
|
94dfb990-3587-4abc-9a3b-6f528da2c88d
| 0
|
public void setUsuarioidUsuario(Usuario usuarioidUsuario) {
this.usuarioidUsuario = usuarioidUsuario;
}
|
3a55027b-71f9-4e5b-b323-8df61d749d81
| 2
|
public Room getRoom(int id)
{
Room room = null;
try {
PreparedStatement ps = con.prepareStatement("SELECT * FROM rooms WHERE id=?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if( rs.next() )
{
room = getRoomFromRS(rs);
}
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return room;
}
|
395aaebd-e4e0-420e-a1c0-9faad91c11ff
| 2
|
public boolean removeEntity(int x, int y) {
if (state != null) {
throw new IllegalStateException("game currently ticking");
}
boolean success = thisTick[x][y] != null;
log(Level.INFO, "Removing %d at (%d, %d)", success ? thisTick[x][y].id : -1, x, y);
thisTick[x][y] = null;
return success;
}
|
60c3858d-a872-468a-87fc-3e4183adcab2
| 8
|
static public Object[] toArray(Object coll) throws Exception{
if(coll == null)
return EMPTY_ARRAY;
else if(coll instanceof Object[])
return (Object[]) coll;
else if(coll instanceof Collection)
return ((Collection) coll).toArray();
else if(coll instanceof Map)
return ((Map) coll).entrySet().toArray();
else if(coll instanceof String) {
char[] chars = ((String) coll).toCharArray();
Object[] ret = new Object[chars.length];
for(int i = 0; i < chars.length; i++)
ret[i] = chars[i];
return ret;
}
else if(coll.getClass().isArray()) {
ISeq s = (seq(coll));
Object[] ret = new Object[count(s)];
for(int i = 0; i < ret.length; i++, s = s.next())
ret[i] = s.first();
return ret;
}
else
throw new Exception("Unable to convert: " + coll.getClass() + " to Object[]");
}
|
0974f851-3d36-49a0-a9a2-c0ed2b1cf151
| 0
|
protected Icon getIcon() {
java.net.URL url = getClass().getResource("/ICON/default.gif");
return new javax.swing.ImageIcon(url);
}
|
1243816b-1f42-4e9f-be02-9ea46c25876d
| 8
|
public void drawRect(int xPos, int yPos, int width, int height, int color) {
if (xPos > this.width)
xPos = this.width - 1;
if (yPos > this.height)
yPos = this.height - 1;
if (xPos + width > this.width)
width = this.width - xPos;
if (yPos + height > this.height)
height = this.height - yPos;
width -= 1;
height -= 1;
for (int x = xPos; x < xPos + width; x++) {
pixels[x + yPos * this.width] = color;
}
for (int y = yPos; y < yPos + height; y++) {
pixels[xPos + y * this.width] = color;
}
for (int x = xPos; x < xPos + width; x++) {
pixels[x + (yPos + height) * this.width] = color;
}
for (int y = yPos; y < yPos + height; y++) {
pixels[(xPos + width) + y * this.width] = color;
}
}
|
92a970ba-3708-483a-90db-34d99e225204
| 5
|
public static void keyPress(KeyEvent e){
Ship ship = gameObjects.getShip();
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP){
ship.forwardThrust(true);
}
if (keyCode == KeyEvent.VK_DOWN){
//No reverse
}
if (keyCode == KeyEvent.VK_LEFT){
ship.rotateShip(true, true);
}
if (keyCode == KeyEvent.VK_RIGHT){
ship.rotateShip(false, true);
}
if (keyCode == KeyEvent.VK_SPACE){
bulletFire();
}
}
|
953eafd9-a782-4599-b0c3-8640c09482e2
| 8
|
public static Set<ClassFile> analyzeProject(ClassReference mainClass,
File classPath, final Set<ClassReference> notFound) {
final RootReference root = mainClass.getRootReference();
Set<ClassHolder> classHolders = new HashSet<ClassHolder>();
classHolders.add(new ClassHolder(mainClass));
int checkedAmount = 0;
int foundAmount = 0;
while (checkedAmount < classHolders.size()) {
final ClassHolder currentHolder = findFirstNotChecked(classHolders);
final ClassFile classFile = loadClass(currentHolder.getFile(classPath), root);
if (classFile != null) {
foundAmount++;
Set<ClassReference> dependencies = classFile.getReferencedClasses();
for (ClassReference dependency : dependencies) {
classHolders.add(new ClassHolder(dependency));
}
}
currentHolder.setChecked(classFile);
checkedAmount++;
}
if (notFound != null) {
for (ClassHolder holder : classHolders) {
if (!holder.loaded()) {
notFound.add(holder.reference);
}
}
}
Set<ClassFile> loaded = new HashSet<ClassFile>(foundAmount);
for (ClassHolder holder : classHolders) {
if (holder.loaded()) {
loaded.add(holder.getClassFile());
}
}
return loaded;
}
|
cc507c64-016d-4c9c-8d83-d7c546c28f06
| 6
|
protected String legalMove(Board b, String move) {
// get source pos and target pos
if (move != null) {
Position src, tgt;
int srcRow, srcCol;
int tgtRow, tgtCol;
srcRow = b.getRowNumber(move.substring(1, move.indexOf(' ')));
if (reverse) {
srcCol = 4 - b.getColNumber(move.substring(1, move.indexOf(' ')));
}
else {
srcCol = b.getColNumber(move.substring(1, move.indexOf(' ')));
}
src = new Position(srcRow, srcCol);
tgtRow = b.getRowNumber(move.substring(move.indexOf(' ') + 1,
move.indexOf(')')));
if (reverse) {
tgtCol = 4 - b.getColNumber(move.substring(move.indexOf(' ') + 1,
move.indexOf(')')));
}
else {
tgtCol = b.getColNumber(move.substring(move.indexOf(' ') + 1,
move.indexOf(')')));
}
tgt = new Position(tgtRow, tgtCol);
// We need to see if target position is in the adjacent list of src
Piece piece = b.getPiece(srcRow, srcCol);
boolean isEngineer = piece.getRank().equals(Rank.Engineer);
boolean isOurs = piece.getOurSide();
if (src.adjacentP(b, isEngineer, isOurs).indexOf(tgt) != -1) {
// in the adjacent list, move is legal
return move;
}
else {
// illegal move!
if (TEST) {
outputErrorMove(b);
}
}
}
else {
// illegal move!
if (TEST) {
outputErrorMove(b);
}
}
return null;
}
|
4695d826-566e-4326-9188-f8c902fd2886
| 2
|
public void consume() throws InterruptedException {
Random random = new Random();
while (true) {
synchronized (lock) {
while (list.size() == 0) {
lock.wait();
}
int value = list.removeFirst();
System.out.print("Removed value by consumer is: " + value);
System.out.println(" Now list size is: " + list.size());
lock.notify();
}
Thread.sleep(random.nextInt(1000)); //force producer fill the queue to LIMIT_SIZE
}
}
|
a7c5fcca-6d6e-4417-95ee-f3eae26a194f
| 8
|
void processLoginResponseMessage(Event event)
{
OMMItemEvent ie = (OMMItemEvent)event;
OMMMsg ommMsg = ie.getMsg();
short ommMsgType = ommMsg.getMsgType();
String ommMsgTypeStr = OMMMsg.MsgType.toString((byte)ommMsgType);
System.out.println("<-- " + _className + "Received " + event.toString() + " "
+ ommMsgTypeStr);
GenericOMMParser.parse(ommMsg);
byte messageType = ommMsg.getMsgType();
if (messageType == OMMMsg.MsgType.ACK_RESP)
{
_mainApp.processAckResponse(_className, ommMsg);
return;
}
if (messageType == OMMMsg.MsgType.STATUS_RESP)
{
_mainApp.processStatusResponse(_className, ommMsg);
}
if (ommMsg.isFinal())
{
System.out.println("* Login Response message is final.");
_mainApp.processLogin(false);
return;
}
/* login granted */
if ((ommMsg.getMsgType() == OMMMsg.MsgType.STATUS_RESP) && (ommMsg.has(OMMMsg.HAS_STATE))
&& (ommMsg.getState().getStreamState() == OMMState.Stream.OPEN)
&& (ommMsg.getState().getDataState() == OMMState.Data.OK))
{
boolean bPostingSupported = isPostingSupported(ommMsg);
if (bPostingSupported == true)
{
System.out.println(INFO_APPNAME + " OMMPosting feature is available");
}
else
{
System.out.println(INFO_APPNAME + " OMMPosting feature is not available");
}
_mainApp.processLogin(true);
}
else
{
System.out.println("* Received Login Response - "
+ OMMMsg.MsgType.toString(ommMsg.getMsgType()));
}
return;
}
|
09d7d304-eccd-4d1a-8149-ae3899f3b87b
| 5
|
static final Class171 method459(int i, OpenGlToolkit var_ha_Sub2, String string,
boolean bool) {
try {
anInt861++;
int i_6_ = OpenGL.glGenProgramARB();
OpenGL.glBindProgramARB(i, i_6_);
if (bool != false)
return null;
OpenGL.glProgramStringARB(i, 34933, string);
OpenGL.glGetIntegerv(34379, GraphicsFetcher.anIntArray9069, 0);
if ((GraphicsFetcher.anIntArray9069[0] ^ 0xffffffff) != 0) {
OpenGL.glBindProgramARB(i, 0);
return null;
}
OpenGL.glBindProgramARB(i, 0);
return new Class171(var_ha_Sub2, i, i_6_);
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("iu.I(" + i + ','
+ (var_ha_Sub2 != null ? "{...}"
: "null")
+ ','
+ (string != null ? "{...}"
: "null")
+ ',' + bool + ')'));
}
}
|
98d63b79-80f2-4f98-a434-e849cae879d0
| 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(ListaProductos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ListaProductos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ListaProductos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ListaProductos.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 ListaProductos().setVisible(true);
}
});
}
|
1baf60e6-c8c6-4a8f-9867-0892665b736b
| 4
|
public void WGPwd(String sender, String login, String hostname, Command command) {
if(command.arguments.length == 2) {
User user;
for(Game game : games.values()) {
user = getUser(game, sender, login, hostname);
if(user != null) {
user.setPassword(command.arguments[1]);
if(game.autosave) {
saveGame(game);
}
}
}
sendMessage(sender, "Password set for all users matching your connection details.");
sendMessage(sender, "Use !wglogin <nick> <password> to login if any of your connection details change.");
sendMessage(sender, "If you change your nick, use your old nick in the !wglogin command.");
}
else {
sendMessage(sender, "WGPWD usage: !wgpwd <newpassword>");
}
}
|
dc0e86ef-91b9-4d5c-8529-13430e958d0e
| 4
|
public ParkMain() {
setTitle("\u505C\u8F66\u573A\u7BA1\u7406\u7CFB\u7EDF");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JMenuBar menuBar = new JMenuBar();
JMenu m1 = new JMenu();
m1.setFont(new Font("微软雅黑", Font.PLAIN, 12));
m1.setText("\u7CFB\u7EDF\u7BA1\u7406");
JMenu m2 = new JMenu();
m2.setFont(new Font("微软雅黑", Font.PLAIN, 12));
m2.setText("停车场管理");
JMenu m3 = new JMenu();
m3.setFont(new Font("微软雅黑", Font.PLAIN, 12));
m3.setText("帮助");
JMenuItem item11 = new JMenuItem();
item11.setFont(new Font("微软雅黑", Font.PLAIN, 12));
item11.setText("停车场管理");
JMenuItem item12 = new JMenuItem();
item12.setFont(new Font("微软雅黑", Font.PLAIN, 12));
item12.setText("停车管理员");
JMenuItem item14 = new JMenuItem();
item14.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
item14.setFont(new Font("微软雅黑", Font.PLAIN, 12));
item14.setText("退出");
JMenuItem item22 = new JMenuItem();
item22.setFont(new Font("微软雅黑", Font.PLAIN, 12));
item22.setText("经理");
JMenuItem item32 = new JMenuItem();
item32.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(contentPane, "停车场管理系统V1.0!");
}
});
item32.setFont(new Font("微软雅黑", Font.PLAIN, 12));
item32.setText("版本信息");
m1.add(item11);
JMenuItem menu13 = new JMenuItem();
menu13.setText("停车场经理");
menu13.setFont(new Font("微软雅黑", Font.PLAIN, 12));
m1.add(menu13);
m1.add(item12);
m1.add(item14);
JMenuItem item21 = new JMenuItem();
item21.setFont(new Font("微软雅黑", Font.PLAIN, 12));
item21.setText("Boy");
m2.add(item21);
m2.add(item22);
m3.add(item32);
menuBar.add(m1);
menuBar.add(m2);
JMenu m4 = new JMenu();
menuBar.add(m4);
m4.setText("报表管理");
m4.setFont(new Font("微软雅黑", Font.PLAIN, 12));
JMenuItem m41 = new JMenuItem();
m41.setText("停车场经理");
m41.setFont(new Font("微软雅黑", Font.PLAIN, 12));
m4.add(m41);
JMenuItem m42 = new JMenuItem();
m42.setText("停车场BOSS");
m42.setFont(new Font("微软雅黑", Font.PLAIN, 12));
m4.add(m42);
menuBar.add(m3);
menuBar.setToolTipText("");
setJMenuBar(menuBar);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
final JLabel lblNewLabel = new JLabel("欢迎使用停车场管理系统");
lblNewLabel.setFont(new Font("微软雅黑", Font.PLAIN, 22));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblNewLabel, BorderLayout.CENTER);
//创建停车场
item11.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new CreatePark().setVisible(true);
}
});
//创建停车场管理经理
menu13.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(pm.getParkList().size()==0){
JOptionPane.showMessageDialog(contentPane, "请先创建停车场!");
}else{
new CreateManager().setVisible(true);
}
}
});
//创建停车boy
item12.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(pm.getParkList().size()==0){
JOptionPane.showMessageDialog(contentPane, "请先创建停车场!");
}else{
new CreateBoy().setVisible(true);
}
}
});
m41.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new ManagerReport().setVisible(true);
}
});
m42.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new BossReport().setVisible(true);
}
});
item21.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(pm.getBoyList().size()==0){
JOptionPane.showMessageDialog(contentPane, "还未创建停车Boy!");
}else{
new ParkBoyOperator().setVisible(true);
}
}
});
item22.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(pm.getManagerList().size()==0){
JOptionPane.showMessageDialog(contentPane, "还未创建停车场经理!");
}else{
new ManagerOperator().setVisible(true);
}
}
});
}
|
f6bcb69c-9d69-4e7e-bc98-39663fd73142
| 4
|
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerEnteredArena(PlayerEnteredArenaEvent evt) {
if (!evt.isCancelled()) {
Player evtPlayer = evt.getPlayer();
if (!evtPlayer.isDead() || evt.getMethod() == MoveMethod.RESPAWNED) {
evtPlayer.getInventory().clear();
addItems(evtPlayer);
addArmor(evtPlayer);
evtPlayer.setHealth(20);
evtPlayer.setFoodLevel(20);
evtPlayer.setGameMode(GameMode.SURVIVAL);
evtPlayer.sendMessage(FreeForAll.prefix + "You have entered the arena. Your inventory has been saved.");
for (PotionEffect pt : evtPlayer.getActivePotionEffects()) {
evtPlayer.removePotionEffect(pt.getType());
}
}
}
}
|
b7ca7fa2-8b56-45de-8439-08e3aaa28e52
| 0
|
public JButton getjButtonClose() {
return jButtonClose;
}
|
25dc879a-b325-49c9-b820-a2f2c425d91c
| 2
|
private boolean jj_3_37() {
if (jj_3R_55()) return true;
if (jj_3R_56()) return true;
return false;
}
|
6b297c20-21e7-40f3-8701-3876b9e9ee27
| 0
|
public StudentTableModel(LinkedList<Student> students) {
this.showStudents(students);
}
|
f0788609-2e9d-4c56-bbf7-968cef24b9ce
| 6
|
public void runAway(int fromX, int fromY) {
if (dead || sleeping || exciting || angry) {
return;
}
int toX, toY;
if (x > fromX) {
toX = Terrarium.MAX_X;
}
else {
toX = 0;
}
if (y > fromY) {
toY = Terrarium.MAX_Y;
}
else {
toY = 0;
}
moveTo(toX, toY);
clearActions();
scare = true;
}
|
89d4e124-31ad-41de-aa69-ed022ccb2d12
| 9
|
public double getEnvironmentMult(Player player)
{
Environment env = player.getWorld().getEnvironment();
String envString;
double envMult = 1.0;
if (env.equals(Environment.NORMAL))
{
envString = getMBR().getConfigManager()
.getProperty(MobBountyReloadedConfFile.MULTIPLIERS,
"Environment.Normal");
if (envString == null)
envString = "1.0";
try
{
envMult = Double.parseDouble(envString);
}
catch (NumberFormatException e)
{
envMult = 1.0;
}
}
else if (env.equals(Environment.NETHER))
{
envString = getMBR().getConfigManager()
.getProperty(MobBountyReloadedConfFile.MULTIPLIERS,
"Environment.Nether");
if (envString == null)
envString = "1.0";
try
{
envMult = Double.parseDouble(envString);
}
catch (NumberFormatException e)
{
envMult = 1.0;
}
}
else if (env.equals(Environment.THE_END))
{
envString = getMBR().getConfigManager().getProperty(
MobBountyReloadedConfFile.MULTIPLIERS, "Environment.End");
if (envString == null)
envString = "1.0";
try
{
envMult = Double.parseDouble(envString);
}
catch (NumberFormatException e)
{
envMult = 1.0;
}
}
return envMult;
}
|
5a1244de-42e4-4919-9d35-ad180449e1e7
| 2
|
private void getRequest(HttpExchange he) throws IOException {
try {
String path = he.getRequestURI().getPath();
int lastIndex = path.lastIndexOf("/");
if (lastIndex > 0) {
int id = Integer.parseInt(path.substring(lastIndex + 1));
response = facade.getOneCourseAsJson(id);
status = 200;
} else {
response = facade.getAllCoursesAsJson();
status = 200;
}
} catch (NumberFormatException nfe) {
response = "id is not a number";
status = 404;
}
}
|
b4989c12-c638-4c01-a79f-d2d89890fc64
| 8
|
protected void configureShell(Shell shell) {
GridLayoutFactory.fillDefaults().margins(0, 0).spacing(5, 5).applyTo(
shell);
shell.addListener(SWT.Deactivate, new Listener() {
public void handleEvent(Event event) {
/*
* Close if we are deactivating and have no child shells. If we
* have child shells, we are deactivating due to their opening.
* On X, we receive this when a menu child (such as the system
* menu) of the shell opens, but I have not found a way to
* distinguish that case here. Hence bug #113577 still exists.
*/
if (listenToDeactivate && event.widget == getShell()
&& getShell().getShells().length == 0) {
asyncClose();
} else {
/*
* We typically ignore deactivates to work around
* platform-specific event ordering. Now that we've ignored
* whatever we were supposed to, start listening to
* deactivates. Example issues can be found in
* https://bugs.eclipse.org/bugs/show_bug.cgi?id=123392
*/
listenToDeactivate = true;
}
}
});
// Set this true whenever we activate. It may have been turned
// off by a menu or secondary popup showing.
shell.addListener(SWT.Activate, new Listener() {
public void handleEvent(Event event) {
// ignore this event if we have launched a child
if (event.widget == getShell()
&& getShell().getShells().length == 0) {
listenToDeactivate = true;
// Typically we start listening for parent deactivate after
// we are activated, except on the Mac, where the deactivate
// is received after activate.
// See https://bugs.eclipse.org/bugs/show_bug.cgi?id=100668
listenToParentDeactivate = !Util.isMac();
}
}
});
if ((getShellStyle() & SWT.ON_TOP) != 0 && shell.getParent() != null) {
parentDeactivateListener = new Listener() {
public void handleEvent(Event event) {
if (listenToParentDeactivate) {
asyncClose();
} else {
// Our first deactivate, now start listening on the Mac.
listenToParentDeactivate = listenToDeactivate;
}
}
};
shell.getParent().addListener(SWT.Deactivate,
parentDeactivateListener);
}
shell.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent event) {
handleDispose();
}
});
}
|
3324194e-d4d1-467e-aa10-06b6ec965669
| 1
|
public RacketView(int x, int y) {
BufferedImage img = null;
try {
img = ImageIO.read(new File("src\\jark\\racket.png"));
_elementSprite = new Sprite(img, x, y);
_elementSprite.setSpeed(0, 0);
} catch (IOException e) {
e.printStackTrace();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.