text stringlengths 14 410k | label int32 0 9 |
|---|---|
private ArrayList<ToDoItem> getItems(String cat) {
List list = data.getChildren();
ArrayList<ToDoItem> listOfItems = new ArrayList<>();
Iterator iter = list.iterator();
while (iter.hasNext()) {
Element e = (Element) iter.next();
if (cat.equals("") || cat.equals(e.getAttributeValue("category"))) {
int number = Integer.parseInt(e.getName().substring(1));
Priority prio = null;
switch (e.getAttributeValue("priority").toUpperCase()) {
case "LOW":
prio = Priority.LOW;
break;
case "MEDIUM":
prio = Priority.MEDIUM;
break;
case "HIGH":
prio = Priority.HIGH;
break;
}
int year = Integer.parseInt(e.getAttributeValue("year"));
int month = Integer.parseInt(e.getAttributeValue("month"));
int day = Integer.parseInt(e.getAttributeValue("day"));
int hour = Integer.parseInt(e.getAttributeValue("hour"));
int minute = Integer.parseInt(e.getAttributeValue("minute"));
GregorianCalendar cal = new GregorianCalendar(year, month, day,
hour, minute);
ToDoItem item = new ToDoItem(number, e.getAttributeValue("title"),
e.getAttributeValue("description"),
e.getAttributeValue("category"), prio, cal);
if (e.getAttributeValue("done").equals("true")) {
item.setDone(true);
} else {
item.setDone(false);
}
listOfItems.add(item);
}
}
return listOfItems;
} | 7 |
public double cos(int a){
//normalizing
if(a>360){
a %= 360;
}else if(a<0){
a %= 360;
a += 360;
}
//return
if(a <= 90){
return cos[a];
}else if(a <= 180){
return -cos[180 - a];
}else if(a <= 270){
return -cos[a - 180];
}else{
return cos[360 - a];
}
} | 5 |
private static List<String> parseSqls(List<Sql> sqls, boolean undo) {
List<String> result = new ArrayList<String>();
for (Sql sql : sqls) {
result.add(undo? sql.getUndoSql():sql.getDoSql());
}
if (undo) {
Collections.reverse(result);
}
return result;
} | 3 |
public NumberMessageShower(String message, IOnStringInput onStringInput) {
super(message,SYMBOL, onStringInput);
} | 0 |
public static String getWindowImg(String wnd, int pos) {
if (pos < 1)
pos = 1;
int imgPos = 0;
Widget root = UI.instance.root;
for (Widget wdg = root.child; wdg != null; wdg = wdg.next) {
if (wdg instanceof Window)
if (((Window) wdg).cap.text.equals(wnd))
for (Widget img = wdg.child; img != null; img = img.next)
if (img instanceof Img) {
Img i = (Img) img;
if (i != null) {
if (i.textureName.contains("/invsq")) continue;
imgPos++;
if (imgPos == pos) {
return i.textureName;
}
}
}
}
return "";
} | 9 |
private void consoleInput(){
if(KeyHandler.isPressed(KeyHandler.ESCAPE))
isConsoleDisplayed = false;
else
consolePrint = KeyHandler.keyPressed(KeyHandler.ANYKEY, consolePrint);
if(KeyHandler.isPressed(KeyHandler.ENTER))
consoleCommands(consolePrint);
} | 2 |
@Override
public void copySources( HashMap<String, Source> srcMap )
{
if( srcMap == null )
return;
Set<String> keys = srcMap.keySet();
Iterator<String> iter = keys.iterator();
String sourcename;
Source source;
// Make sure the buffer map exists:
if( bufferMap == null )
{
bufferMap = new HashMap<String, SoundBuffer>();
importantMessage( "Buffer Map was null in method 'copySources'" );
}
// remove any existing sources before starting:
sourceMap.clear();
SoundBuffer buffer;
// loop through and copy all the sources:
while( iter.hasNext() )
{
sourcename = iter.next();
source = srcMap.get( sourcename );
if( source != null )
{
buffer = null;
if( !source.toStream )
{
loadSound( source.filenameURL );
buffer = bufferMap.get( source.filenameURL.getFilename() );
}
if( !source.toStream && buffer != null )
{
buffer.trimData( maxClipSize );
}
if( source.toStream || buffer != null )
{
sourceMap.put( sourcename, new SourceJavaSound( listener,
source, buffer ) );
}
}
}
} | 9 |
public static void updateUtilisateur(Utilisateur utilisateur) {
PreparedStatement stat;
try {
stat = ConnexionDB.getConnection().prepareStatement("select * from utilisateur where id_utilisateur=?",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
stat.setInt(1, utilisateur.getId_utilisateur());
ResultSet res = stat.executeQuery();
if (res.next()) {
res.updateString("prenom", utilisateur.getPrenom());
res.updateString("nom", utilisateur.getNom());
res.updateString("dateNaissance", utilisateur.getDateNaissance());
res.updateString("adresse", utilisateur.getAdresse());
res.updateString("codePostal", utilisateur.getCodePostal());
res.updateString("ville", utilisateur.getVille());
res.updateString("carteBancaire", utilisateur.getCarteBancaire());
res.updateString("dateValiditeCarteBancaire", utilisateur.getDateValiditeCarteBancaire());
res.updateString("rib", utilisateur.getRib());
res.updateString("iban", utilisateur.getIban());
res.updateString("dateCreation", utilisateur.getDateCreation());
res.updateString("login", utilisateur.getLogin());
res.updateString("password", utilisateur.getPassword());
res.updateInt("fk_id_carte", utilisateur.getFk_id_carte());
if(utilisateur.getFk_id_velo()==-1){
res.updateNull("fk_id_velo");
}
else {
res.updateInt("fk_id_velo", utilisateur.getFk_id_velo());
}
res.updateRow();
}
} catch (SQLException e) {
while (e != null) {
System.out.println(e.getErrorCode());
System.out.println(e.getMessage());
System.out.println(e.getSQLState());
e.printStackTrace();
e = e.getNextException();
}
}
} | 4 |
@SuppressWarnings("unchecked")
public void saveMessage(HttpServletRequest request, String msg) {
List messages = (List) request.getSession().getAttribute(MESSAGES_KEY);
if (messages == null) {
messages = new ArrayList();
}
messages.add(msg);
request.getSession().setAttribute(MESSAGES_KEY, messages);
} | 1 |
public void setHasNegativeWeights(boolean hasNegativeWeights) {
this.hasNegativeWeights = hasNegativeWeights;
} | 0 |
private void calcRowSizes(int[] rows, int size, int iterations, int mod)
{
zeroArray(rows, size);
for(int index = 0; index < size; index++)
{
if(index == 0 || index == size -1)
{
rows[index] = iterations;
}
else
{
rows[index] = 2 * iterations;
}
}
for(int index = 0; index < size && mod > 0; index++, mod--)
{
rows[index] += 1;
}
if(mod > 0)
{
for(int index = size-2; index > 0 && mod > 0; index--, mod--)
{
rows[index] += 1;
}
}
} | 8 |
public static void setLogLevel(Level newLevel) {
PropertyTree.logger.setLevel(newLevel);
PropertyTree.consoleHandler.setLevel(newLevel);
} | 0 |
public PersonBean getPerson() {
return person;
} | 0 |
public static IProtocalInfo getProtocalInfoType(String name) {
if (name.equalsIgnoreCase(ProtocolType.EJB.name())) {
return new EJBProtocalInfo();
} else if (name.equalsIgnoreCase(ProtocolType.WEBSERVICE.name())) {
return new WebServiceProtocalInfo();
} else if (name.equalsIgnoreCase(ProtocolType.JMS.name())) {
return new JMSProtocalInfo();
} else if (name.equalsIgnoreCase(ProtocolType.IBMMQ.name())) {
return new IBMMQProtocalInfo();
} else if (name.equalsIgnoreCase(ProtocolType.ACTIVEMQ.name())) {
return new ACTIVEMQProtocalInfo();
} else if (name.equalsIgnoreCase(ProtocolType.RABBITMQ.name())) {
return new RABBITMQProtocalInfo();
} else if (name.equalsIgnoreCase(ProtocolType.FTP.name())) {
return new FTPProtocalInfo();
} else if (name.equalsIgnoreCase(ProtocolType.HESSIAN.name())) {
return new HessianProtocalInfo();
} else if (name.equalsIgnoreCase(ProtocolType.SOCKET.name())) {
return new SocketProtocalInfo();
}else {
logger.error("此协议不支持:" + name);
return null;
}
} | 9 |
public String getPopulationDetails(Field field)
{
StringBuffer buffer = new StringBuffer();
if(!countsValid) {
generateCounts(field);
}
for(Class key : counters.keySet()) {
Counter info = counters.get(key);
int stringLength = info.getName().length();
buffer.append(info.getName().substring(6,stringLength)); // show info
buffer.append(": ");
buffer.append(info.getCount());
buffer.append(' ');
}
return buffer.toString();
} | 2 |
public boolean equals(Object configuration) {
if (configuration == this)
return true;
try {
return super.equals(configuration)
&& myUnprocessedInput
.equals(((FSAConfiguration) configuration).myUnprocessedInput);
} catch (ClassCastException e) {
return false;
}
} | 3 |
public void setDesignacao(String designacao) {
this.designacao = designacao.isEmpty() ? "sem designação" : designacao;
} | 1 |
public void zoomIn(double mouseXCoord, double mouseYCoord)
{
zoomInConstant = 0.98;
if (visibleArea.getyLength() <= (quadTreeToDraw.getQuadTreeLength() / 5000))
{
return;
}
final double mouseMapXCoord = convertMouseXToMap(mouseXCoord);
final double mouseMapYCoord = convertMouseYToMap(mouseYCoord);
final double mouseLengthX = mouseMapXCoord - visibleArea.getxCoord();
final double mouseLengthY = mouseMapYCoord - visibleArea.getyCoord();
final double xPct = mouseLengthX / visibleArea.getxLength();
final double yPct = mouseLengthY / visibleArea.getyLength();
final double xZoomLength = visibleArea.getxLength() * zoomInConstant;
final double yZoomLength = visibleArea.getyLength() * zoomInConstant;
final double deltaXLength = visibleArea.getxLength() - xZoomLength;
final double deltaYLength = visibleArea.getyLength() - yZoomLength;
final double newStartX = visibleArea.getxCoord() + deltaXLength * xPct;
final double newStartY = visibleArea.getyCoord() + deltaYLength * yPct;
visibleArea.setCoord(newStartX, newStartY, xZoomLength, yZoomLength);
} | 1 |
public void host(int port) {
player1.setPos(4, HEIGHT / 2);
player2.setPos(WIDTH - 12, HEIGHT / 2);
hosting = true;
try {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(1000);
serverThread = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Socket socket = null;
try {
socket = serverSocket.accept();
} catch (SocketTimeoutException e) {
}
if (socket == null) {
continue;
}
packetLink = new NetworkPacketLink(Game.this, socket);
packetLink.setPacketListener(Game.this);
packetLink.sendPacket(new Packet1StartGame());
if (menu instanceof MenuWait) {
MenuWait menuWait = (MenuWait) menu;
menuWait.setStatus("Connected!", true);
}
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
serverThread.start();
} catch (IOException e) {
e.printStackTrace();
}
} | 6 |
public UrinalStatus occupyUrinalVO( final int urinalPositionToOccupy ) {
UrinalStatus status = urinalVOs.get( urinalPositionToOccupy ).getStatus();
if( status == UrinalStatus.OCCUPIED )
return UrinalStatus.OCCUPIED;
else if( status == UrinalStatus.TRAPPED )
return UrinalStatus.TRAPPED;
else {
urinalVOs.get( urinalPositionToOccupy ).setStatus( UrinalStatus.OCCUPIED );
if( urinalCount()>2 ) {
if( urinalPositionToOccupy == 0 || urinalPositionToOccupy == urinalCount()-1 ) {
disarmToiletsBetweenPosMinAndPosMax( 0, urinalCount()-1 );
} else {
if (urinalVOs.get( urinalPositionToOccupy-1 ).getStatus().equals( UrinalStatus.FREE_SAVE ))
urinalVOs.get( urinalPositionToOccupy-1 ).setStatus( UrinalStatus.TRAPPED );
if (urinalVOs.get( urinalPositionToOccupy+1 ).getStatus().equals( UrinalStatus.FREE_SAVE ))
urinalVOs.get( urinalPositionToOccupy+1 ).setStatus( UrinalStatus.TRAPPED );
disarmToiletsToTheLeft( urinalPositionToOccupy );
disArmToiletsToTheRight( urinalPositionToOccupy );
}
}
return UrinalStatus.FREE_SAVE;
}
} | 7 |
public static void copyTo(InputStream in, OutputStream out) throws IOException {
int c;
while ((c = in.read()) != -1)
out.write(c);
out.flush();
} | 1 |
public ArrayList<ArrayList<Card>> holeCardsCombinations() {
ArrayList<ArrayList<Card>> combinations = new ArrayList<ArrayList<Card>>();
for (int i = 0; i < cards.size(); i++) {
for (int j = i + 1; j < cards.size(); j++) {
ArrayList<Card> combination = new ArrayList<Card>();
combination.add(cards.get(i));
combination.add(cards.get(j));
combinations.add(combination);
}
}
return combinations;
} | 2 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
if (id != user.id) return false;
if (!email.equals(user.email)) return false;
if (!name.equals(user.name)) return false;
if (!password.equals(user.password)) return false;
if (!surname.equals(user.surname)) return false;
return true;
} | 7 |
public static Connection getConnection() {
try {
driver = PropertiesReader.getValue("driver");
url = PropertiesReader.getValue("url");
user = PropertiesReader.getValue("user");
pwd = PropertiesReader.getValue("pwd");
} catch (Exception e) {
// TODO: handle exception
}
try {
// load driver
Class.forName(driver);
// link to database
Connection conn = DriverManager.getConnection(url, user, pwd);
if (!conn.isClosed())
{
System.out.println("Succeeded connecting to the Database!");
return conn;
}else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
} | 3 |
public void handleAndSendReply(final BufferedInputStream in)
throws IOException {
// Peek at the reply id and tag.
in.mark(200);
final XMLInputFactory xif = XMLInputFactory.newInstance();
final String networkReplyId;
final boolean question;
try {
final XMLStreamReader xmlIn = xif.createXMLStreamReader(in);
xmlIn.nextTag();
networkReplyId = xmlIn.getAttributeValue(null, "networkReplyId");
question = xmlIn.getLocalName().equals("question");
xmlIn.close();
} catch (XMLStreamException xme) {
logger.log(Level.WARNING, "XML stream failure", xme);
return;
}
// Reset and build a message.
final DOMMessage msg;
in.reset();
try {
msg = new DOMMessage(in);
} catch (SAXException e) {
logger.log(Level.WARNING, "Unable to read message.", e);
return;
}
// Process the message in its own thread.
final Connection conn = this;
Thread t = new Thread(msg.getType()) {
@Override
public void run() {
Element reply, element = msg.getDocument()
.getDocumentElement();
try {
if (question) {
reply = messageHandler.handle(conn,
(Element)element.getFirstChild());
if (reply == null) {
reply = DOMMessage.createMessage("reply",
"networkReplyId", networkReplyId);
} else {
Element header = reply.getOwnerDocument()
.createElement("reply");
header.setAttribute("networkReplyId",
networkReplyId);
header.appendChild(reply);
reply = header;
}
} else {
reply = messageHandler.handle(conn, element);
}
if (reply != null) conn.sendDumping(reply);
} catch (Exception e) {
logger.log(Level.WARNING, "Handler failed: "
+ element.toString(), e);
}
}
};
t.setName(name + "-MessageHandler-" + t.getName());
t.start();
} | 6 |
public static void main(String[] args) {
System.err.println("INDI for Java Basic Server initializing...");
int port = 7624;
for (int i = 0 ; i < args.length ; i++) {
String[] s = splitArgument(args[i]);
if (s[0].equals("-p")) {
try {
port = Integer.parseInt(s[1]);
} catch (NumberFormatException e) {
System.err.println("Incorrect port number");
printArgumentHelp();
System.exit(-1);
}
}
}
server = new INDIBasicServer(port);
// Parse arguments
for (int i = 0 ; i < args.length ; i++) {
boolean correct = parseArgument(args[i]);
if (!correct) {
System.err.println("Argument '" + args[i] + "' not correct. Use -help for help. Exiting.");
System.exit(-1);
}
}
System.err.println("Type 'help' for help.");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
try {
while (true) {
line = in.readLine();
line = line.trim();
if (line.length() > 0) {
parseInputLine(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
} | 8 |
@Override
public void run()
{
try
{
this.init();
this.isRunning = true;
while(this.isRunning)
{
this.currentTime = System.currentTimeMillis();
if(this.currentTime-this.lastClockTime >= 1000L)
{
this.applet.showStatus("UPS: "+this.cups+" RPS: "+this.crps);
this.ups = this.cups;
this.rps = this.crps;
this.cups = 0;
this.crps = 0;
this.lastClockTime = this.currentTime;
}
this.partialTick = (this.currentTime-this.lastUpdateTime)*this.requestedUPS/1000F;
if(this.partialTick >= 1F)
{
this.lastUpdateTime = this.currentTime;
this.update();
this.cups++;
this.partialTick = 0F;
}
if(this.currentGui != null)
this.partialTick = 0F;
this.render();
this.crps++;
}
destroy(this); // this method called by Tamas Tegzes
System.exit(0);
}
catch(Exception e)
{
Graphics g = this.getGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.red);
g.setFont(new Font("SansSerif", Font.PLAIN, 40));
RenderingHelper.drawCenteredString(g, this.getWidth()/2, this.getHeight()/2-30, "Something bad happened! :(");
RenderingHelper.drawCenteredString(g, this.getWidth()/2, this.getHeight()/2+30, "Try to reload this page!");
e.printStackTrace();
}
} | 5 |
public void update() {
KeyboardAdapter kba = KeyboardAdapter.getInstance();
int dx = 0;
int dy = 0;
if (kba.isPressed(KeyboardAdapter.KEY_NAME.UP)) {
dy -= speed;
}
if (kba.isPressed(KeyboardAdapter.KEY_NAME.DOWN)) {
dy += speed;
}
if (kba.isPressed(KeyboardAdapter.KEY_NAME.LEFT)) {
dx -= speed;
}
if (kba.isPressed(KeyboardAdapter.KEY_NAME.RIGHT)) {
dx += speed;
}
if (kba.isPressed(KeyboardAdapter.KEY_NAME.CONFIRM) &&
player.hasMule() && location == 2) {
int r = y/1000;
int c = x/1000;
Tile tile = map.getTileAt(r, c);
//if the player tries to place the MULE on an empty tile they own, it succeeds
if (tile.getOwner() == player && !tile.hasMule()) {
tile.setMule(player.getMule());
player.removeMule();
}
else {
player.removeMule();
}
}
x += dx;
y += dy;
correctSpritePosition();
location = calculateLocation();
} | 9 |
public static File renameFile(String srcFile, String destFile)
{
if (StringUtils.isBlank(srcFile) || StringUtils.isBlank(destFile))
{
return null;
}
File oldfile = new File(srcFile);
File newfile = new File(destFile);
if (oldfile.renameTo(newfile))
{
return newfile;
}
return null;
} | 3 |
private ArrayList<Models.DatabaseModel.Bill> findUserBill(int patientId, boolean outStanding) {
String query = "SELECT `bill`.`billId`, "
+ " `bill`.`patientId`, "
+ " `bill`.`dateCreated`, "
+ " `bill`.`datePaid`, "
+ " `bill`.`consultationCost` "
+ " FROM `bill` "
+ " WHERE `bill`.`patientId` = '%d'";
if (outStanding) {
query += " AND `bill`.`datePaid` IS NULL;";
} else {
query += " AND `bill`.`datePaid` IS NOT NULL;";
}
DBA dba = Helper.getDBA();
ArrayList<Models.DatabaseModel.Bill> listOfBills = new ArrayList<>();
try {
ResultSet rs = dba.executeQuery(String.format(query, patientId));
if (rs != null) {
while (rs.next()) {
Models.DatabaseModel.Bill newBill = new Models.DatabaseModel.Bill();
newBill.setId(rs.getInt("billId"));
newBill.setPatientId(rs.getInt("patientId"));
newBill.setDateCreated(rs.getTimestamp("dateCreated"));
newBill.setDatePaid(rs.getTimestamp("datePaid"));
newBill.setConsultationCost(rs.getInt("consultationCost"));
listOfBills.add(newBill);
}
rs.close();
}
dba.closeConnections();
} catch (SQLException sqlEx) {
dba.closeConnections();
Helper.logException(sqlEx);
}
return listOfBills;
} | 4 |
* @param client
*/
private void cmd_set(final String arg, final Client client) {
final Player player = getPlayer(client);
final Room room = getRoom(player.getLocation());
MUDObject mobj;
// ex. @set here=header:======================
debug("SET: " + arg);
String[] args = arg.split("=", 2);
// if there is a property to be set or removed
if (args.length > 1) {
final String target = args[0];
final String other = args[1];
debug("SET (target): " + target);
debug("SET (other): " + other);
// get the property and it's value from the arguments
final String[] temp = Utils.trim(other).split(":", 2);
// if we have a separate key and value to set
if (temp.length == 2) {
final String key = Utils.trim(temp[0]);
final String value = Utils.trim(temp[1]);
debug("SET (property): " + key);
debug("SET (value): " + value);
// get the object
switch(target) {
case "me": mobj = player; break;
case "here": mobj = room; break;
default: mobj = getObject(target); break;
}
debug("MOBJ IS NULL? " + (mobj == null));
// if the object isn't null and is neart the player, modify it's properties
if (mobj != null) {
int dbref = mobj.getDBRef();
int location = mobj.getLocation();
debug("Object Loc: " + location);
debug("");
debug("Player DBRef: " + player.getDBRef());
debug("Player Loc: " + player.getLocation());
boolean roomItself = (dbref == player.getLocation());
boolean sameRoom = (location == player.getLocation());
boolean holding = (location == player.getDBRef());
if( roomItself || holding || sameRoom ) {
if ( !value.equals("") ) {
mobj.setProperty(key, value);
send("Property \'" + key + "\' with value of \'" + value + "\' set on " + mobj.getName(), client);
}
else {
mobj.getProperties().remove(key);
send("Property \'" + key + "\' removed from " + mobj.getName(), client);
}
}
}
}
else {
send("SET: Invalid key-value pair!", client);
}
}
else {
send("SET: No property specified!", client);
}
} | 9 |
public void stacksum(String[] split)// prints the total from each person of
// a person's stack
{
if (split.length != 2)
{
PrintMessage("Syntax:!score [player]");
return;
}
Player p = (Player) getPlayer(split[1]);
if (p == null)
{
PrintMessage(split[1] + " does not exist");
return;
}
for (String name : everyone.keySet())
{
int temp = 0;
for (Moneys m : p.money)
{
if (m.owner.equals(name))
temp += m.amount;
}
if (temp > 0)
PrintMessage(name + ": " + temp);
}
} | 6 |
public void pop() throws NotExistException {
if (amount != 0) {
head = head.next;
} else {
throw new NotExistException("Stack is empty!");
}
} | 1 |
public static String countAndSay(int n) {
if (0 >= n) return "";
if (1 == n) return "1";
String str = "1";
for (int i = 0; i < n - 1; i++) {
int num = 1;
StringBuffer temp = new StringBuffer();
for (int j = 0; j < str.length(); j++) {
if (0 == j) {
if (str.length() > 1) continue;
} else if (str.charAt(j) == str.charAt(j - 1)) {
num = num + 1;
} else {
temp.append(num);
temp.append(str.charAt(j - 1));
num = 1;
}
if (j == str.length() - 1) {
temp.append(num);
temp.append(str.charAt(j));
}
}
str = temp.toString();
}
return str;
} | 8 |
private void saveSettings() {
String[] resolution = ((String) view.getCmbResolution().getSelectedItem()).split("x");
if (resolution.length == 2) {
settings.setWidth(Integer.parseInt(resolution[0]));
settings.setHeight(Integer.parseInt(resolution[1]));
} else {
log.fine("Bad resolution format, reverting to previously saved");
view.getCmbResolution().setSelectedItem(settings.getWidth() + "x" + settings.getHeight());
}
String framerate = (String) view.getCmbFramerate().getSelectedItem();
settings.setFramerate(Integer.parseInt(framerate));
settings.setHud(Key.Hud.getAllowedValues().get(view.getCmbHud().getSelectedIndex()));
settings.setViewmodelSwitch(Key.ViewmodelSwitch.getAllowedValues().get(
view.getCmbViewmodel().getSelectedIndex()));
settings.setViewmodelFov((int) view.getSpinnerViewmodelFov().getValue());
settings
.setDxlevel(Key.DxLevel.getAllowedValues().get(view.getCmbQuality().getSelectedIndex()));
settings.setMotionBlur(view.getEnableMotionBlur().isSelected());
settings.setCombattext(!view.getDisableCombatText().isSelected());
settings.setCrosshair(!view.getDisableCrosshair().isSelected());
settings.setCrosshairSwitch(!view.getDisableCrosshairSwitch().isSelected());
settings.setHitsounds(!view.getDisableHitSounds().isSelected());
settings.setVoice(!view.getDisableVoiceChat().isSelected());
settings.setSkybox((String) view.getCmbSkybox().getSelectedItem());
Path tfpath = settings.getTfPath();
List<String> selected = new ArrayList<>();
for (CustomPath cp : customPaths.getList()) {
Path path = cp.getPath();
if (!cp.getContents().contains(PathContents.READONLY) && cp.isSelected()) {
String key = (path.startsWith(tfpath) ? "tf*" : "");
key += path.getFileName().toString();
selected.add(key);
}
}
settings.setCustomResources(selected);
settings.setHudMinmode(view.getUseHudMinmode().isSelected());
settings
.setBoolean(Key.DeleteBackupsWhenRestoring, view.getChckbxmntmBackupMode().isSelected());
settings.setBoolean(Key.InstallFonts, view.getInstallFonts().isSelected());
settings.setBoolean(Key.CopyUserConfig, view.getCopyUserConfig().isSelected());
if (view.getSourceLaunch().isSelected()) {
settings.setString(Key.LaunchMode, "hl2");
} else if (view.getSteamLaunch().isSelected()) {
settings.setString(Key.LaunchMode, "steam");
} else if (view.getHlaeLaunch().isSelected()) {
settings.setString(Key.LaunchMode, "hlae");
}
settings.setHudPlayerModel(view.getUsePlayerModel().isSelected());
settings.setString(Key.SourceRecorderVideoFormat, view.getCmbSourceVideoFormat()
.getSelectedItem().toString().toLowerCase());
settings.setInt(Key.SourceRecorderJpegQuality, (int) view.getSpinnerJpegQuality().getValue());
if (customSettings != null) {
settings.setCustomSettings(customSettings.getTextArea().getText());
settings.setInt(Key.CustomSettingsDialogWidth, customSettings.getWidth());
settings.setInt(Key.CustomSettingsDialogHeight, customSettings.getHeight());
}
settings.save();
log.fine("Settings saved");
} | 9 |
public int writeVarLong (long value, boolean optimizePositive) throws KryoException {
if (!optimizePositive) value = (value << 1) ^ (value >> 63);
int varInt = 0;
varInt = (int)(value & 0x7F);
value >>>= 7;
if (value == 0) {
writeByte(varInt);
return 1;
}
varInt |= 0x80;
varInt |= ((value & 0x7F) << 8);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeInt(varInt);
niobuffer.order(byteOrder);
position -= 2;
niobuffer.position(position);
return 2;
}
varInt |= (0x80 << 8);
varInt |= ((value & 0x7F) << 16);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeInt(varInt);
niobuffer.order(byteOrder);
position -= 1;
niobuffer.position(position);
return 3;
}
varInt |= (0x80 << 16);
varInt |= ((value & 0x7F) << 24);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeInt(varInt);
niobuffer.order(byteOrder);
position -= 0;
return 4;
}
varInt |= (0x80 << 24);
long varLong = (varInt & 0xFFFFFFFFL);
varLong |= (((long)(value & 0x7F)) << 32);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeLong(varLong);
niobuffer.order(byteOrder);
position -= 3;
niobuffer.position(position);
return 5;
}
varLong |= (0x80L << 32);
varLong |= (((long)(value & 0x7F)) << 40);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeLong(varLong);
niobuffer.order(byteOrder);
position -= 2;
niobuffer.position(position);
return 6;
}
varLong |= (0x80L << 40);
varLong |= (((long)(value & 0x7F)) << 48);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeLong(varLong);
niobuffer.order(byteOrder);
position -= 1;
niobuffer.position(position);
return 7;
}
varLong |= (0x80L << 48);
varLong |= (((long)(value & 0x7F)) << 56);
value >>>= 7;
if (value == 0) {
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeLong(varLong);
niobuffer.order(byteOrder);
return 8;
}
varLong |= (0x80L << 56);
niobuffer.order(ByteOrder.LITTLE_ENDIAN);
writeLong(varLong);
niobuffer.order(byteOrder);
write((byte)(value));
return 9;
} | 9 |
public static <T extends DC> Set<Set<Pair<Pair<PT<Integer>,T>,Pair<PT<Integer>,T>>>> despatch(Pair<Pair<PT<Integer>,T>,Pair<PT<Integer>,T>> pair,
Set<Set<Pair<Pair<PT<Integer>,T>,Pair<PT<Integer>,T>>>> sets)
{ if(pair==null)
{ return sets;
}
else
{ if(sets==null)
{ return new Set(new Set(pair,null),null);
}
else//pair!=null && sets!=null
{ if(sets.getNext()==null)
{ return new Set(sets.getFst().ins(pair),null);
}
else
{ return new Set(sets.getFst().ins(pair),despatch(pair,sets.getNext()));
}
}
}
} | 3 |
@Override
public void setCivilState(String civilState) {
super.setCivilState(civilState);
}; | 0 |
private void drawCollection(Graphics2D g, Object collection, Class cls) {
ModelEntityAdapter adapter = modelAdapters.get(cls);
if (adapter == null) return;
if (collection instanceof Map) {
Map map = (Map)collection;
for (Object key: map.keySet()) {
Object obj = map.get(key);
ModelEntity en = (ModelEntity)obj;
if (!isObjectActive(en)) adapter.drawEntity(g, en, false);
}
}
else if (collection instanceof java.util.List) {
java.util.List list = (java.util.List)collection;
for (Object obj: list) {
ModelEntity en = (ModelEntity)obj;
if (!isObjectActive(en)) adapter.drawEntity(g, en, false);
}
}
for (ModelEntity en: activeObjects) {
if (cls.isInstance(en)) adapter.drawEntity(g, en, true);
}
} | 9 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Uitlening)) {
return false;
}
Uitlening other = (Uitlening) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} | 5 |
public String toString() {
boolean test = false;
if (test || m_test) {
System.out.println("Coordinate :: toString() BEGIN");
}
if (test || m_test) {
System.out.println("Coordinate :: toString() END");
}
return "Coordinate(" + m_X + ", " + m_Y + ", " + m_Value + ")";
} | 4 |
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._var_ == oldChild)
{
setVar((PVar) newChild);
return;
}
if(this._aDe_ == oldChild)
{
setADe((TNumeroInt) newChild);
return;
}
if(this._aAte_ == oldChild)
{
setAAte((TNumeroInt) newChild);
return;
}
for(ListIterator<PComando> i = this._comando_.listIterator(); i.hasNext();)
{
if(i.next() == oldChild)
{
if(newChild != null)
{
i.set((PComando) newChild);
newChild.parent(this);
oldChild.parent(null);
return;
}
i.remove();
oldChild.parent(null);
return;
}
}
throw new RuntimeException("Not a child.");
} | 6 |
public String compareFiles(String filenameOK, String filenameOUT) throws FileNotFoundException {
Scanner sOK = new Scanner(new File(filenameOK));
Scanner sOUT = new Scanner(new File(filenameOUT));
while (sOUT.hasNext()) {
String s1 = sOK.nextLine();
String s2 = sOUT.nextLine();
if (!s2.contains(s1)) {
System.out.println(s2 + " " + s1);
return "Invalid output";
}
}
return "Valid output";
} | 2 |
private final boolean cvc(int i)
{ if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false;
{ int ch = b[i];
if (ch == 'w' || ch == 'x' || ch == 'y') return false;
}
return true;
} | 7 |
public boolean existeStation(Station s){
if(s == null) return false;
for(Station st : stations){
if(st != null) {
if(st.getNom().equals(s.getNom())){
return true;
}
}
}
return false;
} | 4 |
public String getTypeName() {
return this.typeName;
} | 0 |
public boolean validationCategory (String chargeCategory) {
Statement statement = null;
try {
statement = connection.createStatement();
statement.execute("select category from categories");
ResultSet set = statement.getResultSet();
while(set.next()){
String cat = set.getString("category");
if (cat.equals(chargeCategory)) {
return true;
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
System.out.println("Выбрана неверная категория затрат");
return false;
} | 5 |
void setExampleWidgetBackgroundImage () {
if (backgroundImageButton != null && backgroundImageButton.isDisposed()) return;
Control [] controls = getExampleControls ();
for (int i=0; i<controls.length; i++) {
controls [i].setBackgroundImage (backgroundImageButton.getSelection () ? instance.images[ControlExample.ciBackground] : null);
}
} | 4 |
@After
public void tearDown() {
} | 0 |
public void generate(Shell parentShell, IType objectClass) {
IMethod existingEquals = objectClass.getMethod("equals",
new String[] { "QObject;" });
IMethod existingHashCode = objectClass.getMethod("hashCode",
new String[0]);
Set excludedMethods = new HashSet();
if (existingEquals.exists()) {
excludedMethods.add(existingEquals);
}
if (existingHashCode.exists()) {
excludedMethods.add(existingHashCode);
}
try {
IField[] fields;
if (PreferenceUtils.getDisplayFieldsOfSuperclasses()) {
fields = JavaUtils
.getNonStaticNonCacheFieldsAndAccessibleNonStaticFieldsOfSuperclasses(objectClass);
} else {
fields = JavaUtils.getNonStaticNonCacheFields(objectClass);
}
boolean disableAppendSuper = JavaUtils
.isDirectSubclassOfObject(objectClass)
|| !JavaUtils.isEqualsOverriddenInSuperclass(objectClass)
|| !JavaUtils.isHashCodeOverriddenInSuperclass(objectClass);
EqualsHashCodeDialog dialog = new EqualsHashCodeDialog(parentShell,
"Generate Equals and HashCode", objectClass, fields,
excludedMethods, disableAppendSuper);
int returnCode = dialog.open();
if (returnCode == Window.OK) {
if (existingEquals.exists()) {
existingEquals.delete(true, null);
}
if (existingHashCode.exists()) {
existingHashCode.delete(true, null);
}
IField[] checkedFields = dialog.getCheckedFields();
IJavaElement insertPosition = dialog.getElementPosition();
boolean appendSuper = dialog.getAppendSuper();
boolean generateComment = dialog.getGenerateComment();
boolean compareReferences = dialog.getCompareReferences();
boolean useGettersInsteadOfFields = dialog.getUseGettersInsteadOfFields();
IInitMultNumbers imNumbers = dialog.getInitMultNumbers();
IJavaElement created = generateHashCode(parentShell,
objectClass, checkedFields, insertPosition,
appendSuper, generateComment, imNumbers,
useGettersInsteadOfFields);
created = generateEquals(parentShell, objectClass,
checkedFields, created, appendSuper, generateComment,
compareReferences, useGettersInsteadOfFields);
ICompilationUnit cu = objectClass.getCompilationUnit();
IEditorPart javaEditor = JavaUI.openInEditor(cu);
JavaUI.revealInEditor(javaEditor, (IJavaElement) created);
}
} catch (CoreException e) {
MessageDialog.openError(parentShell, "Method Generation Failed", e
.getMessage());
}
} | 9 |
public static String reverseWords(String s) {
List<String> words = new ArrayList<String>();
int len = s.length();
StringBuffer res = new StringBuffer();
String word = null;
int begin = 0, end = 0;
for (int i = 0; i < len; i++) {
if (' ' == s.charAt(i)) {
if (end != begin) {
word = s.substring(begin, end);
words.add(word);
end = end + 1;
begin = end;
} else {
end = i + 1;
begin = end;
}
} else {
end = i + 1;
}
}
if (begin != end) {
words.add(s.substring(begin, end));
}
for (int i = words.size() - 1; i >= 0; i--) {
res.append(words.get(i));
if (i != 0) res.append(" ");
}
return res.toString();
} | 6 |
public static Set smallerSymbols(Grammar grammar) {
Set smaller = new HashSet();
Production[] prods = grammar.getProductions();
boolean added;
do {
added = false;
for (int i = 0; i < prods.length; i++) {
String left = prods[i].getLHS();
String right = prods[i].getRHS();
int rightLength = minimumLength(right, smaller);
int leftLength = minimumLength(left, smaller);
if (leftLength > rightLength) {
for (int j = 0; j < left.length(); j++) {
String symbol = left.substring(j, j + 1);
char s = symbol.charAt(0);
if (smaller.contains(symbol))
continue;
if (count(left, s) <= count(right, s))
continue;
smaller.add(symbol);
added = true;
}
}
}
} while (added);
return smaller;
} | 6 |
public BuscarItem() {
setLayout(new GridLayout(2,2));
aceptarBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Inventario.setStatusBarText("Se dispone a buscar una cadena!!!");
IServidorInventario servidor = ConexionServidor.getServidor();
String buscar = buscarFdl.getText();
String cadena;
int iguales = 0;
int contenidas = 0;
int fila = 0;
int columna = 0;
try {
Vector productos = servidor.getAllItems(ConexionServidor.getIdentificadorUnico(), Inventario.getOrdenamientoDatos());
for(int i=0; i < productos.size(); i++) {
Vector detalles = (Vector) productos.elementAt(i);
for(int j=0; j < detalles.size(); j++) {
cadena = (String) detalles.elementAt(j);
cadena += "";
if(cadena.equalsIgnoreCase(buscar)){
iguales++;
if(fila == 0 && columna == 0){
fila = i;
columna = j;
}
}
else if(cadena.contains(buscar))
contenidas++;
}
}
} catch (RemoteException e1) {
e1.printStackTrace();
}
dispose();
MainPanelBuilder.setSeleccion(fila, columna);
JOptionPane.showMessageDialog(null,
"Cadenas iguales: "+iguales+"\n" +
"Cadenas contenidas: "+contenidas,
"Resultados de la busqueda",
JOptionPane.INFORMATION_MESSAGE);
}
});
cancelarBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Inventario.setStatusBarText("Accion Cancelada!!!");
dispose();
}
});
add(buscarLbl);
add(buscarFdl);
add(aceptarBtn);
add(cancelarBtn);
buscarFdl.addKeyListener(this);
if(ConexionServidor.estaConectado()) {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setSize(250,80);
setTitle("Buscar una cadena");
setLocation(Toolkit.getDefaultToolkit().getScreenSize().width/2-125, Toolkit.getDefaultToolkit().getScreenSize().height/2-40);
setResizable(false);
setModal(true);
setAlwaysOnTop(true);
setVisible(true);
}
else {
Inventario.setStatusBarText("No esta conectado al servidor!!!");
dispose();
}
} | 8 |
public int minCut(String s) {
int n = s.length();
int[] part = new int[n];
boolean[][] isPalindrome = new boolean[n][n];
//j as start index, i + 1 as length
for(int i = 0; i < n; i++) {
for(int j = 0; j < n - i; j++) {
if(i < 1)
isPalindrome[j][i] = true;
else
isPalindrome[j][i] = (s.charAt(j) == s.charAt(j + i) && isPalindrome[j + 1][i - 2]);
}
}
//j as start index, i + 1 as length
for(int i = 0; i < n; i++) {
part[i] = Integer.MAX_VALUE;
if(isPalindrome[0][i]) {
part[i] = 1;
}
for(int j = i; j >= 0; j--) {
if(j > 0 && isPalindrome[j][i - j]) {
part[i] = Math.min(part[i], part[j - 1] + 1);
}
}
}
return part[n - 1] - 1;
} | 9 |
private static void game() {
while (continueGame) {
listElements(); //Prints out the elements you have
String element1 = GuiMaster.getEnteredText();//inputs first element
if(elementValidize(element1)){ //checks first and second
String element2 = GuiMaster.getEnteredText();; //inputs second element
if(elementValidize(element2)){
int newElementInt = findNewElement(element1, element2);//finds new element's int
if(newElementInt != -1){
String newElement = elementString(newElementInt); //converts new element's int to string
if(!checkElementDiscovered(newElement)){ //Check valid checks if it's been discovered. If it has been
//then make it discovered.
elementsDiscovered[elementsNotNull(elementsDiscovered)] = newElementInt;
}
GuiMaster.println(element1 + " + " + element2 + " = " + newElement);
GuiMaster.println("The elements you have discovered are, \n");
}
}
}
}
} | 5 |
public void upgradePawn(Point location, Piece newPiece)
{
if(!this.isOnBoard(location))
{
throw new AssertionError("This location: "+location+"isn't on the board");
}
if(!(newPiece instanceof Queen ||newPiece instanceof Rook ||newPiece instanceof Bishop||newPiece instanceof Knight))//if it isn't a queen, rook, bishop or knight, we can't upgrade it
{
throw new AssertionError("A pawn can't be upgraded to a"+newPiece.getClass().toString());
}
if(!(this.getPiece(location)instanceof Pawn))//we can't upgrade something that isn't a pawn
{
throw new AssertionError("You can't upgrade a "+ newPiece.getClass().toString());
}
newPiece.setLocation(location);
theGrid[location.x][location.y]=newPiece;
} | 6 |
public boolean isOccupied(int x, int y){
for (int i = 0; i < mobs.size(); i++){
int occupiedX = mobs.get(i).getX();
int occupiedY = mobs.get(i).getY();
if (x == occupiedX && y == occupiedY){
return true;
}
}
return false;
} | 3 |
@EventHandler
public void registerEconomyPlayer(PlayerJoinEvent event) {
Player player = event.getPlayer();
User user = EdgeCoreAPI.userAPI().getUser(player.getName());
if (user == null)
return;
try {
if (economy.existsEconomyPlayer(player.getName()))
return;
economy.registerEconomyPlayer(user.getUUID());
player.sendMessage(lang.getColoredMessage(user.getLanguage(), "registration_eco_success"));
} catch(Exception e) {
e.printStackTrace();
player.sendMessage(lang.getColoredMessage(user.getLanguage(), "globalerror"));
}
} | 3 |
private boolean isNumberStart() {
if (isEof()) {
return false;
}
int[] c = peek3();
if (isDigit(c[0]) || (c[0] == '.' && isDigit(c[1]))) {
return true;
}
if (c[0] == '+' || c[0] == '-') {
if (isDigit(c[1])) {
return true;
}
if (c[1] == '.' && isDigit(c[2])) {
return true;
}
}
return false;
} | 9 |
public static double incrementPrice(double price) {
double newPrice;
if (price >= 100.0) {
newPrice = price + 10.0;
} else if (price >= 50.0) {
newPrice = price + 5.0;
} else if (price >= 30.0) {
newPrice = price + 2.0;
} else if (price >= 20.0) {
newPrice = price + 1.0;
} else if (price >= 10.0) {
newPrice = price + 0.5;
} else if (price >= 6.0) {
newPrice = price + 0.2;
} else if (price >= 4.0) {
newPrice = price + 0.1;
} else if (price >= 3.0) {
newPrice = price + 0.05;
} else if (price >= 2.0) {
newPrice = price + 0.02;
} else {
newPrice = price + 0.01;
}
newPrice = Double.parseDouble(formatPrice(newPrice));
return newPrice;
} | 9 |
public static void main(String[] args) {
String input;
System.out.println("Enter the string ");
Scanner scan = new Scanner(System.in);
input = scan.nextLine();
System.out.println("Reversed word : " + reverseWord(input));
} | 0 |
protected void loadFields(com.sforce.ws.parser.XmlInputStream __in,
com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException {
super.loadFields(__in, __typeMapper);
__in.peekTag();
if (__typeMapper.isElement(__in, CreatedBy__typeInfo)) {
setCreatedBy((com.sforce.soap.enterprise.sobject.Name)__typeMapper.readObject(__in, CreatedBy__typeInfo, com.sforce.soap.enterprise.sobject.Name.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, CreatedById__typeInfo)) {
setCreatedById(__typeMapper.readString(__in, CreatedById__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, CreatedDate__typeInfo)) {
setCreatedDate((java.util.Calendar)__typeMapper.readObject(__in, CreatedDate__typeInfo, java.util.Calendar.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, Entitlement__typeInfo)) {
setEntitlement((com.sforce.soap.enterprise.sobject.Entitlement)__typeMapper.readObject(__in, Entitlement__typeInfo, com.sforce.soap.enterprise.sobject.Entitlement.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, EntitlementId__typeInfo)) {
setEntitlementId(__typeMapper.readString(__in, EntitlementId__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, Field__typeInfo)) {
setField(__typeMapper.readString(__in, Field__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, IsDeleted__typeInfo)) {
setIsDeleted((java.lang.Boolean)__typeMapper.readObject(__in, IsDeleted__typeInfo, java.lang.Boolean.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, NewValue__typeInfo)) {
setNewValue((java.lang.Object)__typeMapper.readObject(__in, NewValue__typeInfo, java.lang.Object.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, OldValue__typeInfo)) {
setOldValue((java.lang.Object)__typeMapper.readObject(__in, OldValue__typeInfo, java.lang.Object.class));
}
} | 9 |
private void detectEnd(){
if(LogController.getConsumedLogs() >= endNum){
threadFlag = false;
}
} | 1 |
public Double convert(Object object,Double defultValue,Object... args) throws HeraException{
if(object instanceof Integer){
return new IntegerDoubleConverter().convert((Integer)object, defultValue, args);
} else if(object instanceof Long){
return new LongDoubleConverter().convert((Long)object, defultValue, args);
} else {
try{
return Double.valueOf(object.toString());
}catch (Exception e) {
if(defultValue!=null){
return defultValue;
}else{
throw new HeraException("Object to Ingeger 转化错误 :"+e.getMessage() );
}
}
}
} | 4 |
protected void printParameter(String parentParameterFile,
String childParameterFile, ArrayList<_Doc> docList) {
System.out.println("printing parameter");
try {
System.out.println(parentParameterFile);
System.out.println(childParameterFile);
PrintWriter parentParaOut = new PrintWriter(new File(
parentParameterFile));
PrintWriter childParaOut = new PrintWriter(new File(
childParameterFile));
for (_Doc d : docList) {
if (d instanceof _ParentDoc) {
parentParaOut.print(d.getName() + "\t");
parentParaOut.print("topicProportion\t");
for (int k = 0; k < number_of_topics; k++) {
parentParaOut.print(d.m_topics[k] + "\t");
}
parentParaOut.println();
for (_ChildDoc cDoc : ((_ParentDoc) d).m_childDocs) {
childParaOut.print(cDoc.getName() + "\t");
childParaOut.print("topicProportion\t");
for (int k = 0; k < number_of_topics; k++) {
childParaOut.print(cDoc.m_topics[k] + "\t");
}
childParaOut.println();
}
}
}
parentParaOut.flush();
parentParaOut.close();
childParaOut.flush();
childParaOut.close();
} catch (Exception e) {
e.printStackTrace();
}
} | 6 |
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof javax.swing.Icon) value = new JLabel((Icon) value);
if (value instanceof ZoomButtons) value=new DropButton((ZoomButtons)value);
((JComponent)value).setOpaque(true);
if ((value instanceof JSlider)){
//On linux the slider component does not function correctly so do not display it
if (!Settings.isWindows())
return new JPanel();
sliderHasFocus=isSelected;
}
if(isSelected){//Alt text?
selectedIndex = index;
}
return (JComponent)value;
}
}
class ZoomEditor extends BasicComboBoxEditor{//implements ComboBoxEditor{//
static final BufferedImage img =SysIcon.ZoomToX.getBufferedImage(1, BufferedImage.TYPE_INT_ARGB);
ZoomBar parent;
GUI mainGUI;
ZoomEditor(GUI gui,ZoomBar parnt){
super();
parent=parnt;
mainGUI=gui;
}
public void update(){
setItem(null);
}
public void makeFocusable(){
editor.setFocusable(true);
}
boolean focusWasLocked(){
return !editor.isFocusable();
}
void dispatchMouse(MouseEvent e){
editor.dispatchEvent(e);
}
@Override
public JTextField createEditorComponent() {
editor = new JTextField("",4){
@Override
public void paint(Graphics g){
super.paint(g);
float trans = 0.15f;
float[] scale = {trans,trans,trans,trans};
RescaleOp op = new RescaleOp(scale,(new float[4]),null);
Graphics2D g2 = ((Graphics2D)g);
g2.drawImage(img,op, (getWidth()/2)-(img.getWidth()/2), 0);
}
};
editor.setHorizontalAlignment(JTextField.CENTER);
editor.setBorder(null);
return editor;
}
@Override
public void setItem(Object anObject){
String setText="Zoom: Fit";
int sliderVal =parent.zoomSlider.getValue();
if(sliderVal>=300) sliderVal = Math.max(300,(int)(mainGUI.mainPanel.getZoomMult()*100));
if (sliderVal!=0) setText=Integer.toString(sliderVal)+"%";
editor.setText(setText);
editor.setFocusable(false);
}
@Override
public Object getItem(){
parent.zoomSlider.setValueIsAdjusting(true);
String editorText = editor.getText();
int newVal =0;
if(editorText!=null){
if(editorText.toLowerCase().endsWith("fit")) parent.zoomSlider.setValue(0);
else{
StringBuffer numbers = new StringBuffer();
char c;
for (int i=0;i<editorText.length();i++) {
c = editorText.charAt(i);
if (Character.isDigit(c)) {
numbers.append(c);
}
}
try{
newVal=Integer.parseInt(numbers.toString());
parent.zoomSlider.setValue(newVal);
} catch (Exception e){
//fail silently if invalid
}
}
}
if(parent.zoomSlider.getValue()<300) {
parent.zoomSlider.setValueIsAdjusting(false);
return parent.zoomSlider.getValue();
}
mainGUI.zoomTo(newVal);
return newVal;
}
}
class RefreshableComboBoxModel extends DefaultComboBoxModel{
RefreshableComboBoxModel(Object[] itmes){
super(itmes);
}
public void refresh(){
this.fireContentsChanged(this, 0, 2);
}
} | 5 |
public static Proposition buildTopLevelProposition(Stella_Object tree, boolean trueassertionP) {
if (Stella_Object.isaP(tree, Logic.SGT_STELLA_STRING_WRAPPER)) {
return (Logic.buildTopLevelProposition(Stella.readSExpressionFromString(((StringWrapper)(tree)).wrapperValue), trueassertionP));
}
{ Proposition proposition = null;
Cons logicvariabletable = ((Cons)(Logic.$LOGICVARIABLETABLE$.get()));
{ Object old$Logicvariabletable$000 = Logic.$LOGICVARIABLETABLE$.get();
Object old$Variableidcounter$000 = Logic.$VARIABLEIDCOUNTER$.get();
Object old$Termunderconstruction$000 = Logic.$TERMUNDERCONSTRUCTION$.get();
try {
Native.setSpecial(Logic.$LOGICVARIABLETABLE$, ((Cons)(((logicvariabletable != null) ? logicvariabletable : Stella.NIL))));
Native.setIntSpecial(Logic.$VARIABLEIDCOUNTER$, ((Integer)(Logic.$VARIABLEIDCOUNTER$.get())).intValue());
Native.setSpecial(Logic.$TERMUNDERCONSTRUCTION$, tree);
proposition = ((Proposition)(Logic.buildProposition(tree)));
if (proposition != null) {
Proposition.normalizeTopLevelProposition(proposition);
Proposition.verifyForallPropositions(proposition);
if (!(Proposition.collectUnresolvedSlotReferences(proposition) == Stella.NIL)) {
if (trueassertionP) {
Proposition.updateSkolemTypeFromIsaAssertions(proposition);
}
Logic.resolveUnresolvedSlotReferences(proposition);
}
if (trueassertionP &&
((proposition.kind == Logic.KWD_EXISTS) &&
(!Logic.descriptionModeP()))) {
Proposition.instantiateUndefinedSurrogates(proposition);
}
proposition = Proposition.recursivelyFastenDownPropositions(proposition, false);
}
} finally {
Logic.$TERMUNDERCONSTRUCTION$.set(old$Termunderconstruction$000);
Logic.$VARIABLEIDCOUNTER$.set(old$Variableidcounter$000);
Logic.$LOGICVARIABLETABLE$.set(old$Logicvariabletable$000);
}
}
return (proposition);
}
} | 8 |
public static <V> List<V> topologicalSort(final DirectedGraph<V> g) {
List<V> ts = new LinkedList<>();
int inDegree[] = new int[g.getNumberOfVertexes()];
Queue<V> q = new LinkedList<>();
int i = 0;
// for every vertex...
for (V vertex : g.getVertexList()) {
inDegree[i] = g.getPredecessorVertexList(vertex).size();
if (inDegree[i] == 0) {
q.add(vertex);
}
i++;
}
V v;
int j = 0;
while (!q.isEmpty()) {
v = q.remove();
ts.add(v);
for (V vertex : g.getSuccessorVertexList(v)) {
j = 0;
for (V vertex2 : g.getVertexList()) {
if (vertex2 == vertex) {
break;
}
j++;
}
if (--inDegree[j] == 0) {
q.add(vertex);
}
}
}
if (ts.size() != g.getNumberOfVertexes()) {
// Graph with cycle
throw new IllegalStateException("Zyklus gefunden!");
} else {
return ts;
}
} | 8 |
@Override
public void update(final Observable o, final Object arg) {
if (!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
update(o, arg);
}
});
return;
}
if (o instanceof Modele) {
super.getContentPane().remove(super.getScore());
super.getContentPane().remove(super.getGrid());
super.getContentPane().remove(super.getPieces());
super.getContentPane().remove(score2);
super.getContentPane().remove(grid2);
super.getContentPane().remove(pieces2);
Modele _plateau1 = (Modele) o;
Modele _plateau2 = (Modele) o;
updateGrid(_plateau1, _plateau2);
super.getScore().setScore(_plateau1.getScore(), _plateau1.getNbLignes());
score2.setScore(_plateau2.getScore(), _plateau2.getNbLignes());
}
super.getContentPane().add(super.getScore(), BorderLayout.WEST);
super.getContentPane().add(super.getPieces(), BorderLayout.WEST);
super.getContentPane().add(super.getGrid(), BorderLayout.CENTER);
getContentPane().add(grid2, BorderLayout.CENTER);
getContentPane().add(pieces2, BorderLayout.EAST);
getContentPane().add(score2, BorderLayout.EAST);
super.getContentPane().repaint();
} | 2 |
public void loadFromFiles() {
List<String> categories = Arrays.asList("pets", "futurama", "perl",
"smac", "starwars", "familyguy", "humorists", "computers", "linux", "goedel",
"art", "ascii-art", "cookie", "debian", "definitions", "drugs", "education",
"ethnic", "firefly", "food", "fortunes", "kids", "knghtbrd", "law", "linuxcookie",
"literature", "love", "magic", "medicine", "men-women", "miscellaneous", "news",
"paradoxum", "people", "platitudes", "politics", "riddles", "science", "songs-poems",
"sports", "startrek", "wisdom", "work", "zippy", "offensive", "duckdynasty", "mismanagement", "grail",
"airplane", "caddyshack", "animal-house", "princess-bride", "godfather", "office-space",
"stripes", "spaceballs", "blazing-saddles", "this-is-the-end", "top100",
"naked-gun", "police-academy", "big-lebowski", "young-frankenstein", "history-of-the-world",
"pulp-fiction", "orange-county", "shawshank", "ghostbusters", "harold-and-kumar", "strange-brew"
);
TreeMap<String, ArrayList<String>> fortunes = new TreeMap<String, ArrayList<String>>();
for (String cat : categories) {
InputStream in = getClass().getResourceAsStream("/fortunes/" + cat);
ArrayList<String> catList = new ArrayList<String>();
try {
DataInputStream ds = new DataInputStream(in);
BufferedReader br = new BufferedReader(new InputStreamReader(ds));
String strLine;
StringBuffer buf = new StringBuffer("");
while ((strLine = br.readLine()) != null) {
if (strLine.equalsIgnoreCase("%")) {
String fullFortune = buf.toString();
catList.add(fullFortune);
buf.setLength(0);
} else {
buf.append(strLine + "\n");
}
}
in.close();
fortunes.put(cat, catList);
} catch (Exception e) {
System.err.println("Fortune Error: " + e.getMessage());
}
}
try {
Statement s = db.createStatement();
for (String cat : fortunes.keySet()) {
System.out.println("inserting");
s.executeUpdate("insert into categories values (\"" + cat + "\")");
System.out.println("getting id");
ResultSet rs = s.executeQuery("select last_insert_rowid()");
if (rs.next()) {
System.out.println("getting long");
long catId = rs.getLong(1);
System.out.println(cat + " got category id " + catId);
// insert fortunes for cat
ArrayList<String> catFortunes = fortunes.get(cat);
for (String f : catFortunes) {
System.out.println("inserting fortune");
//String safeF = f;//f.replaceAll("\"", "\\\\\"");
String safeF = f.replaceAll("'", "''");
//System.out.println("==[ " + safeF + " ]==");
s.executeUpdate("insert into fortunes values ('" + safeF + "', " + catId + ")");
}
}
System.out.println("going to next cat");
}
} catch (SQLException e) {
System.err.println("Caught SQLException while inserting stuff");
System.err.println(e);
}
} | 8 |
private static String convertToHex(byte[] data) {
StringBuilder buf = new StringBuilder(50);
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
} | 4 |
static void LWS()
{
Scanner in = new Scanner(System.in);
final Board b = Board.readBoard(in);
ArrayList<Integer> nextPiece = new ArrayList<Integer>();
while(in.hasNextInt())
nextPiece.add(in.nextInt());
Heuristic hAll [] =
{
new LinearWeightedSum(new double[] {0.3,0.1,0.6,0.0,}),
new LinearWeightedSum(new double[] {0.7,0.2,0.1,0.0,}),
new LinearWeightedSum(new double[] {0.2,0.5,0.3,0.0,}),
new LinearWeightedSum(new double[] {0.3,0.5,0.2,0.0,}),
};
System.err.println("Searcher\tHeuristic\tScore\tMov/S:\t");
for (Heuristic h : hAll)
{
for (int i = 5; i <= 8; i++){
Searcher s = new DLDFS(h, i);
s.playGame(b, new ArrayList<Integer>(nextPiece));
}
}
} | 3 |
@Override
public void encodeTerm(long[] longs, DataOutput out, FieldInfo fieldInfo, BlockTermState _state, boolean absolute) throws IOException {
IntBlockTermState state = (IntBlockTermState)_state;
if (absolute) {
lastState = emptyState;
}
longs[0] = state.docStartFP - lastState.docStartFP;
if (writePositions) {
longs[1] = state.posStartFP - lastState.posStartFP;
if (writePayloads || writeOffsets) {
longs[2] = state.payStartFP - lastState.payStartFP;
}
}
if (state.singletonDocID != -1) {
out.writeVInt(state.singletonDocID);
}
if (writePositions) {
if (state.lastPosBlockOffset != -1) {
out.writeVLong(state.lastPosBlockOffset);
}
}
if (state.skipOffset != -1) {
out.writeVLong(state.skipOffset);
}
lastState = state;
} | 8 |
private static Thread createCommandManagerThread(PrintStream commandSender) {
CommandManager commandManager = new CommandManager(commandSender, verbose);
log.info("Create commandManager");
Thread commandManagerThread = new Thread(commandManager);
log.info("Create commandManagerThread");
return commandManagerThread;
} | 0 |
private void computePositions() {
// Determine time for rendering
if (fConf.getInt("fixedTime") == 0) {
// No fixed time.
// final long lTimePassed = System.currentTimeMillis() - fsStartTime;
// fCurrentTime = fsStartTime + (long) (fConf.getDouble("timeWarpFactor") * lTimePassed);
fCurrentTime = System.currentTimeMillis();
} else {
// Fixed time.
fCurrentTime = fConf.getInt("fixedTime") * 1000L;
}
if (fConf.getBoolean("sunMovesP")) {
fConf.setSunPos(SunPositionCalculator.getSunPositionOnEarth(fCurrentTime));
}
// Determine viewing position
if (fConf.is("viewPositionType", "Fixed")) {
fViewPos = fConf.getViewPos();
} else if (fConf.is("viewPositionType", "Sun-relative")) {
fViewPos = getSunRelativePosition();
} else if (fConf.is("viewPositionType", "Orbit")) {
fViewPos = getOrbitPosition(fCurrentTime);
} else if (fConf.is("viewPositionType", "Random")) {
fViewPos = getRandomPosition();
} else if (fConf.is("viewPositionType", "Moon")) {
fViewPos = SunPositionCalculator.getMoonPositionOnEarth(fCurrentTime);
}
// for ViewRotGalactic, compute appropriate viewing rotation
if (fConf.is("viewRotationType", "Galactic")) {
fViewRotation = (Toolkit.degsToRads(fConf.getSunPos().getLat()
* Math.sin((fViewPos.getLong() - fConf.getSunPos().getLong()))));
} else {
fViewRotation = fConf.getDouble("viewRotation");
}
} | 8 |
public static Filter createFilter(String command) {
// NYI: A filter with arguments.
command = command.trim();
int argIndex = command.indexOf(" ");
String name = null;
if (argIndex > 1) {
name = "filters." + command.substring(0, argIndex);
} else {
name = "filters." + command;
}
try {
Class filterClass = Class.forName(name);
if (filterClass == null) {
return null;
}
// NYI: Make sure this cast is valid.
Filter filter = (Filter) filterClass.newInstance();
String args = null;
if (argIndex > 1) {
args = command.substring(argIndex, command.length());
} else {
args = "";
}
filter.setArguments(args);
return filter;
} catch (ClassNotFoundException e) {
// Do nothing.
} catch (InstantiationException e) {
// Do nothing.
} catch (IllegalAccessException e) {
// Do nothing.
} catch (NoClassDefFoundError e) {
// Do nothing.
}
return null;
} | 7 |
@Override
public String getPayRecord(String mid) {
// TODO Auto-generated method stub
String payRecordInfo = "";
ArrayList<PayRecord> payRecords = new ArrayList<>();
String sql = "select * from payrecord where mid = \'" + mid + "\'";
try {
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
payRecords.add(new PayRecord(resultSet.getString(1), resultSet
.getDate(2), resultSet.getDouble(3)));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (PayRecord payRecord : payRecords) {
payRecordInfo += payRecord.getDate() + "*" + payRecord.getMoney()
+ "$";
}
if (payRecordInfo.length() > 1)
payRecordInfo = payRecordInfo.substring(0,
payRecordInfo.length() - 1);
return payRecordInfo;
} | 4 |
private boolean setColumnDividerHighlight(int x) {
int oldDividerIndex = mMouseOverColumnDivider;
int dividerIndex = mAllowColumnResize ? overColumnDivider(x) : -1;
setCursor(dividerIndex == -1 ? Cursor.getDefaultCursor() : Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));
mMouseOverColumnDivider = dividerIndex;
if (oldDividerIndex != dividerIndex) {
repaintDivider(oldDividerIndex);
repaintDivider(dividerIndex);
}
return dividerIndex != -1;
} | 3 |
private void addMainFunction(StringBuilder code){
// variables names:
final String luminance = "luminance";
final String feature = "feature";
final String heightColor = "h";
// function code:
String func = "void main(void){\n";
if (renderTraces){
func +=
// access the seismic texture sampler, as a base color:
FLOAT_TYPE + " " + luminance + " = float(texture3D(" + TRACES_SAMPLER + ", gl_TexCoord[0].stp));\n"
// normalize data:
+ luminance + " = ((" + luminance + " - " + MIN_AMPLITUDE + ") / (" + MAX_AMPLITUDE + " - " + MIN_AMPLITUDE + "));\n"
;
}//if
if (renderFeatures){
func +=
// access the features texture sampler:
FLOAT_TYPE + " " + feature + " = float(texture3D(" + FEATURES_SAMPLER + ", gl_TexCoord[1].stp));\n"
// Height-Based Color
+ FLOAT_TYPE + " " + heightColor + ";\n"
;
// go through the features:
String loop = "";
for (int i=0; i < featuresIDs.length; i++){
// get a new color
float [] c = new float[3];
c = COLOR_DB[i].getRGBColorComponents(c);
System.out.println("(" + c[0] + "," + c[1] + "," + c[2] + ")");
if (i != 0)
loop += "else ";
loop +=
"if (" + feature + " == " + FEATURE_NO_ + i + "[0]){\n"
+ heightColor + " = (gl_TexCoord[1].s - " + FEATURE_NO_ + i + "[1])"
+ " / (" + FEATURE_NO_ + i + "[2] - " + FEATURE_NO_ + i + "[1]);\n"
+ "gl_FragColor = vec4("
+ PALETTE_REV_FUNC + "(" + heightColor + "), 1.0);\n}\n" //vec4(1.0, 0.0, 0.0, 1.0);
// + c[0] + "," + c[1] + "," + c[2] + ",1.0);\n}\n"
;
}
// add the loop to the function:
func += loop;
}//if
if (renderTraces){
String ifStatement = "";
// add "else" if features to be rendered to continue the loop:
if (renderFeatures){
ifStatement += "else ";
}
ifStatement += "if((1 - gl_TexCoord[0].p) < " + SEISMIC_TEX_DEPTH + "){\n"
+ "gl_FragColor = vec4(" + luminance + ", " + luminance + ", " + luminance + ", " + ALPHA + ");\n}\n";
// add it to func:
func += ifStatement;
}//if
// [20/11/2012] add a clear color in case nothing to be rendered:
// this is required after the updated on the graphics card in Nov. 2012
func += "else{\n"
+ "gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);\n}\n";
// end func and add it to the code:
code.append(func + "}\n");
}//addMainFunction | 6 |
public void loadAllStaff(){//COMPLETE
try {
ResultSet dbAllStaff = null;
Statement statement;
statement = connection.createStatement();
dbAllStaff = statement.executeQuery( "SELECT Staff.staffID, Staff.role FROM Staff;");
while(dbAllStaff.next())
{
User tempUser = null;
for (int i=0; i<allUsers.size();i++){
if(allUsers.get(i).getUserID()==(dbAllStaff.getInt("staffID")))
{
tempUser = (allUsers.get(i));
}
}
Staff newStaff = new Staff(tempUser, dbAllStaff.getString("role"));
allStaff.addStaff(newStaff);
}
} catch (SQLException ex) {
Logger.getLogger(testFrame3Tim.class.getName()).log(Level.SEVERE, null, ex);
}
} | 4 |
@Override
public int compare(Quiz quiz1, Quiz quiz2) {
if (quiz1.raterNumber == 0)
return 1;
if (quiz2.raterNumber == 0)
return -1;
if (quiz1.totalRating / quiz1.raterNumber > quiz2.totalRating / quiz2.raterNumber)
return -1;
else
return 1;
} | 3 |
public boolean Salvar(Email obj, int idPessoa) {
try{
if(obj.getId() == 0){
PreparedStatement comando = banco.getConexao()
.prepareStatement("INSERT INTO emails (endereco,"
+ "id_pessoa,ativo) VALUES (?,?,?)");
comando.setString(1, obj.getEndereco());
comando.setInt(2, idPessoa);
comando.setInt(3, obj.getAtivo());
comando.executeUpdate();
comando.getConnection().commit();
}else{
PreparedStatement comando = banco.getConexao()
.prepareStatement("UPDATE emails SET endereco = ?,id_pessoa = ?,ativo = ? WHERE id = ?");
comando.setString(1, obj.getEndereco());
comando.setInt(2, idPessoa);
comando.setInt(3, obj.getAtivo());
comando.setInt(4, idPessoa);
comando.executeUpdate();
comando.getConnection().commit();
}
return true;
}catch(SQLException ex){
ex.printStackTrace();
return false;
}
} | 2 |
public int[] getHitBox() {
if (isWalking) {
switch (getFacing()) {
case North:
return new int[] {trueX(), trueY(), trueX(), trueY() - 1};
case South:
return new int[] {trueX(), trueY(), trueX(), trueY() + 1};
case East:
return new int[] {trueX(), trueY(), trueX() + 1, trueY()};
case West:
return new int[] {trueX(), trueY(), trueX() - 1, trueY()};
default:
break;
}
}
return new int[]{trueX(), trueY()};
} | 5 |
public EncryptedCommunityCards listenForCommunityCards()
throws InvalidKeyException, IllegalBlockSizeException,
BadPaddingException, NoSuchAlgorithmException,
InvalidSubscriptionException, IOException, InterruptedException {
final Subscription encSub = elvin.subscribe(NOT_TYPE + " == '"
+ COMMUNITY_CARDS + "' && " + GAME_ID + " == '"
+ gameHost.getID() + "'");
Notification not;
encSub.addListener(new NotificationListener() {
public void notificationReceived(NotificationEvent e) {
byte[] tmpBytes = (byte[]) e.notification
.get(ENCRYPTED_COM_CARDS);
try {
encryptedCommunityCards = (EncryptedCommunityCards) Passable
.readObject(tmpBytes);
if (!sigServ.validateSignature(encryptedCommunityCards,
gameHost.getPublicKey())) {
// sig failed!
callCheat(SIGNATURE_FAILED);
System.exit(0);
}
} catch (Exception e1) {
shutdown();
System.exit(0);
}
synchronized (encSub) {
encSub.notify();
}
}
});
not = new Notification();
not.set(NOT_TYPE, HAVE_MY_HAND);
not.set(GAME_ID, gameHost.getID());
not.set(SOURCE_USER, user.getID());
not.set(SIGNATURE,
sigServ.createVerifiedSignature(SigService.HAVE_HAND_NONCE));
synchronized (encSub) {
elvin.send(not);
// wait until received reply
encSub.wait();
}
encSub.remove();
System.out.println("Got Community Cards!");
// System.out.println(new
// String(encryptedCommunityCards.data.get(0).cardData));
return encryptedCommunityCards;
} | 2 |
void assignToRow( Atom a ) throws Exception
{
if ( !addToExisting(a) )
{
Row r = new Row( sigla, groups, base );
// this will always be a nested row
r.setNested( this.nested() );
FragList fl = new FragList();
fl.setBase( a.versions.nextSetBit(base)==base );
fl.add( a );
r.add( fl );
r.versions.or( a.versions );
// contraint it to the versions of the table
r.versions.and( this.versions );
addRow( r );
//System.out.println("Created row "+Utils.bitSetToString(sigla,
// r.versions));
if ( r.versions==null || r.versions.isEmpty() )
System.out.println("row versions are empty");
}
} | 3 |
public ArrayList<Point> getAllFreeSpots(){
ArrayList<Point> result = new ArrayList<Point>();
for(int x=0; x<level.length; x++){
for(int y=0; y<level[0].length; y++){
if(level[x][y] == null){
result.add(new Point(x, y));
}
}
}
return result;
} | 3 |
private boolean advanceRpts(PhrasePositions pp) throws IOException {
if (pp.rptGroup < 0) {
return true; // not a repeater
}
PhrasePositions[] rg = rptGroups[pp.rptGroup];
FixedBitSet bits = new FixedBitSet(rg.length); // for re-queuing after collisions are resolved
int k0 = pp.rptInd;
int k;
while((k=collide(pp)) >= 0) {
pp = lesser(pp, rg[k]); // always advance the lesser of the (only) two colliding pps
if (!advancePP(pp)) {
return false; // exhausted
}
if (k != k0) { // careful: mark only those currently in the queue
bits = FixedBitSet.ensureCapacity(bits, k);
bits.set(k); // mark that pp2 need to be re-queued
}
}
// collisions resolved, now re-queue
// empty (partially) the queue until seeing all pps advanced for resolving collisions
int n = 0;
// TODO would be good if we can avoid calling cardinality() in each iteration!
int numBits = bits.length(); // larges bit we set
while (bits.cardinality() > 0) {
PhrasePositions pp2 = pq.pop();
rptStack[n++] = pp2;
if (pp2.rptGroup >= 0
&& pp2.rptInd < numBits // this bit may not have been set
&& bits.get(pp2.rptInd)) {
bits.clear(pp2.rptInd);
}
}
// add back to queue
for (int i=n-1; i>=0; i--) {
pq.add(rptStack[i]);
}
return true;
} | 9 |
public <T> T getProperty( String key, Class<T> type ) {
Object value = parsed.get( key );
if ( value != null ) {
try {
return type.cast( value );
} catch ( ClassCastException cce ) {
// fall through to ParseException below
}
} else {
try {
Method method = this.getClass().getMethod( "get" + type.getSimpleName(), String.class );
value = method.invoke( this, key );
if ( value == null ) {
return null;
}
return type.cast( value );
} catch (NoSuchMethodException e) {
// fall through to ParseException below
} catch (IllegalArgumentException e) {
//
} catch (IllegalAccessException e) {
//
} catch (InvocationTargetException e) {
//
}
}
throw new IllegalArgumentException( "\"" + key + "\": can't parse value \""
+ getProperty( key ) + " as " + type.getSimpleName() );
} | 7 |
@Override
public GameState[] allActions(GameState state, Card card, int time) {
GameState[] states = new GameState[1];
states[0] = state;
if(time == Time.DAY)
{
states[0] = monkeyDay(new GameState(state), card, false);
}
else if(time == Time.DUSK)
{
PickTreasure temp = new PickTreasure();
states = temp.allActions(new GameState(state), card, time);
}
else if(time == Time.NIGHT)
{
//Nothing to do
}
return states;
} | 3 |
public static String get(String ip, String comunidade, String objeto) throws Exception {
System.out.println("\nSNMP Get");
System.out.println("Objeto: " + objeto);
System.out.println("Comunidade: " + comunidade);
// Inicia sessaso SNMP
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
// Configura o endereco
Address endereco = new UdpAddress(ip + "/" + porta);
// Configura target
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(comunidade));
target.setAddress(endereco);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c);
// Cria PDU (SNMP Protocol Data Unit)
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(objeto)));
pdu.setType(PDU.GET);
// Envia PDU
ResponseEvent responseEvent = snmp.send(pdu, target);
String resultado = "";
if(responseEvent != null) {
// Extrai a resposta PDU (pode ser null se ocorreu timeout)
PDU responsePDU = responseEvent.getResponse();
if(responsePDU != null) {
int errorStatus = responsePDU.getErrorStatus();
int errorIndex = responsePDU.getErrorIndex();
String errorStatusText = responsePDU.getErrorStatusText();
if (errorStatus == PDU.noError) {
Vector <VariableBinding> tmpv = (Vector <VariableBinding>) responsePDU.getVariableBindings();
if(tmpv != null) {
for(int k=0; k <tmpv.size();k++) {
VariableBinding vb = (VariableBinding) tmpv.get(k);
if (vb.isException()) {
String errorString = vb.getVariable().getSyntaxString();
System.out.println("Error:"+errorString);
if(errorString.equals("NoSuchObject"))
throw new NoSuchObjectException("No Such Object: " + objeto);
if(errorString.equals("NoSuchInstance"))
throw new NoSuchInstanceException("No Such Instance: " + objeto);
}
else {
Variable var = vb.getVariable();
OctetString oct = new OctetString(var.toString());
String sVar = oct.toString();
resultado = sVar;
System.out.println(resultado);
}
}
}
}
else {
System.out.println("Erro: GET Request Falhou");
System.out.println("Status do Erro = " + errorStatus);
System.out.println("Index do Erro = " + errorIndex);
System.out.println(errorStatusText);
}
}
else {
System.out.println("Resultado vazio");
throw new NullPointerException("Null Response");
}
}
else {
throw new RuntimeException("GET Request Timed Out");
}
snmp.close();
return resultado;
} | 8 |
@org.junit.Test
public void testLevels_Grey2JUL()
{
LEVEL[] levels = LEVEL.values();
for (int idx = 0; idx != levels.length; idx++)
{
LEVEL lvl = levels[idx];
java.util.logging.Level jul_lvl;
switch (lvl)
{
case OFF: jul_lvl = java.util.logging.Level.OFF; break;
case ALL: jul_lvl = java.util.logging.Level.ALL; break;
case ERR: jul_lvl = java.util.logging.Level.SEVERE; break;
case WARN: jul_lvl = java.util.logging.Level.WARNING; break;
case INFO: jul_lvl = java.util.logging.Level.INFO; break;
case TRC: jul_lvl = java.util.logging.Level.FINE; break;
case TRC2: jul_lvl = java.util.logging.Level.FINER; break;
default: jul_lvl = java.util.logging.Level.FINEST; break;
}
org.junit.Assert.assertEquals(jul_lvl, Interop.mapLevel(lvl));
if (lvl.ordinal() > LEVEL.TRC3.ordinal()) lvl = LEVEL.TRC3;
org.junit.Assert.assertEquals(lvl, Interop.mapLevel(Interop.mapLevel(lvl)));
}
} | 9 |
public cell getCell(int x, int y){
cell hyperion = new conveyorCell();
switch(aamode){
case 1: hyperion = pete.culture[x][y];
case 2: for(int b = 0; b < gridy; b++){
for(int a = 0; a < gridx; a++){
if(x >= grid[a][b].xmin && y >= grid[a][b].ymin){
if(x <= grid[a][b].xmax && y <= grid[a][b].ymax){
hyperion = grid[a][b].getCell(x,y);}}}}
break;
}
return hyperion;
} | 8 |
private String mygettoken() {
while (this.index < this.length){
char c = this.line.charAt(this.index);
if (this.flag) {
if (this.resky.indexOf(c) != -1) {
if (this.count > 0) {
String t = this.line.substring(this.start,this.index).trim();
this.count = 0;
if (t.length() > 0)
return t;
}
this.start = this.index+1;
this.index += 1;
return "" + c;
}
else if (c == this.QUOTE) {
if (this.count > 0) {
String t = this.line.substring(this.start,this.index).trim();
this.count = 0;
if (t.length() > 0)
return t;
}
this.flag = false;
this.start = this.index;
}
else
this.count += 1;
}
else
if (c == this.QUOTE) {
String t = this.line.substring(this.start,this.index+1);
this.start = this.index+1;
this.flag = true;
this.index += 1;
return t;
}
this.index += 1;
}
return null;
} | 9 |
@Test
public void testExecutionSuccess() throws ExecutionException {
IProcessComponent<Void> decoratedComponent = TestUtil.executionSuccessComponent(true);
IProcessComponent<Void> busyComponent = new BusyComponent(decoratedComponent);
AsyncComponent<Void> ac = new AsyncComponent<Void>(busyComponent);
Future<?> future = null;
try {
future = ac.execute();
} catch (InvalidProcessStateException | ProcessExecutionException ex) {
fail(ex.getMessage());
}
try {
future.get();
} catch (InterruptedException ex) {
fail(ex.getMessage());
} catch (ExecutionException ex) {
if (ex.getCause() instanceof ProcessExecutionException) {
fail("Should execute successfully.");
} else {
throw ex;
}
}
assertTrue(ac.getState() == ProcessState.EXECUTION_SUCCEEDED);
assertTrue(ac.getState() == decoratedComponent.getState());
} | 5 |
public boolean checkThatDatesSelected() {
String checkFromDate = this.fromDate.getText();
String checkTillDate = this.tillDate.getText();
Date frDate = null;
Date tiDate = null;
try {
tiDate = currentFormat.parse(checkTillDate);
} catch (ParseException e) {
e.printStackTrace();
}
try {
frDate = currentFormat.parse(checkFromDate);
} catch (ParseException e) {
e.printStackTrace();
}
if (((this.fromDate.getText() != "" || this.fromDate.getText() != null) && isThisDateValid(checkFromDate, "dd/MM/yyyy")) &&
(this.tillDate.getText() != "" || this.tillDate.getText() != null) && isThisDateValid(checkFromDate, "dd/MM/yyyy") &&
(frDate.compareTo(tiDate) < 1)) {
return true;
} else {
new ErrorMsge("Внимание! Не корректные даты.\n Введите даты в формате \n День/Месяц/Год (дд/мм/гггг)");
return false;
}
} | 9 |
public void run()
{
try
{
this.MPrioW.acquire();
if(this.counter == 0)
this.MReading.acquire();
this.counter++;
this.MPrioW.release();
this.MWriting.acquire();
System.out.println("Ecriture");
Thread.sleep(1000);
this.MWriting.release();
this.MPrioW.acquire();
this.counter--;
if(this.counter == 0)
this.MReading.release();
this.MPrioW.release();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
} | 3 |
private static String getStringFromDocument(Document doc) {
try {
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
} catch (TransformerException ex) {
ex.printStackTrace();
return null;
}
} | 1 |
@Override
public void startSetup(Attributes atts) {
super.startSetup(atts);
addActionListener(this);
Outliner.documents.addDocumentListener(this);
Outliner.documents.addDocumentRepositoryListener(this);
setEnabled(false);
} | 0 |
public void refreshGrid(Square[][] grid) {
if (grid != null) {
board = grid;
}
playerList.clear();
for (int j = 1; j < BOARD_SIZE - 1; j++) {
for (int k = 1; k < BOARD_SIZE - 1; k++) {
if (board[j][k].getPlayer() != null) {
if (!board[j][k].getPlayer().getName().contains("Enemy")) {
playerList.add(board[j][k].getPlayer());
}
}
}
}
if(board[0][0] != null){
if(board[0][0].getPlayer() != null){
List<Object> objs = board[0][0].getObjects();
for(int x = 0; x < objs.size(); x++){
if (objs.get(x) instanceof Player){
playerList.add((Player) objs.get(x));
}
}
}
}
} | 9 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("A faint curing glow surrounds <T-NAME>."):L("^S<S-NAME> @x1 for <T-NAMESELF> to be cured of <T-HIS-HER> affliction.^?",prayWord(mob)));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
final Ability A=target.fetchEffect("Prayer_Cannibalism");
if(A!=null)
A.unInvoke();
}
}
else
beneficialWordsFizzle(mob,target,auto?"":L("<S-NAME> @x1 for <T-NAMESELF>, but nothing happens.",prayWord(mob)));
// return whether it worked
return success;
} | 7 |
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.