text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static Interlocuteur selectByIdCommercial(int id) throws SQLException {
String query = null;
Interlocuteur interlocuteur1 = new Interlocuteur();
ResultSet resultat;
try {
query = "SELECT * from INTERLOCUTEUR where ID_COMMERCIAL =? ";
PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query);
pStatement.setInt(1, id);
resultat = pStatement.executeQuery();
while (resultat.next()) {
// System.out.println(resultat.getString("INTNOM"));
interlocuteur1 = new Interlocuteur(resultat.getInt("ID_INTERLOCUTEUR"),resultat.getInt("ID_COMMERCIAL"), resultat.getInt("ID_VILLE"), resultat.getInt("ID_SERVICE"), resultat.getString("INTNOM"), resultat.getString("INTPRENOM"), resultat.getString("INTEMAIL"));
}
} catch (SQLException ex) {
Logger.getLogger(RequetesInterlocuteur.class.getName()).log(Level.SEVERE, null, ex);
}
return interlocuteur1;
} | 2 |
public String toString(){
String toString = "";
if(pointGuard1 != null){
toString = "PG: "+ pointGuard1.getName();
}
else {toString = toString+"PG: None ";}
if(pointGuard2 != null){
toString = toString + " PG: "+pointGuard2.getName();
}
else {toString = toString+" PG: None ";}
if(shootingGuard1 != null){
toString = toString + " SG: "+shootingGuard1.getName();
}
else {toString = toString+" SG: None ";}
if(shootingGuard2 != null){
toString = toString + " SG: "+shootingGuard2.getName();
}
else {toString = toString+" SG: None ";}
if(smallForward1 != null){
toString = toString + " SF: "+smallForward1.getName();
}
else {toString =toString+ " SF: None ";}
if(smallForward2 != null){
toString = toString + " SF: "+smallForward2.getName();
}
else {toString = toString+" SF: None ";}
if(powerForward1 != null){
toString = toString + " PF: "+powerForward1.getName();
}
else {toString = toString+" PF: None ";}
if(powerForward2 != null){
toString = toString + " PF: "+powerForward2.getName();
}
else {toString = toString+ " PF: None ";}
if(center != null){
toString = toString + " C: "+center.getName();
}
else {toString = toString+ " C: None";}
return toString;
} | 9 |
public void ping()
{
if(camera != null && timer.milliTime() > PING_TIME)
{
int x = 0;
int y = 0;
if(getX() > camera.getX() + camera.getWidth())
x = camera.getX() + camera.getWidth();
else if(getX() < camera.getX())
x = camera.getX();
else
x = getX();
if(getY() > camera.getY() + camera.getHeight())
y = camera.getY() + camera.getHeight();
else if(getY() < camera.getY())
y = camera.getY();
else
y = getY();
if(getX() == x && getY() == y)//is on screen so don't spawn
return;
Ripple r = new LevelChangeRipple(x, y, RIPPLE_LIFE, RIPPLE_GROWTH, getColor(), getWorld());
getWorld().addEntity(r);
timer.reset();
}
} | 8 |
public boolean isSym(TreeNode n1,TreeNode n2){
if(n1==null&&n2==null){
return true;
}else if((n1==null&&n2!=null) || (n1!=null&&n2==null)){
return false;
}else{
if(n1.val==n2.val&&isSym(n1.left, n2.right)&&isSym(n1.right,n2.left)){
return true;
}
return false;
}
} | 9 |
public static boolean haveConversation(Option... options) {
final TimedCondition stop = new TimedCondition(20000) {
@Override
public boolean isDone() {
return !isOpen() && !Widgets.canContinue();
}
};
while (stop.isRunning()) {
if (Widgets.canContinue()) {
final WidgetChild cont = Widgets.getContinue();
Keyboard.sendText(" ", false);
new TimedCondition(1000) {
@Override
public boolean isDone() {
return !cont.visible();
}
}.waitStop();
} else {
for (Option opt : options) {
if (opt.meets() && chooseOption(opt.getText())) {
break;
}
}
}
}
return stop.isDone();
} | 6 |
public void setCountry(String country) {
this.country.set(country);
} | 0 |
boolean contains( Fragment f )
{
for ( int i=0;i<rows.size();i++ )
{
Row r = rows.get(i);
if ( r.cells.size()==1 )
{
FragList fl = r.cells.get( 0 );
if ( fl.fragments.size()==1 )
{
Atom a = fl.fragments.get(0);
if ( a instanceof Fragment )
{
Fragment g = (Fragment)a;
if ( f.versions.equals(g.versions)
&& f.contents.equals(g.contents) )
return true;
}
}
}
}
return false;
} | 6 |
@XmlElementDecl(namespace = "http://www.w3.org/2001/04/xmlenc#", name = "DataReference", scope = ReferenceList.class)
public JAXBElement<ReferenceType> createReferenceListDataReference(ReferenceType value) {
return new JAXBElement<ReferenceType>(_ReferenceListDataReference_QNAME, ReferenceType.class, ReferenceList.class, value);
} | 0 |
@EventHandler
public void GiantJump(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.getGiantConfig().getDouble("Giant.Jump.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getGiantConfig().getBoolean("Giant.Jump.Enabled", true) && damager instanceof Giant && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, plugin.getGiantConfig().getInt("Giant.Jump.Time"), plugin.getGiantConfig().getInt("Giant.Jump.Power")));
}
} | 6 |
public void addArmForce(int armForce) {
this.armForce += armForce;
} | 0 |
public void triangulate (FaceList newFaces, double minArea)
{
HalfEdge hedge;
if (numVertices() < 4)
{ return;
}
Vertex v0 = he0.head();
Face prevFace = null;
hedge = he0.next;
HalfEdge oppPrev = hedge.opposite;
Face face0 = null;
for (hedge=hedge.next; hedge!=he0.prev; hedge=hedge.next)
{ Face face =
createTriangle (v0, hedge.prev.head(), hedge.head(), minArea);
face.he0.next.setOpposite (oppPrev);
face.he0.prev.setOpposite (hedge.opposite);
oppPrev = face.he0;
newFaces.add (face);
if (face0 == null)
{ face0 = face;
}
}
hedge = new HalfEdge (he0.prev.prev.head(), this);
hedge.setOpposite (oppPrev);
hedge.prev = he0;
hedge.prev.next = hedge;
hedge.next = he0.prev;
hedge.next.prev = hedge;
computeNormalAndCentroid (minArea);
checkConsistency();
for (Face face=face0; face!=null; face=face.next)
{ face.checkConsistency();
}
} | 4 |
private void checkColors() {
for (int i = 1; i < 7; i++) {
switch (labels[i].getText()) {
case "2771":
labels[i].setBackground(Color.DARK_GRAY);
break;
case "":
labels[i].setBackground(Color.BLACK);
break;
default:
if (i < 4) {
labels[i].setBackground(Color.RED);
} else {
labels[i].setBackground(Color.BLUE);
}
break;
}
}
} | 4 |
@EventHandler(ignoreCancelled = true)
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
// hide any hidden players from them
// but only if they can't see everyone anyway
if(PermissionsManager.playerHasPermission(player, "vanish.seeall")) {
return;
}
// get all our online players that are vanished
Player[] onlinePlayers = Bukkit.getServer().getOnlinePlayers();
for(Player online: onlinePlayers) {
// and vanish vanished players to the logging-in player
if(isVanished(online)) {
player.hidePlayer(online);
}
}
} | 3 |
@Override
protected Point2D calculateControl(GObject target, Context context) {
// Create variables to check for horizontal and vertical movement.
int horizontal = 0;
int vertical = 0;
// Check the context for relevant keys.
for (Integer i : context.getKeyCodesPressed()) {
// Check the code.
if (i.equals(controlScheme.up)) {
// We want to go up. That's -Y.
vertical--;
}
if (i.equals(controlScheme.dn)) {
// We want to go down. That's +Y.
vertical++;
}
if (i.equals(controlScheme.rt)) {
// We want to go right. That's +X.
horizontal++;
}
if (i.equals(controlScheme.lt)) {
// We want to go left. That's -X.
horizontal--;
}
}
// Follow the rules.
if (!verticalAllowed) {
vertical = 0;
}
if (!horizontalAllowed) {
horizontal = 0;
}
// Find the speed.
double speed = getMaxSpeed();
// Are we in both directions?
if (horizontal > 0 && vertical > 0) {
// We want to compensate for that. Pythagoras's theorem gives us:
speed /= Math.sqrt(2);
}
return new Point2D.Double(speed * horizontal, speed * vertical);
} | 9 |
public float getFloat( String name ){
XAttribute attribute = getAttribute( name );
if( attribute == null )
throw new XException( "no attribute known with name: " + name );
return attribute.getFloat();
} | 1 |
private BufferedImage createTile(int tile){
int sheetWidth = sheet.getWidth()/width;
int yOrigin = tile / sheetWidth;
int xOrigin = tile % sheetWidth;
if(xOrigin<sheet.getWidth()&&yOrigin<sheet.getHeight()){
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int x = 0;x<width;x++){
for (int y =0; y<height;y++){
if((xOrigin*width)+x<sheet.getWidth()&&(yOrigin*height)+y<sheet.getHeight()){
image.setRGB(x,y,sheet.getRGB((xOrigin*width)+x, (yOrigin*height)+y));
}else{
image.setRGB(x, y, new Color(0f,0f,0f,0f).getRGB());
}
}
}
return image;
}else{
return null;
}
} | 6 |
@Override
public void documentRemoved(DocumentRepositoryEvent e) {} | 0 |
public List<Mapping> getMappings(Literal selectLiteral) {
List<Mapping> result = new ArrayList<>();
//for(Literal literal: view.literals){
int[] positions = viewPositions.get(selectLiteral.id);
if(positions==null)
return result;
for (int i = positions[0]; i < positions[1]; i++) {
//if(literal.id==selectLiteral.id) {
Mapping currentMapping;
try {
currentMapping = new Mapping(selectLiteral, view.literals[i]);
} catch (Exception e) {
continue;
}
result.add(currentMapping);
// }
}
return result;
} | 3 |
@Override
public Connection crearConexion() {
try {
InitialContext initialContext=new InitialContext();
DataSource dataSource=(DataSource) initialContext.lookup("java:comp/env/jdbc/" + Conexion.getDatabaseName());
Connection connection=dataSource.getConnection();
return connection;
} catch (NamingException | SQLException ex) {
throw new RuntimeException(ex);
}
} | 1 |
public void insertPlace() {
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/WEB-INF/places-sample.csv");
BufferedReader br;
try {
String l="";
boolean isHeader = true;
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while((l=br.readLine())!=null){
if (isHeader) isHeader=false;
else {
String[] sa = l.split(",");
importProvider.addPlace(Long.parseLong(sa[0]), sa[1],
Integer.parseInt(sa[2]),
Integer.parseInt(sa[3]),
Integer.parseInt(sa[4]),
Integer.parseInt(sa[5]),
Integer.parseInt(sa[6]),
Long.parseLong(sa[7]), sa[8],
Integer.parseInt(sa[9]),
Integer.parseInt(sa[10]),
Integer.parseInt(sa[11]),
Integer.parseInt(sa[12]),
Integer.parseInt(sa[13]),
Long.parseLong(sa[14]), sa[15],
Integer.parseInt(sa[16]),
Integer.parseInt(sa[17]),
Integer.parseInt(sa[18]),
Integer.parseInt(sa[19]),
Integer.parseInt(sa[20]));
System.out.println("XX");
}
}
} catch (IOException e) {
e.printStackTrace();
}
} | 3 |
public String request_from_api(String data){
try {
if(this.debug){
this.MCAC.logger.log("Sending request!");
}
final URL url = new URL("http://api.crashcraft.co.uk/" + this.MCAC.APIKey);
final URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setDoOutput(true);
final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
final StringBuilder buf = new StringBuilder();
final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
buf.append(line);
}
final String result = buf.toString();
if(this.debug){
this.MCAC.logger.log(result);
}
wr.close();
rd.close();
return result;
} catch (final Exception e) {
if(this.debug){
if(this.MCAC!=null){
this.MCAC.logger.log("Fetch Data Error");
}
e.printStackTrace();
}
return "";
}
} | 6 |
private boolean r_verb_suffix() {
int among_var;
int v_1;
int v_2;
int v_3;
int v_4;
// (, line 175
// setlimit, line 176
v_1 = limit - cursor;
// tomark, line 176
if (cursor < I_pV)
{
return false;
}
cursor = I_pV;
v_2 = limit_backward;
limit_backward = cursor;
cursor = limit - v_1;
// (, line 176
// [, line 176
ket = cursor;
// substring, line 176
among_var = find_among_b(a_8, 96);
if (among_var == 0)
{
limit_backward = v_2;
return false;
}
// ], line 176
bra = cursor;
limit_backward = v_2;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 179
// try, line 179
v_3 = limit - cursor;
lab0: do {
// (, line 179
// literal, line 179
if (!(eq_s_b(1, "u")))
{
cursor = limit - v_3;
break lab0;
}
// test, line 179
v_4 = limit - cursor;
// literal, line 179
if (!(eq_s_b(1, "g")))
{
cursor = limit - v_3;
break lab0;
}
cursor = limit - v_4;
} while (false);
// ], line 179
bra = cursor;
// delete, line 179
slice_del();
break;
case 2:
// (, line 200
// delete, line 200
slice_del();
break;
}
return true;
} | 8 |
public static LinkedList<Integer[]> listaTorol( LinkedList<Integer[]> lista, Integer[] parok )
{
LinkedList<Integer[]> ujLista = new LinkedList<Integer[]>();
for( Integer[] i : lista )
{
int j=0;
for( j=0; j<6; j++ )
{
if( i[j] != parok[j] )
break;
}
if(j == 6)
ujLista.add(i);
}
for( Integer[] i : ujLista )
lista.remove(i);
return lista;
} | 5 |
private static IParameters parseParameters(String[] args) throws IOException {
IParameters parameters;
if (args.length != 0) {
parameters = new ConsoleParameters(args);
} else {
String currentDir = System.getProperty("user.dir") + "\\";
File propertiesFile = new File(currentDir + FileParameters.DEFAULT_PROPERTIES_FILE_NAME);
File articlesFile = new File(currentDir + FileParameters.DEFAULT_ARTICLES_FILE_NAME);
parameters = new FileParameters(propertiesFile, articlesFile);
}
return parameters;
} | 1 |
private static byte[] scanKeyFile(CryptobyConsole console) {
scanner = new Scanner(System.in);
byte[] tempKey = null;
do {
System.out.println("\nAllowed Key Sizes 128,192 and 256 Bit.");
System.out.println("Enter Path to Key File (Type '" + quit + "' to Escape):");
if (scanner.hasNext(quit)) {
aesCrypterFile(console);
}
keyPath = scanner.next();
try {
tempKey = CryptobyFileManager.getKeyFromFile(keyPath);
} catch (IOException ex) {
CryptobyHelper.printIOExp();
aesCrypterFile(console);
} catch (NumberFormatException nfex) {
System.out.println("Key File format is not correct!");
aesCrypterFile(console);
}
keySize = tempKey.length * 4;
} while (keySize != 128 && keySize != 192 && keySize != 256);
return tempKey;
} | 6 |
public List validate() {
String error;
if(!isNameValidate()) {
error = "Name is not valid.";
validateErrors.add(error);
}
if(!isSurnameValidate()) {
error = "Surname is not valid.";
validateErrors.add(error);
}
if(!isBirthdayValidate()) {
error = "Birthday is not valid.";
validateErrors.add(error);
}
if(!isEmailValidate()) {
error = "Email is not valid.";
validateErrors.add(error);
}
if(!isPasswordValidate()) {
error = "Password is not valid.";
validateErrors.add(error);
}
if(!isPasswordAndConfirmEquals()) {
error = "Password and password confirm not equals.";
validateErrors.add(error);
}
return this.validateErrors;
} | 6 |
private void setLinear() throws Exception {
//then set default behaviour for node.
//set linear regression combined with attribute filter
//find the attributes used for splitting.
boolean[] attributeList = new boolean[m_training.numAttributes()];
for (int noa = 0; noa < m_training.numAttributes(); noa++) {
attributeList[noa] = false;
}
TreeClass temp = this;
attributeList[m_training.classIndex()] = true;
while (temp != null) {
attributeList[temp.m_attrib1] = true;
attributeList[temp.m_attrib2] = true;
temp = temp.m_parent;
}
int classind = 0;
//find the new class index
for (int noa = 0; noa < m_training.classIndex(); noa++) {
if (attributeList[noa]) {
classind++;
}
}
//count how many attribs were used
int count = 0;
for (int noa = 0; noa < m_training.numAttributes(); noa++) {
if (attributeList[noa]) {
count++;
}
}
//fill an int array with the numbers of those attribs
int[] attributeList2 = new int[count];
count = 0;
for (int noa = 0; noa < m_training.numAttributes(); noa++) {
if (attributeList[noa]) {
attributeList2[count] = noa;
count++;
}
}
m_filter = new Remove();
((Remove)m_filter).setInvertSelection(true);
((Remove)m_filter).setAttributeIndicesArray(attributeList2);
m_filter.setInputFormat(m_training);
Instances temp2 = Filter.useFilter(m_training, m_filter);
temp2.setClassIndex(classind);
m_classObject = new LinearRegression();
m_classObject.buildClassifier(temp2);
} | 8 |
@Override
public void sourceConfInit(FlowProcess<JobConf> flowProcess,
Tap<JobConf, RecordReader, OutputCollector> tap, JobConf conf) {
conf.setInputFormat(AccumuloInputFormat.class);
setFields(TapType.SOURCE);
AccumuloTap accumuloTap = (AccumuloTap) tap;
if (false == ConfiguratorBase.isConnectorInfoSet(
AccumuloInputFormat.class, conf)) {
try {
AccumuloInputFormat.setConnectorInfo(conf,
accumuloTap.accumuloUserName,
accumuloTap.accumuloAuthToken);
AccumuloInputFormat.setScanAuthorizations(conf,
accumuloTap.accumuloAuthorizations);
AccumuloInputFormat.setInputTableName(conf,
accumuloTap.tableName);
AccumuloInputFormat.setZooKeeperInstance(conf,
accumuloTap.accumuloInstanceName,
accumuloTap.accumuloZookeeperQuorum);
} catch (AccumuloSecurityException ex) {
LOG.error("Error in AccumuloScheme.sourceConfInit", ex);
}
if (columnFamilyColumnQualifierPairs.size() > 0) {
AccumuloInputFormat.fetchColumns(conf,
columnFamilyColumnQualifierPairs);
}
if (!rowKeyStart.equals("*") && !rowKeyEnd.equals("*/0")) {
AccumuloInputFormat.setRanges(conf,
Collections.singleton(new Range(rowKeyStart, rowKeyEnd)));
}
if (addRegexFilter) {
IteratorSetting regex = new IteratorSetting(50, "regex",
RegExFilter.class);
RegExFilter.setRegexs(regex, this.rowRegex,
this.columnFamilyRegex, this.columnQualifierRegex,
this.valueRegex, false);
AccumuloInputFormat.addIterator(conf, regex);
}
if (maxAge != null) {
IteratorSetting maxAgeFilter = new IteratorSetting(48, "maxAgeFilter",
AgeOffFilter.class);
AgeOffFilter.setTTL(maxAgeFilter, maxAge);
AccumuloInputFormat.addIterator(conf, maxAgeFilter);
}
if (minAge != null) {
IteratorSetting minAgeFilter = new IteratorSetting(49, "minAgeFilter",
AgeOffFilter.class);
AgeOffFilter.setTTL(minAgeFilter, minAge + 1);
AgeOffFilter.setNegate(minAgeFilter, true);
AccumuloInputFormat.addIterator(conf, minAgeFilter);
}
}
} | 8 |
public void update(GameContainer gc, int delta, BlockMap bmap)throws SlickException
{
Vector2f trans = new Vector2f(0,0);
Input input = gc.getInput();
if(input.isKeyDown(Input.KEY_W))
{
trans.y -= 0.5f * delta;
}
if(input.isKeyDown(Input.KEY_S))
{
trans.x -= 0.5f * delta;
}
int mapWidth = bmap.tmap.getWidth() * bmap.tmap.getTileWidth();
int mapHeight = bmap.tmap.getHeight() * bmap.tmap.getTileHeight();
if(viewPort.getX() + trans.x < 0)
{
viewPort.setX(0);
}else if(viewPort.getX() + trans.x + gc.getWidth() > mapWidth){
viewPort.setX(mapWidth - gc.getWidth());
}else{
viewPort.setX(viewPort.getX() + trans.x);
}
if(viewPort.getY() + trans.y < 0)
{
viewPort.setY(0);
}else if(viewPort.getY() + trans.y + gc.getHeight() > mapHeight){
viewPort.setY(mapHeight - gc.getHeight());
}else{
viewPort.setY(viewPort.getY() + trans.y);
}
} | 6 |
public void setVar(PVar node)
{
if(this._var_ != null)
{
this._var_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._var_ = node;
} | 3 |
public void adaptSegments(boolean positiveReinforcement){
//NO WAY to remove synapses added to segment
//find a method to replace low perm synapses with new comer
if(segmentUpdateList.size()>0){
for(SegmentUpdate sUpdate : segmentUpdateList){
//System.out.print(sUpdate.updateSegment.synapses.size()+"-"+sUpdate.updateSynapsesList.size()+";");
if(positiveReinforcement){
if(sUpdate.updateSegment.newSegment==true){
this.distSegments.add(sUpdate.updateSegment);
sUpdate.updateSegment.newSegment=false;
}
for(Synapse s : sUpdate.updateSynapsesList){
s.permanenceInc();
s.updated=true;
}
for(Synapse s : sUpdate.updateSegment.synapses){
if(s.updated==false) s.permanenceDec();
else s.updated=false;
}
}else{
for(Synapse s : sUpdate.updateSynapsesList){
s.permanenceDec();
}
}
}
}
} | 8 |
public static void main(String[] args)
{
Frame frame = new Frame();
frame.setSize(width, height);
frame.setDefaultCloseOperation(3); //3 = Exit_ON_CLOSE
frame.setLocationRelativeTo(null);
frame.setResizable(false);
// frame.setUndecorated(true);
frame.setVisible(true);
frame.makscreen();
long lastFrame = System.currentTimeMillis();
while(true)
{
long thisFrame = System.currentTimeMillis();
float timeSinceLastFrame = (float) ((thisFrame - lastFrame)/1000.0);
lastFrame = thisFrame;
frame.update(timeSinceLastFrame);
frame.repaint();
try
{
Thread.sleep(10);
} catch(InterruptedException e)
{
e.printStackTrace();
}
}
} | 2 |
@Override
public void mousePressed(MouseEvent e) {
cancelDrag = false;
if (e.getComponent() == map) {
xPress = e.getX()* map.getResizeConstant();
yPress = e.getY()* map.getResizeConstant();
xPressLocal = map.getPress().x + (map.getRelease().x - map.getPress().x)*xPress/850;
yPressLocal = map.getPress().y + (map.getRelease().y - map.getPress().y)*yPress/660;
}
if(e.isPopupTrigger() && e.isShiftDown()) {
popUpPosX = e.getX();
popUpPosY = e.getY();
view.popUp.show(e.getComponent(),(int) popUpPosX,(int) popUpPosY);
}
} | 3 |
public var_type mod(var_type rhs) throws SyntaxError{
var_type v = new var_type();
keyword returnType = getPromotionForBinaryOp(v_type, rhs.v_type);
if(isNumber() && rhs.isNumber()){
if(returnType == keyword.DOUBLE || returnType == keyword.FLOAT){
sntx_err("mod uses integral types only");
}
if(rhs.value.intValue()==0)
run_err("divide by 0");
else if(returnType == keyword.INT){
v.v_type = keyword.INT;
v.value = value.intValue()%rhs.value.intValue();
}
}
v.lvalue = false;
v.constant = constant && rhs.constant;
return v;
} | 7 |
public static void main(String args[]){
if (args[0].equals("-r")){
int cycles = Integer.parseInt(args[1]);
int rounds = args.length == 3 ? ROUNDS : Integer.parseInt(args[2]);
int actLen = args.length == 3 ? Integer.parseInt(args[2]) : Integer.parseInt(args[3]);
runRandom(cycles, rounds, actLen);
}
else if (args[0].equals("-a")){
int rounds = args.length == 2 ? ROUNDS : Integer.parseInt(args[1]);
int actLen = args.length == 2 ? Integer.parseInt(args[1]) : Integer.parseInt(args[2]);
runAll(rounds, actLen);
}
else if (args[0].equals("-m")){
int rounds = args.length == 2 ? ROUNDS : Integer.parseInt(args[1]);
String actors = args.length == 2 ? args[1] : args[2];
runManual(rounds, actors);
}
} | 9 |
public Case choixCase(){
Case c;
Scanner console = new Scanner(System.in);
System.out.println("Entrez l'abscisse de la case");
int a,b;
try{
a = Integer.parseInt(console.nextLine());
} catch (NumberFormatException e) {
a = -1;
}
System.out.println("Entrez l'ordonnée de la case");
try{
b = Integer.parseInt(console.nextLine());
} catch (NumberFormatException e) {
b = -1;
}
c = goban.getCase(a, b);
if (c == null || c.getJoueur() != null || goban.isSuicide(c, this)){
System.out.println("Cette case n'est pas disponible.");
c = null;
}
return c;
} | 5 |
private int readTypeSpecTable
(ResTable_TypeSpec typeSpecTable,
byte[] data,
int offset) throws IOException {
typeSpecTable.id = readUInt8(data, offset);
offset += 1;
typeSpecTable.res0 = readUInt8(data, offset);
offset += 1;
if (typeSpecTable.res0 != 0)
throw new RuntimeException("File format violation, res0 was not zero");
typeSpecTable.res1 = readUInt16(data, offset);
offset += 2;
if (typeSpecTable.res1 != 0)
throw new RuntimeException("File format violation, res1 was not zero");
typeSpecTable.entryCount = readUInt32(data, offset);
offset += 4;
return offset;
} | 2 |
private int maxValue(int[][] grid, int depth, int alpha, int beta)
{
//check if the board is in a terminal (winning) state and
//return the maximum or minimum utility value (255 - depth or
//0 + depth) if the max player or min player is winning.
int winner = checkForWinner(grid);
if ( winner != GV.PLAYER_EMPTY)
{
if ( winner == player)
return 255 - depth;
else
return depth;
}
//check if the depth has reached its limit or if the
//board is in a terminal (tie) state and return its utility value.
if ( (depth == searchDepthLimit) || isDraw(grid))
return evaluateContent(grid);
depth++;
int column = 0;
for (int i = 0; i < GV.BOARD_COLUMNS; i++)
{
int lowestemptyrow = getLowestEmptyRow(grid, i);
if (lowestemptyrow>=0)
{
grid[lowestemptyrow][i] = player;
int value = minValue(grid, depth, alpha, beta);
if (value > alpha)
{
alpha = value;
column = i;
}
remove(grid, i);
if (alpha >= beta)
return alpha;
}
}
this.proposedColumn = column;
return alpha;
} | 8 |
@Override
public Balance Accesscreate() {
return Balance.create();
} | 0 |
public String commandTOP(String arguments) {
// Splits the input down to the message number and number of lines.
String[] argSplit = (arguments + " ").split(" ", 2);
String msgs = (argSplit[0].toUpperCase()).trim();
String ns = (argSplit[1]).trim();
int msg = convertStrToInt(msgs); if(msg == -1) {return createERR("no such message TOP " + arguments);}
int n = convertStrToInt(ns); if(n == -1){ return createERR("please enter a valid line number TOP " + arguments);}
if(idb.isMessageMarked(idb.getiMailIDFromRow(msg - 1))) {return createERR("Msg deleted. TOP " + arguments);}
String[] messages = idb.getMailMessages();
String output = createOK("TOP " + arguments);
if(msg == 0 || msg > messages.length) { return createERR("no such message, only " + messages.length + " messages in maildrop TOP " + arguments);}
String[] msgHeadersSplit = messages[msg - 1].split(CRLF + CRLF, 2);
String[] msgHeaders = msgHeadersSplit[0].split(CRLF);
String[] messageWithoutHeader = msgHeadersSplit[1].split(CRLF , n + 1);
for (int i = 0; i < msgHeaders.length && i < 10; i++) {
output += (msgHeaders[i] + CRLF);
}
output += (CRLF + CRLF);
for (int i = 0; i < messageWithoutHeader.length - 1; i++) {
output += ( messageWithoutHeader[i] + CRLF);
}
return output + "." + CRLF;
} | 8 |
public void addMethod(CtMethod m) throws CannotCompileException {
checkModify();
if (m.getDeclaringClass() != this)
throw new CannotCompileException("bad declaring class");
int mod = m.getModifiers();
if ((getModifiers() & Modifier.INTERFACE) != 0) {
m.setModifiers(mod | Modifier.PUBLIC);
if ((mod & Modifier.ABSTRACT) == 0)
throw new CannotCompileException(
"an interface method must be abstract: " + m.toString());
}
getMembers().addMethod(m);
getClassFile2().addMethod(m.getMethodInfo2());
if ((mod & Modifier.ABSTRACT) != 0)
setModifiers(getModifiers() | Modifier.ABSTRACT);
} | 4 |
private static double[] getSupportPoints(int curvePoints,int lineNumber, double[] lowPrices) {
double[] sPoints = new double[lineNumber];
for(int i =0;i<lineNumber-1;i++){
double price = 999999999;
for(int j=-(curvePoints);j<=0;j++){
if((i+j>=0) && (i+j<lineNumber-1) && lowPrices[i+j]<price){
price =lowPrices[i+j];
sPoints[i]=price;
}
}
}
return sPoints;
} | 5 |
private Collection<ITask> getRemoverTasks(Collection<ITask> availableTasks, Person person, SimulationMap map) {
Collection<ITask> removers = new ArrayList<>();
Set<String> states = person.getState();
for(ITask t: availableTasks){
if(t.getType().equals("Cleanup") && t.itemsExist(person, map)) removers.add(t);
else{
for(String state: states){
if(t.getNeg().contains(state)) removers.add(t);
}
}
}
if(removers.isEmpty())return null;
else return removers;
} | 6 |
public Object get(String atrName) {
Object ret = null;
if (atrName.equals(LABEL)) {
ret = v.getLabel();
} else if (atrName.equals(SHAPE)) {
ret = v.getShape();
} else if (atrName.equals(BORDER)) {
ret = v.getShapeStroke();
} else if (atrName.equals(LOCATION)) {
ret = v.getLocation();
} else if (atrName.equals(SIZE)) {
ret = v.getSize();
} else if (atrName.equals(MARK)) {
ret = v.getMark();
} else if (atrName.equals(SELECTED)) {
ret = v.isSelected;
} else if (atrName.equals(COLOR)) {
ret = v.getColor();
} else if (atrName.equals(LABEL_LOCATION)) {
ret = v.getLabelLocation();
} else {
ret = v.getUserDefinedAttribute(atrName);
}
return ret;
} | 9 |
@Test
public void testCheckTutChoices(){
//Initialize a boolean saying there are no students who have no first choices and aren't flagged.
boolean startEmptyFirstChoices = true;
//For each student
for(Student s: students){
//If a student has no first choices and isn't flagged
if(s.getFirstChoiceTuts().isEmpty()){
if(s.getFlaggedForTuts() == false){
//Set boolean to false
startEmptyFirstChoices = false;
}
}
}
//Run data through a StudentChoiceOrder
StudentChoiceOrder sco = new StudentChoiceOrder(students);
//Initialize a boolean saying there are no students who have no first choices and aren't flagged.
boolean endEmptyFirstChoices = true;
//For each student
for (Student s : sco.getStudents()){
//If a student has no first choices
if(s.getFirstChoiceTuts().isEmpty()){
//Ignore if they have no choices and are flagged
if(s.getFlaggedForTuts()==true && s.getSecondChoiceTuts().isEmpty() && s.getThirdChoiceTuts().isEmpty()){}
//Otherwise
else {
//Set boolean to false
endEmptyFirstChoices = false;
}
}
}
assertTrue(!startEmptyFirstChoices);
assertTrue(endEmptyFirstChoices);
} | 8 |
public void setZoom(float zoom) {
if (zoom > this.max_zoom || zoom < this.min_zoom)
return;
if (this.zoomElement) {
this.taille_noeud = taille_noeud / this.zoom * zoom;
this.decalage_passage = decalage_passage / this.zoom * zoom;
this.largeur_chausse = largeur_chausse / this.zoom * zoom;
this.larg_paint = larg_paint / this.zoom * zoom;
}
this.zoom = zoom;
} | 3 |
public Object getJsonFromFile(Class<?> type) throws IOException {
Gson gson = new Gson();
Object jsonObject = null;
InputStream stream = this.getClass().getClassLoader()
.getResourceAsStream(getPath());
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(stream));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
stringBuilder.append(line);
line = bufferedReader.readLine();
}
jsonObject = gson.fromJson(stringBuilder.toString(), type);
} finally {
bufferedReader.close();
}
return jsonObject;
} | 2 |
protected String read_zigzag(char[][] block, int[] num_key,boolean row)
{
StringBuilder sb=new StringBuilder();
if(row)
{
for(int i=1;i<=num_key.length;i++)
{
int pos=Generic_Func.search_index(num_key, i, 0);
for(int j=0;j<block[pos].length;j++)
{
if(block[pos][j]!='\0')
sb.append(block[pos][j]);
}
}
}
else//column
{
for(int i=1;i<=num_key.length;i++)
{
int pos=Generic_Func.search_index(num_key, i, 0);
for(int j=0;j<block.length;j++)
{
if(block[j][pos]!='\0')
sb.append(block[j][i]);
}
}
}
return sb.toString();
} | 7 |
public int storeAnnotation(Annotation anno) {
int result = 0;
ResultSet rs = null;
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("insert into Annotations (TicketID_FK, WorkerID_FK, Annotation, CreatedOn) values (?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
statement.setInt(1, anno.getTicketID());
statement.setInt(2, anno.getWorkerID());
statement.setString(3, anno.getText());
statement.setTimestamp (4, anno.getCreatedOn());
statement.executeUpdate();
rs = statement.getGeneratedKeys();
rs.next();
result = rs.getInt(1);
} catch(SQLException e){
e.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (Exception e) {}
try { if (statement != null) statement.close(); } catch (Exception e) {}
}
return result;
} | 5 |
private Parameter createGroup(int contextParameter, List<Type> types, List<Annotation[]> annotationsList, List<Field> fields,
Class groupType, Method methodType)
{
List<Parameter> parameters = new ArrayList<>();
int posList = 0;
for (int i = contextParameter + 1; i < types.size(); i++)
{
final Type type = types.get(i);
final Annotation[] annotations = annotationsList.get(i);
Parameter param = createParameter(fields, methodType, i, type, annotations);
if (param.getParameterType() == ParameterType.INDEXED)
{
param.offer(Properties.FIXED_POSITION, posList++);
}
parameters.add(param);
}
Parameter parameter = new Parameter();
parameter.offer(Properties.PARSER, new GroupParser(parameter, groupType, parameters));
return parameter;
} | 2 |
private Move_Two processInput(String xmlString) {
//goal is to convert XML representation, embedded
//in xmlString, to instance of move object. Ideally
//this could be done auto-magically, but these technologies
//are heavyweight and not particularly robust. A nice
//compromise is to use a generic tree parsing methodology.
//such exists for XML -- it is called DOM. DOM is mapped
//to many languages and is robust and simple (if a bit
//of a hack). JDOM is superior but not as uniformly adopted.
//first goal is to yank these values out of XML with minimal effort
int moveLocation;
String color;
String requestType;
//parse XML into DOM tree
//getting parsers is longwinded but straightforward
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//once you have parse just call parse. to parse a string vs.
//a File requires using an InputSource. In any case result is
//a DOM tree -- ie an instance of org.w3c.dom.Document
Document document
= builder.parse(new InputSource(new StringReader(xmlString)));
//must invoke XML validator here from java. It is a major advantage
//of using XML
//assuming validated we continue to parse the data ...
//always start by getting root element
Element root = document.getDocumentElement();
//get the value of the id attribute
requestType = root.getAttribute("type");
if (requestType.equalsIgnoreCase("move")) {
Element locElement =
(Element) document.getElementsByTagName("location").item(0);
Element colorElement =
(Element) document.getElementsByTagName("color").item(0);
moveLocation =
Integer.parseInt(locElement.getFirstChild().getNodeValue());
color = colorElement.getFirstChild().getNodeValue();
Move_Two moveTwo = new Move_Two(1, color, moveLocation);
return moveTwo;
} else return null;
} catch (Exception e) {
System.out.print(e);
return null;
}
} | 2 |
public static void bubbleSortImproved(int[] a){
System.out.println("Array before sorting");
for(int i:a)
System.out.print(i+" ");
System.out.println();
System.out.println("Sorting sequences after each iteration");
int n=a.length;
boolean swapped=true;
for(int i=0;i<n&&swapped;i++){
swapped=false;
for(int j=0;j<(n-i-1);j++){
if(a[j]>a[j+1]){
//swap elements, greatest one bubbles out.
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
swapped=true;
}
}
for(int k:a)
System.out.print(k+" ");
System.out.println();
}
System.out.println("Array after sorting");
for(int i:a)
System.out.print(i+" ");
} | 7 |
public void test_LocalDate_toDateMidnight_Turk() {
LocalDate date = new LocalDate(2007, 4, 1);
try {
date.toDateMidnight(MOCK_TURK);
fail();
} catch (IllegalInstantException ex) {
assertEquals(true, ex.getMessage().startsWith("Illegal instant due to time zone offset transition"));
}
} | 1 |
public static String decrypt (String str) {
byte[] keyMac = OSUtils.getMacAddress();
byte[] keyHardware = OSUtils.getHardwareID();
String s;
try {
Cipher aes = Cipher.getInstance("AES");
if (keyHardware != null && keyHardware.length > 0) {
try {
aes.init(Cipher.DECRYPT_MODE, new SecretKeySpec(pad(keyHardware), "AES"));
s = new String(aes.doFinal(Base64.decodeBase64(str)), "utf8");
if (s.startsWith("FDT:") && s.length() > 4)
return s.split(":", 2)[1];// it was decrypted with HW UUID
} catch (Exception e) {
Logger.logDebug("foo", e);
}
}
// did not open, try again with old mac based key
aes.init(Cipher.DECRYPT_MODE, new SecretKeySpec(pad(keyMac), "AES"));
s = new String(aes.doFinal(Base64.decodeBase64(str)), "utf8");
if (s.startsWith("FDT:") && s.length() > 4)
return s.split(":", 2)[1];//we don't want the decryption test
else
return decryptLegacy(str, keyMac);
} catch (Exception e) {
Logger.logError("Error Decrypting information, attempting legacy decryption", e);
return decryptLegacy(str, keyMac);
}
} | 8 |
private void nextLevel() {
resetLevel();
if(nextLevel.startsWith("b")){
getKarpfenGame().setLvl(new BossLevel(nextLevel, getKarpfenGame()));
}else if(nextLevel.startsWith("s")){
getKarpfenGame().setStory(new Storyline(nextLevel, getKarpfenGame()));
}else{
getKarpfenGame().setLvl(new Level(nextLevel, karpfenGame));
}
} | 2 |
public static int[] heapSort(int[] array) {
if(array == null || array.length <= 1) {
return array;
}
buildMaxHeap(array);
for(int heapSize = array.length; heapSize > 1; heapSize--) {
swap(array, 0, heapSize - 1);
maxHeapify(array, 0, heapSize - 1);
}
return array;
} | 3 |
public MethodVisitor visitMethod(final int access, final String name,
final String desc, final String signature, final String[] exceptions) {
if ((access & Opcodes.ACC_SYNTHETIC) != 0) {
cp.newUTF8("Synthetic");
}
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
cp.newUTF8("Deprecated");
}
cp.newUTF8(name);
cp.newUTF8(desc);
if (signature != null) {
cp.newUTF8("Signature");
cp.newUTF8(signature);
}
if (exceptions != null) {
cp.newUTF8("Exceptions");
for (int i = 0; i < exceptions.length; ++i) {
cp.newClass(exceptions[i]);
}
}
return new MethodConstantsCollector(cv.visitMethod(access, name, desc,
signature, exceptions), cp);
} | 5 |
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(TelaInicial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaInicial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaInicial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaInicial.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 TelaInicial().setVisible(true);
}
});
} | 6 |
public static IXMLFormatter getXMLFormatter(Class toClass)
{
if (g_oFormatters == null)
{
g_oFormatters = new HashTable<Class, IXMLFormatter>();
}
if (g_oFormatters.containsKey(toClass))
{
return g_oFormatters.get(toClass);
}
// Need to load and cache the formatter for this type
// TODO: Need to implement the usage of FormatTypes
List<IXMLFormatter> loFormatters = Application.getInstance().getObjectCache().getObjects(IXMLFormatter.class, "supports");
IXMLFormatter loDefaultFormatter = getDefaultFormatter();
IXMLFormatter loCurrent = null;
for (IXMLFormatter loFormatter : loFormatters)
{
// Taking note of what this formatter (examined in the loop) supports.
Class loSupportedClass = loFormatter.supports();
if (loSupportedClass == toClass)
{
loCurrent = loFormatter;
break;
}
// If this formatter is not a default formatter
// and the class (whose formatter we are looking for) is equal or assignable
// to the class this formatter supports
if (loFormatter.getClass() != loDefaultFormatter.getClass() && Goliath.DynamicCode.Java.isEqualOrAssignable(loSupportedClass, toClass))
{
// Get the formatter whose supported class is at the closest distance to the class whose formatter we're looking for
// If currently there's no selected formatter, or the class supported by the currently selected
// extends the class supported by this formatter
if (loCurrent == null || Goliath.DynamicCode.Java.isEqualOrAssignable(loCurrent.supports(), loSupportedClass))
{
loCurrent = loFormatter;
}
}
}
g_oFormatters.put(toClass, (loCurrent == null) ? loDefaultFormatter : loCurrent);
return g_oFormatters.get(toClass);
} | 9 |
public Puzzle findSolution()
{
iterativeLogicSolve();
printPuzzle();
if(getTruthState()==1)
{
return this;
}
else if(getTruthState()==-1)
{
return null;
}
else
{
Cell c = this.getChoice();
ArrayList<Integer> guesses = c.getPosNumbers();
Puzzle solution = null;
for(int i=0; i<guesses.size(); i++)
{
Puzzle guess = this.clone();
guess.getCell(c.getRow(), c.getCol()).setValue(guesses.get(i));
Puzzle terminal = guess.findSolution();
if(terminal!=null)
{
solution = terminal;
i = guesses.size();
}
}
return solution;
}
} | 4 |
public void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) {
this.tempFileManagerFactory = tempFileManagerFactory;
} | 0 |
private boolean r_Step_4() {
int among_var;
int v_1;
// (, line 91
// [, line 92
ket = cursor;
// substring, line 92
among_var = find_among_b(a_5, 19);
if (among_var == 0)
{
return false;
}
// ], line 92
bra = cursor;
// call R2, line 92
if (!r_R2())
{
return false;
}
switch(among_var) {
case 0:
return false;
case 1:
// (, line 95
// delete, line 95
slice_del();
break;
case 2:
// (, line 96
// or, line 96
lab0: do {
v_1 = limit - cursor;
lab1: do {
// literal, line 96
if (!(eq_s_b(1, "s")))
{
break lab1;
}
break lab0;
} while (false);
cursor = limit - v_1;
// literal, line 96
if (!(eq_s_b(1, "t")))
{
return false;
}
} while (false);
// delete, line 96
slice_del();
break;
}
return true;
} | 9 |
public static int partition(int[] a, int low, int high)
{
int i = low;
int j = high + 1;
int point = a[low];
while(true)
{
while( less(a[++i], point) )
{
if(i == high)
break;
}
while( less(point, a[--j]) )
{
if(j == low)
break;
}
if(i >= j)
break;
exchange(a, i, j);
}
exchange(a, low , j);
return j;
} | 6 |
public void assignBehaviour(Behaviour behaviour) {
if (behaviour == null) I.complain("CANNOT ASSIGN NULL BEHAVIOUR.") ;
if (updatesVerbose) I.sayAbout(actor, "Assigning behaviour "+behaviour) ;
actor.assignAction(null) ;
final Behaviour replaced = rootBehaviour() ;
cancelBehaviour(replaced) ;
pushBehaviour(behaviour) ;
if (replaced != null && ! replaced.finished()) {
if (updatesVerbose) I.sayAbout(actor, " SAVING PLAN AS TODO: "+replaced) ;
todoList.include(replaced) ;
}
} | 5 |
public static void Unread(String hostmask)
{
for(String s : Prefixes){ if(s.split(" ")[0].equalsIgnoreCase(hostmask)) Prefixes.remove(s); }
for(String s : Suffixes){ if(s.split(" ")[0].equalsIgnoreCase(hostmask)) Suffixes.remove(s); }
} | 4 |
public void startListening() {
listening = true;
Thread thread = new Thread(this);
thread.start();
} | 0 |
public void readBdn(File inFile, File outFile) {
boolean pngToBmp = true;
long lasting = System.currentTimeMillis();
File inParentDirectory = inFile.getParentFile();
File outParentDirectory = outFile.getParentFile();
if (!inParentDirectory.isDirectory()) {
System.out.println("inParentDirectory: " + inParentDirectory.toString() + " is not directory.");
return;
}
if (!outParentDirectory.isDirectory()) {
System.out.println("outParentDirectory: " + outParentDirectory.toString() + " is not directory.");
return;
}
try {
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF8"));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inFile);
NodeList formatNl = doc.getElementsByTagName("Format");
Element formatElement = (Element) formatNl.item(0);
Float frameRate = Float.parseFloat(formatElement.getAttribute("FrameRate"));
NodeList eventNl = doc.getElementsByTagName("Event");
int total = eventNl.getLength();
listener.changeStatus("Total length: " + total);
for (int i = 0; i < total; i++) {
Node eventNode = eventNl.item(i);
Element eventElement = (Element) eventNode;
NodeList graphNodes = eventNode.getChildNodes();
String startTime = eventElement.getAttribute("InTC");
String endTime = eventElement.getAttribute("OutTC");
startTime = BdnToSrtConverter.BDNTimeToSrtTime(startTime, frameRate);
endTime = BdnToSrtConverter.BDNTimeToSrtTime(endTime, frameRate);
listener.changeStatus("Converting: " + (i+1) + "/" + total);
out.append(String.format("%d", (i + 1))).append("\r\n");
out.append(startTime);
out.append(" --> ");
out.append(endTime).append("\r\n");
for (int j = 0; j < graphNodes.getLength(); j++) {
String nodeName = graphNodes.item(j).getNodeName();
if (!nodeName.equals("Graphic")) {
continue;
}
Element graphNode = (Element) graphNodes.item(j);
String text = graphNode.getTextContent();
if (pngToBmp) {
String inPngFilePath = inParentDirectory.toString() + "/" + text;
text = String.format("%04d.bmp", (i + 1));
String outBmpFilePath = outParentDirectory.toString() + "/" + text;
// convert file and save to destination
BdnToSrtConverter.pngToBmp(new File(inPngFilePath), new File(outBmpFilePath));
}
out.append(text).append("\r\n");
}
out.append("\r\n");
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
} | 7 |
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ESCAPE) {
getStageManager().close();
}
} | 1 |
@Override
public void separateOperands() {
operandArray = new ArrayList<String>();
instructionArray = new ArrayList<String>();
for (int i = 0; i < programString.size(); i++) {
if (programString.get(i).contains("DATA")) { //Only operand declarations contain this String sequence
operandArray.add(programString.get(i));
}
else if (programString.get(i).trim().startsWith("#")) { //Detect comments embedded between lines of code
//Do nothing; don't add comment lines to instruction or operand arrays
}
else { //If the line isn't a comment or operand declaration, add to instructionArray
instructionArray.add(programString.get(i));
}
}
//Create array to hold assembled program, deducing size from instruction and operand ArrayList sizes
programCode = new Data[instructionArray.size() + operandArray.size()];
operandAddressPointer = instructionArray.size(); //Set operand address pointer to a location that will come immediately
//after the last instruction (deduced by size of instructionArray).
} | 3 |
private void calcWindow()
{
// get current dims
width = getWidth();
height = getHeight();
// do some checks to see if we need a new draw buffer
if(buf == null
|| width < buf.getWidth() - 40
|| width > buf.getWidth()
|| height < buf.getHeight() - 40
|| height > buf.getHeight()
){
buf = new BufferedImage(width+20, height+20, BufferedImage.TYPE_INT_ARGB);
}
// calculate list boxes
for(int x = 0; x <= 6; x++)
lbx[x] = (x*width*2+1)/(6*2);
lby = (16*(TrackerFont.FNT_XAIMUS.getHeight()+1)+1);
for(int i = 0; i < 6; i++)
{
if(lbsel[i] < lboffs[i])
lboffs[i] = lbsel[i];
if(lbsel[i] > lboffs[i]+15)
lboffs[i] = lbsel[i]-15;
}
} | 9 |
@Override
public void actionPerformed(ActionEvent ae)
{
for (Updatable u : updatables)
{
if (u == null)
continue;
//When game is paused only update PlayerInput
if (gameIsPaused && u.getClass() != PlayerInput.class)
continue;
u.update();
}
} | 4 |
private void layTrack() {
int[] next = null;
switch (buildDir) {
case "N":
next = coaster.nextTrack(1);
break;
case "E":
next = coaster.nextTrack(2);
break;
case "S":
next = coaster.nextTrack(3);
break;
case "W":
next = coaster.nextTrack(4);
break;
}
if (next != null) {
if (WorldTiles.isRightCorner(selectedTrack)) placeRightCorner(next);
else {
boolean canLay = worldData.addTile(next[0], next[1], next[2], selectedTrack);
if (canLay) coaster.addTrack(next, selectedTrack);
}
}
} | 7 |
public boolean bonusPeutAttaquer(Territoire from, Territoire to){
if( to.estEnBordure() )
return true;
return false;
} | 1 |
@Override
public void makeVisible(boolean v) {
for(IScreenItem item : screenItems) {
item.setVisible(v);
}
} | 1 |
public StringBuilder sub(StringBuilder aValue, String MaxForSub) {
while (aValue.length() > MaxForSub.length()) {
//fills up 0's if value got more numbers
MaxForSub = "0" + MaxForSub;
}
for (int i = aValue.length(); i >= 1; i--) {
if (MaxForSub.charAt(i - 1) > aValue.charAt(i - 1)) {
tmp = i - 1;
while (aValue.charAt(tmp - 1) == '0') {
aValue.setCharAt(tmp - 1, '9');
tmp--;
if (tmp == 0) {
break;
}
if (aValue.charAt(tmp - 1) != '0') {
tmp1 = aValue.charAt(tmp - 1);
aValue.setCharAt(tmp - 1, convertAndSubtrac1(tmp1));
minuend = aValue.charAt(i - 1);
subtrahend = MaxForSub.charAt(i - 1);
aValue.setCharAt(i - 1, convertAndSubtrac10(minuend, subtrahend));
break;
}
}
} else {
minuend = aValue.charAt(i - 1);
subtrahend = MaxForSub.charAt(i - 1);
aValue.setCharAt(i - 1, convertAndSubtrac(minuend, subtrahend));
}
}
if (aValue.charAt(0) == '0') {
aValue.deleteCharAt(0);
}
aValue.setCharAt(aValue.length() - 1, convertAndSubtrac1(aValue.charAt(aValue.length() - 1)));
return aValue;
} | 7 |
public static void refreshNYMSList() {
System.out.println("IN refreshNYMSList");
((NYMTableModel) jTable_NymsList.getModel()).setValue(new NYM().loadNYM(), jTable_NymsList);
nymMap = new NYM().loadNYM();
String serverID = "ALL";
if (serverMap != null && serverMap.size() > 0 && jComboBox5.getSelectedIndex() > -1) {
serverID = ((String[]) serverMap.get((Integer) jComboBox5.getSelectedIndex()))[1];
}
nymRegisteredMap = new NYM().loadRegisteredNYM(serverID);
((NYMTableModel) jTable6.getModel()).setValue(new NYM().loadNYM(), jTable6);
Helpers.populateCombo(nymMap, jComboBox_Nyms);
Helpers.populateComboWithoutAll(nymRegisteredMap, jComboBox6);
} | 3 |
public float getDiscount() {
return discount;
} | 0 |
public void update(GoldRushApplet app, Mine m) {
if (Collision(m)) {
app.ir.goldcount += currentgold;
currentgold = 0;
x = ux;
y = uy;
if (!(lives - 1 < 0)) {
lives--;
}
if (lives == 0) {
gameOver = true;
}
}
if(a.il.goldcount == 5000 && currentgold == 0){
win = true;
}
if (x + dx < 120) { // if close to left island
x = 120;
unload_x = x; // for unloading later
timer.start();
} else if (x + dx > app.ir.x - app.ir.width - 30) { // if close to right island
x = app.ir.x - app.ir.width - 30;
load_x = x;
timer.start();
}
if (y + dy < 200) { // location of water edge
y = 200;
} else if (y + dy > app.getHeight() - img_r.getHeight(null)) {
y = app.getHeight() - img_r.getHeight(null);
}
} | 9 |
public static String stripWhitespace(String str) {
char[] from = str.toCharArray();
char[] to = new char[from.length];
int t = 0;
for (char c : from) {
if (!(c == ' ' || c == '\t' || c == '\n' || c == '\r')) {
to[t++] = c;
}
}
return new String(to, 0, t);
} | 5 |
public HashMap<Integer, String[]> sort( File f ) throws IOException{
BufferedReader br = new BufferedReader( new FileReader(f) );
HashMap<Integer, String[]> out = new HashMap<Integer, String[]>();
int c;
int bracket = (int) '>';
int newline = (int) '\n';
int flag = 0;
String annotation = "";
String sequence = "";
String[] entry = new String[2];
Integer i = 0;
while ( (c = br.read()) != -1 ) {
if (c == bracket){
flag = 1;
i += 1;
if ( !sequence.equals("") ){
entry[1] = sequence;
out.put( i, entry );
}
}
if (flag == 1) {
if ( c == newline ){
entry[0] = annotation;
flag = 0;
} else {
annotation += (char) c;
}
} else {
sequence += (char) c;
}
}
return out;
} | 5 |
private static int outcode(double pX, double pY, double rectX, double rectY, double rectWidth, double rectHeight) {
int out = 0;
if (rectWidth <= 0) {
out |= OUT_LEFT | OUT_RIGHT;
} else if (pX < rectX) {
out |= OUT_LEFT;
} else if (pX > rectX + rectWidth) {
out |= OUT_RIGHT;
}
if (rectHeight <= 0) {
out |= OUT_TOP | OUT_BOTTOM;
} else if (pY < rectY) {
out |= OUT_TOP;
} else if (pY > rectY + rectHeight) {
out |= OUT_BOTTOM;
}
return out;
} | 6 |
public static void CLASS(){
double i = Math.random();
if (i < 0.33)
System.out.println("Even though Damon slept through class, he obtained notes from his good friends Nan, Kevin, and David.");
else if (i < 0.66)
System.out.println("Damon slept through the class, but he somehow feels like he reached an epiphany, and thus learned the material anyways. (We don't know how either)");
else
System.out.println("Surprisingly Damon took notes today, and managed to learn the material covered in class (atleast that's what we think).");
} | 2 |
public static void main(String[] args)
{
System.out.println("------- Some testing --------\n");
Test.jExec();
System.out.println("Program is on.\n");
try {
listeningSocket = new ServerSocket(portNumber);
while(true){
System.out.println("Waiting for a new client...\n");
Socket interactiveSocket = listeningSocket.accept();
System.out.println("A new user has come!...\n");
DesireThread threadForUser = new DesireThread(interactiveSocket);
System.out.println("Thread is made\n");
threadForUser.start();
}
} catch (IOException error){
System.out.println(error.getMessage());
}
finally{
try {
listeningSocket.close();
System.out.println("Server socket is successfully closed\n");
}
catch (IOException error) {
System.out.println("Listening socket can't be closed\n");
}
}
System.out.println("Program is successfully over.\n");
} | 3 |
private synchronized void processRequest(Packet packet) {
if(packet == null) {
sendToClient(Packet.getIncorrectCommandPacket());
} else {
String code = packet.getCode();
if(code.equals(Packet.PACKET_CODES.LEAVE_GAME_CMD)) {
leave();
} else if(code.equals(Packet.PACKET_CODES.FINISH_GAME_CMD)) {
finish();
} else if(code.equals(Packet.PACKET_CODES.MAKE_TURN_CMD)) {
makeTurn(packet);
} else if(code.equals(Packet.PACKET_CODES.UPDATE_CMD)) {
update();
} else {
sendToClient(Packet.getIncorrectCommandPacket());
}
}
} | 5 |
public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
} | 6 |
public void remove(IHudItem hudItem) {
if (!hudItemQueue.remove(hudItem)) {
logger.info("tried to remove a hud item that didn't exist");
}
} | 1 |
public void testNegated() {
Hours test = Hours.hours(12);
assertEquals(-12, test.negated().getHours());
assertEquals(12, test.getHours());
try {
Hours.MIN_VALUE.negated();
fail();
} catch (ArithmeticException ex) {
// expected
}
} | 1 |
@EventHandler(priority = EventPriority.HIGH)
public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled())
return;
Block bl = event.getBlock();
Location loc = bl.getLocation();
if (bl.getType().equals(Material.ANVIL)) {
if (plugin.anvils.containsKey(loc)) {
ItemStack hand = event.getPlayer().getItemInHand();
ItemMeta meta = hand.getItemMeta();
if (hand.getType().equals(Material.STONE_PICKAXE)
&& meta.getDisplayName().equals(
ChatColor.WHITE + "Hammer")) {
event.setCancelled(true);
} else {
Inventory inv = plugin.anvils.get(loc);
for (int i = 0; i <= 8; i++) {
ItemStack is = inv.getItem(i);
if (is != null) {
bl.getWorld().dropItemNaturally(loc, is);
}
}
plugin.anvils.remove(loc);
}
}
}
} | 7 |
public boolean handleReleased(Point clickPoint) {
HUDArea hudArea = null;
boolean ret = false;
if(!shouldRender) {
return false;
}
if (isInside(clickPoint)) {
//start from the top and work our way down to "layer" the huds
for (int i = (hudAreas.size() - 1); i >= 0; i--) {
hudArea = hudAreas.get(i);
if (hudArea.handleReleased(clickPoint)) {
HUDAreaReleased(hudArea);
ret = true;
break;
}
}
}
return ret;
} | 4 |
public static byte getPrecedence(byte t) {
switch (t) {
case WATER:
return WATER_PRECEDENCE;
case GRASS:
return GRASS_PRECEDENCE;
case SNOW:
return SNOW_PRECEDENCE;
case SAVANNAH:
return SAVANNAH_PRECEDENCE;
case SAND_DESERT:
return SAND_DESERT_PRECEDENCE;
default:
return (byte) 0;
}
} | 5 |
public void getInput() throws IOException {
String command;
Scanner inFile = new Scanner(System.in);
do {
this.display(); // display the menu
// get command entered
command = inFile.nextLine();
command = command.trim().toUpperCase();
switch (command) {
case "N":
this.mainMenuControl.startGame();
break;
case "O":
this.mainMenuControl.displayOptionMenu();
break;
case "H":
this.mainMenuControl.displayHelpMenu();
break;
case "Q":
break;
default:
new MemoryError().displayError("Invalid command. Please enter a valid command.");
continue;
}
} while (!command.equals("Q"));
System.out.println(
"\t-----Quits Game----"
);
} | 5 |
protected static boolean withinGlobeQuandrant(double latitude, double longitude, double nLat, double sLat, double eLong, double wLong) {
return (latitude <= nLat && latitude >= sLat && longitude <= eLong && longitude >= wLong);
} | 3 |
public Label getLabel() {
if (label == null) {
label = new Label();
}
return label;
} | 1 |
public static List<String> split(String l, String sep, Boolean all) {
int nest = 0;
int lsep = sep.length();
ArrayList<String> returnValue = new ArrayList<String>();
if (l.equals("")) {
return returnValue;
}
for (int i = 0; i <= l.length() - lsep; i++) {
String current = l.substring(i, i + lsep);
if ((nest <= 0) && (current.equals(sep))) {
if (all) {
returnValue.add(l.substring(0, i));
returnValue.addAll(split(l.substring(i + lsep), sep, all));
} else {
returnValue.add(l.substring(0, i));
returnValue.add(l.substring(i + lsep));
}
return returnValue;
}
if ((current.equals("[")) || (current.equals("("))) {
nest += 1;
}
if ((current.equals("]")) || (current.equals(")"))) {
nest -= 1;
}
}
returnValue.add(l);
return returnValue;
} | 9 |
public void testColumnNameCount() {
DataSet ds = null;
try {
final DelimitedColumnNamesInFile testDelimted = new DelimitedColumnNamesInFile();
ds = testDelimted.getDsForTest();
// check that we parsed in the right amount of column names
assertEquals(6, ds.getColumns().length);
} catch (final Exception ex) {
ex.printStackTrace();
} finally {
}
} | 1 |
private double findStopFraction()
{
// We would like to walk the full length of centerToAff ...
double scale = 1;
stopper = -1;
// ... but one of the points in S might hinder us
for (int j = 0; j < size; ++j)
if (!support.isMember(j))
{
// Compute vector centerToPoint from center to the point S[j]:
for (int i = 0; i < dim; ++i)
centerToPoint[i] = S.coord(j, i) - center[i];
double dirPointProd = 0;
for (int i = 0; i < dim; ++i)
dirPointProd += centerToAff[i] * centerToPoint[i];
// We can ignore points beyond support since they stay enclosed anyway
if (distToAffSquare - dirPointProd < Eps * radius * distToAff) continue;
// Compute the fraction we can walk along centerToAff until
// we hit point S[i] on the boundary.
// (Better don't try to understand this calculus from the code,
// it needs some pencil-and-paper work.)
double bound = 0;
for (int i = 0; i < dim; ++i)
bound += centerToPoint[i] * centerToPoint[i];
bound = (squaredRadius - bound) / 2 / (distToAffSquare - dirPointProd);
// Take the smallest fraction
if (bound > 0 && bound < scale)
{
if (log) debug("found stopper " + j + " bound=" + bound + " scale=" + scale);
scale = bound;
stopper = j;
}
}
return scale;
} | 9 |
public void setProtocol(FileProtocol protocol) {
this.protocol = protocol;
setText(protocol.getName());
} | 0 |
public static List<Utterance> segUtterances(List<Utterance> goldUtterances,
boolean dropStress) {
List<Utterance> segUtterances = new LinkedList<Utterance>();
for (Utterance utt : goldUtterances) {
Utterance segUtt = new Utterance(utt, false);
if (dropStress) {
segUtt.reduceStresses();
}
segUtterances.add(segUtt);
}
return segUtterances;
} | 2 |
public void comandos(){
boolean sesion;
do{
sesion = false;
System.out.println(" ");
if(ManejadorAdministradores.getInstancia().getAdmin() != null){
System.out.print(ManejadorAdministradores.getInstancia().getAdmin().getNick()+">>");
sesion = true;
}else{
ManejadorMiembros.getInstancia().comprobarEstado(ManejadorMiembros.getInstancia().getMiembro());
if(ManejadorMiembros.getInstancia().getMiembro() != null){
ManejadorMiembros.getInstancia().volverCero();
System.out.print(ManejadorMiembros.getInstancia().getMiembro().getNick()+">>");
sesion = true;
}
}
if(sesion == true){
comandos = Ingresar.leerString();
if(comandos != null){
this.decodificar.separarComando(comandos);
}else{
System.out.println("Debes escribir algo");
}
}
}while(sesion == true);
} | 5 |
public ArrayList<Course> getUnfulfilledCourseRequests(HashMap<String, Course> cs) {
ArrayList<Course> unfulfilledRequests = new ArrayList<Course>();
for (String courseKey : taf.getProcessedCourses()) {
boolean unfulfilled = true;
Course course = cs.get(courseKey);
for (Course assigned : courses) {
if (course.equals(assigned)) {
unfulfilled = false;
}
}
if (unfulfilled) {
unfulfilledRequests.add(course);
}
}
return unfulfilledRequests;
/*
ArrayDeque<String> prefCourseNames = taf.GetPreferredCourseKeys();
ArrayList<Course> prefCourses = new ArrayList();
// add equivalent course objects to preferredList
while(!prefCourseNames.isEmpty() && prefCourseNames.peek() != null) {
prefCourses.add (cs.get(prefCourseNames.poll()));
}
// if the course already exists in the instructors courses (assigned)
// list, we remove it from our ArrayLists
for (Course c1 : prefCourses) {
for (Course c2 : courses) {
if (c1.equals(c2)) {
prefCourses.remove(c2);
}
}
}
return prefCourses;
* */
} | 4 |
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.