method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
542439c2-2eb7-4a82-96fa-2703aca1e5bd | 7 | private boolean setCategory(int index) {
final String currentCategory = getCategory();
final String[] categorys = getCategorys();
if (categorys.length > index) {
final String target = categorys[index];
if (currentCategory.equalsIgnoreCase(target)) {
return true;
}
Component child = ctx.widgets.component(WIDGET_INTERFACE_MAIN, WIDGET_INTERFACE_CATEGORY).component(0);
if (child.valid() && child.click(true)) {
if (Condition.wait(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return getCategoryRectangle(ctx, target) != null;
}
})) {
ctx.sleep(400);
Component component = getCategoryRectangle(ctx, target);
if (component != null && component.interact("Select")) {
Condition.wait(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return !currentCategory.equalsIgnoreCase(getCategory());
}
}, 200, 10);
ctx.sleep(400);
}
}
}
return getCategory().equalsIgnoreCase(target);
}
// Assume true for only one category
return true;
} |
1dcf2307-5088-435c-a464-f9b561709423 | 9 | @Override
protected void parseSelf(Document doc)
throws ProblemsReadingDocumentException {
List<Element> scriptList = queryXPathList(SCRIPT_DESC_XPATH, doc);
for (Element el: scriptList) {
String rawData = el.getText();
// clear JavaScript escaping: "\/" --> "/", etc.
rawData = rawData.replaceAll("\\\\(.)", "$1");
// try to recover each property by its pattern
for (Map.Entry<String, Pattern> entry: dataPatterns.entrySet()) {
Matcher m = entry.getValue().matcher(rawData);
if (m.matches())
setProperty(entry.getKey(), m.group(1));
}
setTitle(getProperty("title"));
}
// fix url
String relativePath = getProperty("mediaLink");
try {
setProperty("mediaLink", resolveLink(relativePath).toString());
} catch (MalformedURLException e) {
setProperty("mediaLink", null);
throw new ProblemsReadingDocumentException(e);
}
try {
// if album or artist data is missing we can try to salvage it
// from parenting pages
String album = getProperty("album");
String artist = getProperty("artist");
// fix track number
if (album==null || album.isEmpty())
setProperty("album",getParent().getTitle());
if (artist==null || artist.isEmpty())
setProperty("artist",getParent().getParent().getTitle());
} catch (NullPointerException e) {
// skip if not enough parents in a line;
}
} |
7d664db7-9d98-4d01-9d49-88e8243cf310 | 1 | public Matrix[] invPsvd () {
Matrix[] residueMat = residue.getMatrix();
Matrix[] diagMat = diag.getMatrix();
Matrix[] decStackedToOneColMat = new Matrix[3];
decStackedToOneColMat[0] = reshapedProductUVBaseMat[0].times(diagMat[0]).plus(residueMat[0]).timesEquals(255.0);
if (codeCbCr) {
decStackedToOneColMat[1] = reshapedProductUVBaseMat[1].times(diagMat[1]).plus(residueMat[1]).timesEquals(255.0);
decStackedToOneColMat[2] = reshapedProductUVBaseMat[2].times(diagMat[2]).plus(residueMat[2]).timesEquals(255.0);
}
return decStackedToOneColMat;
} |
8c7665a5-3064-4dd3-a76d-400ec3da0229 | 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(New_Intervenant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(New_Intervenant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(New_Intervenant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(New_Intervenant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
New_Intervenant dialog = new New_Intervenant(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} |
82fccda4-35df-4ec3-9616-3cb795e2dda4 | 4 | private boolean AddIncomingTab(InetAddress ip) {
LinkedList<User> clients = this.client.getUsers();
for (User user : clients) {
if (user.getIP().equals(ip)) {
if (nextKeyEvents > (keyEvents.length - 1)) {
new Popup(
user.getName()
+ " tried to start a private chat with you. However you reached the maximum number of tabs, please close one!");
} else {
addTab(user);
return true;
}
}
}
if (ip != null) {
addTab(ip, ip.getHostName().replace(".local", ""));
}
return false;
} |
b1382c65-0c9e-44d5-883d-ecb47e0888d7 | 7 | @Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
super.executeMsg(myHost,msg);
if((affected!=null)
&&(affected instanceof MOB)
&&(msg.amISource((MOB)affected)||msg.amISource(((MOB)affected).amFollowing())||(msg.source()==invoker()))
&&(msg.sourceMinor()==CMMsg.TYP_QUIT))
{
unInvoke();
if(msg.source().playerStats()!=null)
msg.source().playerStats().setLastUpdated(0);
}
} |
f8fc90ac-0268-4c87-afa3-8632e6b01302 | 8 | public MainToolBar()
{
// Format those buttons to look natural (no background, border, etc)
upButton.setMargin(new Insets(0, 0, 0, 0));
upButton.setBorder(null);
upButton.setOpaque(false);
upButton.setContentAreaFilled(false);
upButton.setBorderPainted(false);
upButton.setEnabled(false);
upButton.setFocusPainted(false);
refreshButton.setMargin(new Insets(0, 0, 0, 0));
refreshButton.setBorder(null);
refreshButton.setOpaque(false);
refreshButton.setContentAreaFilled(false);
refreshButton.setBorderPainted(false);
refreshButton.setFocusPainted(false);
// Tooltips
upButton.setToolTipText("Go up a folder");
refreshButton.setToolTipText("Refresh");
locationBar.setToolTipText("The current path, relative to the backup directory");
// Format the directory text field to be disabled and a dark grey
locationBar.setDisabledTextColor(new Color(0.2f, 0.2f, 0.2f));
// Refresh button clicked
refreshButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// Disable options that require a selected file
MainFrame.getInstance().menubar.copyToOption.setEnabled(false);
MainFrame.getInstance().menubar.revisionsOption.setEnabled(false);
// Recreate the table
MainFrame.getInstance().redrawTable(MainFrame.getInstance().currentDirectory);
}
});
// Up button clicked
upButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// Figure out the new path
MainFrame.getInstance().currentDirectory = MainFrame.getInstance().currentDirectory.resolve(
"..").normalize();
// Disable the up button if we're in the backup directory
if(MainFrame.getInstance().currentDirectory.equals(Main.backupDirectory))
{
MainFrame.getInstance().toolbar.upButton.setEnabled(false);
}
// Disable options that require a selected file
MainFrame.getInstance().menubar.copyToOption.setEnabled(false);
MainFrame.getInstance().menubar.revisionsOption.setEnabled(false);
// And recreate the table
MainFrame.getInstance().redrawTable(MainFrame.getInstance().currentDirectory);
}
});
// Enter key pressed within the location bar
locationBar.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// Remove the separate character (it's just for looks)
String text = locationBar.getText();
if(!text.equals("") && text.charAt(0) == File.separatorChar)
{
text = text.substring(1);
}
// Calculate the new path
Path enteredPath = null;
try
{
enteredPath = Main.backupDirectory.resolve(text).toFile().getCanonicalFile().toPath();
}
catch(IOException e1)
{
Errors.nonfatalError("Could not interpret entered path.", e1);
}
// Make sure that the path is a directory and not a parent of the backup directory
if(enteredPath.toFile().isDirectory()
&& (!Main.backupDirectory.startsWith(enteredPath.normalize()) || Main.backupDirectory.equals(enteredPath.normalize())))
{
MainFrame.getInstance().redrawTable(enteredPath.normalize());
MainFrame.getInstance().currentDirectory = enteredPath.normalize();
}
else
{
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"The entered directory does not exist or is outside of the backup directory.");
}
// Possible disable or enable the up button
if(MainFrame.getInstance().currentDirectory.equals(Main.backupDirectory))
{
MainFrame.getInstance().toolbar.upButton.setEnabled(false);
}
else
{
MainFrame.getInstance().toolbar.upButton.setEnabled(true);
}
}
});
this.setFloatable(false);
this.add(upButton);
this.addSeparator();
this.add(refreshButton);
this.addSeparator();
this.add(locationBar);
} |
991dbe7a-4661-4b39-9ac8-6d17f2eee0d3 | 6 | public BTnode postOrderTraversal(BTnode root)
{
BTnode left, right;
if(root == null)
return null;
if(root.left == null && root.right == null)
return root;
left = postOrderTraversal(root.left);
right = postOrderTraversal(root.right);
//if(right != null)
//{
//for(;right.left != null; right = right.left);
//}
if(left != null && right != null)
{
right.right = root;
root.left = right;
root.right = null;
for(;right.left != null; right = right.left);
left.right = right;
right.left = left;
//for(;right.right!=null; right=right.right);
return root;
}
/*if(left == null && right != null)
{
right.left = left;
for(;right.right!=null; right=right.right);
//System.out.println("for2 done");
right.right = root;
return root;
}
if(left != null && right == null)
{
left.right = root;
root.left = left;
return root;
}*/
return null;
} |
783b1990-b975-4eb6-8d1b-912c97e98191 | 1 | public BufferedImage loadImage(String fnm) {
BufferedImage im = null;
try {
im = ImageIO.read(ImageLoader.class.getResource(fnm));
} catch (IOException e) {
//System.out.println("Load Image error for " + fnm + ":\n" + e);
}
return im;
} |
ccf6447d-9d53-45c3-92f9-6e89404e4192 | 1 | @Override
public void init(ServletConfig config) throws ServletException {
ServletContext sc = config.getServletContext();
String log4jLocation = config.getInitParameter("log4j-properties-location");
File propFile = new File(sc.getRealPath("/") + log4jLocation);
if (propFile.exists()) {
PropertyConfigurator.configure(sc.getRealPath("/") + log4jLocation);
LOGGER.info("Initializing log4j.");
} else {
throw new RuntimeException("Init log4j-properties-file not found");
}
super.init(config);
} |
cdb6d569-965f-41b9-9662-ae16ac331b80 | 5 | private void createT(String in1, String out)
{
TFlipFlop t = new TFlipFlop();
// Connect the first input
// Check if the in wire is an input
if (stringToInput.containsKey(in1))
{
Wire inWire = new Wire();
stringToInput.get(in1).connectOutput(inWire);
t.connectInput(inWire);
}
// Check if the in wire is an output
else if (stringToOutput.containsKey(in1))
{
Wire inWire = new Wire();
stringToOutput.get(in1).connectOutput(inWire);
t.connectInput(inWire);
}
// Check if the in wire is just a wire already known to the circuit
else if (stringToWire.containsKey(in1))
t.connectInput(stringToWire.get(in1));
else
MainFrame.showError("Error, the wire " + in1
+ " isn't in the circuit");
// Connect the output
// Check if the in wire is an output
if (stringToOutput.containsKey(out))
{
Wire outWire = new Wire();
stringToOutput.get(out).connectInput(outWire);
t.connectOutput(outWire);
}
// Check if the in wire is just a wire already known to the circuit
else if (stringToWire.containsKey(out))
t.connectOutput(stringToWire.get(out));
else
MainFrame.showError("Error, the wire " + out
+ " isn't in the circuit");
flipflops.add(t);
} |
5229ebe3-b4d4-4cd1-8532-037ba58e9b71 | 0 | void swap(ArrayList<Item> al,int item1, int item2) {
Item temp = al.get(item1);
al.set(item1, al.get(item2));
al.set(item2, temp);
} |
bf5db85f-62dd-49ff-b7e8-c2cde62eb743 | 1 | private JLabel getJLabel0() {
if (jLabel0 == null) {
jLabel0 = new JLabel();
jLabel0.setText("DATABASE TOOL");
}
return jLabel0;
} |
e0cd73a9-34dc-40c4-893e-ba2113095241 | 1 | private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(this.serverPort, 0, address);
isRunning = true;
} catch (IOException e) {
isRunning = false;
this.serverSocket = null;
isStopped = true;
Setup.println("[ForwardingService.openServerSocket] Forwarder detenido.");
throw new RuntimeException("No se puede abrir el puerto " + serverPort, e);
}
} |
4c397e53-bc0c-457c-b791-2d2e255e1aa2 | 4 | public static void printObjectType(Object o)
{
if (o instanceof Cat) {
System.out.println("Кошка");
}
else if (o instanceof Dog) {
System.out.println("Собака");
}
else if (o instanceof Bird) {
System.out.println("Птица");
}
else if (o instanceof Lamp) {
System.out.println("Лампа");
}
else {
System.out.println("Неизвестный тип");
}
} |
332aea4a-fec9-4515-ab37-e57ad189b0d1 | 0 | public void setTwitterModel(TwitterModel twitterModel) {
this.twitterModel = twitterModel;
} |
98db98d8-ce93-41d3-88fc-288ff4e8cc8b | 3 | public boolean stopTransaction() throws DatabaseManagerException {
if( inTransaction ) {
if( conn == null ) {
throw new IllegalStateException("Connection closed!");
}
try {
conn.setAutoCommit(originalCommit);
inTransaction = false;
} catch(SQLException e) {
throw new DatabaseManagerException("Error stopping transaction.", e);
}
}
return inTransaction;
} |
afa7124d-77b8-4cf1-b175-560fdcd1a593 | 0 | public Map<String, SubCommand> getCommandList() {
return commands;
} |
b7d97fc1-cdbf-4385-9bcb-b811c2f1a26e | 3 | public static int maxPathSum(TreeNode root) {
if (null == root) return 0;
List<Integer> max = new ArrayList<Integer>();
maxSinglePathSum(root, max);
int res = root.val;
for (Integer i : max) {
if (i > res) res = i;
}
return res;
} |
7cefe386-cff6-4303-aaa1-aaeac0ffbc4a | 9 | private final String lock2key(String lock) {
String key_return;
int len = lock.length();
char[] key = new char[len];
for (int i = 1; i < len; i++)
key[i] = (char) (lock.charAt(i) ^ lock.charAt(i - 1));
key[0] = (char) (lock.charAt(0) ^ lock.charAt(len - 1) ^ lock.charAt(len - 2) ^ 5);
for (int i = 0; i < len; i++)
key[i] = (char) (((key[i] << 4) & 240) | ((key[i] >> 4) & 15));
key_return = new String();
for (int i = 0; i < len; i++) {
if (key[i] == 0) {
key_return += "/%DCN000%/";
} else if (key[i] == 5) {
key_return += "/%DCN005%/";
} else if (key[i] == 36) {
key_return += "/%DCN036%/";
} else if (key[i] == 96) {
key_return += "/%DCN096%/";
} else if (key[i] == 124) {
key_return += "/%DCN124%/";
} else if (key[i] == 126) {
key_return += "/%DCN126%/";
} else {
key_return += key[i];
}
}
log.println(key_return);
return key_return;
} |
0f5c40dc-8e89-4bd8-b782-c528eff2e8ee | 3 | private String printTree(ClassifierTreeNode parent) {
String line = "\n|";
for (int i = 0; i < parent.getLevel(); i++) {
line += "-";
}
line += parent.getFeature().getName();
if (!parent.getChildren().isEmpty()) {
for (ClassifierTreeNode node : parent.getChildren()) {
line += printTree(node);
}
}
return line;
} |
62d6a748-3d61-4b3b-bd3e-858285fdb2d0 | 3 | public Nodo getObjetivo() {
ArrayList<Nodo> nodos = estado.getAdyacentes(estado.getActual());
int max = 0;
Nodo dest = null;
for (Nodo n : nodos) {
if (max < memoria.getNode(n.id).score) {
max = (int) memoria.getNode(n.id).score;
dest = n;
}
}
if (dest == null) {// No deberia hacerse esto, pero asi evitamos algun
// que otro pete
Random r = new Random();
dest = nodos.get(r.nextInt(nodos.size()));
}
return dest;
} |
789d5e16-d692-406d-8b77-e388a6b19803 | 5 | public String addBinary(String a, String b) {
StringBuilder builder = new StringBuilder();
int ia = a.length() - 1;
int ib = b.length() - 1;
int carry = 0;
while (ia >= 0 || ib >= 0) {
int d1, d2;
if (ia >= 0) {
d1 = a.charAt(ia) - '0';
} else {
d1 = 0;
}
if (ib >= 0) {
d2 = b.charAt(ib) - '0';
} else {
d2 = 0;
}
int sum = d1 + d2 + carry;
int d = sum % 2;
carry = sum / 2;
builder.append(d);
ia--;
ib--;
}
if (carry > 0) {
builder.append(carry);
}
return builder.reverse().toString();
} |
15de86b2-7e22-4e3c-856e-ad53817df63f | 9 | public void paint(Graphics g) {
if (g == null)
return;
if (image == null) {
image = canvas.createImage(IMG_TOTWIDTH, IMG_TOTHEIGHT);
g2 = image.getGraphics();
g2.setFont(new Font("Monospaced", Font.PLAIN, 11));
}
if (crtImage == null) {
crtImage = new BufferedImage(displayWidth, displayHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics gcrt = crtImage.getGraphics();
gcrt.setColor(TRANSPARENT_BLACK);
for (int i = 0, n = displayHeight; i < n; i += 2) {
gcrt.drawLine(0, i, displayWidth, i);
}
}
// Why is there transparency?
g2.drawImage(screen, 0, 0, null);
if (reset > 0) {
g2.setColor(darks[colIndex]);
int xp = 44;
if (reset < 44) {
xp = reset;
}
g2.drawString("JaC64 " + version + " - Java C64 - www.jac64.com",
xp + 1, 9);
g2.setColor(lites[colIndex]);
g2.drawString("JaC64 " + version + " - Java C64 - www.jac64.com",
xp, 8);
reset--;
} else {
String msg = "JaC64 ";
if ((message != null) && (message != "")) {
msg += message;
} else {
colIndex = 0;
}
msg += tmsg;
g2.setColor(darks[colIndex]);
g2.drawString(msg, 1, 9);
g2.setColor(lites[colIndex]);
g2.drawString(msg, 0, 8);
if (ledOn) {
g2.setColor(LED_ON);
} else {
g2.setColor(LED_OFF);
}
g2.fillRect(372, 3, 7, 1);
g2.setColor(LED_BORDER);
g2.drawRect(371, 2, 8, 2);
}
g.fillRect(0, 0, offsetX, displayHeight + offsetY * 2);
g.fillRect(offsetX + displayWidth, 0,
offsetX, displayHeight + offsetY * 2);
g.fillRect(0, 0, displayWidth + offsetX * 2, offsetY);
g.fillRect(0, displayHeight + offsetY,
displayWidth + offsetX * 2, offsetY);
Graphics2D g2d = (Graphics2D) g;
// g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
// RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.drawImage(image, offsetX, offsetY, displayWidth, displayHeight, null);
// g.drawImage(crtImage, offsetX, offsetY, displayWidth, displayHeight, null);
// monitor.info("Repaint: " + (System.currentTimeMillis() - repaint) + " " + memory[IO_OFFSET + 55296 + 6 * 40]);
// repaint = System.currentTimeMillis();
} |
f03a1927-999c-4a6e-80ca-f83917a3d562 | 4 | public Line(String type, Level l) {
this.level = l;
this.line = type;
if (line.contains("|")) {
String connect = line.split("\\|")[1];
String[] parameter = connect.split(",");
if (parameter[0].equals("ACTIVATE")) {
level.connect(parameter[1]).active = false;
}
}
try {
TextureImpl.unbind();
Image img = new Image("Arial.png");
img.bind();
fnt = new AngelCodeFont("Arial.fnt", img);
} catch (SlickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (line.split("\"").length == 2) {
}
} |
98ae4713-877c-4ac8-8b8d-6b03e2321b88 | 7 | AES256v2HeaderData(byte[] data) throws InvalidDataException {
Validate.notNull(data, "Data cannot be null.");
// Need the header to be able to determine the length
if (data.length < AES256v3Ciphertext.HEADER_SIZE) {
throw new InvalidDataException("Not enough data to read header.");
}
int index = 0;
version = data[index++];
if (version != AES256v3Ciphertext.EXPECTED_VERSION) {
throw new InvalidDataException(String.format(
"Expected version %d but found %d.",
AES256v3Ciphertext.EXPECTED_VERSION, version));
}
options = data[index++];
// Test for any invalid flags
if (options != 0x00 && options != AES256v3Ciphertext.FLAG_PASSWORD) {
throw new InvalidDataException("Unrecognised bit in the options byte.");
}
// If the password bit is set, we can expect salt values
isPasswordBased = ((options & AES256v3Ciphertext.FLAG_PASSWORD) == AES256v3Ciphertext.FLAG_PASSWORD);
final int minimumLength = (isPasswordBased) ? SIZE_WITH_PASSWORD
: SIZE_WITHOUT_PASSWORD;
if (data.length < minimumLength) {
throw new InvalidDataException(String.format(
"Data must be a minimum length of %d bytes, but found %d bytes.",
minimumLength, data.length));
}
if (isPasswordBased) {
encryptionSalt = new byte[AES256v3Ciphertext.ENCRYPTION_SALT_LENGTH];
System.arraycopy(data, index, encryptionSalt, 0, encryptionSalt.length);
index += encryptionSalt.length;
hmacSalt = new byte[AES256v3Ciphertext.HMAC_SALT_LENGTH];
System.arraycopy(data, index, hmacSalt, 0, hmacSalt.length);
index += hmacSalt.length;
} else {
encryptionSalt = null;
hmacSalt = null;
}
iv = new byte[AES256v3Ciphertext.AES_BLOCK_SIZE];
System.arraycopy(data, index, iv, 0, iv.length);
index += iv.length;
} |
c7c01e1f-9d59-4eb5-9559-db7740d78ad2 | 4 | public static <R> ImmutableGrid<R> copyOfDeriveCounts(Iterable<? extends Cell<R>> cells) {
if (cells == null) {
throw new IllegalArgumentException("Cells must not be null");
}
if (cells.iterator().hasNext() == false) {
return new EmptyGrid<R>();
}
int rowCount = 0;
int columnCount = 0;
for (Cell<R> cell : cells) {
rowCount = Math.max(rowCount, cell.getRow());
columnCount = Math.max(columnCount, cell.getColumn());
}
return new SparseImmutableGrid<R>(rowCount + 1, columnCount + 1, cells);
} |
8c8768ff-8376-42ff-b265-edb39b27aaa5 | 4 | public void setName(String name) {
if(!name.equals("") || name != null) {
synchronized (Person.class) {
if (!name.equals("") || name != null) {
this.name = name;
System.out.println(name);
}
}
}
} |
07860583-3cb3-4a4d-b2df-cc3048acc690 | 2 | public long getLong(String key) throws JSONException {
Object object = this.get(key);
try {
return object instanceof Number
? ((Number)object).longValue()
: Long.parseLong((String)object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) +
"] is not a long.");
}
} |
15a3f030-e49c-47d9-a692-93dd65f99972 | 5 | private static Number appropriateParseFor(String text, Class<? extends Number> numberFormat) throws NumberFormatException {
if(numberFormat == Long.class){
return Long.parseLong(text);
}
else if(numberFormat == Integer.class){
return Integer.parseInt(text);
}
else if(numberFormat == Double.class){
return Double.parseDouble(text);
}
else if(numberFormat == Float.class){
return Float.parseFloat(text);
}
else{
throw new RuntimeException("cant figure out appropriate number format");
}
} |
b03b3f23-c844-43e1-a5b5-24453935d8f1 | 8 | @Override
public Parameter getParameter(final int parameterIndex) {
Parameter parameter;
switch (parameterIndex) {
case 0:
case 1:
parameter = super.getParameter(parameterIndex);
break;
case 2:
parameter = rate;
break;
case 3:
parameter = pulseWidth;
break;
case 4:
parameter = depth;
break;
case 5:
parameter = phase;
break;
case 6:
parameter = resonance;
break;
case 7:
parameter = blend;
break;
default:
parameter = null;
}
return parameter;
} |
1f381d6d-a86f-497f-889c-3cd125778296 | 7 | private void followingItem(T infix, int degree) throws ShouldNotBeHereException, BadNextValueException
{
switch(degree)
{
case 0:
if(((String)infix).matches(OPERAND) || ((String)infix).matches(PARA1)) // no number or parenthesis
{throw new BadNextValueException("Opening parenthesis or number following a number");}
break;
case 1:
if(((String)infix).matches(OPERATOR)) // no operators
{throw new BadNextValueException("Operator following Operator");}
break;
case 2:
if(((String)infix).matches(PARA2)) // no )
{throw new BadNextValueException(") following (");}
break;
default:
throw new ShouldNotBeHereException();
}
} |
591ffc1b-9145-4e62-ad42-2ccea57dc466 | 1 | protected void setSingleReachable() {
if (getParent() != null)
getParent().setReachable();
} |
4775b8fe-0f70-4fe5-b563-d0a85687565e | 1 | public String toString()
{
if (uninitialized())
{
return "NO SUCH ROUTE";
}
return Integer.toString(length);
} |
9b513405-1c28-4be5-9e4b-17d7ac203beb | 5 | private void handleUpdate() {
// We can simplify this when we move more methods into the Preference Interface.
if (pref instanceof PreferenceHashMap) {
// Update pref
PreferenceHashMap prefHashMap = (PreferenceHashMap) pref;
DefaultTableModel model = (DefaultTableModel) table.getModel();
HashMap map = new HashMap();
// Turn model into a hashmap
for (int i = 0; i < model.getRowCount(); i++) {
String key = (String) model.getValueAt(i,1);
String value = (String) model.getValueAt(i,2);
if (key == null) {
key = "";
model.setValueAt(key,i,1);
}
if (value == null) {
value = "";
model.setValueAt(value,i,2);
}
if (map.containsKey(key)) {
key = "";
model.setValueAt(key,i,1);
}
map.put(key,value);
}
prefHashMap.tmp = map;
// Update
table.setModel(model);
model.fireTableDataChanged();
}
} |
6ca229b2-f2ad-4115-a754-8b9e924d99a1 | 0 | public static String js(){
return "<script type=\"text/javascript\">\n" +
"\n" +
" $(document).ready(function() {\n" +
" $('table')\n" +
" .bind('filterEnd', function () {\n" +
" var f = $.tablesorter.getFilters( $(this) );\n" +
" var empty=true\n" +
" for (var i = 0; i < f.length; i++) {\n" +
" if(f[i] != \"\"){\n" +
" empty=false;\n" +
" }\n" +
" }\n" +
" if(empty){\n" +
" console.log(\"empty\");\n" +
" $(\"[data-level]\").hide();\n" +
" $(\"[data-level='0']\").show();\n" +
" }\n" +
" else{\n" +
" console.log(\"not empty\");\n" +
" $(\"[data-level='1']\").hide();\n" +
" $(\"[data-level='2']\").hide();\n" +
" }\n" +
" });\n" +
"\n" +
"\n" +
" $(\"table\").tablesorter({\n" +
" cssChildRow: 'nosort',\n" +
" widgets: [\"zebra\", \"filter\"],\n" +
" widgetOptions : {\n" +
" // include child row content while filtering, if true\n" +
" filter_childRows : false,\n" +
" // search from beginning\n" +
" filter_startsWith : true,\n" +
" filter_columnFilters : true,\n" +
" }\n" +
" });\n" +
"\n" +
" function getChildren($row) {\n" +
" var children = [], level = $row.attr('data-level');\n" +
" while($row.next().attr('data-level') > level) {\n" +
"\n" +
" if($row.next().attr('data-level') == parseInt(level)+1){\n" +
" children.push($row.next());\n" +
" }\n" +
" $row = $row.next();\n" +
" }\n" +
" return children;\n" +
" }\n" +
"\n" +
" $('.parent').on('click', function() {\n" +
"\n" +
" var children = getChildren($(this));\n" +
" $.each(children, function() {\n" +
" if($(this).is(\":visible\")){\n" +
" var subchilds=getChildren($(this))\n" +
" $.each(subchilds, function() {\n" +
" $(this).hide()\n" +
" })\n" +
" }\n" +
" $(this).toggle();\n" +
" })\n" +
" });\n" +
" $(\"[data-level]\").hide();\n" +
" $(\"[data-level='0']\").show();\n" +
" })\n" +
"</script>";
} |
59fa9f97-a82a-4f5d-a2ca-3d11efbb6cb7 | 7 | int getPositive(int i){
int octaveOffset = i/ Constants.NOTES_IN_SCALE;
int mod = i% Constants.NOTES_IN_SCALE;
int noteOffset = 0;
if(mod > 0){
switch(mod){
case 6: noteOffset += steps[5];
case 5: noteOffset += steps[4];
case 4: noteOffset += steps[3];
case 3: noteOffset += steps[2];
case 2: noteOffset += steps[1];
case 1: noteOffset += steps[0];
}
}
return (octaveOffset* Constants.STEPS_IN_OCTAVE) + noteOffset;
} |
dbfa6e6d-c7b3-453d-9ccb-a4ccb3642c7d | 5 | private long removeRefAskData(long lIndex) {
//
// loop through the elements in the actual container, in order to find the one
// at lIndex. Once it is found, then loop through the reference list and remove
// the corresponding reference for that element.
//
AskData refActualElement = GetAskData(lIndex);
if (refActualElement == null)
return lIndex; // oh well.
// Loop through the reference list and remove the corresponding reference
// for the specified element.
//
for(int intIndex = 0; intIndex < elementList.size(); intIndex++)
{
Object theObject = elementList.get(intIndex);
if ((theObject == null) || !(theObject instanceof AskData))
continue;
AskData tempRef = (AskData)(theObject);
if ((AskData.getCPtr(tempRef) == AskData.getCPtr(refActualElement)))
{
elementList.remove(tempRef);
break;
}
}
return lIndex;
} |
c8ce9275-8393-4a3c-9110-9fa7df2d8f82 | 5 | public void sort(int [] intArray,int sequenceflag){
System.out.println("您调用的是选择排序算法");
int flag=0;
int max=intArray[0];
long startTime=System.nanoTime();
for(int i=intArray.length-1;i>0;i--)
{
//寻找最值放在最后
for(int j=0;j<i;j++){
if(intArray[j] > max)
{
max=intArray[j];
flag=j;
}
}
intArray[flag]=intArray[i];
intArray[i]=max;
max=intArray[0];
flag=0;
}
long endTime = System.nanoTime();
System.out.print("排序完成的数组是: {");
for(int i=0;i<intArray.length;i++)
{
if(i == intArray.length-1)
System.out.print(intArray[i]);
else
System.out.print(intArray[i]+", ");
}
//此处(endTime-startTime)必须有括号,要不然会报错
System.out.println("}\n排序的时间是"+(endTime-startTime)+"ns");
} |
53bce10c-d73f-4593-8aff-e9a6c2238333 | 4 | private List<Integer> quicksort(List<Integer> input)
{
if(input.size() <= 1)
{
return input;
}
int middle = (int) Math.ceil((double)input.size() / 2);
int pivot = input.get(middle);
List<Integer> less = new ArrayList<Integer>();
List<Integer> greater = new ArrayList<Integer>();
for (int i = 0; i < input.size(); i++)
{
if(input.get(i) <= pivot)
{
if(i == middle)
{
continue;
}
less.add(input.get(i));
}
else
{
greater.add(input.get(i));
}
}
return concatenate(quicksort(less), pivot, quicksort(greater));
} |
6229a0e4-4a49-4211-88bd-4b22d1f85a0a | 0 | public int[][] getBlockSheet() {
return blockSheet;
} |
5b0236dd-71f1-4651-af6f-db0dceb16206 | 2 | String represent(String s) {
if (s.length() == 1)
return s;
String s1 = represent(s.substring(0, s.length() / 2));
String s2 = represent(s.substring(s.length() / 2 + 1));
if (s1.compareTo(s2) > 0)
return s2 + s1;
return s1 + s2;
} |
fbe712be-9e6e-4256-bb73-81ddbfa91dad | 1 | public boolean canHaveAsCreditLimit(BigInteger creditLimit) {
return (creditLimit != null) && (creditLimit.compareTo(BigInteger.ZERO) <= 0);
} |
a99dd0e0-b8c1-4d19-9a16-f4b802153540 | 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(EleBase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(EleBase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(EleBase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(EleBase.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 EleBase().setVisible(true);
}
});
} |
4f0ff9a6-ea16-4768-8fe4-4adf343a9261 | 9 | private BigInteger findFactor(){
BigInteger sq = BigInteger.ONE.add(BigInteger.ONE);
while(!limit.mod(sq).equals(BigInteger.ZERO) && (sq.compareTo(limit)<=0)){
sq = sq.add(BigInteger.ONE);
}
System.out.println("Found 1st factor "+sq);
if (sq.compareTo(limit)>0)
return sq;
BigInteger lq = limit.divide(sq);
while (lq.compareTo(sq) >= 0){
if (isPrime(lq)){
return lq;
}
if (isPrime(sq)){
largePrime = sq;
}
sq = sq.add(BigInteger.ONE);
while(!limit.mod(sq).equals(BigInteger.ZERO) && (sq.compareTo(lq)<=0)){
sq = sq.add(BigInteger.ONE);
}
lq = limit.divide(sq);
}
//if it reaches here, it means it's a prime number itself.
if (largePrime.compareTo(BigInteger.ONE)>0 )
return largePrime;
else
return limit;
} |
32e3706b-f375-4e88-82c3-29c2a8756f5c | 6 | private void checkForErrors() {
// Retrieve the type of error from OpenGL.
int error = glGetError();
switch (error) {
case GL_NO_ERROR:
break;
case GL_INVALID_ENUM:
gameWorld.error(RenderingSystem.class, "OpenGL error: GL_INVALID_ENUM");
break;
case GL_INVALID_VALUE:
gameWorld.error(RenderingSystem.class, "OpenGL error: GL_INVALID_VALUE");
break;
case GL_INVALID_OPERATION:
gameWorld.error(RenderingSystem.class, "OpenGL error: GL_INVALID_OPERATION");
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
gameWorld.error(RenderingSystem.class, "OpenGL error: GL_INVALID_FRAMEBUFFER_OPERATION");
break;
case GL_OUT_OF_MEMORY:
gameWorld.error(RenderingSystem.class, "OpenGL error: GL_OUT_OF_MEMORY");
break;
}
} |
5b90546c-36ea-4113-8e67-57b598a0bfcd | 0 | @Test
public void testPlus(){
//ReversePolishNotationCalculator calculator = new ReversePolishNotationCalculator();
calculator.pushOperand(3.0);
calculator.pushOperand(2);
System.out.println(calculator.operandsToString());
calculator.pushPlusOperator();
System.out.println(calculator.operatorsToString());
calculator.evaluateStack();
assertEquals(5.0, calculator.popOperand(), 0);
} |
54a089df-24cc-4cab-a288-696a13325bd9 | 0 | @Basic
@Column(name = "FES_USUARIO")
public String getFesUsuario() {
return fesUsuario;
} |
8b67efad-ba10-4f1b-bd60-3d100afd4950 | 2 | public int getNextBlock() {
for(int i = 0; i < this.blocks.length; i++){
if(blocks[i] == null)
return i;
}
return -1;
} |
5cab4ffe-e118-47d1-8ba2-d266c1a146c2 | 9 | private boolean addGroupsFrame(){
boolean ret = false;
try {
// Создадим поле ввода
JTextField num = new JTextField();
// загрузим данные для комбобокса
Faculty[] facultys = ua.edu.odeku.pet.database.data.GetDataTable.getFacultys();
// создадим комбобокс
JComboBox<Faculty> box = new JComboBox<Faculty>(facultys);
// Создаем штуку для ввода времени
JYearChooser year = new JYearChooser();
Calendar calendar = Calendar.getInstance();
// Получим текущий год
int y = calendar.get(Calendar.YEAR);
year.setStartYear(y - 10);
year.setEndYear(y + 2);
// Собираем компоненты
JComponent[] component = new JComponent[]{
new JLabel("Номер группы:"),
num,
new JLabel("Год поступления:"),
year,
new JLabel("Факультет:"),
box
};
do {
boolean flag = SMS.dialog(this, "Введите данные о группе:", component);
if (!flag) {
break;
}
String number = num.getText();
if (number.trim().length() <= 0) {
SMS.warning(this, "Введите номер группы!");
continue;
}
int numb;
try {
numb = Integer.parseInt(number);
} catch (NumberFormatException ex) {
SMS.message(this, "Номер группы должен быть числом\nили ввели слишком большое число!");
continue;
}
int inputYear = year.getYear();
if (box.getSelectedItem() == null) {
SMS.message(this, "Укажите факультет!");
continue;
}
// Все проверки прошли
// Собираем объект
Groups groups = new Groups();
groups.setNumGroup(numb);
groups.setYearSupply(inputYear);
groups.setFaculty((Faculty) box.getSelectedItem());
int res = groups.insertInto();
if (res == -1) {
if (SMS.query(this, "Такое значение уже есть,\nХотите другие данные ввести?")) {
continue;
} else {
break;
}
} else if (res >= 0) {
ret = true;
break;
}
} while (true);
} catch (SQLException ex) {
SMS.error(this, ex.toString());
Logger.getLogger(GroupsInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
this.dispose();
} finally {
return ret;
}
} |
efa56b81-2801-4d55-bc06-c4dad5e24d16 | 3 | public RseqVNode(AbsValueNode n1, AbsValueNode n2, AbsValueNode n3, int line) {
super(line);
if (n1 != null && n2 != null && n3 != null)
setChildren(n1, n2, n3);
} |
45c7d4a1-9ab4-4ca1-a606-43491e84e202 | 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 Sale)) {
return false;
}
Sale other = (Sale) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} |
7ce67327-7f57-4a2c-a119-9d083c734e2b | 3 | private synchronized void sendInfoPacket(Sim_event ev)
{
IO_data data = (IO_data) ev.get_data();
Object obj = data.getData();
// gets all the relevant info
long size = data.getByteSize();
int destId = data.getDestID();
int netServiceType = data.getNetServiceLevel();
int tag = ev.get_tag();
String name = GridSim.getEntityName(outPort_.get_dest());
// we need to packetsize the data, all packets are sent with size MTU
// only the last packet contains the ping data, the receiver should
// throw away all other data
int MTU = link_.getMTU();
int numPackets = (int) Math.ceil(size / (MTU * 1.0));
// break ping size into smaller pieces
// Also, make sure that it is not for pinging itself
FnbEndToEndPath conn; // = new FnbEndToEndPath(destId, super.get_id(), netServiceType, numPackets);
int glID;
if (obj instanceof Gridlet)
{
glID = ((Gridlet) obj).getGridletID();
conn = new FnbEndToEndPath(destId, super.get_id(), netServiceType, numPackets, glID, false);
}
else
{
conn = new FnbEndToEndPath(destId, super.get_id(), netServiceType, numPackets);
}
if (size > MTU && outPort_.get_dest() != destId)
{
// make dummy packets with null data
convertIntoPacket(MTU, numPackets, tag, conn);
}
// get the remaining ping size
size = data.getByteSize() - MTU * (numPackets - 1);
// create the real InfoPacket
InfoPacket pkt = new InfoPacket(name, pktID_, size, outPort_.get_dest(),
destId, netServiceType);
// set the required info
pkt.setLast(super.get_id());
pkt.addHop(outPort_.get_dest());
pkt.addEntryTime(GridSim.clock());
pkt.setOriginalPingSize(data.getByteSize());
pktID_++; // increments packet ID
enque(pkt, GridSimTags.SCHEDULE_NOW);
} |
332798af-184e-407e-ab3b-d0496ddca40a | 2 | @Override
public boolean validaEscalao(int anoNascimento, int epoca) {
if ((epoca-anoNascimento) ==14 || (epoca-anoNascimento) == 15)
return true;
else
return false;
} |
07c9969e-e736-4819-bdd7-fb7fee18225d | 4 | private void fillTechnicalData(float[][] dailyData, float[] rawData) {
// construct technical data
// 82 - 171
// 82 = month
// 83 = day
// 84 = year
// 85-90 = 6 daily data points
// repeats 10 times
// System.out.println(" -------------- --------------------- -----");
for (int x = 0; x < 10; x++) {
final int month = (int) rawData[82 + 9 * x] + 1;
final int day = (int) rawData[83 + 9 * x];
final int year = (int) rawData[84 + 9 * x];
String mnth = "";
if (month < 10)
mnth += "0";
mnth += month;
String dy = "";
if (day < 10)
dy += "0";
dy += day;
try {
final Date date1 = new SimpleDateFormat("MM/dd/yy").parse(mnth
+ "/" + dy + "/" + year);
final long moneyTime = date1.getTime();
float dayTime = moneyTime / 1000.0f;
dayTime /= 3600.0f;
dayTime /= 24.0f;
// dateset.add(dayTime);////////////////////////////////////////////////////////////
final float open = rawData[85 + 9 * x];
final float high = rawData[86 + 9 * x];
final float low = rawData[87 + 9 * x];
final float close = rawData[88 + 9 * x];
final float vol = rawData[89 + 9 * x];
final float adjClose = rawData[90 + 9 * x];
final float[] dlda = { dayTime, open, high, low, close, vol,
adjClose };
// System.out.println(Arrays.toString(dlda));
dailyData[x] = dlda;
} catch (ParseException e) {
e.printStackTrace();
}
}
} |
62546d6f-7a9f-44aa-9ab3-d0707fd949b9 | 0 | public void appendBall(Ball ball) {
balls.add(ball);
} |
096b8228-f076-4109-8189-484fea32ee33 | 4 | public void printVlootStatus(Board board) {
StringBuffer sunken = new StringBuffer();
StringBuffer notSunken = new StringBuffer();
for (Boat b : fleet) {
if (b.getSunken(board)) {
sunken.append(b.toString() + "\n");
} else {
notSunken.append(b.toString() + "\n");
}
}
if (!notSunken.toString().equals("")) {
System.out.println(NOTSUNKEN);
System.out.println(notSunken.toString());
}
if (!sunken.toString().equals("")) {
System.out.println(SUNKEN);
System.out.println(sunken.toString());
}
} |
ce4caea1-2254-45fc-8b6f-3a60ad112a56 | 0 | public New(){
//create a ProcessList or queue
} |
b0162b86-1134-4f4c-babe-13a7fe04c263 | 4 | private byte[][] GenerateCollisionMap(boolean[][]Map)
{
byte[][] CollisionMap = new byte[this.GrabModel().MapSizeX][this.GrabModel().MapSizeY];
for(int x = 0; x < this.GrabModel().MapSizeX; x++) //Loopception courtesy of Cobe & Cecer
{
for(int y = 0; y < this.GrabModel().MapSizeY; y++)
{
if (FurniCollisionMap[x][y] == 0) //Tile is closed becuase furni is there..
{
CollisionMap[x][y] = FurniCollisionMap[x][y];
}
else if (this.GrabModel().Squares[x][y] == SquareState.WALKABLE) //By model, it's walkable
{
CollisionMap[x][y] = 1;
}
else //It's not a valid tile
{
CollisionMap[x][y] = 0;
}
}
}
return CollisionMap;
} |
9e88fe35-b144-4317-85e0-36bcaf7e6672 | 8 | public void printMaxMin() throws Exception {
if (inFile==null) throw new Exception("bad");
String sBuf=inFile.readLine();
int iNum=Integer.valueOf(sBuf);
System.out.println("number of members: " + iNum);
HashMap<String, Integer> map=new HashMap<String, Integer>(iNum);
while (true) {
try {
// read a member's accusation list
sBuf=inFile.readLine();
if (sBuf==null) break;
sBuf=sBuf.trim();
if (sBuf.length()==0) break;
}
catch(IOException e) { break; }
StringTokenizer tok=new StringTokenizer(sBuf);
String sAccuser=tok.nextToken();
int iNumAccused=Integer.valueOf(tok.nextToken());
// add this member to the map
if (map.containsKey(sAccuser)==false)
map.put(sAccuser, new Integer(0));
for (int i=0; i<iNumAccused; ++i) {
String sAccused=inFile.readLine().trim();
if (map.containsKey(sAccused)==false)
map.put(sAccused, new Integer(1));
else
map.put(sAccused, map.get(sAccused)+1);
}
}
System.out.println(map.toString());
} |
bfb1e036-2ec4-4d32-8b30-1a2f232c65c1 | 0 | public EditWindow(Box box)
{
Font used = new Font ("Segoe UI", Font.PLAIN, 20);
Font other = new Font ("Segoe UI", Font.PLAIN, 14);
JPanel content = new JPanel (new GridBagLayout());//panel to display the information
GridBagConstraints c = new GridBagConstraints();//layout
Box b = box;
d = b.getDayStored();//get the day stored by the box that is double clicked by the user
m = b.getMonthStored();
y = b.getYearStored();
JLabel date = new JLabel ();
JLabel eventTitle = new JLabel("Event Title: ");
JLabel startTime = new JLabel("Start Time: ");
JLabel endTime = new JLabel("End Time: ");
eventName = new JTextField("",25);
JLabel location = new JLabel("Location: ");
place = new JTextField ("",25);
descrip = new JTextArea ("",6,25);
JScrollPane pane = new JScrollPane(descrip, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
descrip.setLineWrap(true);
JLabel description = new JLabel ("Description: ");
Date dater = new Date();
SpinnerDateModel sm = new SpinnerDateModel(dater, null, null, Calendar.HOUR_OF_DAY);
SpinnerDateModel sm2 = new SpinnerDateModel(dater, null, null, Calendar.HOUR_OF_DAY);
spinner = new JSpinner(sm);
spinner2 = new JSpinner(sm2);
JSpinner.DateEditor de = new JSpinner.DateEditor(spinner, "h:mm a");
JSpinner.DateEditor de2 = new JSpinner.DateEditor(spinner2, "h:mm a");
spinner.setEditor(de);
spinner2.setEditor(de2);
JButton ok = new JButton("Ok");
JButton cancel = new JButton("Cancel");
date.setText("Date: "+d.getName()+", "+ m.getName()+" "+d.getNum()+", "+y.getNumber());
descrip.setFont(used);
description.setFont(used);
date.setFont(used);
spinner.setFont(used);
startTime.setFont(used);
eventTitle.setFont(used);
eventName.setFont(used);
place.setFont(used);
location.setFont(used);
endTime.setFont(used);
spinner2.setFont(used);
ok.setFont(used);
ok.addActionListener(new ButtonPress());
cancel.setFont(used);
cancel.addActionListener(new ButtonPress());
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_START;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 10;
c.gridheight = 1;
content.add(date,c);
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(10, 0, 10,0);
content.add(eventTitle,c);
c.gridwidth =9;
c.gridx = 1;
c.insets = new Insets (10,15,10,0);
content.add(eventName,c);
c.insets = new Insets (0,0,0,0);
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 2;
content.add(startTime,c);
c.gridx = 1;
c.insets = new Insets (10,15,0,0);
c.gridwidth = 3;
content.add(spinner,c);
c.gridx = 4;
c.gridwidth = 2;
c.insets = new Insets (10,30,0,0);
content.add(endTime,c);
c.insets = new Insets (10,20,0,0);
c.gridx = 6;
c.gridwidth = 1;
content.add(spinner2,c);
c.gridx = 0;
c.gridy = 3;
c.insets = new Insets (0,0,0,0);
c.gridwidth = 1;
content.add(location,c);
c.insets = new Insets (10,15,0,0);
c.gridx = 1;
c.gridwidth =9;
content.add(place,c);
c.insets = new Insets (0,0,10,0);
c.gridwidth = 1;
c.gridx=0;
c.gridy = 4;
content.add(description,c);
c.insets = new Insets(10,15,10,0);
c.gridx = 1;
c.gridheight = 5;
c.gridwidth = 9;
content.add(pane,c);
c.gridwidth = 1;
c.gridheight = 1;
c.gridx = 4;
c.gridy = 9;
content.add(ok,c);
c.gridx = 5;
c.gridwidth = 2;
content.add(cancel,c);
// c.gridx =1;
// c.gridwidth = 7;
// content.add(place,c);
this.setContentPane(content);
this.setResizable(false);
this.setSize(700,450);
this.setTitle(d.getName()+", "+ m.getName()+" "+d.getNum()+", " + y.getNumber());
this.setLocationRelativeTo(null);
this.setIconImage(icon);
this.setAlwaysOnTop(true);
this.setVisible(true);
} |
df5840ed-58bc-4811-bf06-d61840d42b01 | 9 | public static AHCGraph getGraphFromImageCSVFile(String path){
AHCGraph graph = null;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
double max = -1000;
try {
br = new BufferedReader(new FileReader(path));
int rowNum = 0;
boolean isFirst = true;
while ((line = br.readLine()) != null) {
String[] row = line.split(cvsSplitBy);
if(isFirst){
isFirst = false;
graph = new AHCGraph(row.length);
}
for(int i=0; i<row.length; i++){
double weight = Double.parseDouble(row[i].trim());
if(weight>max) max = weight;
graph.addEdge(rowNum, i, weight != 0? weight :0);
}
rowNum++;
}
} catch (FileNotFoundException e) {
System.out.println(path);
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("MAX VAL: " + max);
return graph;
} |
6bc649b9-bf09-471a-8e79-080674013f5c | 7 | private static void writeWatchableObject(DataOutputStream par0DataOutputStream, WatchableObject par1WatchableObject) throws IOException
{
int i = (par1WatchableObject.getObjectType() << 5 | par1WatchableObject.getDataValueId() & 0x1f) & 0xff;
par0DataOutputStream.writeByte(i);
switch (par1WatchableObject.getObjectType())
{
case 0:
par0DataOutputStream.writeByte(((Byte)par1WatchableObject.getObject()).byteValue());
break;
case 1:
par0DataOutputStream.writeShort(((Short)par1WatchableObject.getObject()).shortValue());
break;
case 2:
par0DataOutputStream.writeInt(((Integer)par1WatchableObject.getObject()).intValue());
break;
case 3:
par0DataOutputStream.writeFloat(((Float)par1WatchableObject.getObject()).floatValue());
break;
case 4:
Packet.writeString((String)par1WatchableObject.getObject(), par0DataOutputStream);
break;
case 5:
ItemStack itemstack = (ItemStack)par1WatchableObject.getObject();
par0DataOutputStream.writeShort(itemstack.getItem().shiftedIndex);
par0DataOutputStream.writeByte(itemstack.stackSize);
par0DataOutputStream.writeShort(itemstack.getItemDamage());
break;
case 6:
ChunkCoordinates chunkcoordinates = (ChunkCoordinates)par1WatchableObject.getObject();
par0DataOutputStream.writeInt(chunkcoordinates.posX);
par0DataOutputStream.writeInt(chunkcoordinates.posY);
par0DataOutputStream.writeInt(chunkcoordinates.posZ);
break;
}
} |
6252ea00-155d-45f2-b7d2-ad2531933891 | 5 | public boolean merge(Frame frame) {
boolean changed = false;
// Local variable table
for (int i = 0; i < locals.length; i++) {
if (locals[i] != null) {
Type prev = locals[i];
Type merged = prev.merge(frame.locals[i]);
// always replace the instance in case a multi-interface type changes to a normal Type
locals[i] = merged;
if (! merged.equals(prev) || merged.popChanged()) {
changed = true;
}
} else if (frame.locals[i] != null) {
locals[i] = frame.locals[i];
changed = true;
}
}
changed |= mergeStack(frame);
return changed;
} |
5e7f0806-f656-4ab6-8982-b5a66e6e2d78 | 2 | public boolean ignoreMethod(final MemberRef method) {
if (ignoreMethods.contains(method)) {
return (true);
} else if (ignoreClass(method.declaringClass())) {
addIgnoreMethod(method);
return (true);
}
return (false);
} |
b159d577-2d74-4b7a-8ab4-0062000ca843 | 2 | private int defense(State s){
int def = 10;
int natk = 0;
State ns;
MyList moves = s.findMoves();
Iterator it = moves.iterator();
Move m;// = (Move) it.next();
//ns = s.tryMove((Move) m);
//natk = attack(ns, s);
while (it.hasNext()){
m = (Move) it.next();
ns = s.tryMove((Move) m);
natk = attack(ns, s);
//System.out.println("natk = "+natk);
if(natk < def)
def = natk;
}
return def;
} |
409e6725-4cf7-4406-9a9c-54731e143703 | 9 | @Test
public void testEqualsAndHashCode()
{
final List<Node> nodes = new ArrayList<Node>();
final DCRGraph graph = new DCRGraph();
final Random random = new Random();
for (int i = 0; i < 10; ++i)
{
final Node node = new Node();
node.setGtCluster(new OrdinaryCluster(graph, random.nextDouble()));
node.setGtClIndex(random.nextInt());
node.setPsClIndex(random.nextInt());
node.setOperationIndex(random.nextInt());
nodes.add(node);
}
nodes.add(null);
nodes.add(null);
nodes.add(null);
for (int i = 0; i < nodes.size(); ++i)
{
// reflexivity
final Node fst = nodes.get(i);
if (fst != null)
{
Assert.assertEquals(fst, fst);
Assert.assertFalse(fst.equals(null));
for (int j = 0; j < nodes.size(); ++j)
{
final Node snd = nodes.get(j);
if (snd != null)
{
// symmetry
Assert
.assertTrue(BooleanUtils.equivalent(fst.equals(snd), snd.equals(fst)));
//
Assert.assertTrue(BooleanUtils.implies(fst.equals(snd),
fst.hashCode() == snd.hashCode()));
for (int k = 0; k < nodes.size(); ++k)
{
final Node thd = nodes.get(k);
// transitivity
Assert.assertTrue(BooleanUtils.implies(
fst.equals(snd) && snd.equals(thd),
fst.equals(thd)));
}
}
else
{
Assert.assertFalse(fst.equals(snd));
}
}
}
}
for (int i = 0; i < nodes.size(); ++i)
{
final Node node = nodes.get(i);
if (node != null)
{
Assert.assertFalse(node.equals(new Object()));
Assert.assertFalse(node.equals("Hallo Test!"));
}
}
} |
9aa24152-d116-45a9-992f-b7f654df0c25 | 5 | @Override
public void handleIt(Object... args) {
while (!authentication) {
Scanner input = new Scanner(System.in);
// Getting authentication information from user
System.out.print("Please enter your username: ");
userName = input.next();
System.out.print("Please enter your password: ");
userPassword = input.next();
// Creating an authentication object based on user input
authObject = new AuthenticationBean(userName, userPassword);
// Getting socket and user from passed arguments
Socket sock = (Socket) args[0];
User currentUser = (User) args[1];
try {
// Constructing input and output streams
JSONOutputStream jsonOut = new JSONOutputStream(sock.getOutputStream());
// Writing command object to server
jsonOut.writeObject(authObject);
// Reading response from server
int success = sock.getInputStream().read();
// If authentication is successful
if (success == 1) {
authentication = true;
currentUser.setUsername(userName);
currentUser.setPassword(userPassword);
currentUser.setLoggedIn(true);
} else if(success == 0){
System.out.println("\nAuthentication unsuccessful, please check user credentials\n");
} else {
System.out.println("Something went wrong...");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
} |
e4c893e2-d657-4db0-91e4-35b2347035f8 | 5 | @Override
public void ejecutar(Stack<Valor> st, MemoriaDatos md, Cp cp)
throws Exception {
if (st.size() < 2)
throw new Exception("IGUAL: faltan operandos");
Valor op1 = st.pop();
Valor op2 = st.pop();
if (op1 instanceof Booleano && op2 instanceof Booleano) {
st.push(new Booleano(((boolean) op1.getValor()) == ((boolean) op2.getValor())));
cp.incr();
}
else if (op1 instanceof Entero && op2 instanceof Entero) {
st.push(new Booleano(((int) op1.getValor()) == ((int) op2.getValor())));
cp.incr();
}
else
throw new Exception("IGUAL: operandos de distinto tipo");
} |
4833dfc5-8ea3-44cd-a579-9634631bbc2d | 6 | private void shift(int delta)
{
double[] old = new double[values.length];
System.arraycopy(values, 0, old, 0, values.length);
int oldIndex = delta;
for (int i = 0; i < values.length; i ++)
{
if (oldIndex >= 0 && oldIndex < values.length) {
values[i] = old[oldIndex];
}
oldIndex ++;
}
if (delta < 0) {
for (int i = Math.abs(delta) - 1; i >= 0; i --) {
values[i] = Math.random() * randomFactor + values[i + 1] * (1 - randomFactor);
}
} else {
for (int i = values.length - delta; i < values.length; i ++) {
values[i] = Math.random() * randomFactor + values[i - 1] * (1 - randomFactor);
}
}
} |
d8c920d1-9232-4885-a2aa-5325a5b79bb9 | 5 | public City getCityAt(Position p) {
if ( p.getRow() == 1 && p.getColumn() == 1 ) {
return new City() {
public Player getOwner() { return Player.RED; }
public int getSize() { return 1; }
public String getProduction() {return null;}
public String getWorkforceFocus() {return null;}
public int getProductionAmount() {return 0;}
public void setOwner(Player owner) {}
};
}
else if ( p.getRow() == 2 && p.getColumn() == 1 && blueGotACity == true) {
return new CityImpl(Player.BLUE);
}
return null;
} |
79d89424-7417-4477-ae08-d2d2a2f49add | 4 | @Override
public int hashCode() {
int hash = 0;
hash += (name != null ? name.hashCode() : 0)
+ (releaseForm != null ? releaseForm.hashCode() : 0)
+ (ages != null ? ages.hashCode() : 0)
+ (quantityPerPack != null ? quantityPerPack.hashCode() : 0);
return hash;
} |
c4332800-32f3-4b61-9fd3-d78a1fb53a61 | 1 | @Override
public void render(GameContainer gc, Graphics g) {
// TODO Auto-generated method stub
if(isHealthy) {
//g.drawString("Rendering " + facing + " - " + position.getX() + ", " + position.getY(), 10, 60);
_animation[facing].draw(position.getX(), position.getY());
}
} |
10c19710-ac68-4702-91c3-c5e50bb6e11c | 3 | public void createPiece (Piece _piece, int n){
Vecteur<Integer> points[] = _piece.getForme().getPoints();
for (int i = n*4; i<n*4+4;i++){
for (int j=0; j<4;j++){
this.setValueAt(new ImageIcon (getClass().getResource("/images/Frames/vide.png")), i, j);
}
}
for (Vecteur<Integer> point : points) {
this.setValueAt(_piece.getFrame(), n*4+point.get(0)+2, point.get(1));
}
} |
6d7acb94-f731-40f4-9ddb-e6910acad767 | 0 | public Priority(){} |
3bd5c6bd-70b6-403e-8684-4af19644a384 | 7 | public void inserir(Cliente c) {
Statement st;
Connection con;
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(JanelaLogin.class.getName()).log(Level.SEVERE, null, ex);
}
try {
con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/bicicletaria", "postgres", "root");
st = con.createStatement();
String query = "SELECT cpf FROM usuario WHERE cpf = '" + c.getCpf() + "'";
ResultSet rs = st.executeQuery(query);
if(rs.next())
mensagem = "Já existe um cliente cadastrado com este CPF";
else if(c.getNome().equals("") || c.getCpf().equals(""))
mensagem = "Campo vazio!";
else
try {
dao.create(c);
mensagem = "Cliente cadastrado com sucesso!";
} catch (PreexistingEntityException ex) {
Logger.getLogger(ControladorCliente.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(ControladorCliente.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (SQLException ex) {
Logger.getLogger(ControladorCliente.class.getName()).log(Level.SEVERE, null, ex);
}
} |
88446f7f-4f82-4bfe-9362-0a8b6687071b | 9 | public void CreateDirectory(Message message, int opID) {
String filepath = message.filePath;
System.out.println("Trying to create file path: "+ message.filePath);
if (!NamespaceMap.containsKey(filepath)) { // directory doesn't exist
if(AddExclusiveParentLocks(filepath, opID))
{
File path = new File(filepath);
String parentPath = path.getParent();
String parent;
if (parentPath == null) {
parent = filepath;
} else {
parent = parentPath;
}
for(int r=0;r<10;r++){
if (!NamespaceMap.containsKey(parent) && !(parent.equals(filepath))) {
// parent directory does not exist
System.out.println("Parent directory doesnt exist");
if(r<9){
continue;
}
SendErrorMessageToClient(message);
return;
} else if (NamespaceMap.containsKey(parent)) {
NamespaceMap.get(parent).children.add(filepath);
break;
}
}
NamespaceNode newNode = new NamespaceNode(nodeType.DIRECTORY);
NamespaceMap.put(filepath, newNode);
SendSuccessMessageToClient(message);
tfsLogger.LogMsg("Created directory " + filepath);
//System.out.println("Creating direcotry " + filepath);
//WritePersistentNamespaceMap(filepath, newNode);
System.out.println("OPID " + opID + " Finished");
}
/*else
{
SendErrorMessageToClient(message);
}*/
} else // directory already exists
{
SendErrorMessageToClient(message);
}
synchronized(NamespaceMap)
{
ClearNamespaceMapFile();
for(String key : NamespaceMap.keySet())
{
WritePersistentNamespaceMap(key, NamespaceMap.get(key));
//System.out.println("Key: " + key);
}
}
} |
8493eedd-f1fc-4ec8-b11d-b63a1695a9c9 | 5 | private void updateBuyOption() {
if(model.getBuyOptionState() == Model.BuyOptionState.DEACTIVATED) {
buyOption.setEnabled(false);
} else {
buyOption.setEnabled(true);
}
switch(model.getBuyOptionState()) {
case PURCHASABLE:
buyOptionText = "Feld kaufen (" + model.getPurchasablePrice() + ")";
break;
case BUYHOUSE:
buyOptionText = "Haus kaufen (" + model.getStreetUpgrade() + ")";
break;
case BUYHOTEL:
buyOptionText = "Hotel kaufen (" + model.getStreetUpgrade() + ")";
break;
case DEACTIVATED:
buyOptionText = "Nichts zu kaufen";
break;
}
buyOption.setText(buyOptionText);
} |
0a5452de-57cd-4487-bc20-ff007d5fbd58 | 8 | private void initPageAnnotations() throws InterruptedException {
// find annotations in main library for our pages dictionary
Object annots = library.getObject(entries, ANNOTS_KEY.getName());
if (annots != null && annots instanceof Vector) {
Vector v = (Vector) annots;
annotations = new ArrayList<Annotation>(v.size() + 1);
// add annotations
Object annotObj;
org.icepdf.core.pobjects.annotations.Annotation a = null;
for (int i = 0; i < v.size(); i++) {
if (Thread.interrupted()) {
throw new InterruptedException(
"Page Annotation initialization thread interrupted");
}
annotObj = v.elementAt(i);
Reference ref = null;
// we might have a reference
if (annotObj instanceof Reference) {
ref = (Reference) v.elementAt(i);
annotObj = library.getObject(ref);
}
// but most likely its an annotations base class
if (annotObj instanceof Annotation) {
a = (Annotation) annotObj;
}
// or build annotations from dictionary.
else if (annotObj instanceof Hashtable) { // Hashtable lacks "Type"->"Annot" entry
a = Annotation.buildAnnotation(library, (Hashtable) annotObj);
}
// set the object reference, so we can save the state correct
// and update any references accordingly.
if (ref != null) {
a.setPObjectReference(ref);
}
// add any found annotations to the vector.
annotations.add(a);
}
}
} |
57e7b573-9bd5-46a2-98a8-41b96816a8ca | 3 | public int get(int key){
LinkedNode root = this;
if(root == null){
return -1;
}
while(root!=null){
if(root.getKey() == key){
return root.getValue();
}
root = root.getNext();
}
return -1;
} |
95541798-5857-4d92-837f-0a3c07840b48 | 1 | public CommandGroup getCurrentGroup()
{
return activeChild == null ? this : activeChild.getCurrentGroup();
} |
7357d3f2-12da-4e1e-b4db-2452f6762287 | 7 | public int rootState_dispatchEvent(short id) {
int res = RiJStateReactive.TAKE_EVENT_NOT_CONSUMED;
switch (rootState_active) {
case EmergencyStopped:
{
res = EmergencyStopped_takeEvent(id);
}
break;
case EmergencyMoving:
{
res = EmergencyMoving_takeEvent(id);
}
break;
case EmergencyBaseLevel:
{
res = EmergencyBaseLevel_takeEvent(id);
}
break;
case Stopped:
{
res = Stopped_takeEvent(id);
}
break;
case waitingForRequest:
{
res = waitingForRequest_takeEvent(id);
}
break;
case Finished:
{
res = Finished_takeEvent(id);
}
break;
case Moving:
{
res = Moving_takeEvent(id);
}
break;
default:
break;
}
return res;
} |
7a0d23c2-abe3-4fbc-9689-a549fd0f533c | 0 | public void setCantCompany(int cantCompany) {
CantCompany = cantCompany;
} |
31d71d6d-2bbf-4547-9c10-87ed43df8bf6 | 8 | public boolean stateEquals(Object o)
{
if (o==this) return true;
if (o == null || !(o instanceof MersenneTwister))
return false;
MersenneTwister other = (MersenneTwister) o;
if (mti != other.mti) return false;
for(int x=0;x<mag01.length;x++)
if (mag01[x] != other.mag01[x]) return false;
for(int x=0;x<mt.length;x++)
if (mt[x] != other.mt[x]) return false;
return true;
} |
98a7307f-0abe-47f2-861b-68c84982749c | 7 | public final void method70(int i, int i_42_, byte i_43_, int i_44_,
int i_45_, int i_46_, int i_47_, byte[] is,
Class304 class304) {
try {
((Class14) this).aClass377_5082.method3850((byte) -39, this);
anInt8647++;
if ((i_44_ ^ 0xffffffff) == -1)
i_44_ = i_46_;
OpenGL.glPixelStorei(3317, 1);
if (i_43_ >= -4)
method250(74, false, -106);
if (i_46_ != i_44_)
OpenGL.glPixelStorei(3314, i_44_);
OpenGL.glTexSubImage2Dub(((Class14) this).anInt5093, 0, i_47_, i,
i_46_, i_45_,
Class348_Sub40_Sub3.method3055(120,
class304),
5121, is, i_42_);
if ((i_44_ ^ 0xffffffff) != (i_46_ ^ 0xffffffff))
OpenGL.glPixelStorei(3314, 0);
OpenGL.glPixelStorei(3317, 4);
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("tw.T(" + i + ',' + i_42_ + ','
+ i_43_ + ',' + i_44_ + ','
+ i_45_ + ',' + i_46_ + ','
+ i_47_ + ','
+ (is != null ? "{...}" : "null")
+ ','
+ (class304 != null ? "{...}"
: "null")
+ ')'));
}
} |
595b30d2-fb6e-4fae-9bfa-835d906f9c57 | 4 | public Boolean produceFrom(ResultSet result) throws SQLException {
String s = result.getString(1);
if (s.equalsIgnoreCase(T))
return true;
if (s.equalsIgnoreCase(F))
return false;
int i = result.getInt(1);
if (i == 1) return true;
if (i == 0) return false;
return result.getBoolean(1);
} |
c0f5a5ea-5701-4824-bcc7-df51e2c5b18e | 8 | @Override
public Void doInBackground() throws Exception
{
for (Hero h : lcm.heroes)
{
if (jpegMode)
lcm.exportHeroToJpeg(h, folder);
else
lcm.exportHeroToPng(h, folder);
frame.setTitle("Exporting (" + (getCurrentValue()+1) + "/" + getMaxValue() + ")...");
setProgress(currentValue++);
}
for (Villain v : lcm.villains)
{
if (jpegMode)
lcm.exportVillainToJpeg(v, folder);
else
lcm.exportVillainToPng(v, folder);
frame.setTitle("Exporting (" + (getCurrentValue()+1) + "/" + getMaxValue() + ")...");
setProgress(currentValue++);
}
for (SchemeCard s : lcm.schemes)
{
if (jpegMode)
lcm.exportSchemeToJpeg(s, folder);
else
lcm.exportSchemeToPng(s, folder);
frame.setTitle("Exporting (" + (getCurrentValue()+1) + "/" + getMaxValue() + ")...");
setProgress(currentValue++);
}
for (CustomCard s : lcm.customCards)
{
if (jpegMode)
lcm.exportCustomCardToJpeg(s, folder);
else
lcm.exportCustomCardToPng(s, folder);
frame.setTitle("Exporting (" + (getCurrentValue()+1) + "/" + getMaxValue() + ")...");
setProgress(currentValue++);
}
return null;
} |
4470fb20-0aa1-410d-81e5-1fd6fb3d5257 | 8 | public static void kMeansClustering(int k,List<Vector> dataset){
Cluster[] clusters = new Cluster[k];
Collections.shuffle(dataset);
for(int i = 0;i<k;i++){
Vector randomVector = dataset.get(i);
clusters[i] = new Cluster(randomVector);
clusters[i].addVector(randomVector);
}
DistanceMeasure dm = new EuclideanDistance();
boolean clusteringStable = false;
String previousClustering = "";
while(!clusteringStable){
for(Cluster c : clusters){
c.determineNewSeed();
c.members.clear();
}
for(Vector v : dataset){
double smallestDistance = Double.MAX_VALUE;
Cluster closesCluster = null;
for(Cluster c : clusters){
double distance = dm.distance(v, c.getSeed());
if(distance<smallestDistance){
closesCluster = c;
smallestDistance = distance;
}
}
closesCluster.addVector(v);
}
StringBuilder newClustering = new StringBuilder();
for(Cluster c : clusters){
newClustering.append(c.toString());
}
clusteringStable = previousClustering.equals(newClustering.toString());
previousClustering = newClustering.toString();
}
for(Cluster c : clusters){
System.out.println(c.toString());
}
} |
34c546d6-5a04-4083-b499-e2a54c8b1782 | 5 | public Clip loadSound(String fileName) {
Clip clip = null;
URL url;
// file directory relative to the file structure of the class
url = frame.getClass().getResource(fileName);
System.out.println(url);
AudioInputStream audioIn = null;
try {
audioIn = AudioSystem.getAudioInputStream(url);
} catch (UnsupportedAudioFileException e) {
System.out.println("Error: " + e);
e.printStackTrace();
} catch (IOException e) {
System.out.println("Error: " + e);
e.printStackTrace();
}
try {
clip = AudioSystem.getClip();
} catch (LineUnavailableException e) {
System.out.println("Error: " + e);
e.printStackTrace();
}
try {
clip.open(audioIn);
} catch (LineUnavailableException e) {
System.out.println("Error: " + e);
e.printStackTrace();
} catch (IOException e) {
System.out.println("Error: " + e);
e.printStackTrace();
}
return clip;
} |
05142c75-8c56-4cd6-a777-fa665f88abd8 | 6 | public void addTime(String showName, String dei, String roomName, Time time){
Days day = Days.valueOf(dei);
int d = day.ordinal();
for (Show show : days[d].getShows()) { //iter the show array
if (!show.getName().equals(showName)){ //see if there is a show with tha correct name
for (Room room : show.getRooms()) { //iter the rooms of the given show
if (!room.getName().equals(roomName)) { //see if there is a room with the same name
for (Time time1 : room.getTime()) { //iter the time array
if (!time1.equals(time)){ //see if there is a show for this time already there
room.addTime(time);
}
}
}
}
}
}
} |
a517b70f-7afa-43bf-9195-f1be28187d4c | 1 | void overzicht() {
for(int i = 0; i < kamer.length; i++) {
System.out.println("Kamer " + kamer[i].kamernummer + ": " +
kamer[i].voornaam + " " + kamer[i].achternaam);
}
System.out.println("");
} |
38a68110-3f16-4673-af3d-b06f7a801149 | 4 | public static String doEntityReference (String text) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (ch == '<')
result.append("<");
else if (ch == '&')
result.append("&");
else if (ch == '>')
result.append(">");
else
result.append(ch);
}
return result.toString();
} |
252fcf07-070c-4b44-bcec-71b7e6ae300c | 0 | @BeforeClass
public static void setUpClass() throws Exception {
ctx = new AnnotationConfigApplicationContext(ConnectionConfig.class);
} |
fe622cd6-8ef0-490f-9b68-08c6f7f537c2 | 5 | @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (event.getMaterial() == Material.ENDER_PEARL) {
if (plugin.isInCombat(event.getPlayer().getUniqueId())) {
if (plugin.settings.blockEnderPearl()) {
event.getPlayer().sendMessage(ChatColor.RED + "[CombatTag] You can't ender pearl while tagged.");
event.setCancelled(true);
}
}
}
}
} |
8c7eaff2-ebac-45e3-8333-ede018041298 | 7 | public final void addRow(String row) {
if (rowCount < dimension && row.length() == dimension) {
char[] values = row.toCharArray();
Entry[] tempRow = new Entry[dimension];
int tCountTemp = tCount;
boolean containsEmpty = false;
for (int i = 0; i < dimension; i++) {
Entry current = Entry.getEntry(values[i]);
if (current == Entry.T) {
tCountTemp++;
if (tCountTemp > MAX_T_COUNT) {
throw new IllegalArgumentException("Number of T's greater than allowed max: " + MAX_T_COUNT);
}
} else if (current == Entry.EMPTY) {
containsEmpty = true;
}
tempRow[i] = current;
}
store[rowCount] = tempRow;
rowCount++;
tCount = tCountTemp;
hasEmpty = hasEmpty || containsEmpty;
} else {
throw new IllegalArgumentException("Requested row cannot fit in a board of dimension " + dimension);
}
} |
714a0e18-f926-4518-bdea-3d2e92597617 | 8 | @Override
public FileInfo getAttr(String server, String user, String dir)
throws ServerOfflineException, NoPermissionsException,
NoSuchFileException, NoSuchPathException {
String path = Domains.parsePath(dir);
if (server == null) {
FileInfo fi = this.fileSystem.getAttr(path);
if (fi != null) {
return fi;
}
return null;
}
String url;
try {
url = this.getFileServerURL(Domains.getFileServerURL(server, user));
} catch (NoSuchServerException e1) {
Logger.log("No such server " + server);
return null;
}
IRmiRemoteFileServer rfs = this.getRmiFileServer(url);
if (rfs == null)
throw new ServerOfflineException("File Server is offline");
int tries = RemoteUtils.NTRIES;
while (true) {
try {
FileInfo info = rfs.getAttr(path);
if (info != null) {
return info;
}
return null;
} catch (RemoteException e) {
tries--;
if (tries == 0) {
throw new ServerOfflineException("File Server is offline");
}
RemoteUtils.sleepToRetry();
}
}
} |
9e298fcf-2404-4aa2-bcae-12dc2b91242f | 4 | @Override
public boolean select (Viewer viewer, Object parentElement, Object element) {
if (searchString == null || searchString.length() == 0) {
return true;
}
// loop on all column of the current row to find matches
CSVRow row = (CSVRow) element;
for (String s:row.getEntries()) {
Matcher m = searchPattern.matcher(s);
if (m.matches()) {
return true;
}
}
return false;
} |
83cb2dd0-2c59-44ee-b90b-b6ea11a41492 | 1 | @Override
public void changedMostRecentDocumentTouched(DocumentRepositoryEvent e) {
if (e.getDocument() == null) {
setEnabled(false);
} else {
setEnabled(true);
}
} |
67d510cf-cffe-4878-8d1b-0980d2fe3ee1 | 9 | public boolean similar(Object other) {
try {
if (!(other instanceof JSONObject)) {
return false;
}
Set<String> set = this.keySet();
if (!set.equals(((JSONObject)other).keySet())) {
return false;
}
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
Object valueThis = this.get(name);
Object valueOther = ((JSONObject)other).get(name);
if (valueThis instanceof JSONObject) {
if (!((JSONObject)valueThis).similar(valueOther)) {
return false;
}
} else if (valueThis instanceof JSONArray) {
if (!((JSONArray)valueThis).similar(valueOther)) {
return false;
}
} else if (!valueThis.equals(valueOther)) {
return false;
}
}
return true;
} catch (Throwable exception) {
return false;
}
} |
fb8914a5-1d02-4f8c-8f6b-e192a19dd666 | 2 | public Operator getOperator(String literal) {
int operatorCount = this.operatorList.size();
for(int i = 0;i<operatorCount;i++) {
Operator currentOperator = this.operatorList.get(i);
String currentText = currentOperator.getLiteral();
boolean isMatchingExpression = literal.equals(currentText);
if (isMatchingExpression) {
return currentOperator;
}
}
return null;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.