method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
0f31c7ec-d18d-4358-9ee1-6e829a467061 | 2 | private void utilities(){
if(center) Base.render.center();
if(quit) System.exit(0);
} |
b717f251-9c71-4b1b-8d13-6bb18074749f | 9 | @Override
public Object getValueAt(int rowIndex, int columnIndex) {
ContaReceber ContaReceber = filtrados.get(rowIndex);
switch (columnIndex) {
case 0:
return ContaReceber.getId();
case 1:
if (ContaReceber.getParceiro().isFisica()) {
return ContaReceber.getParceiro().getNome();
}
return ContaReceber.getParceiro().getRazaoSocial();
case 2:
return Formatar.formatarData(ContaReceber.getData());
case 3:
return Formatar.formatarData(ContaReceber.getVencimento());
case 4:
return ContaReceber.getObs();
case 5:
return Formatar.formatarNumero(ContaReceber.getValor());
case 6:
if(ContaReceber.isRecebido())
return "SIM";
return "NÃO";
default:
throw new IndexOutOfBoundsException("columnIndex out of bounds");
}
} |
1165b766-09c7-4c2c-ac7b-d06907a4e944 | 9 | private long sizeOfType(Class<?> type) {
if (type == int.class) {
return INT;
} else if (type == long.class) {
return LONG;
} else if (type == byte.class) {
return BYTE;
} else if (type == boolean.class) {
return BOOLEAN;
} else if (type == char.class) {
return CHAR;
} else if (type == float.class) {
return FLOAT;
} else if (type == double.class) {
return DOUBLE;
} else if (type == short.class) {
return SHORT;
} else
return REFERENCE;
} |
4435bba3-20c6-4fa2-9582-e490e674d977 | 1 | public static <T> Set<T> treeSet(T... params) {
Set<T> result = new TreeSet<T>();
for (T t : params) {
result.add(t);
}
return result;
} |
a4884d20-9057-40f3-b4ae-7b5174ff0f5b | 4 | private void bind() {
HasAllMouseHandlers canvas = automatonView.getHandlerCanvas();
canvas.addMouseDownHandler(new MouseDownHandler() {
@Override
public void onMouseDown(MouseDownEvent event) {
StateView stateView = findStateAt(event.getX(), event.getY());
if (stateView != null) {
moveState = stateView;
disableMoveMode();
return;
}
moveCanvas = true;
}
});
canvas.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
disableMoveMode();
moveState = null;
}
});
canvas.addMouseOutHandler(new MouseOutHandler() {
@Override
public void onMouseOut(MouseOutEvent event) {
disableMoveMode();
moveState = null;
}
});
canvas.addMouseMoveHandler(new MouseMoveHandler() {
@Override
public void onMouseMove(MouseMoveEvent event) {
if (moveCanvas) {
if (lastPosition != null) {
double x = event.getX() - lastPosition.x;
double y = event.getY() - lastPosition.y;
automatonView.offset.plus(x, y);
overView.draw();
}
lastPosition = new Vector(event.getX(), event.getY());
} else if (moveState != null) {
moveState.setWorldPosition(event.getX(), event.getY());
overView.draw();
}
}
});
} |
bda5adc9-a9f7-4748-a0af-aac5a6c73c34 | 3 | public static double getWeaponSpeed(WeaponType type) {
switch (type) {
case mel_sword:
return 3;
case mel_hammer:
return 4;
case rng_bow:
return 5;
}
return 1;
} |
9a86fffa-463e-44fd-9363-cbe942b5e470 | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof EMailTyp))
return false;
EMailTyp other = (EMailTyp) obj;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
return true;
} |
2dda5206-b5de-4970-ae2a-2bc719d307b4 | 5 | public static void unzipFile(String zipFilePath, String outputDir) {
byte[] buffer = new byte[1024];
try {
// create output directory is not exists
File folder = new File(outputDir);
if (!folder.exists()) {
folder.mkdir();
}
// getLogger().info("zip file : " + zipFilePath);
// get the zip file content
ZipInputStream zis = new ZipInputStream(new FileInputStream(
zipFilePath));
// get the zipped file list entry
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputDir + File.separator + fileName);
if (newFile.exists()) {
ze = zis.getNextEntry();
getLogger().info(
"file exists : " + newFile.getAbsolutePath());
continue;
}
getLogger()
.info("file unzipped : " + newFile.getAbsolutePath());
// create all non exists folders
// else you will hit FileNotFoundException for compressed folder
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
zis.closeEntry();
zis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
} |
f4b14bce-71e6-4463-afd7-e5e1943dcda1 | 3 | public void run() {
URL url = null;
try {
url = new URL("http://skriptlib.exsoloscript.com/files/" + name + "/" + name);
} catch (MalformedURLException e) {
this.plugin.messageOps("Something went wrong whilst connecting to the SkriptLib server.");
return;
}
if (!exists(url)) {
this.plugin.messageOps("Script with the name '" + name + "' does not exist. Look for scripts on the SkriptLib server with /search or /lookup");
return;
}
try {
FileUtils.copyURLToFile(url, new File(dir, name), 4000, 4000);
} catch (IOException e) {
this.plugin.messageOps("Something went wrong whilst copying the file from the SkriptLib server to your Skript direcotry");
return;
}
} |
edc736ec-7aee-4a61-b477-326aac136fa9 | 4 | private void Open_File_Menu_ItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Open_File_Menu_ItemActionPerformed
//==== Initialize the filechooser, using the user's home dir, or the last working dir
if(this.currentDirectory.equals(""))
{ this.fc = new JFileChooser(); }
else
{ this.fc = new JFileChooser(this.currentDirectory); }
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
if(file.exists())
{
ResultXML xml = new ResultXML();
boolean itSaved = xml.openFile(file);
if (itSaved)
{
//Graph graph = xml.getGraph();
//thisSession = new DigLibSESession(graph, this);
this.Graph_View_Frame.setContentPane(thisSession.getRadialGraph().getGraphDisplayPanel());
this.Main_Tab_Pane.setSelectedIndex(1);
}
else
{
//==== File couldn't open, give an error message
final JFrame errorMessage = new JFrame();
errorMessage.setTitle("File Error");
errorMessage.setLocationRelativeTo(fc);
JLabel title = new JLabel("Error opening file, check file format and try again.");
title.setFont(new Font("Tahoma", 0, 12));
//==== Create the button for not overwriting the file
JButton closeButton = new JButton();
closeButton.setText("Close");
closeButton.setToolTipText("Close");
closeButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
errorMessage.setVisible(false);
}
});
//==== Add the label and the button to the panel
JPanel complete = new JPanel();
GridLayout layout = new GridLayout(2,1);
layout.addLayoutComponent("title", title);
layout.addLayoutComponent("button", closeButton);
complete.add(title);
complete.add(closeButton);
complete.setLayout(layout);
Dimension d = new Dimension(300, 100);
errorMessage.setSize(d);
errorMessage.setContentPane(complete);
errorMessage.setVisible(true);
} //end else, file read error
this.currentDirectory = file.getPath();
} //end if, file exists
} //end if, user clicked the button
}//GEN-LAST:event_Open_File_Menu_ItemActionPerformed |
82eb2bea-96c8-4e70-ac68-b6d8b7172a77 | 5 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Colaborador other = (Colaborador) obj;
if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
return false;
}
return true;
} |
ea4db6df-2307-4e6e-9de8-e9035a448bb0 | 0 | public AIModule getAI() {
return ai;
} |
c8e3bc74-37c1-4bca-b080-516f57651503 | 5 | private static void Sortingbywieghtdividedbylength() {
// TODO Auto-generated method stub
int i = 0;
int j = 0;
for (i = 0; i < 10000; i++) {
for (j = 0; j < 9999; j++) {
if (jobs[j][0] * jobs[j + 1][1] < jobs[j + 1][0] * jobs[j][1]) {
int l, m, n;
l = jobs[j][0];
m = jobs[j][1];
n = jobs[j][2];
jobs[j][0] = jobs[j + 1][0];
jobs[j][1] = jobs[j + 1][1];
jobs[j][2] = jobs[j + 1][2];
jobs[j + 1][0] = l;
jobs[j + 1][1] = m;
jobs[j + 1][2] = n;
} else {
if (jobs[j][2] == jobs[j + 1][2]) {
if (jobs[j][0] < jobs[j + 1][0]) {
float l, m, n;
l = jobs[j][0];
m = jobs[j][1];
n = jobs[j][2];
jobs[j][0] = jobs[j + 1][0];
jobs[j][1] = jobs[j + 1][1];
jobs[j][2] = jobs[j + 1][2];
jobs[j + 1][0] = (int) l;
jobs[j + 1][1] = (int) m;
jobs[j + 1][2] = (int) n;
}
}
}
}
}
} |
5c826486-0bae-44bf-99c4-ab8b7a216df6 | 8 | static boolean isPlain(char ch) {
switch(ch) {
case '0': case '1': // don't have letters
case '+': case '-': // int'l prefix, dash
case '(': case ')': // silly North Americans
case '*': case '#': // just in case (should not occur, but...)
return true;
}
return false;
} |
6098fd6d-f430-44d9-8b76-37354a1c2a4a | 0 | @Override
public void display(UserInterface ui) {
UserInterface.println(
"Unraveling execution and re-executing current function.");
ui.signalNeedToDisplayFunction();
} |
2daf9d67-7c89-4fe7-8008-28d046e781b0 | 5 | public static TimerLabel swigToEnum(int swigValue) {
if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue) {
return swigValues[swigValue];
}
for (int i = 0; i < swigValues.length; i++) {
if (swigValues[i].swigValue == swigValue) {
return swigValues[i];
}
}
throw new IllegalArgumentException("No enum " + TimerLabel.class + " with value " + swigValue);
} |
172818a3-5925-4b6d-bde1-6e0d06f32ce0 | 1 | private JPanel pasEncore()
{
JPanel panel = new JPanel(new BorderLayout());
JLabel label ;
try {
BoxLayout bl=new BoxLayout(panel,BoxLayout.Y_AXIS); //layoutManager
panel.setLayout(bl); //attache le layoutManager au panel
label=new JLabel("En cours de développement ...");
panel.add(label);
//panel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
//panel.add(new JScrollPane(editor), BorderLayout.CENTER);
} catch (Exception e) {
}
return panel;
} |
12fb904b-8c85-49ed-aec9-bd283f6b834f | 3 | public byte dominantDimensionNum()
{
int d = -1;
int dl = -1;
for (int i = 0; i < min.length; i++)
{
int il = max[i] - min[i];
if (il > dl && canSplitInDim(i))
{
dl = il;
d = i;
}
}
return (byte) d;
} |
ea02cb65-a800-431c-aaa4-8decc4a158db | 1 | public static void main(String[] args) throws Exception
{
PrivateMember p = new PrivateMember();
Class<?> classType = p.getClass();
Method method = classType.getDeclaredMethod("getMessage",new Class[]{String.class});
/**
*
* Exception in thread "main" java.lang.NoSuchMethodException: reflection.PrivateMember.getMessage(java.lang.String)
* at java.lang.Class.getMethod(Unknown Source)
* at reflection.CallPrivateMethod.main(CallPrivateMethod.java:13)
*
*/
method.setAccessible(true); //禁止java的访问控制检查
String str = (String)method.invoke(p, new Object[]{"li si"});
System.out.println(str);
} |
e9965351-d3a7-4bc0-acdd-9fb872fee0a8 | 0 | @BeforeClass
public static void setUpClass() throws Exception {
ctx = new AnnotationConfigApplicationContext(ConnectionConfig.class);
} |
eadc406c-2774-4db1-ad81-7ccc7cb05b21 | 7 | void updateGui(String fieldname) {
Object fieldval = fieldvalues.get(fieldname);
Object fieldcom = fieldcomponents.get(fieldname);
String fieldtype = (String)fieldtypes.get(fieldname);
if (fieldcom instanceof JCheckBox) {
((JCheckBox)fieldcom).setSelected(
((Boolean)fieldval).booleanValue() );
/* more work in progress
} else if (fieldcom instanceof CoordPanel) {
CoordPanel cp = (CoordPanel) fieldcom;
if (fieldval instanceof Point) {
cp.setValue((Point)fieldval);
} else if (fieldval instanceof Dimension) {
cp.setValue((Dimension)fieldval);
} else if (fieldval instanceof Rectangle) {
cp.setValue((Rectangle)fieldval);
} else {
System.err.println("Cannot match field with CoordPanel");
}
*/
} else if (fieldcom instanceof JColorChooser) {
JColorChooser jcc = (JColorChooser) fieldcom;
jcc.setColor((Color)fieldval);
} else if (fieldcom instanceof KeyField) {
((KeyField)fieldcom).setValue( ((Integer)fieldval).intValue() );
} else if (fieldcom instanceof JTextField) {
JTextField textfield = (JTextField) fieldcom;
if (fieldtype.equals("int")
|| fieldtype.equals("double") ) {
textfield.setText(""+fieldval);
} else if (fieldtype.equals("String")) {
textfield.setText(""+fieldval);
}
}
} |
ffc5e15e-02f6-4e59-bfcc-e44a80858b2b | 4 | public void figureVoxels() {
start = dateFormat.format(cal.getTime());
/*
long commonCounter = 0;
for (int i = 0; i < topView3DCoordinates.size(); i++) {
Coord3d sample = topView3DCoordinates.get(i);
if (foundLateral(sample) == true && foundFront(sample) == true) {
commonCounter++;
System.out.println("Common Coordinate #" + commonCounter + " found");
commonCoordinates.add(sample);
}
}
*/
int[] size = {
imageArrays[0].length,
imageArrays[0][0].length,
imageArrays[1][0].length};
System.out.println(size[0]);
System.out.println(size[1]);
System.out.println(size[2]);
long commonCounter = 0;
// TODO: better dimensions calculation
for (int ix = 0; ix < size[0]; ix++)
for (int iy = 0; iy < size[1]; iy++)
for (int iz = 0; iz < size[2]; iz++) {
if (filterAtPoint(ix, iy, iz)) {
System.out.println("Common coordinate #" + commonCounter + " found.");
final float x = ix;
final float y = iy;
final float z = iz;
commonCoordinates.add(new Coord3d((float) x, (float) y, (float) z));
commonCounter++;
}
}
System.out.println("topView3DCoordinates: " + topView3DCoordinates.size());
System.out.println("lateralView3DCoordinates: " + lateralView3DCoordinates.size());
System.out.println("Figured out Voxels");
dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
cal = Calendar.getInstance();
System.out.println(start);
System.out.println(dateFormat.format(cal.getTime()));
} |
c63a008c-12ec-4fb1-a8ee-6fdf4272e2dc | 0 | public static void main(String[] args) {
ParcelLocal p = new ParcelLocal();
Destination d = p.destination("Tasmania");
} |
b72f8b3f-7df9-491c-8f78-05fb9b165048 | 9 | public Test getTest(String suiteClassName) {
if (suiteClassName.length() <= 0) {
clearStatus();
return null;
}
Class testClass= null;
try {
testClass= loadSuiteClass(suiteClassName);
} catch (ClassNotFoundException e) {
String clazz= e.getMessage();
if (clazz == null)
clazz= suiteClassName;
runFailed("Class not found \""+clazz+"\"");
return null;
} catch(Exception e) {
runFailed("Error: "+e.toString());
return null;
}
Method suiteMethod= null;
try {
suiteMethod= testClass.getMethod(SUITE_METHODNAME, new Class[0]);
} catch(Exception e) {
// try to extract a test suite automatically
clearStatus();
return new TestSuite(testClass);
}
if (! Modifier.isStatic(suiteMethod.getModifiers())) {
runFailed("Suite() method must be static");
return null;
}
Test test= null;
try {
test= (Test)suiteMethod.invoke(null, new Class[0]); // static method
if (test == null)
return test;
}
catch (InvocationTargetException e) {
runFailed("Failed to invoke suite():" + e.getTargetException().toString());
return null;
}
catch (IllegalAccessException e) {
runFailed("Failed to invoke suite():" + e.toString());
return null;
}
clearStatus();
return test;
} |
6c6c806d-ad3b-45e0-9069-56cb17a78024 | 0 | public int getIconWidth() {
return 400;
} |
b57f8b23-3707-4c68-95fd-2e5965a07c4b | 1 | public CtConstructor[] getConstructors() {
try {
return getSuperclass().getConstructors();
}
catch (NotFoundException e) {
return super.getConstructors();
}
} |
2c4a4d6c-8e21-4e96-97e1-b36677b9a2d5 | 7 | public static void selectWordLeftText(OutlinerCellRendererImpl textArea, JoeTree tree, OutlineLayoutManager layout) {
Node currentNode = textArea.node;
int currentPosition = textArea.getCaretPosition();
String text = textArea.getText();
int text_length = text.length();
if (currentPosition == 0) {
return;
}
// Update Preferred Caret Position
char[] chars = text.substring(0,currentPosition).toCharArray();
char c = chars[chars.length - 1];
boolean isWordChar = false;
if (Character.isLetterOrDigit(c) || c == '_') {
isWordChar = true;
}
int i = chars.length - 2;
for (; i >= 0; i--) {
c = chars[i];
if ((Character.isLetterOrDigit(c) || c == '_') == !isWordChar) {
break;
}
}
int newCaretPosition = currentPosition - (chars.length - 1 - i);
tree.getDocument().setPreferredCaretPosition(newCaretPosition);
// Record the CursorPosition only since the EditingNode should not have changed
tree.setCursorPosition(newCaretPosition, false);
textArea.moveCaretPosition(newCaretPosition);
// Redraw and Set Focus if this node is currently offscreen
if (!currentNode.isVisible()) {
layout.draw(currentNode,OutlineLayoutManager.TEXT);
}
// Freeze Undo Editing
UndoableEdit.freezeUndoEdit(currentNode);
} |
40bd5c7b-5f1a-4f1d-a557-e065cd2c00a7 | 1 | protected void reEstablishCycConnection() throws UnknownHostException, IOException, CycApiException {
previousAccessedMilliseconds = System.currentTimeMillis();
cycConnection.close();
cycConnection = new CycConnection(hostName,
port,
this);
if (!(cycImageID.equals(getCycImageID()))) {
Log.current.println("New Cyc image detected, resetting caches.");
CycObjectFactory.resetCaches();
}
} |
48a4d698-88dd-4a49-9aac-ab9675934da2 | 4 | public UIAltaAnuncio() {
cal.setTime(new Date());
vendedor = usuarioservice.obtenerVendedor(usuarioservice.validar(usuario, contrasenia));
initComponents();
jTextField3.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
enterSegundo+=1;
if (jTextField1.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Escribe algo en el buscador");
} else {
if(enterSegundo==2){
buscar(jTextField3.getText());
actualizarLista(jTable2, listaResultadoUsuarios, "Usuarios");
enterSegundo=0;}
}
}
}
/*
public void keyTyped(KeyEvent e) {
public void keyPressed(KeyEvent e) {
}*/
});
jSpinner1.setVisible(false);
jLabel6.setVisible(false);
/**
* Seteo de los íconos en los botones
*/
jButton4.setIcon(this.achicar(searchIcon, 30, 30));
jButton7.setIcon(this.achicar(flechabajo, 30, 30));
jButton8.setIcon(this.achicar(flecharriba, 30, 30));
jButton9.setIcon(this.achicar(flechabajo, 30, 30));
jButton10.setIcon(this.achicar(flecharriba, 30, 30));
for (Iterator<String> it = listaUsuariosCompleta.iterator(); it.hasNext();) {
String temporal = it.next();
arregloUsuarios.add(temporal);
}
AutoComplete.autocompletar(jTextField3, arregloUsuarios);
} |
9b3eabcb-380c-44b2-a224-d2bfb83eb53a | 8 | public Set<Map.Entry<Long,Float>> entrySet() {
return new AbstractSet<Map.Entry<Long,Float>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TLongFloatMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if (o instanceof Map.Entry) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TLongFloatMapDecorator.this.containsKey(k)
&& TLongFloatMapDecorator.this.get(k).equals(v);
} else {
return false;
}
}
public Iterator<Map.Entry<Long,Float>> iterator() {
return new Iterator<Map.Entry<Long,Float>>() {
private final TLongFloatIterator it = _map.iterator();
public Map.Entry<Long,Float> next() {
it.advance();
long ik = it.key();
final Long key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik );
float iv = it.value();
final Float v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv );
return new Map.Entry<Long,Float>() {
private Float val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry
&& ( ( Map.Entry ) o ).getKey().equals(key)
&& ( ( Map.Entry ) o ).getValue().equals(val);
}
public Long getKey() {
return key;
}
public Float getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Float setValue( Float value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<Long,Float> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
Long key = ( ( Map.Entry<Long,Float> ) o ).getKey();
_map.remove( unwrapKey( key ) );
modified = true;
}
return modified;
}
public boolean addAll( Collection<? extends Map.Entry<Long, Float>> c ) {
throw new UnsupportedOperationException();
}
public void clear() {
TLongFloatMapDecorator.this.clear();
}
};
} |
9dfa46c1-abc7-4608-a235-2913b33083c4 | 1 | public static void main(String[] args) throws Exception {
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++)
exec.execute(new Accesor(i));
TimeUnit.SECONDS.sleep(3);
exec.shutdownNow();
} |
381a5fb0-11c8-429a-8e07-79e4b23801b3 | 8 | @Override
public List<Item> getDepositedItems(String depositorName)
{
if((depositorName==null)||(depositorName.length()==0))
return new ArrayList<Item>();
final List<Item> items=new Vector<Item>();
final Hashtable<String,Pair<Item,String>> pairings=new Hashtable<String,Pair<Item,String>>();
for(final PlayerData PD : getRawPDDepositInventory(depositorName))
{
final Pair<Item,String> pair=makeItemContainer(PD.xml());
if(pair!=null)
pairings.put(PD.key(), pair);
}
for(final Pair<Item,String> pair : pairings.values())
{
if(pair.second.length()>0)
{
Pair<Item,String> otherPair = pairings.get(pair.second);
if((otherPair != null)&&(otherPair.first instanceof Container))
pair.first.setContainer((Container)otherPair.first);
}
items.add(pair.first);
}
return items;
} |
90a87e07-5321-438d-839e-9d11aadbab90 | 4 | @Override
public Object registeringGUI() {
String name, descr;
int year;
double initPrice;
name = guiImpl.requestData("Nome:");
descr = guiImpl.requestData("Decrição:");
while(true){
try{
year = Integer.parseInt(guiImpl.requestData("Ano:"));
break;
}catch(NumberFormatException e){
GUIAbsTemplate.operationFailedGUI("Ano inválido");
}
}
while(true){
try{
initPrice = Float.parseFloat(guiImpl.requestData("Preço:"));
break;
}catch(NumberFormatException e){
GUIAbsTemplate.operationFailedGUI("Preço inválido");
}
}
return new Product(name, descr, initPrice, year);
} |
413b3e68-ffcf-4ba3-9126-48d26dec1eed | 0 | private Memento(int state) {
this.state = state;
} |
9bc49188-9fe1-4c18-a7c3-fd939b6f7d99 | 3 | public boolean verify(byte[] sig) throws Exception{
int i=0;
int j=0;
byte[] tmp;
if(sig[0]==0 && sig[1]==0 && sig[2]==0){
j=((sig[i++]<<24)&0xff000000)|((sig[i++]<<16)&0x00ff0000)|
((sig[i++]<<8)&0x0000ff00)|((sig[i++])&0x000000ff);
i+=j;
j=((sig[i++]<<24)&0xff000000)|((sig[i++]<<16)&0x00ff0000)|
((sig[i++]<<8)&0x0000ff00)|((sig[i++])&0x000000ff);
tmp=new byte[j];
System.arraycopy(sig, i, tmp, 0, j); sig=tmp;
}
//System.err.println("j="+j+" "+Integer.toHexString(sig[0]&0xff));
return signature.verify(sig);
} |
594ff528-bbeb-4343-a171-ab3172e35b7e | 7 | public void drawCCW(Bitmap bitmap, int xo, int yo) {
for (int y = 0; y < bitmap.width; y++) {
int yy = bitmap.width - y + yo;
if (yy < 0 || yy >= this.height)
continue;
for (int x = 0; x < bitmap.height; x++) {
int xx = x + xo;
if (xx < 0 || xx >= this.width)
continue;
int color = bitmap.pixels[y + x * bitmap.width];
if (color < 0)
pixels[xx + yy * this.width] = color;
}
}
} |
20696e5a-8d92-4ccb-83cb-517d8ae52eee | 3 | @Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getSource() instanceof JFormattedTextField) {
JFormattedTextField jtf = (JFormattedTextField) evt.getSource();
if ("File Size Change".equals(jtf.getName())) {
Number num = (Number) jtf.getValue();
if (num != null) {
model.setMinMovieFileSize(num.floatValue());
updateViews();
}
}
}
} |
d022f529-de4b-423d-b1dc-4cb62825ce27 | 9 | public static String getProperName(String name) {
String stringSplitUp[], totalString = null;
// Regex strip everthing exept leters and spaces.
name = name.replaceAll("[^A-Za-z ]", "_").trim();
if (name != null && !name.isEmpty() && name.length() > 1) {
stringSplitUp = name.split(" ");
if (stringSplitUp != null && stringSplitUp.length >= 1) {
// For each String array element make the first letter upper then the rest lower.
for (int i = 0; i < stringSplitUp.length; i++) {
// Make the string lower case all except for the first letter
if (stringSplitUp[i].length() >= 1) {
String restOfSubString = stringSplitUp[i].substring(1, stringSplitUp[i].length()).toLowerCase();
String capFirstLetterThenRest = stringSplitUp[i].substring(0, 1).toUpperCase() + restOfSubString;
// Add everthing together
if (totalString != null) {
totalString = totalString + " " + capFirstLetterThenRest;
} else {
totalString = capFirstLetterThenRest;
}//if(totalString != null){
} else {
if (totalString != null) {
// Make upper case first letter then combine the rest of the string.
totalString = totalString + " " + stringSplitUp[i].substring(0, 1).toUpperCase();
} else {
totalString = stringSplitUp[i].substring(0, 1).toUpperCase();
}//if(totalString != null){
}//if(stringSplitUp[i].length() >= 1){
}//for(int i = 0; i < stringSplitUp.length; i++){
}//if(stringSplitUp != null && stringSplitUp.length >= 1){
return totalString.trim();
}
return null;
} |
7d79ce86-8271-4738-847d-6e42ddfaf289 | 2 | private void setupIndividualCardPosition(Card card, int rowNumber,
int colNumber) {
final int CARD_DISPLAY_TOP = 60;
final int DISPLAY_GAP = 6;
int leftPositionForRow = getLeftPositionForRow(rowNumber);
int y = CARD_DISPLAY_TOP + (cardHeight * 3 / 4) * rowNumber;
int x = CARD_DISPLAY_LEFT + leftPositionForRow
+ (cardWidth + DISPLAY_GAP - 1) * colNumber;
if (rowNumber == 0 || rowNumber == NUMBER_OF_ROWS - 1) {
x = CARD_DISPLAY_LEFT + leftPositionForRow
+ (cardWidth + DISPLAY_GAP - 1) * 2 * colNumber;
}
card.setCardArea(x, y, cardWidth, cardHeight);
} |
8937c880-c872-48ad-93f1-edceba88447d | 2 | private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
DepartamentoBO departamentoBO = new DepartamentoBO();
try {
departamentoBO.DeleteDepartamento(txtCodDepartamnento.getText());
JOptionPane.showMessageDialog(null, "Departamento Deletado com Sucesso !!!",
"Gestão de Departamento", JOptionPane.INFORMATION_MESSAGE);
logSegurancaDados log = null;
log = new logSegurancaDados("INFO",
"Exclusão de Departamento realizada com sucesso pelo "
+ usuarioLogado.getTipo() + " : " + usuarioLogado.getNome());
txtCodDepartamnento.setText("");
txtNomeDepartamento.setText("");
this.listarDepartamentos();
this.btnExcluir.setEnabled(false);
this.btnSalvarAlteracao.setEnabled(false);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao deletar o departamento\n"
+ " Não é possivel deletar este Departamento",
"Gestão de Departamento", JOptionPane.ERROR_MESSAGE);
} catch (excecaoDeletarElemento ex) {
JOptionPane.showMessageDialog(null, "Erro ao deletar o departamento\n"
+ " Não é possivel deletar este Departamento",
"Gestão de Departamento", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_btnExcluirActionPerformed |
d152bf84-d8aa-40cb-b708-1123bf2ee265 | 8 | @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
if (!(sender instanceof Player))
{
sender.sendMessage("Only players can use this command.");
return true;
}
Player p = (Player) sender;
Block lookingAt = Utilities.getLookingAtAir(p);
if(lookingAt == null)
{
sender.sendMessage("no block found");
return true;
}
Material m = p.getItemInHand().getType();
if (m.isBlock())
{
if (label.equals("floor"))
{
fillFloor(p, m, lookingAt);
p.sendMessage("Success! Placed " + count + " " + m + " as a floor.");
}
else if(label.equals("wall"))
{
Block look = Utilities.getLookingAtBlock(p);
if(look.getX() == lookingAt.getX() && look.getZ() == lookingAt.getZ())
{
p.sendMessage("Cannot build a wall here.");
return true;
}
else
{
if(look.getX() == lookingAt.getX())
{
// Z-axis wall
fillWall(p, m, lookingAt.getX(), lookingAt.getY(), lookingAt.getZ(), 0, 1);
}
else
{
// X-axis wall
fillWall(p, m, lookingAt.getX(), lookingAt.getY(), lookingAt.getZ(), 1, 0);
}
}
p.sendMessage("Success! Placed " + count + " " + m + " as a wall.");
}
} else
{
p.sendMessage("Cannot place this type of block.");
return true;
}
return true;
} |
cf1a94df-a440-4e10-8e05-80c59ae6f89b | 9 | @EventHandler
public void OnGameQuit(GameQuitEvent event){
String pName = event.getPlayerName();
Player p = event.getPlayer();
if (plugin.PlayersInGame.contains(pName))
{
plugin.PlayersInGame.remove(pName);
if (plugin.sbHandler.badTeam != null && plugin.sbHandler.goodTeam != null)
{
if (plugin.sbHandler.badTeam.hasPlayer(p))
{
if (plugin.sbHandler.badTeam.getPlayers().size() == 1)
{
plugin.sbHandler.badTeam.removePlayer(p);
GameEndEvent e = new GameEndEvent(plugin.PlayersInGame);
plugin.getServer().getPluginManager().callEvent(e);
}
}
else if (plugin.sbHandler.goodTeam.hasPlayer(p))
{
if (plugin.sbHandler.goodTeam.getPlayers().size() == 1)
{
plugin.sbHandler.goodTeam.removePlayer(p);
GameEndEvent e = new GameEndEvent(plugin.PlayersInGame);
plugin.getServer().getPluginManager().callEvent(e);
}
}
}
if (plugin.sbHandler.manager != null)
{
p.setScoreboard(plugin.sbHandler.manager.getNewScoreboard());
}
}
if(plugin.PlayersInGame.size() <= 1){
GameEndEvent e = new GameEndEvent(plugin.PlayersInGame);
plugin.getServer().getPluginManager().callEvent(e);
}
} |
1c32f81e-2462-4be0-99d3-9e6e25463fb3 | 3 | public void visitGotoStmt(final GotoStmt stmt) {
if (stmt.target() == oldDst) {
if (FlowGraph.DEBUG) {
System.out.print(" replacing " + stmt);
}
stmt.setTarget(newDst);
if (FlowGraph.DEBUG) {
System.out.println(" with " + stmt);
}
}
} |
0c7854c1-c0a6-4a19-a7e9-20a4e7ee9ed8 | 8 | @EventHandler (priority = EventPriority.NORMAL)
public void join(final PlayerJoinEvent evt) {
String name = evt.getPlayer().getDisplayName();
evt.setJoinMessage(null);
for (Player pl : Bukkit.getServer().getOnlinePlayers()) {
if (pl.getName().equalsIgnoreCase(evt.getPlayer().getName())) break;
if (pl.hasPermission("group.mod")) {
pl.sendMessage(evt.getPlayer().getDisplayName() + ChatColor.GREEN + " has joined the game " + ChatColor.RED + "(" + ChatColor.WHITE + address.get(name) + ChatColor.RED + ")");
if (!evt.getPlayer().hasPlayedBefore()) {
pl.sendMessage(String.format("%sThis is their first time on the server!", ChatColor.GREEN));
}
} else {
if (evt.getPlayer().hasPlayedBefore()) {
pl.sendMessage(String.format("%s%s has joined the game", evt.getPlayer().getDisplayName(), ChatColor.GREEN));
} else {
pl.sendMessage(String.format("%s%s has joined the game for the first time", evt.getPlayer().getDisplayName(), ChatColor.GREEN));
}
}
}
if (!evt.getPlayer().hasPlayedBefore() && !evt.getPlayer().hasPermission("group.users"))
evt.getPlayer().sendMessage(
ChatColor.translateAlternateColorCodes('&', this.plugin.getConfig().getString("new_player").replaceAll("<player>", name)));
new PlayerList(evt.getPlayer());
evt.getPlayer().sendMessage(fileHandler.contents);
new BukkitRunnable() {
@Override
public void run() {
evt.getPlayer().playSound(evt.getPlayer().getLocation(), Sound.CHICKEN_EGG_POP, 2500, 2500);
for (int i = 0; i < 3; i++) {
evt.getPlayer().playEffect(EntityEffect.WOLF_HEARTS);
}
}
}.runTaskLater(plugin, 2);
} |
ea3c9a28-735e-4cd3-bede-b9ce3160c3ea | 0 | public Object getResponse() {
return response;
} |
d4b5b0f7-0744-456f-98dd-72bf22b98778 | 9 | public static String nickOf(final String source) {
if (source.length() < 1) {
return "";
}
final int si;
switch (source.charAt(0)) {
case '#':
case '!':
case '&':
case '*':
return "";
case '+':
case '@':
case '%':
si = 1;
break;
default:
si = 0;
break;
}
final int idx = source.indexOf('!');
if (idx != -1) {
return source.substring(si, idx);
} else {
return source;
}
} |
fb886821-e656-46ff-8ec4-d9b9a7f0cca3 | 0 | public Crs getCrs()
{
return crs;
} |
54060b73-5b00-4d99-a241-b1d58158d017 | 8 | private Boolean checkTables() throws Exception {
if (!this.db.checkTable("chunky_objects")) {
if (!db.createTable(QueryGen.createObjectTable())) return false;
Logging.info("Created chunky_objects table.");
}
if (!this.db.checkTable("chunky_ownership")) {
if (!db.createTable(QueryGen.createOwnerShipTable())) return false;
Logging.info("Created chunky_ownership table.");
}
if (!this.db.checkTable("chunky_permissions")) {
if (!db.createTable(QueryGen.createPermissionsTable())) return false;
Logging.info("Created chunky_permissions table.");
}
if (!this.db.checkTable("chunky_groups")) {
if (!db.createTable(QueryGen.createGroupsTable())) return false;
Logging.info("Created chunky_groups table.");
}
return true;
} |
e22654da-3a78-4a19-9fdc-43aa12b8ec44 | 5 | public String doFilter(String input) {
StringBuffer buffer = new StringBuffer();
File file = new File(input);
if (file.exists()) {
if (file.isDirectory()) {
File list[] = file.listFiles();
for (int i = 0; i < list.length; ++i) {
if (showFullPath) {
buffer.append(list[i]);
buffer.append('\n');
} else {
buffer.append(list[i].getName());
buffer.append('\n');
}
}
} else {
if (showFullPath) {
buffer.append(file);
buffer.append('\n');
} else {
buffer.append(file.getName());
buffer.append('\n');
}
}
}
return buffer.toString();
} |
cedb2ef0-e4e5-49d3-ac87-b7304b562e29 | 3 | public void addEvent(final GenericEvent ge) {
final Class<?> c = ge.getClass( );
if ( this.handlers.containsKey(c) )
for (final EventHandler h : this.handlers.get(c))
h.add(ge);
} |
a0f1149f-65c1-47c4-a8c7-a66071bb2fcf | 7 | public ArrayList<Integer> findLongestTrainTrack(){
ArrayList<Integer> maxId = new ArrayList<Integer>(); //最長火車的id序列
for(int i=0 ; i<receivingTrack.length ; i++){
int count = maxId.size();
for(int j=maxId.size()-1 ; j>=0 ; j--){
if(receivingTrack[i].ifEmpty == false){
if(receivingTrack[i].train.size() > receivingTrack[maxId.get(j)].train.size()){
count = j;
}
}
}
if(receivingTrack[i].ifEmpty == false)
maxId.add(count, i);
}
if(maxId.isEmpty()){ //如果為空
maxId.add(-1);
}
else{
for(int i: maxId)
System.out.println("%%" + receivingTrack[i].train.size());
}
return maxId;
} |
9782fb21-fbe1-4790-83a7-8b65f46aeab2 | 3 | @Override
public void addIllness(IllnessDTO illness) throws SQLException {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(illness);
session.getTransaction().commit();
}
catch (Exception e) {
System.err.println("Error while adding an illness!");
}
finally {
if (session != null && session.isOpen())
session.close();
}
} |
8934ff3d-0253-466a-9d9f-928c8e3039e8 | 8 | String classToType(Class cls) {
if (cls==Point.class) {
return "int2";
} else if (cls==Integer.TYPE
|| cls==Integer.class ) {
return "int";
} else if (cls==Double.TYPE
|| cls==Double.class ) {
return "double";
} else if (cls==String.class) {
return "String";
} else if (cls==Boolean.TYPE
|| cls==Boolean.class ) {
return "boolean";
} else {
return null;
}
} |
84563bb5-70e8-45de-bc91-72ca40aac8de | 3 | private boolean isValidFont(String name, Map<String, String> data) {
StringBuilder errorList = new StringBuilder();
// Iterate through the required fields and make sure we have the field
// we need! Otherwise append to the string builder, at this point we
// don't kill it and throw an exception. I believe it's more 'user
// friendly' this way, as it allows the developer to know everything
// that's went wrong at once.
for (String requiredField : REQUIRED_XML_FIELDS) {
if (!(data.containsKey(requiredField))) {
errorList.append("No field found for '").append(requiredField).append("'\n");
}
}
// If we received any errors whilst validating, output all of the found
// errors and return false
if (errorList.length() > 0) {
logger.error(new Exception(), "Failed at loading font for asset name ", name, "\n", errorList.toString());
return false;
}
return true;
} |
c5b78e0f-62ef-4870-bfd9-fc282c3f17d9 | 4 | private String getIdSetSqlCondition() {
if (!selectedIds.isPresent()) {
return "";
}
Set<Long> ids = selectedIds.get();
StringBuilder sb = new StringBuilder("id in (");
if (ids.isEmpty()) {
sb.append("null");
} else {
Iterator<Long> idIterator = selectedIds.get().iterator();
while (idIterator.hasNext()) {
Long id = idIterator.next();
sb.append(id);
if (idIterator.hasNext()) {
sb.append(",");
}
}
}
sb.append(")");
return sb.toString();
} |
5e6550bd-bcfa-456b-8d92-a46fce0b88ad | 5 | public void useSkill(Skill skill) {
if (skill.getEffect().getType().equals("remove debuffs")) {
skill.use(this, target);
}
else if (hitAvailable && !isStunned && !skill.isUsed() && !isDead) {
skill.use(this, target);
hitAvailable = false;
cooldownTimer.start();
}
} |
edc65a29-e524-4fae-939e-d39f0766bfd7 | 3 | protected void assignToTeamAOrB(String teamType) {
Object selectedValue = studentsCDJlst.getSelectedValue();
String selectedStudent = null;
int selectedIndex = 0;
if (selectedValue == null ) {
//warn no selected student
JOptionPane.showMessageDialog(this, "No student selected", "No student selected", JOptionPane.WARNING_MESSAGE);
} else {
selectedStudent = selectedValue.toString();
selectedIndex = studentsCDJlst.getSelectedIndex();
studentsCDDLM.removeElementAt(selectedIndex);
if (teamType.equals("A")) {
teamACDDLM.addElement(selectedStudent);
teamACDJlbl.setText("Team A(" + teamACDDLM.getSize() + "/" + userNumb + ")");
} else if (teamType.equals("B")) {
teamBCDDLM.addElement(selectedStudent);
teamBCDJlbl.setText("Team B(" + teamBCDDLM.getSize() + "/" + userNumb + ")");
}
}
} |
845f2996-8dd3-4fe9-b0bc-ebd1b14ae99d | 5 | private void enabledPanels(Boolean enabled){
for(int i=0;i<jTabbedPane1.getComponentCount();i++){
if(jTabbedPane1.getComponent(i) instanceof JPanel){
JPanel jpanelTemp=(JPanel)jTabbedPane1.getComponent(i);
for(int j=0;j<jpanelTemp.getComponentCount();j++){
jpanelTemp.getComponent(j).setEnabled(enabled);
}
}
}
if (enabled==false){
for(int j=0;j<this.jPanel3.getComponentCount();j++){
this.jPanel3.getComponent(j).setEnabled(!enabled);
}
}
} |
f1b35bf2-a826-4302-8e4a-6989ffda1055 | 3 | public Node search(Node x, int key) {
if (x == null || x.key == key) {
return x;
}
if (key < x.key) {
return search(x.left, key);
} else {
return search(x.right, key);
}
} |
5cc98aaf-4f3e-43c5-ac76-4d46b4bd838b | 7 | static final public void opRel() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 56:
jj_consume_token(56);
expression.empiler(EGAL);yvm.push(EGAL);
break;
case 57:
jj_consume_token(57);
expression.empiler(DIFFERENT);yvm.push(DIFFERENT);
break;
case 58:
jj_consume_token(58);
expression.empiler(INF);yvm.push(INF);
break;
case 59:
jj_consume_token(59);
expression.empiler(INFOUEG);yvm.push(INFOUEG);
break;
case 60:
jj_consume_token(60);
expression.empiler(SUP); yvm.push(SUP);
break;
case 61:
jj_consume_token(61);
expression.empiler(SUPOUEG); yvm.push(SUPOUEG);
break;
default:
jj_la1[23] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
} |
a7fdb261-e470-46dc-b256-a7219795663b | 6 | public static void removePacks (String xml) {
ArrayList<ModPack> remove = Lists.newArrayList();
int removed = -1; // TODO: if private xmls ever contain more than one modpack, we need to change this
for (ModPack pack : packs) {
if (pack.getParentXml().equalsIgnoreCase(xml)) {
remove.add(pack);
}
}
for (ModPack pack : remove) {
removed = pack.getIndex();
packs.remove(pack);
}
for (ModPack pack : packs) {
if (removed != -1 && pack.getIndex() > removed) {
pack.setIndex(pack.getIndex() - 1);
}
}
Main.getEventBus().post(new PackChangeEvent(PackChangeEvent.TYPE.REMOVE, true, xml));//makes sure the pack gets removed from the pane
} |
10193a80-7cc1-4c94-886b-9f2fa7ab9458 | 6 | final ItemDefinition method1177(int i) {
if (stackIDs != null && i > 1) {
int k = -1;
for (int l = 0; l < 10; l++) {
if (i >= stackAmounts[l] && stackAmounts[l] != 0) {
k = stackIDs[l];
}
}
if (k != -1) {
return NPC.itemDefinitionForID(k);
}
}
return this;
} |
a9b1f2c1-63a9-4a49-a377-04cd7cb9005c | 0 | public Iterator<Pfad> getPathIterator() {
return pfadList.iterator();
} |
220c9055-85a2-48c8-ad2e-529901ea51ab | 0 | protected void doEditing() {} |
2ce9c209-2856-4c69-9c07-18dfd2c883cf | 2 | public RuleConfigs custom(Tester<?,?> tester,String tag){
testerMapping.put(tag,tester);
return this;
} |
aec70c5d-8df8-440c-953a-c0003348dedb | 8 | @Override
//for simplicity, the getNeighbor method is the same for 4 and 8 pixels, works
//for both values (and even larger ones, for experiments)
public PixelInfo getNeighbor(PixelInfo pixel, int i, int width, int height) {
//in case that i>8:
//1 cycle = 8 pixels around the given pixel
//i'th neighbor = number of cycles (n) + rest
//still works best for i<=8 :-)
int rest = i%8;
int n=(i/8)+1;
int x = pixel.x;
int y = pixel.y;
switch (rest) {
case 0:
x=x+n;
break;
case 1:
y=y+n;
break;
case 2:
x=x-n;
break;
case 3:
y=y-n;
break;
case 4:
x=x+n;
y=y-n;
break;
case 5:
x=x+n;
y=y+n;
break;
case 6:
x=x-n;
y=y+n;
break;
case 7:
x=x-n;
y=y-n;
break;
}
//now we can calculate the new neighbor-pixel
PixelInfo neighbor = PixelInfo.createFromXY(x,y,width,height);
return neighbor;
} |
7cbf1309-18ce-43a0-b56e-995c05496b0e | 2 | private void verMensajes() {
Mensaje mensaje;
while ((mensaje = client.getNuevoMensaje()) != null)// llamamos a client
{
System.out.print(NUEVO_MENSAJE);
System.out.println(mensaje.getSource());
System.out.println(ASUNTO + mensaje.getTitulo());
System.out.println(MENSAJE + mensaje.getMsg());
System.out.println(SLASH);
if (yesNoQuestion(REPLY))
client.responderMensaje(mensaje, askMensaje());// llamamos a client
}
System.out.println(NO_NEW_MESSAGES);
} |
6c76adac-9cc1-4c55-ad0d-c40323f8b05c | 6 | public void checkforbubble() {
if (bubble == 1) {
setImage(bubble1);
}
else if (bubble == 2) {
setImage(bubble2);
}
else if (bubble == 3) {
setImage(enemylist);
}
else if (bubble == 4) {
setImage(enemylist2);
}
else if (bubble == 5) {
setImage(objectslist);
}
else if (bubble == 6) {
getWorld().addObject(new rockcounter(), 60, 100);
getWorld().addObject(new rocksleft(), 70, 20);
getWorld().addObject(new rocksleftcount(), 155, 20);
getWorld().addObject(new score(), 670, 20);
getWorld().addObject(new scorecounter(), 720, 20);
getWorld().addObject(new health(), 370, 20);
getWorld().addObject(new display(), 435, 20);
getWorld().addObject(new Dolphin(), 400, 300);
getWorld().addObject(new Eel(), 720, 250);
world dolphinworld = (world) getWorld();
maingame++; // sets variable up, so that the enemys won't respawn at the end of the map
bevorestart.stop();
dolphinworld.musicplay(); // starts the mainmusic
getWorld().removeObjects(getWorld().getObjects(turtle.class));
}
} |
28616659-15ad-48ff-a398-a7bc72ae7aa6 | 3 | public static void main(String[] args) {
MultipleLayerLruCache cache = new MultipleLayerLruCache(128, "C:/cache/", 1024L);
StringCache []datas = new StringCache[count];
for(int i=0;i<count;++i){
String s = "";
for(int j=0;j<48;++j) s += ""+i;
StringCache sc = new StringCache();
sc.mContent = s;
datas[i] = sc;
}
for(int i=0;i<datas.length;++i){
push(cache, ""+i, datas[i]);
}
} |
98bfd63d-cf1e-4e2c-8861-dcb84566e13d | 5 | private void detectFields() {
try {
ProtobufDecoder protobufDecoder = new ProtobufDecoder(
transMeta.environmentSubstitute(wClasspath.getText().trim()
.split(File.pathSeparator)), wRootClass.getText(),
null);
try {
Map<String, Class<?>> fields = protobufDecoder.guessFields();
RowMeta rowMeta = new RowMeta();
for (Entry<String, Class<?>> e : fields.entrySet()) {
String fieldPath = e.getKey();
int i = fieldPath.lastIndexOf('.');
String fieldName = i != -1 ? fieldPath.substring(i + 1)
: fieldPath;
rowMeta.addValueMeta(new FieldMeta(fieldName, fieldPath,
KettleTypesConverter.javaToKettleType(e.getValue())));
}
BaseStepDialog.getFieldsFromPrevious(rowMeta, wFields, 1,
new int[] { 1 }, new int[] { 3 }, -1, -1,
new TableItemInsertListener() {
public boolean tableItemInserted(
TableItem tableItem, ValueMetaInterface v) {
tableItem.setText(2, ((FieldMeta) v).path);
return true;
}
});
} finally {
protobufDecoder.dispose();
}
} catch (ProtobufDecoderException e) {
new ErrorDialog(
shell,
BaseMessages.getString("System.Dialog.Error.Title"),
Messages.getString("ProtobufDecodeDialog.ErrorDialog.ErrorDetectingFields"),
e);
}
} |
5520ec6d-5172-45e1-b9ab-032de31622cc | 4 | @MethodInformation(author="Wolfgang", date="07.12.2012", description="deletes element from Set")
public boolean delete(Object element) {
Node p = head;
Node prev = head;
while(p != null) {
if(p.getElement() == element) {
if(p == head)
head = p.getNextNode();
if(p == tail)
tail = prev;
return true;
}
prev = p;
p = p.getNextNode();;
}
return false;
} |
3410585f-9f80-4f71-aa59-55d67cc33b09 | 6 | public static Symbol getInstanceName(Stella_Object instanceref) {
{ Stella_Object instance = Logic.getInstance(instanceref);
{ Surrogate testValue000 = Stella_Object.safePrimaryType(instance);
if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_LOGIC_OBJECT)) {
{ LogicObject instance000 = ((LogicObject)(instance));
if ((instance000 != null) &&
(instance000.surrogateValueInverse != null)) {
return (Symbol.internSymbolInModule(instance000.surrogateValueInverse.symbolName, ((Module)(instance000.surrogateValueInverse.homeContext)), true));
}
}
}
else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_STELLA_THING)) {
{ Thing instance000 = ((Thing)(instance));
if ((instance000 != null) &&
(instance000.surrogateValueInverse != null)) {
return (Symbol.internSymbolInModule(instance000.surrogateValueInverse.symbolName, ((Module)(instance000.surrogateValueInverse.homeContext)), true));
}
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + testValue000 + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
}
return (null);
}
} |
0e571275-fc19-44e0-8209-a96f1b889883 | 8 | private static boolean isToken(String x)
{
return isString(x)||isFloat(x)||isIdentifier(x)||isKeyword(x)||isWhite(x)||isSemicolon(x)||isOpenParen(x)||isCloseParen(x)||isOperator(x);
} |
e75c90b6-aafa-408b-8b0d-f1fd37546e79 | 1 | public int bonusGain() {
int bonus = 0;
Iterator<Element> it = this.elements.iterator();
while (it.hasNext()) {
bonus += it.next().bonusGain();
}
return bonus;
} |
776bcfda-c3fd-4c7e-8bc8-01091018c099 | 5 | @Override
public String toString() {
byte b;
final StringBuilder s = new StringBuilder(bits.length * Byte.SIZE);
for (int i = 0; i < lastByte; i++) {
for (int j = Byte.SIZE - 1; j >= 0; j--) {
b = bits[i];
s.append((b >> j & 1) == 0 ? '0' : '1');
}
}
for (int j = Byte.SIZE - 1; j >= lastBit; j--) {
b = bits[lastByte];
s.append((b >> j & 1) == 0 ? '0' : '1');
}
return s.toString();
} |
334dc7eb-4458-4476-8226-cda58248f291 | 2 | public void output() {
if (!isEmpty()) {
for (ValueType current : this) {
System.out.print(current + " ");
}
System.out.println();
}
} |
d65215eb-af8a-4293-baa5-5733926505ab | 7 | private ArrayList<ArrayList<Integer>> createGen() {
ArrayList<ArrayList<Integer>> nextGen = new ArrayList<ArrayList<Integer>>();
double fitSum = getFitSum();
for (int i = 0; i < currGen.size(); i++) {
nextGen.add(new ArrayList<Integer>());
int parentOne = getIndividual(fitSum);
int parentTwo = getIndividual(fitSum);
int crossOverPoint = rand.nextInt() % currGen.get(i).size();
double shouldCross = rand.nextDouble();
if (shouldCross <= crossRate) {
for (int j = 0; j < currGen.get(i).size(); j++) {
double shouldMutate = rand.nextDouble();
if (shouldMutate <= mutRate) {
nextGen.get(i).add(individual.mutate(j));
} else {
if (j < crossOverPoint) {
nextGen.get(i).add(currGen.get(parentOne).get(j));
} else {
nextGen.get(i).add(currGen.get(parentTwo).get(j));
}
}
}
} else {
for (int j = 0; j < currGen.get(i).size(); j++) {
double shouldMutate = rand.nextDouble();
if (shouldMutate <= mutRate) {
nextGen.get(i).add(individual.mutate(j));
} else {
nextGen.get(i).add(currGen.get(parentOne).get(j));
}
}
}
}
return nextGen;
} |
0b323b49-19e7-4325-818a-42d8aa17da50 | 8 | protected void inPostAttrib(final char c)
{
switch(c)
{
case ' ': case '\t': case '\r': case '\n': bufDex++; return;
case '=': changeTagState(State.BEFOREATTRIBVALUE); return;
case '<':
endEmptyAttrib(endDex[State.INATTRIB.ordinal()]);
piece.innerStart = bufDex;
abandonTagState(State.BEFORETAG);
return;
case '>':
endEmptyAttrib(endDex[State.INATTRIB.ordinal()]);
changeTagState(State.START);
piece.innerStart =bufDex;
return;
case '/':
endEmptyAttrib(endDex[State.INATTRIB.ordinal()]);
changedTagState(State.BEGINTAGSELFEND);
return;
default: changedTagState(State.INATTRIB); return;
}
} |
a5a72f80-68aa-4754-81f8-ba25fc9b7f18 | 6 | private void configureCGIHeaderMap() {
// Find the child environment for the 'cgi_map_headers' section
Environment<String,BasicType> cgiHeaderMap =
this.getHandler().getGlobalConfiguration().getChild( Constants.CKEY_HTTPCONFIG_SECTION_CGI_MAP_HEADERS );
if( cgiHeaderMap == null ) {
this.getLogger().log( Level.WARNING,
getClass().getName() + ".configureCGIHeaderMap(...)",
"The HTTP config has no '" + Constants.CKEY_HTTPCONFIG_SECTION_CGI_MAP_HEADERS + "' section. No headers will be mapped to the CGI enviroment." );
return;
}
Iterator<Map.Entry<String,BasicType>> iter = cgiHeaderMap.entrySet().iterator();
while( iter.hasNext() ) {
Map.Entry<String,BasicType> entry = iter.next();
if( entry.getKey() == null
|| entry.getKey().length() == 0
|| entry.getValue() == null
|| !entry.getValue().getBoolean() ) {
continue;
}
this.getHandler().getCGIMapHeadersSet().add( entry.getKey() );
}
this.getLogger().log( Level.INFO,
getClass().getName() + ".configureCGIHeaderMap(...)",
"Set up cgiHeaderMap: " + this.getHandler().getCGIMapHeadersSet() );
/*
Set<String> includeHeaderSet = new TreeSet<String>( CaseInsensitiveComparator.sharedInstance );
BasicType wrp_documentRoot = this.getHandler().getGlobalConfiguration().get( Constants.CKEY_HTTPCONFIG_DOCUMENT_ROOT );
if( wrp_documentRoot != null ) {
String documentRoot = CustomUtil.processCustomizedFilePath( wrp_documentRoot.getString() );
this.getLogger().log( Level.INFO,
getClass().getName() + ".loadConfigurationFile(...)",
"Set up DOCUMENT_ROOT to '" + documentRoot + "' ..." );
this.getHandler().setDocumentRoot( new File(documentRoot) );
}
*/
} |
9ef05521-54da-40db-9d78-55d0131809d9 | 8 | protected double getBalance(MOB mob)
{
double balance = 0;
// return the balance in int form
if(surviveReboot)
{
final List<JournalEntry> V =CMLib.database().DBReadJournalMsgsByUpdateDate("BRIBEGATE_"+gates(), true);
final Vector<JournalEntry> mine = new Vector<JournalEntry>();
for (int v = 0; v < V.size(); v++)
{
final JournalEntry V2 =V.get(v);
if ( ( V2.from().equalsIgnoreCase(mob.Name())))
{
mine.addElement(V2);
}
}
for (int v = 0; v < mine.size(); v++)
{
final JournalEntry V2 = mine.elementAt(v);
final String fullName = V2.subj();
if (fullName.equals("COINS"))
{
final Coins item = (Coins) CMClass.getItem("StdCoins");
if (item != null)
{
CMLib.coffeeMaker().setPropertiesStr(item,V2.msg(), true);
item.recoverPhyStats();
item.text();
balance += item.getTotalValue();
}
}
}
}
else
{
Hashtable H=(Hashtable)notTheJournal.get(gates());
if(H==null)
{
H=new Hashtable();
notTheJournal.put(gates(),H);
}
Double D=(Double)H.get(mob.Name());
if(D==null)
{
D=Double.valueOf(0.0);
H.put(mob.Name(),D);
}
balance=D.doubleValue();
}
return balance;
} |
7ad0d932-684e-4565-a53b-ae6df0cc429e | 8 | @Override
public void run() {
try {
// Eclipse doesn't support System.console()
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
ConfigManager config = NetBase.theNetBase().config();
String targetIP = config.getProperty("net.server.ip");
if ( targetIP == null ) {
System.out.print("Enter the server's ip, or empty line to exit: ");
targetIP = console.readLine();
if ( targetIP == null || targetIP.trim().isEmpty() ) return;
}
System.out.print("Enter the server's RPC port, or empty line to exit: ");
String targetTCPPortStr = console.readLine();
if ( targetTCPPortStr == null || targetTCPPortStr.trim().isEmpty() ) return;
int targetTCPPort = Integer.parseInt( targetTCPPortStr );
System.out.print("Enter number of trials: ");
String trialStr = console.readLine();
int nTrials = Integer.parseInt(trialStr);
int socketTimeout = config.getAsInt("net.timeout.socket", 2000);
System.out.println("Host: " + targetIP);
System.out.println("tcp port: " + targetTCPPort);
System.out.println("trials: " + nTrials);
ElapsedTimeInterval pingResult = null;
if ( targetTCPPort != 0 ) {
ElapsedTime.clear();
JSONObject header = new JSONObject().put(EchoRPCService.HEADER_TAG_KEY, EchoRPCService.HEADER_STR);
pingResult = ping(header, targetIP, targetTCPPort, socketTimeout, nTrials);
}
if ( pingResult != null ) System.out.println("PING: " + String.format("%.2f msec (%d failures)", pingResult.mean(), pingResult.nAborted()));
} catch (Exception e) {
System.out.println("EchoRPC.run() caught exception: " +e.getMessage());
}
} |
ebb67adf-65de-496e-8779-332ea2f33cad | 8 | public synchronized void allsended ()
{
if (GD != null) GD.unchain();
if (Closed) return;
ListElement p = L.first();
int i, n = 0;
while (p != null)
{
n++;
p = p.next();
}
if (n > 3)
{
GamesObject v[] = new GamesObject[n - 1];
p = L.first().next();
for (i = 0; i < n - 1; i++)
{
v[i] = new GamesObject((String)p.content());
p = p.next();
}
Sorter.sort(v);
T.setText("");
T.appendLine0(" " + (String)L.first().content());
Color FC = Color.green.darker().darker();
for (i = 0; i < n - 1; i++)
{
T.appendLine0(v[i].game(), v[i].friend()?FC:Color.black);
}
T.doUpdate(false);
}
else
{
p = L.first();
while (p != null)
{
T.appendLine((String)p.content());
p = p.next();
}
T.doUpdate(false);
}
} |
b1d18634-b418-42c4-95c8-46f3fe0fff12 | 8 | public GibbsLDA (int K, int V, float alpha, float beta, int iter, int data [][]) {
this.K = K;
this.V = V;
this.alpha = alpha;
this.beta = beta;
this.iter = iter;
this.data = data;
this.M = data.length;
int N = 0;
Random random = new Random ();
zAssign = new int [M][];
//NWZ,NMZ,NZ,NM
NWZ = new int [V][K];
NMZ = new int [M][K];
NZ = new int [K];
NM = new int [M];
for (int i=0;i<V;++i) {
for (int j=0;j<K;++j) {
NWZ [i][j] = 0;
}
}
for (int i=0;i<M;++i) {
for (int j=0;j<K;++j) {
NMZ [i][j] = 0;
}
}
for (int i=0;i<K;++i) {
NZ [i] = 0;
}
for (int i=0;i<M;++i) {
NM [i] = 0;
}
// Create zAssign and init it
int z = 0;
int wordId = 0;
for (int m=0;m<M;++m) {
N = data [m].length;
zAssign [m] = new int [N];
for (int n=0;n<N;++n) {
wordId = data [m][n];
z = random.nextInt (this.K);
zAssign [m][n] = z;
NWZ [wordId][z] += 1;
NMZ [m][z] += 1;
NZ [z] += 1;
}
NM [m] += N;
}
} |
0c3c1580-48e8-4f36-a908-4e22b4eba44a | 8 | public boolean isValidItem(EntityType et, Material mat) {
if (et == null || mat == null) {
return false;
}
try {
if (ITEMS_REQUIRED.containsKey(et.name())) {
if (ITEMS_REQUIRED.get(et.name()).contains("ANY")) {
return true;
}
if (ITEMS_REQUIRED.get(et.name()).contains(String.valueOf(mat.getId()))) {
return true;
} else {
for (String s : ITEMS_REQUIRED.get(et.name())) {
if (s.toUpperCase().equals(mat.toString())) {
return true;
}
}
}
}
} catch (Exception ex) {
logDebug("isValidItem: Catching exception: " + ex.getMessage()
+ " [: " + et.name() + "] [" + mat.name() + "] [" + ITEMS_REQUIRED.size() + "]");
return false;
}
return false;
} |
5af72255-18a0-4936-8a3b-5a5384d06960 | 2 | @SuppressWarnings("unchecked")
private static <T> Converter<Object, T> lookupConversionService(Class from,
Class to) {
for (ConversionProvider converter : convServices) {
Converter c = converter.getConverter(from, to);
if (c != null) {
return c;
}
}
return null;
} |
766ccd39-3ee1-4c6a-9b27-348452a6c684 | 9 | private static void traverse(int row, int i, char[][] board) {
Stack<Pair> stack = new Stack<Pair>();
stack.push(new Pair(row, i));
while (!stack.isEmpty()) {
Pair p = stack.pop();
board[p.row][p.col] = 'E';
if (p.row - 1 > 0 && board[p.row - 1][p.col] == 'O') {
stack.push(new Pair(p.row - 1, p.col));
}
if (p.row + 1 != board.length && board[p.row + 1][p.col] == 'O') {
stack.push(new Pair(p.row + 1, p.col));
}
if (p.col - 1 > 0 && board[p.row][p.col - 1] == 'O') {
stack.push(new Pair(p.row, p.col - 1));
}
if (p.col + 1 != board[p.row].length && board[p.row][p.col + 1] == 'O') {
stack.push(new Pair(p.row, p.col + 1));
}
}
} |
2c9f89f0-3538-4363-86da-d82ffbf43f17 | 4 | public final int runNextPlan(int deciSeconds) throws FatalError,
RestartLater {
if (planManager == null) {
return deciSeconds;
}
GregorianCalendar finish = new GregorianCalendar();
finish.setTime(Config.getDate());
finish.add(Calendar.MILLISECOND, deciSeconds * 100);
while (((finish.getTimeInMillis() - new GregorianCalendar()
.getTimeInMillis()) / 100) > 0
&& planManager.runLookAhead())
;
if (planManager.wasLookAhead()) {
Output.printClockLn("Springe zurück -> " + name, Output.INFO);
}
return (int) ((finish.getTimeInMillis() - new GregorianCalendar()
.getTimeInMillis()) / 100);
} |
95351e63-0754-4913-8379-749fcbcefb39 | 7 | private void copyFileToArchive(final ZipArchiveOutputStream zos, final File file, final String dir) {
try {
if (file.isFile()) {
ZipArchiveEntry zae = new ZipArchiveEntry(dir + file.getName());
zae.setSize(file.length());
zos.putArchiveEntry(zae);
MessageDigest md = MessageDigest.getInstance("SHA-1");
DigestInputStream in = new DigestInputStream(new FileInputStream(file), md);
byte[] buf = new byte[16384];
int l = 0;
while ((l = in.read(buf)) > 0) {
zos.write(buf, 0, l);
progNow += l;
if (Thread.currentThread().isInterrupted()) {
zos.closeArchiveEntry();
return;
}
updateProgress();
}
Application.getController().displayVerbose("Hash of " + zae.getName() + ": " + new Base64().encodeToString(md.digest()));
zae.setComment(new Base64().encodeToString(md.digest()));
zos.closeArchiveEntry();
} else if (file.isDirectory()) {
File subs[] = file.listFiles();
for (int i = 0; i < subs.length; i++) {
copyFileToArchive(zos, subs[i], dir + file.getName() + "/");
}
}
} catch (IOException ex) {
Application.getController().displayError(bundle.getString("error_generic_io"), ex.getLocalizedMessage());
} catch (NoSuchAlgorithmException ex) {
Application.getController().displayError(bundle.getString("unknown_alg_text"), ex.getLocalizedMessage());
}
} |
8bb96fce-af0c-40c4-82a2-1f760dd2fe38 | 6 | @Override
public void run() {
while (!paused) {
update();
repaint();
if (inHandler.getKeys()[KeyEvent.VK_F3]) {
if(!opened){
opened=true;
// opens new frame
JFrame frame = new JFrame();
frame.setSize(500, 210);
frame.setLayout(new BorderLayout());
baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
old = System.out;
System.setOut(ps);
textArea1 = new JTextArea();
textArea1.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea1);
scrollPane.setPreferredSize(new Dimension(490,170));
frame.add(scrollPane, BorderLayout.NORTH);
textArea2 = new JTextArea();
textArea2.setPreferredSize(new Dimension(440,30));
frame.add(textArea2, BorderLayout.CENTER);
JButton but = new JButton("Enter");
but.setPreferredSize(new Dimension(50,30));
frame.add(but,BorderLayout.EAST);
frame.setVisible(true);
WinListener win = new WinListener();
but.addActionListener(win);
frame.addWindowListener(win);
Action keyAction = new AbstractAction() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println(textArea2.getText());
if(textArea2.getText().indexOf("/")==0){
String str= textArea2.getText().replace("/", "");
String[] str2 = str.split(" ");
Level.executeCommand(str2);
}
textArea2.setText("");
}
};
textArea2.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "ENTER key");
textArea2.getActionMap().put("ENTER key", keyAction);
System.out.println("Started Dev Console");
}
}
if(baos!=null){
if(!baos.toString().equals("")){
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
textArea1.append("<"+dateFormat.format(date)+">"+baos.toString());
baos.reset();
}
}
}
} |
20372854-b666-48eb-8795-91508afe6b0b | 9 | private void affichageErreur(List<Error> erreurs) {
for (Error e : erreurs) {
switch (e) {
case raisonSocialeVide:
this.labelErreurRaisonSociale.setText("Veuillez saisir une raison sociale");
break;
case telephoneVide:
this.labelErreurTelephone.setText("Veuillez saisir un numéro de telephone");
break;
case telephoneInvalide:
this.labelErreurTelephone.setText("Veuillez saisir un numéro de telephone valide");
break;
case emailVide:
this.labelErreurEmail.setText("Veuillez saisir une adresse email");
break;
case emailInvalide:
this.labelErreurEmail.setText("Veuillez saisir une adresse email valide");
break;
case adresseVide:
this.labelErreurAdresse.setText("Veuillez saisir une adresse");
break;
case siretVide:
this.labelErreurSiret.setText("Veuillez saisir un numéro de siret");
break;
case siretInvalide:
this.labelErreurSiret.setText("Veuillez saisir un numéro de siret valide");
break;
}
}
} |
2bb0bc74-0f97-444c-94e7-a8221019a3bc | 2 | public static int[] scramble(int[] m, int[] c) {
int x = 0;
int y = 0;
while (x < m.length) {
if (y >= c.length) {
y = 0;
}
m[x] = m[x] * c[y];
x++;
y++;
}
return m;
} |
7892c1a3-8c78-4a98-a3ac-06b76f6cd0ee | 3 | @Override
public AuthorModel getAuthor(int id) throws WebshopAppException {
if (id > 0) {
try (Connection conn = getConnection()) {
String sql = "SELECT * FROM author WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
AuthorModel author = parseAuthor(rs);
LOGGER.trace(String.format("%s.GET_AUTHOR - %s %s",
this.getClass().getSimpleName(),
"Author get from database: ", author));
return author;
}
}
}
} catch (SQLException e) {
WebshopAppException excep = new WebshopAppException(
e.getMessage(), this.getClass().getSimpleName(),
"GET_AUTHOR");
LOGGER.error(excep);
throw excep;
}
} else {
LOGGER.error("Get Author: Input = null");
}
return null;
} |
5f394c61-a69b-45d3-bfa2-7c8a5d3c513f | 8 | @Override
public void Run()
{
List<ClassDocumentation> docs = DeserializeModel(Android);
for( ClassDocumentation doc : docs )
{
for( ThreadElement thread : doc.getValidatedThreads() )
{
HashSet<LinkType> types = new HashSet<LinkType>();
for( LinkSpan link : thread.Question.getLinks(doc.Klass) )
{
if( link.Validated )
{
types.add(link.LinkType);
}
}
for( AnswerElement ans : thread.Answers )
{
for( LinkSpan link : ans.getLinks(doc.Klass) )
{
if( link.Validated )
{
types.add(link.LinkType);
}
}
}
if( types.size() >= 3)
{
System.out.println("http://stackoverflow.com/questions/" + thread.Question.Id);
}
}
}
} |
c0b99b11-eb87-4e78-958b-fb56ee7bcdd9 | 3 | * @return the ID for the meeting
* @throws IllegalArgumentException if the meeting is set for a time in the past,
* of if any contact is unknown / non-existent
*/
public int addFutureMeeting(Set<Contact> contacts, Calendar date) throws IllegalArgumentException
{
now.setTime(new Date());
if(date.before(now))
{
throw new IllegalArgumentException("date should not be in the past");
}
for(Contact contact : contacts)
{
if(!isContactValid(contact))
{
throw new IllegalArgumentException("contact id " + contact.getId() + " is invalid");
}
}
MeetingImpl fm = new FutureMeetingImpl(contacts, date);
meetingList.add(fm);
meetingSet.add(fm);
return fm.getId();
} |
482ae2f4-573e-4425-a47b-1e630addaffd | 5 | @Override public void paintDeterminate(Graphics g, JComponent c) {
if (!(g instanceof Graphics2D)) {
return;
}
Insets b = progressBar.getInsets(); // area for border
int barRectWidth = progressBar.getWidth() - (b.right + b.left);
int barRectHeight = progressBar.getHeight() - (b.top + b.bottom);
if (barRectWidth <= 0 || barRectHeight <= 0) {
return;
}
// amount of progress to draw
int amountFull = getAmountFull(b, barRectWidth, barRectHeight);
if(progressBar.getOrientation() == JProgressBar.HORIZONTAL) {
// draw the cells
// float x = amountFull / (float)barRectWidth;
g.setColor(getColorFromPallet(pallet, 1));
g.fillRect(b.left, b.top, amountFull, barRectHeight);
g.setColor(getColorFromPallet(pallet, 0));
g.fillRect(b.left+amountFull, b.top, progressBar.getWidth()-amountFull, barRectHeight);
} else { // VERTICAL
//...
}
// Deal with possible text painting
if(progressBar.isStringPainted()) {
paintString(g, b.left, b.top, barRectWidth, barRectHeight, amountFull, b);
}
} |
8411657a-93d8-4af7-bccb-0ccaa5262ee1 | 7 | public static void OrdiVsJoueur(Parametre param){
Ligne ligneOrdi = new Ligne(param, true);
Ligne ligneJoueur = new Ligne(param, false);
LigneMarqueur liMarq = new LigneMarqueur(param.getTailleLigne());
Scanner sc = new Scanner(System.in);
String esp = param.esp(" "); // On récupère le nombre d'espace qu'il faut pour l'affichage
int nbCoup = 1;
String rep;
boolean continuer;
boolean gagne = false;
IA ordi = new IA(param);
System.out.println("\n Ordi : \n");
System.out.println("------------------------------------------------" + param.esp("---"));
System.out.println("| Joueur | "+esp+"Jeu"+esp+" |"+esp+"Réponse"+esp+"| Coup |");
System.out.println("------------------------------------------------" + param.esp("---"));
while(!gagne && nbCoup <= param.getNbCoupMax()){
do{
continuer = true;
System.out.println("Joueur : Entrez une combinaison("+ param.getTailleLigne() + " couleurs) : ");
rep = sc.nextLine();
if(rep.length() > param.getTailleLigne()){
System.out.println("Vous avez entré trop de couleurs.");
continuer = false;
}
else if(rep.length() < param.getTailleLigne()){
System.out.println("Vous n'avez pas entré assez de couleurs.");
continuer = false;
}
}while(!continuer);
System.out.print("| Vous avez entrez : | ");
ligneJoueur = ordi.jouer(liMarq); // L'ordinateur propose une combinaison, pas de souci si liMarq est vide. Tous ces éléments sont initilisés à 0
System.out.print(" ");
ligneOrdi.afficher();
liMarq = ligneJoueur.compare(ligneOrdi); // On compare la ligne de l'ordi avec la ligne secrète
System.out.print(" | ");
liMarq.afficher();
System.out.print(esp+" | "+nbCoup+ " |\n");
System.out.println("-------------------------------------------------" + param.esp("---"));
if(liMarq.gagne()){
System.out.println("L'ordi a gagné, en "+ nbCoup+" coups.");
gagne = true;
}
else if(nbCoup > param.getNbCoupMax()){
System.out.println("L'ordi2 a perdu ! le réponse était : " + ligneJoueur.toString());
}
nbCoup++;
}
} |
955ec2ad-585a-4372-af6a-3daf79de8afe | 1 | public void parseExpressions(String expressions, Handler handler) {
for(String expression : expressions.split("[\n\r,]+")) {
parseExpression(expression, handler);
}
} |
ff8fd0a7-35b8-4f5f-be5b-3170d14cdaea | 1 | public void toggle_draw_pf() {
if (!draw_pf_map) {
draw_pf_map = true;
APXUtils._pf_compute(0);
} else {
draw_pf_map = false;
}
} |
4f1f12f5-9d54-409a-8497-4fb8a1381701 | 9 | private Object readResolve() throws ObjectStreamException {
RectangleAnchor result = null;
if (this.equals(RectangleAnchor.CENTER)) {
result = RectangleAnchor.CENTER;
}
else if (this.equals(RectangleAnchor.TOP)) {
result = RectangleAnchor.TOP;
}
else if (this.equals(RectangleAnchor.BOTTOM)) {
result = RectangleAnchor.BOTTOM;
}
else if (this.equals(RectangleAnchor.LEFT)) {
result = RectangleAnchor.LEFT;
}
else if (this.equals(RectangleAnchor.RIGHT)) {
result = RectangleAnchor.RIGHT;
}
else if (this.equals(RectangleAnchor.TOP_LEFT)) {
result = RectangleAnchor.TOP_LEFT;
}
else if (this.equals(RectangleAnchor.TOP_RIGHT)) {
result = RectangleAnchor.TOP_RIGHT;
}
else if (this.equals(RectangleAnchor.BOTTOM_LEFT)) {
result = RectangleAnchor.BOTTOM_LEFT;
}
else if (this.equals(RectangleAnchor.BOTTOM_RIGHT)) {
result = RectangleAnchor.BOTTOM_RIGHT;
}
return result;
} |
edeb476e-2d43-4598-857f-adb4b5f76a3a | 1 | private int getDayOfBirth() {
view.printDayOfBirthInputRequest();
int dayOfBirth = ConsoleInputUtils.readIntValue();
List<ValidateException> validateExceptionList = new DOBValidator().validateDay(dayOfBirth);
if (!validateExceptionList.isEmpty()) {
view.printValidateExceptionsList(validateExceptionList);
dayOfBirth = getDayOfBirth();
}
return dayOfBirth;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.