text stringlengths 14 410k | label int32 0 9 |
|---|---|
public int getPageNumber(Reference r) {
Page pg = (Page) library.getObject(r);
if (pg == null)
return -1;
// pg.init();
int globalIndex = 0;
Reference currChildRef = r;
Reference currParentRef = pg.getParentReference();
PageTree currParent = pg.getParent();
while (currParentRef != null && currParent != null) {
currParent.init();
int refIndex = currParent.indexOfKidReference(currChildRef);
if (refIndex < 0)
return -1;
int localIndex = 0;
for (int i = 0; i < refIndex; i++) {
Object pageOrPages = currParent.getPageOrPagesPotentiallyNotInitedFromReferenceAt(i);
if (pageOrPages instanceof Page) {
localIndex++;
} else if (pageOrPages instanceof PageTree) {
PageTree peerPageTree = (PageTree) pageOrPages;
peerPageTree.init();
localIndex += peerPageTree.getNumberOfPages();
}
}
globalIndex += localIndex;
currChildRef = currParentRef;
currParentRef = (Reference) currParent.entries.get("Parent");
currParent = currParent.parent;
}
return globalIndex;
} | 7 |
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_DeltaCols.setUpper(getInputFormat().numAttributes() - 1);
int selectedCount = 0;
for (int i = getInputFormat().numAttributes() - 1; i >= 0; i--) {
if (m_DeltaCols.isInRange(i)) {
selectedCount++;
if (!getInputFormat().attribute(i).isNumeric()) {
throw new UnsupportedAttributeTypeException("Selected attributes must be all numeric");
}
}
}
if (selectedCount == 1) {
throw new Exception("Cannot select only one attribute.");
}
// Create the output buffer
FastVector newAtts = new FastVector();
boolean inRange = false;
String foName = null;
int clsIndex = -1;
for(int i = 0; i < instanceInfo.numAttributes(); i++) {
if (m_DeltaCols.isInRange(i) && (i != instanceInfo.classIndex())) {
if (inRange) {
Attribute newAttrib = new Attribute(foName);
newAtts.addElement(newAttrib);
}
foName = instanceInfo.attribute(i).name();
foName = "'FO " + foName.replace('\'', ' ').trim() + '\'';
inRange = true;
} else {
newAtts.addElement((Attribute)instanceInfo.attribute(i).copy());
if ((i == instanceInfo.classIndex()))
clsIndex = newAtts.size() - 1;
}
}
Instances data = new Instances(instanceInfo.relationName(), newAtts, 0);
data.setClassIndex(clsIndex);
setOutputFormat(data);
return true;
} | 9 |
private MoveType getTradeMoveType(Settlement settlement) {
if (settlement instanceof Colony) {
return (getOwner().atWarWith(settlement.getOwner()))
? MoveType.MOVE_NO_ACCESS_WAR
: (!hasAbility("model.ability.tradeWithForeignColonies"))
? MoveType.MOVE_NO_ACCESS_TRADE
: MoveType.ENTER_SETTLEMENT_WITH_CARRIER_AND_GOODS;
} else if (settlement instanceof IndianSettlement) {
// Do not block for war, bringing gifts is allowed
return (!allowContact(settlement))
? MoveType.MOVE_NO_ACCESS_CONTACT
: (hasGoodsCargo())
? MoveType.ENTER_SETTLEMENT_WITH_CARRIER_AND_GOODS
: MoveType.MOVE_NO_ACCESS_GOODS;
} else {
return MoveType.MOVE_ILLEGAL; // should not happen
}
} | 6 |
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof HighLowRenderer)) {
return false;
}
HighLowRenderer that = (HighLowRenderer) obj;
if (this.drawOpenTicks != that.drawOpenTicks) {
return false;
}
if (this.drawCloseTicks != that.drawCloseTicks) {
return false;
}
if (!PaintUtilities.equal(this.openTickPaint, that.openTickPaint)) {
return false;
}
if (!PaintUtilities.equal(this.closeTickPaint, that.closeTickPaint)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
return true;
} | 7 |
public MyCustomEventPublisher(MyCustomEventListener listener) {
this.listener = listener;
} | 0 |
@Override
public void executar() throws Exception
{
boolean goBack = false;
while ( !goBack )
{
mostrarOpcions();
int choice = readint("\nOPCIO: ");
switch (choice)
{
case 1:
visitantService.consultarJornada();
break;
case 2:
visitantService.consultarClassificacio();
break;
case 3:
vendreEntrada();
break;
case 4:
goBack = true;
break;
case 5:
System.exit(0);
default:
System.out.println("\nValor incorrecte. Si us plau, torna a seleccionar la opció desitjada.\n");
}
}
} | 6 |
public void mutePlayer(Client c, String name) {
if (!isOwner(c)) {
c.sendMessage("You do not have the power to do that!");
return;
}
if (clans[c.clanId] != null) {
for (int j = 0; j < clans[c.clanId].mutedMembers.length; j++) {
for(int i = 0; j < Config.MAX_PLAYERS; i++) {
if (Server.playerHandler.players[i].playerName.equalsIgnoreCase(name)) {
Client c2 = (Client)Server.playerHandler.players[i];
if (!isInClan(c2)) {
c.sendMessage(c2.playerName+" is not in your clan!");
return;
}
if (clans[c.clanId].mutedMembers[j] <= 0) {
clans[c.clanId].mutedMembers[j] = i;
c2.sendMessage("You have been muted in: " + clans[c.clanId].name);
}
} else {
c.sendMessage("This person is not online!");
}
}
}
}
} | 7 |
protected Neuron(Element neuronE, NeuralLayer layer) {
m_layer = layer;
m_ID = neuronE.getAttribute("id");
String bias = neuronE.getAttribute("bias");
if (bias != null && bias.length() > 0) {
m_bias = Double.parseDouble(bias);
}
String width = neuronE.getAttribute("width");
if (width != null && width.length() > 0) {
m_neuronWidth = Double.parseDouble(width);
}
String altitude = neuronE.getAttribute("altitude");
if (altitude != null && altitude.length() > 0) {
m_neuronAltitude = Double.parseDouble(altitude);
}
// get the connection details
NodeList conL = neuronE.getElementsByTagName("Con");
m_connectionIDs = new String[conL.getLength()];
m_weights = new double[conL.getLength()];
for (int i = 0; i < conL.getLength(); i++) {
Node conN = conL.item(i);
if (conN.getNodeType() == Node.ELEMENT_NODE) {
Element conE = (Element)conN;
m_connectionIDs[i] = conE.getAttribute("from");
String weight = conE.getAttribute("weight");
m_weights[i] = Double.parseDouble(weight);
}
}
} | 8 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Temperature other = (Temperature) obj;
if (this.unit != other.unit) {
return false;
}
return this.value == other.value;
} | 3 |
public DataModel getDataModel() {
return dataModel;
} | 0 |
public boolean collidesWith(Placeable other)
{
boolean collidesX = (other.x < this.x && other.x + other.width >= this.x) || (other.x > this.x && this.x + this.width >= other.x) || other.x == this.x;
boolean collidesY = (other.y < this.y && other.y + other.width >= this.y) || (other.y > this.y && this.y + this.width >= other.y) || other.y == this.y;
return collidesX && collidesY;
} | 9 |
public void vizExportConceptTree(LogicObject concept, Module module) {
{ VizInfo self = this;
self.nodeColor = "palegreen";
self.vizExportConcept(concept, module);
self.nodeColor = "yellow";
self.vizAllowObject(concept);
{ LogicObject renamed_Super = null;
edu.isi.powerloom.PlIterator iter000 = edu.isi.powerloom.PLI.getProperSuperrelations(concept, module, null);
while (iter000.nextP()) {
renamed_Super = ((LogicObject)(iter000.value));
self.vizAllowObject(renamed_Super);
}
}
{ LogicObject sub = null;
edu.isi.powerloom.PlIterator iter001 = edu.isi.powerloom.PLI.getProperSubrelations(concept, module, null);
while (iter001.nextP()) {
sub = ((LogicObject)(iter001.value));
self.vizAllowObject(sub);
}
}
{ LogicObject renamed_Super = null;
edu.isi.powerloom.PlIterator iter002 = edu.isi.powerloom.PLI.getProperSuperrelations(concept, module, null);
while (iter002.nextP()) {
renamed_Super = ((LogicObject)(iter002.value));
if (Surrogate.subtypeOfP(Stella_Object.safePrimaryType(renamed_Super), OntosaurusUtil.SGT_LOGIC_LOGIC_OBJECT)) {
{ LogicObject super000 = ((LogicObject)(renamed_Super));
self.vizExportConcept(super000, module);
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("viz-export-concept-tree: concept not handled: `" + renamed_Super + "'");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
}
}
{ LogicObject sub = null;
edu.isi.powerloom.PlIterator iter003 = edu.isi.powerloom.PLI.getProperSubrelations(concept, module, null);
while (iter003.nextP()) {
sub = ((LogicObject)(iter003.value));
if (Surrogate.subtypeOfP(Stella_Object.safePrimaryType(sub), OntosaurusUtil.SGT_LOGIC_LOGIC_OBJECT)) {
{ LogicObject sub000 = ((LogicObject)(sub));
self.vizExportConcept(sub000, module);
}
}
else {
{ OutputStringStream stream001 = OutputStringStream.newOutputStringStream();
stream001.nativeStream.print("viz-export-concept-tree: concept not handled: `" + sub + "'");
throw ((StellaException)(StellaException.newStellaException(stream001.theStringReader()).fillInStackTrace()));
}
}
}
}
}
} | 6 |
public SimpleExample() {
setTitle("Simple example");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
String s = (String)JOptionPane.showInputDialog(
this,
"Ge mig ett binärt tal, tack! MAX 4 STYCKEN!",
JOptionPane.PLAIN_MESSAGE
);
List<Integer> varden = new ArrayList<Integer>();
for(int i = 0; i < 4; i++)
{
int binar = (int) s.charAt(i);
System.out.println(s.charAt(i));
switch(binar)
{
case 1:
int tal = 2^i;
if(i == 1)
tal = 1;
varden.set(i, tal);
}
System.out.println(varden);
}
} | 3 |
public void addTask(){
int counter=taskCounter.get().intValue();
counter++;
taskCounter.set(counter);
} | 0 |
public static void main(String[] args)
{
/* theme
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(UnsupportedLookAndFeelException e)
{
}
catch(ClassNotFoundException e)
{
}
catch(InstantiationException e)
{
}
catch(IllegalAccessException e)
{
}
*/
// set window size
Dimension dim = new Dimension(512, 384);
final JoeClient joe = new JoeClient();
JFrame frame = new JFrame("JoeClient");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setPreferredSize(dim);
frame.setMinimumSize(dim);
frame.add(joe.panel);
MainMenu menu = new MainMenu(joe);
frame.setJMenuBar(menu);
frame.setSize(dim.width, dim.height);
frame.setVisible(true);
//win = SwingUtilities.windowForComponent(frame);
joe.win = (Frame)frame;
new Thread()
{
int bump = 0;
public void run()
{
while(true)
{
// try to stay connected
try
{
Thread.sleep(500);
bump++;
if(bump > 120)
{
bump = 0;
if(joe.chat.connected && joe.cd.keep_alive.isSelected())
{
try
{
joe.chat.out.write("\n");
joe.chat.out.flush();
}
catch(IOException e)
{
}
}
}
}
catch(InterruptedException e)
{
}
}
}
}.start();
} | 6 |
public String sample_frequency_string()
{
switch (h_sample_frequency)
{
case THIRTYTWO:
if (h_version == MPEG1)
return "32 kHz";
else if (h_version == MPEG2_LSF)
return "16 kHz";
else // SZD
return "8 kHz";
case FOURTYFOUR_POINT_ONE:
if (h_version == MPEG1)
return "44.1 kHz";
else if (h_version == MPEG2_LSF)
return "22.05 kHz";
else // SZD
return "11.025 kHz";
case FOURTYEIGHT:
if (h_version == MPEG1)
return "48 kHz";
else if (h_version == MPEG2_LSF)
return "24 kHz";
else // SZD
return "12 kHz";
}
return(null);
} | 9 |
public static int m_fht(final int n) {
return (int) Math.pow(2,Math.ceil(log(12.8*n,2)));
} | 0 |
double VectorMin(double[] v) {
double sum = 0;
for (int i = 0; i < v.length; i++) {
sum = Math.min(v[i], sum);//*v[i];
}
return sum;//Math.sqrt(sum);
} | 1 |
public static Pair<Boolean, Pair<Integer,Integer>> check(Map<Integer, Pair<Double,String>> first, Map<Integer, Pair<Double,String>> second){
int firstVal = -1;
int secondVal = -1;
int counter = 0;
for(Map.Entry<Integer, Pair<Double,String>> f : first.entrySet()){
if(counter == 0){
firstVal = f.getKey();
}
if(counter == 1){
secondVal = f.getKey();
}
counter++;
}
for(Map.Entry<Integer, Pair<Double,String>> s : second.entrySet()){
if(s.getKey() == firstVal){
return Pair.make(true, Pair.make(s.getKey(), secondVal));
}
else if(s.getKey() == secondVal){
return Pair.make(true, Pair.make(s.getKey(), firstVal));
}
}
return Pair.make(false, Pair.make(-1,-1));
} | 6 |
public void run() {
List<SQLStatement> sqlStatementsToLoad = new ArrayList<>();
int numberStatements;
//noinspection InfiniteLoopStatement
while (true) {
if (unloadedSQLStatements.size() > 0) {
sqlStatementsToLoad.clear();
numberStatements = 0;
Iterator<SQLStatement> iterator = unloadedSQLStatements.iterator();
// load at most 400 statements before going to sleep
// 400 is a magic number - no special meaning. But keep it somehow related to the
// SQLTextLoadHelper and its chunk size.
while (iterator.hasNext() && numberStatements <= 400) {
sqlStatementsToLoad.add(iterator.next());
numberStatements++;
}
SQLTextLoadHelper.loadSQLStatements(sqlStatementsToLoad);
// remove the loaded statements from the list
for (SQLStatement statement : sqlStatementsToLoad) {
unloadedSQLStatements.remove(statement);
}
}
// sleep for 0.2 seconds so all the other tasks can do their work
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// we don't care for being interrupted
}
}
} | 6 |
private void addExtras(JToolBar toolbar) {
toolbar.addSeparator();
toolbar.add(new TooltipAction("Complete",
"This will finish all expansion.") {
public void actionPerformed(ActionEvent e) {
controller.complete();
}
});
toolbar.add(new TooltipAction("Done?", "Are we finished?") {
public void actionPerformed(ActionEvent e) {
controller.done();
}
});
} | 0 |
public boolean isSorted()
{
boolean sorted = true;
// TODO: Determine if the array is sorted.
if (list.size() == 0)
{
return sorted;
}
else
{
String previous = list.get(0);
for (String each : list)
{
if (previous.compareTo(each) > 0)
{
sorted = false;
break;
}
previous = each;
}
}
return sorted;
} | 3 |
public void update(long nowTime) {
if (m_inScroll) {
long delta = nowTime - m_startTime;
if (delta < m_maxTime) {
double t = ((double)delta)/m_maxTime;
m_target.x = (int)(m_scrollTo.x * t + m_scrollFrom.x * (1.0 - t));
m_target.y = (int)(m_scrollTo.y * t + m_scrollFrom.y * (1.0 - t));
}
else { // times up, go!
m_target.x = m_scrollTo.x;
m_target.y = m_scrollTo.y;
m_inScroll = false;
}
}
} | 2 |
public boolean atTerminator() {
if (!hasNext()) {
return true;
}
final char ch = peek();
return isSpace(ch) || isEndOfLine(ch) || ch == '.' || ch == ',' || ch == '|' || ch == ':' || ch == '(' || ch == ')' || rightDelimiter.charAt(0) == ch;
} | 9 |
@Override
public void cleanup()
{
if( ALSource != null )
{
try
{
// Stop playing the source:
AL10.alSourceStop( ALSource );
AL10.alGetError();
}
catch( Exception e )
{}
try
{
// Delete the source:
AL10.alDeleteSources( ALSource );
AL10.alGetError();
}
catch( Exception e )
{}
ALSource.clear();
}
ALSource = null;
super.cleanup();
} | 3 |
public static int personneX(int travee,int orientation){
int centreX = centrePositionX(travee) ;
switch(orientation){
case Orientation.NORD :
centreX -= 10 ;
break ;
case Orientation.EST :
centreX -= 25 ;
break ;
case Orientation.SUD :
centreX -= 10 ;
break ;
case Orientation.OUEST :
centreX += 5 ;
break ;
}
return centreX ;
} | 4 |
@Override
public int joinRoom(String roomName, short roomKind) throws RemoteException {
// TODO Auto-generated method stub
String check="";
int roomID=-1;
int i;
for(i=0;i<rooms.size();i++)
{
check=(String) rooms.get(i).get(0);
if(check.equals(roomName)==true)
{
roomID=i;
i=rooms.size();
}
}
if(roomID==-1)
{
if(roomKind==0)
{
for(i=0;i<rooms.size();i++)
{
String[] pseudos=roomName.split("privatechatwith");
check=(String) rooms.get(i).get(0);
if(check.startsWith(pseudos[1])==true && check.endsWith(pseudos[0])==true)
{
roomID=i;
i=rooms.size();
}
}
}
if(roomID==-1)
{
rooms.add(new ArrayList<String>());
rooms.get(i).add(roomName);
roomID=i;
if(roomKind==1)
{
publicRoomsName.add(roomName);
}
System.out.println("New room created : "+roomName+" with ID : "+roomID);
}
}
return roomID;
} | 9 |
public void drawText(Graphics2D g) {
// We don't want to corrupt the graphics environs with our
// affine transforms!
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.transform(affineToText);
// What about the text label?
FontMetrics metrics = g2.getFontMetrics();
bounds = metrics.getStringBounds(getLabel(), g2);
// Will the label appear to be upside down?
boolean upsideDown = end.x < start.x;
float dx = (float) bounds.getWidth() / 2.0f;
float dy = (curvy < 0.0f) ^ upsideDown ? metrics.getAscent() : -metrics
.getDescent();
bounds.setRect(bounds.getX() - dx, bounds.getY() + dy, bounds
.getWidth(), bounds.getHeight());
for (int i = 0; i < label.length(); i += CHARS_PER_STEP) {
String sublabel = label.substring(i, Math.min(i + CHARS_PER_STEP,
label.length()));
g2.drawString(sublabel, -dx, dy);
dx -= metrics.getStringBounds(sublabel, g2).getWidth();
}
// g2.drawString(label, -dx, dy);
g2.dispose();
/*
* if (GRAPHICS == null) { GRAPHICS = g.create(); METRICS =
* GRAPHICS.getFontMetrics(); }
*/
} | 2 |
@Override
public void execute(GameActor character, CharacterAction action) {
switch (action) {
case JUMPRIGHT:
if (character.isOnGround()) character.updateVelocity(7, -80);
else character.updateVelocity(7, 0);
character.setOnGround(false);
return;
case JUMPLEFT:
if (character.isOnGround()) character.updateVelocity(-7, -80);
else character.updateVelocity(-7, 0);
character.setOnGround(false);
return;
case JUMP:
if (character.isOnGround()) character.updateVelocity(0, -80);
character.setOnGround(false);
return;
case MOVERIGHT:
character.updateVelocity(2, 0);
break;
case MOVELEFT:
character.updateVelocity(-2, 0);
break;
}
if (character.isOnGround()) character.setCurrentAction(action);
} | 9 |
private boolean measurementIsValid(Measurement measurement, OpenCellIdCell cell, double r) {
double distanceToCellTower = Geom.sphericalDistance(
cell.getCellTowerCoordinates().getX(),
cell.getCellTowerCoordinates().getY(),
measurement.getCoordinates().getX(),
measurement.getCoordinates().getY());
if(distanceToCellTower > r) {
return false;
}
int signalStrength = measurement.getSignalStrength();
if(signalStrength >= 32)
return false;
else if(signalStrength >= 0 && signalStrength <= 31) {
int signalStrengthDBM = (2*signalStrength)-113;
measurement.setSignalStrength(signalStrengthDBM);
}
return true;
} | 4 |
public Integer getIdHospital() {
return idHospital;
} | 0 |
public void buyed()
{
for (int i=0; i<recruits.length; ++i) {
recruits[i].updateRange();
}
for (int i=0; i<buys.length; ++i) {
buys[i].checkActive();
}
updateResources();
} | 2 |
private void processAfterLogin(int choice){
switch (choice){
case 1: logout();
break;
case 2: bookRepository.showAllBooks();
break;
case 3: movieStore.showAllMovies();
break;
case 4: getLibraryNumber();
break;
case 5: bookRepository.reserveBook(userInput.askBookName());
break;
case 6: bookRepository.returnBook(userInput.askBookName());
break;
case 7: System.exit(0);
}
} | 7 |
void doNewGame() {
if (gameInProgress) {
// If the current game is not over, it is an error to try
// to start a new game.
message = "You still have to finish this game!";
repaint();
return;
}
deck = new Deck(); // Create the deck and hands to use for this game.
dealerHand = new BlackjackHand();
playerHand = new BlackjackHand();
deck.shuffle();
dealerHand.addCard( deck.dealCard() ); // Deal two cards to each player.
dealerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
if (dealerHand.getBlackjackValue() == 21) {
message = "Sorry, you lose. Dealer has Blackjack.";
gameInProgress = false;
}
else if (playerHand.getBlackjackValue() == 21) {
message = "You win! You have Blackjack.";
gameInProgress = false;
}
else {
message = "You have " + playerHand.getBlackjackValue() + ". Hit or stand?";
gameInProgress = true;
}
repaint();
} // end newGame(); | 3 |
public static <T extends Satellite> Satellite create(int id, Class<T> type, Planet primary) {
PropertyManager pm = new PropertyManager("config.properties");
Random rnd = new Random();
double satelliteMass = pm.getDoubleProperty("min.Satellite.Mass") + (pm.getDoubleProperty("max.Satellite.Mass") - pm.getDoubleProperty("min.Satellite.Mass")) * rnd.nextDouble();
if (type.getName().contains("NaturalSatellite")) {
return new Satellite.Builder()
.id(id)
.name(NameGenerator.generate())
.mass(satelliteMass)
.population(rnd.nextInt(pm.getIntProperty("max.Satellite.Population")))
.mineralResources(Arrays.asList(MineralResource.values()[rnd.nextInt(MineralResource.values().length)]))
.buildNaturalSatellite(primary);
}
if (type.getName().contains("ArtificialSatellite")) {
return new Satellite.Builder()
.id(id)
.name(NameGenerator.generate())
.mass(satelliteMass)
.inhabited(rnd.nextBoolean())
.electricCharge(rnd.nextInt(2000))
.energySource(EnergySource.values()[rnd.nextInt(EnergySource.values().length)])
.mineralResources(Arrays.asList(MineralResource.values()[rnd.nextInt(MineralResource.values().length)]))
.buildArtificialSatellite(primary);
}
return new ArtificialSatellite();
} | 2 |
private void dijkstraButtonClick(java.awt.event.ActionEvent evt) {
//GraphPoint[] gps = graph.getSelectedPoints();
// GraphElement[] ges;// = GraphElement[0];
// if (gps.length == 2) {
// ges = graph.getDijkstraPath(gps[0], gps[1]);
// } else {
// return;
// }
GraphElement[] ges = graph.getDijkstraPath();
if (ges == null) {
distanseField.setText("Infinit");
return;
}
int dist = 0;
for (int i = 0; i < ges.length; i++) {
ges[i].getComponent().setColor(TREEANDMINIMUMCOLOR);
if (GraphLine.class.isInstance(ges[i])) {
dist += ((GraphLine)ges[i]).getWeight();
}
}
distanseField.setText(dist + "");
} | 3 |
public Long128 add(Long128 number) {
long lowerSum = myLowerDigits + number.myLowerDigits;
boolean carry = false;
// overflow
if ((lowerSum > 0 && myLowerDigits < 0 && number.myLowerDigits < 0) ||
(lowerSum < 0 && myLowerDigits > 0 && number.myLowerDigits > 0)) {
lowerSum = lowerSum & Long.MAX_VALUE;
carry = true;
}
if (lowerSum > MAX_LOWER)
carry = true;
long upperSum = myUpperDigits + number.myUpperDigits;
if (carry)
upperSum++;
return new Long128(lowerSum, upperSum);
} | 8 |
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(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainGUI.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 MainGUI().setVisible(true);
}
});
} | 6 |
public boolean isGlobalAdmin()
{
if (isOwner() == true)
return true;
else if (permission.has(player, "FC_Suite.admin"))
return true;
else if (player.isOp() == true)
return true;
return false;
} | 3 |
public String getName(int ID)
{
try {
int employeeID = ID;
if(employeeID > 0) {
if(employeeID < ReadFromFile.getNumberFromFile("employee.txt")) {
Employee [] checkEmployees = ReadFromFile.findAllEmployeeData();
return checkEmployees[employeeID-1].getFirstName() + " " + checkEmployees[employeeID-1].getLastName();
}
}
}
catch(NumberFormatException n) {}
return "";
} | 3 |
private ArrayList<Long> generateIdsForCondition(String indexName, String value)
{
ArrayList<Long> results = new ArrayList<>();
NodeReference node = DataWorker.GetNodeReference(indexGlobal);
String key = "";
while (true)
{
key = node.nextSubscript(indexName, value, key);
if (key.equals(""))
break;
Long parsedKey = Long.parseLong(key);
if (ids != null && !ids.contains(parsedKey))
continue;
results.add(parsedKey);
}
return results;
} | 4 |
@Override
protected void paintTabBackground( Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected ){
Graphics2D g2D = (Graphics2D)g;
//colores degradados para los tabs
GradientPaint gradientSel = new GradientPaint( 0, 0, new Color(242,249,242), 0, y+h/2, new Color(217,237,246) );
GradientPaint gradientUnsel = new GradientPaint( 0, 0, new Color(232,232,232), 0, y+h/2, new Color(205,205,205) );
switch( tabPlacement ){
case LEFT:
case RIGHT:
case BOTTOM:
/* codigo para estos tabs */
break;
case TOP:
default:
xp = new int[]{ x,
x,
x+4,
x+w+5,
x+w+5,
x+w,
x+w,
x
};
yp = new int[]{ y+h,
y+4,
y,
y,
y+5,
y+10,
y+h,
y+h
};
break;
}
shape = new Polygon( xp, yp, xp.length );
if ( isSelected ){
g2D.setPaint( gradientSel );}
else{
g2D.setPaint( gradientUnsel );
}
g2D.fill( shape );
} | 5 |
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost, msg))
return false;
if((myHost instanceof MOB)&&(myHost == this.affected)&&(((MOB)myHost).location()!=null))
{
if((msg.sourceMinor()==CMMsg.TYP_SHUTDOWN)
||((msg.sourceMinor()==CMMsg.TYP_QUIT)&&(msg.amISource((MOB)myHost))))
{
aborted=true;
unInvoke();
}
}
return true;
} | 7 |
public static void printList(List<?> lst) {
System.out.println("Index\t Value");
for (int i = 0; i < lst.size(); i++) {
System.out.println(i + "\t " + lst.get(i));
}
} | 2 |
public Response handleObject(Request request) {
String interfaceClassName = metadata.getImplClass();
try {
Class<?> interfaceClazz = Class.forName(interfaceClassName);
return new Response(interfaceClazz.newInstance(),interfaceClazz);
} catch (ClassNotFoundException e) {
log.error("class not found on server");
return null;
} catch (InstantiationException e) {
log.error("InstantiationException");
return null;
} catch (IllegalAccessException e) {
log.error("IllegalAccessException");
return null;
}
} | 4 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VarDeclarationNode other = (VarDeclarationNode) obj;
if (identList == null) {
if (other.identList != null)
return false;
} else if (!identList.equals(other.identList))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
} | 9 |
public FloorItem FindItemByID(int ID)
{
FloorItem Return = null;
for(FloorItem Item : FloorItems.values())
{
if(Item.ID == ID)
{
Return = Item;
}
}
return Return;
} | 2 |
public void handlePacket(Packet packet) {
if (!handlers.containsKey(packet.getID())) {
throw new IllegalArgumentException("No handler for packet " + packet.getID());
}
if(!listeners.get(packet.getClass()).isEmpty()){
Iterator<PacketListener> it = listeners.get(packet.getClass()).iterator();
while(it.hasNext()) //Iterator -> no ConcurrentModificationException
it.next().handlePacket(packet);
}
try {
handlers.get(packet.getID()).invoke(this, packet);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Could not invoke handler for packet " + packet.getID(), e);
}
} | 4 |
public int evaluateGameBoard() {
int score = 0;
// scores for the positions
int mt_score = 0;
int ps_score = 0;
int mb_score = 0;
for (int i = 0; i < all_pieces.size(); i++) {
BoardPiece piece = all_pieces.get(i);
mt_score += m_table.get(piece.piece_type);
if (all_pieces.size() + oponents.size() > end_count_pieces) {
if (position_matrix.get(piece.piece_type) != null) {
ps_score += position_matrix.get(piece.piece_type)[piece.xCoord][piece.yCoord];
}
}
ArrayList<SquarePosition> squares = controller.get_attacking_pos(piece);
for (int k = 0; k < squares.size(); k++) {
mb_score++;
if (squares.get(k).yCoord > side + (3 * pawn_direction)) {
mb_score++;
}
}
}
// subtract scores from the oponent
for (int i = 0; i < oponents.size(); i++) {
BoardPiece piece = oponents.get(i);
mt_score -= m_table.get(piece.piece_type);
}
mt_score *= m_weight;
ps_score *= position_weight;
mb_score *= mb_weight;
score += mt_score;
score += ps_score;
score += mb_score;
// pawn structure
int pawn_structure = evaluatePawn();
pawn_structure *= st_weight;
score += pawn_structure;
// System.out.println(evalScore);
return score;
} | 6 |
public static List<Participant> getParticipants(int gameid) throws SQLException {
String sql = null;
Connection connection = null;
PreparedStatement query = null;
ResultSet results = null;
try {
sql = "SELECT gameid, participant.playerid, playername, points, notes from participant, player where gameid = ? and participant.playerid = player.playerid order by points, playername";
connection = Database.getConnection();
query = connection.prepareStatement(sql);
query.setInt(1, gameid);
results = query.executeQuery();
Player player = null;
List<Participant> participants = new ArrayList<Participant>();
while (results.next()) {
try {
player = Player.getPlayer(Integer.parseInt(results.getString("playerid")));
Participant participant = new Participant();
participant.setGameid(Integer.parseInt(results.getString("gameid")));
participant.setPlayerid(Integer.parseInt(results.getString("playerid")));
if (results.getString("points") != null) {
participant.setPoints(Integer.parseInt(results.getString("points")));
}
participant.setNotes(results.getString("notes"));
participant.setName(player.getName());
// participant.setMeta(player.getMeta());
participants.add(participant);
} catch (SQLException ex) {
Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
}
}
return participants;
} finally {
try {
results.close();
} catch (Exception e) {
}
try {
query.close();
} catch (Exception e) {
}
try {
connection.close();
} catch (Exception e) {
}
}
} | 6 |
@Override
public Map<String, String> getCompra(Cliente cliente, Funcionario funcionario){
Map<String, String> compra = new HashMap<>();
try{
conn = ConnectionFactory.getConnection();
String sql = "SELECT to_char(datacompra, 'dd/mm/yyyy') as datacompra, secao.nome as nome FROM compra, ingresso, secao " +
"WHERE compra.idingresso = ingresso.id " +
"AND ingresso.idsecao = secao.id " +
"AND idfuncionario IN (SELECT id FROM funcionario WHERE cpf LIKE ?) " +
"AND idcliente IN (SELECT id FROM cliente WHERE cpf LIKE ?)";
ps = conn.prepareStatement(sql);
ps.setString(1, funcionario.getCpf());
ps.setString(2, cliente.getCpf());
rs = ps.executeQuery();
while(rs.next()){
String datacompra = rs.getString("datacompra");
String secao = rs.getString("nome");
compra.put(datacompra, secao);
}
} catch (SQLException e){
throw new RuntimeException("Erro " + e.getSQLState()
+ " ao atualizar o objeto: "
+ e.getLocalizedMessage());
} catch (ClassNotFoundException e){
throw new RuntimeException("Erro ao conectar ao banco: "
+ e.getMessage());
} finally {
close();
}
return compra;
} | 3 |
public List<LinkedNode<T>> removeSubNode(T key) {
if (key == null)
return null;
List<LinkedNode<T>> searchResult = new ArrayList<LinkedNode<T>>();
List<LinkedNode<T>> removeResult = new ArrayList<LinkedNode<T>>();
for (LinkedNode<T> node : subNodes) {
if (key.equals(node.getValue())) {
searchResult.add(node);
}
}
for (int i = searchResult.size() - 1; i > -1; i--) {
removeResult.add(this.removeSubNodeByIndex(searchResult.get(i)
.getIndex()));
}
return removeResult;
} | 4 |
public String getMimeType(String incUrl) {
if (incUrl.endsWith(".html") || incUrl.endsWith(".htm")) {
return "text/html";
} else if (incUrl.endsWith(".txt") || incUrl.endsWith(".java")) {
return "text/plain";
} else if (incUrl.endsWith(".gif")) {
return "image/gif";
} else if (incUrl.endsWith(".class")) {
return "application/octet-stream";
} else if (incUrl.endsWith(".jpg") || incUrl.endsWith(".jpeg")) {
return "image/jpeg";
} else {
return "text/plain";
}
} | 8 |
public ArrayList<String> getFileLists(String fn) {
if(fn.endsWith("/"))
fn.substring(0, fn.length()-1);
File file = new File(fn);
ArrayList<String> output = new ArrayList<String>();
if(file.exists()) {
if(file.isFile()) {
// Extract the folder part of the name
int dir_index = fn.lastIndexOf('/');
if (dir_index > 0 && dir_index < fn.length()) {
TestFolderPath.set(fn.substring(0, dir_index + 1));
} else {
TestFolderPath.set("");
}
output.add(fn);
} else {
TestFolderPath.set(fn + "/");
for(String fl : file.list()) {
if(fl.endsWith(".xml")) {
output.add(TestFolderPath.get() + fl);
}
}
}
}
return output;
} | 7 |
public static String reformat(String input) {
String output = input.replaceAll("@", "_").replaceAll("^", "_")
.replaceAll("\\*", "_");
if (input.contains("</table>"))
output = output.substring(0, output.indexOf("</table>"));
output = output.replaceAll("d><t", "d> <t").replaceAll("h><t", "h> <t")
.replaceAll("d></t", "d>@</t").replaceAll(" ", "-")
.replaceAll("--", "");
return output;
} | 1 |
public static void collapseToParent(Node currentNode) {
// Shorthand
JoeTree tree = currentNode.getTree();
OutlineLayoutManager layout = tree.getDocument().panel.layout;
Node parent = currentNode.getParent();
if (parent.isRoot()) {
// Collapse
currentNode.CollapseAllSubheads();
// Redraw and Set Focus
layout.draw(currentNode,OutlineLayoutManager.ICON);
} else {
// Collapse
parent.CollapseAllSubheads();
// Record the EditingNode, Mark and CursorPosition
tree.setEditingNode(parent);
tree.setComponentFocus(OutlineLayoutManager.ICON);
// Update Selection
tree.setSelectedNodesParent(parent.getParent());
tree.addNodeToSelection(parent);
// Redraw and Set Focus
layout.draw(parent,OutlineLayoutManager.ICON);
}
return;
} | 1 |
public FeedForwardNeuron(Layer previousLayer, List<Double> weigths)
throws WeigthNumberNotMatchException {
if (weigths.size() != previousLayer.getNeuronCount())
throw new WeigthNumberNotMatchException();
this.weigths = new Vector<Double>(weigths.size());
this.weigths.addAll(weigths);
previous = previousLayer;
} | 1 |
public synchronized static void sendMsg2One(UserInfo srcUser,MsgHead msg){
//1.Һ
if(msg.getType()==IMsgConstance.command_find){
//ߵĺб
Set<UserInfo> users=stList.keySet();
Iterator<UserInfo> its=users.iterator();
MsgFindResp mfr=new MsgFindResp();
mfr.setType(IMsgConstance.command_find_resp);
mfr.setSrc(msg.getDest());
mfr.setDest(msg.getSrc());
while(its.hasNext()){
UserInfo user=its.next();
if(user.getJkNum()!=msg.getSrc()){
mfr.addUserInfo(user);
}
}
//û
int count=mfr.getUsers().size();
mfr.setTotalLen(4+1+4+4+4+count*(4+10));
//Ͳҵû
stList.get(srcUser).sendMsg2Me(mfr);
return;
}
//2.Ӻ,ֻ,ҲҪϢ
if(msg.getType()==IMsgConstance.command_addFriend){
MsgAddFriend maf=(MsgAddFriend)msg;
UserInfo destUser=UserDao.addFriend(msg.getSrc(),maf.getFriendJkNum());
MsgAddFriendResp mar=new MsgAddFriendResp();
mar.setTotalLen(4+1+4+4+4+10);
mar.setDest(msg.getSrc());
mar.setSrc(msg.getDest());
mar.setType(IMsgConstance.command_addFriend_Resp);
mar.setFriendJkNum(destUser.getJkNum());//ҪӵûJK
mar.setFriendNikeName(destUser.getNikeName());
stList.get(srcUser).sendMsg2Me(mar);//Ͳҽ
//ӵҲһӺѵϢ
mar.setDest(destUser.getJkNum());
mar.setSrc(msg.getDest());
mar.setFriendJkNum(srcUser.getJkNum());
mar.setFriendNikeName(srcUser.getNikeName());
//ӵûδ,ͻ!
stList.get(destUser).sendMsg2Me(mar);
return ;
}
//3.ļϢת
if(msg.getType()==IMsgConstance.command_chatText
||msg.getType()==IMsgConstance.command_chatFile){
//,ļϢ,ת
Set<UserInfo> users=stList.keySet();
Iterator<UserInfo> its=users.iterator();
while(its.hasNext()){
UserInfo user=its.next();
if(user.getJkNum()==msg.getDest()){
stList.get(user).sendMsg2Me(msg);
}
}
}
} | 8 |
void save()
{
try
{
long t1 = System.currentTimeMillis();
if (debug)
{
System.err.println("DEBUG: nntp: newsrc saving " +
file.getPath());
}
int bs = (groups.size() * 20); // guess an average line length
FileOutputStream fw = new FileOutputStream(file);
BufferedOutputStream writer = new BufferedOutputStream(fw, bs);
for (Iterator i = groups.iterator(); i.hasNext();)
{
String group = (String) i.next();
StringBuffer buffer = new StringBuffer(group);
if (subs.contains(group))
{
buffer.append(':');
}
else
{
buffer.append('!');
}
Object r = lines.get(group);
if (r instanceof String)
{
buffer.append((String) r);
}
else
{
RangeList ranges = (RangeList) r;
if (ranges != null)
{
buffer.append(ranges.toString());
}
}
buffer.append('\n');
byte[] bytes = buffer.toString().getBytes(NEWSRC_ENCODING);
writer.write(bytes);
}
writer.flush();
writer.close();
long t2 = System.currentTimeMillis();
if (debug)
{
System.err.println("DEBUG: nntp: newsrc save: " +
groups.size() + " groups in " +
(t2 - t1) + "ms");
}
}
catch (IOException e)
{
System.err.println("WARNING: nntp: unable to save newsrc file");
if (debug)
{
e.printStackTrace(System.err);
}
}
dirty = false;
} | 8 |
private void doEscape(String str)
throws IOException, SQLException, SyntaxException {
String rest = null;
if (str.length() > 2) {
rest = str.substring(2);
}
if (str.startsWith("\\d")) { // Display
if (rest == null){
throw new SyntaxException("\\d needs display arg");
}
display(rest);
} else if (str.startsWith("\\m")) { // MODE
if (rest == null){
throw new SyntaxException("\\m needs output mode arg");
}
setOutputMode(rest);
} else if (str.startsWith("\\o")){
if (rest == null){
throw new SyntaxException("\\o needs output file arg");
}
setOutputFile(rest);
} else if (str.startsWith("\\q")){
exit(0);
} else {
throw new SyntaxException("Unknown escape: " + str);
}
} | 8 |
void register(CommandSender sender, Command cmd, String commandLabel, String[] args){
if(args.length==1){
plugin.error(sender, "/authy register (email) (phone number)");
}else if(args.length == 3){
}
} | 2 |
public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
} | 9 |
public static void test_Gleitpunktzahl() {
/**********************************/
/* Test der Klasse Gleitpunktzahl */
/**********************************/
System.out.println("-----------------------------------------");
System.out.println("Test der Klasse Gleitpunktzahl");
/*
* Verglichen werden die BitFelder fuer Mantisse und Exponent und das
* Vorzeichen
*/
Gleitpunktzahl.setAnzBitsMantisse(8);
Gleitpunktzahl.setAnzBitsExponent(6);
Gleitpunktzahl x;
Gleitpunktzahl y;
Gleitpunktzahl gleitref = new Gleitpunktzahl();
Gleitpunktzahl gleiterg;
/* Addition */
System.out.println("Test der Addition mit Gleitpunktzahl");
try {
// Test: Addition
System.out.println("Test: Addition x + y");
x = new Gleitpunktzahl(13.57);
y = new Gleitpunktzahl(5.723);
// Referenzwerte setzen
gleitref.mantisse.setInt(155);
gleitref.exponent.setInt(37);
gleitref.vorzeichen = false;
gleitref = new Gleitpunktzahl(19.293);
// Berechnung
gleiterg = x.add(y);
// Test, ob Ergebnis korrekt
if (gleiterg.compareAbsTo(gleitref) != 0
|| gleiterg.vorzeichen != gleitref.vorzeichen) {
printAdd(x.toString(), y.toString());
printErg(gleiterg.toString(), gleitref.toString());
} else {
System.out.println(" Richtiges Ergebnis\n");
}
} catch (Exception e) {
System.out.print("Exception bei der Auswertung des Ergebnis!!\n");
}
/* Subtraktion */
try {
System.out.println("Test der Subtraktion mit Gleitpunktzahl");
// Test: Addition
System.out.println("Test: Subtraktion x + y");
x = new Gleitpunktzahl(13.57);
y = new Gleitpunktzahl(5.723);
// Referenzwerte setzen
gleitref.mantisse.setInt(155);
gleitref.exponent.setInt(37);
gleitref.vorzeichen = false;
gleitref = new Gleitpunktzahl(7.847);
// Berechnung
gleiterg = x.sub(y);
// Test, ob Ergebnis korrekt
if (gleiterg.compareAbsTo(gleitref) != 0
|| gleiterg.vorzeichen != gleitref.vorzeichen) {
printSub(x.toString(), y.toString());
printErg(gleiterg.toString(), gleitref.toString());
} else {
System.out.println(" Richtiges Ergebnis\n");
}
/*************
* Eigene Tests einfuegen
*/
System.out.println("\n\nEIGENE TESTS EINFÜGEN!!!!!!!\n\n");
} catch (Exception e) {
System.out.print("Exception bei der Auswertung des Ergebnis!!\n");
}
/* Sonderfaelle */
System.out.println("Test der Sonderfaelle mit Gleitpunktzahl");
try {
// Test: Sonderfaelle
// 0 - inf
System.out.println("Test: Sonderfaelle");
x = new Gleitpunktzahl(0.0);
y = new Gleitpunktzahl(1.0 / 0.0);
// Referenzwerte setzen
gleitref.mantisse.setInt(0);
gleitref.exponent.setInt(63);
gleitref.vorzeichen = true;
// Berechnung mit der Methode des Studenten durchfuehren
gleiterg = x.sub(y);
// Test, ob Ergebnis korrekt
if (gleiterg.compareAbsTo(gleitref) != 0
|| gleiterg.vorzeichen != gleitref.vorzeichen) {
printSub(x.toString(), y.toString());
printErg(gleiterg.toString(), gleitref.toString());
} else {
System.out.println(" Richtiges Ergebnis\n");
}
} catch (Exception e) {
System.out
.print("Exception bei der Auswertung des Ergebnis in der Klasse Gleitpunktzahl!!\n");
}
} | 9 |
public void setClassName(String className) {
this.className = className;
} | 0 |
public Image getImage(URL paramURL, String paramString)
{
InputStream localInputStream = getClass().getResourceAsStream("/" + paramString);
if (localInputStream == null)
{
return super.getImage(paramURL, paramString);
}
ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
BufferedInputStream localBufferedInputStream = new BufferedInputStream(localInputStream);
try
{
byte[] arrayOfByte = new byte[4096];
int i;
while ((i = localBufferedInputStream.read(arrayOfByte)) > 0)
{
localByteArrayOutputStream.write(arrayOfByte, 0, i);
}
Image localImage = getToolkit().createImage(localByteArrayOutputStream.toByteArray());
return localImage;
}
catch (IOException localIOException)
{
System.err.println("getImage(): Failed attempt to acquire Image Resource:");
localIOException.printStackTrace();
}
return null;
} | 3 |
public static int insert(Statement stat, String table, HashMap<String, Object> values) throws SQLException {
String db_Name = DataBaseManager.getDb_name();
System.out.println("--------db_name----->>>>"+db_Name);
String fieldSql = "select COLUMN_NAME from information_schema.columns where table_name='" + table + "' and TABLE_SCHEMA = 'may_stv' ";
// String fieldSql = "select COLUMN_NAME from information_schema.columns where table_name='" + table + "' and TABLE_SCHEMA = ' " + db_Name + " ' ";
ResultSet rse = stat.executeQuery(fieldSql);
List<String> fields = new ArrayList<String>();
while (rse.next()) {
System.out.println(rse.getString(1));
fields.add(rse.getString(1));
}
StringBuffer sb = new StringBuffer();
sb.append("insert into ").append(table).append(" values(");
for (int i = 0; i < fields.size(); ++i) {
if (i == fields.size() - 1 || i == 0 && fields.size() == 1) {
System.out.println("--fileds.get(i)-->>" + fields.get(i));
sb.append(values.get(fields.get(i)));
System.out.println("----" + values.get(fields.get(i)));
continue;
}
System.out.println("----" + fields.get(i));
System.out.println("----" + values.get(fields.get(i)));
sb.append(values.get(fields.get(i))).append(",");
}
sb.append(");");
System.out.println("sql----" + sb.toString());
return stat.execute(sb.toString()) ? 0 : -1;
} | 6 |
*/
public synchronized byte[] Final () {
byte bits[];
int index, padlen;
MD5State fin;
if (finals == null) {
fin = new MD5State(state);
bits = Encode(fin.count, 8);
index = (int) ((fin.count[0] >>> 3) & 0x3f);
padlen = (index < 56) ? (56 - index) : (120 - index);
Update(fin, padding, 0, padlen);
/**/
Update(fin, bits, 0, 8);
/* Update() sets finalds to null */
finals = fin;
}
return Encode(finals.state, 16);
} | 2 |
public void putAll( Map<? extends Byte, ? extends Character> map ) {
Iterator<? extends Entry<? extends Byte,? extends Character>> it =
map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends Byte,? extends Character> e = it.next();
this.put( e.getKey(), e.getValue() );
}
} | 8 |
public static void main(String[] args) {
Client client = new Client();
client.test();
} | 0 |
@Test
public void runTestActivityLifecycle1() throws IOException {
InfoflowResults res = analyzeAPKFile("Lifecycle_ActivityLifecycle1.apk");
Assert.assertEquals(1, res.size());
} | 0 |
public static String colorToString (final Color c)
{
try {
final Field[] fields = Color.class.getFields();
for (final Field f : fields) {
if (Modifier.isPublic(f.getModifiers())
&& Modifier.isFinal(f.getModifiers())
&& Modifier.isStatic(f.getModifiers())) {
final String name = f.getName();
final Object oColor = f.get(null);
if (oColor instanceof Color) {
if (c.equals(oColor)) {
return name;
}
}
}
}
}
catch (Exception e) {
//
}
// no defined constant color, so this must be a user defined color
final String color = Integer.toHexString(c.getRGB() & 0x00ffffff);
final StringBuffer retval = new StringBuffer(7);
retval.append("#");
final int fillUp = 6 - color.length();
for (int i = 0; i < fillUp; i++) {
retval.append("0");
}
retval.append(color);
return retval.toString();
} | 8 |
public double winPossibility(ArrayList<Action> history, int playerHandStrength) {
int numRaises = 0;
for(Action a : history) {
if(a == Action.RAISE) {
numRaises++;
}
}
int[] histogram = historyToHandStrength.get(numRaises);
int aphs = adjustedHandStrength(playerHandStrength);
if(histogram == null)
return 1 - (aphs / 8);
// win % = hands player beats / total hands
int handsPlayerWins = 0;
int handsOpponentWins = 0;
int i;
for(i = 0; i < aphs; i++) {
handsOpponentWins += histogram[i];
}
for(; i < histogram.length; i++) {
handsPlayerWins += histogram[i];
}
return (double) handsPlayerWins / (handsPlayerWins + handsOpponentWins);
} | 5 |
private boolean usesNetwork(Message message, SoftwareSystem system) {
try {
Component sender = (Component) message.getSender();
Component receiver = (Component) message.getReceiver();
HardwareSet senderHS = null, receiverHS = null;
for (DeployedComponent deployedComponent : system.getDeploymentAlternative().getDeployedComponents()) {
if (deployedComponent.getComponent().equals(sender))
senderHS = deployedComponent.getHardwareSet();
if (deployedComponent.getComponent().equals(receiver))
receiverHS = deployedComponent.getHardwareSet();
}
if (!system.getActuallyUsedHardwareSets().contains(senderHS))
system.getActuallyUsedHardwareSets().add(senderHS);
if (!system.getActuallyUsedHardwareSets().contains(receiverHS))
system.getActuallyUsedHardwareSets().add(receiverHS);
return (senderHS != null && receiverHS != null && !senderHS.equals(receiverHS));
} catch (Exception e) {
}
return false;
} | 8 |
private AnswerCombination generateAnswerCombination(int black, int white) {
List<Token<AnswerColors>> tokens = new ArrayList<Token<AnswerColors>>();
for (int i = 0; i < black; i++) {
tokens.add(new Token<AnswerColors>(AnswerColors.BLACK));
}
for (int i = 0; i < white; i++) {
tokens.add(new Token<AnswerColors>(AnswerColors.WHITE));
}
while (tokens.size() < Combination.SIZE){
tokens.add(new Token<AnswerColors>(AnswerColors.EMPTY));
}
return new AnswerCombination(tokens);
} | 3 |
public OreVein[] getWorldData(World w){
if(data.containsKey(w))
return data.get(w);
else if ( conf.contains(w.getName()) ){
data.put(w, OreVein.loadConf( conf.getMapList( w.getName() ) ) );
return data.get(w);
}
else if( def!=null )
return def;
else if( conf.contains( "default" ) ){
def = OreVein.loadConf( conf.getMapList("default") );
return def;
}
return null;
} | 4 |
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(args.length == 1){
if(!(Plugin.getVoteManager().getVoteByPlayer(args[0]) == null)){
if(args[0].equalsIgnoreCase(sender.getName())){
sender.sendMessage("[RP] You can't vote for yourself!");
}else{
Plugin.getVoteManager().getVoteByPlayer(args[0]).addVote();
sender.sendMessage("[RP] Thanks for voting for " + args[0]);
}
}
}else{
sender.sendMessage("[RP] Usage: /vote <player>");
}
return false;
} | 3 |
public void strongConnectedComponent(int adjacency_matrix[][])
{
for (int i = number_of_nodes; i > 0; i--)
{
if (explore[i] == 0)
{
dfs_1(adjacency_matrix, i);
}
}
int rev_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
for (int i = 1; i <= number_of_nodes; i++)
{
for (int j = 1; j <= number_of_nodes; j++)
{
if (adjacency_matrix[i][j] == 1)
rev_matrix[finishing_time_of_node[j]][finishing_time_of_node[i]] = adjacency_matrix[i][j];
}
}
for (int i = 1; i <= number_of_nodes; i++)
{
explore[i] = 0;
leader_node[i] = 0;
}
for (int i = number_of_nodes; i > 0; i--)
{
if (explore[i] == 0)
{
leader = i;
dfs_2(rev_matrix, i);
}
}
} | 8 |
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(Motors.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Motors.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Motors.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Motors.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 Motors().setVisible(true);
}
});
} | 6 |
public static JSONObject readFile(String path) throws FileNotFoundException {
File f = new File(path);
if (!f.exists())
throw new FileNotFoundException();
try {
String jString = fileToString(path);
JSONObject obj = (JSONObject) JSONValue.parse(jString);
return obj;
} catch (IOException e) {
e.printStackTrace();
}
return null;
} | 2 |
public List<Item> getAllItems(){
try{
org.hibernate.Query query = session.createQuery("from Item");
@SuppressWarnings("unchecked")
ArrayList<Item> items = (ArrayList<Item>) query.list();
return items;
}
catch(HibernateException e){
Main.getFrame().showError("A hozzáadás sikertelen volt: "+e.getMessage());
}
return null;
} | 1 |
public SnakeServerMessage snakeServerMessageDecode(String mess)
throws JSONException {
JSONObject obj = new JSONObject(mess);
double[] p;
JSONArray JArr = obj.getJSONArray("PlayerArray");
SnakeServerMessage SSM = new SnakeServerMessage(JArr.length());
for (int i = 0; i < JArr.length(); i++) {
p = new double[10];
JSONObject l = JArr.getJSONObject(i);
JSONArray JArr2 = l.getJSONArray("Coordinates");
for (int d = 0; d < p.length; d++) {
p[d] = JArr2.getDouble(d);
}
SnakePlayer sp = new SnakePlayer(l.getInt("PlayerID"),
l.getDouble("PosX"), l.getDouble("PosY"),
l.getBoolean("Alive"), l.getInt("Score"), p);
sp.PlayerName = l.getString("PlayerName");
SSM.hasWon = obj.getBoolean("HasWon");
SSM.winnerName = obj.getString("WinnerName");
SSM.Players[i] = sp;
SSM.clearBoard = obj.getBoolean("ClearBoard");
}
return SSM;
} | 2 |
public void createPawnLabelsAdd(JPanel Square[][])
{
arraybPawns= new ArrayList<JLabel>();
arraywPawns= new ArrayList<JLabel>();
//I create the labels for every the pawns
for (int i = 0; i < 8; i++)
{
arraybPawns.add(new JLabel( new ImageIcon("pawn.png") ));
}
for (int i = 0; i < 8; i++)
{
arraywPawns.add(new JLabel( new ImageIcon("WhitePawn.png") ));
}
//I add the black pawns to the board
for (int i = 0; i < 8; i++)
{
Square[1][i].add(arraybPawns.get(i));
}
//I add the white pawns to the board
for (int i = 0; i < 8; i++)
{
Square[6][i].add(arraywPawns.get(i));
}
} | 4 |
public void originalCentrosLocal(double paramDistancia,double paramRadio)
{
Iterator elemFuente;
Elemento entrada,salida;
Iterator elemDestino = destino.listaElementos();
double sumaDistancias,sumaValores,distancia,ponderacion;
fuente.generaCentros();
destino.generaCentros();
while(elemDestino.hasNext()) //Recorre elementos destino
{
sumaDistancias = sumaValores = 0; // inicializa sumas
salida = (Elemento)((Entry)elemDestino.next()).getValue();
elemFuente = fuente.listaElementos(); //carga fuentes
while(elemFuente.hasNext()) //recorre elementos fuente
{
entrada = (Elemento)((Entry)elemFuente.next()).getValue();
distancia = distanciaCentros(entrada,salida);
if(distancia < paramRadio)
{
ponderacion = Math.pow(distancia, paramDistancia);
sumaDistancias += 1/ponderacion;
sumaValores += entrada.valor() / ponderacion;
}
}
salida.valor(sumaValores / sumaDistancias);
}
} | 3 |
@Override
public void caseAConstantesDeclaracao(AConstantesDeclaracao node)
{
inAConstantesDeclaracao(node);
if(node.getConst() != null)
{
node.getConst().apply(this);
}
if(node.getVar() != null)
{
node.getVar().apply(this);
}
if(node.getValor() != null)
{
node.getValor().apply(this);
}
outAConstantesDeclaracao(node);
} | 3 |
@Override
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
_listener.actionSPACE();
}
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
_listener.actionENTER();
}
if (evt.getKeyCode() == KeyEvent.VK_ESCAPE){
_listener.actionESC();
}
} | 3 |
@Override
public void playRoadBuildingCard(IPresenter presenter, EdgeLocation spot1,
EdgeLocation spot2) {
MoveResponse response=presenter.getProxy().playRoadBuildingCard(presenter.getPlayerInfo().getIndex(), spot1, spot2, presenter.getCookie());
if(response != null && response.isSuccessful()) {
presenter.updateServerModel(response.getGameModel());
}
else {
System.err.println("Error playing road building in playing state");
}
} | 2 |
private long parseWithMultiplier(String numberStr) {
char c = numberStr.charAt(numberStr.length() - 1);
final long mult;
if (Character.isDigit(c)) {
mult = 1;
} else {
switch (c) {
case 'k':
case 'K':
mult = 1L << 10;
break;
case 'm':
case 'M':
mult = 1L << 20;
break;
case 'g':
case 'G':
mult = 1L << 30;
break;
case 't':
case 'T':
mult = 1L << 40;
break;
default:
throw new IllegalArgumentException("Unknown multiplier character ["+c+"]");
}
numberStr = numberStr.substring(0, numberStr.length() - 1);
}
long body = Long.parseLong(numberStr);
return mult * body;
} | 9 |
public void newGameRender(GameContainer gamec, Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.white);
GC.getSisyphus().draw(0, 0, GC.getSisyphus().getWidth() * .6667f,
GC.getSisyphus().getHeight() * 0.5555f);
if (toggleCursor) {
g.drawString(">> " + commandBuff + "|", 325, 575);
} else {
g.drawString(">> " + commandBuff, 325, 575);
}
for (int i=0; i < cities.size(); i++) {
g.drawString(cities.get(i).getName() + "\n population: " + cities.get(i).getLocalPop()+
"\n rescources: " + cities.get(i).getLocalRes(),10, (i*60)+cityListY);
}
for (int i=0; i < mines.size(); i++) {
g.drawString(mines.get(i).getName() + "\n population: " +
mines.get(i).getLocalPop(), 1100, (i*40)+mineListY);
}
if(logs.size() >= 1) {
int count = 0;
for (int i=logs.size()-1; i >= 0; i--){
if(count < 4) {
g.drawString(logs.get(i), 325, 570-((logs.size()-i)*20));
count++;
}
}
}
g.drawRect(215, 10, 30, 30);
g.drawRect(215, 375, 30, 30);
g.drawRect(1035, 10, 30, 30);
g.drawRect(1035, 375, 30, 30);
} | 6 |
public void build(SegmentTermEnum indexEnum, int indexDivisor, int tiiFileLength) throws IOException {
if (instantOn.load(this,directory,segment)) {
return;
}
int indexSize = 1 + ((int) indexEnum.size - 1) / indexDivisor;
indexToTerms = new int[indexSize];
// this is only an inital size, it will be GCed once the build is complete
int initialSize = (int) (tiiFileLength * 1.5);
ByteArrayOutputStream baos = new ByteArrayOutputStream(initialSize);
CustomDataOutputStream outputStream = new CustomDataOutputStream(baos);
String currentField = null;
List<String> fieldStrs = new ArrayList<String>();
int fieldCounter = -1;
for (int i = 0; indexEnum.next(); i++) {
Term term = indexEnum.term();
if (currentField != term.field) {
currentField = term.field;
fieldStrs.add(currentField);
fieldCounter++;
}
TermInfo termInfo = indexEnum.termInfo();
indexToTerms[i] = baos.size();
outputStream.writeVInt(fieldCounter);
outputStream.writeString(term.text());
outputStream.writeVInt(termInfo.docFreq);
outputStream.writeVInt(termInfo.skipOffset);
outputStream.writeVLong(termInfo.freqPointer);
outputStream.writeVLong(termInfo.proxPointer);
outputStream.writeVLong(indexEnum.indexPointer);
for (int j = 1; j < indexDivisor; j++)
if (!indexEnum.next())
break;
}
outputStream.close();
fields = new Term[fieldStrs.size()];
for (int i = 0; i < fields.length; i++) {
fields[i] = new Term(fieldStrs.get(i));
}
this.data = baos.toByteArray();
instantOn.save(this,directory,segment);
} | 6 |
public boolean isFound(T searchData){
ListNode<T> actualNode = head;
while ((actualNode != null) && !searchData.equals(actualNode.getData())) {
actualNode = actualNode.getNext();
}
if (actualNode == null) {
return false;
} else {
return true;
}
} | 3 |
public boolean fromTrade(int itemID, int fromSlot, int amount) {
if (amount > 0 && (itemID + 1) == playerTItems[fromSlot]) {
if (amount > playerTItemsN[fromSlot]) {
amount = playerTItemsN[fromSlot];
}
addItem((playerTItems[fromSlot] - 1), amount);
if (amount == playerTItemsN[fromSlot]) {
playerTItems[fromSlot] = 0;
PlayerHandler.players[tradeWith].playerOTItems[fromSlot] = 0;
}
playerTItemsN[fromSlot] -= amount;
PlayerHandler.players[tradeWith].playerOTItemsN[fromSlot] -= amount;
resetItems(3322);
resetTItems(3415);
PlayerHandler.players[tradeWith].tradeUpdateOther = true;
if (PlayerHandler.players[tradeWith].tradeStatus == 3) {
PlayerHandler.players[tradeWith].tradeStatus = 2;
PlayerHandler.players[tradeWith].AntiTradeScam = true;
sendFrame126("", 3431);
}
return true;
}
return false;
} | 5 |
public boolean isEvil(){
switch(this){
case LAWFUL_EVIL:
case NEUTRAL_EVIL:
case CHAOTIC_EVIL:
return true;
default:
return false;
}
} | 3 |
protected final Logger getLogger() {
return LoggerFactory.getLogger(this.getClass());
} | 0 |
public void run(double duration) {
double endtime = _currentTime + duration;
while ((!empty()) && (_head.next.waketime <= endtime)) {
// if ((_head.next.waketime - _currentTime) <= 1e-05) {
// super.setChanged();
// super.notifyObservers();
// }
if ((_currentTime - _lastUpdate) > (MP.simulationTimeStep * .1)) {
_lastUpdate = _currentTime;
super.setChanged();
super.notifyObservers();
}
//System.out.println("Time is now " + _currentTime + " vs " + _head.next.waketime + " " + (_currentTime - _head.next.waketime) + " LU: " + _lastUpdate);
_currentTime = _head.next.waketime;
dequeue().run();
//super.setChanged();
//super.notifyObservers();
}
_currentTime = endtime;
} | 3 |
public void allowSort(boolean allow) {
if (allow != mAllowSort) {
mAllowSort = allow;
if (!mAllowSort) {
mSortSequence = -1;
}
}
} | 2 |
public void save(String site, String login, String mdp) {
dataSaved = false;
identifiant = new Identifiant();
if (site.isEmpty()) {
site = "NA";
}
if (login.isEmpty()) {
login = "NA";
}
if (mdp.isEmpty() || mdp == null) {
mdp = "NA";
}
byte[] loginEncrypted = this.encrypt(login, clef);
byte[] mdpEncrypted = this.encrypt(mdp, clef);
AppUtils.setConsoleMessage("mdp: " + mdp + " ; login: " + login, SQLiteDAO.class, MessageType.INFORMATION, 120, AppParams.DEBUG_MODE);
AppUtils.setConsoleMessage("mdp crypté: " + mdpEncrypted + " ; login crypté: " + loginEncrypted, SQLiteDAO.class, MessageType.INFORMATION, 121, AppParams.DEBUG_MODE);
Connection connexion = null;
PreparedStatement prepstmt = null;
try {
connexion = this.openDB();
connexion.setAutoCommit(false);
AppUtils.setConsoleMessage("Succès de la connexion à la BDD SQLite.", SQLiteDAO.class, MessageType.INFORMATION, 130, AppParams.DEBUG_MODE);
prepstmt = connexion.prepareStatement("INSERT INTO identifiants (site, login, mdp) VALUES (?, ?, ?);");
prepstmt.setString(1, site);
// prepstmt.setString(2, login);
// prepstmt.setString(3, mdp);
prepstmt.setBytes(2, loginEncrypted);
prepstmt.setBytes(3, mdpEncrypted);
prepstmt.executeUpdate();
AppUtils.setConsoleMessage("Succès de l'enregistrement des données.", SQLiteDAO.class, MessageType.INFORMATION, 144, AppParams.DEBUG_MODE);
// SKUtils.showUserMessage("Succès de l'enregistrement des données.", JOptionPane.INFORMATION_MESSAGE);
identifiant.setSite(site);
identifiant.setLogin(login);
identifiant.setMdp(mdp);
AppUtils.setConsoleMessage(identifiant.toString(), SQLiteDAO.class, MessageType.INFORMATION, 150, AppParams.DEBUG_MODE);
// this.notifyObservers();
this.notifyObservers(identifiant);
dataSaved = true;
// prepstmt.close();
// connexion.commit();
// connexion.close();
} catch (SQLException e) {
System.out.println("e.getClass() : " + e.getClass());
System.out.println("e.getClass().getName() : " + e.getClass().getName());
System.out.println("e.getErrorCode() : " + e.getErrorCode());
System.out.println("e.getSQLState() : " + e.getSQLState());
System.out.println("e.getMessage() : " + e.getMessage());
AppUtils.setConsoleMessage(e.getClass().getName() + ": " + e.getMessage(), SQLiteDAO.class, MessageType.ERROR, 138, AppParams.DEBUG_MODE);
// System.exit(0);
}
finally {
try {
prepstmt.close();
connexion.commit();
connexion.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}// END save() | 6 |
private void refresh(boolean repopulateCombo) {
if (combo == null || combo.isDisposed())
return;
// $TODO GTK workaround
try {
if (zoomManager == null) {
combo.setEnabled(false);
combo.setText(""); //$NON-NLS-1$
} else {
if (repopulateCombo)
combo.setItems(getZoomManager().getZoomLevelsAsText());
String zoom = getZoomManager().getZoomAsText();
int index = combo.indexOf(zoom);
if (index == -1 || forceSetText)
combo.setText(zoom);
else
combo.select(index);
combo.setEnabled(true);
}
} catch (SWTException exception) {
if (!SWT.getPlatform().equals("gtk")) //$NON-NLS-1$
throw exception;
}
} | 8 |
SoundEffect(String soundFileName) {
try {
// Use URL (instead of File) to read from disk and JAR.
URL url = this.getClass().getClassLoader().getResource(soundFileName);
// Set up an audio input stream piped from the sound file.
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);
// Get a clip resource.
clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioInputStream);
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
} | 3 |
public boolean check(Hand hand) {
List<Card> cards = new ArrayList<Card>(hand.getCards());
Collections.sort(cards);
Map<Suit, Integer> suits = new TreeMap<Suit, Integer>();
Map<Rank, Integer> ranks = new TreeMap<Rank, Integer>();
for (Card c : cards) {
if (!suits.containsKey(c.getSuit()))
suits.put(c.getSuit(), 1);
else {
suits.put(c.getSuit(), suits.get(c.getSuit()) + 1);
}
if (!ranks.containsKey(c.getRank()))
ranks.put(c.getRank(), 1);
else {
ranks.put(c.getRank(), ranks.get(c.getRank()) + 1);
}
}
return c(cards, cards.get(cards.size() - 1).getRank(), cards.get(0).getRank(), suits, ranks);
} | 3 |
private int truncX (int x) {
if (x < 3) {
x = 3;
}
if ((x + slider.getWidth() + 3) > INDICATOR_WIDTH) {
x = INDICATOR_WIDTH - slider.getWidth() - 3;
}
return x;
} | 2 |
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.