method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
7daf9d05-2363-491a-9141-7fe3ff5e0b31 | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IkszorBinaryObject other = (IkszorBinaryObject) obj;
if (!Arrays.equals(decodedValue, other.decodedValue))
return false;
if (!Arrays.equals(encodedValue, other.encodedValue))
return false;
if (!Arrays.equals(symmetricKey, other.symmetricKey))
return false;
return true;
} |
8c0ba5b4-ed1a-4668-af5a-feded20c0e14 | 8 | private Result pDirectAbstractDeclarator$$Tail1(final int yyStart)
throws IOException {
Result yyResult;
int yyBase;
int yyOption1;
Node yyOpValue1;
Action<Node> yyValue;
ParseError yyError = ParseError.DUMMY;
// Alternative 1.
yyResult = pSymbol(yyStart);
if (yyResult.hasValue("[")) {
final String v$g$2 = "[";
final int yyChoice1 = yyResult.index;
// Nested alternative 1.
yyOption1 = yyChoice1;
yyOpValue1 = null;
yyResult = pAssignmentExpression(yyOption1);
yyError = yyResult.select(yyError, yyOption1);
if (yyResult.hasValue()) {
final Node v$el$1 = yyResult.semanticValue();
yyOption1 = yyResult.index;
yyOpValue1 = v$el$1;
}
{ // Start scope for v$g$3.
final Node v$g$3 = yyOpValue1;
yyBase = yyOption1;
yyResult = pSymbol(yyBase);
if (yyResult.hasValue("]")) {
yyValue = new Action<Node>() {
public Node run(Node v$1) {
return GNode.create("DirectAbstractDeclarator", v$1, v$g$2, v$g$3);
}};
return yyResult.createValue(yyValue, yyError);
} else {
yyError = yyError.select("']' expected", yyBase);
}
} // End scope for v$g$3.
// Nested alternative 2.
yyResult = pVariableLength(yyChoice1);
yyError = yyResult.select(yyError);
if (yyResult.hasValue()) {
final Node v$g$4 = yyResult.semanticValue();
yyBase = yyResult.index;
yyResult = pSymbol(yyBase);
if (yyResult.hasValue("]")) {
yyValue = new Action<Node>() {
public Node run(Node v$1) {
return GNode.create("DirectAbstractDeclarator", v$1, v$g$2, v$g$4);
}};
return yyResult.createValue(yyValue, yyError);
} else {
yyError = yyError.select("']' expected", yyBase);
}
}
}
// Alternative 2.
yyResult = pSymbol(yyStart);
if (yyResult.hasValue("(")) {
final String v$g$5 = "(";
yyOption1 = yyResult.index;
yyOpValue1 = null;
yyResult = pParameterTypeList(yyOption1);
yyError = yyResult.select(yyError, yyOption1);
if (yyResult.hasValue()) {
final Node v$el$2 = yyResult.semanticValue();
yyOption1 = yyResult.index;
yyOpValue1 = v$el$2;
}
{ // Start scope for v$g$6.
final Node v$g$6 = yyOpValue1;
yyBase = yyOption1;
yyResult = pSymbol(yyBase);
if (yyResult.hasValue(")")) {
yyValue = new Action<Node>() {
public Node run(Node v$1) {
return GNode.create("DirectAbstractDeclarator", v$1, v$g$5, v$g$6);
}};
return yyResult.createValue(yyValue, yyError);
} else {
yyError = yyError.select("')' expected", yyBase);
}
} // End scope for v$g$6.
}
// Done.
yyError = yyError.select("direct abstract declarator expected", yyStart);
return yyError;
} |
cff5a7a7-89f2-4767-953e-b63248fe653c | 3 | public static void filledCircle(double x, double y, double r) {
if (r < 0) {
throw new IllegalArgumentException("circle radius must be nonnegative");
}
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2 * r);
double hs = factorY(2 * r);
if (ws <= 1 && hs <= 1) {
pixel(x, y);
} else {
offscreen.fill(new Ellipse2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
}
draw();
} |
ac10a55a-3d0c-4634-a7d1-a680f8c1a4aa | 5 | public boolean setPlayer2(Player player) {
boolean test = false;
if (test || m_test) {
System.out.println("Game :: setPlayer2() BEGIN");
}
if (player == null) {
throw new IllegalArgumentException(
"Game::SetPlayer2 - Invalid player type(null) for player2");
}
m_player2 = player;
if (test || m_test) {
System.out.println("Game :: setPlayer2() END");
}
return true;
} |
0dd80b05-9340-4875-9afb-9973a9d753a2 | 1 | @Override
public int getRoll(){
Iterator<IStrategy> it = this.getStrategies().iterator();
int max = 0;
while(it.hasNext()){
max = Math.max(it.next().getRoll(), max);
}
return max;
} |
9aa9377e-2ea0-4509-8b36-736eaaec6904 | 1 | public void addAgent(Agent agent) {
agents.add(agent);
if(this instanceof Connection){
agent.addConnection(this);
} else {
System.out.println(this.toString());
}
} |
d38a6c61-53b0-433d-8454-2323121e24be | 8 | public int maxPoints(Point[] points) {
Map<Double, Integer> statistic = new HashMap<Double, Integer>();
int maxNum = 0;
int duplicate = 1;
double k = 0.0;
for(int i=0; i < points.length; i++) {
statistic.clear();
statistic.put(Double.MIN_VALUE, 0); //itself
duplicate = 1;
for(int j=0; j < points.length; j++) {
if(i == j) continue;
if(points[i].x == points[j].x && points[i].y == points[j].y) {
duplicate++;
continue;
}
k = getK(points[i], points[j]);
if(statistic.containsKey(k)){
statistic.put(k, statistic.get(k) + 1);
}else{
statistic.put(k, 1);
}
}
Collection<Integer> list =statistic.values();
for(Integer element : list) {
if(element + duplicate > maxNum) {
maxNum = element + duplicate;
}
}
}
return maxNum;
} |
4d159c0b-1fd1-4dc7-aaba-ca76d17df606 | 0 | @Override
public boolean hasMoreElements() {
return hasMore;
} |
c282ad39-aeec-4e74-a22b-d26e9342fad3 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUIAdministration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUIAdministration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUIAdministration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUIAdministration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUIAdministration().setVisible(true);
}
});
} |
cdf98f36-3980-489c-8bf3-d4f67aa4857b | 1 | public List<List<Integer>> permute(int[] num) {
length = num.length;
if(length == 0) return result;
flag = new boolean[length]; //init flag
DFS(num); // dfs deep first research
return result; // return
} |
70a2ab0c-0397-4106-8000-080a2e027d97 | 3 | @Test
public void testGetPastMeetingList1()
{
cmInst.addNewPastMeeting(testContactSet, pastDate, "added as NewPastMeeting");
Calendar fDate = Calendar.getInstance();
fDate.setTime(new Date());
fDate.add(Calendar.SECOND, 1);
int fmId = cmInst.addFutureMeeting(testContactSet, fDate);
try {
Thread.sleep(1100);
} catch (InterruptedException e) {
Assert.fail("sleep was interrupted, please rerun tests.");
}
cmInst.addMeetingNotes(fmId, "future meeting convd to Past");
cmInst.addFutureMeeting(testContactSet, futureDate); // should not show up in list
Set<Contact> cSet = cmInst.getContacts(3);
for(Contact testContact : cSet)
{
List<PastMeeting> list = cmInst.getPastMeetingList(testContact);
Assert.assertEquals("added as NewPastMeeting", list.get(0).getNotes());
Assert.assertEquals("future meeting convd to Past", list.get(1).getNotes());
Assert.assertEquals(2, list.size());
}
cSet = cmInst.getContacts(6);
for(Contact testContact : cSet)
{
List<PastMeeting> list = cmInst.getPastMeetingList(testContact);
Assert.assertEquals(0, list.size());
}
} |
3a5588d4-d793-4ac4-a589-d65b9f14275e | 8 | public CoordinateWrapper promptForCoordinates() {
Scanner in = Sudoku260.input;
int x, y;
do {
//Prompt the user for the coordinates:
System.out.println("Enter the coordinates in the format: x y");
String response = in.nextLine();
if(response.equals("q")) {
break;
}
//Split our string by the space:
//For example, if I type A B, it will return an array of ["A", "B"]
String[] coordinates = response.split(" ");
if(coordinates.length == 2) {
try {
x = Integer.parseInt(coordinates[0]);
y = Integer.parseInt(coordinates[1]);
if(x > 0 && x < 10 && y > 0 && y < 10) {
return new CoordinateWrapper(x, y);
}
} catch (NumberFormatException ex) {
}
}
System.out.println("Invalid coordinates.");
} while(true);
return null;
} |
e2c8443d-29c6-4093-be56-e9b06d284b1c | 7 | public void fillWithData()
{
try
{
synchronized (this)
{
if (reader != null)
{
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
while (reader.available() > 0)
{
final int c = reader.read();
if (c == -1)
throw new IOException("Received EOF");
if (c != 0)
bout.write(c);
}
if (bout.size() > 0)
super.addScreenMessage(new String(bout.toByteArray(), "UTF-8"));
}
}
}
catch (final java.net.SocketTimeoutException se)
{
}
catch (final Exception e)
{
super.addScreenMessage("*** Telnet disconnected: " + e.getMessage() + " ***");
super.forceNewMessageScan();
shutdown();
super.forceUpMenu();
super.forceNewMenuRead();
}
} |
9614875d-c9b5-42ed-a910-99e5489b0157 | 1 | public SignatureVisitor visitReturnType() {
endFormals();
if (!hasParameters) {
buf.append('(');
}
buf.append(')');
return this;
} |
2f84bc2b-ca9d-4547-82f3-d51169cd2262 | 9 | public void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.black);
g2d.drawString("START", 30, 250);
int[] c = new int[3];
c[0] = 20;
c[1] = 80;
c[2] = 50;
int[] d = new int[3];
d[0] = 290;
d[1] = 290;
d[2] = 310;
g2d.fillPolygon( c, d, 3 );
g2d.fillRect(40, 250, 20, 40);
g2d.drawString("GOLD AND GLORY", 760, 140);
int[] a = new int[3];
a[0] = 780;
a[1] = 840;
a[2] = 810;
int[] b = new int[3];
b[0] = 180;
b[1] = 180;
b[2] = 200;
g2d.fillPolygon( a, b, 3);
g2d.fillRect(800, 140, 20, 40);
g2d.setColor(Color.DARK_GRAY);
g2d.setStroke(new BasicStroke(6));
if (level == 0)
g2d.drawOval(20, 280, 100, 70);
else if (level == 1) {
g2d.drawLine(80, 310, 210, 310);
g2d.drawOval(210, 290, 45, 50);
}
else if (level == 2) {
g2d.drawLine(255, 310, 405, 290);
g2d.drawOval(405, 260, 50, 60);
}
else if (level == 3) {
g2d.drawLine(455, 280, 470, 250);
g2d.drawOval(470, 220, 55, 60);
}
else if (level == 4) {
g2d.drawLine(525, 250, 540, 250);
g2d.drawOval(540, 230, 50, 40);
}
else if (level == 5) {
g2d.drawLine(580, 260, 605, 275);
g2d.drawOval(600, 270, 40, 50);
}
else if (level == 6) {
g2d.drawLine(640, 275, 705, 275);
g2d.drawOval(705, 250, 70, 60);
}
else if (level == 7) {
g2d.drawLine(770, 295, 790, 300);
g2d.drawOval(790, 290, 80, 40);
}
else if (level == 8) {
g2d.drawLine(810, 290, 805, 275);
g2d.drawOval(760, 180, 180, 120);
}
} |
e575ffb7-baca-4399-9409-13ab88a946f3 | 5 | public static ArrayList<String> words(String line){
if(stopwords.size() == 0)
addStopwords();
ArrayList result = new ArrayList();
String[] words = line.split("[ \t\n,\\.\"!?$~()\\[\\]\\{\\}:;/\\\\<>+=%*]");
for(int i=0; i < words.length; i++){
if(words[i] != null && !words[i].equals("")){
String word = words[i].toLowerCase();
if(!stopwords.contains(word)){
result.add(StemmerHani.stem(word));
}
}
}
return result;
} |
b792f662-a0a9-4df1-92ee-73de431f2758 | 4 | @Override
public void actionPerformed(ActionEvent e)
{
if ("yes".equals(e.getActionCommand()))
{
action.buttonClicked(ButtonClicked.YES_CLICKED);
if (action.removeFrame())
{
frame.dispose();
}
}
if ("no".equals(e.getActionCommand()))
{
action.buttonClicked(ButtonClicked.NO_CLICKED);
if (action.removeFrame())
{
frame.dispose();
}
}
} |
effd6b25-5382-449e-83d5-8bb825034638 | 7 | public int splitBalanced(int[] array) {
if (array == null
|| array.length == 0
|| array.length == 1) {
return -1;
}
int length = array.length;
long leftSum = 0;
long rightSum = 0;
int quit = -1;
for (int i = 1; i < length; i++) {
for (int li = 0; li < i; li++) {
leftSum += array[li];
}
for (int ri = i; ri < length; ri++) {
rightSum += array[ri];
}
if (leftSum == rightSum) {
quit = i;
break;
} else {
leftSum = 0;
rightSum = 0;
}
}
return quit;
} |
e58be9c5-d92d-4618-9104-fb44c4b663bd | 9 | public String getPermutation(int n, int k) {
if (n==1) return "1";
String rs = "";
if(k==1) {
for (int i=1; i<=n; i++){
rs += i;
}
return rs;
}
k = k - 1;
int[] product = new int[8];
product[0] = 1;
for(int i=1; i<8; i++){
product[i] = (i+1) * product[i-1];
}
HashSet<Integer> set = new HashSet<Integer>();
for (int i=1; i<=n; i++) set.add(i);
for(int i=n-1; i>=0; i--){
int digit;
if(i>0) {
digit = k/product[i-1];
k = k%product[i-1];
}
else digit = 0;
//System.out.println("digit:"+digit);
//System.out.println(set);
int j = 0;
while (digit>=0){
j++;
if(set.contains(j)){
digit--;
}
}
rs += j;
set.remove(j);
}
return rs;
} |
75841b4e-8a8f-44cc-80c0-e6b1c93ce5ec | 5 | public State[] getStatesOnTerminal(String terminal, State[] states,
Automaton automaton) {
ArrayList list = new ArrayList();
for (int k = 0; k < states.length; k++) {
State state = states[k];
Transition[] transitions = automaton.getTransitionsFromState(state);
for (int i = 0; i < transitions.length; i++) {
FSATransition transition = (FSATransition) transitions[i];
if (transition.getLabel().equals(terminal)) {
State toState = transition.getToState();
State[] closure = ClosureTaker.getClosure(toState,
automaton);
for (int j = 0; j < closure.length; j++) {
if (!list.contains(closure[j])) {
list.add(closure[j]);
}
}
}
}
}
return (State[]) list.toArray(new State[0]);
} |
084b4212-8a6e-4e09-9255-2a5f66c67c83 | 0 | @Override
public EntityManager getEntityManager() {
return super.getEntityManager();
} |
7a44938a-2a63-4640-bd1a-b6e634e6f158 | 4 | @Override
public boolean isInsideCircle(int cX, int cY, int rad, FieldObject fo) {
int dx = cX - fo.getX();
int dy = cY - fo.getY();
boolean insSq = Math.abs(dx) <= rad && Math.abs(dy) <= rad;
if (!insSq) { return false; }
if (dx * dy < 0) { return true; }
int stX = Math.max(cX - rad, 0);
int stY = Math.max(cY - rad, 0);
int diagX = fo.getX() - stX;
int diagY = fo.getY() - stY;
return (rad <= diagX + diagY) && (diagX + diagY <= 3*rad);
} |
1974306c-d234-4467-af8c-a788a095b102 | 9 | private void playGame()
{
gameCurrentlyRunning = true;
//infinite game!!
while(true)
{
if(currentGame == totalLevels){
JOptionPane.showMessageDialog( null, "Thanks for playing Asteroids! Congrats on battling the asteroid belt.\nRestart game..." );
//gameCurrentlyRunning = false;
currentGame = -1;
break;
}
// Measure the current time in an effort to keep up a consistent
// frame rate
long time = System.currentTimeMillis();
// If the ship has been dead for more than 3 seconds, revive it
if(shipDead && shipTimeOfDeath + 3000 < time)
{
shipDead = false;
ship = new Ship(playWidth/2, playHeight/2, 0, 0);
}
// Process game events, move all the objects floating around,
// and update the display
if(!shipDead)
handleKeyEntries();
handleCollisions();
moveSpaceObjects();
if(comets.isEmpty()){
//still have more levels to play
if(currentGame+1 != totalLevels);
else{
JOptionPane.showMessageDialog( null, "Thanks for playing Asteroids! Congrats on battling the asteroid belt.\nRestart game..." );
//gameCurrentlyRunning = false;
//break;
currentGame = -1;
}
if(currentGame+1 >= maxLevelPlayed) maxLevelPlayed = currentGame+2;
String label = "Level " + (currentGame+2) + " ready. Click okay to continue.";
JOptionPane.showMessageDialog( null, label);
currentGame++;
nextLevel(currentGame);
}
// Sleep until it's time to draw the next frame
// (i.e. 32 ms after this frame started processing)
try
{
long delay = Math.max(0, 32-(System.currentTimeMillis()-time));
Thread.sleep(delay);
}
catch(InterruptedException e)
{
}
}
} |
ffe287ce-ddc5-43ad-bd40-17b719f28571 | 4 | public static void loadFonkozeBase(){
ImD1 = new ImportDriver1("//localhost/fonkoze","root","");
if(ImD1.verifyConnection()){
try{
result=ImD1.executer("SELECT * FROM membre");
if(result !=null){
while(result.next()){
System.out.println("id: "+result.getInt("id"));
System.out.println("NumeroMembre: "+result.getString("numero_membre"));
System.out.println("Nom: "+result.getString("nom"));
System.out.println("Prenom: "+result.getString("prenom"));
System.out.println("Centre: "+result.getString("prenom"));
System.out.println("Telephone: "+result.getString("telephone"));
System.out.println("Adresse: "+result.getString("adresse")+"\n");
}
}
else{
System.out.println("the database is empty");
}
} catch(SQLException ex){
Logger.getLogger(ImportDriver.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
System.out.println("Connection failed !!!");
}
} |
ef96bce1-30b0-486a-9a19-ad95a3163585 | 2 | public void addReturn(CtClass type) {
if (type == null)
addOpcode(RETURN);
else if (type.isPrimitive()) {
CtPrimitiveType ptype = (CtPrimitiveType)type;
addOpcode(ptype.getReturnOp());
}
else
addOpcode(ARETURN);
} |
db8106be-11ba-4c2d-a658-d3c8421dd9f9 | 2 | public void setKickingDistance(float newDistance) {
if (newDistance <= 1.0f && newDistance > 0.0f)
kickingDistance = newDistance;
} |
fa74d193-0b58-4cb7-ac16-e8f040839b38 | 6 | public static Ptg calcNormsInv( Ptg[] operands )
{
if( operands.length != 1 )
{
return PtgCalculator.getValueError();
}
try
{
double x = operands[0].getDoubleVal();
if( (x < 0) || (x > 1) )
{
return new PtgErr( PtgErr.ERROR_NUM );
}
/*
* the algorithm is supposed to iterate over NORMSDIST values using Newton-Raphson's approximation
* Newton-Raphson uses an iterative process to approach one root of a function (i.e the zero of the function or
* where the function = 0)
* Newton-Raphson is in the form of:
*
* Xn+1= Xn- (f(xn)/f'(xn)
* where Xn is the current known X value, f(xn) is the value of the function at X, f'(Xn) is the derivative or slope
* at X, Xn+1 is the next X value. Essentially, f'(xn) represents (f(x)/delta x) so f(xn)/f'(xn)== delta x.
* the more iterations we run over, the closer delta x will be to 0.
*
* The Newton-Raphson method does not always work, however. It runs into problems in several places.
What would happen if we chose an initial x-value of x=0? We would have a "division by zero" error, and would not be able to proceed.
You may also consider operating the process on the function f(x) = x1/3, using an inital x-value of x=1.
Do the x-values converge? Does the delta-x decrease toward zero (0)?
is the derivative of the standard normal distribution = the standard probability density function???
*/
/* below is not accurate enough - but N-R approximation is impossible ((:*/
// Coefficients in rational approximations
double[] a = new double[]{
-3.969683028665376e+01,
2.209460984245205e+02,
-2.759285104469687e+02,
1.383577518672690e+02,
-3.066479806614716e+01,
2.506628277459239e+00
};
double[] b = new double[]{
-5.447609879822406e+01, 1.615858368580409e+02, -1.556989798598866e+02, 6.680131188771972e+01, -1.328068155288572e+01
};
double[] c = new double[]{
-7.784894002430293e-03,
-3.223964580411365e-01,
-2.400758277161838e+00,
-2.549732539343734e+00,
4.374664141464968e+00,
2.938163982698783e+00
};
double[] d = new double[]{
7.784695709041462e-03, 3.224671290700398e-01, 2.445134137142996e+00, 3.754408661907416e+00
};
// Define break-points.
double plow = 0.02425;
double phigh = 1 - plow;
double result;
// Rational approximation for lower region:
if( x < plow )
{
double q = Math.sqrt( -2 * Math.log( x ) );
BigDecimal r = new BigDecimal( ((((((((((c[0] * q) + c[1]) * q) + c[2]) * q) + c[3]) * q) + c[4]) * q) + c[5]) / ((((((((d[0] * q) + d[1]) * q) + d[2]) * q) + d[3]) * q) + 1) );
r.setScale( 15, java.math.RoundingMode.HALF_UP );
return new PtgNumber( r.doubleValue() );
}
// Rational approximation for upper region:
if( phigh < x )
{
double q = Math.sqrt( -2 * Math.log( 1 - x ) );
BigDecimal r = new BigDecimal( -((((((((((c[0] * q) + c[1]) * q) + c[2]) * q) + c[3]) * q) + c[4]) * q) + c[5]) / ((((((((d[0] * q) + d[1]) * q) + d[2]) * q) + d[3]) * q) + 1) );
r.setScale( 15, java.math.RoundingMode.HALF_UP );
return new PtgNumber( r.doubleValue() );
}
// Rational approximation for central region:
double q = x - 0.5;
double r = q * q;
BigDecimal rr = new BigDecimal( (((((((((((a[0] * r) + a[1]) * r) + a[2]) * r) + a[3]) * r) + a[4]) * r) + a[5]) * q) / ((((((((((b[0] * r) + b[1]) * r) + b[2]) * r) + b[3]) * r) + b[4]) * r) + 1) );
rr.setScale( 15, java.math.RoundingMode.HALF_UP );
return new PtgNumber( rr.doubleValue() );
}
catch( Exception e )
{
return PtgCalculator.getValueError();
}
} |
3ab251b2-be85-48a3-bf6c-68e0c0b97bab | 4 | public String getColumnName(int i) throws Exception {
String colName = null;
if (i == 0)
colName = "personID";
else if (i == 1)
colName = "name";
else if (i == 2)
colName = "projectID";
else if (i == 3)
colName = "role";
else
throw new Exception("Access to invalid column number in courselist table");
return colName;
} |
6befb169-7a77-4f04-ad8b-da22eaa6bfcf | 4 | public Currency search(String token) {
for (Currency currency : CurrencySet.getInstance()) {
if (currency.getCode().toLowerCase().equals(token.toLowerCase()))
return currency;
if (currency.getSymbol().toLowerCase().equals(token.toLowerCase()))
return currency;
if (currency.getName().toLowerCase().equals(token.toLowerCase()))
return currency;
}
return null;
} |
9076d5f5-c034-4d60-9a05-7d795249cfdc | 2 | public static RailSubmodesOfTransportEnumeration fromValue(String v) {
for (RailSubmodesOfTransportEnumeration c: RailSubmodesOfTransportEnumeration.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
} |
70ac114d-c8ab-46af-ae05-e4e76e9ce5fe | 6 | private static boolean verifyRunningReplica(Task task, OurSim ourSim) {
int running = 0;
for (Replica replica : task.getReplicas()) {
ExecutionState replicaState = replica.getState();
if (ExecutionState.RUNNING.equals(replicaState) || ExecutionState.UNSTARTED.equals(replicaState)) {
running++;
}
}
int maxReplicas = ourSim.getIntProperty(Configuration.PROP_BROKER_MAX_REPLICAS);
int maxSimultaneousReplicas = ourSim.getIntProperty(Configuration.PROP_BROKER_MAX_SIMULTANEOUS_REPLICAS);
return task.getReplicas().size() < maxReplicas && running < maxSimultaneousReplicas
&& (ExecutionState.RUNNING.equals(task.getState()) || ExecutionState.UNSTARTED.equals(task.getState()));
} |
c123027f-e66f-4cc7-8f62-7432af1edbb0 | 6 | @SuppressWarnings("deprecation")
@EventHandler
public void onPlayerInteractBlock(PlayerInteractEvent event)
{
if(event.getPlayer().hasPermission("skeptermod.useitem.warhammer") || (event.getPlayer().isOp()))
if(event.getPlayer().getItemInHand().getTypeId() == Material.GOLD_AXE.getId() && event.getPlayer().getItemInHand().getEnchantmentLevel(Enchantment.ARROW_DAMAGE) == 1 && (event.getAction().equals(Action.RIGHT_CLICK_AIR) || event.getAction().equals(Action.RIGHT_CLICK_BLOCK)))
{
event.getPlayer().getWorld().strikeLightning(event.getPlayer().getTargetBlock(null, 20).getLocation());
event.getPlayer().getWorld().strikeLightning(event.getPlayer().getTargetBlock(null, 20).getLocation());
event.getPlayer().getWorld().strikeLightning(event.getPlayer().getTargetBlock(null, 20).getLocation());
event.getPlayer().getWorld().strikeLightning(event.getPlayer().getTargetBlock(null, 20).getLocation());
event.getPlayer().getWorld().strikeLightning(event.getPlayer().getTargetBlock(null, 20).getLocation());
event.getPlayer().getWorld().strikeLightning(event.getPlayer().getTargetBlock(null, 20).getLocation());
event.getPlayer().getWorld().strikeLightning(event.getPlayer().getTargetBlock(null, 20).getLocation());
event.getPlayer().getWorld().strikeLightning(event.getPlayer().getTargetBlock(null, 20).getLocation());
event.getPlayer().getWorld().createExplosion(event.getPlayer().getTargetBlock(null, 20).getLocation(), 8.0F, true);
}
} |
1ea751ce-a3b2-4b79-9a1b-fb20d7023508 | 5 | public void setLine(Line line) {
if (line.getPoint0() == this || line.getPoint1() == this) {
haveLine = true;
this.line = line;
if (this == line.getPoint0()) {
if (line.getPoint0().getX() == line.getPoint1().getX()) { //Для вертикальных прямых
isLeft = line.getPoint0().getY() < line.getPoint1().getY();
} else {
isLeft = line.getPoint0().getX() < line.getPoint1().getX();
}
} else {
if (line.getPoint0().getX() == line.getPoint1().getX()) {
isLeft = line.getPoint0().getY() > line.getPoint1().getY();
} else {
isLeft = line.getPoint0().getX() > line.getPoint1().getX();
}
}
} else {
throw new IllegalArgumentException("Точка не лежит на концах отрезка");
}
} |
58d0316a-37f8-4c29-8ba4-9ad4645a293a | 1 | private void read_page (PageId pageno, Page page) throws
BufMgrException {
try {
SystemDefs.JavabaseDB.read_page(pageno, page);
} catch (Exception e) {
throw new BufMgrException(e, "BUFMGR: read_page() failed");
} // end try
} // end read_page() |
dbfefd38-8508-4b55-b38e-28ab0dd0d011 | 8 | @Override
public ArrayList< DefaultConfig > loadConfig( String configPath )
{
ArrayList< DefaultConfig > result = new ArrayList< DefaultConfig >();
File config = null;
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader reader = null;
String line = null;
String name = null;
DefaultConfig item = null;
try
{
config = new File( configPath );
fis = new FileInputStream( config );
isr = new InputStreamReader( fis, "UTF-8" );
reader = new BufferedReader( isr );
while ( (line = reader.readLine()) != null )
{
line = line.trim().substring( 0, line.indexOf( "#" ) );
if ( line.length() == 0 )
{
continue;
}
if ( line.charAt( 0 ) == '[' )
{
if ( item != null )
{
result.add( item );
}
name = line.substring( 1, line.lastIndexOf( "]" ) ).trim();
item = new DefaultConfig();
item.setName( name );
continue;
}
String[] split = line.split( "=" );
if ( split.length >= 2 )
{
if ( item != null )
{
item.setParamater( split[ 0 ].trim(), split[ 1 ].trim() );
}
else
{
reader.close();
isr.close();
fis.close();
throw new IllegalArgumentException(
"Invalid config file!" );
}
}
}
result.add( item );
reader.close();
isr.close();
fis.close();
return result;
}
catch ( IllegalArgumentException e )
{
log.logToConsole( "Invalid config file!", LogCollector.ERROR );
log.logToConsole( e.getMessage(), LogCollector.ERROR );
return result;
}
catch ( IOException e )
{
// TODO Auto-generated catch block
log.logToConsole( "Failed to open config file!", LogCollector.ERROR );
log.logToConsole( e.getMessage(), LogCollector.ERROR );
return result;
}
} |
b625273f-285c-4cc7-9501-f8e75aa06008 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (firstname == null) {
if (other.firstname != null)
return false;
} else if (!firstname.equals(other.firstname))
return false;
if (lastname == null) {
if (other.lastname != null)
return false;
} else if (!lastname.equals(other.lastname))
return false;
return true;
} |
44bad31a-be36-416f-b42f-77c173bb9dc4 | 8 | * @param end
* @param dict
* @return
*/
public ArrayList<ArrayList<String>> findLadders(String start, String end, HashSet<String> dict) {
ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
dict.add(end);
int size = dict.size();
ArrayList<String> queue = new ArrayList<String>();
ArrayList<Integer> parent = new ArrayList<Integer>();
HashMap<String, Boolean> visited = new HashMap<String, Boolean>();
for (String s : dict) {
visited.put(s, false);
}
queue.add(start);
parent.add(-1);
int cur = 0;
while (cur < queue.size()) {
String current = queue.get(cur);
for (String neighbor : neighbors(current, dict, visited)) {
if (neighbor.equals(end)) {
ArrayList<String> list = new ArrayList<String>();
list.add(neighbor);
int p = cur;
while (p != -1) {
list.add(0, queue.get(p));
p = parent.get(p);
}
if (result.size() == 0 || result.get(0).size() == list.size()) {
result.add(list);
} else if (list.size() < result.get(0).size()) {
result.clear();
result.add(list);
}
visited.put(neighbor, false);
} else {
queue.add(neighbor);
parent.add(cur);
visited.put(neighbor, true);
}
}
cur++;
}
return result;
} |
c5194db3-5ae2-41cb-b0f3-8a4430541058 | 3 | @Override
public void run() {
while(running){
try{
if(inStream.available() > 0){
gameTime = inStream.readDouble();
//playerArray = (int[][]) inStream.readObject();
}
} catch(Exception e){
e.printStackTrace();
}
}
} |
1839e2a1-a037-43fb-9364-8058189689a4 | 1 | public Placeable getRandomPlacable() {
Placeable p = null;
Object[] ks = placeables.keySet().toArray();
if (ks.length > 0) {
String s = ks[Rand.getRange(0, ks.length - 1)].toString();
p = placeables.get(s);
}
return p;
} |
657809cf-995e-4bae-9fa6-3f7bbd016cf2 | 1 | @Override
public void connect() throws Exception {
if (remoteClientCall == null) {
throw new IllegalStateException("RemoteClientConnection is not initial.");
}
remoteClientCall.connect();
} |
69518e2c-5fd1-4a6b-bce0-93baaffe9f23 | 4 | private Vector2 SnapToGrid(Vector2 mouse)
{
if (mouse.X % gridW[mode] != 0)
{
if (mouse.X < 0)
mouse.X -= gridW[mode];
mouse.X = ((int) (mouse.X / gridW[mode])) * gridW[mode];
}
if (mouse.Y % gridH[mode] != 0)
{
if (mouse.Y < 0)
mouse.Y -= gridH[mode];
mouse.Y = ((int) (mouse.Y / gridH[mode])) * gridH[mode];
}
return mouse;
} |
e53c28fd-58b7-4d0a-bf2e-1fc184e03694 | 1 | public void start() {
if (state == EnumStopWatchState.STOP) {
timer = new Timer(NAME);
timer.scheduleAtFixedRate(this, 0, 1000);
state = EnumStopWatchState.RUNNING;
log.info("start stopwatch, it's state:" + state + ", elapseTime:"
+ elapseTime);
}
} |
aa36f9eb-c682-491b-8078-4a03b34cbc7c | 2 | public File getTransactionFile(String name) {
for (File f : getTransactionFiles()) {
main.debug("Comparing " + f.getName() + " to " + name + ".yml");
if (f.getName().equals(name + ".yml")) {
return f;
}
}
return null;
} |
a1482d95-de75-4c5d-ab48-95fa981a5b9f | 6 | protected void updateTable(String name, Map<String, String> columns) throws SQLException {
PreparedStatement statement = null;
try {
StringBuilder builder = new StringBuilder();
builder.append("CREATE TABLE IF NOT EXISTS ? (");
for (int i = 0; i < columns.size(); i++) {
builder.append("? ?");
if (i + 1 < columns.size()) {
builder.append(", ");
}
}
builder.append(")");
statement = getConnection().prepareStatement(builder.toString());
statement.execute();
} catch (SQLException e) {
throw e;
} catch (DataLoadFailedException e) {
throw new SQLException(e);
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
}
}
}
} |
73991ddd-17db-4c69-9c20-3260f602411e | 0 | @Override
public void clearAppenders() {
doClearAppenders();
} |
8d0f1afb-e41d-4bc5-a86d-3baf9290b677 | 2 | public void addInputCallPanel(final String remoteChannel, final String localChannel){
if(remoteChannel!=null&&localChannel!=null){
final String remoteNumber = remoteChannel.substring(0,remoteChannel.indexOf("-"));
JPanel panel = new JPanel();
answerButton = new JButton("Ответить");
answerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
HoldIfNotActive();
Answer(remoteChannel);
}
});
answerButton.setPreferredSize(new Dimension(170, 80));
answerButton.setBackground(new Color(0,30,0));
answerButton.setForeground(new Color(255,255,255));
answerButton.setFont(buttonFont);
panel.add(answerButton);
JButton hangupButton = new JButton("Завершить");
hangupButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
Hangup(remoteChannel);
}
});
hangupButton.setPreferredSize(new Dimension(170, 80));
hangupButton.setBackground(new Color(100,0,0));
hangupButton.setForeground(new Color(255,255,255));
hangupButton.setFont(buttonFont);
panel.add(hangupButton);
addPanel(remoteNumber,null,panel);
CallFrame.MakeFramesNotEnable(false);
new CallFramesTrue().start();
}
else {
removeFromList(this);
setVisible(false);
dispose();
}
} |
abf3d01e-4b40-41c7-9442-344617a1a02c | 5 | JComponent getBankingTab() {
JPanel inner = new JPanel(new GridBagLayout());
GridBagConstraints innerConstraints = new GridBagConstraints();
innerConstraints.fill = GridBagConstraints.BOTH;
innerConstraints.gridx = 0;
innerConstraints.gridy = 0;
innerConstraints.weightx = 1;
innerConstraints.gridwidth = 3;
{
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
constraints.gridy = 0;
panel.add(new JLabel("You must have a failsafe method enabled (in case script forgets an item while banking)", JLabel.CENTER), constraints);
constraints.gridy++;
panel.add(new JLabel("[F] = Failsafe method (should never fail)", JLabel.CENTER), constraints);
constraints.gridy++;
JLabel label = new JLabel("Green has obelisk", JLabel.CENTER);
label.setFont(label.getFont().deriveFont(Font.BOLD));
label.setForeground(new Color(0, 102, 51));
panel.add(label, constraints);
inner.add(panel, innerConstraints);
}
innerConstraints.weighty = 1;
innerConstraints.gridwidth = 1;
innerConstraints.gridy++;
{
JPanel disabledTitle = new JPanel(new BorderLayout());
disabledTitle.setBorder(new CompoundBorder(new TitledBorder("Disabled Methods"), new EmptyBorder(5, 5, 5, 5)));
JScrollPane scrollPane = new JScrollPane(disabledBank);
disabledTitle.setPreferredSize(new Dimension(50, 50));
disabledTitle.add(scrollPane);
inner.add(disabledTitle, innerConstraints);
}
innerConstraints.gridx++;
innerConstraints.weightx = 0;
{
JPanel centerPane = new JPanel(new GridBagLayout());
GridBagConstraints centerConstraints = new GridBagConstraints();
centerConstraints.fill = GridBagConstraints.HORIZONTAL;
centerConstraints.gridy = 0;
centerPane.add(addBank, centerConstraints);
centerConstraints.gridy = 1;
centerPane.add(removeBank, centerConstraints);
inner.add(centerPane, innerConstraints);
}
innerConstraints.gridx++;
innerConstraints.weightx = 1;
{
JPanel enabledTitle = new JPanel(new BorderLayout());
enabledTitle.setBorder(new CompoundBorder(new TitledBorder("Enabled Methods"), new EmptyBorder(5, 5, 5, 5)));
enabledBank.setVisibleRowCount(-1);
enabledBank.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
enabledBank.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferSupport support) {
if (!support.isDrop()) {
return false;
}
support.setShowDropLocation(true);
JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
return dl.getIndex() >= 0 && dl.getIndex() <= enabledBank.getModel().getSize();
}
@Override
public boolean importData(TransferSupport support) {
if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
return false;
}
JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
int index = dl.getIndex();
java.util.List list = Arrays.asList(enabledBank.getSelectedValues());
for (int i = list.size() - 1; i >= 0; i--) {
final Object o = list.get(i);
if (index > bankEnabledModel.indexOf(o)) {
index--;
}
bankEnabledModel.removeElement(o);
bankEnabledModel.insertElementAt(o, index);
index = bankEnabledModel.indexOf(o);
}
return true;
}
@Override
public int getSourceActions(JComponent component) {
return MOVE;
}
@Override
protected Transferable createTransferable(JComponent component) {
return new StringSelection("");
}
});
enabledBank.setDropMode(DropMode.INSERT);
enabledBank.setDragEnabled(true);
JScrollPane scrollPane = new JScrollPane(enabledBank);
enabledTitle.setPreferredSize(new Dimension(50, 50));
enabledTitle.add(scrollPane, BorderLayout.CENTER);
enabledTitle.add(new JLabel("Drag to set priority (highest at top)", JLabel.CENTER), BorderLayout.SOUTH);
inner.add(enabledTitle, innerConstraints);
}
return inner;
} |
ae3dcb39-73ed-46b8-ac19-a805e5864d56 | 0 | @AfterClass
public static void tearDownClass() {
} |
122ec0d1-af94-47db-b06b-7997c1f77ee6 | 2 | public static Storyboard findStoryboardById(ArrayList<Storyboard> storyboards, int id) {
for(Storyboard storyboard:storyboards) {
if(storyboard.getId()==id) {
return storyboard;
}
}
return new Storyboard();
} |
2166a610-d71a-4f74-ba96-79bf4635c790 | 7 | @Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == browse) {
JFileChooser chooser = new JFileChooser();
int approve = chooser.showOpenDialog(null);
if(approve == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
if(e.getSource() == browse) {
ids.setText(selectedFile.getAbsolutePath());
}
if(e.getSource() == browse2) {
try {
Desktop.getDesktop().open(new File(location));
} catch (IOException e1) {
e1.printStackTrace();
}
//prizes.setText(selectedFile.getAbsolutePath());
}
}
}
if(e.getSource() == browse2) {
try {
Desktop.getDesktop().open(new File(location));
} catch (IOException e1) {
e1.printStackTrace();
}
}
} |
e4e12321-4f92-4d63-86e2-b8926d779fbc | 0 | @Override
protected void finalize() throws Throwable {
stat.close();
conn.close();
super.finalize();
} |
0a13c6a9-d717-45b9-a5dc-9b2a2c30f758 | 9 | protected void applyToTitle(Title title) {
if (title instanceof TextTitle) {
TextTitle tt = (TextTitle) title;
tt.setFont(this.largeFont);
tt.setPaint(this.subtitlePaint);
}
else if (title instanceof LegendTitle) {
LegendTitle lt = (LegendTitle) title;
if (lt.getBackgroundPaint() != null) {
lt.setBackgroundPaint(this.legendBackgroundPaint);
}
lt.setItemFont(this.regularFont);
lt.setItemPaint(this.legendItemPaint);
if (lt.getWrapper() != null) {
applyToBlockContainer(lt.getWrapper());
}
}
else if (title instanceof PaintScaleLegend) {
PaintScaleLegend psl = (PaintScaleLegend) title;
psl.setBackgroundPaint(this.legendBackgroundPaint);
ValueAxis axis = psl.getAxis();
if (axis != null) {
applyToValueAxis(axis);
}
}
else if (title instanceof CompositeTitle) {
CompositeTitle ct = (CompositeTitle) title;
BlockContainer bc = ct.getContainer();
List<Block> blocks = bc.getBlocks();
for (Block b : blocks) {
if (b instanceof Title) {
applyToTitle((Title) b);
}
}
}
} |
4e4c7c65-2fa1-4194-a879-fbeae7722773 | 4 | @Override
public void deleteDirectory(String directory)
{
if (!dirEntries.containsKey(directory.toLowerCase())) return;
DirEntry de = dirEntries.get(directory.toLowerCase());
DirEntry parent = de.parentDir;
if (parent != null)
parent.childrenDirs.remove(de);
dirEntries.remove(directory.toLowerCase());
for (DirEntry cde : de.childrenDirs)
dirEntries.remove(cde.fullName.toLowerCase());
for (FileEntry cfe : de.childrenFiles)
fileEntries.remove(cfe.fullName.toLowerCase());
} |
907d8d5c-58e8-43ae-92a4-a1104d77207a | 9 | public static void main(String[] args) {
Socket clientSocket = null;
DataInputStream in = null;
PrintStream out = null;
DataInputStream inputLine = null;
//open a socket on port 6001
try {
clientSocket = new Socket("localhost", 6001);
out = new PrintStream(clientSocket.getOutputStream());
in = new DataInputStream(clientSocket.getInputStream());
inputLine = new DataInputStream(new BufferedInputStream(System.in));
} catch (UnknownHostException e) {
System.err.println("unknown server");
} catch (IOException e) {
System.err.println("Connection to server failed");
}
if (clientSocket != null && out != null && in != null) {
try {
//keep reading data until *
System.out.println("The client started. Type any text. To quit it type '*'.");
String responseLine;
out.println(inputLine.readLine());
while ((responseLine = in.readLine()) != null) {
System.out.println(responseLine);
if (responseLine.indexOf("*") != -1) {
break;
}
out.println(inputLine.readLine());
}
//close input, output and the socket
out.close();
in.close();
clientSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown server: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
} |
ba6dc45b-ee77-48ff-8af9-a923376c0b2f | 1 | public boolean ModificarTrabajo(Trabajo p){
if (p!=null) {
cx.Modificar(p);
return true;
}else {
return false;
}
} |
cbd4908c-feee-4fd2-aef3-b368efb0af91 | 9 | private void execute() {
if(newWorkspace == null && removedImports.size() == 0) {
for(String newImport : addedImports) {
doImport(newImport);
}
imported.addAll(addedImports);
addedImports.clear();
if(imported.size() > 0 && reloadImportButton != null)
reloadImportButton.setEnabled(true);
return;
}
//Restart required.
if(newWorkspace != null) {
Settings.setProperty("workspace", newWorkspace.toString());
evaluator.setWorkspace(newWorkspace);
newWorkspace = null;
}
evaluator.clear(); //restart
replPanel.clearScreen();
imported.removeAll(removedImports);
removedImports.clear();
imported.addAll(addedImports);
addedImports.clear();
for(String toImport : imported) {
doImport(toImport);
}
if(imported.size() > 0 && reloadImportButton != null)
reloadImportButton.setEnabled(true);
} |
63e8e741-eca9-47b7-840d-d97e87e86aca | 8 | static final public void instruction() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ident:
affectation();
break;
case LIRE:
lecture();
break;
case ECRIRE:
case ALALIGNE:
ecriture();
break;
case SI:
conditionnelle();
break;
case TANTQUE:
iteration();
break;
case RETOURNE:
retourne();
break;
default:
jj_la1[13] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
} |
b157efd0-b417-4f19-8958-4ef88cff70c1 | 0 | public void setLoaded(boolean loaded) {
this.loaded = loaded;
} |
e7668951-81a1-495f-a9c0-82a97338b1ee | 7 | public GameWindow(Game game) {
boolean test = false;
if (test || m_test) {
System.out.println("GameWindow :: GameWindow() BEGIN");
}
boolean m_Trace = false;
if(m_Trace) System.out.println
("GameWindow::GameWindow() - window initializing");
if(m_Trace) System.out.println
("GameWindow::GameWindow() - Linked game is " + game.getClass());
GridBagConstraints c = new GridBagConstraints();
GridBagLayout layout = new GridBagLayout();
setGame(game);
setDrawing(new Drawing(m_gameControl));
setControls(new Controls(this));
setLayout(layout);
JComponent grid = getDrawing().getGridPanel();
c.gridx = 0;
c.gridy = 0;
layout.setConstraints(grid, c);
add(grid);
c.gridx = 1;
layout.setConstraints(getDrawing().getSideBarPanel(), c);
add(getDrawing().getSideBarPanel());
m_menubar = new JMenuBar();
add(m_menubar);
m_newGame = new JMenuItem("New Game");
m_menubar.add(m_newGame);
m_resetGame = new JMenuItem("Restart Game");
m_menubar.add(m_resetGame);
m_save = new JMenuItem("Save");
m_menubar.add(m_save);
m_load = new JMenuItem("Load");
m_menubar.add(m_load);
m_exit = new JMenuItem("Exit");
m_menubar.add(m_exit);
setJMenuBar(m_menubar);
Handler handler = new Handler();
m_newGame.addActionListener(handler);
m_resetGame.addActionListener(handler);
m_save.addActionListener(handler);
m_load.addActionListener(handler);
m_exit.addActionListener(handler);
setTitle("Boardgame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
if(m_Trace) { System.out.println
("GameWindow::GameWindow() - window initialized");
}
if (test || m_test) {
System.out.println("GameWindow :: GameWindow() END");
}
} |
31f36be5-8354-444c-b689-97c30545a986 | 5 | public static Properties readConf(String s) {
File f = new File(s);
System.out.println(s);
if (f.exists() && f.canRead()) {
try {
String s1 = null;
BufferedReader read = new BufferedReader(new FileReader(f));
while ((s1 = read.readLine()) != null) {
if (s1.startsWith("#")) {
} else {
prop = new Properties();
prop.load(new FileInputStream(f));
Config.setMyProperties(prop);
}
}
read.close();
} catch (IOException io) {
io.printStackTrace();
}
}
return prop;
} |
98ca3da1-3537-4e60-8594-9025a6eafc02 | 8 | @Override
protected void drawData(Graphics g) {
if(graphValues == null) return;
int X, Y;
int lastX = Integer.MIN_VALUE;
int highestValue = bufferYmax;
int lowestValue = bufferYmin;
if (lowestValue <= highestValue){
//jLabelVMin.setText("" + lowestValue);
jLabelVMin.setText("" + labelFormat.format(lowestValue * scale));
//jLabelVMax.setText("" + highestValue);
jLabelVMax.setText("" + labelFormat.format(highestValue * scale));
}
int w = computeX(1)- computeX(0) + 1;
g.setColor(color);
Graphics2D g2 = (Graphics2D)g;
Stroke s = g2.getStroke();
g2.setStroke(new BasicStroke(w));
for(int i = 0; i < graphValues.length; i++) {
if(graphValues[i] != graphBuffer.getInvalidNumber()) {
X = computeX(i);
if (graphValues[i] < ymin) {
Y = computeY(ymin);
}
else if (graphValues[i] > ymax) {
Y = computeY(ymax);
}
else {
Y = computeY(graphValues[i]);
}
if (graphValues[i] > 0)
g2.drawLine(X, computeY(0)-w/2, X, Y+w/2);
else if (graphValues[i] < 0)
g2.drawLine(X, computeY(0)+w/2, X, Y-w/2);
}
}
g2.setStroke(s);
} |
5cab840a-45b2-4c64-9934-62afc35c1894 | 1 | public void selectSize(int x,int y)
{
for(int i=0;i<markers;i++)
{
marker[i].selectSize(x, y);
}
} |
094a4044-88f2-4b9a-908b-5e30b753b0ad | 6 | @SuppressWarnings("resource")
public void serverStart() throws Exception {
System.out.println("Server started");
ServerSocket serverSocket = new ServerSocket(5432);
LinkedList<Socket> clientSockets = new LinkedList<Socket>();
ArrayList<PrintWriter> outArrayList = new ArrayList<PrintWriter>();
int count = 0;
/*
* For every 4 clients connected, we create a manager thread which will
* manage the client information.
*
* Server thread continues to run and listens for new connections.
*/
while (true) {
Socket socket = serverSocket.accept();
boolean result = this.verificaiton(socket);
if (!result) {
System.out.println("Verification Failed");
socket.close();
} else {
clientSockets.add(socket);
outArrayList.add(new PrintWriter(socket.getOutputStream(), true));
count++;
System.out.println(count + " p connected.");
for(PrintWriter out : outArrayList) {
out.println(clientSockets.size());
}
}
if (count == PLAYERS_PER_GAME) {
// Create copy of the list of client sockets.
LinkedList<Socket> copyOfClientSockets = new LinkedList<Socket>(clientSockets);
// Pass the clientSockets to the clientManager.
Thread clientManager;
if (this.protocal == PROTOCAL.NOPROTOCAL || this.protocal == PROTOCAL.T2) {
clientManager = new Thread(new UnSecureClientManagerII(copyOfClientSockets));
} else {
clientManager = new Thread(new SecureClientManager(copyOfClientSockets, this));
}
//Thread clientManager = new Thread(new ClientManager(copyOfClientSockets));
System.out.println("Manager thread created.");
clientManager.start();
// Reset count and clear the existing list of clients sockets.
count = 0;
clientSockets.clear();
outArrayList.clear();
}
Thread.sleep(1000);
}
} |
bdfbd9b7-d45a-4d73-8016-77364ee29b28 | 0 | public void setUsername(String username) {
this.username = username;
} |
07a95b32-5ce2-470d-8730-796847adc9fd | 1 | public void setRpcPass(String rpcPass) throws InvalidSettingException {
if (rpcPass != null) {
this.rpcPass = rpcPass;
} else {
throw new InvalidSettingException("Invalid Password");
}
} |
bfd857e5-55a0-427a-8af5-aee62c5a1c1d | 3 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ManualMainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new ManualMainFrame().setVisible(true);
});
} |
cbb68194-f728-42af-97c2-a33b34589222 | 1 | @Test ( timeout = 2000 )
public void serverWriteToSocketClosedByServer () throws Exception {
Socket[] sockets = connectToServer();
try ( Socket serverSocket = sockets[ 0 ];
Socket clientSocket = sockets[ 1 ] ) {
serverSocket.close();
// wait for close to propagate
Thread.sleep(100);
IOException exception = null;
try {
serverSocket.getOutputStream().write(new byte[] {
'1'
});
}
catch ( IOException e ) {
exception = e;
}
assertNotNull("Server should see an IOException when writing to a socket that it closed.", exception);
}
} |
ce35d412-2b8d-4495-ad9e-81612e2ecb0b | 0 | public JobSchedulerBuilder withStoreDurably( boolean storeDurably )
{
this.storeDurably = storeDurably;
return this;
} |
ab5b29ca-0437-4bb6-8f9e-9b36c22993da | 4 | public <T extends IMessage>void addHandler(final Class<T> type, final IMessageHandler<T> handler) {
List<IMessageHandler<? extends IMessage>> handlers = handlersByMessage.get(type);
if (handlers == null) {
handlers = new ArrayList<IMessageHandler<? extends IMessage>>();
handlersByMessage.put(type, handlers);
}
if (!handlers.contains(handler)) {
handlers.add(handler);
}
} |
a8d1737c-84cf-4df5-a72f-e039ab73a03b | 3 | ClientSideView( int portNum, String host )
{
eventMapper = new EventMapper( new ClientActionConfigurator().getConfigurator());
text = new JLabel( "Text to send over socket:" );
textField = new JTextField( 20 );
button = new JButton( "Click Me" );
webSocketPortOpener = new JButton( "Open web-socket port" );
webSocketPortOpener.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
Integer webSocketPort = 0;
try
{
webSocketPort = Integer.parseInt( portNumberTextField.getText() );
}
catch( NumberFormatException ex )
{
ex.printStackTrace();
}
if( webSocketPort != 0 )
{
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("WEBSOCKET_PORT", webSocketPort);
requestSender.sendToServer( new Message( "WS", params ) );
}
}
} );
portNumberTextField = new JTextField( 10 );
button.addActionListener( this );
panel = new JPanel();
panel.setLayout( new BorderLayout() );
panel.setBackground( Color.white );
getContentPane().add( panel );
panel.add( "South", text );
panel.add( "West", textField );
panel.add( "North", button );
panel.add( "East", webSocketPortOpener );
panel.add( "Center", portNumberTextField );
newDataListenerPort = (int) (Math.random() * MAX_PORT_NUM);
while( newDataListenerPort < 80 )
{
newDataListenerPort = (int) (Math.random() * MAX_PORT_NUM);
}
// serverState = new NewDataListener( newDataListenerPort );
// Thread serverStateThread = new Thread( serverState );
// serverStateThread.start();
requestSender = new ClientSocketAdmin( actions, portNum, host, 10 );
dispatcher = new Dispatcher( actions, eventMapper );
Thread dispatcherThread = new Thread(dispatcher);
dispatcherThread.start();
Thread requestSenderThread = new Thread( requestSender );
requestSenderThread.start();
ClientComponentsRegister.addComponent( "SOCKET_ADMIN", requestSender);
// NewDataListener newDataListener = new NewDataListener( 10045 );
// Thread newDataListenerThread = new Thread( newDataListener );
// newDataListenerThread.start();
// System.out.println( "after initialisation" );
} |
8e503737-013c-42f7-ab12-8f54e74c4ee0 | 1 | private synchronized boolean checkPulse(Peer p){
return p.hasPulse()? true:false;
} |
4c5c10fd-e317-4e26-ac91-3bd33828164b | 4 | protected double objectiveFunction() throws NNException {
double result = 0;
for (Pattern<?,?> pattern : patterns) {
List<Double> processed = network.process(pattern.getInputSignal());
for (int i = 0; i < processed.size(); i++) {
result += Math.pow(processed.get(i).doubleValue() - pattern.getOutputSignal().get(i).doubleValue(), 2);
}
}
return result;
} |
f52ea3dd-8f5b-42a1-a721-a3f877a51c74 | 0 | @Override
public int attack(double agility, double luck) {
System.out.println("I did a default skill attack");
return (int) agility;
} |
d1acbaee-121f-4cc8-a8de-58059c1a733b | 9 | public void onEndPage(PdfWriter writer, Document document) {
if (this.numberPos > 0) {
float width = document.getPageSize().getWidth();
float height = document.getPageSize().getHeight();
try {
if (total == null)
total = writer.getDirectContent().createTemplate(30, 16);
if (this.hasTotleNumber)
this.pagenumbertable = new PdfPTable(2);
else
this.pagenumbertable = new PdfPTable(1);
pagenumbertable.setTotalWidth(50f);
pagenumbertable.setLockedWidth(true);
pagenumbertable.getDefaultCell().setFixedHeight(20);
pagenumbertable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
if (this.hasTotleNumber)
pagenumbertable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
else
pagenumbertable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
pagenumbertable.addCell(Integer.toString(writer.getPageNumber()));
if (this.hasTotleNumber) {
PdfPCell cell = new PdfPCell(Image.getInstance(total));
cell.setBorder(Rectangle.NO_BORDER);
pagenumbertable.addCell(cell);
}
switch (numberPos) {
case 3:
pagenumbertable.writeSelectedRows(0, -1, width * 0.9f, height * 0.95f, writer.getDirectContent());
// ColumnText.showTextAligned(writer.getDirectContent(),
// Element.ALIGN_CENTER, new Phrase("< "+String.valueOf(writer
// .getPageNumber())+" >"), width * 0.95f, height * 0.95f, 0);
break;
case 9:
pagenumbertable.writeSelectedRows(0, -1, width * 0.9f, height * 0.05f, writer.getDirectContent());
// ColumnText.showTextAligned(writer.getDirectContent(),
// Element.ALIGN_CENTER, new Phrase(String.valueOf(writer
// .getPageNumber())), width * 0.93f, height * 0.05f, 0);
break;
case 8:
pagenumbertable.writeSelectedRows(0, -1, width * 0.5f, height * 0.05f, writer.getDirectContent());
// ColumnText.showTextAligned(writer.getDirectContent(),
// Element.ALIGN_CENTER, new Phrase("< "+String.valueOf(writer
// .getPageNumber())+" >"), width * 0.5f, height * 0.05f, 0);
break;
default:
break;
}
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
} |
44cb7707-de74-4af7-8ab1-79624d963681 | 1 | public Expression mergeIntoExpression(Expression expr) {
/* assert expr.getFreeOperandCount() == stackMap.length */
for (int i = stackMap.length - 1; i >= 0; i--) {
// if (!used.contains(stackMap[i]))
// used.addElement(stackMap[i]);
expr = expr.addOperand(new LocalLoadOperator(stackMap[i].getType(),
null, stackMap[i]));
}
return expr;
} |
3758f719-954b-4c2f-9f9a-bb4ee025a666 | 9 | public void create(PypAdmAgend pypAdmAgend) {
if (pypAdmAgend.getPypAdmAsistConList() == null) {
pypAdmAgend.setPypAdmAsistConList(new ArrayList<PypAdmAsistCon>());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
PypAdmProgramas idPrograma = pypAdmAgend.getIdPrograma();
if (idPrograma != null) {
idPrograma = em.getReference(idPrograma.getClass(), idPrograma.getId());
pypAdmAgend.setIdPrograma(idPrograma);
}
InfoPaciente idPaciente = pypAdmAgend.getIdPaciente();
if (idPaciente != null) {
idPaciente = em.getReference(idPaciente.getClass(), idPaciente.getId());
pypAdmAgend.setIdPaciente(idPaciente);
}
List<PypAdmAsistCon> attachedPypAdmAsistConList = new ArrayList<PypAdmAsistCon>();
for (PypAdmAsistCon pypAdmAsistConListPypAdmAsistConToAttach : pypAdmAgend.getPypAdmAsistConList()) {
pypAdmAsistConListPypAdmAsistConToAttach = em.getReference(pypAdmAsistConListPypAdmAsistConToAttach.getClass(), pypAdmAsistConListPypAdmAsistConToAttach.getId());
attachedPypAdmAsistConList.add(pypAdmAsistConListPypAdmAsistConToAttach);
}
pypAdmAgend.setPypAdmAsistConList(attachedPypAdmAsistConList);
em.persist(pypAdmAgend);
if (idPrograma != null) {
idPrograma.getPypAdmAgendList().add(pypAdmAgend);
idPrograma = em.merge(idPrograma);
}
if (idPaciente != null) {
idPaciente.getPypAdmAgendList().add(pypAdmAgend);
idPaciente = em.merge(idPaciente);
}
for (PypAdmAsistCon pypAdmAsistConListPypAdmAsistCon : pypAdmAgend.getPypAdmAsistConList()) {
PypAdmAgend oldIdAgendOfPypAdmAsistConListPypAdmAsistCon = pypAdmAsistConListPypAdmAsistCon.getIdAgend();
pypAdmAsistConListPypAdmAsistCon.setIdAgend(pypAdmAgend);
pypAdmAsistConListPypAdmAsistCon = em.merge(pypAdmAsistConListPypAdmAsistCon);
if (oldIdAgendOfPypAdmAsistConListPypAdmAsistCon != null) {
oldIdAgendOfPypAdmAsistConListPypAdmAsistCon.getPypAdmAsistConList().remove(pypAdmAsistConListPypAdmAsistCon);
oldIdAgendOfPypAdmAsistConListPypAdmAsistCon = em.merge(oldIdAgendOfPypAdmAsistConListPypAdmAsistCon);
}
}
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
} |
1d95e9ae-516c-4438-8d5e-e78f29ce1e21 | 2 | @Override
public void paint(Graphics2D g2d) {
super.paint(g2d);
g2d.setColor(Color.CYAN);
g2d.drawString("R:"+salud, x, y+50);
if(salud <= 10 && vidas > 0){
g2d.setColor(Color.LIGHT_GRAY);
g2d.drawString("v:"+vidas, x, y+10);
}
} |
448ae4c1-369d-4f5e-899b-02b68c6dcff7 | 0 | public void setRoomEventList(final List<RoomEvent> roomEventList) {
this.roomEventList = roomEventList;
} |
5b24ccf2-c1cf-4681-8065-c7e4f8d3404b | 5 | private void updateALUTable(){
//Get a copy of the memory stations
ALUStation[] temp_alu = sim_instance.getALUStations();
//Update the table with current values for the stations
for( int i =0; i < temp_alu.length; i++ ){
//generate a meaningfull representation of busy
String busy_desc = (temp_alu[i].isBusy() ? "Yes" : "No" );
rs_model.setValueAt( (( temp_alu[i].isReady() && temp_alu[i].isBusy() ) ? temp_alu[i].getDuration() : "0") ,
i, 0 );
rs_model.setValueAt( temp_alu[i].getName(), i, 1 );
rs_model.setValueAt( busy_desc, i, 2 );
rs_model.setValueAt( ( (temp_alu[i].isBusy()) ? temp_alu[i].getOperation() : " "), i, 3 );
rs_model.setValueAt( temp_alu[i].getVj(), i, 4 );
rs_model.setValueAt( temp_alu[i].getVk(), i, 5 );
rs_model.setValueAt( temp_alu[i].getQj(), i, 6 );
rs_model.setValueAt( temp_alu[i].getQk(), i, 7 );
}
} |
c6ab4244-dee7-41e3-8836-9808122c2a4e | 3 | public static void main(String[] args) {
System.out.println("Starting client...");
// Parse and set command-line arguments
try {
parseCommandLineArguments(args);
} catch (IllegalArgumentException iae) {
System.err.println("Error parsing port number: " + iae.getLocalizedMessage());
System.err.println("Fallback to " + Integer.toString(SERVER_PORT));
}
System.out.println("Using URI " + SERVER_ADDRESS + ":" + Integer.toString(SERVER_PORT) + "/" + SERVER_BASE_URL);
final ClientConfig config = new DefaultClientConfig();
final Client client = Client.create(config);
try {
final WebResource service = client.resource(getBaseURI());
// These are the actual calls to the RESTful service
System.out.println(service.path("palindrom").path(values.toString()).accept(MediaType.TEXT_PLAIN).get(String.class));
System.out.println(service.path("palindrom").path(values.toString()).accept(MediaType.TEXT_XML).get(String.class));
System.out.println(service.path("palindrom").path(values.toString()).accept(MediaType.TEXT_HTML).get(String.class));
} catch (com.sun.jersey.api.client.ClientHandlerException che) {
System.err.println("Error: Server at port not accessible: " + che.getLocalizedMessage());
} catch (com.sun.jersey.api.client.UniformInterfaceException uie) {
System.err.println("Error: Baseurl probably not correct: " + uie.getLocalizedMessage());
}
} |
7326a28f-ab70-4daa-81a2-e8fe309fd7f0 | 7 | public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String linea;
while((linea=bf.readLine())!=null){
String[] boxes = linea.split(" ");
long totalCajas = 0 ;
for(int i=0;i<boxes.length;++i){
totalCajas += Integer.parseInt(boxes[i]);
}
String ordenCajas;
int menorNumMov = Integer.MAX_VALUE;
ordenCajas = "BCG";
menorNumMov = (int) (totalCajas - ( Integer.parseInt(boxes[0]) + Integer.parseInt(boxes[5]) + Integer.parseInt(boxes[7])));
int aux = (int) (totalCajas - ( Integer.parseInt(boxes[0]) + Integer.parseInt(boxes[4]) + Integer.parseInt(boxes[8])));
if( aux < menorNumMov ){
ordenCajas = "BGC";
menorNumMov = aux;
}
aux = (int) (totalCajas - ( Integer.parseInt(boxes[2]) + Integer.parseInt(boxes[3]) + Integer.parseInt(boxes[7])));
if( aux < menorNumMov ){
ordenCajas = "CBG";
menorNumMov = aux;
}
aux = (int) (totalCajas - ( Integer.parseInt(boxes[2]) + Integer.parseInt(boxes[4]) + Integer.parseInt(boxes[6])));
if( aux < menorNumMov ){
ordenCajas = "CGB";
menorNumMov = aux;
}
aux = (int) (totalCajas - ( Integer.parseInt(boxes[1]) + Integer.parseInt(boxes[3]) + Integer.parseInt(boxes[8])));
if( aux < menorNumMov ){
ordenCajas = "GBC";
menorNumMov = aux;
}
aux = (int) (totalCajas - ( Integer.parseInt(boxes[1]) + Integer.parseInt(boxes[5]) + Integer.parseInt(boxes[6])));
if( aux < menorNumMov ){
ordenCajas = "GCB";
menorNumMov = aux;
}
System.out.println(ordenCajas+" "+menorNumMov);
}
} |
a73f0b63-eb95-4f73-903d-f5c8105366c2 | 1 | public String getAuthor() {
return this.author == null ? "" : this.author;
} |
fcbb9b4e-198c-4ff3-93e7-e60ddf5c39e4 | 0 | public static void main(String[] args) {
creator1 = new ConcreteCreator1();
product1 = creator1.factory();
creator2 = new ConcreteCreator2();
product2 = creator2.factory();
} |
912ef84c-a68d-47a4-a1c1-94d8b9eb7e2e | 0 | public void mouseDragged(MouseEvent e){
x = e.getX();
y = e.getY();
} |
f2934623-7a74-497e-9af3-20ca80d88e42 | 7 | public void sort(SortArray a, SortCanvas c) {
int j;
int limit = a.length();
int st = 0;
while (st < limit) {
boolean flipped = false;
st++;
limit--;
for (j = st; j < limit; j++) {
if (a.greater(j, j + 1)) {
a.swap(j, j+1);
flipped = true;
}
c.paintNumbers();
}
if (!flipped) {
return;
}
for (j = limit; --j >= st;) {
if (a.greater(j, j + 1)) {
a.swap(j, j+1);
flipped = true;
}
c.paintNumbers();
}
if (!flipped) {
return;
}
}
} |
e48cbb18-7553-4a01-9c57-75040997de84 | 7 | public void buildAssociations(Instances instances) throws Exception {
Frame valuesFrame = null; /* Frame to display the current values. */
/* Initialization of the search. */
if (m_parts == null) {
m_instances = new Instances(instances);
} else {
m_instances = new IndividualInstances(new Instances(instances), m_parts);
}
m_results = new SimpleLinkedList();
m_hypotheses = 0;
m_explored = 0;
m_status = NORMAL;
if (m_classIndex == -1)
m_instances.setClassIndex(m_instances.numAttributes()-1);
else if (m_classIndex < m_instances.numAttributes() && m_classIndex >= 0)
m_instances.setClassIndex(m_classIndex);
else
throw new Exception("Invalid class index.");
// can associator handle the data?
getCapabilities().testWithFail(m_instances);
/* Initialization of the window for current values. */
if (m_printValues == WINDOW) {
m_valuesText = new TextField(37);
m_valuesText.setEditable(false);
m_valuesText.setFont(new Font("Monospaced", Font.PLAIN, 12));
Label valuesLabel = new Label("Best and worst current values:");
Button stop = new Button("Stop search");
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/* Signal the interruption to the search. */
m_status = STOP;
}
});
valuesFrame = new Frame("Tertius status");
valuesFrame.setResizable(false);
valuesFrame.add(m_valuesText, BorderLayout.CENTER);
valuesFrame.add(stop, BorderLayout.SOUTH);
valuesFrame.add(valuesLabel, BorderLayout.NORTH);
valuesFrame.pack();
valuesFrame.setVisible(true);
} else if (m_printValues == OUT) {
System.out.println("Best and worst current values:");
}
Date start = new Date();
/* Build the predicates and launch the search. */
m_predicates = buildPredicates();
beginSearch();
Date end = new Date();
if (m_printValues == WINDOW) {
valuesFrame.dispose();
}
m_time = new Date(end.getTime() - start.getTime());
} |
d0f62c8a-286a-4885-a1a2-c41c39731462 | 3 | public void ForgotPassword(RequestPacket request, DBCollection coll, User user) {
try {
// Check that given username and email match a record in DB
DBCursor cursor = coll.find(new BasicDBObject("user_name", request.getUser_name()));
if(cursor.hasNext()) {
if(request.getEmail().equalsIgnoreCase(((BasicDBObject) cursor.next()).getString("email"))) {
user.scheduleTimeoutEvent(TIMEOUT);
user.sendMessage(msgTransformer.writeMessage(new ResponsePacket().setResponse("response").setMessage("success")));
}
else
user.sendMessage(msgTransformer.writeMessage(new ResponsePacket().setResponse("response").setMessage("Invalid email")));
} else
user.sendMessage(msgTransformer.writeMessage(new ResponsePacket().setResponse("response").setMessage("Invalid username")));
} catch (Exception e) {
e.printStackTrace();
}
} |
b70821dc-e824-4657-ad97-08273e573870 | 1 | public void createHuffTree()
{
while(items > 2)
{
Node first = removeFirst();
Node second = removeFirst();
Node newNode = new Node(first.frequency + second.frequency, -1);
newNode.left = first;
newNode.right = second;
first.next = first.prev = second.next = second.prev = null;
insert(newNode);
}
Node first = removeFirst();
Node second = root;
Node newNode = new Node(first.frequency + second.frequency, -1);
newNode.left = first;
newNode.right = second;
root = newNode;
} |
db413e2a-9052-483c-af5a-0e76cb6ddd22 | 1 | public synchronized void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
} |
f75c5692-d54f-4dd4-8408-ac6dcfdb4965 | 6 | public static void save(String filename, double[] input) {
// assumes 44,100 samples per second
// use 16-bit audio, mono, signed PCM, little Endian
AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, 1, true, false);
byte[] data = new byte[2 * input.length];
for (int i = 0; i < input.length; i++) {
int temp = (short) (input[i] * MAX_16_BIT);
data[2*i + 0] = (byte) temp;
data[2*i + 1] = (byte) (temp >> 8);
}
// now save the file
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
AudioInputStream ais = new AudioInputStream(bais, format, input.length);
if (filename.endsWith(".wav") || filename.endsWith(".WAV")) {
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(filename));
}
else if (filename.endsWith(".au") || filename.endsWith(".AU")) {
AudioSystem.write(ais, AudioFileFormat.Type.AU, new File(filename));
}
else {
throw new RuntimeException("File format not supported: " + filename);
}
}
catch (Exception e) {
System.out.println(e);
System.exit(1);
}
} |
e026fab8-99c6-469e-a413-e74c9160dec6 | 3 | public void doAll() {
// TODO Auto-generated method stub
switch (currentStep) {
case CREATE_SINGLE_TRAPSTATE:
JOptionPane.showMessageDialog(frame,
"Just create a state.\nIt's not too difficult.",
"Create the State", JOptionPane.ERROR_MESSAGE);
return;
}
for (Integer key:myNeededTransitionMap.keySet())
{
ArrayList <String> list=myNeededTransitionMap.get(key);
for (String terminal: list)
{
FSATransition t=new FSATransition(myStateMap.get(key), myTrapState, terminal);
automaton.addTransition(t);
frame.repaint();
}
}
currentStep=FINISHED;
nextStep();
return;
} |
0b4edb06-1a7c-4fa7-bc52-51a8e3b48e04 | 3 | private JFileChooser setFilters(JFileChooser jfc, boolean predefined, String comment, String extension) {
if (predefined ||
!jfc.getFileFilter().getDescription().equalsIgnoreCase("Todos los Archivos")) {
jfc.setAcceptAllFileFilterUsed(false);
}
FileNameExtensionFilter newFilter = new FileNameExtensionFilter(comment, extension);
jfc.addChoosableFileFilter(newFilter);
if (predefined) {jfc.setFileFilter(newFilter);}
return jfc;
} |
cadecfee-2d2a-442c-8ab8-5e40b032e4fd | 7 | @Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if((affected==null)||(!(affected instanceof MOB))||(target==null))
return true;
final MOB mob=(MOB)affected;
if(mob.location()!=target.location())
unInvoke();
if(mob.getVictim()!=target)
unInvoke();
if(mob.rangeToTarget()>0)
unInvoke();
if(target.getVictim()==mob)
unInvoke();
return super.okMessage(myHost,msg);
} |
719659f0-0188-4096-8cb8-681b0821b683 | 0 | @RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
} |
3c3b7898-b86a-4c69-be22-faa03986e6a3 | 2 | public void log(String content) {
try {
if ( !Files.exists(dir, LinkOption.NOFOLLOW_LINKS) )
Files.createDirectory(dir);
content += System.getProperty("line.separator");
Files.write(file, content.getBytes(), StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
} catch (IOException ex) {
System.err.println("Nelze zapisovat do log souboru " + file);
}
} |
c58d6eca-14c8-4f61-a39f-01dc3ac24fc0 | 5 | public void print(List<String> IdsToStrings,String pad) {
Iterator<T> uniIter=UnigramCounts.keySet().iterator();
T myValue;
Double myVal;
int getVal;
if (pad==null) {
pad="";
}
while (uniIter.hasNext()) {
myValue=uniIter.next();
myVal=UnigramCounts.get(myValue);
if ((IdsToStrings!=null) && (myValue instanceof Integer)) {
getVal=((Integer)myValue).intValue();
System.out.println(pad+"Unigram<"+myValue.getClass().getName()+">:"+IdsToStrings.get(getVal)+" and COUNT="+myVal);
}
else if (myValue instanceof BigramModel) {
System.out.println(pad+"Unigram<"+myValue.getClass().getName()+">:"+((BigramModel)myValue).toString(IdsToStrings)+" and COUNT="+myVal);
}
else {
System.out.println(pad+"Unigram<"+myValue.getClass().getName()+">:"+myValue+" and COUNT="+myVal);
}
}
} |
0d8c612f-f410-4e16-9fce-ed3f2f39c9cd | 6 | private static boolean available(int port) {
if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
throw new IllegalArgumentException("Invalid start port: " + port);
}
ServerSocket ss = null;
DatagramSocket ds = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
ds = new DatagramSocket(port);
ds.setReuseAddress(true);
return true;
} catch (IOException e) {
} finally {
if (ds != null) {
ds.close();
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
/* should not be thrown */
}
}
}
return false;
} |
03d4b3a7-2908-4af3-a07c-18c23ede4f71 | 1 | @Override
public List<Integer> save(List<Order> beans, GenericSaveQuery saveGeneric, Connection conn) throws DaoQueryException {
try {
return saveGeneric.sendQuery(SAVE_QUERY, conn, Params.fill(beans, (Order bean) -> {
Object[] obj = new Object[8];
obj[0] = bean.getUser().getIdUser();
obj[1] = bean.getTour().getIdTour();
obj[2] = bean.getSeats();
obj[3] = bean.getCurrentPrice();
obj[4] = bean.getCurrentDiscount();
obj[5] = bean.getCurrentUserDiscount();
obj[6] = bean.getFinalPrice();
obj[7] = bean.getOrderDate();
return obj;
}));
} catch (DaoException ex) {
throw new DaoQueryException(ERR_ORDER_SAVE, ex);
}
} |
16ae8c63-c0ac-4a95-bf7b-236a3a8d774f | 7 | public PanelValidationReservation(JFrame frame, List<Reservation> listeReservations) {
SimpleDateFormat formatterDeb = new SimpleDateFormat("'Le 'dd/MM/yyyy' de 'HH'h '");
SimpleDateFormat formatterFin = new SimpleDateFormat("HH");
infosPaiement = null;
Date dateReservation = null;
int duree;
dateReservation = listeReservations.get(0).getDate();
duree = listeReservations.get(0).getPlage();
JScrollPane scrollpane;
JLabel lNom = new JLabel("Nom");
JLabel lPrenom = new JLabel("Prenom");
JLabel lNumTel = new JLabel("Tel");
lTypeSalle = new JLabel();
lDate = new JLabel();
lPrix = new JLabel();
lTypeSalle.setOpaque(true);
lTypeSalle.setBackground(Color.LIGHT_GRAY);
lDate.setOpaque(true);
lDate.setBackground(Color.LIGHT_GRAY);
lPrix.setOpaque(true);
lPrix.setBackground(Color.LIGHT_GRAY);
lTypeSalle.setText("Type : " + (listeReservations.get(0).getSalle().getTypeSalle().getTypeSalle().equals("petite")?"Petite salle":(listeReservations.get(0).getSalle().getTypeSalle().getTypeSalle().equals("grande")?"Grande salle":"Salle equipee")));
lDate.setText(formatterDeb.format(dateReservation)
+ "a " + (Integer.parseInt(formatterFin.format(dateReservation))+duree) + "h");
cbForfait = new JComboBox();
cbForfait.setRenderer(new RendererCBForfait());
cbForfait.setMinimumSize(new Dimension(120, 20));
cbForfait.setMaximumSize(new Dimension(120, 20));
cbForfait.setPreferredSize(new Dimension(120, 20));
cbForfait.addItem(null);
checkFidelite = new JCheckBox();
checkFidelite.setBackground(Color.LIGHT_GRAY);
checkPaiement = new JCheckBox();
checkPaiement.setBackground(Color.LIGHT_GRAY);
bgChoixPaiement = new ButtonGroup();
rbDiffere = new JRadioButton();
rbImmediat = new JRadioButton();
rbDiffere.setSelected(true);
rbDiffere.setBackground(Color.LIGHT_GRAY);
rbImmediat.setBackground(Color.LIGHT_GRAY);
bgChoixPaiement.add(rbDiffere);
bgChoixPaiement.add(rbImmediat);
this.frame = frame;
this.listeReservations = listeReservations;
this.setLayout(new GridBagLayout());
modelReservation = new DefaultListModel<Reservation>();
jListeReservations = new JList<Reservation>(modelReservation);
jListeReservations.setCellRenderer(new RendererJListReservation());
for(Reservation r : listeReservations){
modelReservation.addElement(r);
}
GridBagConstraints GBC = new GridBagConstraints();
panelCenterRight = new JPanel();
panelCenterRight.setLayout(new GridBagLayout());
panelCenterRight.setBackground(Color.LIGHT_GRAY);
//panelCenterRight.setPreferredSize(new Dimension(200, 300));
panelOptionsPaiement = new JPanel();
panelOptionsPaiement.setLayout(new FlowLayout(FlowLayout.CENTER));
panelOptionsPaiement.setBackground(Color.LIGHT_GRAY);
panelOptionsPaiement.setVisible(false);
bSendInfos = new JButton(" >> ");
bSendInfos.setBackground(Color.WHITE);
bEnregistrer = new JButton("Valider");
bEnregistrer.setBackground(Color.WHITE);
bEnregistrer.setMinimumSize(new Dimension(150, 20));
bEnregistrer.setMaximumSize(new Dimension(150, 20));
bEnregistrer.setPreferredSize(new Dimension(150, 20));
bRetour = new JButton("Retour");
bRetour.setBackground(Color.WHITE);
bRetour.setMinimumSize(new Dimension(150, 20));
bRetour.setMaximumSize(new Dimension(150, 20));
bRetour.setPreferredSize(new Dimension(150, 20));
bOptionsPaiement = new JButton("Forfaits et pts fidelite");
bOptionsPaiement.setBackground(Color.WHITE);
tfNom = new JTextField();
tfNom.setMinimumSize(new Dimension(100, 20));
tfNom.setMaximumSize(new Dimension(100, 20));
tfNom.setPreferredSize(new Dimension(100, 20));
tfNom.setBackground(Color.WHITE);
tfPrenom = new JTextField();
tfPrenom.setMinimumSize(new Dimension(100, 20));
tfPrenom.setMaximumSize(new Dimension(100, 20));
tfPrenom.setPreferredSize(new Dimension(100, 20));
tfPrenom.setBackground(Color.WHITE);
tfNumTel = new JTextField();
tfNumTel.setMinimumSize(new Dimension(100, 20));
tfNumTel.setMaximumSize(new Dimension(100, 20));
tfNumTel.setPreferredSize(new Dimension(100, 20));
tfNumTel.setBackground(Color.WHITE);
lNom.setMinimumSize(new Dimension(50, 20));
lNom.setMaximumSize(new Dimension(50, 20));
lNom.setPreferredSize(new Dimension(50, 20));
lPrenom.setMinimumSize(new Dimension(50, 20));
lPrenom.setMaximumSize(new Dimension(50, 20));
lPrenom.setPreferredSize(new Dimension(50, 20));
lNumTel.setMinimumSize(new Dimension(50, 20));
lNumTel.setMaximumSize(new Dimension(50, 20));
lNumTel.setPreferredSize(new Dimension(50, 20));
RechercheClient metierRechercheClient = new RechercheClient();
listeClient = metierRechercheClient.listerClients();
model = new DefaultListModel<Client>();
for(Client clt : listeClient){
model.addElement(clt);
}
jlClient = new JList<Client>(model);
jlClient.setCellRenderer(new RendererJListClient());
jlClient.setLayoutOrientation(JList.VERTICAL);
jlClient.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
scrollpane = new JScrollPane(jlClient);
scrollpane.setPreferredSize(new Dimension(200, 300));
scrollpane.setMinimumSize(new Dimension(200, 300));
scrollpane.setMaximumSize(new Dimension(200, 300));
panelOptionsPaiement.add(bOptionsPaiement);
if(listeReservations.size()==1){
infosPaiement = new ConfirmerReservation().getInfosApresPaiement(listeReservations.get(0), null, null, false);
GBC.fill = GridBagConstraints.HORIZONTAL;
GBC.anchor = GridBagConstraints.NORTH;
GBC.gridy = 0;
GBC.gridx = 0;
GBC.gridheight = 1;
GBC.gridwidth = 2;
GBC.weightx = 1;
GBC.weighty = 1;
panelCenterRight.add(lTypeSalle,GBC);
GBC.gridy++;
panelCenterRight.add(lDate,GBC);
GBC.gridy++;
lPrix.setText("Prix : " + infosPaiement[0] + " euro"+(infosPaiement[0]>1?"s":""));
panelCenterRight.add(lPrix,GBC);
} else {
infosPaiement = new ConfirmerReservation().getInfosApresPaiement(listeReservations, null, null, false);
GBC.fill = GridBagConstraints.HORIZONTAL;
GBC.anchor = GridBagConstraints.NORTH;
GBC.gridy = 0;
GBC.gridx = 0;
GBC.gridheight = 1;
GBC.gridwidth = 2;
GBC.weightx = 1;
GBC.weighty = 1;
panelCenterRight.add(lTypeSalle,GBC);
GBC.gridy++;
JScrollPane scrollPaneReservations = new JScrollPane(jListeReservations);
scrollPaneReservations.setPreferredSize(new Dimension(220, 100));
scrollPaneReservations.setMinimumSize(new Dimension(220, 100));
scrollPaneReservations.setMaximumSize(new Dimension(220, 100));
panelCenterRight.add(scrollPaneReservations,GBC);
GBC.gridy++;
lPrix.setText("Prix : " + infosPaiement[0] + " euro"+(infosPaiement[0]>1?"s":""));
panelCenterRight.add(lPrix,GBC);
}
GBC.gridy++;
GBC.gridwidth = 1;
panelCenterRight.add(new JLabel("Paiement :"),GBC);
GBC.gridy++;
panelCenterRight.add(new JLabel("Differe",JLabel.RIGHT),GBC);
GBC.gridx++;
panelCenterRight.add(rbDiffere,GBC);
GBC.gridx=0;
GBC.gridy++;
panelCenterRight.add(new JLabel("Immediat",JLabel.RIGHT),GBC);
GBC.gridx++;
panelCenterRight.add(rbImmediat,GBC);
GBC.gridx = 0;
GBC.gridy++;
GBC.gridwidth = 2;
GBC.fill = GridBagConstraints.VERTICAL;
panelCenterRight.add(panelOptionsPaiement,GBC);
GBC.gridy++;
GBC.gridwidth = 1;
GBC.fill = GridBagConstraints.HORIZONTAL;
panelCenterRight.add(lNom,GBC);
GBC.gridx++;
panelCenterRight.add(tfNom,GBC);
GBC.gridx = 0;
GBC.gridy++;
panelCenterRight.add(lPrenom,GBC);
GBC.gridx++;
panelCenterRight.add(tfPrenom,GBC);
GBC.gridx = 0;
GBC.gridy++;
panelCenterRight.add(lNumTel,GBC);
GBC.gridx++;
panelCenterRight.add(tfNumTel,GBC);
GBC.gridx = 0;
GBC.gridy++;
GBC.gridwidth = 2;
GBC.insets = new Insets(15, 5, 5, 5);
panelCenterRight.add(bEnregistrer,GBC);
GBC.gridy++;
GBC.fill = GridBagConstraints.BOTH;
GBC.anchor = GridBagConstraints.NORTH;
GBC.gridy = 0;
GBC.gridx = 0;
GBC.gridheight = 1;
GBC.gridwidth = 3;
GBC.weightx = 1;
GBC.weighty = 1;
GBC.insets = new Insets(0, 0, 0, 0);
JLabel lTitreHaut = new JLabel("Validation de la reservation",JLabel.CENTER);
lTitreHaut.setOpaque(true);
lTitreHaut.setBackground(Color.GRAY);
this.add(lTitreHaut,GBC);
GBC.anchor = GridBagConstraints.EAST;
GBC.fill = GridBagConstraints.BOTH;
GBC.gridy++;
GBC.gridwidth=1;
GBC.insets = new Insets(3, 10, 0, 0);
this.add(scrollpane,GBC);
GBC.fill = GridBagConstraints.NONE;
GBC.anchor = GridBagConstraints.CENTER;
GBC.gridx++;
GBC.weightx = 0.1;
GBC.weighty = 0.1;
GBC.insets = new Insets(3, 5, 0, 5);
this.add(bSendInfos,GBC);
GBC.fill = GridBagConstraints.BOTH;
GBC.anchor = GridBagConstraints.EAST;
GBC.gridx++;
GBC.weightx = 1;
GBC.weighty = 1;
GBC.insets = new Insets(3, 0, 0, 10);
this.add(panelCenterRight,GBC);
GBC.gridy++;
GBC.gridx = 0;
GBC.gridwidth = 3;
GBC.fill = GridBagConstraints.NONE;
GBC.anchor = GridBagConstraints.CENTER;
GBC.insets = new Insets(5, 0, 3, 0);
this.add(bRetour,GBC);
bSendInfos.addActionListener(this);
bEnregistrer.addActionListener(this);
bRetour.addActionListener(this);
bOptionsPaiement.addActionListener(this);
cbForfait.addActionListener(this);
checkFidelite.addActionListener(this);
rbDiffere.addActionListener(this);
rbImmediat.addActionListener(this);
tfNom.getDocument().addDocumentListener(this);
tfPrenom.getDocument().addDocumentListener(this);
tfNumTel.getDocument().addDocumentListener(this);
} |
636edb4e-a220-4860-b6bc-167363141a8c | 0 | private static void getCommand() {
System.out.print("[Moves:" + moves + " Score:" + score + " Ratio:" + ratio + " Possible directions:" + possibleDirs + "] ");
Scanner inputReader = new Scanner(System.in);
command = inputReader.nextLine();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.