text stringlengths 14 410k | label int32 0 9 |
|---|---|
public ExtDecimal dec() {
if (type == Type.NUMBER) {
return add(new ExtDecimal(-1));
} else if (type == Type.POSITIVEZERO) {
return MINUSONE;
} else if (type == Type.NEGATIVEZERO) {
return MINUSONE;
} else if (type == Type.INFINITY) {
return INFINITY;
} else if (type == Type.NEGATIVEINFINITY) {
return NEGATIVEINFINITY;
} else {
throw new UnsupportedOperationException("Unknown type");
}
} | 5 |
public void averge(){
int grade;
int totalgrade;
int averagegrade = 0;
int counter;
counter=0;
totalgrade=0;
grade=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the grade or -1 to quit:");
grade=s.nextInt();
while(grade!=-1){
totalgrade=totalgrade+grade;
System.out.println("Enter the grade or -1 to quit:");
grade=s.nextInt();
counter++;
}
System.out.println("Total:"+totalgrade);
if(counter!=0)
{
averagegrade=totalgrade/counter;
System.out.println("Average:"+averagegrade );
}
else{
System.out.println("No enter the grade" );
}
} | 2 |
boolean checksum( String sentence, String checksum )
{
int cs = 0;
for( int i = 0; i < sentence.length(); i++ )
cs ^= sentence.charAt(i);
//checksums match?
return Integer.parseInt( checksum, 16 ) == cs;
} | 1 |
private void initPatients(int totalTime) {
int time = 0;
while (time < totalTime) {
Patient p = new Patient(this.patients.size(), time);
this.patients.add(p);
time += this.generateNextCustomerEntranceInterval();
}
} | 1 |
private EditorPane createEditor(final Component panel) {
final SelectionDrawer drawer = new SelectionDrawer(dfa);
EditorPane editor = new EditorPane(drawer, new ToolBox() {
public java.util.List tools(AutomatonPane view,
AutomatonDrawer drawer) {
java.util.List tools = new java.util.LinkedList();
tools.add(new ArrowNontransitionTool(view, drawer) {
public boolean shouldAllowOnlyFinalStateChange() {
return true;
}
public boolean shouldShowStatePopup() {
return true;
}
});
tools.add(new GotoTransitionTool(view, drawer, controller));
return tools;
}
});
// addExtras(editor.getToolBar());
return editor;
} | 0 |
public void availableSlavesPolicy (int availableslaves) {
System.out.println("availableSlavesPolicy");
int pending = pendingVMs.size();
int numberofslaves = resourcePool.size();
if (availableslaves+pending < 0.3*(numberofslaves) && numberofslaves+pending < maximumslaves) {
launchVMs(1);
} else if (availableslaves > 0.5*(numberofslaves) && pending == 0
&& numberofslaves > minimumslaves) {
shutdownVM();
} else if (availableslaves == numberofslaves && pending == 0 && numberofslaves > minimumslaves) {
shutdownVM();
}
} | 8 |
public static String rotateLeft(String str, int rotatePos){
if( rotatePos < 0 ){
throw new IllegalArgumentException("rotatePos < 0");
}
if( str == null ){
throw new IllegalArgumentException("Can't rotate NULL string");
}
final int strLength = str.length();
while( rotatePos > strLength ){
rotatePos = rotatePos % strLength;
}
// small optimization
if( rotatePos == 0 ){
return str;
}
final char[] arr = str.toCharArray();
final BitSet rotatedPositions = new BitSet(rotatePos);
char temp;
char temp2;
for( int i = 0; i < rotatePos; i++ ){
// skip already rotated position
if( rotatedPositions.get(i) ){
continue;
}
int index = strLength - rotatePos + i;
temp = arr[i];
while( true ){
temp2 = arr[index];
arr[index] = temp;
temp = temp2;
rotatedPositions.set(index);
if( index == i ){
break;
}
if( index < rotatePos ){
index = strLength - rotatePos + index;
}
else {
index = index - rotatePos;
}
}
}
return new String(arr);
} | 9 |
private void loadProperties(String path) {
ResourceBundle rbHome = ResourceBundle.getBundle(path);
Enumeration<String> actionEnumHome = rbHome.getKeys();
while(actionEnumHome.hasMoreElements())
{
String command = actionEnumHome.nextElement();;
String className = rbHome.getString(command);
try {
Class commandClass = Class.forName(className);
Object commandInstance = commandClass.newInstance();
commandMap.put( command, commandInstance);
} catch(ClassNotFoundException e) {
continue; // error
//throw new ServletException(e);
} catch(InstantiationException e) {
e.printStackTrace();
} catch(IllegalAccessException e) {
e.printStackTrace();
}
}
} | 4 |
private boolean move(float a_xa, float a_ya)
{
while (a_xa > 8)
{
if (!move(8, 0)) return false;
a_xa -= 8;
}
while (a_xa < -8)
{
if (!move(-8, 0)) return false;
a_xa += 8;
}
while (a_ya > 8)
{
if (!move(0, 8)) return false;
a_ya -= 8;
}
while (a_ya < -8)
{
if (!move(0, -8)) return false;
a_ya += 8;
}
//No collision detection. It's fair.
m_x += a_xa;
m_y += a_ya;
return true;
} | 8 |
final public CycList xorForm(boolean requireEOF) throws ParseException, java.io.IOException, UnsupportedVocabularyException {
CycObject sent = null;
CycObject sent2 = null;
CycList val = new CycList();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case XOR_CONSTANT:
jj_consume_token(XOR_CONSTANT);
break;
case XOR_GUID_CONSTANT:
jj_consume_token(XOR_GUID_CONSTANT);
break;
default:
jj_la1[7] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
val.add(getCycAccess().xorConst);
sent = sentence(false);
val.add(sent);
sent2 = sentence(false);
val.add(sent2);
eof(requireEOF);
{if (true) return val;}
throw new Error("Missing return statement in function");
} | 4 |
public static List<Map<Integer, Double>> startLdaCreation(BookmarkReader reader, int sampleSize, boolean sorting, int numTopics, boolean userBased, boolean resBased, boolean topicCreation, boolean smoothing) {
timeString = "";
int size = reader.getBookmarks().size();
int trainSize = size - sampleSize;
Stopwatch timer = new Stopwatch();
timer.start();
MalletCalculator userCalc = null;
List<Map<Integer, Integer>> userMaps = null;
//List<Double> userDenoms = null;
if (userBased) {
userMaps = Utilities.getUserMaps(reader.getBookmarks().subList(0, trainSize));
userCalc = new MalletCalculator(userMaps, numTopics);
userCalc.predictValuesProbs();
//userDenoms = getDenoms(userPredictionValues);
System.out.println("User-Training finished");
}
MalletCalculator resCalc = null;
List<Map<Integer, Integer>> resMaps = null;
//List<Double> resDenoms = null;
if (resBased) {
resMaps = Utilities.getResMaps(reader.getBookmarks().subList(0, trainSize));
resCalc = new MalletCalculator(resMaps, numTopics);
resCalc.predictValuesProbs();
//resDenoms = getDenoms(resPredictionValues);
System.out.println("Res-Training finished");
}
List<Map<Integer, Double>> results = new ArrayList<Map<Integer, Double>>();
if (trainSize == size) {
trainSize = 0;
}
timer.stop();
long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);
timer = new Stopwatch();
timer.start();
for (int i = trainSize; i < size; i++) { // the test set
Bookmark data = reader.getBookmarks().get(i);
int userID = data.getUserID();
int resID = data.getWikiID();
//Map<Integer, Integer> userMap = null;
//if (userBased && userMaps != null && userID < userMaps.size()) {
// userMap = userMaps.get(userID);
//}
//Map<Integer, Integer> resMap = null;
//if (resBased && resMaps != null && resID < resMaps.size()) {
// resMap = resMaps.get(resID);
//}
double userTagCount = 0.0;//Utilities.getMapCount(userMap);
double resTagCount = 0.0;//Utilities.getMapCount(resMap);
/*
double userDenomVal = 0.0;
if (userDenoms != null && userID < userDenoms.size()) {
userDenomVal = userDenoms.get(userID);
}
double resDenomVal = 0.0;
if (resDenoms != null && resID < resDenoms.size()) {
resDenomVal = resDenoms.get(resID);
}
*/
Map<Integer, Double> userPredMap = null;
if (userCalc != null) {
userPredMap = userCalc.getValueProbsForID(userID, topicCreation);
}
Map<Integer, Double> resPredMap = null;
if (resCalc != null) {
resPredMap = resCalc.getValueProbsForID(resID, topicCreation);
}
Map<Integer, Double> map = getRankedTagList(reader, userPredMap, userTagCount, resPredMap, resTagCount, sorting, smoothing, topicCreation);
results.add(map);
}
timer.stop();
long testTime = timer.elapsed(TimeUnit.MILLISECONDS);
timeString += ("Full training time: " + trainingTime + "\n");
timeString += ("Full test time: " + testTime + "\n");
timeString += ("Average test time: " + testTime / (double)sampleSize) + "\n";
timeString += ("Total time: " + (trainingTime + testTime) + "\n");
return results;
} | 6 |
private static void evaluateAndSavePredictions(Predictor predictor,
List<Instance> instances, String predictions_file) throws IOException {
PredictionsWriter writer = new PredictionsWriter(predictions_file);
// TODO Evaluate the model if labels are available.
AccuracyEvaluator e = new AccuracyEvaluator();
System.out.println("The accuracy is: "+ e.evaluate(instances, predictor));
for (Instance instance : instances) {
Label label = predictor.predict(instance);
writer.writePrediction(label);
}
writer.close();
} | 1 |
int serialisePair( byte[] bytes, int p, int setSize, int dataOffset,
int dataTableOffset, int parentId ) throws MVDException
{
try
{
int oldP = p;
int flag = 0;
if ( parent != null )
flag = CHILD_FLAG;
else if ( children != null )
flag = PARENT_FLAG;
if ( bytes.length > p + pairSize(setSize) )
{
p += serialiseVersions( bytes, p, setSize );
// write data offset
// can't see the point of this any more
//writeInt( bytes, p, (children==null)?dataOffset:-dataOffset );
writeInt( bytes, p, dataOffset );
p += 4;
// write data length ORed with the parent/child flag
int dataLength = (data==null)?0:this.byteLength();
dataLength |= flag;
writeInt( bytes, p, dataLength );
p += 4;
if ( parentId != MVD.NULL_PID )
{
writeInt( bytes, p, parentId );
p += 4;
}
// write actual data
if ( parent == null && !isHint() )
p += writeData( bytes, dataTableOffset+dataOffset, getData() );
}
else
throw new Exception( "No room for pair during serialisation" );
return p - oldP;
}
catch ( Exception e )
{
throw new MVDException(e);
}
} | 8 |
public static void write(Map<?, ?> map, File file) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file));
for (Map.Entry<?, ?> entry : map.entrySet()) {
writer.write(entry.getKey() + "=" + entry.getValue() + System.lineSeparator());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} | 8 |
@Override
public void delete(Sondage obj) {
PreparedStatement pst = null;
try {
pst = this.connect().prepareStatement("DELETE FROM Sondage where id=?;");
pst.setInt(1, obj.getId());
pst.executeUpdate();
System.out.println("suppression effectuer");
} catch (SQLException ex) {
Logger.getLogger(SondageDao.class.getName()).log(Level.SEVERE, "suppression echoué", ex);
}finally{
try {
if(pst != null)
pst.close();
} catch (SQLException ex) {
Logger.getLogger(SondageDao.class.getName()).log(Level.SEVERE, "liberation preparedstatement echoué", ex);
}
}
} | 3 |
private void updateWeights(){
//update the weights matrix based on the decisions made in the round
for (Decision d: myDecisions)
weights[d.getSlot()][d.getCard()]++;
} | 1 |
public void compress(long maxDelta) {
long[] bandBoundaries = computeBandBoundaries(maxDelta);
for (int i = this.numTuples - 2; i >= 0; i--) {
if (this.summary[i].delta >= this.summary[i + 1].delta) {
int band = 0;
while (this.summary[i].delta < bandBoundaries[band]) {
band++;
}
long belowBandThreshold = Long.MAX_VALUE;
if (band > 0) {
belowBandThreshold = bandBoundaries[band - 1];
}
long mergeG = this.summary[i + 1].g + this.summary[i].g;
int childI = i - 1;
while (((mergeG + this.summary[i + 1].delta) < maxDelta)
&& (childI >= 0)
&& (this.summary[childI].delta >= belowBandThreshold)) {
mergeG += this.summary[childI].g;
childI--;
}
if (mergeG + this.summary[i + 1].delta < maxDelta) {
// merge
int numDeleted = i - childI;
this.summary[childI + 1] = new Tuple(this.summary[i + 1].v,
mergeG, this.summary[i + 1].delta);
// todo complete & test this multiple delete
System.arraycopy(this.summary, i + 2, this.summary,
childI + 2, this.numTuples - (i + 2));
for (int j = this.numTuples - numDeleted; j < this.numTuples; j++) {
this.summary[j] = null;
}
this.numTuples -= numDeleted;
i = childI + 1;
}
}
}
} | 9 |
public static void listen() {
listener = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
if (rxSock == null || rxSock.isClosed()) {
rxSock = new ServerSocket(receivePort);
}
try {
waiting.add(rxSock.accept());
// Handle message reception in a new thread
new Thread() {
@Override
public void run() {
synchronized (listeners) {
for (CommsListener l : listeners) {
l.messageReceived();
}
}
}
}.start();
} catch (IOException ex) {
if (!ex.getMessage().equals("socket closed")) {
Alerter.getHandler().severe(
"Connection Listener",
"Unable to accept incoming message. "
+ ex.getMessage());
}
}
}
} catch (IOException ex) {
Alerter.getHandler().fatal(
"Connection Listener",
"Unable to listen for incoming messages. "
+ ex.getMessage());
} finally {
if (rxSock != null) {
try {
rxSock.close();
} catch (IOException ignore) {}
}
}
}
};
listener.start();
} | 9 |
public ObjectInstantiator newInstantiatorOf(Class type) {
if(!Serializable.class.isAssignableFrom(type)) {
throw new ObjenesisException(new NotSerializableException(type+" not serializable"));
}
if(JVM_NAME.startsWith(SUN)) {
if(VM_VERSION.startsWith("1.3")) {
return new Sun13SerializationInstantiator(type);
}
}
else if(JVM_NAME.startsWith(GNU)) {
return new GCJSerializationInstantiator(type);
}
else if(JVM_NAME.startsWith(PERC)) {
return new PercSerializationInstantiator(type);
}
return new ObjectStreamClassInstantiator(type);
} | 5 |
public ParkerPaulTime(String time) {
error = null;
String[] splitTime = time.split(":");
if (splitTime.length != 2) {
error = "Invalid or No separator entered";
return;
}
if (!applyHour(splitTime[0])) {
return;
}
if (!validateRange(hour, 0, 23, "Invalid hours entered: ")) {
return;
}
if (!applyMinute(splitTime[1])) {
return;
}
validateRange(minute, 0, 59, "Invalid minutes enter: ");
} | 4 |
private void extractOperator(Class<? extends IOperatorToken> operatorClass) {
Stack<Integer> positions = new Stack<Integer>();
// find operator positions
for (int i = size() - 1; i >= 0; i--) {
if (operatorClass.isInstance(get(i))) {
positions.push(i);
}
}
// offset, used when positions are updated while replacing tokens
int offset = 0;
while (!positions.isEmpty()) {
// get position of the next token
int pos = positions.pop() + offset;
IToken operatorToken = get(pos);
if (operatorToken instanceof TokenBinaryOperator) {
TokenBinaryOperator opToken = (TokenBinaryOperator) operatorToken;
// get operands
TokenList leftArg = get(pos - 1).wrapInTokenList();
TokenList rightArg = get(pos + 1).wrapInTokenList();
// build an operation
Operation op = opToken.toOperation(leftArg, rightArg);
// discard used tokens
subList(pos - 1, pos + 2).clear();
// put back the operation
add(pos - 1, op);
// shift offset
offset -= 2;
} else if (operatorToken instanceof TokenUnaryOperatorLeft) {
TokenUnaryOperatorLeft opToken = (TokenUnaryOperatorLeft) operatorToken;
// get operand
TokenList leftArg = get(pos - 1).wrapInTokenList();
// build an operation
Operation op = opToken.toOperation(leftArg);
// discard used tokens
subList(pos - 1, pos + 1).clear();
// put back the operation
add(pos - 1, op);
// shift offset
offset -= 1;
} else if (operatorToken instanceof TokenUnaryOperatorRight) {
TokenUnaryOperatorRight opToken = (TokenUnaryOperatorRight) operatorToken;
// variable for left operand
TokenList rightArg = get(pos + 1).wrapInTokenList();
// build an operation
Operation op = opToken.toOperation(rightArg);
// discard used tokens
subList(pos, pos + 2).clear();
// put back the operation
add(pos, op);
// shift offset
offset -= 1;
}
}
} | 7 |
boolean valid(int x, int y) {
if (x < 0 || y < 0)
return false;
if (x >= m)
return false;
if (y >= n)
return false;
return true;
} | 4 |
private CycList queryVariablesInternal(final CycList queryVariables,
final CycObject query,
final CycObject mt,
final InferenceParameters queryProperties,
final String inferenceProblemStoreName,
final long timeoutMsecs)
throws UnknownHostException, IOException, CycApiException {
//// Preconditions
if (queryVariables == null) {
throw new NullPointerException("queryVariables must not be null");
}
if (queryVariables.isEmpty()) {
throw new IllegalArgumentException("queryVariables must not be empty");
}
if (query == null) {
throw new NullPointerException("query must not be null");
}
if (mt == null) {
throw new NullPointerException("mt must not be null");
}
if (inferenceProblemStoreName == null) {
throw new NullPointerException("inferenceProblemStoreName must not be null");
}
if (inferenceProblemStoreName.length() == 0) {
throw new IllegalArgumentException("inferenceProblemStoreName must not be an empty list");
}
final InferenceParameters tempQueryProperties = (queryProperties == null) ? getHLQueryProperties() : queryProperties;
tempQueryProperties.put(makeCycSymbol(":problem-store"), makeCycSymbol("problem-store", false));
final String script =
"(clet ((problem-store (find-problem-store-by-name \"" + inferenceProblemStoreName + "\")))"
+ " (query-template " + queryVariables.stringApiValue() + " "
+ query.stringApiValue() + " " + makeELMt(mt).stringApiValue() + " " + queryPropertiesToString(tempQueryProperties) + "))";
SubLWorkerSynch worker = new DefaultSubLWorkerSynch(script, this, timeoutMsecs);
if (CycObjectFactory.nil.equals(worker.getWork())) {
return new CycList<Object>();
}
return (CycList) worker.getWork();
} | 8 |
public void showHint(LBNode n) {
if(intfHint.isVisible() || n.getHint().trim().equals("")) return;
intfHint.setTitle(n.getLabel());
hintNode=n;
hintWidth = n.getHintWidth();
if (n.getHintIsHTML()) {
tpHint.setEditorKit(new HTMLEditorKit());
URL documentBase = tgLinkBrowser.getDocumentBase();
if (documentBase!=null) ((HTMLDocument) tpHint.getDocument()).setBase(documentBase);
}
else {
tpHint.setEditorKit(new StyledEditorKit());
}
tpHint.setText(n.getHint());
int ix = (int) n.drawx;
int iy = (int) n.drawy;
spHint.getVerticalScrollBar().setVisible(false);
hintHeight = n.getHintHeight();
if(hintHeight<LBNode.MINIMUM_HINT_HEIGHT) {
//Set the height to 10, because we don't care what it is. We only need to set the
//width so that hintHight can be correctly determined.
tpHint.setSize(new Dimension(hintWidth-16,10));
hintHeight = tpHint.getPreferredScrollableViewportSize().height+40;
}
int topEdge = 0;
int tgPanelHeight = tgPanel.getSize().height;
int nodeHeight = n.getHeight()/2;
if(iy>tgPanelHeight/2 || iy-nodeHeight>hintHeight) {
hintHeight=Math.min(iy-nodeHeight,hintHeight);
topEdge = iy-hintHeight-nodeHeight;
}
else {
hintHeight=Math.min(tgPanelHeight-iy-nodeHeight,hintHeight);
topEdge = iy + nodeHeight;
}
int leftEdge=ix-hintWidth/2;
leftEdge = Math.max(Math.min(leftEdge,tgPanel.getWidth()-hintWidth),0);
intfHint.setSize(new Dimension(hintWidth,hintHeight));
intfHint.setLocation(leftEdge,topEdge);
intfHint.setVisible(true);
} | 7 |
private void exportToJournal() {
// TODO save movements (and counterparties) into accounting [or with different button]
int[] rows = tabel.getSelectedRows();
if (checkAccountAndSelection(rows)) {
if (checkCounterParties(rows)) {
Object[] accountList = accounts.getBusinessObjects().toArray();
Account bankAccount = (Account) JOptionPane.showInputDialog(this, "Select Bank account",
"Select account", JOptionPane.INFORMATION_MESSAGE, null, accountList, null);
Journal journal;
Object[] journalsList = journals.getBusinessObjects().toArray();
if (journals.getBusinessObjects().size() == 1) {
journal = (Journal) journalsList[0];
} else {
journal = (Journal) JOptionPane.showInputDialog(this, "Select Journal", "Select journal",
JOptionPane.INFORMATION_MESSAGE, null, journalsList, null);
}
if (bankAccount != null && journal != null) {
for(int i : rows) {
BusinessObject counterParty = (BusinessObject) tabel.getValueAt(i, 4);
Account account = ((CounterParty)counterParty).getAccount();
boolean debet = tabel.getValueAt(i, 2).equals("D");
if (account == null) {
BusinessObject counterParty2 = counterParties.getBusinessObject(counterParty.getName());
if (counterParty2 != null) {
counterParty = counterParty2;
account = ((CounterParty)counterParty2).getAccount();
}
}
while (account == null) {
account = (Account) JOptionPane.showInputDialog(this, "Select account", "Select account",
JOptionPane.INFORMATION_MESSAGE, null, accountList, null);
((CounterParty)counterParty).setAccount(account);
}
BigDecimal amount = (BigDecimal) tabel.getValueAt(i, 3);
Transaction transaction = journals.getCurrentObject().getCurrentObject();
Booking booking1 = new Booking(account, amount, debet);
Booking booking2 = new Booking(bankAccount, amount, !debet);
transaction.addBusinessObject(booking1);
transaction.addBusinessObject(booking2);
String cal = (String) tabel.getValueAt(i, 1);
Calendar date = Utils.toCalendar(cal);
transaction.setDate(date);
String description = (String) tabel.getValueAt(i, 6);
transaction.setDescription(description);
journal.addBusinessObject(transaction);
transaction = new Transaction(accounts, date, "");
// take the same date as previous transaction
// leave the description empty
journals.getCurrentObject().setCurrentObject(transaction);
}
}
}
}
refresh();
} | 9 |
public void setDate(LocalDate value) {
this._date = value;
} | 0 |
public GameState(int[] Perm, int inNumPlayers){
NumWolves = Perm.length - 1;
NumPlayers = inNumPlayers;
PlayerRoles = new int[NumPlayers];
for(int n = 0; n < NumPlayers; n++){
PlayerRoles[n] = 1; // Initialise all players to be living innocents.
}
for(int i = 0; i < Perm.length; i++){
int n = Perm[i];
PlayerRoles[n - 1] = i + 2;
}
TimeOfDeath = new int[NumPlayers];
RoundNum = 1;
} | 2 |
public static boolean isPermitted(String user, MessageEvent event) throws IllegalAccessException, SQLException, InstantiationException {
if (CommandLinks.permitted.contains(user) || isRegular(user,event,false)) {
return true;
} else {
if (!CommandLinks.strike1.contains(user)) {
event.getBot().sendRaw().rawLine("PRIVMSG " + event.getChannel().getName() + " :.timeout " + event.getUser().getNick() + " 5");
event.respond(Strings.strike1);
CommandLinks.strike1.add(user);
} else {
if (CommandLinks.strike1.contains(user)) {
event.getBot().sendRaw().rawLine("PRIVMSG " + event.getChannel().getName() + " :.timeout " + event.getUser()
.getNick() + Strings.bantime);
event.respond(Strings.strike2 + Strings.bantimeOnMSG);
CommandLinks.strike1.remove(user);
}
}
}
return false;
} | 4 |
@Override
public void setComponent(JComponent c) {
this.component = c;
} | 0 |
public double DeltaAdd(Instance inst, double r) {
//System.out.println("DeltaAdd");
int S_new;
int W_new;
double profit;
double profit_new;
double deltaprofit;
S_new = 0;
W_new = occ.size();
if (inst instanceof SparseInstance) {
//System.out.println("DeltaAddSparceInstance");
for (int i = 0; i < inst.numValues(); i++) {
S_new++;
if ((Integer) this.occ.get(inst.index(i)) == null) {
W_new++;
}
}
} else {
for (int i = 0; i < inst.numAttributes(); i++) {
if (!inst.isMissing(i)) {
S_new++;
if ((Integer) this.occ.get(i + inst.toString(i)) == null) {
W_new++;
}
}
}
}
S_new += S;
if (N == 0) {
deltaprofit = S_new / Math.pow(W_new, r);
} else {
profit = S * N / Math.pow(W, r);
profit_new = S_new * (N + 1) / Math.pow(W_new, r);
deltaprofit = profit_new - profit;
}
return deltaprofit;
} | 7 |
@Override
public void actionPerformed(ActionEvent e) {
try {
if (e.getActionCommand().equals("Voeg opdracht toe aan quiz")) {
voegOpdrachtToeAanQuiz();
} else if (e.getActionCommand().equals(" Verwijder opdracht in quiz ")) {
verwijderOpdrachtInQuiz();
} else if (e.getActionCommand().equals("Alle wijzigingen opslaan")) {
if (!quizWijzigenView.getCmbbxLeraar().getSelectedItem()
.equals(quizWijzigenView.getNotSelectableOption())
|| !quizWijzigenView.getCmbbxQuizStatus().getSelectedItem()
.equals(quizWijzigenView.getNotSelectableOption())) {
wijzigingQuizOpslaan();
} else {
quizWijzigenView.popUpWindow();
}
} else if (e.getActionCommand().equals("Wijzig quiz")) {
wijzigQuiz();
} else if (e.getActionCommand().equals("Annuleer")) {
annuleer();
}
} catch (Exception e2) {
System.out.println(e);
}
} | 8 |
public void rebuild() {
backButton = new GuiButton(this, 0, 300, 550, "gui.back");
videoButton = new GuiButton(this, 0, 100, 200, "gui.options.video");
videoVsyncButton = new GuiButton(this, 0, 100, 200, "gui.options.video.vsync." + (Client.instance.preferences.video.vsync ? "on" : "off"));
videoFullscreenButton = new GuiButton(this, 0, 100, 200, "gui.options.video.fullscreen." + (Client.instance.preferences.video.fullscreen ? "on" : "off"));
languageButton = new GuiButton(this, 0, 100, 200, "gui.options.language");
languageButtons.clear();
gameButton = new GuiButton(this, 0, 100, 200, "gui.options.game");
gameArrowButton = new GuiButton(this, 0, 100, 200, "gui.options.game.arrow");
gameZoomButton = new GuiButton(this, 0, 100, 200, "gui.options.game.zoom." + (Client.instance.preferences.game.invertZoom ? "inverted" : "normal"));
arrowButtons.clear();
setSection(section);
} | 3 |
private void updateTurnOption() {
if(model.getTurnOptionState() == Model.TurnOptionState.DEACTIVATED) {
turnOption.setEnabled(false);
} else {
turnOption.setEnabled(true);
}
switch(model.getTurnOptionState()) {
case THROWDICE:
turnOptionText = "Wuerfeln";
break;
case THROWDICEAGAIN:
turnOptionText = "Erneut Wuerfeln";
break;
case ENDTURN:
turnOptionText = "Zug beenden";
break;
case DEACTIVATED:
turnOptionText = "Wuerfeln";
break;
}
turnOption.setText(turnOptionText);
} | 5 |
public static boolean isMove(Commands one, Commands two){
boolean path = getFileName(one).equals(getFileName(two));
boolean cata = one.getCatalog() == two.getCatalog();
//Null check and makes sure that the commands are opposite
boolean comm = !(((one.getCommand() == null) || (two.getCommand() == null)) || one.getCommand().equals(two.getCommand())) ;
return path && cata && comm;
} | 4 |
public void run() {
DbConnection dbConn = new DbConnection();
Connection conn = dbConn.getConnection();
try {
String statement;
while (true) {
Statement stmt = conn.createStatement();
statement = ImageStorage.statementsPoll();
try {
if (statement != null) {
stmt.execute(statement);
} else if (ImageStorage.isEndStatement()) {
stmt.close();
break;
} else {
Thread.sleep(1000);
}
} catch (MySQLSyntaxErrorException e) {
System.out.println(statement);
}
}
System.out.println("Base Data Thread finished");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
dbConn.closeConnection(conn);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} | 7 |
protected Object computeBounds() {
Envelope bounds = null;
for (Iterator i = getChildBoundables().iterator(); i.hasNext(); ) {
Boundable childBoundable = (Boundable) i.next();
if (bounds == null) {
bounds = new Envelope((Envelope)childBoundable.getBounds());
}
else {
bounds.expandToInclude((Envelope)childBoundable.getBounds());
}
}
return bounds;
} | 2 |
public static File choose(Component comp, boolean open, String title, String dir, String name, String... extension) {
StdFileDialog filter = new StdFileDialog(extension);
FileDialog dialog;
Window window = WindowUtils.getWindowForComponent(comp);
int mode = open ? FileDialog.LOAD : FileDialog.SAVE;
if (window instanceof Frame) {
dialog = new FileDialog((Frame) window, title, mode);
} else {
dialog = new FileDialog((Dialog) window, title, mode);
}
dialog.setFilenameFilter(filter);
dialog.setDirectory(dir);
dialog.setFile(name);
dialog.setVisible(true);
String result = dialog.getFile();
if (result != null) {
if (filter.accept(null, result)) {
File file = new File(dialog.getDirectory(), result);
RecentFilesMenu.addRecent(file);
return file;
} else if (!open) {
File file = new File(dialog.getDirectory(), PathUtils.enforceExtension(result, extension[0]));
RecentFilesMenu.addRecent(file);
return file;
}
showCannotOpenMsg(comp, result, null);
}
return null;
} | 5 |
public boolean equals(Object object) {
if (object instanceof ActivityNode) {
ActivityNode actNode = (ActivityNode) object;
if ((this.activity == null || actNode.getActivity() == null) &&
!(this.activity == null && actNode.getActivity() == null)) {
return false;
}
if (this.nodeNr != actNode.nodeNr) {
return false;
}
if (this.activity != null && actNode.getActivity() != null &&
!this.activity.equals(actNode.getActivity())) {
return false;
}
return true;
}
return false;
} | 9 |
public void majPlateau(Positions pos, Positions newPos)
{
if (!(newPos == null))
{
this.plateau[pos.getLigne()][pos.getColonne()] = EtatDesCases.LIBRE;
this.plateau[newPos.getLigne()][newPos.getColonne()] = EtatDesCases.OCCUPEE;
return;
}
if (this.plateau[pos.getLigne()][pos.getColonne()] == EtatDesCases.OCCUPEE)
return;
this.plateau[pos.getLigne()][pos.getColonne()] = EtatDesCases.OCCUPEE;
} | 2 |
public void draw(Graphics2D g) {
for (int row = 0; row < mapHeight; row++) {
for (int column = 0; column < mapWidth; column++) {
int currentTile = map[row][column];
tilesSpec.position.x = column * tilesSpec.size;
tilesSpec.position.y = row * tilesSpec.size;
switch (currentTile) {
case 0:
g.drawImage(wall, tilesSpec.position.x,
tilesSpec.position.y, null);
break;
case 1:
g.setColor(Color.BLACK);
g.fillRect(tilesSpec.position.x, tilesSpec.position.y,
tilesSpec.size, tilesSpec.size);
break;
case 2:
g.drawImage(grass, tilesSpec.position.x,
tilesSpec.position.y, null);
break;
case 3:
g.drawImage(tree1, tilesSpec.position.x,
tilesSpec.position.y, null);
break;
case 4:
g.drawImage(tree2, tilesSpec.position.x,
tilesSpec.position.y, null);
break;
case 5:
g.drawImage(flower, tilesSpec.position.x,
tilesSpec.position.y, null);
break;
case 6:
g.drawImage(bush, tilesSpec.position.x,
tilesSpec.position.y, null);
break;
default:
break;
}
}
}
} | 9 |
public void setCommandButtonBorderthickness(int[] border) {
if ((border == null) || (border.length != 4)) {
this.buttonCom_Borderthickness = UIBorderthicknessInits.COM_BTN.getBorderthickness();
} else {
this.buttonCom_Borderthickness = border;
}
somethingChanged();
} | 2 |
public void killAll() {
for (int i = 0; i < bots.size(); i++) {
bots.get(i).close();
}
} | 1 |
public void setLastName(String lastName) {
this.lastName = lastName;
} | 0 |
public Object clone() {
return new Turtle(this);
} | 0 |
@Override
public String getOOXML()
{
StringBuffer ooxml = new StringBuffer();
if( cxnSp != null )
{
ooxml.append( cxnSp.getOOXML() );
}
if( graphicFrame != null )
{
ooxml.append( graphicFrame.getOOXML() );
}
if( grpSp != null )
{
ooxml.append( grpSp.getOOXML() );
}
if( pic != null )
{
ooxml.append( pic.getOOXML() );
}
if( sp != null )
{
ooxml.append( sp.getOOXML() );
}
return ooxml.toString();
} | 5 |
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
if (args.length != 1) {
sender.sendMessage("/delmail <ID>");
return true;
}
ResultSet rs;
java.sql.Statement stmt;
Connection con;
try {
String Playername = player.getName().toLowerCase();
con = service.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM SM_Mail WHERE id='" + args[0] + "'");
if (!rs.getString("target").equalsIgnoreCase(Playername)) {
sender.sendMessage(plugin.GRAY+"[SimpleMail] "+plugin.RED+"This is not your message to delete or it does not exist. ");
} else {
stmt.executeUpdate("DELETE FROM SM_Mail WHERE id='"+args[0]+"' AND target='"+Playername+"'");
sender.sendMessage(plugin.GRAY+"[SimpleMail] "+plugin.GREEN+"Message Deleted.");
}
rs.close();
} catch(Exception e) {
if (e.toString().contains("ResultSet closed")) {
sender.sendMessage(plugin.GRAY+"[SimpleMail] "+plugin.RED+"This is not your message to delete or it does not exist.");
} else if (e.toString().contains("java.lang.ArrayIndexOutOfBoundsException")) {
sender.sendMessage("/delmail <id>");
} else {
plugin.log.info("[SimpleMail] "+"Error: "+e);
player.sendMessage(plugin.GRAY+"[SimpleMail] "+plugin.RED+"Error: "+plugin.WHITE+e);
}
}
return true;
} | 6 |
@Override
/*public void focusGained(FocusEvent evt) {
if (evt.getSource() == dataPacketText) {
dataPacketText.setText("");
}
}
@Override
public void focusLost(FocusEvent evt) {
// do nothing
}*/
public void actionPerformed(ActionEvent evt){
if (evt.getSource() == connectBtn) {
serialPortManager.connect();
if (serialPortManager.getConnectionStatus() == true)
{
if (serialPortManager.initIOStream() == true)
{
serialPortManager.initListener();
}
}
//logFile.WriteHeader();
} else if (evt.getSource() == disconnectBtn) {
resetTimePerCycle();
serialPortManager.disconnect();
//networkThread.interrupt();
System.out.println(networkThread.getName() + " 's status is: " + networkThread.getState());
} /*else if (evt.getSource() == dataPacketText) {
logAreaText.append("Default packet value changed" + "\n");
}*/ else if (evt.getSource() == sendBtn) {
//timePerCycle++;
//timeSlotValueLabel.setText(String.valueOf(timePerCycle));
if (!networkThread.isAlive() && !networkThread.isInterrupted()) {
networkThread.start();
}
//serialPortManager.sendData(0, 0, 0, 0);
} else if (evt.getSource() == dataPacketButton) {
String packetText = dataPacketButton.getText();
StringTokenizer token = new StringTokenizer(packetText, ",");
int botId = Integer.parseInt(token.nextToken());
int parent = Integer.parseInt(token.nextToken());
int timeSlot = Integer.parseInt(token.nextToken());
int packetSubTree = Integer.parseInt(token.nextToken());
serialPortManager.sendData(botId, parent, timeSlot, packetSubTree);
System.out.println(networkThread.getName() + " 's status is: " + networkThread.getState());
}
} | 8 |
protected Behaviour getNextStep() {
if (stage >= STAGE_DONE) return null ;
if (type != TYPE_CONTACT && ! canTalk(other)) {
abortBehaviour() ;
return null ;
}
if (starts == actor && stage == STAGE_INIT) {
final Action greeting = new Action(
actor, other,
this, "actionGreet",
Action.TALK, "Greeting "
) ;
greeting.setProperties(Action.RANGED) ;
return greeting ;
}
if (stage == STAGE_CHAT) {
Actor chatsWith = ((Dialogue) Rand.pickFrom(sides())).actor ;
if (chatsWith == actor) chatsWith = other ;
final Action chats = new Action(
actor, chatsWith,
this, "actionChats",
Action.TALK_LONG, "Chatting with "
) ;
setLocationFor(chats) ;
return chats ;
}
if (stage == STAGE_BYE) {
final Action farewell = new Action(
actor, other,
this, "actionFarewell",
Action.TALK, "Saying farewell to "
) ;
farewell.setProperties(Action.RANGED) ;
return farewell ;
}
return null ;
} | 8 |
public void insert(Key v)
{
// Insert
pq[++N] = v;
int i = swim(N);
// resizing
if (N >= pq.length - 1)
pq = resize(pq, 2 * pq.length);
// Mark the min
if (minIndex == -1)
minIndex = i;
else if (v.compareTo(pq[minIndex]) < 0)
minIndex = i;
} | 3 |
private boolean findEntry() {
Cursor waitCursor = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
shell.setCursor(waitCursor);
boolean matchCase = searchDialog.getMatchCase();
boolean matchWord = searchDialog.getMatchWord();
String searchString = searchDialog.getSearchString();
int column = searchDialog.getSelectedSearchArea();
searchString = matchCase ? searchString : searchString.toLowerCase();
boolean found = false;
if (searchDialog.getSearchDown()) {
for(int i = table.getSelectionIndex() + 1; i < table.getItemCount(); i++) {
if (found = findMatch(searchString, table.getItem(i), column, matchWord, matchCase)){
table.setSelection(i);
break;
}
}
} else {
for(int i = table.getSelectionIndex() - 1; i > -1; i--) {
if (found = findMatch(searchString, table.getItem(i), column, matchWord, matchCase)){
table.setSelection(i);
break;
}
}
}
shell.setCursor(null);
waitCursor.dispose();
return found;
} | 6 |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MultiBelop other = (MultiBelop) o;
if (nokkelBelopMap.size()!= nokkelBelopMap.size()) {
return false;
}
for(T key : nokkelBelopMap.keySet())
if (!other.nokkelBelopMap.containsKey(key)) {
return false;
}
for(T key : nokkelBelopMap.keySet()) {
if(!nokkelBelopMap.get(key).equals(other.nokkelBelopMap.get(key))) {
return false;
}
}
return true;
} | 8 |
public static void main(String[] args)
{
if (args.length != 1)
System.out.println("Please specify a Unit Test Case name");
else
{
LogQuerierTest lqTest = new LogQuerierTest();
if(args[0].compareTo("-generateLogs") == 0)
{
lqTest.genrateLogFiles();
return;
}
if((new File("unit_tests/" + args[0])).exists())
{
String unitTestName = args[0];
try
{
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("unit_tests/" + unitTestName + "/unit_test.prop");
prop.load(fis);
fis.close();
if(lqTest.executeDistributedQuery(prop.getProperty("key"), prop.getProperty("value"), unitTestName) &&
lqTest.cleanUpDistributedOutput(unitTestName) &&
lqTest.executeLocalQuery(prop.getProperty("key"), prop.getProperty("value"), unitTestName) &&
lqTest.compareOutputs(unitTestName))
System.out.println("Unit Test Case : " + unitTestName + " was SUCCESSFULLY executed");
else
System.out.println("Unit Test Case : " + unitTestName + " FAILED");
}
catch(IOException ioe)
{
System.out.println("ERROR : Exeception while executing unit test : " + unitTestName);
}
}
else
{
System.out.println("ERROR : Invalid Unit Test Case name. Please enter a valid Unit Test Case name");
}
}
} | 8 |
public MemoryUsagePanel() {
super();
// initializes members
m_Memory = new Memory();
m_History = new Vector<Double>();
m_Percentages = new Vector<Double>();
m_Colors = new Hashtable<Double,Color>();
// colors and percentages
m_BackgroundColor = parseColor("BackgroundColor", Color.WHITE);
m_DefaultColor = parseColor("DefaultColor", Color.GREEN);
String[] percs = PROPERTIES.getProperty("Percentages", "70,80,90").split(",");
for (int i = 0; i < percs.length; i++) {
// do we have a color associated with percentage?
if (PROPERTIES.getProperty(percs[i]) != null) {
double perc;
Color color;
// try parsing the number
try {
perc = Double.parseDouble(percs[i]);
}
catch (Exception e) {
System.err.println(
"MemoryUsagePanel: cannot parse percentage '"
+ percs[i] + "' - ignored!");
continue;
}
// try parsing the color
color = parseColor(percs[i], null);
if (color == null)
continue;
// store color and percentage
m_Percentages.add(perc);
m_Colors.put(perc, color);
}
else {
System.err.println(
"MemoryUsagePanel: cannot find color for percentage '"
+ percs[i] + "' - ignored!");
}
}
Collections.sort(m_Percentages);
// layout
setLayout(new BorderLayout());
JPanel panel = new JPanel(new BorderLayout());
add(panel, BorderLayout.EAST);
m_ButtonGC = new JButton("GC");
m_ButtonGC.setToolTipText("Runs the garbage collector.");
m_ButtonGC.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.gc();
}
});
panel.add(m_ButtonGC, BorderLayout.NORTH);
// dimensions
int height;
int width;
try {
height = Integer.parseInt(PROPERTIES.getProperty("Height", "" + (int) m_ButtonGC.getPreferredSize().getHeight()));
width = Integer.parseInt(PROPERTIES.getProperty("Width", "400"));
}
catch (Exception e) {
System.err.println("MemoryUsagePanel: Problem parsing the dimensions - " + e);
height = (int) m_ButtonGC.getPreferredSize().getHeight();
width = 400;
}
setPreferredSize(new Dimension(width, height));
// position
int top;
int left;
try {
top = Integer.parseInt(PROPERTIES.getProperty("Top", "0"));
left = Integer.parseInt(PROPERTIES.getProperty("Left", "0"));
}
catch (Exception e) {
System.err.println("MemoryUsagePanel: Problem parsing the position - " + e);
top = 0;
left = 0;
}
m_FrameLocation = new Point(left, top);
// monitoring thread
int interval;
try {
interval = Integer.parseInt(PROPERTIES.getProperty("Interval", "1000"));
}
catch (Exception e) {
System.err.println("MemoryUsagePanel: Problem parsing the refresh interval - " + e);
interval = 1000;
}
m_Monitor = new MemoryMonitor();
m_Monitor.setInterval(interval);
m_Monitor.setPriority(Thread.MAX_PRIORITY);
m_Monitor.start();
} | 7 |
private void hold() {
if (hold.isEnabled()) {
hold.setEnabled(false);
if (hold.getTetromino() == null) {
initializePositions();
hold.setTetromino(tetromino);
getNextTetromino();
}
else {
initializePositions();
Tetromino tmp = hold.getTetromino();
hold.setTetromino(tetromino);
tetromino = tmp;
}
}
} | 2 |
public PlanSkill(JSONObject skill) throws FatalError {
super("Skill");
try {
category = skill.getString("Kategorie");
try {
count = skill.getInt("Anzahl");
} catch (JSONException e) {
}
try {
bank = skill.getBoolean("Bank");
} catch (JSONException e) {
}
} catch (JSONException e) {
throw new ConfigError("Skill");
}
} | 3 |
public static int getFriendlySupport(Game game, Position position,
Player player) {
Iterator<Position> neighborhood = get8NeighborhoodIterator(position);
Position p;
int support = 0;
while ( neighborhood.hasNext() ) {
p = neighborhood.next();
if ( game.getUnitAt(p) != null &&
game.getUnitAt(p).getOwner() == player ) {
support++;
}
}
return support;
} | 3 |
public void getFullName() {
fullName.toString();
} | 0 |
void BaseExpr() {
printer.startProduction("BaseExpr");
switch (la.kind) {
case 9: {
Get();
printer.print(stack.size() + ": In with: " + currentType);
this.enterParenthesis(this.currentType);
Expr();
Expect(10);
this.exitParenthesis();
printer.print(stack.size() + ": Out with: " + lastType);
printer.endProduction("BaseExpr");
break;
}
case 1: {
IdAccess();
printer.endProduction("BaseExpr");
break;
}
case 2: {
Get();
printer.print(t.val);
this.checkInteger(t.val);
printer.endProduction("BaseExpr");
break;
}
case 18: {
Get();
printer.print(t.val);
this.lastType = BOOLEAN;
this.isExpected(BOOLEAN);
this.generator.push(1);
printer.endProduction("BaseExpr");
break;
}
case 19: {
Get();
printer.print(t.val);
this.lastType = BOOLEAN;
this.isExpected(BOOLEAN);
this.generator.push(0);
printer.endProduction("BaseExpr");
break;
}
case 20: {
Get();
this.lastType = INTEGER;
this.isExpected(INTEGER);
this.generator.commandRead();
break;
}
default: SynErr(36); break;
}
} | 6 |
public RestrictedAction(String string, Icon icon) {
super(string, icon);
} | 0 |
@Override
public boolean equals( Object obj ) {
if( obj == this ) {
return true;
}
if( obj == null || obj.getClass() != getClass() ) {
return false;
}
DefaultItemKey<?> that = (DefaultItemKey<?>) obj;
return that.id == id && that.typeName.equals( typeName );
} | 6 |
@EventHandler
public void CaveSpiderSpeed(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getCaveSpiderConfig().getDouble("CaveSpider.Speed.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getCaveSpiderConfig().getBoolean("CaveSpider.Speed.Enabled", true) && damager instanceof CaveSpider && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, plugin.getCaveSpiderConfig().getInt("CaveSpider.Speed.Time"), plugin.getCaveSpiderConfig().getInt("CaveSpider.Speed.Power")));
}
} | 6 |
public void afficherPraticien(Praticien unPraticien) { /*Lieu exercice a ajouter */
this.vue.getjTextFieldNum().setText(unPraticien.getNumero());
this.vue.getjTextFieldNom().setText(unPraticien.getNom());
this.vue.getjTextFieldPrenom().setText(unPraticien.getPrenom());
this.vue.getjTextFieldAdresse().setText(unPraticien.getAdresse());
this.vue.getjTextFieldVilleCP().setText(unPraticien.getCp());
this.vue.getjTextFieldVilleNom().setText(unPraticien.getVille());
this.vue.getjTextFieldCoefNot().setText(unPraticien.getCoef());
TypePraticien unTypePraticien=DaoTypePraticienJPA.selectOne(em, unPraticien.getCode());
this.vue.getjTextFieldLieux().setText(unTypePraticien.getLibelle());
} | 0 |
/* */ public static void sendPacket(Player p, Object packet)
/* */ {
/* */ try {
/* 68 */ Object nmsPlayer = getHandle(p);
/* 69 */ Field con_field = nmsPlayer.getClass().getField("playerConnection");
/* 70 */ Object con = con_field.get(nmsPlayer);
/* 71 */ Method packet_method = getMethod(con.getClass(), "sendPacket");
/* 72 */ packet_method.invoke(con, new Object[] { packet });
/* */ } catch (SecurityException e) {
/* 74 */ e.printStackTrace();
/* */ } catch (IllegalArgumentException e) {
/* 76 */ e.printStackTrace();
/* */ } catch (IllegalAccessException e) {
/* 78 */ e.printStackTrace();
/* */ } catch (InvocationTargetException e) {
/* 80 */ e.printStackTrace();
/* */ } catch (NoSuchFieldException e) {
/* 82 */ e.printStackTrace();
/* */ }
/* */ } | 5 |
public Path(String path)
{
this.path = path;
pathArray = trimSlashes(path).split(DELIMITER);
} | 0 |
@Override
public boolean checkLife() {
if (curHP <= 0) {
return false;
} else {
return true;
}
} | 1 |
private final void promoteSuccs(Instruction from, Instruction to) {
if (succs == from)
succs = to;
else if (succs instanceof Instruction[]) {
Instruction[] ss = (Instruction[]) succs;
for (int i = 0; i < ss.length; i++)
if (ss[i] == from)
ss[i] = to;
}
} | 4 |
private void initMachine(Collection<State> states) {
if (states == null || states.size() == 0) {
throw new NullPointerException("Machine must have at least one state");
}
//put all the states into the hash map
int numStartStates = 0;
for (State state : states) {
numStartStates += state.isStart()? 1 : 0;
this.states.put(state.getID(), state);
}
if (numStartStates != 1) { //Invalid number of start states
throw new InvalidParameterException("There must be exactly one start state");
}
this.alphabet = new char[] {'0', '1'};
} | 5 |
public void run(){
DataInputStream dIn = user.getInput();
boolean done = false;
try {
while(!done) {
byte messageType = dIn.readByte();
switch(messageType)
{
case 1: // Chat messg
Server.printMessage(user.getName() + ": " +dIn.readUTF(), user);
break;
case 2: // Command
int iterations = dIn.readByte();
ArrayList<String> command = new ArrayList<String>();
for(int i=0;i<iterations;i++){
command.add(dIn.readUTF());
}
Iterator<String> commandIterator = command.iterator();
commandIterator.next();
/*Command Handler*/
switch(command.get(0).toLowerCase()){
case "name":
StringBuilder sb = new StringBuilder();
sb.append(commandIterator.next());
while(commandIterator.hasNext()){
sb.append(" " +commandIterator.next());
}
Server.printMessage("User " + user.getName() + " is now " + sb.toString(), null);
user.setName(sb.toString());
}
break;
case -1:
Server.removeUser(user);
dIn.close();
done = true;
break;
default:
done = false;
}
}
} catch (IOException e) {
e.printStackTrace();
}
} | 8 |
private byte[] crypt_raw(byte password[], byte salt[], int log_rounds) {
int rounds, i, j;
int cdata[] = (int[])bf_crypt_ciphertext.clone();
int clen = cdata.length;
byte ret[];
if (log_rounds < 4 || log_rounds > 31)
throw new IllegalArgumentException ("Bad number of rounds");
rounds = 1 << log_rounds;
if (salt.length != BCRYPT_SALT_LEN)
throw new IllegalArgumentException ("Bad salt length");
init_key();
ekskey(salt, password);
for (i = 0; i < rounds; i++) {
key(password);
key(salt);
}
for (i = 0; i < 64; i++) {
for (j = 0; j < (clen >> 1); j++)
encipher(cdata, j << 1);
}
ret = new byte[clen * 4];
for (i = 0, j = 0; i < clen; i++) {
ret[j++] = (byte)((cdata[i] >> 24) & 0xff);
ret[j++] = (byte)((cdata[i] >> 16) & 0xff);
ret[j++] = (byte)((cdata[i] >> 8) & 0xff);
ret[j++] = (byte)(cdata[i] & 0xff);
}
return ret;
} | 7 |
@Override
public void load() throws IOException
{
FileInputStream fileInputStream = new FileInputStream(new File(file));
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd,MM,yyyy");
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++)
{
try
{
XSSFSheet sheet = workbook.getSheetAt(sheetNum);
if (sheet.getSheetName().startsWith("P"))
{
CellReference cellReference = new CellReference("D61");
XSSFRow row = sheet.getRow(cellReference.getRow());
XSSFCell cell = row.getCell(cellReference.getCol());
double scrapPct;
DateTime parsedTime;
if (cell != null)
{
CellValue cellValue = evaluator.evaluate(cell);
scrapPct = cellValue.getNumberValue();
cellReference = new CellReference("C3");
row = sheet.getRow(cellReference.getRow());
cell = row.getCell(cellReference.getCol());
if (cell != null)
{
cellValue = evaluator.evaluate(cell);
String cellAsString = cellValue.getStringValue();
if (cellAsString != null)
{
parsedTime = fmt.parseDateTime(cellAsString);
parsedTime = parsedTime.plusHours(23).plusMinutes(59);
Map<String, String> map = new HashMap<>();
map.put("scrap", String.valueOf(scrapPct * 100));
addToDB("scrap", rounder.round(parsedTime.getMillis()), parsedTime.getMillis(), map);
}
}
}
}
}
catch (Exception ex)
{
LoggerFactory.getLogger(this.getClass().getName()).error(ex.toString());
}
}
} | 6 |
@Override
protected void doEditing() {
if (this.col == 0) {
component.model.removeRow(this.row);
}
} | 1 |
public void renderGame(Game game) {
Ship ship = game.getShip();
List<Bullet> bullets = game.getBullets();
List<Asteroid> asteroids = game.getAsteroids();
List<Alien> aliens = game.getAliens();
List<Powerup> powerups = game.getPowerups();
List<Particle> particles = game.getParticles();
long points = game.getPoints();
int level = game.getLevel();
int accuracy = ship.getAccuracy();
// Prepare buffer strategy and graphics
BufferStrategy bufferStrategy = getBufferStrategy();
if (bufferStrategy == null) {
createBufferStrategy(2);
return;
}
Graphics2D g = (Graphics2D)bufferStrategy.getDrawGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
super.paint(g);
// Render entities
Renderer.render(ship, g);
for (Bullet b : bullets) {
Renderer.render(b, g);
}
for (Asteroid asteroid : asteroids) {
Renderer.render(asteroid, g);
}
for (Alien alien : aliens) {
Renderer.render(alien, g);
}
for (Powerup p : powerups) {
Renderer.render(p, g);
}
for (Particle p : particles) {
Renderer.render(p, g);
}
// Render HUD
Renderer.renderHUD(points, level, accuracy, g);
// Clean up and show
g.dispose();
bufferStrategy.show();
} | 6 |
private TuplesWithNameTable updateTuplesByCond(Condition cond, ArrayList<AttrAssign> attrAssignList, ArrayList<Integer> PrimaryKeyList, TuplesWithNameTable tuples){
Hashtable<String, Integer> nameTable = tuples.getNameTable();
//Tuple list will be modified directly
ArrayList< ArrayList<Value> > tupleList = tuples.getTupleList();
//Check primary key list
//NOT FINISHED!
ArrayList<Value> firstTuple = tupleList.get(0);
//Check update values type
for(AttrAssign attrAssign : attrAssignList){
Value updatingValue = attrAssign.getValue();
String valueName = attrAssign.getAttrName();
Integer valuePos = nameTable.get(valueName);
Value currentValue = firstTuple.get(valuePos.intValue());
if(currentValue.getType() != updatingValue.getType()){
throw new Error("UPDATE: Updating Value " + valueName + " has invalid type");
}
}
int updatedValueNum = 0;
//If no update condition, update all values
if(cond == null){
for(ArrayList<Value> tuple : tupleList){
for(AttrAssign attrAssign : attrAssignList){
String attrName = attrAssign.getAttrName();
Integer attrPos = nameTable.get(attrName);
tuple.set(attrPos.intValue(), attrAssign.getValue());
}
updatedValueNum++; //Update tuple num
}
}else{
//Evaluate condition and update tuples that satisfies the condition
Exp exp = cond.getExp();
Object ret;
for(ArrayList<Value> tuple : tupleList){
ret = exp.accept(this, nameTable, tuple);
if(ret instanceof Boolean){
if( ((Boolean) ret).booleanValue() == true ){
for(AttrAssign attrAssign : attrAssignList){
String attrName = attrAssign.getAttrName();
Value updatedValue = attrAssign.getValue();
int namePos = nameTable.get(attrName).intValue();
tuple.set(namePos, updatedValue);
}
updatedValueNum++; //Update tuple num
}
}
}
}
TuplesWithNameTable tupleTable = new TuplesWithNameTable(nameTable, tupleList);
tupleTable.setUpdatedTuplesNum(updatedValueNum);
return tupleTable;
} | 9 |
public static void submitStackTraces(Context context) {
Log.d(Constants.TAG, "Looking for exceptions in: " + Constants.FILES_PATH);
String[] list = searchForStackTraces();
if ((list != null) && (list.length > 0)) {
Log.d(Constants.TAG, "Found " + list.length + " stacktrace(s).");
for (int index = 0; index < list.length; index++) {
try {
// Read contents of stack trace
StringBuilder contents = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(context.openFileInput(list[index])));
String line = null;
while ((line = reader.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
reader.close();
String stacktrace = contents.toString();
// Transmit stack trace with POST request
Log.d(Constants.TAG, "Transmitting crash data: \n" + stacktrace);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(getURLString());
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("raw", stacktrace));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
httpClient.execute(httpPost);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
context.deleteFile(list[index]);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
} | 6 |
public void joueurSuivant() {
setEtape(0);
/* on calcule les gains du tour et on met à jour les pts de victoire */
int argent = joueurEnCours.calcArgentTour();
Game.getInstance().showTemp(argent + " point(s) gagné(s) durant ce tour !");
joueurEnCours.addArgent(argent);
if (indexJoueurEnCours == lstJoueurs.size() - 1) {
nouveauTour();
}
else {
indexJoueurEnCours++;
joueurEnCours = lstJoueurs.get(indexJoueurEnCours);
if (joueurEnCours.getPeuple() == null) {
Game.getInstance().selectionPeuple();
}
else if (joueurEnCours.getPeuple().getNbUnite() == 0) {
remettreBoite(joueurEnCours.getPeuple());
Game.getInstance().selectionPeuple();
}
miseEnMain();
Game.getInstance().showTemp(joueurEnCours.getNom() + " attaque !");
}
} | 3 |
public static ComplexPoly rootsToPoly(Complex[] roots){
if(roots==null)return null;
int pdeg = roots.length;
Complex[] rootCoeff = Complex.oneDarray(2);
rootCoeff[0] = roots[0].times(Complex.minusOne());
rootCoeff[1] = Complex.plusOne();
ComplexPoly rPoly = new ComplexPoly(rootCoeff);
for(int i=1; i<pdeg; i++){
rootCoeff[0] = roots[i].times(Complex.minusOne());
ComplexPoly cRoot = new ComplexPoly(rootCoeff);
rPoly = rPoly.times(cRoot);
}
return rPoly;
} | 2 |
public void updatePos() {
if(--time >= 0 && direction != -1) {
switch (direction) {
case 0: {
y--;
break;
}
case 1: {
x++;
break;
}
case 2: {
y++;
break;
}
case 3: {
x--;
break;
}
}
}
} | 6 |
public void populate(IChunkProvider var1, int var2, int var3) {
BlockSand.fallInstantly = true;
int var4 = var2 * 16;
int var5 = var3 * 16;
int var6;
int var7;
int var8;
int var9;
for(var6 = 0; var6 < 8; ++var6) {
var7 = var4 + this.hellRNG.nextInt(16) + 8;
var8 = this.hellRNG.nextInt(120) + 4;
var9 = var5 + this.hellRNG.nextInt(16) + 8;
(new WorldGenHellLava(Block.lavaMoving.blockID)).generate(this.worldObj, this.hellRNG, var7, var8, var9);
}
var6 = this.hellRNG.nextInt(this.hellRNG.nextInt(10) + 1) + 1;
int var10;
for(var7 = 0; var7 < var6; ++var7) {
var8 = var4 + this.hellRNG.nextInt(16) + 8;
var9 = this.hellRNG.nextInt(120) + 4;
var10 = var5 + this.hellRNG.nextInt(16) + 8;
(new WorldGenFire()).generate(this.worldObj, this.hellRNG, var8, var9, var10);
}
var6 = this.hellRNG.nextInt(this.hellRNG.nextInt(10) + 1);
for(var7 = 0; var7 < var6; ++var7) {
var8 = var4 + this.hellRNG.nextInt(16) + 8;
var9 = this.hellRNG.nextInt(120) + 4;
var10 = var5 + this.hellRNG.nextInt(16) + 8;
(new WorldGenGlowStone1()).generate(this.worldObj, this.hellRNG, var8, var9, var10);
}
for(var7 = 0; var7 < 10; ++var7) {
var8 = var4 + this.hellRNG.nextInt(16) + 8;
var9 = this.hellRNG.nextInt(128);
var10 = var5 + this.hellRNG.nextInt(16) + 8;
(new WorldGenGlowStone2()).generate(this.worldObj, this.hellRNG, var8, var9, var10);
}
if(this.hellRNG.nextInt(1) == 0) {
var7 = var4 + this.hellRNG.nextInt(16) + 8;
var8 = this.hellRNG.nextInt(128);
var9 = var5 + this.hellRNG.nextInt(16) + 8;
(new WorldGenFlowers(Block.mushroomBrown.blockID)).generate(this.worldObj, this.hellRNG, var7, var8, var9);
}
if(this.hellRNG.nextInt(1) == 0) {
var7 = var4 + this.hellRNG.nextInt(16) + 8;
var8 = this.hellRNG.nextInt(128);
var9 = var5 + this.hellRNG.nextInt(16) + 8;
(new WorldGenFlowers(Block.mushroomRed.blockID)).generate(this.worldObj, this.hellRNG, var7, var8, var9);
}
BlockSand.fallInstantly = false;
} | 6 |
public Template(String directory, String filename) {
this.tpl = new YamlConfiguration();
try {
file = new File(directory, filename);
this.tpl.load(file);
upgrade(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
} | 3 |
public void updateChampion (Champion c) {
if (champion != c) {
champion = c;
icon.setIcon (champion.getIcon());
name.setText (champion.getName());
style.setText (firstLetterUppercase (champion.getPlayStyle().toString()));
tacticBox.removeAll();
tacticBox.add (new JLabel (c.getPrimaryStrategy().getIcon (false)));
for (Strategy s : c.getSecondaryStrategies()) {
tacticBox.add (new JLabel (s.getIcon (true)));
}
roles.setText (parseList (c.getRoles()));
positions.setText (parseList (c.getPositions()));
counters.setText (parseList (c.getCounters()));
}
} | 2 |
@Override
public void enqueCommand(final List<String> commands, final int metaFlags, double actionCost)
{
if (commands == null)
return;
final CMObject O = CMLib.english().findCommand(this, commands);
if((O == null)
||((O instanceof Ability)
&&CMath.bset(metaFlags, MUDCmdProcessor.METAFLAG_ORDER)
&&CMath.bset(((Ability)O).flags(), Ability.FLAG_NOORDERING)))
{
CMLib.commands().handleUnknownCommand(this, commands);
return;
}
actionCost = calculateActionCost(O, commands, actionCost);
if (actionCost < 0.0)
return;
if (actionCost == 0.0)
doCommand(commands, metaFlags);
else
synchronized (commandQue)
{
final QMCommand cmd = new QMCommand();
cmd.nextCheck = System.currentTimeMillis() - 1;
cmd.seconds = -1;
cmd.actionCost = actionCost;
cmd.metaFlags = metaFlags;
cmd.commandObj = O;
cmd.commandVector = commands;
commandQue.addLast(cmd);
}
dequeCommand();
} | 7 |
private Animation createMirrorEnemyAnim(String str) {
Animation anim = new Animation();
for(int i=1;i<=26;i++){
anim.addFrame(getMirrorImage(loadImage(str+i+".png")), 80);
}
return anim;
} | 1 |
@Override
public boolean matches(List<Character> currentMatching) {
if(currentMatching.get(0) != KeyMappingProfile.ESC_CODE)
return false;
if(currentMatching.size() == 1)
return true;
if(currentMatching.get(1).charValue() > 26)
return false;
if(currentMatching.size() == 2)
return true;
return false;
} | 4 |
public Model load(Path path) throws IOException {
// read file line by line
BufferedReader read = null;
Model model = null;
try {
String currentLine;
FileReader reader = new FileReader(path.toFile());
read = new BufferedReader(reader);
while ((currentLine = read.readLine()) != null) {
if (currentLine.isEmpty())
continue;
parseLine(currentLine);
}
model = new Model(vertexIndices.size());
for (int i = 0; i < vertexIndices.size(); i++) {
model.setVertex(i, vertices.get(vertexIndices.get(i)));
}
for (int i = 0; i < normals.size(); i++)
model.setNormal(i, normals.get(normalIndices.get(i)));
for (int i = 0; i < textureCoords.size(); i++)
model.setTexCoord(i, textureCoords.get(textureIndices.get(i)));
if (normals.isEmpty())
model.generateNormals();
model.rewindBuffers();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (read != null)
read.close();
}
return model;
} | 8 |
public boolean equals(Object ob) {
if (super.equals(ob)) {
CandyForKid other = (CandyForKid) ob;
if (color != other.color)
return false;
}
return true;
} | 2 |
@Override
public int compareTo(AstronomicalObject o) {
return (this.mass < o.mass) ? -1 : (this.mass > o.mass) ? 1 : 0;
} | 2 |
private Handshake validateHandshake(Socket socket, byte[] peerId)
throws IOException, ParseException {
InputStream is = socket.getInputStream();
//< obfuscated handshake extension
// Read the handshake from the wire
byte[] data = new byte[Handshake.BASE_HANDSHAKE_LENGTH + 20];
is.read(data, 0, data.length);
int pstrlen = data[0] == 0x13 ? data[0] : 0x13;
byte[] pstr = Arrays.copyOfRange(data, 1, 20);
// Parse and check the handshake
Handshake hs = Handshake.parse(ByteBuffer.wrap(data));
logger.debug("Validating handshake from " + socket + ": " + Torrent.byteArrayToHexString(hs.getBytes()));
if (hs.isObfuscated()) {
//byte[] clientPeerId = this.id.getBytes();
byte[] clientPeerId = this.id;
byte[] infoHash = this.torrent.getInfoHash();
byte[] infoHashPeerId = Arrays.copyOf(infoHash, infoHash.length + clientPeerId.length);
System.arraycopy(clientPeerId, 0, infoHashPeerId, infoHash.length, clientPeerId.length);
try {
byte[] sighash = Torrent.hash(infoHashPeerId);
if (!Arrays.equals(sighash, hs.getSignature())) {
throw new ParseException("Invalid obfuscated handshake", pstrlen);
}
} catch (NoSuchAlgorithmException nsae) {
// fall through
}
// read padding message
byte[] paddingheader = new byte[5];
is.read(paddingheader);
int paddingLen = ByteBuffer.wrap(paddingheader).getInt();
byte[] paddingBytes = new byte[paddingLen];
is.read(paddingBytes);
} else if (!Handshake.BITTORRENT_PROTOCOL_IDENTIFIER.equals(new String(pstr, Torrent.BYTE_ENCODING))) {
throw new ParseException("Invalid handshake signature", pstrlen);
}
//> obfuscated handshake extension
if (!Arrays.equals(hs.getInfoHash(), this.torrent.getInfoHash())) {
throw new ParseException("Handshake for unknown torrent " +
Torrent.byteArrayToHexString(hs.getInfoHash()) +
" from " + this.socketRepr(socket) + ".", pstrlen + 9);
}
if (peerId != null && !Arrays.equals(hs.getPeerId(), peerId)) {
throw new ParseException("Announced peer ID " +
Torrent.byteArrayToHexString(hs.getPeerId()) +
" did not match expected peer ID " +
Torrent.byteArrayToHexString(peerId) + ".", pstrlen + 29);
}
return hs;
} | 8 |
static String spellHundredsNumber(int num){
if(primitiveNumbers.containsKey(num)) return primitiveNumbers.get(num);
String num_str = "";
if(num/100 != 0) num_str = primitiveNumbers.get(num / 100) + " Hundred ";
num = num % 100;
if(primitiveNumbers.containsKey(num)) num_str += primitiveNumbers.get(num);
else if(num < 20) num_str += primitiveNumbers.get(num - 10) + "teen";
else{
if(primitiveNumbers.containsKey(num / 10 * 10)) num_str += primitiveNumbers.get(num / 10 * 10) + " " + primitiveNumbers.get(num % 10);
else{
num_str += primitiveNumbers.get(num / 10) + "ty";
if(num % 10 != 0) num_str += " " + primitiveNumbers.get(num % 10);
}
}
return num_str;
} | 6 |
public void mouseEntered(MouseEvent event) {
} | 0 |
public void play(String audioFilePath) {
File audioFile = new File(audioFilePath);
try {
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip audioClip = (Clip) AudioSystem.getLine(info);
audioClip.addLineListener(this);
audioClip.open(audioStream);
audioClip.start();
while (!playCompleted) {
// wait for the playback completes
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
audioClip.close();
} catch (UnsupportedAudioFileException ex) {
System.out.println("The specified audio file is not supported.");
ex.printStackTrace();
} catch (LineUnavailableException ex) {
System.out.println("Audio line for playing back is unavailable.");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("Error playing the audio file.");
ex.printStackTrace();
}
} | 5 |
@Override
public void stateChanged(ChangeEvent ce) {
String classSelec = DocsPanel.CLASSES[this.panel.selector.getSelectedIndex()];
switch (classSelec) {
case DocsPanel.LIBROS: {
if (this.panel.lastRowSelecDocs[0] == -1) {
this.panel.disableDocButtons();
} else {
this.panel.enableDocButtons();
//if (this.panel.bl.size() > 0) {
// this.panel.cut.actualizarDatos(this.panel.bl);
//}
}
if (this.panel.lastRowSelecUser[0] == -1) {
this.panel.disableUserButtons();
} else {
this.panel.enableUserButtons();
this.panel.cut.selectRow(this.panel.lastRowSelecUser[0]);
}
break;
}
case DocsPanel.CD_DVD: {
if (this.panel.lastRowSelecDocs[1] == -1) {
this.panel.disableDocButtons();
} else {
this.panel.enableDocButtons();
//if (this.panel.cl.size() > 0) {
// this.panel.cut.actualizarDatos(this.panel.cl);
//}
}
if (this.panel.lastRowSelecUser[1] == -1) {
this.panel.disableUserButtons();
} else {
this.panel.enableUserButtons();
this.panel.cut.selectRow(this.panel.lastRowSelecUser[1]);
}
break;
}
default: {
if (this.panel.lastRowSelecDocs[2] == -1) {
this.panel.disableDocButtons();
} else {
this.panel.enableDocButtons();
//if (this.panel.ml.size() > 0) {
// this.panel.cut.actualizarDatos(this.panel.ml);
//}
}
if (this.panel.lastRowSelecUser[2] == -1) {
this.panel.disableUserButtons();
} else {
this.panel.enableUserButtons();
this.panel.cut.selectRow(this.panel.lastRowSelecUser[2]);
}
break;
}
}
} | 8 |
public String getMatricule() {
return matricule;
} | 0 |
public boolean containsKey(Object k) {
PositionalVector pos;
if (k instanceof CoordinateEntry)
pos = ((CoordinateEntry) k).asPosition();
else if (k instanceof PositionalVector)
pos = (PositionalVector) k;
else return false;
for (int i = 0; i < data.length; ++i) {
CoordinateEntry entry = data[i];
if (entry.has(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ())) {
this.lastFetched = i;
return true;
}
}
return false;
} | 4 |
public AmericanFlag(int x, int y, double scale){
this.scale = scale;
this.union = new Rectangle(x,(y+(int)(this.scale*10)),(int)(this.scale*99),(int)(this.scale*70), Color.blue);
this.stripes = new Rectangle[13];
this.wstars = new Star[9][6];
// this.wstars = new Stars[9][6];
for (int i = 0; i < 13 ; i++ ) {
if (i % 2 == 0) {
stripes[i] = new Rectangle(x, (int)((i + 1) * this.scale*10 + y), (int)(this.scale * 247),(int)(this.scale * 10), Color.red);
}else{
stripes[i] = new Rectangle(x, (int)((i + 1) * this.scale*10 + y), (int)(this.scale * 247),(int)(this.scale * 10), Color.white);
}
}
for (int i = 0; i < 9; i++){
for (int j = 0; j < 6; j++){
if (i%2 ==0){
// wstars[i][j] = new Stars((int)(2*8.19*this.scale*(j+1)+(x-8.94*this.scale)), (int)((i+1)*this.scale*6.50 + y+this.scale*10), (int)(this.scale * 4),(int)(this.scale * 4), Color.white);
wstars[i][j] = new Star(5,(int)(2*8.19*this.scale*(j+1)+(x-8.0*this.scale)), (int)((i+1)*this.scale*6.5 + y+this.scale*13), (int)(this.scale * 4),(int)(this.scale * 4), Color.white);
}else{
wstars[i][j] = new Star(5,(int)(2*8.19*this.scale*(j+1)+x), (int)((i+1)*this.scale*6.5 + y+this.scale*13), (int)(this.scale * 4),(int)(this.scale * 4), Color.white);
}
}
}
} | 5 |
void run(){
int S = 125000;
int[] a = new int[S];
int s = 0;
for(int i=0;i<S;i++){
a[i] = s;
int L = 1000*i, R = L+999;
if((L+"").length()==(R+"").length())s+=1000*(L+"").length();
else{
for(int k=L;k<=R;k++)s+=(k+"").length();
}
}
Scanner sc = new Scanner(System.in);
for(;;){
int N = sc.nextInt(), K = sc.nextInt();
if((N|K)==0)break;
int id = 0;
for(int i=0;i+1<S;i++){
if(a[i]<=N&&N<a[i+1]){
id = i; break;
}
}
N-=a[id];
StringBuilder sb = new StringBuilder();
for(int k=1000*id;sb.length()<=N+K;k++)sb.append(k);
System.out.println(sb.substring(N, N+K));
}
} | 9 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ProdutosConsumidos other = (ProdutosConsumidos) obj;
if (this.IdProdutosConsumidos != other.IdProdutosConsumidos && (this.IdProdutosConsumidos == null || !this.IdProdutosConsumidos.equals(other.IdProdutosConsumidos))) {
return false;
}
return true;
} | 5 |
public PrivatePackDialog() {
super(LaunchFrame.getInstance(), true);
setupGui();
getRootPane().setDefaultButton(add);
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(DownloadUtils.staticFileExists(modpackName.getText() + ".xml") && !modpackName.getText().isEmpty() && !Settings.getSettings().getPrivatePacks().contains(modpackName.getText())) {
Logger.logInfo("Adding: " + modpackName.getText());
ModPack.loadXml(modpackName.getText() + ".xml");
Settings.getSettings().addPrivatePack(modpackName.getText());
Settings.getSettings().save();
setVisible(false);
} else {
ErrorUtils.tossError(I18N.getLocaleString("PRIVATEPACK_ERROR"));
}
}
});
cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
remove.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
ArrayList<String> codes = Settings.getSettings().getPrivatePacks();
if(codes.contains(modpackName.getText())) {
Settings.getSettings().removePrivatePack(modpackName.getText());
Settings.getSettings().save();
try {
for(ModPack pack : ModPack.getPackArray()) {
if(pack.getParentXml().equalsIgnoreCase(modpackName.getText() + ".xml")) {
FileUtils.delete(new File(OSUtils.getDynamicStorageLocation(), "ModPacks/" + pack.getDir()));
break;
}
}
ModPack.removePacks(modpackName.getText() + ".xml");
FileUtils.delete(new File(OSUtils.getDynamicStorageLocation(), "ModPacks/" + modpackName.getText() + ".xml"));
LaunchFrame.getInstance().modPacksPane.sortPacks();
} catch (IOException e) {
e.printStackTrace();
}
Logger.logInfo(modpackName.getText() + " " + I18N.getLocaleString("PRIVATEPACK_SECCESS"));
modpackName.setText("");
setVisible(false);
} else {
Logger.logInfo(I18N.getLocaleString("PRIVATEPACK_NOTEXISTS"));
}
}
});
} | 7 |
static protected void FillBuff() throws java.io.IOException
{
int i;
if (maxNextCharInd == 4096)
maxNextCharInd = nextCharInd = 0;
try {
if ((i = inputStream.read(nextCharBuf, maxNextCharInd,
4096 - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
if (bufpos != 0)
{
--bufpos;
backup(0);
}
else
{
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
throw e;
}
} | 4 |
private Value[] fillParameters(BytecodeInfo code, Object cls,
Object[] params) {
Value[] locals = new Value[code.getMaxLocals()];
for (int i = 0; i < locals.length; i++)
locals[i] = new Value();
String myType = code.getMethodInfo().getType();
String[] myParamTypes = TypeSignature.getParameterTypes(myType);
int slot = 0;
if (!code.getMethodInfo().isStatic())
locals[slot++].setObject(cls);
for (int i = 0; i < myParamTypes.length; i++) {
locals[slot].setObject(params[i]);
slot += TypeSignature.getTypeSize(myParamTypes[i]);
}
return locals;
} | 3 |
protected static void readUIFile(UIFileTextVO uiFile, Path uifilepath) {
assert (uiFile != null) && FileUtil.control(uifilepath);
uiFile.setLineList(FileUtil.readTextFile(uifilepath));
} | 1 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.