method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
f34aa478-2ca0-4c08-b75a-b41ec8e93990 | 5 | public String fullMap(){
String map = "";
for (int i = 0; i < 15; i++){
for (int j = 0; j < 11; j++){
if (rooms[i][j] != null)
if (i == currentY && j == currentX)
map += "[*]";
else
map += rooms[i][j];
else
map += " ";
}
map += "\n";
}
return map;
} |
7b8f5e7b-6b2f-44ff-bdbe-a9e613471ecd | 5 | private void save(String nameV,String surnameV,String usernameV,String passV,String oximaV,String action){
/*
* apothikeuei ta stoixia i tis allages sthn vash kai emfanizei ta katallhla minimata
*/
String query;
if(action.equals("insert"))
query="insert into odigoi(onoma,eponimo,username,password,oxima) values(?,?,?,?,?)";
else
query="update odigoi set onoma=?, eponimo=? , username=?,password=?,oxima=? WHERE id=?";
try {
con.pS=con.conn.prepareStatement(query);
con.pS.setString(1, nameV);
con.pS.setString(2, surnameV);
con.pS.setString(3, usernameV);
con.pS.setString(4, passV);
con.pS.setString(5, oximaV);
if(action.equals("update"))
con.pS.setInt(6, id);
} catch (SQLException e) {
e.printStackTrace();
}
if(con.makeQuery(query)){
JOptionPane.showMessageDialog(null, "Saved!");
if(id!=0)
dispose();
else{
name.setText("");
surname.setText("");
username.setText("");
pass.setText("");
pass2.setText("");
}
}else{
JOptionPane.showMessageDialog(null, "Something went wrong please try later!");
}
} |
77f471e6-622a-4bf3-820b-98d99fcf4c2e | 0 | @Override
public void Volum (double n) {
this.volume=this.hight*this.hight*this.hight*n;
this.hight = Math.pow(volume , 1/3);
} |
40e916a9-ce31-4720-a99f-e370cd14da1b | 4 | public void setExpAux(List<?> list)
{
for(PExpAux e : this._expAux_)
{
e.parent(null);
}
this._expAux_.clear();
for(Object obj_e : list)
{
PExpAux e = (PExpAux) obj_e;
if(e.parent() != null)
{
e.parent().removeChild(e);
}
e.parent(this);
this._expAux_.add(e);
}
} |
d945e8fe-6fc1-4854-abc4-9349892c82b3 | 1 | public static void createHeap(int[] heap) {
for (int i = heap.length - 1; i >= 0; i--) {
adjustHeap(heap, i, heap.length);
}
} |
2e591464-213e-4cdb-9ab9-4633082a8cfb | 5 | protected Behaviour getNextStep() {
if (
safePoint == null || actor.aboard() == safePoint ||
safePoint.pathType() == Tile.PATH_BLOCKS
) {
safePoint = nearestHaven(actor, null) ;
priorityMod *= 0.5f ;
if (priorityMod < 0.25f) priorityMod = 0 ;
}
if (safePoint == null) {
abortBehaviour() ;
return null ;
}
final Action flees = new Action(
actor, safePoint,
this, "actionFlee",
Action.LOOK, "Fleeing to "
) ;
flees.setProperties(Action.QUICK) ;
return flees ;
} |
0e57aacf-8441-4321-b2e7-2a421f2a404b | 7 | public static void initCraftableStats()
{
if (!blockStatsInitialized || !itemStatsInitialized)
{
return;
}
HashSet hashset = new HashSet();
IRecipe irecipe;
for (Iterator iterator = CraftingManager.getInstance().getRecipeList().iterator(); iterator.hasNext(); hashset.add(Integer.valueOf(irecipe.getRecipeOutput().itemID)))
{
irecipe = (IRecipe)iterator.next();
}
ItemStack itemstack;
for (Iterator iterator1 = FurnaceRecipes.smelting().getSmeltingList().values().iterator(); iterator1.hasNext(); hashset.add(Integer.valueOf(itemstack.itemID)))
{
itemstack = (ItemStack)iterator1.next();
}
objectCraftStats = new StatBase[32000];
Iterator iterator2 = hashset.iterator();
do
{
if (!iterator2.hasNext())
{
break;
}
Integer integer = (Integer)iterator2.next();
if (Item.itemsList[integer.intValue()] != null)
{
String s = StatCollector.translateToLocalFormatted("stat.craftItem", new Object[]
{
Item.itemsList[integer.intValue()].getStatName()
});
objectCraftStats[integer.intValue()] = (new StatCrafting(0x1010000 + integer.intValue(), s, integer.intValue())).registerStat();
}
}
while (true);
replaceAllSimilarBlocks(objectCraftStats);
} |
16e02701-469d-465d-9ddd-32623eea0cd2 | 5 | @Override
public int write(String path, Object fh, boolean isWritepage,
ByteBuffer buf, long offset) throws FuseException {
FileHandle handle = (FileHandle)fh;
if (handle == null)
return Errno.EBADSLT;
if (handle.hasClosed)
return Errno.EBADSLT;
if (!handle.write)
return Errno.EACCES;
handle.isEmptyFile = false;
try {
fileSystem.write(handle, buf, offset);
} catch (DriveFullException e) {
return Errno.ENOSPC;
} catch (PartIsLockedException e) {
return Errno.EACCES;
}
return 0;
} |
d3e2cf88-6637-4d32-a77f-204cc2ebe01c | 9 | public void testSetBufferLength() {
ByteArrayBuilder builder = new ByteArrayBuilder();
byte[] testdata = new byte[777];
for(int i=0;i<testdata.length;i++) {
testdata[i] = (byte)i;
}
builder.clear();
for(int i=0;i<testdata.length;i++) {
assertEquals(i, builder.length());
builder.append(testdata[i]);
builder.setBufferLength(i+2);
// check
{
byte[] result = builder.getBuffer();
int s = 0;
int e = builder.length();
assertEquals(i+1, e);
if(i==0||i%LEVEL==0){
for(int j=s;j<e;j++) {
assertEquals((byte)j, result[j]);
}
}
}
}
builder.clear();
for(int i=0;i<testdata.length;i++) {
assertEquals(i, builder.length());
builder.setBufferLength(i+2);
builder.append(testdata[i]);
// check
{
byte[] result = builder.getBuffer();
int s = 0;
int e = builder.length();
assertEquals(i+1, e);
if(i==0||i%LEVEL==0){
for(int j=s;j<e;j++) {
assertEquals((byte)j, result[j]);
}
}
}
}
} |
17cb6ce3-b022-4d2a-b7bb-81100800a5e4 | 8 | public synchronized int available()
throws IOException
{
int avail = super.available();
int unencoded = precount - prepos + in.available();
if (encoder.getEncoder().getVbr()) {
switch (mode) {
case 0: // Narrowband
// ogg header size = 27 + packetsPerOggPage
// count 1 byte (min 5 bits) for each block available
return avail + (27 + 2 * packetsPerOggPage) *
(unencoded / (packetsPerOggPage*framesPerPacket*320));
case 1: // Wideband
// ogg header size = 27 + packetsPerOggPage
// count 2 byte (min 9 bits) for each block available
return avail + (27 + 2 * packetsPerOggPage) *
(unencoded / (packetsPerOggPage*framesPerPacket*640));
case 2: // Ultra wideband
// ogg header size = 27 + packetsPerOggPage
// count 2 byte (min 13 bits) for each block available
return avail + (27 + 3 * packetsPerOggPage) *
(unencoded / (packetsPerOggPage*framesPerPacket*1280));
default:
return avail;
}
}
else {
// Calculate size of a packet of Speex data.
int spxpacketsize = encoder.getEncoder().getEncodedFrameSize();
if (channels > 1) {
spxpacketsize += 17; // 1+4(14=inband)+4(9=stereo)+8(stereo data)
}
spxpacketsize *= framesPerPacket;
spxpacketsize = (spxpacketsize + 7) >> 3; // convert bits to bytes
// Calculate size of an Ogg packet containing X Speex packets.
// Ogg Packet = Ogg header + size of each packet + Ogg packets
int oggpacketsize = 27 + packetsPerOggPage * (spxpacketsize + 1);
int pcmframesize; // size of PCM data necessary to encode 1 Speex packet.
switch (mode) {
case 0: // Narrowband
// 1 frame = 20ms = 160ech * channels = 320bytes * channels
pcmframesize = framesPerPacket * 320 * encoder.getChannels();
avail += oggpacketsize *
(unencoded / (packetsPerOggPage * pcmframesize));
return avail;
case 1: // Wideband
// 1 frame = 20ms = 320ech * channels = 640bytes * channels
pcmframesize = framesPerPacket * 640 * encoder.getChannels();
avail += oggpacketsize *
(unencoded / (packetsPerOggPage * pcmframesize));
return avail;
case 2: // Ultra wideband
// 1 frame = 20ms = 640ech * channels = 1280bytes * channels
pcmframesize = framesPerPacket * 1280 * encoder.getChannels();
avail += oggpacketsize *
(unencoded / (packetsPerOggPage * pcmframesize));
return avail;
default:
return avail;
}
}
} |
1f529d51-32cf-42c6-b5a0-1f1fb5bace61 | 1 | public static ValidationResult okIfNull(String s) {
return s == null ? ok() : error(s);
} |
a4ab93ea-8965-4084-ae77-692c35455eea | 1 | public void printPatronymicStr(String enteredPatronymic, boolean lineSeparator) {
if (lineSeparator) {
System.out.printf("Patronymic: %s\n", enteredPatronymic);
} else {
System.out.printf("Patronymic: %s", enteredPatronymic);
}
} |
ee99fad8-2a5a-4499-bc85-31049d4ef603 | 1 | private String checkParen() {
holdPos = pos;
String paren = line.substring( pos );
int i = paren.indexOf( ")" );
if ( i == -1 ) {
increment();
paren = "Error: '(' must have an ending ')' present on the same line.";
}
lastPos = holdPos;
return paren;
} |
3594f753-fb02-45e1-836b-6c26fc738abd | 7 | public void statisticsReport(final String outFilename, final boolean postfix) {
final String o = outFilename;
final String xmlstats = outFilename + ".xml";
final File f = new File(o);
int i = 1;
for (final ParseErrorDataPoint e : this.listErrorDataPoints) {
LOGGER.info(i + ":Example-Data:" + e);
i++;
if (i == 2) {
break;
}
}
FileOutputStream fos = null;
FileOutputStream fosXML = null;
try {
fos = new FileOutputStream(f);
fosXML = new FileOutputStream(new File(xmlstats));
this.statsReportPrintln(System.out);
this.statsReportPrintln(new PrintStream(fos));
this.statsReportPrintlnXml(new PrintStream(fosXML));
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (fosXML != null) {
fosXML.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
} // End of try write
final ReportPlotWriter plotWriter = new ReportPlotWriter(stats);
plotWriter.statisticsReportGnuPlotHisto(outFilename);
plotWriter.statisticsReportGnuPlotHisto2(outFilename);
plotWriter.statisticsReportGnuPlotHistoScript1(outFilename, "error_log_stats.txt.dat", "error_log_stats1.png",
"plot '${INPUT_PLOT_FILE}' u 2:xtic(1) t 'Recently' w histograms, '' u 3 t 'Week' w histograms");
plotWriter.statisticsReportGnuPlotHistoScript1(outFilename+"2", "error_log_stats2.txt.dat", "error_log_stats2.png",
"plot '${INPUT_PLOT_FILE}' u 2:xtic(1) t 'All Time' w histograms");
} |
a1f91cbd-7dbe-46ce-ab90-aba67841e0ed | 8 | public static void getResponses() throws IOException {
responses = new ArrayList<String>();
try {
int counter = 0;
CoordinatorGUI.textArea.append("Waiting for response from nodes..." + "\n" + "\n");
responseSocket.setSoTimeout(5000);
while (counter < nodes) {
Socket connection = responseSocket.accept();// venter inntil noen tar kontakt
ThreadResponseHandler th = new ThreadResponseHandler(connection);
th.start();
counter++;
}
int waitTime = 0;
while (responses.size() < nodes || waitTime >= 30) {
Thread.sleep(1000);
waitTime++;
}
if (responses.size() == nodes) {
hasResponse = true;
}
if (hasResponse) {
CoordinatorGUI.textArea.append("Recevied response from every node..." + "\n" + "\n");
}
} catch (InterruptedException | IOException e) {
if (e.getMessage().contains("Accept timed out")) {
CoordinatorGUI.textArea.append("Timeout has been reached..." + "\n" + "\n");
timeout = true;
hasResponse = false;
if (commit) {
CoordinatorGUI.textArea.append("Signaling nodes to rollback..." + "\n" + "\n");
String rollback = "rollback";
buf = rollback.getBytes();
packet = new DatagramPacket(buf, buf.length, group, 4446);
socket.send(packet);
logError();
} else {
abort();
}
} else {
System.err.println(e);
}
}
} |
4fbb2921-4466-408f-b199-aa0aed52c5ed | 6 | @Override
public void run(){
while(true){
try {
JSONObject o = read();
if(o == null){
throw new IOException("Client disconnected");
}
connection.input(o);
}
catch (IOException e){
//globalClientList.remove(connection);
Debug.warn("Disconnect from " + connection.getIp() + ". "
+ globalClientList.size() + " clients active.");
connection.isAlive = false;
return;
}
catch (ProtocolException e){
try {
JSONObject errorMessage = new JSONObject().put("error", e.getMessage());
connection.sendMessage(errorMessage);
}
catch (JSONException f){}
catch (IOException g){
}
}
}
} |
387ce476-78b7-40d0-b7f1-7e8b6ba69f46 | 8 | public static void main(String[] args) throws Exception {
Handler h = new FileHandler(System.getProperty("user.dir") + File.separatorChar + "log.txt", true);
h.setFormatter(new SimpleFormatter());
logger.setUseParentHandlers(false);
logger.addHandler(h);
try {
logger.info("Start Session");
logger.setLevel(Level.parse(System.getProperty("loglevel")));
} catch (Exception E) {
logger.warning("Not a valid log level in '-Dloglevel=???': '" + System.getProperty("loglevel") + "'");
logger.setLevel(Level.INFO);
} finally {
logger.info("Log level: " + logger.getLevel().toString());
}
logger.info("OMS version " + Utils.getOMSAppVersion());
logger.info("User dir: " + System.getProperty("user.dir"));
logger.info("OMS home: " + Console.oms3Home);
logger.info("java.home: " + java_home());
// adjust LnF
String osName = System.getProperty("os.name");
if ((osName != null) && osName.toLowerCase().startsWith("lin")) {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
} else {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
try {
String.class.getMethod("isEmpty", (Class<?>[]) null);
} catch (Exception E) {
JOptionPane.showMessageDialog(null,
"You are using an older Java version, however JDK 1.6 is needed!\nPlease install the right JDK, start again ...",
"Problem...", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
String jh = java_home();
if (jh == null) {
JOptionPane.showMessageDialog(null,
"You need to install the latest JDK and set 'JAVA_HOME' to your JDK install directory. "
+ "\nPlease start again ...",
"Problem...", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
if (!new File(jh).exists()) {
JOptionPane.showMessageDialog(null,
"'JAVA_HOME' (" + jh + ") does not exists. Please fix this."
+ "\nPlease start again ...",
"Problem...", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
// open window
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final Console c = new Console();
c.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
c.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (JOptionPane.showConfirmDialog(c, "Exit ?", "Console", JOptionPane.YES_NO_OPTION)
== JOptionPane.YES_OPTION) {
c.savePrefs();
logger.info("Exit");
System.exit(0);
}
}
});
c.setSize(800, 600);
c.setLocationRelativeTo(null);
c.setVisible(true);
}
});
} |
51b6c779-04e5-45ab-b009-3ed8c782d23f | 4 | public float[] findMinMaxHeights() {
float[] minmax = new float[2];
float currentMin, currentMax;
currentMin = heightData[0][0];
currentMax = heightData[0][0];
for (int i = 0; i < imageHeight; i++) {
for (int j = 0; j < imageWidth; j++) {
if (heightData[i][j] > currentMax) {
currentMax = heightData[i][j];
} else if (heightData[i][j] < currentMin) {
currentMin = heightData[i][j];
}
}
}
minmax[0] = currentMin;
minmax[1] = currentMax;
return minmax;
} |
69b9da24-7d96-40ac-8c4c-84257b538eef | 4 | public boolean isEmpty(){
int i = 0;
int i2 = 0;
int i3 = 0;
while(i < blocks.length){
while(i2 < blocks[i].length){
while(i3 < blocks[i][i2].length){
if(blocks[i][i2][i3] != null)return false;
i3++;
}
i2++;
}
i++;
}
return true;
} |
e416b122-c78f-43c3-a46d-8ec8ee564091 | 7 | @Override
public boolean canBeLearnedBy(int job) {
int jid = job;
int skillForJob = id / 10000;
if (job < 1000) {
if (jid / 100 != skillForJob / 100 && skillForJob / 100 != 0) { // wrong job
return false;
}
} else {
if (jid / 1000 != skillForJob / 1000 && skillForJob / 1000 != 0) { // wrong job
return false;
}
}
if ((skillForJob / 10) % 10 > (jid / 10) % 10) { // wrong 2nd job
return false;
}
if (skillForJob % 10 > jid % 10) { // wrong 3rd/4th job
return false;
}
return true;
} |
cd2977fe-084e-4b7a-83da-cc1670e24a2e | 7 | private static ArrayList<String> getWordsFromComposite(Composite composite) {
ArrayList<String> allWords = new ArrayList<>();
Iterator<Component> itBook = composite.iterator();
while (itBook.hasNext()) {
// абзацы + код
Component compBook = itBook.next();
if (compBook.getClass() == Composite.class) {
Iterator<Component> itPar = ((Composite) compBook).iterator();
while (itPar.hasNext()) {
//предложения
Component compSentence = itPar.next();
if (compSentence.getClass() == Composite.class) {
Iterator<Component> itSent = ((Composite) compSentence).iterator();
while (itSent.hasNext()) {
//лексемы
Component compLexeme = itSent.next();
if ((compLexeme.getClass() == Lexeme.class) && (((Lexeme) compLexeme).getType() == LexemeType.WORD)) {
allWords.add(((Lexeme) compLexeme).getTextOfComponent());
}
}
}
}
}
}
return allWords;
} |
bc6f166c-5dcb-489d-a150-8d1a4f3fedd8 | 5 | private void calculateScreenPosition(int x, int height, int y) {
if (x < 128 || y < 128 || x > 13056 || y > 13056) {
spriteDrawX = -1;
spriteDrawY = -1;
return;
}
int z = getFloorDrawHeight(plane, y, x) - height;
x -= cameraPositionX;
z -= cameraPositionZ;
y -= cameraPositionY;
int sineHorizontal = Model.SINE[cameraVerticalRotation];
int cosineHorizontal = Model.COSINE[cameraVerticalRotation];
int sineVertical = Model.SINE[cameraHorizontalRotation];
int cosineVertical = Model.COSINE[cameraHorizontalRotation];
int temp = y * sineVertical + x * cosineVertical >> 16;
y = y * cosineVertical - x * sineVertical >> 16;
x = temp;
temp = z * cosineHorizontal - y * sineHorizontal >> 16;
y = z * sineHorizontal + y * cosineHorizontal >> 16;
z = temp;
if (y >= 50) {
spriteDrawX = Rasterizer.centreX + (x << 9) / y;
spriteDrawY = Rasterizer.centreY + (z << 9) / y;
} else {
spriteDrawX = -1;
spriteDrawY = -1;
}
} |
9461d13b-651f-41d2-b3f9-1941632646fe | 3 | @Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showOpenDialog(tulip.Tulip.mainFrame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try (ObjectInputStream oin = new ObjectInputStream(new FileInputStream(file))) {
tulip.Tulip.mainFrame.setTabName(file.getName());
tulip.Tulip.mainFrame.getGrapPanel().addUnits((ArrayList<AbstractUnit>) oin.readObject());
System.out.println(file.getName());
} catch (IOException ex) {
Logger.getLogger(SaveFileAction.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(LoadFileAction.class.getName()).log(Level.SEVERE, null, ex);
}
}
} |
6e379460-262e-42aa-bd11-eb1c8d3e10ed | 3 | public void similarFiles(double threshold) {
for (int i = 0; i < size; i++)
for (int j = i + 1; j < size; j++) {
double d = calculateResemblance(resemblances[i], resemblances[j], b);
if (d > threshold)
System.out.println(
"Resemblance between file\n" +
" " + urls[i] +"\n" +
"and file\n" +
" " + urls[j] + "\n" +
"is beyond threshold " + threshold + ".");
}
System.out.println("----------------------------------------------------------------");
} |
70279141-9f32-4320-ae4f-3c860c997108 | 4 | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != ConvertiblePair.class) {
return false;
}
ConvertiblePair other = (ConvertiblePair) obj;
return this.sourceType.equals(other.sourceType) && this.targetType.equals(other.targetType);
} |
70015010-ceca-4185-a429-5001757c98fc | 3 | boolean union(int u, int v) {
if ((u = set(u)) == (v = set(v)))
return false;
if (rnk[u] < rnk[v]) {
set[u] = v;
} else {
set[v] = u;
if (rnk[u] == rnk[v])
rnk[u]++;
}
return true;
} |
147a9000-3d90-413a-ba98-60bce8d61791 | 7 | public void trainLive(Sample s)
{
// lc*=0.9999f;
//clear the network
this.prepare();
//do a run through with the current values
process(s);
//make an array of output errors
float[] outputErrors = new float[s.outs.size()];
//calculate output errors
for(int i =0; i <outputErrors.length; i++)
{
float o = outputNeurons.get(i).getOutput();
outputErrors[i] = o*(1.0f-o)*(s.outs.get(i) - o);
}
//change output layer weights
//get weights from hidden to output layer
for(Neuron n : hiddenNeurons)
{
/*
* this counts which of the destination neurons we are dealing with
* in this cycle so we can access the error from the errors vector
*/
int count = 0;
for(Connection c : n.connections)
{
c.weight = c.weight + lc*outputErrors[count]*n.output;
count++;
}
}
/**
* Propagate hidden layer errors. This means another vector of errors, one for each hidden neuron.
*/
float[] hiddenErrors = new float[hiddenNeurons.size()];
//calculate output errors
for(int i =0; i <hiddenErrors.length; i++)
{
float o = hiddenNeurons.get(i).getOutput();
//do the error summation
float sum = 0;
int count = 0;
for(Connection c : hiddenNeurons.get(i).connections)
{
sum+=outputErrors[count]*c.weight;
count++;
}
hiddenErrors[i] = o*(1.0f-o) * sum;
}
/**
* Change hidden layer weights.
*/
//get weights from input to hidden layer
for(Neuron n : inputNeurons)
{
/*
* this counts which of the destination neurons we are dealing with
* in this cycle so we can access the error from the errors vector
*/
int count = 0;
for(Connection c : n.connections)
{
//remember that the input layer outputs don't go through a sigmoid, so they are the same as the inputs
c.weight = c.weight + lc*hiddenErrors[count]*n.output;
count++;
}
}
//the network is now trained!
} |
28178fb5-efea-4a82-8dcb-a29cb3ddb737 | 5 | public static BufferedImage brightness(BufferedImage input, double factor) {
BufferedImage result = new BufferedImage(input.getWidth(), input.getHeight(), input.getType());
for (int i = 0; i < result.getWidth(); i++) {
for (int j = 0; j < result.getHeight(); j++) {
Color c = new Color(input.getRGB(i, j));
int r = c.getRed() * factor > 255 ? 255 : (int) (c.getRed() * factor);
int g = c.getGreen() * factor > 255 ? 255 : (int) (c.getGreen() * factor);
int b = c.getBlue() * factor > 255 ? 255 : (int) (c.getBlue() * factor);
result.setRGB(i, j,
new Color(r, g, b).getRGB());
}
}
return result;
} |
5e748d10-b3da-4c5b-a24d-791352ad8146 | 0 | public List<Park> getParkList() {
return parkList;
} |
883103c8-2174-4214-b9f0-b9fa67ff86d6 | 1 | public List<Object> getAny() {
if (any == null) {
any = new ArrayList<Object>();
}
return this.any;
} |
f33f0c54-6927-4705-92a1-1f54ea87f955 | 5 | public String getDefaultName() {
switch (((IntegerType) getHint()).possTypes) {
case IT_Z:
return "bool";
case IT_C:
return "c";
case IT_B:
case IT_S:
case IT_I:
return "i";
default:
throw new alterrs.jode.AssertError(
"Local can't be of constant type!");
}
} |
db740361-83b0-4c46-94ba-52b1b1798e89 | 9 | private void allocaAcqua(int numeroCelle) { // Testato da popolaMappa
Coord tempCoord = null;
HashSet<Coord> mySet = new HashSet<Coord>();
Iterator<Coord> itCoord = null;
do {
tempCoord = CommonUtils.getNewRandomCoord(getLatoDellaMappa());
} while (!isCellaTerra(tempCoord));
mySet.add(tempCoord);
HashSet<Coord> tempSet = new HashSet<Coord>();
//System.out.println("[allocaAcqua] sto per entrare nel ciclo per allocare " + numeroCelle + " acque");
while (mySet.size()<numeroCelle) {
//System.out.println("[allocaAcqua] cerco " + (numeroCelle-mySet.size()) + " celle");
tempSet.clear();
itCoord = mySet.iterator();
while (itCoord.hasNext()) {
getNearbyEarthCells(itCoord.next(), tempSet);
if (tempSet.size() != 0) { break; }
}
//System.out.println("[allocaAcqua] trovate " + tempSet.size() + " celle");
if (tempSet.size() != 0) {
itCoord = tempSet.iterator();
while (itCoord.hasNext()) {
if (mySet.size()>=numeroCelle) { break; }
mySet.add(itCoord.next());
}
//System.out.println("[allocaAcqua] ho aggiunto le celle nuove al set.");
}
else {
if (mySet.size()<numeroCelle) return;
}
}
itCoord = mySet.iterator();
while(itCoord.hasNext()) {
tempCoord = itCoord.next();
MappaACelle[tempCoord.getX()][tempCoord.getY()] = new Acqua();
}
//System.out.println("[allocaAcqua] allocate " + mySet.size() + " celle");
} |
fa19c425-5447-4578-ac79-272cb6c0ba52 | 4 | public boolean withdraw (int amount) {
if (amount < 0) {
System.out.println ("Cannot withdraw negative amount.");
return false;
} else if (this.myBalance > amount) {
this.myBalance=this.myBalance-amount;
return true;
}else if (this.myBalance < amount && this.parentAccount!=null) {
parentAccount.withdraw(amount-this.balance());
this.myBalance=0;
return true;
} else{
return false;
}
} |
15c0e577-63ba-46f7-a50b-629d3c056273 | 5 | private static int runToInputHiOrLoR(Gameboy gbL, Gameboy gbR, int limit, int joypadInputAdd) {
int initialSteps = gbR.stepCount;
int add = runToAddressR(limit, gbL, gbR, joypadInputAdd);
while (true) {
if (add == 0 || gbR.stepCount - initialSteps > limit)
return 0;
int lastVframe = gbR.stepCount - 1; // subtract started frame
add = dualStepUntilR(gbL, gbR, 0, 0, gbR.rom.readJoypadAddress);
if (add != 0)
return lastVframe;
add = runToAddressR(limit, gbL, gbR, joypadInputAdd, gbR.rom.readJoypadAddress);
if (add == gbR.rom.readJoypadAddress)
return lastVframe;
}
} |
622ebcaa-d232-42e3-bc69-fe040830b8df | 1 | public static void main(String[] args)
{
StringDigraph sg = new StringDigraph(args[0], args[1]);
System.out.println(args[0] + "\n" + sg);
Topological top = new Topological(sg.G());
System.out.println("Scheduling order");
System.out.println("----------------");
for (int v : top.order())
System.out.println(sg.name(v) + "(" + v + "): ");
} |
ec83062d-f82b-4430-8e70-74b09ec934cd | 3 | @Override
public boolean verifier() throws SemantiqueException {
super.verifier();
if(gauche.isBoolean())
GestionnaireSemantique.getInstance().add(new SemantiqueException("Expression gauche du modulo est booléenne, arithmétique attendue ligne:"+line+" colonne:"+col));
if(droite.isBoolean())
GestionnaireSemantique.getInstance().add(new SemantiqueException("Expression droite du modulo est booléenne, arithmétique attendue ligne:"+line+" colonne:"+col));
//Pas de division par 0
if(droite.isZero())
GestionnaireSemantique.getInstance().add(new SemantiqueException("Division par 0 ligne:"+line+" colonne:"+col));
return true;
} |
f627c2fe-b5d6-4f2c-b0a3-60606451c2be | 3 | public Node<T> getNode(int x) {
if (this.length != 0 && x < this.length) {
Node<T> ele = _head;
for (int i = 0; i < x; i++)
ele = ele.getNext();
return ele;
}
return null;
} |
ddfa6086-1682-453b-bb9a-d77f569c5a35 | 5 | public Image isolate(Image im, int width, int height, int color)
{
// Color: 0 = red, 1 = green, 2 = blue, 3 = alpha
int pix[] = JIPTUtilities.getPixelArray(im);
int size = pix.length;
for(int i = 0; i < size; i++)
{
int alpha = (pix[i] >> 24) & 0xff;
int red = (pix[i] >> 16) & 0xff;
int green = (pix[i] >> 8) & 0xff;
int blue = (pix[i] ) & 0xff;
int new_color = 0;
switch(color)
{
case 0 : new_color = red; break;
case 1 : new_color = green; break;
case 2 : new_color = blue; break;
case 3 : new_color = alpha;
}
pix[i] = 0;
pix[i] += (alpha << 24); // alpha
pix[i] += (new_color << 16); // r
pix[i] += (new_color << 8); // g
pix[i] += (new_color ); // b
}
Image new_im = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(width, height, pix, 0, width));
return new_im;
} |
29d30e7b-4d9e-4972-8157-84fed61dc61c | 0 | public void setBuildingId(String buildingId) {
this.buildingId = buildingId;
setDirty();
} |
4875b6df-00c1-4b9f-8395-a617a8270b3a | 9 | private void loadConfiguration(String company, String product, Map<String, Object> userOptions, String[] extraOptionsList) {
optionsList = ArrayUtils.addAll(new String[]{"scheme", "host", "port", "user_agent"}, extraOptionsList);
options = new HashMap<String, Object>();
env = (String)userOptions.get("env");
if (env == null) {
env = System.getenv(company.toUpperCase() + "_" + product.toUpperCase() + "_ENV");
}
if (env == null) {
env = System.getenv(company.toUpperCase() + "_ENV");
}
if (env == null) {
env = (String)defaultOptions.get("env");
}
loadFromHash(userOptions);
loadFromConfig(company, product, (String)userOptions.get("config"));
loadFromConfig(company, product, System.getenv(company.toUpperCase() + "_" + product.toUpperCase() + "_CONFIG"));
loadFromConfig(company, product, System.getenv(company.toUpperCase() + "_CONFIG"));
loadFromEnv(company.toUpperCase() + "_" + product.toUpperCase());
loadFromEnv(company.toUpperCase());
List<String> suffixes = new ArrayList<String>();
if (env != null) {
suffixes.add("-" + env);
suffixes.add("_" + env);
}
suffixes.add("");
for (String suffix : suffixes) {
for (String configBase : new String[]{company + "-" + product, company + "_" + product, company}) {
loadFromConfig(company, product, System.getProperty("user.dir") + "/" + configBase + suffix + ".json");
loadFromConfig(company, product, System.getProperty("user.dir") + "/." + configBase + suffix + ".json");
loadFromConfig(company, product, System.getProperty("user.dir") + "/config/" + configBase + suffix + ".json");
loadFromConfig(company, product, System.getProperty("user.dir") + "/config/." + configBase + suffix + ".json");
loadFromConfig(company, product, System.getProperty("user.home") + "/" + configBase + suffix + ".json");
loadFromConfig(company, product, System.getProperty("user.home") + "/." + configBase + suffix + ".json");
}
}
loadFromConfig(company, product, (String)defaultOptions.get("config"));
loadFromHash(defaultOptions);
projectId = (String)getOption("project_id");
token = (String)getOption("token");
if (userOptions.containsKey("cloud")) {
Object cloudOption = userOptions.get("cloud");
if(cloudOption != null && cloudOption instanceof Cloud){
cloud = (Cloud) cloudOption;
}
} else {
cloud = new Cloud((String)getOption("scheme"), (String)getOption("host"), ((Number)getOption("port")).intValue());
}
} |
e911c0a6-e6bb-43c7-922d-62b8d5cb4aa1 | 4 | public static boolean isPrime(int n) {
// Here, 2 is prime
if(n == 2) return true;
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
} |
e9e70ee8-112e-47d9-99e5-61b27936c13f | 6 | public static void main(String args[]) {
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(TrackingNumberWatcherDetailsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TrackingNumberWatcherDetailsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TrackingNumberWatcherDetailsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TrackingNumberWatcherDetailsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
}
});
} |
8ffa3c43-3f94-48b2-8c54-2bc0199be016 | 0 | @Override
protected EntityManager getEntityManager() {
return em;
} |
65a6b808-767c-40a8-9a00-789f91d5087f | 1 | public void handleAttack() {
target = addrField.getText();
numThreads = (int) threadSlider.getValue();
udpflood.setTarget(target);
udpflood.setThreads(numThreads);
if (udpflood.isRunning()) {
attackBtn.setText("Start Attack");
udpflood.stop();
}
else {
attackBtn.setText("Stop Attack");
udpflood.start();
}
} |
428bf20a-340a-4765-88e7-1f6e4c99e301 | 9 | public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int[][] arr = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
arr[i][j] = sc.nextInt();
}
}
//B G C
int min = Integer.MAX_VALUE;
String ret = "";
int cur = arr[1][0] + arr[2][0] + arr[0][2] + arr[2][2] + arr[0][1] + arr[1][1];
if (cur < min) {
min = cur;
ret = "BCG";
}
cur = arr[1][0] + arr[2][0] + arr[0][1] + arr[2][1] + arr[0][2] + arr[1][2];
if (cur < min) {
min = cur;
ret = "BGC";
}
cur = arr[1][2] + arr[2][2] + arr[0][0] + arr[2][0] + arr[0][1] + arr[1][1];
if (cur < min) {
min = cur;
ret = "CBG";
}
cur = arr[1][2] + arr[2][2] + arr[0][1] + arr[2][1] + arr[0][0] + arr[1][0];
if (cur < min) {
min = cur;
ret = "CGB";
}
cur = arr[1][1] + arr[2][1] + arr[0][0] + arr[2][0] + arr[0][2] + arr[1][2];
if (cur < min) {
min = cur;
ret = "GBC";
}
cur = arr[1][1] + arr[2][1] + arr[0][2] + arr[2][2] + arr[0][0] + arr[1][0];
if (cur < min) {
min = cur;
ret = "GCB";
}
System.out.println(ret + " " + min);
}
} |
bfe8ed4e-ab1d-4f7a-8935-052f252eab4f | 8 | public int characterAt(int at) throws JSONException {
int c = get(at);
if ((c & 0x80) == 0) {
return c;
}
int character;
int c1 = get(at + 1);
if ((c1 & 0x80) == 0) {
character = ((c & 0x7F) << 7) | c1;
if (character > 0x7F) {
return character;
}
} else {
int c2 = get(at + 2);
character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2;
if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF
&& (character < 0xD800 || character > 0xDFFF)) {
return character;
}
}
throw new JSONException("Bad character at " + at);
} |
77609424-1d0e-46d6-b252-47f5f44b7c1a | 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(PrestamosUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PrestamosUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PrestamosUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PrestamosUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PrestamosUsuario().setVisible(true);
}
});
} |
24dedb84-a2d3-4ea7-8941-0f707ff7b84e | 3 | @Override
public T build(Map<Class<?>, ClassBuilder<?>> how) {
T o = null;
try {
o = this.underConstruction.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return o;
} |
4c6ead24-429a-46a5-9cce-f871274e4b9b | 5 | public void set(Object object, Object value)
{
try
{
if (m_method != null)
{
m_method.invoke(object, value);
}
else
{
m_field.set(object, value);
}
}
catch (IllegalArgumentException ex)
{
throw new ParameterException(ex);
}
catch (IllegalAccessException ex)
{
throw new ParameterException(ex);
}
catch (InvocationTargetException ex)
{
// If a ParameterException was thrown, don't wrap it into another
// one
if (ex.getTargetException() instanceof ParameterException)
{
throw (ParameterException) ex.getTargetException();
}
else
{
throw new ParameterException(ex);
}
}
} |
266477af-0f13-42d5-b3ad-6848d8659459 | 1 | public void run() {
while (countDown-- > 0) {
System.out.print(status());
Thread.yield();
}
} |
2673cd5b-a96d-43e0-bafd-cd3f3dc0962a | 9 | public static void modifyAccountTypes(List<Account> accountList, AccountTypes accountTypes){
if(!accountList.isEmpty()) {
boolean singleMove;
if (accountList.size() == 1) {
singleMove = true;
} else {
int option = JOptionPane.showConfirmDialog(null, getBundle("BusinessActions").getString("APPLY_SAME_TYPE_FOR_ALL_ACCOUNTS"),
getBundle("BusinessActions").getString("ALL"),
JOptionPane.YES_NO_OPTION);
singleMove = (option == JOptionPane.YES_OPTION);
}
if (singleMove) {
Object[] types = accountTypes.getBusinessObjects().toArray();
int nr = JOptionPane.showOptionDialog(null, ActionUtils.getFormattedString(ActionUtils.CHOOSE_NEW_TYPE),
ActionUtils.getFormattedString(ActionUtils.CHANGE_TYPE),
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, types, null);
if (nr != JOptionPane.CANCEL_OPTION && nr != JOptionPane.CLOSED_OPTION) {
for (Account account : accountList) {
account.setType((AccountType) types[nr]);
}
}
} else {
for (Account account : accountList) {
Object[] types = accountTypes.getBusinessObjects().toArray();
int nr = JOptionPane.showOptionDialog(null, ActionUtils.getFormattedString(CHOOSE_NEW_TYPE_FOR,account.getName()),
ActionUtils.getFormattedString(ActionUtils.CHANGE_TYPE), JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, types,
account.getType());
if (nr != JOptionPane.CANCEL_OPTION && nr != JOptionPane.CLOSED_OPTION) {
account.setType((AccountType) types[nr]);
}
}
}
}
//ComponentMap.refreshAllFrames();
} |
938f48ce-06c3-488f-884a-33805397945c | 1 | public static void toggleCommentInheritanceText(Node currentNode, JoeTree tree, OutlineLayoutManager layout) {
CompoundUndoablePropertyChange undoable = new CompoundUndoablePropertyChange(tree);
toggleCommentInheritanceForSingleNode(currentNode, undoable);
if (!undoable.isEmpty()) {
undoable.setName("Toggle Comment Inheritance for Node");
tree.getDocument().getUndoQueue().add(undoable);
}
// Redraw
layout.draw(currentNode, OutlineLayoutManager.TEXT);
} |
c2ef5abf-0d27-46f3-9a9e-0cf5b2587368 | 1 | public void test_toParser() {
DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder();
try {
bld.toParser();
fail();
} catch (UnsupportedOperationException ex) {}
bld.appendLiteral('X');
assertNotNull(bld.toParser());
} |
43364b0e-8658-49e0-8a66-7c8ac4e41252 | 7 | private void handle_color(String[] cmd) {
String oldc;
int c;
if (cmd.length == 1) { // Print only the palette
print_palette();
return;
}
if (cmd.length != 2) {
cliprint("Wrong parameter count. See \\help for details." + VT100.crlf);
return;
}
try {
c = Integer.parseInt(cmd[1]);
} catch (NumberFormatException ex) {
c = 99;
cliprint("Wrong color number. Not changing anything" + VT100.crlf);
return;
}
if (c > 15 || c < 1) {
cliprint("Wrong color number. Not changing anything" + VT100.crlf);
return;
}
oldc = client.color;
client.color = VT100.colors[c];
if (!oldc.equals(client.color)) {
dispatch2all(VT100.inverse + "User '" + client.nickname + "' has CHANGED HIS COLOR to " + client.color + VT100.inverse + "Color " + c + VT100.normal + VT100.crlf);
if (ms.jokes) dispatch2all(VT100.inverse + " Nag him if its your color." + VT100.normal + VT100.crlf);
}
return;
} |
23ab1c06-a65e-40cf-81b9-f9fb3e5b7bde | 6 | public ArrayList<Annotation> createAnnotationArrayListByTicket(int ticketId) {
ArrayList<Annotation> result = new ArrayList<Annotation>();
ResultSet rs = null;
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("select * from Annotations where TicketID_FK=? order by CreatedOn ASC");
statement.setInt(1, ticketId);
rs = statement.executeQuery();
while (rs.next()) {
int ticketid_fk;
int workerid_fk;
int annotationid;
String annotation;
Timestamp createdOn;
ticketid_fk = rs.getInt("TicketID_FK");
workerid_fk = rs.getInt("WorkerID_FK");
annotationid = rs.getInt("AnnotationID");
annotation = rs.getString("Annotation");
createdOn = rs.getTimestamp("CreatedOn");
Annotation temp = ModelFactory.createAnnotation(annotationid, annotation, createdOn, ticketid_fk, workerid_fk);
result.add(temp);
}
} catch(SQLException e){
e.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (Exception e) {}
try { if (statement != null) statement.close(); } catch (Exception e) {}
}
return result;
} |
f0a52d32-07a0-428d-a635-92e6e0c4a1a6 | 1 | public static void insertStock( int idarticle, int stock,int stockmin,int stockmaxi,Date datemaj,Float marge, Float ttc ) throws SQLException {
String query="";
try {
query = "INSERT INTO STOCK (ID_ARTICLE,STSTOCK,STMINI,STMAXI,STDATEMAJ,STMARGE,STTTC ) VALUES (?,?,?,?,?,?,?);";
PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query);
pStatement.setInt(1,idarticle);
pStatement.setInt(2, stock);
pStatement.setInt(3,stockmin);
pStatement.setInt(4, stockmaxi);
pStatement.setObject(5, datemaj);
pStatement.setFloat(6,marge );
pStatement.setFloat(7,ttc );
pStatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(RequetesStock.class.getName()).log(Level.SEVERE, null, ex);
}
} |
1a8569a9-8362-4925-bfe2-65da6c614b7d | 4 | public static int executeProgram(String[] cmd, File workingDir, StreamMonitor inputStream, StreamMonitor errStream) {
logger.trace("Executing '"+explode(cmd)+"' with working dir '"+workingDir.getAbsolutePath()+"'.");
int exitVal;
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd, null, workingDir);
// consume the err stream and stdout stream from the process
Thread inputStreamThread;
if (inputStream != null) {
inputStream.setStream(proc.getInputStream());
inputStreamThread = new Thread(inputStream);
}
else {
inputStreamThread = new StreamGobbler(proc.getInputStream(), StreamType.STDOUT); // the input stream is the STDOUT from the program being executed
}
inputStreamThread.start();
Thread errStreamThread;
if (errStream != null) {
errStream.setStream(proc.getErrorStream());
errStreamThread = new Thread(errStream);
}
else {
errStreamThread = new StreamGobbler(proc.getErrorStream(), StreamType.ERR);
}
errStreamThread.start();
// wait make sure stream threads have finished collecting output
inputStreamThread.join();
errStreamThread.join();
exitVal = proc.waitFor();
} catch (IOException e) {
throw(new RuntimeException("Error trying to execute program."));
} catch (InterruptedException e) {
throw(new RuntimeException("InterruptException occured. This shouldn't happen."));
}
return exitVal;
} |
e822e025-c296-44aa-a95a-2f807e7e8579 | 1 | public MapLayer getLayer(int i) {
try {
return layers.get(i);
} catch (ArrayIndexOutOfBoundsException e) {
}
return null;
} |
fe59b9f8-5cd7-47e6-a329-0f458bfe4a88 | 8 | private void initPrintWriter(StringBuilder sb) {
Log.info("Entities = " + getData().getEntities().size());
final boolean huge = getData().getEntities().size() > 800;
sb.append("digraph unix {");
for (String s : dotStrings) {
sb.append(s);
}
sb.append("bgcolor=\"" + getAsHtml(getData().getSkinParam().getBackgroundColor()) + "\";");
if (huge) {
sb.append("size=\"400,400;\"");
} else {
sb.append("ratio=auto;");
// sb.append("concentrate=true;");
}
// sb.append("ordering=out;");
sb.append("compound=true;");
final DotSplines dotSplines = getData().getSkinParam().getDotSplines();
final GraphvizLayoutStrategy strategy = getData().getSkinParam().getStrategy();
if (dotSplines == DotSplines.ORTHO) {
sb.append("splines=ortho;");
} else if (dotSplines == DotSplines.POLYLINE) {
sb.append("splines=polyline;");
} else if (strategy != GraphvizLayoutStrategy.DOT) {
sb.append("splines=true;");
}
// if (strategy == GraphvizLayoutStrategy.NEATO) {
// sb.append("overlap=false;");
// }
if (strategy != GraphvizLayoutStrategy.DOT) {
sb.append("layout=" + strategy.name().toLowerCase() + ";");
sb.append("overlap=false;");
}
sb.append("remincross=true;");
sb.append("searchsize=500;");
if (getData().getRankdir() == Rankdir.LEFT_TO_RIGHT) {
sb.append("rankdir=LR;");
}
if (getData().getDpi() != 96) {
sb.append("dpi=" + getData().getDpi() + ";");
sb.append("imagescale=both;");
}
} |
860fe707-3536-4348-a332-0ed6f79c94dd | 6 | public static void run(RobotController myRC)
{
rc = myRC;
RobotType t = rc.getType();
try
{
if (t == RobotType.SOLDIER)
{
Soldier.soldierCode(rc);
}
else if(t == RobotType.HQ)
{
HQ.hqCode(rc);
}
else if(t == RobotType.GENERATOR || t == RobotType.SUPPLIER)
{
Supplier.supplierCode(rc);
}
else
{
while(true)
{
rc.yield();
}
}
}
catch (Exception e)
{
System.out.println("caught exception before it killed us:");
e.printStackTrace();
}
} |
f0cf00d8-1e2a-4970-8720-ea165656f68e | 1 | @Override
public boolean retainAll(Collection<?> c) {
// TODO Auto-generated method stub
return false;
} |
f513dfc2-c698-4d76-a54b-958e2962c20f | 2 | private int[][] getLay(int numberLay) {
int lay[][] = new int[HEIGHT][HEIGHT];
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < HEIGHT; j++) {
lay[i][j] = yCbCr[i][j][numberLay];
}
}
return lay;
} |
5d819abf-29a6-4bc8-a8dd-13744ecc7cef | 6 | private void createDragObjects(CategoryType kat) {
ArrayList<Player> tmpPlayer = player.getPlayer(kat); //ArrayListe mit den Playern
String tmpTitle;
ImageLabel tmpLabel;
ArrayList<String> tmpObjectPath = null;
int posCoordinate = 0;
if (kat == CategoryType.BASS) {
tmpObjectPath = this.bassObjectPath;
posCoordinate = 0;
} else if (kat == CategoryType.BEATS) {
tmpObjectPath = this.beatsObjectPath;
posCoordinate = 3;
} else if (kat == CategoryType.HARMONY) {
tmpObjectPath = this.harmonyObjectPath;
posCoordinate = 6;
} else if (kat == CategoryType.MELODY) {
tmpObjectPath = this.melodyObjectPath;
posCoordinate = 9;
} else if (kat == CategoryType.EFFECTS) {
tmpObjectPath = this.effectsObjectPath;
posCoordinate = 12;
}
//Hinzufuegen der DragObjects mit ihren jeweiligen Bildern, Titel, Kategorien
//und Startpositionen zur ArrayList dragObjects
int i = 0;
for (Player actPlayer : tmpPlayer) {
tmpTitle = actPlayer.getTrack().getTitle();
tmpLabel = new ImageLabel(tmpObjectPath.get(i), tmpTitle, kat,
startCoordinate[posCoordinate + i][0],
startCoordinate[posCoordinate + i][1], actPlayer);
dragObject.add(tmpLabel);
i++;
}
} |
7cb64baf-46e2-4be7-86b2-8e63a322036a | 3 | public int getStartingY(int index) {
if(index == 0) {
return 0;
}
if(index == 1) {
return 0;
}
if(index == 2) {
return 200;
}
return 0;
} |
2ca07f05-2c1b-4c95-873e-93b545e156fe | 2 | private void createContent(WritableSheet sheet) throws WriteException,
RowsExceededException {
// Write a few number
for (int i = 1; i < 10; i++) {
// First column
addNumber(sheet, 0, i, i + 10);
// Second column
addNumber(sheet, 1, i, i * i);
}
// Lets calculate the sum of it
StringBuffer buf = new StringBuffer();
buf.append("SUM(A2:A10)");
Formula f = new Formula(0, 10, buf.toString());
sheet.addCell(f);
buf = new StringBuffer();
buf.append("SUM(B2:B10)");
f = new Formula(1, 10, buf.toString());
f.setCellFormat(bgBlue);
sheet.addCell(f);
// now a bit of text
for (int i = 12; i < 20; i++) {
// First column
addLabel(sheet, 0, i, "Boring text " + i);
// Second column
addLabel(sheet, 1, i, "Another text");
}
} |
efe0b29f-0cf3-4861-91f6-d20f57118f43 | 0 | public TransformsType createTransformsType() {
return new TransformsType();
} |
47eb5eec-3bbb-4c8a-9395-5b5d6c66a9c2 | 8 | public int largestRectangleArea(int[] height) {
int max = 0;
if(height.length ==0) return 0;
int[] nh = Arrays.copyOf(height, height.length+1);
nh[height.length] = 0;
Stack<Integer> large = new Stack<Integer>();
for(int i=0; i<nh.length; i++)
{
if(large.isEmpty() ||nh[i]>=nh[large.peek()])
{
large.add(i);
}else
{
while(!large.isEmpty() && (nh[large.peek()]>nh[i] || large.peek() ==0))
{
int j=large.pop();
max = Math.max(max, (large.isEmpty()?i:(i-j))*nh[j]);
}
large.add(i);
}
}
return max;
} |
45510c84-3fd7-4c18-8484-2aeed29ec2e5 | 8 | private static String normalizeCondition(String variable, String operator, String content) {
String normalCondition = "";
content = content.toLowerCase();
if (content.contains(" * ")) {
normalCondition = "\"" + variable + "\".match(/\\b" + content.replace(" * ", "\\b.*\\b") + "\\b/) !== null";
}
else if ("*".equals(content)) {
normalCondition = "\"" + variable + "\" !== null";
}
else if ("=".equals(operator)) {
normalCondition = "\"\\b" + variable + "\\b\" === \"\\b" + content + "\\b\"";
}
else if ("!=".equals(operator)) {
normalCondition = "\"\\b" + variable + "\\b\" !== \"\\b" + content + "\\b\"";
}
else if ("in".equals(operator)) {
normalCondition = "\"" + variable + "\".match(/\\b" + content + "\\b/) !== null";
}
else if ("!in".equals(operator)) {
normalCondition = "\"" + variable + "\".match(/\\b" + content + "\\b/) === null";
}
else if ("sw".equals(operator)) {
normalCondition = "\"" + variable + "\".match(/^" + content + "\\b/) !== null";
}
else if ("ew".equals(operator)) {
// Assume every utterances end with a punctuation
normalCondition = "(\"" + variable + "\".lastIndexOf(\"" + content + "\") >= 0 && \"" + variable + "\".lastIndexOf(\"" + content + "\") == \"" + variable + "\".length - \"" + content + "\".length)";
}
else {
normalCondition = "\"" + variable + "\" " + operator + " \"" + content + "\"";
}
return normalCondition;
} |
065189e6-fe81-4aa6-a84f-631ef3bafab7 | 7 | @Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Move other = (Move) obj;
if (x1 != other.x1) {
return false;
}
if (x2 != other.x2) {
return false;
}
if (y1 != other.y1) {
return false;
}
if (y2 != other.y2) {
return false;
}
return true;
} |
a3d587b3-826e-48bc-813e-8edb7e4f0b7a | 5 | public void draw(Graphics g, ImageObserver io){
if(waittime > 0){
waittime = waittime - 1;
return;
}
g.drawImage(bimage1, char_x, char_y, io);
char_x = char_x - 4;
if(char_x < -48){
syutsugen();
}
if(spkey == true){
speed = speed - 0.15;
}else{
speed = speed + 0.15;
}
if(speed > 4 || speed < -4){
spkey = !spkey;
char_y = char_y + (int)speed;
}
} |
7b5af77b-faba-418d-a578-0f4cb754c120 | 8 | static long readVLong(DataInput in) throws IOException {
byte b = in.readByte();
if (b >= 0) return b;
long i = b & 0x7FL;
b = in.readByte();
i |= (b & 0x7FL) << 7;
if (b >= 0) return i;
b = in.readByte();
i |= (b & 0x7FL) << 14;
if (b >= 0) return i;
b = in.readByte();
i |= (b & 0x7FL) << 21;
if (b >= 0) return i;
b = in.readByte();
i |= (b & 0x7FL) << 28;
if (b >= 0) return i;
b = in.readByte();
i |= (b & 0x7FL) << 35;
if (b >= 0) return i;
b = in.readByte();
i |= (b & 0x7FL) << 42;
if (b >= 0) return i;
b = in.readByte();
i |= (b & 0x7FL) << 49;
if (b >= 0) return i;
b = in.readByte();
i |= (b & 0xFFL) << 56;
return i;
} |
b2e5db2e-c644-4d0d-8785-d22b79a457bb | 1 | private static int[] mergeSort(int[] A, int l, int r){
if(r-l<1) return new int[]{A[r]};
int mid = (l+r)/2;
int[] leftSorted = mergeSort(A, l, mid);
int[] rightSorted = mergeSort(A, mid+1, r);
return merge(leftSorted,rightSorted);
} |
0cf95674-31e5-41cb-8098-8f200f56d7e4 | 6 | private void jBListarIncidentesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBListarIncidentesActionPerformed
// TODO add your handling code here:
int barrio = combo_barrio_reporte.getSelectedIndex();
if (barrio != 0) {
Barrio codigobarrio = controlador.buscarBarrio(combo_barrio_reporte.getSelectedItem().toString());
getControlador().cargarIncidentesPorBarrio(codigobarrio.getBar_codigo());
DefaultTableModel lstIncidente = (DefaultTableModel) tableListaIncidente.getModel();
if (!getControlador().getListaInci().isEmpty()) {
JOptionPane.showMessageDialog(null, "Se tienen " + getControlador().getListaInci().size() + " Incidentes Registrados en el Barrio: " + codigobarrio.getBar_nombre());
tableListaIncidente.removeAll();
int rowCount = lstIncidente.getRowCount();
for (int i = 0; i < rowCount; i++) {
lstIncidente.removeRow(i);
}
for (int i = 0; i < getControlador().getListaInci().size(); i++) {
lstIncidente.addRow(new Object[]{getControlador().getListaInci().get(i).getBarrio().getBar_nombre(), getControlador().getListaInci().get(i).getInc_codigoIncidente(), getControlador().getListaInci().get(i).getInc_descripcionIncidente(), getControlador().getListaInci().get(i).getInc_fechaIncidente(), getControlador().getListaInci().get(i).getUsuario().getTelefono(), getControlador().getListaInci().get(i).getTipo_incidente().getTipinc_descripcion(),getControlador().getListaInci().get(i).getTipo_ingreso_incidente().getTii_descripcion()});
}
} else {
JOptionPane.showMessageDialog(null, "No tiene Se Tienen Incidentes en el Barrio: " + codigobarrio.getBar_nombre());
int rowCount = lstIncidente.getRowCount();
for (int i = 0; i < rowCount; i++) {
lstIncidente.removeRow(i);
}
if (lstIncidente.getRowCount() > 0) {
lstIncidente.removeRow(tableListaIncidente.getSelectedRow());
}
}
} else {
JOptionPane.showMessageDialog(null, "Debe Seleccionar Un Barrio");
}
}//GEN-LAST:event_jBListarIncidentesActionPerformed |
91335a61-4824-4203-b5b6-1bc25ef40099 | 3 | LineScanner(String text) {
int c = 0;
data = new ArrayList<String>();
String tmp = "";
lineCount = 1;
current = 0;
while (c < text.length()) {
tmp = tmp + Character.toString(text.charAt(c));
if (text.charAt(c) == 0x0a) {
data.add(tmp);
tmp = "";
lineCount++;
}
c++;
}
if (!tmp.matches("")) {
data.add(tmp);
}
} |
90544224-5ed1-4c8d-811a-9f3943b7f090 | 2 | private int divide(int startIndex, int endIndex) {
int optimalIndex = getOptimalIndex(startIndex, endIndex);
int pivot = a[optimalIndex];
swap(optimalIndex, endIndex);
int marker = startIndex;
for (int i = startIndex; i < endIndex; i++) {
if (a[i] <= pivot) {
swap(i, marker);
marker++;
}
}
swap(marker, endIndex);
return marker;
} |
6e08b79a-ace7-43af-8e02-817121957de5 | 1 | public void testSetInterval_RInterval2() {
MutableInterval test = new MutableInterval(TEST_TIME1, TEST_TIME2);
try {
test.setInterval(new MockBadInterval());
fail();
} catch (IllegalArgumentException ex) {}
} |
d3911835-6e42-446b-9794-23ae3571837b | 4 | private static char mul (int a, char b) {
int inda = (a < 0) ? (a + 256) : a;
int indb = (b < 0) ? (b + 256) : b;
if ( (a != 0) && (b != 0) ) {
int index = (LogTable[inda] + LogTable[indb]);
char val = (char)(AlogTable[ index % 255 ] );
return val;
}
else
return 0;
} // mul |
8aa8fcc3-0c55-4a5b-8c7b-c34e3d6a7b7b | 2 | public static String readString() {
String line = null;
try {
BufferedReader is = new BufferedReader(new InputStreamReader(
System.in));
line = is.readLine();
} catch (NumberFormatException ex) {
System.err.println("Not a valid number: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
return line;
} |
829eaaea-ecce-4cb4-b1ee-5937a7fb673a | 9 | public static void main(String[] args)
{
// default values
int portNumber = 27886;
String serverAddress = "localhost";
String username = "Anonymus";
// depending of the number of arguments provided we fall through
switch(args.length)
{
// > java Client username portNumber serverAddress
case 3:
serverAddress = args[2];
// > java Client username portNumber
case 2:
try
{
portNumber = Integer.parseInt(args[1]);
}
catch(Exception e)
{
System.out.println("Invalid port number.");
System.out.println("Usage is: > java Client [username] [portNumber] [serverAddress]");
return;
}
// > java Client username
case 1:
username = args[0];
case 0:
break;
// ivalid number of arguments
default:
System.out.println("Usage is: > java Client [username] [portNumber] [serverAddress]");
return;
}
// create the Client Object
Client _client = new Client(serverAddress, portNumber, username);
// test if we can start the connection to the server
// if it failed, nothing we can do
if(!_client.start())
return;
// wait for messages from user
Scanner scan = new Scanner(System.in);
// loop forever for message from the user
while(true)
{
System.out.println("> ");
// read message from user
String msg = scan.nextLine();
// logout if message is LOGOUT
if(msg.equalsIgnoreCase("LOGOUT"))
{
_client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, ""));
// break to do the disconnect
break;
}
// message WHOISIN
else if(msg.equalsIgnoreCase("WHOISIN"))
{
_client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, ""));
}
// default to ordinary message
else
{
_client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, msg));
}
}
// done disconnect
scan.close();
_client.disconnect();
} |
5bda7275-986f-4b2d-bf3d-8386c756c20c | 5 | static String[] flavorSet(int n) {
// Force it to be positive & within bounds:
n = Math.abs(n) % (flav.length + 1);
String[] results = new String[n];
int[] picks = new int[n];
for (int i = 0; i < picks.length; i++)
picks[i] = -1;
for (int i = 0; i < picks.length; i++) {
retry: while (true) {
int t = (int) (Math.random() * flav.length);
for (int j = 0; j < i; j++)
if (picks[j] == t)
continue retry;
picks[i] = t;
results[i] = flav[t];
break;
}
}
return results;
} |
961a28ac-2b55-410d-9967-bbff5e72e7a6 | 3 | @Override
public boolean isUserError() {
if (getCategory() == 1)
return true;
else if (getCategory() == 3 && getCode() == 52)
return true;
else
return false;
} |
db9d10f9-7c3c-4314-9481-581cfdecc87b | 2 | private boolean passCards(PinochlePlayer from, PinochlePlayer to, List<Card> cards) {
boolean result = false;
try {
List<Card> fromCards = new ArrayList<Card>(from.getCurrentCards());
List<Card> toCards = new ArrayList<Card>(to.getCurrentCards());
System.out.println("from Old : " + fromCards);
System.out.println("to Old : " + toCards);
for (Card card : cards) {
toCards.add(card);
fromCards.remove(card);
}
from.setCards(fromCards);
to.setCards(toCards);
System.out.println("from New : " + fromCards);
System.out.println("to New : " + toCards);
result = true;
}
catch(Exception e) {
e.printStackTrace();
}
return result;
} |
c21204f6-f3d5-47a8-85c0-0ef053b5e14a | 9 | public static long m68ki_get_sr() {
return ((((m68k_cpu.t1_flag != 0) ? 1 : 0) << 15)
| (((m68k_cpu.t0_flag != 0) ? 1 : 0) << 14)
| (((m68k_cpu.s_flag != 0) ? 1 : 0) << 13)
| (((m68k_cpu.m_flag != 0) ? 1 : 0) << 12)
| (m68k_cpu.int_mask << 8)
| (((m68k_cpu.x_flag != 0) ? 1 : 0) << 4)
| (((m68k_cpu.n_flag != 0) ? 1 : 0) << 3)
| (((m68k_cpu.not_z_flag == 0) ? 1 : 0) << 2)
| (((m68k_cpu.v_flag != 0) ? 1 : 0) << 1)
| ((m68k_cpu.c_flag != 0) ? 1 : 0));
} |
70aa28e4-4af6-43ce-9130-a1a9aea07d7c | 9 | protected void process(double[][] B, int att, int pos, BitSet C, double[][] D)
{
if (!isCanonical(B, D, att) || (C.cardinality() < minSup) ) return;
if (Main.printResult)
System.out.println("Closed " +toStringPattern(D) + " --- " + toStringBitSet(C));
closedCount++;
for (int i = att; i < attCount; i++)
{
if (D[i][0] == D[i][1]) continue;
if (!(i == att && pos == 1))
{
patternR = clonePattern(D);
patternR[i][1] = domains[i].lower(D[i][1]);
if (patternR[i][0] <= patternR[i][1])
{
prime = prime(patternR,C);
process(patternR, i, 0, prime, prime(prime));
}
}
patternL = clonePattern(D);
patternL[i][0] = domains[i].higher(D[i][0]);
if (patternL[i][0] <= patternL[i][1])
{
prime = prime(patternL,C);
process(patternL, i, 1, prime, prime(prime));
}
}
} |
01eef310-c97b-4a70-be1b-051edaa3d18f | 2 | public synchronized void reset() {
for(int i = 0; i < receivedPackets.length; i++)
receivedPackets[i] = null;
receivedPacketHistoryInt = 0;
lastReceivedPacketIndex = -1;
lastReceivedPacketSequenceNumber = Packet.SEQUENCE_NUMBER_NOT_APPLICABLE;
for(int i = 0; i < sentPackets.length; i++)
sentPackets[i] = null;
lastSentPacketIndex = -1;
lastSentPacketSequenceNumber = Packet.SEQUENCE_NUMBER_NOT_APPLICABLE;
lastSentPacketCheckedForDelivery = Packet.SEQUENCE_NUMBER_NOT_APPLICABLE;
} |
9d137d73-32e8-4bef-8b0e-a68e67a51bdf | 8 | @Override
public void run() {
while (_model.isRunning()) {
long beginTimeMillis, timeTakenMillis, timeLeftMillis;
beginTimeMillis = System.currentTimeMillis();
if(_model.isResetGame()){
resetHard();
for (Ball b : balls) {
b.setBallImg(Functions.getBallIMG(_model.getBallChoice()));
}
_model.setResetGame(false);
}
if (balls.get(0) != null && tm.getGameField() != null) {
if (_model.isMoving() && !_model.isPause()) {
gameUpdate();
}
}
repaint();
// Draaien op 30 FPS
timeTakenMillis = System.currentTimeMillis() - beginTimeMillis;
timeLeftMillis = 1000L / _model.getUPDATE_RATE() - timeTakenMillis;
if (timeLeftMillis < 5) {
timeLeftMillis = 5; // Minimum bepaald
}
sleep(thread, timeLeftMillis);
}
} |
78add6c6-2fba-465d-a8fb-ebcb0a1a0287 | 4 | public void flipCard(int row, int col){
if (prevSelectedCardRow == -1 && prevSelectedCardCol == -1){
prevSelectedCardRow = row;
prevSelectedCardCol = col;
cards[row][col].setShowing(true);
updateButtons();
}
else if ( prevSelectedCardRow != -1 && prevSelectedCardCol != -1){
cards[row][col].setShowing(true);
updateButtons();
this.game.matchedCards( cards[prevSelectedCardRow][prevSelectedCardCol], cards[row][col]);
scoreLabel.setText(Integer.toString(this.game.getScore()));
//update the score in the UI
prevSelectedCardRow = -1;
prevSelectedCardCol = -1;
}
} |
093857a9-deb9-42fa-994e-1a6cbc77295d | 9 | @Override
public Object visitUnaryExprAST(UnaryExprAST ast, Object o) throws CompilationException
{
int constmt = findCon(ast.parent.line);
System.out.println("Parent line "+ ast.parent.line + " " + constmt);
String res = "";
if(ast.opType == UnaryExprAST.LOGICAL_NOT)
{
if(o == "c")
{
res += "(not " + ast.e.visit(this, "c") + ")";
return res;
}
else
{
boolean check = true;
PathNode obj = (PathNode)o;
int branch = obj.branch;
if(branch == 0)
{
res += "(assert (not " + ast.e.visit(this, "c") + "))\n";
ArrayList<String> temp = con.get(constmt).getTruepath();
for(int i=0; i < temp.size(); i++)
if(temp.get(i).equals(res))
check = false;
if(check == true)
{
con.get(constmt).getTruepath().add(res);
con.get(constmt).getTruecon().add(obj.con);
}
}
else
{
res += "(assert " + ast.e.visit(this, "c") + ")\n";
ArrayList<String> temp = con.get(constmt).getFalsepath();
for(int i=0; i < temp.size(); i++)
if(temp.get(i).equals(res))
check = false;
if(check == true)
{
con.get(constmt).getFalsepath().add(res);
con.get(constmt).getFalsecon().add(obj.con);
}
}
return "";
}
}
return "";
} |
e9ae4d0d-4e05-48b2-a7fe-f7ffff4763fa | 7 | public boolean isActive(int t){
//this function figures out whether the overlap score of this column
//is among the top DesiredLocalActivity-percent of its neighbor
//if it is set it active, if not remain inactive
if(overlap>0){
int tie=1;
int ahead=0;
for(Column c : neighbor){
if(c.overlap > this.overlap){
ahead++;
continue;
}
else if(c.overlap == this.overlap) tie++;
}
//int maxLocalRank= DesiredLocalActivity;
int maxLocalRank= (int) Math.round(neighbor.size()*DesiredLocalActivityRatio);
//test display
//System.out.print(maxLocalRank);
//System.out.print("["+this.posRow+","+this.posColumn+"];");
if(ahead+tie <= maxLocalRank){
active=true;
activeQueue.offer(t);
return true;
}else if(ahead < maxLocalRank){
if(Math.random() < (double)1/tie){
active=true;
activeQueue.offer(t);
return true;
}
}
}
return false;
} |
6a4809be-2beb-4805-bdf4-74f484e078a0 | 3 | public void setEquipa(Collection<String> equipas, String cod_competicao) {
DAOTorneio.setEquipa(equipas, cod_competicao);
for (String a : equipas) {
Collection<Jogador> jogadores = this.getEquipa().get(a).getJogadores();
if (jogadores != null) {
for (Jogador jog : jogadores) {
this.getMarcador().put(cod_competicao, jog.getCodJogador());
}
}
}
} |
f9b367a9-7781-47ea-a6a6-fda52e01f278 | 7 | private boolean computeCell(int col, int row) {
boolean liveCell = getCell(col, row);
int neighbours = countNeighbours(col, row);
boolean nextCell = false;
if (neighbours < 2)
nextCell = false;
if (liveCell && (neighbours == 2 || neighbours == 3))
nextCell = true;
if (neighbours > 3)
nextCell = false;
if (!liveCell && (neighbours == 3))
nextCell = true;
return nextCell;
} |
6c4dbb6d-983d-43db-a2be-97cbc593a517 | 3 | private static String getServerIP(int port) throws HeadlessException {
BufferedReader in = null;
try {
// ip = InetAddress.getLocalHost().getHostAddress() + ":" + port;
// Connect to website containing IP address.
URL whatismyip = new URL("http://api.exip.org/?call=ip");
in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
// Add port and return.
return in.readLine() + ":" + port;
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage(), "Alert", JOptionPane.ERROR_MESSAGE);
} finally {
if (in != null)
try {
in.close();
} catch (IOException ex) {
// ignore
}
}
// If unable to get address, return unknown.
return "?:" + port;
} |
0b68b26e-7fd1-4834-a207-9e2de75b6147 | 9 | public void addMatch()
{
Players players = new Players();
Scanner scan = new Scanner(System.in);
Player resultPlayer = null;
while (resultPlayer == null)
{
System.out.println("Wybierz pierwszego gracza:");
firstPlayer = scan.nextInt();
try {
resultPlayer = players.getPlayer(firstPlayer);
} catch (SQLException e) {
e.printStackTrace();
}
}
firstPlayerObj = resultPlayer;
resultPlayer = null;
while (resultPlayer == null)
{
System.out.println("Wybierz drugiego gracza:");
secondPlayer = scan.nextInt();
try {
resultPlayer = players.getPlayer(secondPlayer);
} catch (SQLException e) {
e.printStackTrace();
}
}
secondPlayerObj = resultPlayer;
firstScore = 0;
secondScore = 0;
String firstPL = firstPlayerObj.name + " " + firstPlayerObj.lastname;
String secondPL = secondPlayerObj.name + " " + secondPlayerObj.lastname;
while (firstScore < 2 && secondScore <2)
{
int firstChoice = generateChoice();
int secondChoice = generateChoice();
System.out.println("W tym losowaniu wylosowano:");
System.out.println(firstPL + ": " + choiceDict.get(firstChoice));
System.out.println(secondPL + ": " + choiceDict.get(secondChoice));
if ((Integer) beatsList.get(firstChoice) == secondChoice)
{
firstScore++;
System.out.println("Wygrywa: " + firstPL);
}
else if ((Integer) beatsList.get(secondChoice) == firstChoice)
{
secondScore++;
System.out.println("Wygrywa: " + secondPL);
}
else
{
System.out.println("Remis.");
}
System.out.println();
System.out.println();
}
int firstPoints = firstPlayerObj.points;
int secondPoints = secondPlayerObj.points;
int winner = 0;
if (firstScore == 2)
{
winner = firstPlayerObj.id;
firstPoints += winPoints;
secondPoints += loosePoints;
System.out.println("Cały mecz wygrywa: " + firstPL);
}
else
{
winner = secondPlayerObj.id;
firstPoints += loosePoints;
secondPoints += winPoints;
System.out.println("Cały mecz wygrywa: " + secondPL);
}
addMatchToDB(firstPlayerObj.id, secondPlayerObj.id, firstScore, secondScore, winner);
addPoints(firstPlayerObj.id, firstPoints);
addPoints(secondPlayerObj.id, secondPoints);
updateMatchCount(firstPlayerObj.id, firstPlayerObj.matches + 1);
updateMatchCount(secondPlayerObj.id, secondPlayerObj.matches + 1);
} |
a60b499b-60c9-488b-a66a-c16de5995614 | 0 | public void setjButtonNext(JButton jButtonNext) {
this.jButtonNext = jButtonNext;
} |
833a3d2d-5947-4bde-90fa-d4ea05c76f17 | 0 | public static HashMap<String, String> readJSON(String line)
{
return null;
} |
86dd7949-a4a2-42f3-b96f-3ccc50f8639d | 6 | public void mouseDragged(MouseEvent e) {
performDragScrollIfActive(e);
Tile tile = mapViewer.convertToMapTile(e.getX(), e.getY());
if (tile != null &&
(e.getModifiers() & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK) {
// only perform the goto for the left mouse button
if (mapViewer.isGotoStarted()) {
Unit active = mapViewer.getActiveUnit();
if (active == null) {
mapViewer.stopGoto();
} else {
if (lastTile != tile) {
lastTile = tile;
if (active.getTile() != tile) {
PathNode dragPath = active.findPath(tile);
mapViewer.setGotoPath(dragPath);
} else {
mapViewer.setGotoPath(null);
}
}
}
} else {
mapViewer.startGoto();
}
}
} |
e806a9d6-274c-45dd-9da4-c397b9cc1162 | 7 | private void testHelper_method_unknownAnchor_shouldFail(MethodToTest method)
{
final IMutableMolecule UNKNOWN_ANCHOR = mock(IMutableMolecule.class);
switch (method)
{
case changeMoleculeEnergyLevel:
moleculeMediator.changeMoleculeEnergyLevel(UNKNOWN_ANCHOR, VALID_POSITION, VALID_ENERGY_CHANGE_AMOUNT);
break;
case createMoleculeAtPositionRelativeToAnchor:
moleculeMediator.createMoleculeAtPositionRelativeToAnchor(
UNKNOWN_ANCHOR,
VALID_POSITION,
new MoleculeDescriptor(
VALID_REMAINING_ENERGY,
VALID_MAX_ENERGY,
VALID_BEHAVIOUR,
neuteredMovementAction));
break;
case getMoleculeAtPositionRelativeToAnchor:
moleculeMediator.getMoleculeAtPositionRelativeToAnchor(UNKNOWN_ANCHOR, VALID_POSITION);
break;
case getResourcesAtPositionRelativeToAnchor:
moleculeMediator.getResourcesAtPositionRelativeToAnchor(UNKNOWN_ANCHOR, VALID_POSITION);
break;
case exchangeMoleculePositions:
moleculeMediator.exchangeMoleculePositions(UNKNOWN_ANCHOR, VALID_POSITION);
break;
case changeResourceAmount:
moleculeMediator.changeResourceAmount(UNKNOWN_ANCHOR, VALID_POSITION, VALID_TYPE, VALID_AMOUNT);
break;
case modifyMolecule:
moleculeMediator.modifyMolecule(UNKNOWN_ANCHOR, VALID_POSITION, VALID_MODIFIER);
break;
default: throw new RuntimeException("Unknown method: " + method.name());
}
} |
f690a5eb-c58e-4edf-b4e9-81413363b956 | 0 | @Test
public void testUpdate() {
fail("Not yet implemented");
} |
8c4ab498-5a6c-41a3-8391-de45b004de88 | 8 | public void moveRight() {
setDirection(90);
for (TetrisBug tb : blocks){
tb.setDirection(90);
}
if (rotationPos==0){
if (blocks.get(0).canMove() && blocks.get(2).canMove()) {
blocks.get(2).move();
move();
blocks.get(0).move();
blocks.get(1).move();
}
}
if (rotationPos == 1){
if (blocks.get(2).canMove() && canMove() && blocks.get(1).canMove()){
blocks.get(2).move();
move();
blocks.get(1).move();
blocks.get(0).move();
}
}
} |
52358310-2fef-468b-a9ea-3a38cff0eb3c | 7 | void radf2(final int ido, final int l1, final float in[], final int in_off, final float out[], final int out_off, final int offset) {
int i, ic, idx0, idx1, idx2, idx3, idx4;
float t1i, t1r, w1r, w1i;
int iw1;
iw1 = offset;
idx0 = l1 * ido;
idx1 = 2 * ido;
for (int k = 0; k < l1; k++) {
int oidx1 = out_off + k * idx1;
int oidx2 = oidx1 + idx1 - 1;
int iidx1 = in_off + k * ido;
int iidx2 = iidx1 + idx0;
float i1r = in[iidx1];
float i2r = in[iidx2];
out[oidx1] = i1r + i2r;
out[oidx2] = i1r - i2r;
}
if (ido < 2)
return;
if (ido != 2) {
for (int k = 0; k < l1; k++) {
idx1 = k * ido;
idx2 = 2 * idx1;
idx3 = idx2 + ido;
idx4 = idx1 + idx0;
for (i = 2; i < ido; i += 2) {
ic = ido - i;
int widx1 = i - 1 + iw1;
int oidx1 = out_off + i + idx2;
int oidx2 = out_off + ic + idx3;
int iidx1 = in_off + i + idx1;
int iidx2 = in_off + i + idx4;
float a1i = in[iidx1 - 1];
float a1r = in[iidx1];
float a2i = in[iidx2 - 1];
float a2r = in[iidx2];
w1r = wtable_r[widx1 - 1];
w1i = wtable_r[widx1];
t1r = w1r * a2i + w1i * a2r;
t1i = w1r * a2r - w1i * a2i;
out[oidx1] = a1r + t1i;
out[oidx1 - 1] = a1i + t1r;
out[oidx2] = t1i - a1r;
out[oidx2 - 1] = a1i - t1r;
}
}
if (ido % 2 == 1)
return;
}
idx2 = 2 * idx1;
for (int k = 0; k < l1; k++) {
idx1 = k * ido;
int oidx1 = out_off + idx2 + ido;
int iidx1 = in_off + ido - 1 + idx1;
out[oidx1] = -in[iidx1 + idx0];
out[oidx1 - 1] = in[iidx1];
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.