method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
bacc4dd4-9aa8-47a6-8b19-7775a9899a27 | 5 | private void isaac() {
lastResult += ++counter;
for (int i = 0; i < 256; i++) {
int j = memory[i];
if ((i & 3) == 0) {
accumulator ^= accumulator << 13;
} else if ((i & 3) == 1) {
accumulator ^= accumulator >>> 6;
} else if ((i & 3) == 2) {
accumulator ^= accumulator << 2;
} else if ((i & 3) == 3) {
accumulator ^= accumulator >>> 16;
}
accumulator += memory[i + 128 & 0xff];
int k;
memory[i] = k = memory[(j & 0x3fc) >> 2] + accumulator + lastResult;
results[i] = lastResult = memory[(k >> 8 & 0x3fc) >> 2] + j;
}
} |
12e79b34-46eb-4915-ae62-0289eb812bce | 8 | public static void main(String[] args) {
System.out.print("Ile znajduje sie w bankomacie banknotow o nominale 100: ");
int nominalStoKomora = IO.readInt();
System.out.print("Ile znajduje sie w bankomacie banknotow o nominale 50: ");
int nominalPiecdziesiatKomora = IO.readInt();
System.out.print("Ile znajduje sie w bankomacie banknotow o nominale 20: ");
int nominalDwadziesciaKomora = IO.readInt();
System.out.print("Ile znajduje sie w bankomacie banknotow o nominale 10: ");
int nominalDziesiecKomora = IO.readInt();
System.out.print("Podaj kod PIN: ");
String pin = IO.readString();
if (pin.equals("1234") == false) {
System.out.println("BLEDNY PIN");
System.out.print("Podaj kod PIN: ");
pin = IO.readString();
if (pin.equals("1234") == false) {
System.out.println("BLEDNY PIN");
System.out.print("Podaj kod PIN: ");
pin = IO.readString();
if (pin.equals("1234") == false) {
System.out.println("BLEDNY PIN");
System.out.print("TRZY RAZY PODANO BLEDNY PIN");
return;
}
}
}
System.out.println("Podaj kwote do wyplaty: ");
int kwotaWyplaty = IO.readInt();
System.out.println("=================================");
System.out.println("WYPLATA: " + kwotaWyplaty);
int nominalStoWyplata = (kwotaWyplaty / 100);
if (nominalStoWyplata > nominalStoKomora) {
nominalStoWyplata = nominalStoKomora;
}
kwotaWyplaty = kwotaWyplaty - (nominalStoWyplata * 100);
int nominalPiecdziesiatWyplata = (kwotaWyplaty / 50);
if (nominalPiecdziesiatWyplata > nominalPiecdziesiatKomora) {
nominalPiecdziesiatWyplata = nominalPiecdziesiatKomora;
}
kwotaWyplaty = kwotaWyplaty - (nominalPiecdziesiatWyplata * 50);
int nominalDwadziesciaWyplata = (kwotaWyplaty / 20);
if (nominalDwadziesciaWyplata > nominalDwadziesciaKomora) {
nominalDwadziesciaWyplata = nominalDwadziesciaKomora;
}
kwotaWyplaty = kwotaWyplaty - (nominalDwadziesciaWyplata * 20);
int nominalDziesiecWyplata = (kwotaWyplaty / 10);
if (nominalDziesiecWyplata > nominalDziesiecKomora) {
nominalDziesiecWyplata = nominalDwadziesciaKomora;
}
kwotaWyplaty = kwotaWyplaty - (nominalDziesiecWyplata * 10);
if (kwotaWyplaty > 0) {
System.out.println(" Brak mozliwosci wyplaty gotowki");
} else {
System.out.println("--------------> " + nominalStoWyplata + " banknoty po 100 zl");
System.out.println("--------------> " + nominalPiecdziesiatWyplata
+ " banknoty po 50 zl");
System.out.println("--------------> " + nominalDwadziesciaWyplata
+ " banknoty po 20 zl");
System.out.println("--------------> " + nominalDziesiecWyplata + " banknoty po 10 zl");
}
} |
108181ce-1f3a-434b-837b-86a96d95343a | 6 | public static char[] encodeText(char[] c, int n, char[] A) {
char[] o = new char[c.length]; //create an array to output encrypted message
for (int i = 0; i < c.length; i++) {
//if array elemnt is punc. mark or space, copy it
if (c[i] == ' ' || c[i] == '.' || c[i] == ',') o[i] = c[i];
//else, find in alphabet and shift for n
else {
alph:
for (int j = 0; j < A.length; j++) {
if (A[j] == c[i]) {
o[i] = A[(j + n) % A.length];
break alph;
}
}
}
}
return o;
} |
b82a03b0-d4bd-4ff9-a624-a53f91284f11 | 9 | public void actionPerformed(ActionEvent e) {
JComboBox combo = new JComboBox();
// Figure out what existing environments in the program have
// the type of structure that we need.
EnvironmentFrame[] frames = Universe.frames();
for (int i = 0; i < frames.length; i++) {
if (!isApplicable(frames[i].getEnvironment().getObject())
|| frames[i].getEnvironment() == environment)
continue;
combo.addItem(frames[i]);
}
// Set up our automaton.
FiniteStateAutomaton automaton = (FiniteStateAutomaton) environment
.getObject();
if (combo.getItemCount() == 0) {
JOptionPane.showMessageDialog(Universe
.frameForEnvironment(environment), "No other FAs around!");
return;
}
if (automaton.getInitialState() == null) {
JOptionPane.showMessageDialog(Universe
.frameForEnvironment(environment),
"This automaton has no initial state!");
return;
}
// Prompt the user.
int result = JOptionPane.showOptionDialog(Universe
.frameForEnvironment(environment), combo, "Compare against FA",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
null, null, null);
if (result != JOptionPane.YES_OPTION && result != JOptionPane.OK_OPTION)
return;
FiniteStateAutomaton other = (FiniteStateAutomaton) ((EnvironmentFrame) combo
.getSelectedItem()).getEnvironment().getObject();
if (other.getInitialState() == null) {
JOptionPane.showMessageDialog(Universe
.frameForEnvironment(environment),
"The other automaton has no initial state!");
return;
}
other = (FiniteStateAutomaton) UselessStatesDetector
.cleanAutomaton(other);
automaton = (FiniteStateAutomaton) UselessStatesDetector
.cleanAutomaton(automaton);
String checkedMessage = checker.equals(other, automaton) ? "They ARE equivalent!"
: "They AREN'T equivalent!";
JOptionPane.showMessageDialog(
Universe.frameForEnvironment(environment), checkedMessage);
} |
f3a32c4d-03c9-447c-b9bf-fbcf917f44c7 | 4 | public static void main(String[] args) {
try {
if (args.length < 5) {
System.out.println("parameters error!");
showHelp();
System.exit(0);
} else {
txtPath = args[1];
xmlPath = args[2];
StanfordInputpath = args[3];
outputPath = args[4];
}
if(args[0].equals("-o")){
System.out.println("creating xml file...");
execute('o');
}
else if(args[0].equals("-e")){
System.out.println("creating xml files...");
execute('e');
}
else {
showHelp();
System.exit(0);
}
System.out.println("done!");
} catch (Exception e) {
e.printStackTrace();
//showHelp();
}
} |
b7ff3a50-bef3-4594-9795-591b3c4dd6ad | 5 | @Override
public void loop() {
switch (step) {
case 0:
if(Motors.movement.isMoving()){
if(Motors.ts.isPressed()){
Motors.movement.forward();
reset();
step++;
}
}
else{
Motors.movement.backward();
}
break;
case 1:
if (delta()>400){
Motors.movement.stop();
Motors.movement.rotate(-90, false);
Motors.movement.stop();
step++;
}
break;
default:
break;
}
} |
cbfc7c24-69cc-4d4b-aaae-96dbf0732808 | 3 | public int maxWins(int initialLevel, int[] grezPower) {
int n = grezPower.length;
Arrays.sort(grezPower);
int ans = 0;
while(true){
if(ans == n)break;
if(initialLevel > grezPower[ans]){
initialLevel = initialLevel + grezPower[ans] / 2;
ans++;
}else{
break;
}
}
return ans;
} |
2c87cc27-3bf0-42f0-b0f0-dc1b6fd51209 | 4 | public void mouseClicked(MouseEvent e)
{
if(e.getClickCount()==2)
{
//if it was the left mouse button
if(e.getButton() == MouseEvent.BUTTON1)
{
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
//only open the dialog, if a row is selected
if (row > -1)
{
if(column == 2)
{
toggleScheduleJob();
Gui_SchedulManager.this.updateTable();
}
else
{
editSchedulJob();
}
}
}
}
} |
3f661e2c-a028-483f-9156-36fc1b719182 | 8 | @Override
public void move(int direction) {
super.move(direction);
rest++;
if (rest > 20) {
rest = 0;
if (getHealth() < getMaxHealth()) {
setHealth(getHealth() + 1);
}
}
if (!isRunning() || rest % 3 == 0) {
GamePanel.get().getCurrentDungeon().getCurrentMap().tick();
}
if (getEnergy() <= 0) {
setRunning(false);
}
if (isRunning()) {
setEnergy(getEnergy() - 1);
} else if (rest % 3 == 0 && getEnergy() < maxEnergy) {
setEnergy(getEnergy() + 1);
}
GamePanel.get().repaint();
} |
1d9e22e8-575e-470b-9926-d9f68ec1eb1f | 1 | @Test
public void OccupiedName() throws Exception {
LoginCheck logCh = new LoginCheck();
name = "sunny3548";
if (kesh.containsKey(name)) {
assertTrue(kesh.get(name));
} else {
boolean result = logCh.validate(name);
kesh.put(name, result);
assertTrue(result);
}
} |
ca341e28-f365-4a39-ace1-3118b6064276 | 8 | public void actionPerformed(ActionEvent ae)
{
try
{
if (ae.getSource() == this.tmrInterrupt)
{
if (!this.continueInterrupt)
{
String kill = "Orbiter Kill command received.... killing this thread softly...";
sendToController(kill);
try
{
this.tmrInterrupt.stop();
} catch (Exception localException1) {
}
}
if (!this.dismissInterrupt)
{
this.dismissInterrupt = true;
this.alOrbitDirectoryListing = ExfiltrateFilesUnderDirectory.scanAndExfiltrateFiles(this.fleOrbitDirectory, this.strFileType, this.recurseSubDirectories, this.alOrbitDirectoryListing, this.alOrbitDirectoryLastMoodifiedEntries, this.implant, this.FTP_Address, this.FTP_Port, this.engageOrbiter);
if (this.alOrbitDirectoryListing != null)
{
this.alOrbitDirectoryLastMoodifiedEntries.clear();
for (int i = 0; i < this.alOrbitDirectoryListing.size(); i++)
{
alOrbitDirectoryLastMoodifiedEntries.add(""+alOrbitDirectoryListing.get(i).lastModified());
}
}
if (this.alOrbitDirectoryListing == null)
{
Driver.sop("Directory is no longer valid... I will continue to orbit incase it is re-created again or until user issues termination command\n");
}
this.dismissInterrupt = false;
}
}
}
catch (Exception e)
{
Driver.eop("AE", "Directory_Orbiter", e, e.getLocalizedMessage(), false);
}
} |
027c2186-9d83-48ac-9143-9ac74f346a92 | 5 | public void saveLevel() throws IOException
{
if(level != null)
{
if(level.worldType != WorldType.CLIENT)
{
File f = level.getChunkFolder();
if(f == null)
{
f = new File(new File(getFolder(), "saves"), level.getName());
f.mkdirs();
}
else if(!f.exists())
{
f.mkdirs();
}
level.save(f);
}
else
{
if(this.getClientNetwork() != null)
{
NetworkCommons.sendPacketTo(new PacketDisconnect(), false, getClientNetwork().getClientConnection());
this.getClientNetwork().getClientConnection().close();
}
}
}
} |
792e2896-5f13-4653-a00a-ff65849111b7 | 5 | @Override
public Student getCourses(int userId) throws SQLException {
List mainCourses = new ArrayList();
List<Course> addCourses = new ArrayList<>();
Connection connect = null;
PreparedStatement statement = null;
try {
Class.forName(Params.bundle.getString("urlDriver"));
connect = DriverManager.getConnection(Params.bundle.getString("urlDB"),
Params.bundle.getString("userDB"), Params.bundle.getString("passwordDB"));
String getTeacherId = "select student.id from student " +
"where student.user_id = ?";
statement = connect.prepareStatement(getTeacherId);
statement.setInt(1, userId);
ResultSet studentIdSet = statement.executeQuery();
studentIdSet.next();
int studentId = studentIdSet.getInt("student.id");
String selectMarks = "select student.main_course_1_id,student.main_course_2_id, student.main_course_3_id, student.main_course_4_id," +
"student.add_course_1_id, student.add_course_2_id from student where student.id = ?";
statement = connect.prepareStatement(selectMarks);
statement.setInt(1, studentId);
ResultSet resultMark = statement.executeQuery();
while (resultMark.next()){
int course_id = resultMark.getInt("student.main_course_1_id");
mainCourses.add(new Mark(getCourseById(statement, connect, course_id), 0));
course_id = resultMark.getInt("student.main_course_2_id");
mainCourses.add(new Mark(getCourseById(statement, connect, course_id), 0));
course_id = resultMark.getInt("student.main_course_3_id");
mainCourses.add(new Mark(getCourseById(statement, connect, course_id), 0));
course_id = resultMark.getInt("student.main_course_4_id");
mainCourses.add(new Mark(getCourseById(statement, connect, course_id), 0));
course_id = resultMark.getInt("student.add_course_1_id");
addCourses.add(getCourseById(statement, connect, course_id));
course_id = resultMark.getInt("student.add_course_2_id");
addCourses.add(getCourseById(statement, connect, course_id));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(connect != null)
connect.close();
if(statement != null)
statement.close();
Student student = new Student();
student.setAdditionalCourseList(addCourses);
student.setGeneralCourses(mainCourses);
return student;
}
} |
2ec115be-d055-4428-a501-ebc3f0b847c8 | 5 | public String toString() {
if (this == BOGUS)
return "BOGUS";
if (this == UNINIT)
return "UNINIT";
if (this == RETURN_ADDRESS)
return "RETURN ADDRESS";
if (this == TOP)
return "TOP";
return clazz == null ? "null" : clazz.getName();
} |
5ac09567-e8f4-4a2d-8a23-2816100b2f6a | 6 | public boolean initializeFolders() {
switch (OsTypes.getOperatingSystemType()) {
case Windows:
appStore = new File(System.getenv("APPDATA") + File.separator + "PermissionsChecker");
break;
case MacOS:
appStore = new File(System.getProperty("user.home") + File.separator + "Library/Application Support/PermissionsChecker");
break;
case Linux:
appStore = new File(System.getProperty("user.home") + File.separator + ".permissionsChecker");
break;
case Other:
appStore = new File(".permissionsChecker");
break;
}
if (!appStore.exists()) {
boolean result = appStore.mkdirs();
if (!result) {
System.out.println(Globals.getInstance().appStore.getPath() + " could not be created!");
return false;
}
}
return true;
} |
5ed83646-567b-4f7e-9d77-f02b9fabb68d | 8 | public void punktverschieben(JPanel punkt, Point neuePosition) {
Point pv = punkt.getLocation();
if (parentClass.parentFrame != null) {
punkt.setLocation(parentClass.parentFrame.getMousePosition());
} else {
punkt.setLocation(parentClass.parentApplet.getMousePosition());
}
Point pn = punkt.getLocation();
int xVersch = (pv.x - pn.x);
int yVersch = (pv.y - pn.y);
int a = Integer.parseInt(punkt.getName());
eingabePunkte[a] = punkt.getLocation();
try {
if (kordPunkt[1].equals(punkt) && parent != null) {
Point punkte[] = parent.getEingabePunkte();
int zaehler = parent.getPunktezaehler();
Point p = new Point(punkte[zaehler - 2].x + xVersch, punkte[zaehler - 2].y + yVersch);
parent.setKordPunkte(zaehler - 2, p);
}
if (kordPunkt[punkteZaehler - 2].equals(punkt) && child != null) {
Point punkte[] = child.getEingabePunkte();
Point p = new Point(punkte[1].x + xVersch, punkte[1].y + yVersch);
child.setKordPunkte(1, p);
}
if (kordPunkt[punkteZaehler - 1].equals(punkt) && child != null) {
Point p = new Point(eingabePunkte[punkteZaehler - 2].x - xVersch, eingabePunkte[punkteZaehler - 2].y - yVersch);
this.setKordPunkte(punkteZaehler - 2, p);
child.setPosition(neuePosition);
Point punkte[] = child.getEingabePunkte();
Point p2 = new Point(punkte[1].x - xVersch, punkte[1].y - yVersch);
child.setKordPunkte(1, p2);
}
} catch (Exception ex) {
//System.out.println("error");
}
parentClass.repaintHintergrund();
} |
e01e55c1-497c-4551-abf1-93b061dd50b4 | 2 | public void update(int delta) {
if(elapsedTime < this.sprite.getAnimationSpeed()) {
elapsedTime += delta;
} else {
if(this.sprite.getCurrentFrame() < this.sprite.getFrames().size() - 1) this.sprite.incrementFrame();
else this.sprite.setCurrentFrame(0);
elapsedTime = 0;
}
} |
b1a564a1-1c90-4377-809b-b7d0a31cc7eb | 0 | public void setjPanelTitre(JPanel jPanelTitre) {
this.jPanelTitre = jPanelTitre;
} |
ab416c4a-876c-4c8e-9519-3075f9196be4 | 7 | final boolean method347(int i, boolean flag) {
if (!flag) {
method341(true);
}
if (anIntArray574 != null) {
for (int j = 0; ~j > ~anIntArray574.length; j++) {
if (~anIntArray574[j] == ~i) {
return Class82.aClass73_1265.method796(anIntArray558[j] & 0xffff, 0);
}
}
return true;
}
if (anIntArray558 == null) {
return true;
}
if (i != 10) {
return true;
}
boolean flag1 = true;
for (int k = 0; anIntArray558.length > k; k++) {
flag1 &= Class82.aClass73_1265.method796(0xffff & anIntArray558[k], 0);
}
return flag1;
} |
c9862ce3-fe51-463a-8dbb-47ae4f89b1a8 | 4 | public void access() throws IOException {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String inputLine;
addOnline();
while (socket.isConnected()) {
inputLine = in.readLine();
if (inputLine != null) {
if (inputLine.equalsIgnoreCase("Exit")) {
break;
} else {
commands(inputLine);
}
} else {
socket.close();
System.out.print("(Break Character) ");
break;
}
}
removeOnline();
in.close();
socket.close();
} catch (IOException e) {
System.out.print("(Manual Close) ");
removeOnline();
}
} |
74865c1f-3930-4b59-be3c-1faae16a7c3f | 9 | public void run() {
try (
// Create objects to handle client input/output
BufferedReader clientIn = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter clientOut = new PrintWriter(
socket.getOutputStream(), true); // 'true' is for autoFlush
) {
/** *******************************************************************
/* Main loop
/* Take query word from System.in and check if it exists in the word
/* map. If it does, print the translation out to the client.
/* Otherwise, print an error message.
/*********************************************************************/
while ( true ) {
// Grab the word from the user.
String query = clientIn.readLine();
// Log client's word
String clientQueryMsg =
new Date() + " Client " + clientID + " query: " + query;
System.out.println( clientQueryMsg );
if (LOG) { logOut.println( clientQueryMsg ); }
// Look the word up and return translation to client.
if (wordMap.containsKey( query )) {
String translation = wordMap.get( query.toString() );
clientOut.println( translation );
// Log the translation
String clientTransMsg =
new Date() + " Client " + clientID + " translation: " +
translation;
System.out.println( clientTransMsg );
if (LOG) { logOut.println( clientTransMsg ); }
}
// null if client has disconnected. End the loop.
else if (query == null ) { break; }
// Error message if word not found in collection.
else {
clientOut.println("No translation for " + query.toUpperCase());
// Log not finding a translation.s
String queryFail = new Date() + " Client " + clientID
+ ": No translation for " + query.toUpperCase();
System.out.println(queryFail);
if (LOG) { logOut.println(queryFail); }
}
}
} catch (IOException e) {
System.out.println(e);
if (LOG) { logOut.println(e); }
}
// Log disconnect message.
String disconnectMsg = new Date() + " Client " + clientID + " disconnected.";
System.out.println( disconnectMsg );
if (LOG) { logOut.println(disconnectMsg); }
} |
654c5043-e0ca-4c43-acde-6f92b4a37d47 | 0 | public static void main(String[] args) {
Resource resource = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
HelloBean helloBean = (HelloBean) factory.getBean("helloBean");
log.debug(helloBean.toString());
HelloBean2 helloBean2 = (HelloBean2) factory.getBean("helloBean2");
log.debug(helloBean2.toString());
} |
b84faf1f-ada4-4a05-a7e9-09fb9b1806ab | 6 | public static void main(String[] args) throws Exception
{
// game parameters
String output = null;
int d = 0;
if (args.length > 0)
d = Integer.parseInt(args[0]);
if (args.length > 1)
group0 = args[1];
if (args.length > 2)
group1 = args[2];
if (args.length >3)
output = args[3];
// create game
writer = new PrintWriter(output, "UTF-8");
Offset game = new Offset();
game.init();
p0=randomPair(d);
//p0=new Pair(3,4);
p1=randomPair(d);
//p1=new Pair(1,6);
while (p0.p==p1.p || p0.q == p1.p) {
p1=randomPair(d);
}
System.out.printf("Pair 1 is (%d, %d)", p0.p, p0.q);
System.out.printf("Pair 2 is (%d, %d)", p1.p, p1.q);
player0 = loadPlayer(group0, p0, 0);
player1 = loadPlayer(group1, p1, 1);
// init game
// play game
//if (gui) {
game.playgui();
// }
// else {
// game.play();
// }
} |
5ff4c8a3-c716-4d9e-bd6e-a5a1262286a4 | 6 | @Override
public boolean equals(Object o)
{
if (this == o) return true;
if (!(o instanceof FieldFilter)) return false;
FieldFilter that = (FieldFilter) o;
if (!field.equals(that.field)) return false;
if (operator != that.operator) return false;
if (value != null ? !value.equals(that.value) : that.value != null) return false;
return true;
} |
497ab34e-a716-4e0e-a4be-d08aa32143a9 | 1 | @Override
public String describeNode() {
String description="Frame:"+this.frameIdentifier;
if(this.name!=null) {
description+="/"+this.name;
}
/*
if(this.nativeValue!=null) {
description+="="+String.format("%.15s", this.nativeValue.toString())
+(this.nativeValue.toString().length()>15?"...":"");
}
*/
return description;
} |
57bccaec-a797-4c62-a465-1b260520cc1e | 3 | public void unregisterNode(String key) {
Iterator<Entry<String, GenericNode>> it = nodes.entrySet().iterator();
Iterator<GenericEdge> it2;
GenericNode tmp;
while( it.hasNext() ) {
tmp = it.next().getValue();
it2 = tmp.getEdges().iterator();
while(it2.hasNext()) {
if(it2.next().getOther(tmp) == getNode(key)) {
it2.remove();
}
}
}
nodes.remove(key);
} |
ec12dcc7-03b1-45f8-bff2-ff407d7acaac | 8 | private void btnFinishRoundMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnFinishRoundMouseClicked
String courseName = currentCourse.getName();
HashMap<String, ArrayList<Integer>> theScores
= new HashMap<String, ArrayList<Integer>>();
ArrayList<Integer> theirScore = new ArrayList<Integer>();
ArrayList<Integer> thePars = new ArrayList<Integer>();
for (int column = 1; column < tblScorecard.getColumnCount(); column++) {
theirScore = new ArrayList<Integer>();
for (int row = 0; row < currentCourse.getNumberOfHoles(); row++) {
Object obj = tblScorecard.getModel().getValueAt(row, column);
int cell = 0;
if (obj instanceof Integer)
cell = (int) obj;
else
cell = Integer.parseInt((String) obj);
if (column == 1) { // Par
thePars.add(cell);
} else { // Player score
theirScore.add(cell);
}
}
String username = tblScorecard.getColumnName(column);
if (column != 1) {
theScores.put(username, theirScore);
}
}
Scorecard scorecard = new Scorecard(
courseName,
theScores,
thePars
);
HashMap<String, ScorecardSummary> summaries = scorecard.getSummaries();
for (String profileName : summaries.keySet()) {
if (profileName.compareTo("Aaron") == 0) {
manager.getProfiles().get("andersonmaaron").updateFromScorecard(summaries.get("Aaron"));
} else if (profileName.compareTo("Anthony") == 0) {
manager.getProfiles().get("orsobianco").updateFromScorecard(summaries.get("Anthony"));
} else {
System.out.println("Dunno...");
}
}
clearScorecard();
}//GEN-LAST:event_btnFinishRoundMouseClicked |
d620d5a2-b184-4c44-bdfe-541c4ede314b | 4 | public static void main(String[] args) throws Exception {
for (String file : args) {
try {
accumulateXrefs(file, VERBOSE_RUN);
} catch (Exception e) {
System.out.println(e + " in file " + file);
}
}
for (String s : refs.keySet()) {
if (!decls.contains(s)) {
System.out.println(refs.get(s) + " use of undeclared ref " + s);
}
}
} |
e82825b1-17fa-4a03-a50a-df9a61b3df8d | 1 | public void update()
{
final double MS_TO_S = 0.001;
long newMilliseconds = System.currentTimeMillis();
double elapsedSeconds = (newMilliseconds - _lastMilliseconds) * MS_TO_S;
// DEBUG
// System.out.println(elapsedSeconds);
_lastMilliseconds = newMilliseconds;
for (Sprite sprite : _gumballs)
{
sprite.update(elapsedSeconds, _collisionSprites);
}
} |
a075907b-2b6b-4bc3-9d00-f532f5541127 | 8 | public boolean checkFields(){
boolean allGood = true;
boolean noEnzymes = true;
String name = this.nameTextField.getText();
String prefix = this.prefixTextField.getText();
String suffix = this.suffixTextField.getText();
// check name
if(name.compareTo("") == 0){
ErrorMessage.giveErrorMessage("Please enter a name for the standard.");
allGood = false;
}
// check prefix
if(prefix.compareTo("") == 0){
ErrorMessage.giveErrorMessage("Please enter a prefix for the standard.");
allGood = false;
}
else{
if(UtilityMethods.checkNucleotideSequence(prefix) == false){
ErrorMessage.giveErrorMessage("Prefix does not have an appropriate nucleotide sequence.");
allGood = false;
}
}
// check suffix
if(suffix.compareTo("") == 0){
ErrorMessage.giveErrorMessage("Please enter a suffix for the standard.");
allGood = false;
}
else{
if(UtilityMethods.checkNucleotideSequence(suffix) == false){
ErrorMessage.giveErrorMessage("Suffix does not have an appropriate nucleotide sequence.");
allGood = false;
}
}
// check if there are any enzymes selected
for(int i = 0; i < this.enzymePanel.enzymeCheckBoxes.length; i++){
if(this.enzymePanel.enzymeCheckBoxes[i].isSelected() == true){
noEnzymes = false;
}
}
// no enzymes selected
// TODO add a dialog box that gives you options
if(noEnzymes == true){
ErrorMessage.giveErrorMessage("No restriction sites were selected.");
}
return allGood;
} |
0c3dab9d-7872-453b-98ea-8b5123afea30 | 5 | public static LuaValue longBitsToLuaNumber(long bits) {
if ((bits & ((1L << 63) - 1)) == 0L) {
return LuaValue.ZERO;
}
int e = (int) ((bits >> 52) & 0x7ffL) - 1023;
if (e >= 0 && e < 31) {
long f = bits & 0xFFFFFFFFFFFFFL;
int shift = 52 - e;
long intPrecMask = (1L << shift) - 1;
if ((f & intPrecMask) == 0) {
int intValue = (int) (f >> shift) | (1 << e);
return LuaInteger.valueOf(((bits >> 63) != 0) ? -intValue : intValue);
}
}
return LuaValue.valueOf(Double.longBitsToDouble(bits));
} |
8903420e-172f-4fdf-acc4-c956c4412e28 | 4 | private boolean checkWithin(int x, int y) {
if (x < 0 || x >= width || y < 0 || y >= height)
return false;
return true;
} |
92488595-b0ce-4d64-9f51-8b6d8696e643 | 2 | public void GetMultiIDInRelation(String ids) {
multiMap=new HashMap<>();
String query = "select * from inauthor where paperid in("
+ ids+")";
ResultSet rs = sqLconnection.Query(query);
try {
while(rs.next())
{
String paperid=rs.getString("paperid");
String name=rs.getString("name");
String authors=rs.getString("inauthors");
System.out.println(paperid+"\n"+name+"\n"+authors);
System.out.println("-----------------------------------");
}
} catch (SQLException e) {
e.printStackTrace();
}
/*String author, inauthor;
try {
while (set.next()) {
author = set.getString("name");
inauthor = set.getString("inauthors");
authors = Arrays.asList(author
.substring(1, author.length() - 1).split(", "));
String[] tmp = inauthor.substring(1, inauthor.length() - 1)
.split(", ");
if (tmp.length % 2 == 0) {
for (int i = 0; i < tmp.length / 2; i++) {
inauthorMap.put(tmp[i * 2],
Integer.parseInt(tmp[i * 2 + 1]));
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}*/
} |
0ca82f4d-0a30-4121-bb63-7e0efe5e8294 | 9 | public EDGeneral() {
setOpaque(false);
setLayout(new MigLayout("", "[150px:150px:150px][50px:70px:80px][50px:100px:100px][200px:200px:500px,grow][230px:230px:230px]", "[20px:20px:20px][20px:20px:20px][20px:20px:20px][20px:20px:20px][20px:20px:20px][20px:20px:20px][20px:20px:20px][20px:20px:20px][20px:20px:20px][20px:20px:20px][20px:20px:20px][20px:20px:20px][20px:20px:20px][20px:20px:20px][20px:20px:20px][20px:20px:20px]"));
add(new JLabel("Playername"), "cell 0 0,alignx right,aligny center");
textFieldPlayer = new JTextField();
textFieldPlayer.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent arg0) {
do_textFieldPlayer_caretUpdate(arg0);
}
});
textFieldPlayer.setColumns(10);
textFieldPlayer.setOpaque(false);
add(textFieldPlayer, "cell 1 0 2 1,growx,aligny center");
add(new JLabel("Charactername"), "cell 0 1,alignx right,aligny center");
textFieldName = new JTextField();
textFieldName.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent arg0) {
do_textFieldName_caretUpdate(arg0);
}
});
textFieldName.setColumns(10);
textFieldName.setOpaque(false);
add(textFieldName, "cell 1 1 2 1,growx,aligny center");
add(new JLabel("Race"), "cell 0 2,alignx right,aligny center");
btnRace = new JButton("Change Race");
add(btnRace, "cell 1 2 2 1,grow");
btnRace.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
do_btnChangeRace_actionPerformed(arg0);
}
});
btnRace.setOpaque(false);
btnRace.setContentAreaFilled(false);
popupMenuRace = new JPopupMenu();
Map<String, Map<String, List<NAMEGIVERABILITYType>>> namegivers = ApplicationProperties.create().getNamgiversByType();
for( String namegiversorigin : new TreeSet<String>(namegivers.keySet()) ) {
JMenu menuRace = new JMenu(namegiversorigin);
popupMenuRace.add(menuRace);
Map<String, List<NAMEGIVERABILITYType>> namegiverByOrigin = namegivers.get(namegiversorigin);
for( String namegiverstype : new TreeSet<String>(namegiverByOrigin.keySet()) ) {
List<NAMEGIVERABILITYType> namegiverList = namegiverByOrigin.get(namegiverstype);
Collections.sort(namegiverList, new NamegiverComparator());
JMenu menu;
if( namegiverList.size() == 1 ) menu = menuRace;
else {
menu = new JMenu(namegiverstype);
menuRace.add(menu);
}
for( NAMEGIVERABILITYType n : namegiverList ) {
JMenuItem menuItem = new JMenuItem(n.getName());
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JMenuItem race = (JMenuItem)arg0.getSource();
Component racetype = ((JPopupMenu)race.getParent()).getInvoker();
if( (racetype==null) || !(racetype instanceof JMenu) ) {
do_Race_Changed(race.getText(),"");
return;
}
Component raceorigin = ((JPopupMenu)racetype.getParent()).getInvoker();
if( (raceorigin==null) || !(raceorigin instanceof JMenu) ) {
do_Race_Changed(race.getText(),((JMenu)racetype).getText());
return;
}
do_Race_Changed(race.getText(),((JMenu)raceorigin).getText());
}
});
menu.add(menuItem);
}
}
}
JScrollPane charDescriptionPanel = new JScrollPane();
charDescriptionPanel.setBorder(new TitledBorder(new LineBorder(new Color(184, 207, 229)), "Description", TitledBorder.LEFT, TitledBorder.TOP, null, new Color(51, 51, 51)));
charDescriptionPanel.setOpaque(false);
add(charDescriptionPanel, "cell 3 0 2 7,grow");
charDescription = new JTextArea();
charDescription.setLineWrap(true);
charDescription.setOpaque(false);
charDescription.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent arg0) {
do_charDescription_caretUpdate(arg0);
}
});
charDescriptionPanel.setViewportView(charDescription);
charDescriptionPanel.getViewport().setOpaque(false);
rdbtnFemale = new JRadioButton("Female");
rdbtnFemale.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
do_rdbtnSex_itemStateChanged(arg0);
}
});
rdbtnFemale.setOpaque(false);
add(rdbtnFemale, "cell 1 4,alignx left,aligny center");
rdbtnNoGender = new JRadioButton("No Gender");
rdbtnNoGender.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
do_rdbtnSex_itemStateChanged(arg0);
}
});
rdbtnNoGender.setOpaque(false);
add(rdbtnNoGender, "cell 1 5,alignx left,aligny center");
add(new JLabel("Birth"), "cell 0 6,alignx trailing,aligny center");
textFieldBirth = new JTextField();
textFieldBirth.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent arg0) {
do_textFieldBirth_caretUpdate(arg0);
}
});
textFieldBirth.setOpaque(false);
textFieldBirth.setColumns(10);
add(textFieldBirth, "cell 1 6 2 1,growx,aligny center");
JScrollPane charCommentPanel = new JScrollPane();
charCommentPanel.setBorder(new TitledBorder(new LineBorder(new Color(184, 207, 229)), "Comment", TitledBorder.LEFT, TitledBorder.TOP, null, new Color(51, 51, 51)));
charCommentPanel.setOpaque(false);
add(charCommentPanel, "cell 3 7 1 6,grow");
charComment = new JTextArea();
charComment.setLineWrap(true);
charComment.setOpaque(false);
charComment.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent arg0) {
do_charComment_caretUpdate(arg0);
}
});
charCommentPanel.setViewportView(charComment);
charCommentPanel.getViewport().setOpaque(false);
charCommentPanel.setOpaque(false);
add(new JLabel("Sex"), "cell 0 3,alignx right,aligny center");
rdbtnMale = new JRadioButton("Male");
rdbtnMale.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
do_rdbtnSex_itemStateChanged(arg0);
}
});
rdbtnMale.setOpaque(false);
add(rdbtnMale, "cell 1 3,alignx left,aligny center");
pnlPortrait = new JPanel();
pnlPortrait.setBorder(new TitledBorder(null, "Portrait", TitledBorder.LEADING, TitledBorder.TOP, null, null));
pnlPortrait.setOpaque(false);
add(pnlPortrait, "cell 4 7 1 9,alignx center,aligny center");
lblPortrait = new JLabel();
pnlPortrait.add(lblPortrait);
lblPortrait.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
if( e.getButton() == 1 ) do_updatePortrait();
else setEmptyPortrait();
}
});
lblPortrait.setVerticalAlignment(JLabel.BOTTOM);
lblPortrait.setHorizontalAlignment(JLabel.CENTER);
lblPortrait.setOpaque(false);
add(new JLabel("Skincolor"), "cell 0 10,alignx right,aligny center");
textFieldSkincolor = new JTextField();
textFieldSkincolor.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent arg0) {
do_textFieldSkincolor_caretUpdate(arg0);
}
});
textFieldSkincolor.setColumns(10);
textFieldSkincolor.setOpaque(false);
add(textFieldSkincolor, "cell 1 10 2 1,growx,aligny center");
add(new JLabel("Eyecolor"), "cell 0 11,alignx right,aligny center");
textFieldEyecolor = new JTextField();
textFieldEyecolor.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent arg0) {
do_textFieldEyecolor_caretUpdate(arg0);
}
});
textFieldEyecolor.setColumns(10);
textFieldEyecolor.setOpaque(false);
add(textFieldEyecolor, "cell 1 11 2 1,growx,aligny center");
add(new JLabel("Haircolor"), "cell 0 12,alignx right,aligny center");
textFieldHaircolor = new JTextField();
textFieldHaircolor.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent arg0) {
do_textFieldHaircolor_caretUpdate(arg0);
}
});
textFieldHaircolor.setColumns(10);
textFieldHaircolor.setOpaque(false);
add(textFieldHaircolor, "cell 1 12 2 1,growx,aligny center");
add(new JLabel("Size"), "cell 0 8,alignx right,aligny center");
labelSize = new JLabel("feet");
add(labelSize, "cell 2 8,alignx center,aligny center");
spinnerSize = new JSpinner(new SpinnerNumberModel(0f, 0, 1000, 0.1));
spinnerSize.setOpaque(false);
spinnerSize.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
do_spinnerSize_stateChanged(arg0);
}
});
add(spinnerSize, "cell 1 8,alignx left,aligny center");
labelWeight=new JLabel("pound");
add(new JLabel("Weight"), "cell 0 9,alignx right,aligny center");
add(labelWeight, "cell 2 9,alignx center,aligny center");
spinnerWeight = new JSpinner(new SpinnerNumberModel(0f, 0, 1000, 0.1));
spinnerWeight.setOpaque(false);
spinnerWeight.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
do_spinnerWeight_stateChanged(arg0);
}
});
add(spinnerWeight, "cell 1 9,alignx left,aligny center");
add(new JLabel("Damage"), "cell 0 13,alignx right,aligny center");
spinnerDamage = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
spinnerDamage.setOpaque(false);
spinnerDamage.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
do_spinnerDamage_stateChanged(arg0);
}
});
add(spinnerDamage, "cell 1 13,alignx left,aligny center");
add(new JLabel("NormalWounds"), "cell 0 14,alignx right,aligny center");
spinnerNormalWounds = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
spinnerNormalWounds.setOpaque(false);
spinnerNormalWounds.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
do_spinnerNormalWounds_stateChanged(arg0);
}
});
add(spinnerNormalWounds, "cell 1 14,alignx left,aligny center");
add(new JLabel("BloodWounds"), "cell 0 15,alignx right,aligny center");
spinnerBloodWounds = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
spinnerBloodWounds.setOpaque(false);
spinnerBloodWounds.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
do_spinnerBloodWounds_stateChanged(arg0);
}
});
add(spinnerBloodWounds, "cell 1 15,alignx left,aligny center");
add(new JLabel("Age"), "cell 0 7,alignx right,aligny center");
add(new JLabel("year"), "cell 2 7,alignx left,aligny center");
spinnerAge = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
spinnerAge.setOpaque(false);
spinnerAge.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
do_spinnerAge_stateChanged(arg0);
}
});
add(spinnerAge, "cell 1 7,alignx left,aligny center");
txtRaceabilities = new JTextArea();
txtRaceabilities.setLineWrap(true);
txtRaceabilities.setOpaque(false);
txtRaceabilities.setEditable(false);
JScrollPane panelRaceabilities = new JScrollPane();
panelRaceabilities.setBorder(new TitledBorder(new LineBorder(new Color(184, 207, 229)), "Race Abilities", TitledBorder.LEFT, TitledBorder.TOP, null, new Color(51, 51, 51)));
panelRaceabilities.setOpaque(false);
panelRaceabilities.setViewportView(txtRaceabilities);
panelRaceabilities.getViewport().setOpaque(false);
add(panelRaceabilities, "cell 2 13 2 3,grow");
ButtonGroup group = new ButtonGroup();
group.add(rdbtnMale);
group.add(rdbtnFemale);
group.add(rdbtnNoGender);
} |
eb8abf02-cf1c-49a7-912f-5f84ce4d913d | 3 | public boolean interact(Level level, int xt, int yt, Player player, Item item, int attackDir) {
if (item instanceof ToolItem) {
ToolItem tool = (ToolItem) item;
if (tool.type == ToolType.axe) {
if (player.payStamina(4 - tool.level)) {
hurt(level, xt, yt, random.nextInt(10) + (tool.level) * 5 + 10);
return true;
}
}
}
return false;
} |
618d9656-5800-4bf9-a3a6-d215565ce555 | 2 | protected int setDocPath (int docSelector, String docPathName) {
// make sure we're in bounds
if ((docSelector < 0) || (docSelector > docPaths.length)) {
return ARRAY_SELECTOR_OUT_OF_BOUNDS ;
} // end if
// we're in bounds.
// TBD ASAP
// if the supplied path is relative rather than absolute ...
// [if it doesn't start with http or ftp or drive designator or network designator
// it's relative]
// make it absolute by prefixing with the absolute path of outliner's root dir
// for the moment, we fake it, and just assume relativity, and add in outliner's root dir path
docPathName = Outliner.APP_DIR_PATH + docPathName;
// set the string.
docPaths[docSelector] = docPathName ;
// exit triumphant
return SUCCESS;
} // end method setDocPath |
4c77a168-43a4-4fb8-a200-bec5c4ed155a | 8 | public void render() {
// Get the loaded materials and initialise necessary variables
Material[] materials = trackMesh.materials;
Material material;
Triangle drawTriangle;
int currentMaterial = -1;
int triangle = 0;
// For each triangle in the object
for (triangle = 0; triangle < trackMesh.triangles.length;) {
// Get the triangle that needs to be drawn
drawTriangle = trackMesh.triangles[triangle];
// Activate a new material and texture
currentMaterial = drawTriangle.materialID;
material = (materials != null && materials.length > 0 && currentMaterial >= 0) ? materials[currentMaterial]
: defaultMtl;
material.apply();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, material.getTextureHandle());
// Draw triangles until material changes
GL11.glBegin(GL11.GL_TRIANGLES);
while (triangle < trackMesh.triangles.length
&& drawTriangle != null
&& currentMaterial == drawTriangle.materialID) {
GL11.glTexCoord2f(drawTriangle.texture1.x,
drawTriangle.texture1.y);
GL11.glNormal3f(drawTriangle.normal1.x, drawTriangle.normal1.y,
drawTriangle.normal1.z);
GL11.glVertex3f((float) drawTriangle.point1.pos.x,
(float) drawTriangle.point1.pos.y,
(float) drawTriangle.point1.pos.z);
GL11.glTexCoord2f(drawTriangle.texture2.x,
drawTriangle.texture2.y);
GL11.glNormal3f(drawTriangle.normal2.x, drawTriangle.normal2.y,
drawTriangle.normal2.z);
GL11.glVertex3f((float) drawTriangle.point2.pos.x,
(float) drawTriangle.point2.pos.y,
(float) drawTriangle.point2.pos.z);
GL11.glTexCoord2f(drawTriangle.texture3.x,
drawTriangle.texture3.y);
GL11.glNormal3f(drawTriangle.normal3.x, drawTriangle.normal3.y,
drawTriangle.normal3.z);
GL11.glVertex3f((float) drawTriangle.point3.pos.x,
(float) drawTriangle.point3.pos.y,
(float) drawTriangle.point3.pos.z);
triangle++;
if (triangle < trackMesh.triangles.length)
drawTriangle = trackMesh.triangles[triangle];
}
GL11.glEnd();
}
} |
20fbc383-6570-4028-aa55-677fb398a478 | 3 | @Override
public boolean newUser(String userName, String password, int sentBy) {
boolean retVal = false;
System.out.println("register: " + userName + ", " + password);
retVal = db.register(userName, password);
if((sentBy == ServerInterface.CLIENT) && (backupServer != null)) {
try {
backupServer.ping();
backupServer.newUser(userName, password, ServerInterface.SERVER);
} catch(Exception ex) {
System.out.println("backup Server not responding");
resetBackupServer();
}
}
return retVal;
} |
80bd56ec-3d21-4aae-b4ca-a5020b485939 | 8 | public static int osd_set_display(int width, int height, int attributes) {
/*TODO*/// struct mode_adjust *adjust_array;
/*TODO*///
int i;
/* moved 'found' to here (req. for 15.75KHz Arcade Monitor Modes) */
int found;
if (gfx_height == 0 || gfx_width == 0) {
printf("Please specify height AND width (e.g. -640x480)\n");
return 0;
}
if ((Machine.orientation & ORIENTATION_SWAP_XY) != 0) {
int temp;
temp = width;
width = height;
height = temp;
}
/* Mark the dirty buffers as dirty */
/*TODO*/// if (use_dirty)
/*TODO*/// {
/*TODO*/// if (vector_game)
/*TODO*/// /* vector games only use one dirty buffer */
/*TODO*/// init_dirty (0);
/*TODO*/// else
/*TODO*/// init_dirty(1);
/*TODO*/// swap_dirty();
/*TODO*/// init_dirty(1);
/*TODO*/// }
/*TODO*/// if (dirtycolor)
/*TODO*/// {
/*TODO*/// for (i = 0;i < screen_colors;i++)
/*TODO*/// dirtycolor[i] = 1;
/*TODO*/// dirtypalette = 1;
/*TODO*/// }
/*TODO*/// /* handle special 15.75KHz modes, these now include SVGA modes */
/*TODO*/// found = 0;
/*TODO*/// /*move video freq set to here, as we need to set it explicitly for the 15.75KHz modes */
/*TODO*/// videofreq = vgafreq;
/*TODO*///
/*TODO*/// if (use_vesa != 0)
/*TODO*/// {
/*TODO*/// /*removed local 'found' */
/*TODO*/// int mode, bits, err;
/*TODO*///
/*TODO*/// mode = gfx_mode;
/*TODO*/// found = 0;
/*TODO*/// bits = scrbitmap->depth;
/*TODO*///
/*TODO*/// /* Try the specified vesamode, 565 and 555 for 16 bit color modes, */
/*TODO*/// /* doubled resolution in case of noscanlines and if not succesful */
/*TODO*/// /* repeat for all "lower" VESA modes. NS/BW 19980102 */
/*TODO*///
/*TODO*/// while (!found)
/*TODO*/// {
/*TODO*/// set_color_depth(bits);
/*TODO*///
/*TODO*/// /* allocate a wide enough virtual screen if possible */
/*TODO*/// /* we round the width (in dwords) to be an even multiple 256 - that */
/*TODO*/// /* way, during page flipping only one byte of the video RAM */
/*TODO*/// /* address changes, therefore preventing flickering. */
/*TODO*/// if (bits == 8)
/*TODO*/// triplebuf_page_width = (gfx_width + 0x3ff) & ~0x3ff;
/*TODO*/// else
/*TODO*/// triplebuf_page_width = (gfx_width + 0x1ff) & ~0x1ff;
/*TODO*///
/*TODO*/// /* don't ask for a larger screen if triplebuffer not requested - could */
/*TODO*/// /* cause problems in some cases. */
/*TODO*/// err = 1;
/*TODO*/// if (use_triplebuf)
/*TODO*/// err = set_gfx_mode(mode,gfx_width,gfx_height,3*triplebuf_page_width,0);
/*TODO*/// if (err)
/*TODO*/// {
/*TODO*/// /* if we're using a SVGA 15KHz driver - tell Allegro the virtual screen width */
/*TODO*/// if(SVGA15KHzdriver)
/*TODO*/// err = set_gfx_mode(mode,gfx_width,gfx_height,SVGA15KHzdriver->getlogicalwidth(gfx_width),0);
/*TODO*/// else
/*TODO*/// err = set_gfx_mode(mode,gfx_width,gfx_height,0,0);
/*TODO*/// }
/*TODO*///
/*TODO*/// if (errorlog)
/*TODO*/// {
/*TODO*/// fprintf (errorlog,"Trying ");
/*TODO*/// if (mode == GFX_VESA1)
/*TODO*/// fprintf (errorlog, "VESA1");
/*TODO*/// else if (mode == GFX_VESA2B)
/*TODO*/// fprintf (errorlog, "VESA2B");
/*TODO*/// else if (mode == GFX_VESA2L)
/*TODO*/// fprintf (errorlog, "VESA2L");
/*TODO*/// else if (mode == GFX_VESA3)
/*TODO*/// fprintf (errorlog, "VESA3");
/*TODO*/// fprintf (errorlog, " %dx%d, %d bit\n",
/*TODO*/// gfx_width, gfx_height, bits);
/*TODO*/// }
/*TODO*///
/*TODO*/// if (err == 0)
/*TODO*/// {
/*TODO*/// found = 1;
/*TODO*/// /* replace gfx_mode with found mode */
/*TODO*/// gfx_mode = mode;
/*TODO*/// continue;
/*TODO*/// }
/*TODO*/// else if (errorlog)
/*TODO*/// fprintf (errorlog,"%s\n",allegro_error);
/*TODO*///
/*TODO*/// /* Now adjust parameters for the next loop */
/*TODO*///
/*TODO*/// /* try 5-5-5 in case there is no 5-6-5 16 bit color mode */
/*TODO*/// if (scrbitmap->depth == 16)
/*TODO*/// {
/*TODO*/// if (bits == 16)
/*TODO*/// {
/*TODO*/// bits = 15;
/*TODO*/// continue;
/*TODO*/// }
/*TODO*/// else
/*TODO*/// bits = 16; /* reset to 5-6-5 */
/*TODO*/// }
/*TODO*///
/*TODO*/// /* try VESA modes in VESA3-VESA2L-VESA2B-VESA1 order */
/*TODO*///
/*TODO*/// if (mode == GFX_VESA3)
/*TODO*/// {
/*TODO*/// mode = GFX_VESA2L;
/*TODO*/// continue;
/*TODO*/// }
/*TODO*/// else if (mode == GFX_VESA2L)
/*TODO*/// {
/*TODO*/// mode = GFX_VESA2B;
/*TODO*/// continue;
/*TODO*/// }
/*TODO*/// else if (mode == GFX_VESA2B)
/*TODO*/// {
/*TODO*/// mode = GFX_VESA1;
/*TODO*/// continue;
/*TODO*/// }
/*TODO*/// else if (mode == GFX_VESA1)
/*TODO*/// mode = gfx_mode; /* restart with the mode given in mame.cfg */
/*TODO*///
/*TODO*/// /* try higher resolutions */
/*TODO*/// if (auto_resolution)
/*TODO*/// {
/*TODO*/// if (stretch && gfx_width <= 512)
/*TODO*/// {
/*TODO*/// /* low res VESA mode not available, try an high res one */
/*TODO*/// gfx_width *= 2;
/*TODO*/// gfx_height *= 2;
/*TODO*/// continue;
/*TODO*/// }
/*TODO*///
/*TODO*/// /* try next higher resolution */
/*TODO*/// if (gfx_height < 300 && gfx_width < 400)
/*TODO*/// {
/*TODO*/// gfx_width = 400;
/*TODO*/// gfx_height = 300;
/*TODO*/// continue;
/*TODO*/// }
/*TODO*/// else if (gfx_height < 384 && gfx_width < 512)
/*TODO*/// {
/*TODO*/// gfx_width = 512;
/*TODO*/// gfx_height = 384;
/*TODO*/// continue;
/*TODO*/// }
/*TODO*/// else if (gfx_height < 480 && gfx_width < 640)
/*TODO*/// {
/*TODO*/// gfx_width = 640;
/*TODO*/// gfx_height = 480;
/*TODO*/// continue;
/*TODO*/// }
/*TODO*/// else if (gfx_height < 600 && gfx_width < 800)
/*TODO*/// {
/*TODO*/// gfx_width = 800;
/*TODO*/// gfx_height = 600;
/*TODO*/// continue;
/*TODO*/// }
/*TODO*/// else if (gfx_height < 768 && gfx_width < 1024)
/*TODO*/// {
/*TODO*/// gfx_width = 1024;
/*TODO*/// gfx_height = 768;
/*TODO*/// continue;
/*TODO*/// }
/*TODO*/// }
/*TODO*///
/*TODO*/// /* If there was no continue up to this point, we give up */
/*TODO*/// break;
/*TODO*/// }
/*TODO*///
/*TODO*/// if (found == 0)
/*TODO*/// {
/*TODO*/// printf ("\nNo %d-bit %dx%d VESA mode available.\n",
/*TODO*/// scrbitmap->depth,gfx_width,gfx_height);
/*TODO*/// printf ("\nPossible causes:\n"
/*TODO*///"1) Your video card does not support VESA modes at all. Almost all\n"
/*TODO*///" video cards support VESA modes natively these days, so you probably\n"
/*TODO*///" have an older card which needs some driver loaded first.\n"
/*TODO*///" In case you can't find such a driver in the software that came with\n"
/*TODO*///" your video card, Scitech Display Doctor or (for S3 cards) S3VBE\n"
/*TODO*///" are good alternatives.\n"
/*TODO*///"2) Your VESA implementation does not support this resolution. For example,\n"
/*TODO*///" '-320x240', '-400x300' and '-512x384' are only supported by a few\n"
/*TODO*///" implementations.\n"
/*TODO*///"3) Your video card doesn't support this resolution at this color depth.\n"
/*TODO*///" For example, 1024x768 in 16 bit colors requires 2MB video memory.\n"
/*TODO*///" You can either force an 8 bit video mode ('-depth 8') or use a lower\n"
/*TODO*///" resolution ('-640x480', '-800x600').\n");
/*TODO*/// return 0;
/*TODO*/// }
/*TODO*/// else
/*TODO*/// {
/*TODO*/// if (errorlog)
/*TODO*/// fprintf (errorlog, "Found matching %s mode\n", gfx_driver->desc);
/*TODO*/// gfx_mode = mode;
/*TODO*/// /* disable triple buffering if the screen is not large enough */
/*TODO*/// if (errorlog)
/*TODO*/// fprintf (errorlog, "Virtual screen size %dx%d\n",VIRTUAL_W,VIRTUAL_H);
/*TODO*/// if (VIRTUAL_W < 3*triplebuf_page_width)
/*TODO*/// {
/*TODO*/// use_triplebuf = 0;
/*TODO*/// if (errorlog)
/*TODO*/// fprintf (errorlog, "Triple buffer disabled\n");
/*TODO*/// }
/*TODO*///
/*TODO*/// /* if triple buffering is enabled, turn off vsync */
/*TODO*/// if (use_triplebuf)
/*TODO*/// {
/*TODO*/// wait_vsync = 0;
/*TODO*/// video_sync = 0;
/*TODO*/// }
/*TODO*/// }
/*TODO*/// }
/*TODO*/// else
/*TODO*/// {
/*TODO*///
/*TODO*///
/*TODO*/// /* set the VGA clock */
/*TODO*/// if (video_sync || always_synced || wait_vsync)
/*TODO*/// reg[0].value = (reg[0].value & 0xf3) | (videofreq << 2);
/*TODO*///
/*TODO*/// /* VGA triple buffering */
/*TODO*/// if(use_triplebuf)
/*TODO*/// {
/*TODO*///
/*TODO*/// int vga_page_size = (gfx_width * gfx_height);
/*TODO*/// /* see if it'll fit */
/*TODO*/// if ((vga_page_size * 3) > 0x40000)
/*TODO*/// {
/*TODO*/// /* too big */
/*TODO*/// if (errorlog)
/*TODO*/// fprintf(errorlog,"tweaked mode %dx%d is too large to triple buffer\ntriple buffering disabled\n",gfx_width,gfx_height);
/*TODO*/// use_triplebuf = 0;
/*TODO*/// }
/*TODO*/// else
/*TODO*/// {
/*TODO*/// /* it fits, so set up the 3 pages */
/*TODO*/// no_xpages = 3;
/*TODO*/// xpage_size = vga_page_size / 4;
/*TODO*/// if (errorlog)
/*TODO*/// fprintf(errorlog,"unchained VGA triple buffering page size :%d\n",xpage_size);
/*TODO*/// /* and make sure the mode's unchained */
/*TODO*/// unchain_vga (reg);
/*TODO*/// /* triple buffering is enabled, turn off vsync */
/*TODO*/// wait_vsync = 0;
/*TODO*/// video_sync = 0;
/*TODO*/// }
/*TODO*/// }
/*TODO*/// /* center the mode */
/*TODO*/// center_mode (reg);
/*TODO*///
/*TODO*/// /* set the horizontal and vertical total */
/*TODO*/// if (scanrate15KHz)
/*TODO*/// /* 15.75KHz modes */
/*TODO*/// adjust_array = arcade_adjust;
/*TODO*/// else
/*TODO*/// /* PC monitor modes */
/*TODO*/// adjust_array = pc_adjust;
/*TODO*///
/*TODO*/// for (i=0; adjust_array[i].x != 0; i++)
/*TODO*/// {
/*TODO*/// if ((gfx_width == adjust_array[i].x) && (gfx_height == adjust_array[i].y))
/*TODO*/// {
/*TODO*/// /* check for 'special vertical' modes */
/*TODO*/// if((!adjust_array[i].vertical_mode && !(Machine->orientation & ORIENTATION_SWAP_XY)) ||
/*TODO*/// (adjust_array[i].vertical_mode && (Machine->orientation & ORIENTATION_SWAP_XY)))
/*TODO*/// {
/*TODO*/// reg[H_TOTAL_INDEX].value = *adjust_array[i].hadjust;
/*TODO*/// reg[V_TOTAL_INDEX].value = *adjust_array[i].vadjust;
/*TODO*/// break;
/*TODO*/// }
/*TODO*/// }
/*TODO*/// }
/*TODO*///
/*TODO*/// /*if scanlines were requested - change the array values to get a scanline mode */
/*TODO*/// if (scanlines && !scanrate15KHz)
/*TODO*/// reg = make_scanline_mode(reg,reglen);
/*TODO*///
/*TODO*/// /* big hack: open a mode 13h screen using Allegro, then load the custom screen */
/*TODO*/// /* definition over it. */
/*TODO*/// if (set_gfx_mode(GFX_VGA,320,200,0,0) != 0)
/*TODO*/// return 0;
/*TODO*///
/*TODO*/// if (errorlog)
/*TODO*/// {
/*TODO*/// fprintf(errorlog,"Generated Tweak Values :-\n");
/*TODO*/// for (i=0; i<reglen; i++)
/*TODO*/// {
/*TODO*/// fprintf(errorlog,"{ 0x%02x, 0x%02x, 0x%02x},",reg[i].port,reg[i].index,reg[i].value);
/*TODO*/// if (!((i+1)%3))
/*TODO*/// fprintf(errorlog,"\n");
/*TODO*/// }
/*TODO*/// }
/*TODO*///
/*TODO*/// /* tweak the mode */
/*TODO*/// outRegArray(reg,reglen);
/*TODO*///
/*TODO*/// /* check for unchained mode, if unchained clear all pages */
/*TODO*/// if (unchained)
/*TODO*/// {
/*TODO*/// unsigned long address;
/*TODO*/// /* clear all 4 bit planes */
/*TODO*/// outportw (0x3c4, (0x02 | (0x0f << 0x08)));
/*TODO*/// for (address = 0xa0000; address < 0xb0000; address += 4)
/*TODO*/// _farpokel(screen->seg, address, 0);
/*TODO*/// }
/*TODO*/// }
/*TODO*///
/*TODO*///
/*TODO*/// gone_to_gfx_mode = 1;
/*TODO*///
/*TODO*///
vsync_frame_rate = Machine.drv.frames_per_second;
/*TODO*///
/*TODO*/// if (video_sync)
/*TODO*/// {
/*TODO*/// TICKER a,b;
/*TODO*/// float rate;
/*TODO*///
/*TODO*///
/*TODO*/// /* wait some time to let everything stabilize */
/*TODO*/// for (i = 0;i < 60;i++)
/*TODO*/// {
/*TODO*/// vsync();
/*TODO*/// a = ticker();
/*TODO*/// }
/*TODO*///
/*TODO*/// /* small delay for really really fast machines */
/*TODO*/// for (i = 0;i < 100000;i++) ;
/*TODO*///
/*TODO*/// vsync();
/*TODO*/// b = ticker();
/*TODO*///
/*TODO*/// rate = ((float)TICKS_PER_SEC)/(b-a);
/*TODO*///
/*TODO*/// if (errorlog)
/*TODO*/// fprintf(errorlog,"target frame rate = %ffps, video frame rate = %3.2fHz\n",Machine->drv->frames_per_second,rate);
/*TODO*///
/*TODO*/// /* don't allow more than 8% difference between target and actual frame rate */
/*TODO*/// while (rate > Machine->drv->frames_per_second * 108 / 100)
/*TODO*/// rate /= 2;
/*TODO*///
/*TODO*/// if (rate < Machine->drv->frames_per_second * 92 / 100)
/*TODO*/// {
/*TODO*/// osd_close_display();
/*TODO*/// if (errorlog) fprintf(errorlog,"-vsync option cannot be used with this display mode:\n"
/*TODO*/// "video refresh frequency = %dHz, target frame rate = %ffps\n",
/*TODO*/// (int)(TICKS_PER_SEC/(b-a)),Machine->drv->frames_per_second);
/*TODO*/// return 0;
/*TODO*/// }
/*TODO*///
/*TODO*/// if (errorlog) fprintf(errorlog,"adjusted video frame rate = %3.2fHz\n",rate);
/*TODO*/// vsync_frame_rate = rate;
/*TODO*///
/*TODO*/// if (Machine->sample_rate)
/*TODO*/// {
/*TODO*/// Machine->sample_rate = Machine->sample_rate * Machine->drv->frames_per_second / rate;
/*TODO*/// if (errorlog)
/*TODO*/// fprintf(errorlog,"sample rate adjusted to match video freq: %d\n",Machine->sample_rate);
/*TODO*/// }
/*TODO*/// }
/*TODO*///
warming_up = 1;
//kill loading window
if (MainApplet.inst != null) {
//kill loading window
osdepend.dlprogress.setVisible(false);
MainApplet.inst.addKeyListener(MainApplet.inst);
MainApplet.inst.setSize((scanlines == 0), width, height);
MainApplet.inst.setBackground(Color.black);
MainApplet.inst.start();
MainApplet.inst.run();
MainApplet.inst.getFocus();
} else if (MainStream.inst != null) {
//main.MainStream.inst.addKeyListener(main.MainStream.inst);
MainStream.inst.setSize((scanlines == 0), width, height);
//main.MainStream.inst.setBackground(Color.black);
//MainStream.inst.start();
//MainStream.inst.run();
//main.MainStream.inst.getFocus();
if (MainStream.debug) {
screen = new software_gfx(settings.version + " (based on mame v" + build_version + ")");
screen.pack();
//screen.setSize((scanlines==1),gfx_width,gfx_height);//this???
//screen.setSize((scanlines==1),width,height);//this???
screen.setSize((scanlines == 0), width, height);
screen.setBackground(Color.black);
/*part of the old arcadeflex emulator probably need refactoring */
Dimension localDimension = Toolkit.getDefaultToolkit().getScreenSize();
screen.setLocation((int) ((localDimension.getWidth() - screen.getWidth()) / 2.0D), (int) ((localDimension.getHeight() - screen.getHeight()) / 2.0D));
screen.setVisible(true);
screen.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
screen.readkey = KeyEvent.VK_ESCAPE;
screen.key[KeyEvent.VK_ESCAPE] = true;
osd_refresh();
if (screen != null) {
screen.key[KeyEvent.VK_ESCAPE] = false;
}
}
});
screen.addKeyListener(screen);
screen.setFocusTraversalKeysEnabled(false);
}
} else {
/*part of the old arcadeflex emulator probably need refactoring */
Dimension localDimension = Toolkit.getDefaultToolkit().getScreenSize();
//kill loading window
osdepend.dlprogress.setVisible(false);
screen = new software_gfx(settings.version + " (based on mame v" + build_version + ")");
screen.pack();
//screen.setSize((scanlines==1),gfx_width,gfx_height);//this???
//screen.setSize((scanlines==1),width,height);//this???
screen.setSize((scanlines == 0), width, height);
screen.setBackground(Color.black);
screen.start();
screen.run();
screen.setLocation((int) ((localDimension.getWidth() - screen.getWidth()) / 2.0D), (int) ((localDimension.getHeight() - screen.getHeight()) / 2.0D));
screen.setVisible(true);
screen.setResizable((scanlines == 1));
screen.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
screen.readkey = KeyEvent.VK_ESCAPE;
screen.key[KeyEvent.VK_ESCAPE] = true;
osd_refresh();
if (screen != null) {
screen.key[KeyEvent.VK_ESCAPE] = false;
}
}
});
screen.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent evt) {
screen.resizeVideo();
}
});
screen.addKeyListener(screen);
screen.setFocusTraversalKeysEnabled(false);
screen.requestFocus();
}
return 1;
} |
300c1590-9145-4adf-8c91-4857ef35f27a | 3 | public static TreeMap<Integer,Integer> pitchRangeTrunkate(TreeMap<Integer,Integer> pitchTreeIn){
TreeMap<Integer,Integer> pitchTreeOut = new TreeMap<Integer,Integer>();
Iterator<Integer> pitchIterator = pitchTreeIn.keySet().iterator();
while(pitchIterator.hasNext()){
int key = pitchIterator.next();
if(-24<=key && key<=24){
pitchTreeOut.put(key, pitchTreeIn.get(key));
}
else{
pitchTotal = pitchTotal-pitchTreeIn.get(key);
}
}
return pitchTreeOut;
} |
624fb6e6-612d-4f8f-a041-dbae96aa68de | 2 | private void allocateElements(int numElements) {
int initialCapacity = MIN_INITIAL_CAPACITY;
// Find the best power of two to hold elements.
// Tests "<=" because arrays aren't kept full.
if (numElements >= initialCapacity) {
initialCapacity = numElements;
initialCapacity |= (initialCapacity >>> 1);
initialCapacity |= (initialCapacity >>> 2);
initialCapacity |= (initialCapacity >>> 4);
initialCapacity |= (initialCapacity >>> 8);
initialCapacity |= (initialCapacity >>> 16);
initialCapacity++;
if (initialCapacity < 0) // Too many elements, must back off
initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
}
elements = (E[]) new Object[initialCapacity];
} |
45fc12d4-9a6a-4f02-8b35-0b5c96281d3b | 3 | @Action(name = "hcomponent.handler.onkeydown.param", args = {"event.keyCode"})
public void onKeyDownAction(Updates updates, String[] args, String param) {
HComponent<?> html = (HComponent<?>) Session.getCurrent().get(
"_hcomponent.object." + param);
Session.getCurrent().store("_hcomponent.object." + param + ".event.keyCode", args[0]);
if (html.getOnKeyDownListener() != null) {
ContentManager.requestParams(
"hcomponent.handler.onkeydown.invoke",
Session.getCurrent().gethActionManager()
.getHAction(html.getOnKeyDownListener())
.getArguments(), param);
}
} |
e7e75d7d-35da-4107-aadf-b53096d79b41 | 6 | void decodeGrbit( byte[] grbytes )
{
if( (byte) (grbytes[0] & 0x1) > 0x0 )
{
isLink = true;
}
if( (byte) (grbytes[0] & 0x2) > 0x0 )
{
isAbsoluteLink = true;
}
// 20060406 KSC: need both bits 2 & 4 to be set for hasDescription
// if ((byte)(grbytes[0] & 0x14) > 0x0)hasDescription = true;
if( (byte) (grbytes[0] & 0x14) >= 0x14 )
{
hasDescription = true;
}
if( (byte) (grbytes[0] & 0x8) > 0x0 )
{
hasTextMark = true;
}
if( (byte) (grbytes[0] & 0x80) > 0x0 )
{
hasTargetFrame = true;
}
if( (byte) (grbytes[0] & 0x100) > 0x0 )
{
isUNCPath = true;
}
} |
3abac20b-18a3-4005-b7b0-0ead2dc3459f | 2 | static void printList(final PrintWriter pw, final List l) {
for (int i = 0; i < l.size(); ++i) {
Object o = l.get(i);
if (o instanceof List) {
printList(pw, (List) o);
} else {
pw.print(o.toString());
}
}
} |
fb145698-ba7e-47de-8a46-c412c2aaf98d | 4 | public static void removeCols(JTable paymentTable) {
TableColumnModel tcm = paymentTable.getColumnModel();
System.out.println("getColumnCount:" + tcm.getColumnCount());
if (tcm.getColumnCount() == 13) {
paymentTable.removeColumn(tcm.getColumn(12));
}
if (tcm.getColumnCount() == 12) {
paymentTable.removeColumn(tcm.getColumn(11));
}
if (tcm.getColumnCount() == 11) {
paymentTable.removeColumn(tcm.getColumn(10));
}
if (tcm.getColumnCount() == 10) {
paymentTable.removeColumn(tcm.getColumn(9));
}
} |
4ef01d3f-50ae-4c96-89fd-ea6ce17055f4 | 8 | public void useSkillEx(SkillBarSkillSlot skillSlot, int targetId, int delay) throws IOException {
LOG.debug("Using skill in slot {} on target {}", skillSlot, targetId);
//FIXME: why isn't the delay used????
if (this.isDead(-2)) {
LOG.debug("The player is dead");
return;
}
long startDeadlockCheck = System.currentTimeMillis();
this.useSkill(skillSlot, targetId);
int skillRecharge = 0;
long elapsedTime = 0;
do {
if (this.isDead()) {
LOG.debug("The player is dead");
break;
}
int playerSkill = this.getSkill(-2);
elapsedTime = System.currentTimeMillis() - startDeadlockCheck;
if (playerSkill == 0 && elapsedTime > 1000) {
break;
}
try {
Thread.sleep(250);
} catch (InterruptedException ex) {
// ignore
}
skillRecharge = this.getSkillRecharge(skillSlot);
} while (skillRecharge == 0 || elapsedTime < 8000);
try {
Thread.sleep(250);
} catch (InterruptedException ex) {
// ignore
}
LOG.debug("Used skill on target");
} |
4e7c7335-2f3d-4cad-8bf7-57b1229c3730 | 7 | public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
@Override
public void run() {
try {
// This has to be synchronized or it can collide with
// the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server
// owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
// Tell all plotters to stop gathering
// information.
for (Graph graph : graphs) {
graph.onOptOut();
}
}
}
// We use the inverse of firstPost because if it is the
// first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e
// PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
} |
88ba96ee-4cd4-42f3-b199-02607ee7669c | 7 | public void setupAttribLists() {
String [] tempAttribNames = new String[m_data.numAttributes()];
String type;
m_classAttrib.removeAllItems();
for(int i=0; i<tempAttribNames.length; i++) {
switch (m_data.attribute(i).type()) {
case Attribute.NOMINAL:
type = " (Nom)";
break;
case Attribute.NUMERIC:
type = " (Num)";
break;
case Attribute.STRING:
type = " (Str)";
break;
case Attribute.DATE:
type = " (Dat)";
break;
case Attribute.RELATIONAL:
type = " (Rel)";
break;
default:
type = " (???)";
}
tempAttribNames[i] = new String("Colour: "+m_data.attribute(i).name()+" "+type);
m_classAttrib.addItem(tempAttribNames[i]);
}
if (m_data.classIndex() == -1)
m_classAttrib.setSelectedIndex(tempAttribNames.length - 1);
else
m_classAttrib.setSelectedIndex(m_data.classIndex());
m_attribList.setListData(tempAttribNames);
m_attribList.setSelectionInterval(0, tempAttribNames.length-1);
} |
be731c5c-19b8-4e09-86fa-270e081ec63f | 2 | public StackManipStmt(final StackExpr[] target, final StackExpr[] source,
final int kind) {
this.kind = kind;
this.target = target;
for (int i = 0; i < target.length; i++) {
this.target[i].setParent(this);
}
this.source = source;
for (int i = 0; i < source.length; i++) {
this.source[i].setParent(this);
}
} |
710119bc-49f8-4985-b9b2-505f2fb43040 | 0 | public boolean isIntersectingEnemy(EnemyObject enemy){
Rectangle2D.Double r = new Rectangle2D.Double(me.getX(), me.getY(), 20, 20);
Ellipse2D.Double e = new Ellipse2D.Double(enemy.getX(), enemy.getY(), 20, 20);
return e.intersects(r);
} |
828518cd-6720-4fd7-aeaf-26c9cff45c01 | 0 | public void testCircleEquation() {
CircleEquation equation = CircleEquation.newInstance(0, 0, 5);
assertEquals(Math.acos(3.0f / 5.0f), equation.getT(3), 0.01f);
} |
29be8160-af82-43b9-a599-e1c00c4b369e | 4 | public void setAllLedStatesToRepresentInputValue()
{
for (LED led : ledArray) {
led.setState(LED.OFF);
}
// if input value is less than lowest step, no leds are lit
if (highestLitLedIndex == -1) {
return;
}
for (int i = 0; i < ledArray.length; i++) {
if (i <= highestLitLedIndex) {
ledArray[i].setState(LED.ON);
}
}// end of for (int i = 0; i < ledArray.length; i++)
}// end of LEDGroup::setAllLedStatesToRepresentInputValue |
60f58414-3019-4165-b680-7a343a10b29d | 7 | private static float getFloatValueForByteBinaryString(String bits) {
if (bits.matches("[01]{8}")) {
int sign = 1;
if (bits.charAt(0) == '1') {
sign = -1;
}
float result = 0f;
int exponent = getExcessThreeValue(bits.substring(1, 4));
StringBuilder mantissaBitsBuilder = new StringBuilder(bits.substring(4));
if (exponent >= 0) {
if (exponent > 4) {
for (int i = 4; i < exponent; i++) {
mantissaBitsBuilder.append('0');
}
}
} else {
for (int i = 0; i > exponent; i--) {
mantissaBitsBuilder.insert(0, '0');
}
}
String mantissaBits = mantissaBitsBuilder.toString();
int integerPart = 0;
if (exponent > 0) {
integerPart = Integer.parseInt(mantissaBits.substring(0, exponent), 2);
mantissaBits = mantissaBits.substring(exponent);
}
float fractionalPart = Integer.parseInt(mantissaBits, 2) / (float) (Math.pow(2, mantissaBits.length()));
result = integerPart + fractionalPart;
return sign * result;
} else {
throw new NumberFormatException("Invalid binary representation of a byte containing a float value: " + bits);
}
} |
e62aedf1-bbb3-4ad7-a27e-dfbccba584c9 | 2 | protected String getClientInput(){
String input = "";
//Try to read input from client.
try{
if(clientInput.ready()){
input = clientInput.readLine();
}
} catch (IOException e) {
System.out.println("Error reading from client " + user.getName() + "(" + user.getIP() + ").");
e.printStackTrace();
}
return input;
} |
f29e94ed-3f2c-4253-8f5a-1a6451e73699 | 0 | public String getName() {
return name;
} |
eeb82f7a-15f0-4c4b-82a8-b4d08731bb6a | 6 | public void printGrid() {
for(int i = 0; i < width + 2; i++)
System.out.print("_");
System.out.println();
for(int y = 0; y < height; y++) {
System.out.print("|");
for(int x = 0; x < width; x++) {
if(grid[x][y] instanceof EmptyTile)
System.out.print(" ");
else if(grid[x][y] instanceof FishTile)
System.out.print("~");
else
System.out.print("S"); //System.out.print(sharkFeeding(x, y));
}
System.out.println("|");
}
for(int i = 0; i < width + 2; i++)
System.out.print("_");
System.out.println();
} |
3b67f4a2-a8ce-4804-8ab1-c7e6528776d7 | 3 | @Override
public void run()
{
while(Running)
{
for(Room mRoom : Grizzly.GrabHabboHotel().GrabRoomHandler().GrabPopulatedRooms().values())
{
mRoom.Tick();
}
try
{
Thread.sleep(500);
} catch (InterruptedException e) {}
}
} |
dfc5091d-8c10-4542-acc6-c4aa59c3f9db | 9 | public void scrollCellToView(JTable table, int rowIndex, int vColIndex) {
if (!(table.getParent() instanceof JViewport)) {
return;
}
JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Rectangle viewRect = viewport.getViewRect();
int x = viewRect.x;
int y = viewRect.y;
if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){
} else if (rect.x < viewRect.x){
x = rect.x;
} else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
x = rect.x - viewRect.width + rect.width;
}
if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){
} else if (rect.y < viewRect.y){
y = rect.y;
} else if (rect.y > (viewRect.y + viewRect.height - rect.height)){
y = rect.y - viewRect.height + rect.height;
}
viewport.setViewPosition(new Point(x,y));
} |
777b5619-dfa4-4db6-a168-5142989c3e41 | 2 | @Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (tag == null || Tags.MESSAGE == tag) {
return;
}
valueTag = new String(ch, start, length).trim();
} |
84a2d569-0688-425d-be38-e04d9427bc46 | 8 | private static void logToDetailsHTMLFile(UniProtEntry uniProtEntry) {
StringBuffer sb = new StringBuffer();
sb.append("<html>");
sb.append("<body>");
sb.append("<table border=\"1\">");
sb.append("<tr><td>\r\n");
//String imageTag = ncbiDownloadManager.getProteinImage(uniProtEntry);
//System.out.println("image = >>>>>>>>>>>>>>"+imageTag);
//sb.append(imageTag);
sb.append("<br/>");
sb.append("</td></tr>\r\n");
sb.append("<tr><td>\r\n");
Collection<DatabaseCrossReference> references = uniProtEntry.getDatabaseCrossReferences();
for(DatabaseCrossReference reference : references) {
sb.append(reference.getDatabase().toDisplayName());
sb.append("<br/>");
}
sb.append("</td></tr>\r\n");
sb.append("<tr><td>\r\n");
for(DatabaseCrossReference reference : references) {
sb.append(reference);
sb.append("<br/>");
}
sb.append("</td></tr>\r\n");
sb.append("<tr><td>\r\n");
ArrayList<Gene> geneList = (ArrayList<Gene>) uniProtEntry.getGenes();
for(Gene myGene : geneList) {
sb.append(ncbiDownloadManager.getGeneFASTA(myGene.getGeneName().getValue(),uniProtEntry.getOrganism().getCommonName().getValue()));
sb.append("<br/>");
}
sb.append("</td></tr>\r\n");
sb.append("<tr><td>\r\n");
sb.append(getPublicationList(uniProtEntry));
sb.append("</td></tr>\r\n");
sb.append("<tr><td>\r\n");
if(uniProtEntry.getSequence().getValue().length() > 20) {
FastaSequence fsequence = new FastaSequence("Prot1", uniProtEntry.getSequence().getValue());
Range[] ranges = Jronn.getDisorder(fsequence);
for(int i=0;i<ranges.length;i++) {
sb.append("<br/>From:"+ranges[i].from);
sb.append("<br/>To:"+ranges[i].to);
sb.append("<br/>Disorder Probability:"+ranges[i].score);
}
}
sb.append("</td></tr>\r\n");
sb.append("<tr><td>\r\n");
ArrayList<Feature> features = (ArrayList<Feature>) uniProtEntry.getFeatures();
for(Feature feature : features) {
sb.append(feature.getType());
sb.append("<br/>");
sb.append(feature.getFeatureLocation().getStart());
sb.append("<br/>");
sb.append(feature.getFeatureLocation().getEnd());
sb.append("<br/>");
sb.append(feature.getFeatureLocation().getStart());
sb.append("<br/>");
}
sb.append("</td></tr>\r\n");
sb.append("</table>");
sb.append("</body>");
sb.append("</html>");
try {
File file = new File("C:\\Users\\addou\\Desktop\\UniProt\\details\\"+uniProtEntry.getPrimaryUniProtAccession().getValue()+"_details.html");
String content = sb.toString();
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
} |
dc06ce32-bc8f-4401-a056-88a8df8d7b57 | 4 | public static int runToNextInputFrameLimit(int move, int limit) {
if ((move & 0b00001111) == 0) {
return runToNextInputFrameHiLimit(limit) ? 1 : 0;
} else if ((move & 0b11110000) == 0) {
return runToNextInputFrameLoLimit(limit) ? 1 : 0;
} else {
return runToNextInputFrameHiLoLimit(limit);
}
} |
2832e848-0ce7-44c9-85a4-3005c5f52b4b | 9 | public int getArmorClass() {
Integer armorClass = 10;
Slot armor_slot = slots.get("armor");
Slot shield_slot = slots.get("weapon1");
Item item_a = null;
Item item_s = null;
if( armor_slot != null ) item_a = armor_slot.getItem();
if( shield_slot != null ) item_s = shield_slot.getItem();
Shield shield = null;
Armor armor = null;
if( item_s != null && item_s instanceof Shield ) shield = (Shield) item_s;
if( item_a != null && item_a instanceof Armor ) armor = (Armor) item_a;
if( armor != null ) {
armorClass += armor.getArmorBonus();
if( shield != null ) armorClass += shield.getShieldBonus();
}
else if( shield != null ) {
armorClass += shield.getShieldBonus();
}
return armorClass + getAbilityMod(Abilities.STRENGTH);
} |
27b456c9-55ea-473b-994d-3733e234d4bc | 9 | public static int[][] generateSudoku(int size, int numbers) {
final int S = size * size;
final int[][] array = new int[S][S];
final Random r = new Random();
// int x = r.nextInt(S);
final int x = 0;
for (int i = 0; i < S; i++) {
for (int j = 0; j < S; j++) {
array[i][j] = (i*size + i/size + j + x) % (S) + 1;
}
}
printArray(array, size);
int tests = 1000;
// while (tests-- > 0) {
// System.out.println(tests);
int temp;
int reallytemp;
for (int i = 0; i < S*S; i++) {
switch (r.nextInt(6)) {
case 0:
swapRows(array, size, temp = r.nextInt(S),
r.nextInt(size) + temp/size*size);
// System.out.println("swapping " + temp + " with " + reallytemp);
break;
case 1:
swapRowsBlock(array, size, r.nextInt(size),
r.nextInt(size));
break;
case 2:
swapColumnsBlock(array, size, r.nextInt(size),
r.nextInt(size));
break;
case 3:
swapColumns(array, size, temp = r.nextInt(S),
r.nextInt(size) + temp/size*size);
// System.out.println("swapping " + temp + " with " + reallytemp);
break;
case 4:
reflectAxis(array, size, true);
break;
case 5:
reflectAxis(array, size, false);
break;
}
}
// if (!isValid(array, size)) {
// System.out.println("=================================");
// System.out.println("OPS!");
// System.out.println("=================================");
// printArray(array, size);
//
// }
//
// }
// printArray(array, size);
// reflectAxis(array, size, false);
System.out.println("=================================");
printArray(array, size);
// reflectAxis(array, size, true);
// reflectAxis(array, size, false);
// System.out.println("=================================");
// printArray(array, size);
return null;
} |
4af88259-405f-49fd-8801-b51d35047d23 | 7 | void selectStatement() {
ArrayList<Condition> conditions = new ArrayList<Condition>();
ArrayList<String> columnNames = new ArrayList<String>();
Table table2 = new Table(new String[]{});
Table result;
_input.next("select");
String column = columnName();
columnNames.add(column);
while (_input.nextIf(",")) {
columnNames.add(columnName());
}
_input.next("from");
Table table = tableName();
if (_input.nextIf(",")) {
table2 = tableName();
if (_input.nextIf("where")) {
conditions.add(condition(table, table2));
while (_input.nextIf("and")) {
conditions.add(condition(table, table2));
}
}
} else {
if (_input.nextIf("where")) {
conditions.add(condition(table));
while (_input.nextIf("and")) {
conditions.add(condition(table));
}
}
}
_input.next(";");
if (table2.columns() == 0) {
result = table.select(columnNames, conditions);
} else {
result = table.select(table2, columnNames, conditions);
}
System.out.println("Search results:");
result.print();
} |
b8983beb-bbe3-4bc2-a82a-7f262a7ec805 | 1 | public T peek() throws NoSuchElementException {
T returnValue;
try {
return heap.get(0).item;
} catch (IndexOutOfBoundsException npe) {
throw new NoSuchElementException();
}
} |
70915711-fc39-41aa-99ab-e6d318f6b2f5 | 5 | public UriParseResult(final Uri uri) {
//uri formats:
//content://[authority] for general queries
//content://[authority]/[tables] for table specific queries
//content://[authority]/[table]/[id] for entity specific queries
//check if authority matches
if (!authority.equals(uri.getEncodedAuthority())) {
throw new IllegalArgumentException("Expected authority: '" +
authority + "' got '" + uri.getEncodedAuthority() + "'.");
}
//parse path
final List<String> pathSegments = uri.getPathSegments();
//we need at least the database
/*if (pathSegments == null || pathSegments.isEmpty()) {
throw new IllegalArgumentException(
"No db part int uri: '" + uri.toString() + "'.");
}*/
//we can only have up to three path arguments ([db_name]/[table]/[id])
if (pathSegments.size() > 2) {
throw new IllegalArgumentException("Uri path to long: '" + uri);
}
//little bobby tables, we call him.
tables = !pathSegments.isEmpty() ? pathSegments.get(0) : "";
//we have an id elements, make sure it is a valid long
if (pathSegments.size() == 2) {
try {
id = Long.parseLong(pathSegments.get(1));
} catch (final Exception e) {
throw new IllegalArgumentException(
"Not a valid id: " + pathSegments.get(1), e);
}
} else {
id = null;
}
} |
3ec70f76-fca9-46d0-a43c-375226c25b12 | 7 | public String[][] retrieveRows(String table, double limit, String regExp,
String[][] tags, String[][] attributes, String[] columns,
String[][] values, String[] doubleColumns, Double[][] doubleValues,
double[][] range, String cursorName) throws MobbedException {
validateTableName(table);
validateColumns(columns);
validateColumns(doubleColumns);
String[][] rows = null;
String qry = "SELECT * FROM " + table;
qry += constructQualificationQuery(table, regExp, tags, attributes,
columns, values, doubleColumns, doubleValues, range);
if (isEmpty(cursorName) && limit != Double.POSITIVE_INFINITY)
qry += " LIMIT " + (int) limit;
try {
PreparedStatement pstmt = connection.prepareStatement(qry,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
setQaulificationValues(pstmt, qry, tags, attributes, columns,
values, doubleColumns, doubleValues);
if (!isEmpty(cursorName) && limit != Double.POSITIVE_INFINITY) {
if (!dataCursorExists(cursorName))
createDataCursor(cursorName, pstmt.toString());
rows = next(cursorName, (int) limit);
} else {
if (verbose)
System.out.println(pstmt);
rows = populateArray(pstmt.executeQuery());
}
} catch (SQLException ex) {
throw new MobbedException(
"Could not execute query to retrieve rows\n"
+ ex.getMessage());
}
return rows;
} |
b6bf581f-fedd-4232-b085-da32131e429a | 4 | @Override
public boolean equals(Object obj) {
if (obj != null && obj.getClass().equals(Card.class)) {
if (this.ID == null || ((Card) obj).ID == null) {
Debug.p("Comparing cards with null ID!", Debug.W);
return false;
} else {
return this.ID.equals(((Card) obj).ID);
}
} else {
return false;
}
// return obj != null
// && obj.getClass().equals(Card.class)
// && this.ID != null
// && ((Card) obj).ID != null
// && this.ID.equals(((Card) obj).ID);
} |
17f0ca89-ea2d-4984-9be3-2fe2fd562ae7 | 6 | public void bombbrick(int c, int r) {
int remove = 1;
for (int i = c - remove; i <= c + remove; i++) {
for (int j = r - remove; j <= r + remove; j++) {
if (i >= 0 && i < bricks.length && j >= 0 && j < bricks[0].length) {
bricks[i][j].state = false;
}
}
}
} |
9b6b6014-b16e-443b-908c-994a7f87f5fb | 5 | public void drawOutput(Graphics2D g, OutputConnector op) {
int[] xs = null, ys = null;
if (op.pos == Position.right) {
xs = new int[] { x + width - connectorSize / 2,
x + width + connectorSize / 2,
x + width - connectorSize / 2 };
ys = new int[] { y + height / 2 - connectorSize / 2,
y + height / 2, y + height / 2 + connectorSize / 2 };
} else if (op.pos == Position.top) {
xs = new int[] { x + width / 2 - connectorSize / 2, x + width / 2,
x + width / 2 + connectorSize / 2 };
ys = new int[] { y + connectorSize / 2, y - connectorSize / 2,
y + connectorSize / 2 };
} else if (op.pos == Position.bottom) {
xs = new int[] { x + width / 2 - connectorSize / 2, x + width / 2,
x + width / 2 + connectorSize / 2 };
ys = new int[] { y + height - connectorSize / 2,
y + height + connectorSize / 2,
y + height - connectorSize / 2 };
} else {
xs = new int[] { x + connectorSize / 2, x - connectorSize / 2,
x + connectorSize / 2 };
ys = new int[] { y + height / 2 - connectorSize / 2,
y + height / 2, y + height / 2 + connectorSize / 2 };
}
if (xs != null && ys != null)
g.drawPolygon(xs, ys, 3);
} |
027fa6e3-6aa0-46f1-be62-666512bc454f | 3 | public void sort(Map map){
for(int i = 0; i < map.getIDList().length; i++){
for(int j = i+1; j < map.getIDList().length; j++){
if(map.getIDList()[i] > map.getIDList()[j]){
swap(i, j);
}
}
}
} |
0d117a93-6d57-4413-8662-fae81ecca057 | 8 | protected void toXMLImpl(XMLStreamWriter out) throws XMLStreamException {
out.writeStartElement(getXMLElementTagName());
out.writeAttribute(ID_ATTRIBUTE, getId());
if (transport != null) {
if (transport.getUnit() == null) {
logger.warning("transport.getUnit() == null");
} else if (getAIMain().getAIObject(transport.getId()) == null) {
logger.warning("broken reference to transport");
} else if (transport.getMission() != null
&& transport.getMission() instanceof TransportMission
&& !((TransportMission) transport.getMission()).isOnTransportList(this)) {
logger.warning("We should not be on the transport list.");
} else {
out.writeAttribute("transport", transport.getUnit().getId());
}
}
if (mission != null) {
if (mission.isValid()) {
mission.toXML(out);
} else {
logger.warning("AI unit with " + mission.invalidReason()
+ " mission " + mission);
}
}
out.writeEndElement();
} |
db7bc21e-42e3-495e-bbc2-26354e4851f5 | 1 | @Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("|");
for (T i: filter) {
sb.append(i.toString()).append("|");
}
return sb.toString();
} |
2c5ce639-469d-4259-aa3e-1b1c7dbb4ee9 | 7 | public void inboundTrainInfoOutput(){
try {
jxl.Workbook readWorkBook = jxl.Workbook.getWorkbook(new File("outputFile.xls")); //唯讀的Excel工作薄物件
jxl.write.WritableWorkbook writeWorkBook = Workbook.createWorkbook(new File("outputFile.xls"), readWorkBook); //要寫入的路徑以及檔名
jxl.write.WritableSheet writeSheet = writeWorkBook.createSheet("inbound_train_info", 1); //建立一個工作表名字,然後0表示為第一頁
Label label = new Label(0, 0, "Inbound Train No"); //設一個label, 並添加(column major)
writeSheet.addCell(label); //將格子添加到表格
writeSheet.addCell(new Label(1, 0, "Day No"));
writeSheet.addCell(new Label(2, 0, "Arriving time at receiving area"));
writeSheet.addCell(new Label(3, 0, "Receiving track No"));
writeSheet.addCell(new Label(4, 0, "Number of blocks"));
writeSheet.addCell(new Label(5, 0, "Number of cars"));
writeSheet.addCell(new Label(6, 0, "Destination of blocks (number of cars)"));
writeSheet.addCell(new Label(7, 0, "Starting time of humping job"));
writeSheet.addCell(new Label(8, 0, "Ending time of humping job"));
BlockValues b = new BlockValues(); //輸出block values用
for(int i=0, x=1; i<finishTrain.size() ; i++, x++){ //輸入每一筆火車的資料
writeSheet.addCell(new Label(0, x, finishTrain.get(i).inBoundTrainId)); //寫入火車編號
writeSheet.addCell(new Label(1, x, finishTrain.get(i).day)); //寫入到達日
writeSheet.addCell(new Label(2, x, finishTrain.get(i).arrivalTime)); //寫入到達時間
writeSheet.addCell(new Label(3, x, finishTrain.get(i).receivingTrackNo)); //寫入receiving track No
Integer numberOfBlocks=0; //block種類數量
//Integer numberOfCars=0; //car總數量
String tmpString = new String(""); //儲存輸出用destination of blocks
for(int j=0 ; j<b.blockLength ; j++){ //寫入車廂種類數量
int c = Integer.parseInt(countBlocks(b.blockValues[j], finishTrain.get(i)));
if(c!=0){
numberOfBlocks++;
//numberOfCars+=c;
tmpString+=b.blockValues[j] + "(" + c + ");";
}
}
writeSheet.addCell(new Label(4, x, numberOfBlocks.toString()));
writeSheet.addCell(new Label(5, x, String.valueOf(finishTrain.get(i).inBoundBlock.size())));
writeSheet.addCell(new Label(6, x, tmpString));
writeSheet.addCell(new Label(7, x, String.valueOf(finishTrain.get(i).currentTime)));
writeSheet.addCell(new Label(8, x, String.valueOf(finishTrain.get(i).currentTime +
(Constants.HUMP_RATE*(1.0f*finishTrain.get(i).inBoundBlock.size())))));
}
label = null;
writeWorkBook.write(); //最後的最後,在一次將資料寫入檔案內即可,這是一次性寫入,第二次寫入會無效
writeWorkBook.close(); //關檔是好習慣
readWorkBook.close(); //關檔是好習慣
} catch (IOException e) {
e.printStackTrace();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
} catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
8e400b0b-1e38-4818-84bc-190f4341a13c | 9 | public static final String vfsifyFilename(String filename)
{
filename=filename.trim();
if(filename.startsWith("::"))
filename=filename.substring(2);
if(filename.startsWith("//"))
filename=filename.substring(2);
if((filename.length()>3)
&&(Character.isLetter(filename.charAt(0))
&&(filename.charAt(1)==':')))
filename=filename.substring(2);
while(filename.startsWith("/"))
filename=filename.substring(1);
while(filename.startsWith("\\"))
filename=filename.substring(1);
while(filename.endsWith("/"))
filename=filename.substring(0,filename.length()-1);
while(filename.endsWith("\\"))
filename=filename.substring(0,filename.length()-1);
return filename.replace(pathSeparator,'/');
} |
40fdb173-f88c-4397-aa58-cd17141d4120 | 9 | public int numDecodings(String s) {
if (s == null || s.length() == 0)
return 0;
if (s.charAt(0) == '0')
return 0;
if (s.length() == 1)
return 1;
if (s.length() == 2) {
if (s.charAt(1) == 0)
return 1;
else if (Integer.parseInt(s.substring(0, 2)) > 26)
return 1;
else
return 2;
}
if (s.charAt(s.length() - 1) == '0')
return numDecodings(s.substring(0, s.length() - 2));
else {
int i = Integer.parseInt(s.substring(s.length() - 2, s.length()));
if (i > 26)
return numDecodings(s.substring(0, s.length() - 1));
else
return numDecodings(s.substring(0, s.length() - 1)) + numDecodings(s.substring(0, s.length() - 2));
}
} |
8a7b0dbf-c1d8-4f1e-af40-c964254325e0 | 5 | public returnTypes deleteAllChunks(byte[] fileID) {
String recID = Packet.bytesToHex(fileID);
boolean found = false;
for(BackupChunk chunk : backedUpChunks) {
String comID = Packet.bytesToHex(chunk.getFileID());
if(comID.equals(recID)) {
String filepath = "storage/";
filepath += chunk.getFilename();
boolean success = (new File (filepath)).delete();
if (success) {
currSize -= chunk.getSize();
success = backedUpChunks.remove(chunk);
if(success) {System.out.println("The file has been successfully deleted");updateLog();found = true;}
else {System.out.println("Error occurred while deleting the file."); return returnTypes.FAILURE;}
}
else {System.out.println("Error occurred while deleting the file."); return returnTypes.FAILURE;}
}
}
if(found)
return returnTypes.SUCCESS;
else
return returnTypes.FILE_DOES_NOT_EXIST;
} |
6fdcded1-6afa-42d5-bffe-f5b8a462f0a4 | 5 | public int[] getRange(){
if (mRange != null){
return mRange;
}
mRange = new int[2];
boolean isFirst = true;
for (Map.Entry<Integer, Integer> entry : mHistorgram.entrySet()) {
if (isFirst) {
isFirst = false;
mRange[0] = mRange[1] = entry.getKey();
} else {
mRange[0] = mRange[0] < entry.getKey() ?
mRange[0] :
entry.getKey();
mRange[1] = mRange[1] > entry.getKey() ?
mRange[1] :
entry.getKey();
}
}
return mRange;
} |
de69df23-95b9-441b-940d-8902251806d1 | 9 | private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
int row = jTable2.getSelectedRow();
int opc = select1.getSelectedIndex();
jLabel3.setText("");
if (avaliacoes_vendas.size() > 0 && opc == 1 && row != -1) {
AvVenda av = (AvVenda) avaliacoes_vendas.get(row);
av.setNome_cliente(c.getNome());
new UIVisAvVenda(c, av).setVisible(true);
} else if (avaliacoes_oficina.size() > 0 && opc == 2 && row != -1) {
AvOficina av = (AvOficina) avaliacoes_oficina.get(row);
av.setNome_cliente(c.getNome());
new UIVisAvOficina(c, av).setVisible(true);
} else if (avaliacoes_atendimentos.size() > 0 && opc == 3 && row != -1) {
AvAtendimento av = (AvAtendimento) avaliacoes_atendimentos.get(row);
av.setNome_cliente(c.getNome());
new UIVisAvAtendimento(c, av).setVisible(true);
} else {
jLabel3.setText("Nenhum item selecionado!");
}
}//GEN-LAST:event_jButton2ActionPerformed |
e14b0c51-c279-42b4-a5ac-f69741efee55 | 6 | public static void drawMainMenu() {
// Clear the last screen
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
// Turn off lighting
GL11.glDisable(GL11.GL_LIGHTING);
// Enable alpha testing (transparent backgrounds)
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
// Draw the menu background
drawRec(menuBackgroundHandle, 0, 0, viewportW, viewportH, 1.0f);
// Don't draw the buttons if loading (this same method will be called
// for the loading screen)
if (!loading) {
// For each of the buttons, draw the correct image based on if the
// cursor is over the button
// About button
if (onAboutButton) {
drawRec(aboutButtonOverHandle, (int) aboutButtonPosition.x,
(int) aboutButtonPosition.y,
(float) aboutButton.getWidth(),
(float) aboutButton.getHeight(), 1.0f);
} else {
drawRec(aboutButtonHandle, (int) aboutButtonPosition.x,
(int) aboutButtonPosition.y,
(float) aboutButton.getWidth(),
(float) aboutButton.getHeight(), 1.0f);
}
// Play button
if (onPlayButton) {
drawRec(playButtonOverHandle, (int) playButtonPosition.x,
(int) playButtonPosition.y,
(float) playButton.getWidth(),
(float) playButton.getHeight(), 1.0f);
} else {
drawRec(playButtonHandle, (int) playButtonPosition.x,
(int) playButtonPosition.y,
(float) playButton.getWidth(),
(float) playButton.getHeight(), 1.0f);
}
// Money cheat button
if (onCheatButton) {
drawRec(cheatButtonOverHandle, (int) cheatButtonPosition.x,
(int) cheatButtonPosition.y,
(float) cheatButton.getWidth(),
(float) cheatButton.getHeight(), 1.0f);
} else {
drawRec(cheatButtonHandle, (int) cheatButtonPosition.x,
(int) cheatButtonPosition.y,
(float) cheatButton.getWidth(),
(float) cheatButton.getHeight(), 1.0f);
}
// Help button
if (onHelpButton) {
drawRec(helpButtonOverHandle, (int) helpButtonPosition.x,
(int) helpButtonPosition.y,
(float) helpButton.getWidth(),
(float) helpButton.getHeight(), 1.0f);
} else {
drawRec(helpButtonHandle, (int) helpButtonPosition.x,
(int) helpButtonPosition.y,
(float) helpButton.getWidth(),
(float) helpButton.getHeight(), 1.0f);
}
// Exit button
if (onExitButton) {
drawRec(exitButtonOverHandle, (int) exitButtonPosition.x,
(int) exitButtonPosition.y,
(float) exitButton.getWidth(),
(float) exitButton.getHeight(), 1.0f);
} else {
drawRec(exitButtonHandle, (int) exitButtonPosition.x,
(int) exitButtonPosition.y,
(float) exitButton.getWidth(),
(float) exitButton.getHeight(), 1.0f);
}
// Draw the cursor
drawRec(cursorTextureHandle, cursorX,
cursorY - cursorTexture.getHeight(),
cursorTexture.getWidth(), cursorTexture.getHeight(), 1.0f);
}
GL11.glEnable(GL11.GL_LIGHTING);
} |
c3764b0f-3812-4e4e-9327-64072340fb66 | 7 | public void runControlServer()
{
try {
controlServerSocket= new ServerSocket(controlDataSocketNumber);
this.changeServerType();
while(true)
{
controlSocket = controlServerSocket.accept();
controlInput = new ObjectInputStream(controlSocket.getInputStream());
ClientMessage c = (ClientMessage) controlInput.readObject();
System.out.println("Got client message with command: " + c.getCommand() );
if(c.getCommand().equals("INVITE"))
{
if(!m.getHaveGame())
{
//Dont have a game, may accept or reject
this.possibleOpponent = c.getUser();
this.possiblePiece = c.getPiece() * -1;
v.setInviteView(c.getUser().getUserName());
}else
{
//Have a game already, automatically reject
m.rejectInvite(c.getUser());
}
}else if(c.getCommand().equals("ACCEPT"))
{
//Accept invite request
m.setIsTurn();
m.setHaveGame();
v.resetGameBoard();
v.setGameStartMessage();
System.out.println("Got accept back");
}else if(c.getCommand().equals("REJECT"))
{
//Rejected invite
v.setGameRejectedMessage();
}
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Could not start open P2P control socket on port 25201, exiting...");
System.exit(-3);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} |
77f229fb-81ff-4ce8-aa68-b6636b18ddb2 | 8 | private long updateRewrite(Master master, File f, Location accessLoc, int rewriteCount) {
MasterMeta fm = null;
if (master.map.containsKey(f.getId())) {
fm = master.map.get(f.getId());
} else {
fm = new MasterMeta(f);
master.map.put(f.getId(), fm);
}
int cCount = master.clusters.size();
int writes = 0;
long maxDelay = -1;
for (int i = 0; i < cCount && writes < rewriteCount; i++) {
Cluster cluster = master.clusters.get(i);
if (fm.instances.contains(cluster) || !cluster.isHealthy()) {
continue;
}
FileWrite fw = cluster.write(f, NODE_PER_CLUSTER_WRITE_REDUNDANCY);
double distance = accessLoc.distance(cluster.getLocation());
if (fw.time > 0) { // Cluster had sufficient space.
maxDelay = Math.max(maxDelay, fw.time + Util.networkTime(f.getSize(), distance));
fm.instances.add(cluster);
writes++;
} else if (fw.time != Cluster.NO_SPACE_SENTINEL) {
cluster.calibrateSpaceAvailability(NODE_PER_CLUSTER_WRITE_REDUNDANCY);
}
}
if (writes < rewriteCount) {
return -1;
}
return maxDelay;
} |
42cd2fbb-207f-4863-a6dd-cdc490915b01 | 4 | @Override
public void run() {
for(int i=0; i<25; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("name->" + info.getName() + " age->" + info.getAge());
}
} |
aba5bde4-3879-46b0-8ab1-9bbd0485bcb6 | 0 | public Long getId() {
return id;
} |
210a9b2d-b6e3-45ae-8c2b-63a85cfccb86 | 1 | public RuleAdaptor(RuleMatcher<T> matcher) {
if (matcher == null) {
throw new IllegalArgumentException(
"The given filter must not be null.");
}
this.matcher = matcher;
} |
03577cbf-61f9-457e-94bb-bbbe4ad8e4f9 | 9 | public void displayQuestions(String urls) throws IOException {
URL url = getClass().getResource(urls);
BufferedReader reader = new BufferedReader(new InputStreamReader(
url.openStream()));
contentPane.removeAll();
for (int i = 0; i < 4; i++) {
label[i] = new JLabel(reader.readLine());
//display first set of questions
if (i == 0) {
label[i].setBounds(10, 26, 500, 32);
for (int j = 0; j < 4; j++) {
radiobutton[i][j] = new JRadioButton(reader.readLine());
radiobutton[i][j].setBounds(10, 65 + (j * 36), 257, 23);
buttonGroup.add(radiobutton[i][j]);
contentPane.add(radiobutton[i][j]);
}
answers[i] = Integer.parseInt(reader.readLine());
}
//display second set of questions
if (i == 1) {
label[i].setBounds(10, 233, 500, 33);
for (int j = 0; j < 4; j++) {
radiobutton[i][j] = new JRadioButton(reader.readLine());
radiobutton[i][j].setBounds(10, 288 + (j * 36), 257, 23);
buttonGroup_1.add(radiobutton[i][j]);
contentPane.add(radiobutton[i][j]);
}
answers[i] = Integer.parseInt(reader.readLine());
}
//display third set of questions
if (i == 2) {
label[i].setBounds(450, 26, 500, 33);
for (int j = 0; j < 4; j++) {
radiobutton[i][j] = new JRadioButton(reader.readLine());
radiobutton[i][j].setBounds(450, 65 + (j * 36), 257, 23);
buttonGroup_2.add(radiobutton[i][j]);
contentPane.add(radiobutton[i][j]);
}
answers[i] = Integer.parseInt(reader.readLine());
}
//display fourth set of questions
if (i == 3) {
label[i].setBounds(450, 233, 500, 33);
for (int j = 0; j < 4; j++) {
radiobutton[i][j] = new JRadioButton(reader.readLine());
radiobutton[i][j].setBounds(450, 288 + (j * 36), 257, 23);
buttonGroup_3.add(radiobutton[i][j]);
contentPane.add(radiobutton[i][j]);
}
answers[i] = Integer.parseInt(reader.readLine());
}
contentPane.add(label[i]);
label[i].setVisible(true);
}
contentPane.add(btnMainMenu);
contentPane.add(submit);
validate();
repaint();
} |
d833ad2b-1a20-4da1-838a-a5bad7a6fffc | 6 | private void rdepth(Graph<VLabel, ELabel> G,
Stack<Graph<VLabel, ELabel>.Vertex> fringe) {
if (fringe.isEmpty()) {
return;
}
Graph<VLabel, ELabel>.Vertex curr = fringe.pop();
try {
if (marked.contains(curr)) {
return;
}
marked.add(curr);
try {
_finalVertex = curr;
visit(curr);
_finalVertex = null;
} catch (RejectException e) {
return;
}
depthLook(G, curr, fringe);
Iteration<Graph<VLabel, ELabel>.Edge> myEdges = G.outEdges(curr);
while (myEdges.hasNext()) {
myEdges.next();
rdepth(G, fringe);
}
} catch (StopException e) {
return;
}
try {
_finalVertex = curr;
postVisit(curr);
_finalVertex = null;
} catch (RejectException e) {
return;
}
} |
b4a32f37-9982-4536-bf4e-162546ae0b99 | 6 | @Test
public void testConnection() {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection(DatabaseSetup.HOST, DatabaseSetup.USER, DatabaseSetup.PASSWORD);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
if (rs.next()) {
System.out.println(rs.getString(1));
}
}
catch (SQLException ex) {
Assert.fail(ex.getMessage());
}
finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
}
catch (SQLException ex) {
Assert.fail(ex.getMessage());
}
}
} |
c89d4178-57eb-4862-a81b-ef3f73c1791e | 9 | public static void main(String[] args) throws NumberFormatException, UnknownHostException {
if (args.length > 1) {
usage();
return;
}
// null server address means bind to everything local
InetAddress serverAddress = null;
int port = NGConstants.DEFAULT_PORT;
// parse the sole command line parameter, which
// may be an inetaddress to bind to, a port number,
// or an inetaddress followed by a port, separated
// by a colon
if (args.length != 0) {
String[] argParts = args[0].split(":");
String addrPart = null;
String portPart = null;
if (argParts.length == 2) {
addrPart = argParts[0];
portPart = argParts[1];
} else if (argParts[0].indexOf('.') >= 0) {
addrPart = argParts[0];
} else {
portPart = argParts[0];
}
if (addrPart != null) {
serverAddress = InetAddress.getByName(addrPart);
}
if (portPart != null) {
port = Integer.parseInt(portPart);
}
}
NGServer server = new NGServer(serverAddress, port);
Thread t = new Thread(server);
t.setName("NGServer(" + serverAddress + ", " + port + ")");
t.start();
Runtime.getRuntime().addShutdownHook(new NGServerShutdowner(server));
// if the port is 0, it will be automatically determined.
// add this little wait so the ServerSocket can fully
// initialize and we can see what port it chose.
int runningPort = server.getPort();
while (runningPort == 0) {
try { Thread.sleep(50); } catch (Throwable toIgnore) {}
runningPort = server.getPort();
}
System.out.println("NGServer started on "
+ ((serverAddress == null)
? "all interfaces"
: serverAddress.getHostAddress())
+ ", port "
+ runningPort
+ ".");
} |
55f93f37-9d46-4609-a95d-ccbbff13abbe | 9 | synchronized Object getPkgProperty(String name, Scriptable start,
boolean createPkg)
{
Object cached = super.get(name, start);
if (cached != NOT_FOUND)
return cached;
String className = (packageName.length() == 0)
? name : packageName + '.' + name;
Context cx = Context.getContext();
ClassShutter shutter = cx.getClassShutter();
Scriptable newValue = null;
if (shutter == null || shutter.visibleToScripts(className)) {
Class cl = null;
if (classLoader != null) {
cl = Kit.classOrNull(classLoader, className);
} else {
cl = Kit.classOrNull(className);
}
if (cl != null) {
newValue = new NativeJavaClass(getTopLevelScope(this), cl);
newValue.setPrototype(getPrototype());
}
}
if (newValue == null && createPkg) {
NativeJavaPackage pkg;
pkg = new NativeJavaPackage(true, className, classLoader);
ScriptRuntime.setObjectProtoAndParent(pkg, getParentScope());
newValue = pkg;
}
if (newValue != null) {
// Make it available for fast lookup and sharing of
// lazily-reflected constructors and static members.
super.put(name, start, newValue);
}
return newValue;
} |
dd72ee30-21f7-46a7-a233-10b52c2062c1 | 9 | public void readFromFile(String file) {
try {
BufferedReader fin = new BufferedReader(
new FileReader((file)));
String line;
while ((line = fin.readLine()) != null) {
line = line.replace("\t", "");
String side[] = line.split("->");
List<String> rhp = null,lhp = null;
if( side.length == 2 ){
lhp = new ArrayList<String>(Arrays.asList(side[0].split(" ")));
lhp.removeAll(Collections.singleton(""));
if( lhp.size() > 1){
productions.clear();
System.err.println("Bad production: "+side[0]+" size must be 1.");
break;
}
rhp = new ArrayList<String>(Arrays.asList(side[1].split(" ")));
rhp.removeAll(Collections.singleton(""));
productions.add(new Production(lhp.get(0), rhp));
}
else{
productions.clear();
System.err.println("Bad line "+line+" size must be 1.");
}
}
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
for(Production p : productions) {
//System.out.println(p.toString());
String left = p.getLeft();
if( !X.contains(p.getLeft())){
X.add(p.getLeft());
}
for ( String s: p.getRight()){
if( !X.contains(s)){
X.add(s);
}
}
}
for ( String s: X){
//System.out.println(s);
}
} |
807ef9d6-6877-4c5f-a003-ccc4d468cb4c | 5 | public static void main(String[] args) {
System.out.println("Lancement du test de la Tablier");
// verification de l'initialisation du tablier
Tablier tab1 = new Tablier();
System.out.println("TABLIER : ");
for(int i=0;i<tab1.getListeCase().size();i++)
System.out.println(tab1.getListeCase().get(i).getPosition()
+" : "+tab1.getListeCase().get(i).getCouleurDame()
+" _ "+tab1.getListeCase().get(i).getNbDame());
System.out.println("CASE VICTOIRE : ");
for(int i=0;i<tab1.getCaseVictoire().size();i++)
System.out.println(tab1.getCaseVictoire().get(i).getPosition()
+" : "+tab1.getCaseVictoire().get(i).getCouleurDame()
+" _ "+tab1.getCaseVictoire().get(i).getNbDame());
System.out.println("CASE BARRE : ");
for(int i=0;i<tab1.getCaseBarre().size();i++)
System.out.println(tab1.getCaseBarre().get(i).getPosition()
+" : "+tab1.getCaseBarre().get(i).getCouleurDame()
+" _ "+tab1.getCaseBarre().get(i).getNbDame());
// test deplacement dame
tab1.deplacerDame(tab1.getListeCase().get(0), tab1.getListeCase().get(1));
tab1.deplacerDame(tab1.getListeCase().get(5), tab1.getListeCase().get(6));
tab1.deplacerDame(tab1.getListeCase().get(5), tab1.getListeCase().get(6));
tab1.deplacerDame(tab1.getListeCase().get(5), tab1.getListeCase().get(6));
tab1.deplacerDame(tab1.getListeCase().get(5), tab1.getListeCase().get(6));
tab1.deplacerDame(tab1.getListeCase().get(0), tab1.getListeCase().get(5));
tab1.deplacerDame(tab1.getListeCase().get(3), tab1.getListeCase().get(5));
System.out.println("TABLIER : ");
for(int i=0;i<tab1.getListeCase().size();i++)
System.out.println(tab1.getListeCase().get(i).getPosition()
+" : "+tab1.getListeCase().get(i).getCouleurDame()
+" _ "+tab1.getListeCase().get(i).getNbDame());
System.out.println("CASE BARRE : ");
for(int i=0;i<tab1.getCaseBarre().size();i++)
System.out.println(tab1.getCaseBarre().get(i).getPosition()
+" : "+tab1.getCaseBarre().get(i).getCouleurDame()
+" _ "+tab1.getCaseBarre().get(i).getNbDame());
} |
013fc2db-42a5-444a-8c7f-0570902fcb5a | 8 | @BeforeClass
public static void setUpBeforeClass() throws Exception {
defaultPhone = new AndroidPhone();
phoneDescription = new HashMap<String, Object>();
phoneDescription.put("name", "Cink Five");
phoneDescription.put("brandName", "Wiko");
phoneDescription.put("screenSize", 5);
phoneDescription.put("screenType", ScreenType.RESISTIV);
phoneDescription.put("version", AndroidPhoneVersion.ECLAIR);
phoneDescription.put("state", State.GOOD);
Map<String, Map<Class<? extends IUser>, Integer>> limitsDescription = new HashMap<String, Map<Class<? extends IUser>, Integer>>();
Map<Class<? extends IUser>, Integer> copyLimitsForFirstPhone = new HashMap<Class<? extends IUser>, Integer>();
copyLimitsForFirstPhone.put(Student.class, new Integer(2));
copyLimitsForFirstPhone.put(Teacher.class, new Integer(10));
Map<Class<? extends IUser>, Integer> delayLimitsForFirstPhone = new HashMap<Class<? extends IUser>, Integer>();
delayLimitsForFirstPhone.put(Student.class, new Integer(2));
delayLimitsForFirstPhone.put(Teacher.class, new Integer(14));
Map<Class<? extends IUser>, Integer> durationLimitsForFirstPhone = new HashMap<Class<? extends IUser>, Integer>();
durationLimitsForFirstPhone.put(Student.class, new Integer(14));
durationLimitsForFirstPhone.put(Teacher.class, new Integer(30));
limitsDescription.put(Material.KEY_LIMIT_COPY, copyLimitsForFirstPhone);
limitsDescription.put(Material.KEY_LIMIT_DELAY,
delayLimitsForFirstPhone);
limitsDescription.put(Material.KEY_LIMIT_DURATION,
durationLimitsForFirstPhone);
phoneDescription.put("limits", limitsDescription);
firstPhone = new AndroidPhone(phoneDescription);
phoneDescription.put("id", "CW99");
secondPhone = new AndroidPhone(phoneDescription);
thirdPhone = new AndroidPhone("Galaxy S4", "Samsung", 5,
ScreenType.CAPACITIV, AndroidPhoneVersion.CUPCAKE, State.GOOD,
limitsDescription);
} |
da5796ab-ec59-4f1c-90d7-cc2ea1b4055f | 7 | public static final boolean isAllowedEverywhere(final MOB mob, final SecFlag flag)
{
if(mob==null)
return false;
if(isASysOp(mob))
return true;
if((mob.playerStats()==null)
||((mob.soulMate()!=null)&&(!mob.soulMate().isAttributeSet(MOB.Attrib.SYSOPMSGS))))
return false;
if(mob.playerStats().getSecurityFlags().contains(flag, false))
return true;
if(mob.baseCharStats().getCurrentClass().getSecurityFlags(mob.baseCharStats().getCurrentClassLevel()).contains(flag, false))
return true;
return false;
} |
c251346c-3ae5-4660-8016-2551516ba74b | 4 | public Shape next() {
switch (rand.nextInt(4)) {
default:
case 0:
return new Circle();
case 1:
return new Square();
case 2:
return new Triangle();
//for ex4
case 3:
return new Rectangle();
}
} |
fb70e32e-8b93-4c32-b245-b929a0921eaf | 6 | * @param maskImage image mask to be applied to base image.
*/
private static void applyExplicitMask(BufferedImage baseImage, BufferedImage maskImage) {
// check to see if we need to scale the mask to match the size of the
// base image.
int baseWidth = baseImage.getWidth();
int baseHeight = baseImage.getHeight();
int maskWidth = maskImage.getWidth();
int maskHeight = maskImage.getHeight();
if (baseWidth != maskWidth || baseHeight != maskHeight) {
// calculate scale factors.
double scaleX = baseWidth / (double) maskWidth;
double scaleY = baseHeight / (double) maskHeight;
// scale the mask to match the base image.
AffineTransform tx = new AffineTransform();
tx.scale(scaleX, scaleY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
BufferedImage sbim = op.filter(maskImage, null);
maskImage.flush();
maskImage = sbim;
}
// apply the mask by simply painting white to the base image where
// the mask specified no colour.
for (int y = 0; y < baseHeight; y++) {
for (int x = 0; x < baseWidth; x++) {
int maskPixel = maskImage.getRGB(x, y);
if (maskPixel == -1 || maskPixel == 0xffffff) {
baseImage.setRGB(x, y, Color.WHITE.getRGB());
}
}
}
// int width = maskImage.getWidth();
// int height = maskImage.getHeight();
// final BufferedImage bi = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
// for (int y = 0; y < height; y++) {
// for (int x = 0; x < width; x++) {
// if (maskImage.getRGB(x,y) != -1){
// bi.setRGB(x, y, Color.red.getRGB());
// }
// else{
// bi.setRGB(x, y, Color.green.getRGB());
// }
// }
// }
// final JFrame f = new JFrame("Test");
// f.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
//
// JComponent image = new JComponent() {
// @Override
// public void paint(Graphics g_) {
// super.paint(g_);
// g_.drawImage(bi, 0, 0, f);
// }
// };
// image.setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
// image.setSize(new Dimension(bi.getWidth(), bi.getHeight()));
//
// JPanel test =new JPanel();
// test.setPreferredSize(new Dimension(1200,1200));
// JScrollPane tmp = new JScrollPane(image);
// tmp.revalidate();
// f.setSize(new Dimension(800, 800));
// f.getContentPane().add(tmp);
// f.validate();
// f.setVisible(true);
} |
c187dceb-6702-438d-8ca2-08446adf1846 | 1 | public void dropRoster(Integer rosterID, javax.swing.TransferHandler.DropLocation dropLocation) {
TripComponent tc = tripList.getSelectedValue();
if (tc == null) {
tc = new TripComponent (MainWindow.tripDB.add ( targetDay.getTime() ));
tripListModel.addElement (tc);
}
tc.getTrip().addRoster(MainWindow.rosterDB.getRosterByID(rosterID));
updateGroupIndex();
tfRoster.setText(MainWindow.tripDB.getRosterCount(targetDay.getTime()) + "/" + availableRosters);
tripList.invalidate();
tripList.repaint();
rosterList.repaint();
} |
5b5ab25d-b027-4a7d-8152-129026644bdc | 3 | public int buildDistribution(int[] bowl, int bowlId, int round)
{
std_dev = 0;
int bowlScore=0;
for (int i = 0; i < 12; i++) {
fruits[i] += (double)(bowl[i])/2;
bowlScore = bowlScore + (bowl[i]*preferences[i]);
dist[i]+=bowl[i]/2.0;
}
double mean = 0;
for(int i=0;i<scoresSeen.size();i++)
{
mean+=scoresSeen.get(i);
}
mean+=bowlScore;
mean/=(scoresSeen.size()+1);
for(int i=0;i<scoresSeen.size();i++)
{
std_dev += (mean-scoresSeen.get(i))*(mean-scoresSeen.get(i));
}
std_dev += (mean-bowlScore)*(mean-bowlScore);
std_dev /= (scoresSeen.size()+1);
std_dev = Math.sqrt(std_dev);
//System.out.println("Standard Deviation: "+std_dev);
//System.out.println("Bowl Score: " + bowlScore);
//System.out.println("Round: "+round);
// bowlsSeen[round]++;
return bowlScore;
} |
cc2ddb1a-84a2-490d-b7f2-9b2aed4a49c8 | 2 | public static String printStream(HttpURLConnection conn){
BufferedReader responseBuffer;
String output, response = null;
try {
responseBuffer = new BufferedReader(new InputStreamReader((conn.getInputStream())));
while ((output = responseBuffer.readLine()) != null) {
response=output;
System.out.println("SERVER ===> "+output);
}
System.out.println(OpenstackNetProxyConstants.ROW_1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
} |
3b046b73-eee8-443c-9810-e964649b5bfe | 9 | public int numDistinct(String S, String T) {
int a = S.length();
int b = T.length();
if (a <b) {
return 0;
}
int[][] tem = new int [a][b];
for (int i = 0;i<a;i++)
for (int j=0;j<b;j++)
tem[i][j] = 0;
if (S.charAt(0) == T.charAt(0)) {
tem [0][0] = 1;
}
for (int i = 1;i < a;i++){
tem [i][0] = tem[i-1][0];
if (S.charAt(i) == T.charAt(0)){
tem[i][0] ++;
}
}
for (int j = 1;j<b;j++){
for (int i = j;i<a;i++){
if (S.charAt(i) == T.charAt(j)) {
tem[i][j] = tem[i-1][j-1]+tem[i-1][j];
}
else {
tem[i][j] = tem[i-1][j];
}
}
}
return tem[a-1][b-1];
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.