text stringlengths 14 410k | label int32 0 9 |
|---|---|
void appendButtonsToReport(boolean submit) {
Style style1 = null;
String s = null;
if (submit && !"true".equalsIgnoreCase(System.getProperty("mw.cd.mode"))) {
style1 = page.addStyle(null, null);
JButton button = new JButton(page.uploadReportAction);
s = Modeler.getInternationalText("Submit");
button.setText(s != null ? s : "Submit");
StyleConstants.setComponent(style1, button);
}
Style style2 = page.addStyle(null, null);
JButton button = new JButton(page.printAction);
button.setIcon(IconPool.getIcon("printer"));
s = Modeler.getInternationalText("Print");
if (s != null)
button.setText(s);
StyleConstants.setComponent(style2, button);
Style style3 = page.addStyle(null, null);
button = new JButton(page.saveAsAction);
button.setIcon(IconPool.getIcon("save"));
s = Modeler.getInternationalText("SaveButton");
button.setText(s != null ? s : "Save");
StyleConstants.setComponent(style3, button);
StyledDocument doc = page.getStyledDocument();
try {
doc.insertString(doc.getLength(), "\n\n", null);
if (submit && !"true".equalsIgnoreCase(System.getProperty("mw.cd.mode"))) {
doc.insertString(doc.getLength(), " ", style1);
doc.insertString(doc.getLength(), " ", null);
}
doc.insertString(doc.getLength(), " ", style2);
doc.insertString(doc.getLength(), " ", null);
doc.insertString(doc.getLength(), " ", style3);
doc.insertString(doc.getLength(), "\n\n", null);
}
catch (BadLocationException ble) {
ble.printStackTrace();
}
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setLeftIndent(sas, 8);
StyleConstants.setRightIndent(sas, 8);
doc.setParagraphAttributes(0, doc.getLength(), sas, false);
} | 8 |
private void addMethods(CtClass proxy, Method[] ms)
throws CannotCompileException, NotFoundException
{
CtMethod wmethod;
for (int i = 0; i < ms.length; ++i) {
Method m = ms[i];
int mod = m.getModifiers();
if (m.getDeclaringClass() != Object.class
&& !Modifier.isFinal(mod))
if (Modifier.isPublic(mod)) {
CtMethod body;
if (Modifier.isStatic(mod))
body = forwardStaticMethod;
else
body = forwardMethod;
wmethod
= CtNewMethod.wrapped(toCtClass(m.getReturnType()),
m.getName(),
toCtClass(m.getParameterTypes()),
exceptionForProxy,
body,
ConstParameter.integer(i),
proxy);
wmethod.setModifiers(mod);
proxy.addMethod(wmethod);
}
else if (!Modifier.isProtected(mod)
&& !Modifier.isPrivate(mod))
// if package method
throw new CannotCompileException(
"the methods must be public, protected, or private.");
}
} | 7 |
public void saveTrace(String filename) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
for (AgentState s : state){
if (s instanceof BacktrackingAgentState){
BacktrackingAgentState b = (BacktrackingAgentState)s;
int touch = (b.isHasTouched()) ? 1 : 0;
double sonar = b.getSonar();
int sound = b.getSound();
writer.append(touch + "|" + sonar + "|" + sound + "|" + s.getAction().toString() + "\n");
}
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} | 4 |
public static String getMD5(File file) {
DigestInputStream stream = null;
try
{
stream = new DigestInputStream(new FileInputStream(file), MessageDigest.getInstance("MD5"));
byte[] buffer = new byte[65536];
int read;
read = stream.read(buffer);
while (read >= 1)
read = stream.read(buffer);
}
catch (Exception ignored)
{
return null;
} finally {
closeSilently(stream);
}
return String.format("%1$032x", new Object[] { new BigInteger(1, stream.getMessageDigest().digest()) });
} | 2 |
public static void checkPoints(Form form) {
if (form.getStart().x > form.getEnd().x
&& form.getStart().y > form.getEnd().y) {
Point temp = form.getStart();
form.setStart(form.getEnd());
form.setEnd(temp);
} else if (form.getStart().x < form.getEnd().x
&& form.getStart().y > form.getEnd().y){
int temp = form.getStart().y;
form.setStart(new Point(form.getStart().x, form.getEnd().y));
form.setEnd(new Point(form.getEnd().x, temp));
} else if (form.getStart().x > form.getEnd().x
&& form.getStart().y < form.getEnd().y) {
int temp = form.getStart().x;
form.setStart(new Point(form.getEnd().x, form.getStart().y));
form.setEnd(new Point(temp, form.getEnd().y));
}
} | 6 |
private void addWrappedCall(ClassFile cf, CodeBuilder b, Method m) {
// Special behavior for equals method
boolean isEqualsMethod = false;
if (m.getName().equals("equals") && m.getReturnType().equals(boolean.class)) {
Class[] paramTypes = m.getParameterTypes();
isEqualsMethod = paramTypes.length == 1 && paramTypes[0].equals(Object.class);
}
if (isEqualsMethod) {
b.loadThis();
b.loadLocal(b.getParameter(0));
Label notEqual = b.createLabel();
b.ifEqualBranch(notEqual, false);
b.loadConstant(true);
b.returnValue(TypeDesc.BOOLEAN);
notEqual.setLocation();
// Check if object is our type.
b.loadLocal(b.getParameter(0));
b.instanceOf(cf.getType());
Label isInstance = b.createLabel();
b.ifZeroComparisonBranch(isInstance, "!=");
b.loadConstant(false);
b.returnValue(TypeDesc.BOOLEAN);
isInstance.setLocation();
}
final TypeDesc atomicRefType = TypeDesc.forClass(AtomicReference.class);
// Load wrapped object...
b.loadThis();
b.loadField(REF_FIELD_NAME, atomicRefType);
b.invokeVirtual(atomicRefType, "get", TypeDesc.OBJECT, null);
b.checkCast(TypeDesc.forClass(mType));
// Load parameters...
for (int i=0; i<b.getParameterCount(); i++) {
b.loadLocal(b.getParameter(i));
}
// Special behavior for equals method
if (isEqualsMethod) {
// Extract wrapped object.
b.checkCast(cf.getType());
b.loadField(REF_FIELD_NAME, atomicRefType);
b.invokeVirtual(atomicRefType, "get", TypeDesc.OBJECT, null);
b.checkCast(TypeDesc.forClass(mType));
}
// Invoke wrapped method...
b.invoke(m);
if (m.getReturnType() == void.class) {
b.returnVoid();
} else {
b.returnValue(TypeDesc.forClass(m.getReturnType()));
}
} | 7 |
@Test
public void rnfTest() {
userInput.add("hello");
userInput.add("daniel");
userInput.add("can you help me with cooking");
userInput.add("apple");
userInput.add("yes");
runMainActivityWithTestInput(userInput);
assertTrue(nlgResults.get(2).contains("what") || nlgResults.get(2).contains("What")
&& nlgResults.get(3).contains("apple")
&& nlgResults.get(4).contains("recipe"));
} | 3 |
public HashOperationException(Exception e, String name){
super(e, name);
} | 0 |
private static void initGuiConfig(JSONObject json, Gui gui) throws BadConfig {
JSONObject guiConfig = toJSONObject("gui-config", json.get("gui-config"), false);
try {
if (guiConfig == null) {
gui.setConfigLocation(null, null);
return;
}
gui.setConfigSize(toInteger("width", guiConfig.get("width"), false), toInteger("height", guiConfig.get("height"), false));
gui.setConfigLocation(toString("location-x", guiConfig.get("location-x"), false), toString("location-y",
guiConfig.get("location-y"), false));
} catch (InvalidParameterException e) {
throw new BadConfig(e.getMessage());
}
} | 2 |
public void playSound(Location location)
{
for (String sound : sounds)
{
Packet62NamedSoundEffect soundPacket = new Packet62NamedSoundEffect(sound,
location.getX(), location.getY(), location.getZ(), volume, pitch);
if (soundPacket != null)
{
for (Player player : location.getWorld().getPlayers())
{
if (location.distance(player.getLocation()) <= SOUND_PLAY_DISTANCE)
((CraftPlayer)player).getHandle().playerConnection.sendPacket(soundPacket);
}
}
}
} | 4 |
public void loadOrdersWithDate(Date date)
{
orderlistWithDate.clear();
availableItems.clear();
itemlistReserved.clear();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int h = 0;
for (int j = -1; h < 2; j++)
{
if (j == 0)
{
j = 1;
}
if (j == 2)
{
j = 1;
h = 3;
}
calendar.add(Calendar.DATE, j);
for (int i = 0; i < orderlist.size(); i++)
{
if (orderlist.get(i).getState() != 2 && orderlist.get(i).getorderDate().equals(calendar.getTime()))
{
orderlistWithDate.add(orderlist.get(i));
}
}
}
reservedItem();
availableItems();
} | 6 |
@Test
public void testReporProduto() {
try {
Assert.assertEquals(10, facade.getQuantidadeProduto(1));
Assert.assertTrue(facade.buscarProduto(1).equals(this.p1));
} catch (FacadeException e) {
Assert.fail(e.getMessage());
}
try {
facade.reporProduto(1, 5);
Assert.assertEquals(15, facade.getQuantidadeProduto(1));
Assert.assertTrue(facade.buscarProduto(1).equals(this.p1));
} catch (FacadeException e) {
Assert.fail(e.getMessage());
}
try {
facade.reporProduto(10, 5);
Assert.fail("deveria ter lanÁado uma exceÁ„o");
} catch (FacadeException e) {
// È para lanÁa uma exceÁ„o
}
try {
Assert.assertEquals(5, facade.getQuantidadeProduto(2));
Assert.assertTrue(facade.buscarProduto(2).equals(this.p2));
} catch (FacadeException e) {
Assert.fail(e.getMessage());
}
try {
facade.reporProduto(2, 0);
Assert.assertEquals(5, facade.getQuantidadeProduto(2));
Assert.assertTrue(facade.buscarProduto(2).equals(this.p2));
} catch (FacadeException e1) {
Assert.fail(e1.getMessage());
}
try {
facade.reporProduto(4, 1);
Assert.assertEquals(2, facade.getQuantidadeProduto(4));
Assert.assertTrue(facade.buscarProduto(4).equals(this.p4));
} catch (FacadeException e1) {
Assert.fail(e1.getMessage());
}
try {
facade.reporProduto(3, -1);
Assert.assertEquals(1, facade.getQuantidadeProduto(3));
Assert.fail("deveria ter lanÁado uma exceÁ„o");
} catch (FacadeException e1) {
// È para lanÁa uma exceÁ„o
}
try {
Assert.assertEquals(2, facade.getQuantidadeProduto(4));
Assert.assertTrue(facade.buscarProduto(4).equals(this.p4));
} catch (FacadeException e) {
Assert.fail(e.getMessage());
}
try {
facade.reporProduto(4, 1);
Assert.assertEquals(3, facade.getQuantidadeProduto(4));
} catch (FacadeException e) {
Assert.fail(e.getMessage());
}
} | 9 |
public void setPassword(String password) {
this.password = password;
} | 0 |
private void requestClose(boolean withSaving) {
if (withSaving) {
if (showConfirmDialog(this, res.get("i.confirm-save"), "", YES_NO_OPTION) != YES_OPTION) {
return;
}
ConnectorMap m = new ConnectorMap();
for (Object o : listModel.toArray()) {
ConnectorEntry entry = (ConnectorEntry)o;
final String id = entry.getId();
m.setConnector(id, connectorMap.getConnector(id));
}
try {
ConnectorConfiguration.save(m);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
connectorMap.clear();
connectorMap.putAll(m);
} else {
ConnectorMap fileContent;
try {
fileContent = ConnectorConfiguration.load();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
if (!connectorMap.equals(fileContent)) {
if (showConfirmDialog(this, res.get("i.confirm-without-save"), "", OK_CANCEL_OPTION) != OK_OPTION) {
return;
}
}
}
dispose();
} | 7 |
private static Type decodeType(int dataType) throws IOException {
Type result;
switch (dataType) {
case 0: result = Type.U8 ; break;
case 1: result = Type.STRING; break;
case 2: result = Type.U16 ; break;
case 3: result = Type.U32 ; break;
case 4: result = Type.X8 ; break;
case 5: result = Type.ONE ; break;
case 6: result = Type.TWO ; break;
default:
throw new IOException("Unknown data type.");
}
return result;
} | 7 |
public CompleteDownloadView(){
super();
this.mangaNameTF = new JTextField();
this.mangaUrlTF = new JTextField();
this.pathTF = new JTextField();
this.pathFC = new JFileChooser();
this.pathFC.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
this.startBT = new JButton("Start");
this.stopBT = new JButton("Stop");
this.startBT.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String mangaName = mangaNameTF.getText();
URL mangaUrl = null;
try {
mangaUrl = new URL(mangaUrlTF.getText());
} catch (MalformedURLException e) {
newPopUp("Incorrect URL");
}
String path = pathTF.getText();
path = this.completePath(path);
if (mangaName.equals("") || path.equals(""))
newPopUp("Name and Path fields are empty");
else {
addBars();
final MangaDownloader mangaDownloader = new MangaDownloader(mangaName,mangaUrl, path,linuxOS);
Thread thread = new Thread() { public void run() {mangaDownloader.startDownload(getViewInstance());}};
setThreadInstance(thread);
try{
thread.start();
} catch (Exception e) {
newPopUp("Internal Error: " + e.toString());
}
}
}
private String completePath(String path) {
String[] linux = path.split("/");
if (linux.length>1)
return path+"/";
linuxOS = false;
return path+"\\";
}
});
this.stopBT.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Thread thread = getThreadInstance();
if (!Thread.interrupted())
thread.interrupt();
}
});
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
buttons.add(startBT);
buttons.add(stopBT);
JPanel pathPanel = new JPanel();
pathPanel.setLayout(new BoxLayout(pathPanel, BoxLayout.LINE_AXIS));
JButton selectFoldier = new JButton("Select Foldier");
pathPanel.add(pathTF);
pathPanel.add(selectFoldier);
selectFoldier.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int returnValue = pathFC.showOpenDialog(getParent());
if (returnValue == JFileChooser.APPROVE_OPTION)
pathTF.setText(pathFC.getSelectedFile().getAbsolutePath());
}
});
this.getContentPane().setLayout(new GridLayout(0,1));
this.getContentPane().add(new JLabel("Manga download from www.mangaeden.com"));
this.getContentPane().add(new JLabel("Insert manga name:"));
this.getContentPane().add(this.mangaNameTF);
this.getContentPane().add(new JLabel("Insert manga url:"));
this.getContentPane().add(this.mangaUrlTF);
this.getContentPane().add(new JLabel("Insert path manually or click the left button"));
this.getContentPane().add(pathPanel);
this.getContentPane().add(new JLabel());
this.getContentPane().add(buttons);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
} | 7 |
public void manageCollision(Sprite sprite1, Sprite sprite2, int countFaced) {
if (oldSprite1 == null || (oldSprite1 != sprite2 || oldSprite2 != sprite1)) {
ElementField first, second;
first = Buffer.findElement(sprite1);
second = Buffer.findElement(sprite2);
TYPE type;
if (countFaced > 1) {
type = TYPE.PAIR;
} else {
type = TYPE.DEFAULT;
}
ElementField firstcopy = first.copy();
if (_countReact == 0) {
first.reactOnCollision(second, type);
}
second.reactOnCollision(firstcopy, type);
Buffer.deleteElement(firstcopy);
_countReact++;
if (_countReact == countFaced) {
_countReact = 0;
}
}
oldSprite1 = sprite1;
oldSprite2 = sprite2;
} | 6 |
public String getName() {
return name;
} | 0 |
public static int getHeadingDifference(int heading1, int heading2){
int result = heading1 - heading2;
if(result < -180)
return 360 + result;
if(result > 180)
return 0 - (360 - result);
return result;
} | 2 |
private void renderProgressBar(Screen screen) {
int lClear = linesCleared;
if (lClear < 0) {
lClear = 0;
}
int offset = HEIGHT/GOAL_LINES * lClear;
if (offset > HEIGHT) {
offset = HEIGHT;
}
screen.renderBlank(getX(), getY()+offset, WIDTH-PROGRESS_BAR_WIDTH, HEIGHT-offset, 0xff220000);
screen.renderBlank(getX(), getY()+offset, WIDTH-PROGRESS_BAR_WIDTH, 2, 0xff550000);
screen.renderBlank(getX()-PROGRESS_BAR_WIDTH, getY()+offset, PROGRESS_BAR_WIDTH, HEIGHT-offset, 0xffff0000);
} | 2 |
public String toString() {
try {
// Invoke the static toString() method of the player class
Method displayNameField = playerClass.getMethod("getType", (Class[]) null);
Player player = (Player) playerClass.newInstance();
return (String) displayNameField.invoke(player, (Object[]) null);
}
catch (IllegalAccessException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
catch (IllegalArgumentException ex) {
ex.printStackTrace();
throw ex;
}
catch (InstantiationException ex) {
// The player couldn't be instantiated
ex.printStackTrace();
throw new RuntimeException(ex);
}
catch (InvocationTargetException ex) {
// Problem calling the getType() method on the player
ex.printStackTrace();
throw new RuntimeException(ex);
}
catch (NoSuchMethodException ex) {
// The given player class doesn't have a getType() method.
// This should never happen if the class is an instance of Player.
ex.printStackTrace();
throw new RuntimeException(ex);
}
catch (SecurityException ex) {
ex.printStackTrace();
throw ex;
}
} | 6 |
public String viewErros(TablaTrans tabla) {
String result = "";
int estado_actual = 0;
for (int i = 0; i < listaToken.size(); i++) {
estado_actual = Math.abs(estado_actual); // estado anterior
estado_actual = tabla.getEstadoSiguiente(estado_actual, listaToken.get(i).getValor_token());// estado siguiente
if (estado_actual >= 1000) {// cuando hay error
return listaToken.get(i).getLexema() + "\n";
}
if (estado_actual < 0 && i == listaToken.size() - 1) { // si el recorrido se efectuo con exito
return result;
}
}
if (estado_actual >= 0 && estado_actual < 1000) { // controla esto: 3+
return "Error Sintáctico" + "\n";
}
return result;
} | 6 |
public void addElement(ValueType value) {
if (amount == 0) {
SetElement<ValueType> current = new SetElement<>(value);
head = current;
tail = current;
amount++;
} else {
if (!exist(value)) {
SetElement<ValueType> current = new SetElement<>(value);
tail.connectNext(current);
tail = current;
amount++;
}
}
} | 2 |
public static void acceptTeleportRequest( BSPlayer player ) {
if ( pendingTeleportsTPA.containsKey( player ) ) {
BSPlayer target = pendingTeleportsTPA.get( player );
target.sendMessage( Messages.TELEPORTED_TO_PLAYER.replace( "{player}", player.getDisplayingName() ) );
player.sendMessage( Messages.PLAYER_TELEPORTED_TO_YOU.replace( "{player}", target.getDisplayingName() ) );
teleportPlayerToPlayer( target, player );
pendingTeleportsTPA.remove( player );
} else if ( pendingTeleportsTPAHere.containsKey( player ) ) {
BSPlayer target = pendingTeleportsTPAHere.get( player );
player.sendMessage( Messages.TELEPORTED_TO_PLAYER.replace( "{player}", target.getDisplayingName() ) );
target.sendMessage( Messages.PLAYER_TELEPORTED_TO_YOU.replace( "{player}", player.getDisplayingName() ) );
teleportPlayerToPlayer( player, target );
pendingTeleportsTPAHere.remove( player );
} else {
player.sendMessage( Messages.NO_TELEPORTS );
}
} | 2 |
public int GetSequence()
{
return sequence;
} | 0 |
protected void stateChange(AutomataStateEvent event) {
if (event.isMove())
invalidate();
else
invalidateBounds();
} | 1 |
public static void main(String [] args) {
display.CreateDisplay.frame();
// Model model = new Model("Glass");
// model.createModel();
while(!Display.isCloseRequested()) {
switch(state){
case Main_Menu:
Menu.startup();
Menu.loop();
Menu.stop();
break;
case ThreeDeeTest:
ThreeDeeTest.startup();
ThreeDeeTest.loop();
//ThreeDeeTest.stop();
break;
case FirstPerson:
FirstPerson.startup();
FirstPerson.loop();
FirstPerson.stop();
break;
case Closing:
Closing.loop();
break;
case ModelTest:
ModelTest.main();
}
}
Closing.loop();
} | 6 |
@Override
public void keyPressedHandler(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_1) {
newWindow("A New Frame");
} else if (e.getKeyCode() == KeyEvent.VK_2) {
newDialog("A New Dialog");
} else if (e.getKeyCode() == KeyEvent.VK_3) {
newCombatVisualizer("Combat Visualizer");
}
} | 3 |
private String consumeSubQuery() {
StringBuilder sq = new StringBuilder();
while (!tq.isEmpty()) {
if (tq.matches("("))
sq.append("(").append(tq.chompBalanced('(', ')')).append(")");
else if (tq.matches("["))
sq.append("[").append(tq.chompBalanced('[', ']')).append("]");
else if (tq.matchesAny(combinators))
break;
else
sq.append(tq.consume());
}
return sq.toString();
} | 4 |
private void inOrderRec(Position<T> node) throws InvalidPositionException {
if (node != null) {
BTPosition<T> BTnode = checkPosition(node);
inOrderRec(BTnode.getLeft());
System.out.print(node.element() + " ");
inOrderRec(BTnode.getRight());
}
} | 1 |
public void input()
{
level.input();
if(Input.getKey(Input.KEY_1))
System.exit(0);
// if(Input.getKeyDown(Input.KEY_R))
// {
// AudioUtil.playMidi(playlist.get(track));
// }
} | 1 |
@Test
public void test() {
Comment fetchedComment = (Comment) MongoHelper.fetch(comment, "comments");
if(fetchedComment == null)
TestHelper.failed("comment not found");
fetchedComment.setText("Edited Text");
if(!MongoHelper.save(fetchedComment, "comments")){
TestHelper.failed("text update failed");
}
Comment updatedComment = (Comment) MongoHelper.fetch(fetchedComment, "comments");
TestHelper.asserting(fetchedComment.getText().equals(updatedComment.getText()));
System.out.println("updated comment id: " + updatedComment.getId());
TestHelper.passed();
} | 2 |
public Map<String, String> ReadMsg(int msg_id) {
Map<String, String> map = null;
String query = String.format("select msg.msg_id as msg_id, u.user_id as user_id," + " aut.username as username, message_subject, message_text" + " from %1$sprivmsgs_to msgto" + " left join %1$susers aut on msgto.author_id = aut.user_id" + " left join %1$sprivmsgs msg on msgto.msg_id = msg.msg_id" + " left join %1$susers u on msgto.user_id = u.user_id"
+ " where pm_unread = 1 and lower(u.username) like lower(?)", db_prefix);
if (msg_id != 0) {
query += " and msgto.msg_id = ?";
}
query += " order by message_time desc limit 1";
try {
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, player);
if (msg_id != 0) {
ps.setInt(2, msg_id);
}
ResultSet result = ps.executeQuery();
String[] keys = { "username", "message_subject", "message_text" };
if (result.next()) {
map = new HashMap<String, String>();
for (String key : keys) {
map.put(key, result.getString(key));
}
int user_id = result.getInt("user_id");
msg_id = result.getInt("msg_id");
ps.close();
if (map != null && map.size() > 0) {
conn.setAutoCommit(false);
query = String.format("update %sprivmsgs_to set pm_unread = 0 where msg_id = %d", db_prefix, msg_id);
Statement st = conn.createStatement();
st.executeUpdate(query);
query = String.format("update %susers", db_prefix) + " set user_new_privmsg = case when user_new_privmsg > 0 then" + " user_new_privmsg - 1 else 0 end," + " user_unread_privmsg = case when user_unread_privmsg > 0 then" + " user_unread_privmsg - 1 else 0 end where user_id = " + user_id;
st = conn.createStatement();
st.executeUpdate(query);
conn.commit();
st.close();
conn.setAutoCommit(true);
}
}
return map;
} catch (SQLException ex) {
try {
conn.rollback();
conn.setAutoCommit(true);
this.log.info("[phpbbpm] Error updating new pm number" + ex.getMessage());
} catch (SQLException ex1) {
this.log.info("[phpbbpm] rollback error. ex: " + ex.getMessage());
}
log.log(Level.WARNING, "[phpbbpm] Error getting unreaded message of " + player);
}
return null;
} | 8 |
@Override
public void onMessageReceived(Message message) {
LOG.info(message.toString());
switch (message.getType()) {
case ASK_FOR_LOCATION:
String droneId = new String(message.getPayload());
if (droneId.equals(this.drone5937.getId())) {
if(this.drone5937DispatcherThread != null){
this.drone5937DispatcherThread.resumeSendingLocation();
}
else{
this.drone5937DispatcherThread = new DispatcherThread(drone5937);
this.drone5937DispatcherThread.start();
}
} else if (droneId.equals(this.drone6043.getId())) {
if( this.drone6043DispatcherThread != null ){
this.drone6043DispatcherThread.resumeSendingLocation();
}
else{
this.drone6043DispatcherThread = new DispatcherThread(drone6043);
this.drone6043DispatcherThread.start();
}
}
break;
case TRAFFIC_REPORT: {
this.reportService.saveTrafficRepotEntry(MessageConvertor.jsonBytesArrayToObject(message.getPayload(), TrafficReportEntry.class));
}
break;
default:
LOG.info("Nothing to be done here!");
break;
}
} | 6 |
protected void addMissing(Instances data, int level,
boolean predictorMissing, boolean classMissing) {
int classIndex = data.classIndex();
Random random = new Random(1);
for (int i = 0; i < data.numInstances(); i++) {
Instance current = data.instance(i);
for (int j = 0; j < data.numAttributes(); j++) {
if (((j == classIndex) && classMissing) ||
((j != classIndex) && predictorMissing)) {
if (Math.abs(random.nextInt()) % 100 < level)
current.setMissing(j);
}
}
}
} | 7 |
public boolean debugCheckAssertOnly() {
if ( ! (status == 'O' || status == 'F' || status == 'P') ) {
return incoherenceOuTrucBizarre();
}
if ( ligneDeCaisses.caisse(numeroMem) != this ) {
return incoherenceOuTrucBizarre();
}
return true;
} | 4 |
public SelectionDrawer getDrawer() {
return drawer;
} | 0 |
public boolean validateString(String validationString, String valueName, String printName, int maxLength, boolean isRequired,
boolean isEmail, boolean isName) {
//muuttuja, joka lähetetään, validoinnin onnistuessa tai epäonnistuessa
boolean success = true;
//virheviesti
String virhe;
//jos validoitava merkkijono ylittää sallittavan pituuden
if(validationString.length() > maxLength) {
virhe = (printName + " saa olla maksimissaan " + maxLength + " merkkiä pitkä.");
//lisätään virheviesti Mapiin
virheet.addValue(valueName, virhe);
success = false;
}
if(isRequired == true) {
if(validationString.isEmpty()) {
virhe = printName + "kenttä ei saa olla tyhjä!";
virheet.addValue(valueName, virhe);
success = false;
}
}
if(isEmail == true) {
/*
* emailin tarkistuksessa tarvittava regular expression jaettuna selkeyden vuoksi kolmeen osaan:
* emailPatternNamePart sisältää lähettäjän nimen. emailPatternAddressPart sisältää @-merkin ja osoitteen.
* emailPatternDomainPart sisältää domainin*
*
* emailPatternNamePart:
* (ensimmäinen merkki iso tai pieni kirjain) +
* ((X * numeroita/kirjaimia) tai (X * numeroita/kirjaimia + (. tai -) + (väh. 1 * numeroita/kirjaimia) * X))
*
* emailPatternAddressPart:
* (@-merkki + väh. 1 * kirjaimia/numeroita) + ((X * kirjaimia/numeroita) + (. tai -) + (väh. 1 * kirjaimia/numeroita) * X)
*
* emailPatternDomainPart:
* (.) + (väh. 1 * kirjaimia)
*/
// String emailPatternNamePart = "(^[a-zA-ZäÄöÖåÅ])" + "((\\w*)|((\\w*)(\\.|-)(\\w+))*)";
// String emailPatternAddressPart = "(@(\\w+)((\\w*)(\\.|-)(\\w+))*)";
// String emailPatternDomainPart = "(\\.)([a-zA-Z]+)";
//
// String emailPattern = emailPatternNamePart + emailPatternAddressPart + emailPatternDomainPart;
//regular expressionin toimivuuden testaus
// Pattern pattern = Pattern.compile(emailPattern);
// Matcher matcher = pattern.matcher(validationString);
//
// if(matcher.find()) {
// for(int i = 0; i < matcher.groupCount(); i++) {
// System.out.println(i + " " + matcher.group(i));
// }
// }
if(!validationString.matches(".+@.+\\..+")) {
virheet.addValue(valueName, "Sähköposti on virheellinen");
success = false;
}
}
if(isName == true) {
//Katsotaan, että onko nimessä vain kirjaimia
if(!validationString.matches("[a-zA-ZäÄöÖåÅ]+((-|')*[a-zA-ZäÄöÖåÅ]+)*(\\s)*([a-zA-ZäÄöÖåÅ]+((-|')*[a-zA-ZäÄöÖåÅ]+))*")) {
virheet.addValue(valueName, "Nimi sisältää virheellisiä merkkejä tai se on väärässä muodossa!");
success = false;
}
}
//palautetaan tieto onnistumisesta tai epäonnistumisesta
return success;
} | 7 |
public Integer[] getLineWinningMove(Integer[] move, String type, int i,
String line) {
int j;
if(checkLineNeedWinning(line)) {
j = line.indexOf(" ");
} else {
return move;
}
if(type.equals("row")) {
move[0] = i; move[1] = j;
} else if(type.equals("column")) {
move[0] = j; move[1] = i;
} else if(type.equals("diagonal")) {
move[0] = j; move[1] = j;
} else if(type.equals("inverse")) {
int count = line.length();
i = (((-(j + 1) % count) + count) % count);
move[0] = j; move[1] = i;
}
return move;
} | 5 |
private void updateThisPlayerMovement(PacketBuilder packet) {
/*
* Check if the player is teleporting.
*/
if (player.isTeleporting() || player.isMapRegionChanging()) {
/*
* They are, so an update is required.
*/
packet.putBits(1, 1);
/*
* This value indicates the player teleported.
*/
packet.putBits(2, 3);
/*
* This is the new player height.
*/
packet.putBits(2, player.getLocation().getZ());
/*
* This indicates that the client should discard the walking queue.
*/
packet.putBits(1, player.isTeleporting() ? 1 : 0);
/*
* This flag indicates if an update block is appended.
*/
packet.putBits(1, player.getUpdateFlags().isUpdateRequired() ? 1
: 0);
/*
* These are the positions.
*/
packet.putBits(7,
player.getLocation().getLocalY(player.getLastKnownRegion()));
packet.putBits(7,
player.getLocation().getLocalX(player.getLastKnownRegion()));
} else {
/*
* Otherwise, check if the player moved.
*/
if (player.getSprites().getPrimarySprite() == -1) {
/*
* The player didn't move. Check if an update is required.
*/
if (player.getUpdateFlags().isUpdateRequired()) {
/*
* Signifies an update is required.
*/
packet.putBits(1, 1);
/*
* But signifies that we didn't move.
*/
packet.putBits(2, 0);
} else {
/*
* Signifies that nothing changed.
*/
packet.putBits(1, 0);
}
} else {
/*
* Check if the player was running.
*/
if (player.getSprites().getSecondarySprite() == -1) {
/*
* The player walked, an update is required.
*/
packet.putBits(1, 1);
/*
* This indicates the player only walked.
*/
packet.putBits(2, 1);
/*
* This is the player's walking direction.
*/
packet.putBits(3, player.getSprites().getPrimarySprite());
/*
* This flag indicates an update block is appended.
*/
packet.putBits(1, player.getUpdateFlags()
.isUpdateRequired() ? 1 : 0);
} else {
/*
* The player ran, so an update is required.
*/
packet.putBits(1, 1);
/*
* This indicates the player ran.
*/
packet.putBits(2, 2);
/*
* This is the walking direction.
*/
packet.putBits(3, player.getSprites().getPrimarySprite());
/*
* And this is the running direction.
*/
packet.putBits(3, player.getSprites().getSecondarySprite());
/*
* And this flag indicates an update block is appended.
*/
packet.putBits(1, player.getUpdateFlags()
.isUpdateRequired() ? 1 : 0);
}
}
}
} | 9 |
public void mouseReleased(MouseEvent e) {
if (e.isControlDown() || e.isAltDown()) {
// eyedropper mode, similar to Alt-Click in PhotoShop and Corel Paint.
updatePalettes(e);
} else if (e.isMetaDown()) {
// right-click
updateCell(e);
} else {
recenterCanvas(e);
}
updateLocale(e);
} | 3 |
@Override
public void spring(MOB target)
{
if((target!=invoker())&&(target.location()!=null))
{
if((!invoker().mayIFight(target))
||(isLocalExempt(target))
||(invoker().getGroupMembers(new HashSet<MOB>()).contains(target))
||(target==invoker())
||(doesSaveVsTraps(target)))
target.location().show(target,null,null,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("<S-NAME> avoid(s) setting off a boulder trap!"));
else
if(target.location().show(target,target,this,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("<S-NAME> trigger(s) a trap!")))
{
super.spring(target);
final int damage=CMLib.dice().roll(trapLevel()+abilityCode(),20,1);
CMLib.combat().postDamage(invoker(),target,this,damage,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|CMMsg.TYP_JUSTICE,Weapon.TYPE_BASHING,L("Dozens of boulders <DAMAGE> <T-NAME>!"));
}
}
} | 8 |
public boolean getMapVal(int i, int j)
{
if (i < 0) i = 0;
if (i >= 480) i = 479;
if (j < 0) j = 0;
if (j >= 640) j = 639;
return Map[i][j];
} | 4 |
public DataItem searchItem(String key) {
Node posNode = root;
while (true) {
if (posNode == null) {
break;
}
int itemPos;
System.out.println("================node :" + posNode.getCount());
for (itemPos = 0; itemPos < posNode.getCount(); itemPos++) {
DataItem currentItem = posNode.getDataItems()[itemPos];
System.out.println("compare key :" + currentItem.getKey());
if (key.equals(currentItem.getKey())) {
return currentItem;
} else if (key.compareTo(currentItem.getKey()) < 0) {
if (posNode.isLeaf()) {
return null;
} else {
posNode = StorageUtils.loadNode(storage, posNode.getChild()[itemPos].getStoragePointer());
break;
}
} else {
if (itemPos == posNode.getCount() - 1) {
if (posNode.isLeaf()) {
return null;
} else {
posNode = StorageUtils.loadNode(storage, posNode.getChild()[posNode.getCount()].getStoragePointer());
break;
}
}
}
}
}
return null;
} | 8 |
public static boolean lockInstance(final String lockFile) {
try {
final File file = new File(lockFile);
final RandomAccessFile randomAccessFile = new RandomAccessFile(
file, "rw");
final FileLock fileLock = randomAccessFile.getChannel().tryLock();
if (fileLock != null) {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
fileLock.release();
randomAccessFile.close();
file.delete();
} catch (Exception e) {
System.out.println("Unable to remove lock file: "
+ lockFile);
e.printStackTrace();
}
}
});
return true;
}
} catch (Exception e) {
System.out
.println("Unable to create and/or lock file: " + lockFile);
e.printStackTrace();
}
return false;
} | 3 |
public void downImage(final String imgUrl, final String folderPath,
final String fileName) {
System.out.println("开始下载图片:" + imgUrl);
File destDir = new File(folderPath);
if (!destDir.exists()) {
destDir.mkdirs();
}
pool.execute(new Runnable() {
@Override
public void run() {
HttpClient client = HttpUtil.getHttpClient();
HttpGet get = new HttpGet(imgUrl);
int failCount = 1;
do {
try {
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK && entity != null) {
byte[] data = readFromResponse(entity);
String savePaht = folderPath + fileName;
File imageFile = new File(savePaht);
FileOutputStream outStream = new FileOutputStream(
imageFile);
outStream.write(data);
outStream.close();
}
break;
} catch (Exception e) {
failCount++;
System.err.println("对于图片" + imgUrl + "第" + failCount
+ "次下载失败,正在尝试重新下载...");
} finally {
}
} while (failCount < MAX_FAILCOUNT);
}
});
} | 5 |
public static boolean maybeStraight(List<Card> sourceCards, HandCombinationSink handCombinationSink) {
final Holder<Hand> bestHandHolder = new Holder<Hand>();
CardCombinator.iterate(sourceCards, new CardCombinationCallback() {
@Override
public boolean process(List<Card> cards) {
Collections.sort(cards, new RankComparator());
int prevRankOrdinal = -1;
boolean aceFollowsKing = false;
for (final Card card : cards) {
final int newRankOrdinal = card.getRank().ordinal();
if (prevRankOrdinal >= 0 && (prevRankOrdinal + 1) != newRankOrdinal) {
// test for combination where ACE follows KING, if so -
// current card (which is second one) should be TEN, last card should be KING
if (prevRankOrdinal != Rank.ACE.ordinal() || card.getRank() != Rank.TEN) {
return false;
}
aceFollowsKing = true;
}
prevRankOrdinal = newRankOrdinal;
}
// ok, this is the straight
int rating = 0;
for (final Card card : cards) {
rating |= RATING_FLAG_MAP.get(card.getRank());
}
if (aceFollowsKing) {
final Card ace = cards.get(0);
cards.remove(0);
cards.add(ace);
} else {
// wheel combination
// the ACE rating considered as lowest one (zero) for straight flush when ACE is a leading card
rating &= ~RATING_FLAG_MAP.get(Rank.ACE);
}
if (bestHandHolder.value == null || bestHandHolder.value.getRating() < rating) {
bestHandHolder.value = new DefaultHand(rating, HandRank.STRAIGHT, cards);
}
return false;
}
}, STRAIGHT_HAND_SIZE);
return provideBestHand(bestHandHolder, handCombinationSink);
} | 9 |
protected byte[] getHeader() {
byte[] header = new byte[MINIMUM_PAGE_SIZE + numLVs];
header[0] = (byte)'O';
header[1] = (byte)'g';
header[2] = (byte)'g';
header[3] = (byte)'S';
header[4] = 0; // Version
byte flags = 0;
if(isContinue) {
flags += 1;
}
if(isBOS) {
flags += 2;
}
if(isEOS) {
flags += 4;
}
header[5] = flags;
IOUtils.putInt8(header, 6, granulePosition);
IOUtils.putInt4(header, 14, sid);
IOUtils.putInt4(header, 18, seqNum);
// Checksum @ 22 left blank for now
header[26] = IOUtils.fromInt(numLVs);
System.arraycopy(lvs, 0, header, MINIMUM_PAGE_SIZE, numLVs);
return header;
} | 3 |
public void cancelMove() {
if(canCancelMove())
willCancelMove = true;
} | 1 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((amount == null) ? 0 : amount.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((facility == null) ? 0 : facility.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((pieceOfFurniture == null) ? 0 : pieceOfFurniture.hashCode());
return result;
} | 5 |
public void doPost(HttpServletRequest req,
HttpServletResponse res)
throws IOException, ServletException {
//first goal is to be able to receive and process
//a well formatted XML move piggybacked on a POST
//this gives me a raw stream to payload of Post request
Scanner in = new Scanner(req.getInputStream());
in.useDelimiter("");
StringBuffer input = new StringBuffer();
//peel off XML message a line at a time
while (in.hasNext())
input.append(in.next());
//convert to String for convenience
String inputAsString = input.toString();
//parse the XML and marshal the java Move_Two object
Move_Two move = processInput(inputAsString);
//now create the response
PrintWriter out = res.getWriter();
//at this pont we want to return an XML document
//that represents the move "response" to one or both
//clients
/*
<moveResponse>
<status>confimed</status>
<mover> player ID here </mover>
<loc> loc value here </loc>
</moveResponse>
*/
//A good first test is to just veryify that you can
//successfully send back any XML string. From there
//building up simple response is trivial and can be
//done at the level of String building or, if you prefer,
//DOM objects converted to Strings
//test xml just to show that we can do it.
//no significance to this move definition. just mechanics.
out.println("<move> <location> " + "hello" +
"</location> </move>");
out.flush();
out.close();
} | 1 |
protected void onDisconnect()
{
int tries = 0;
while (tries < 1000 && !isConnected())
{
try
{
connect(ServerName, ServerPort, ServerPassword);
} catch (Exception e)
{
this.log("Connection attempt " + tries + " failed.");
tries++;
if (tries >= 1000000)
System.exit(0);
}
} // while
} | 4 |
public Content deprecatedTagOutput(Doc doc) {
ContentBuilder result = new ContentBuilder();
Tag[] deprs = doc.tags("deprecated");
if (doc instanceof ClassDoc) {
if (Util.isDeprecated((ProgramElementDoc) doc)) {
result.addContent(HtmlTree.SPAN(HtmlStyle.deprecatedLabel,
new StringContent(configuration.getText("doclet.Deprecated"))));
result.addContent(RawHtml.nbsp);
if (deprs.length > 0) {
Tag[] commentTags = deprs[0].inlineTags();
if (commentTags.length > 0) {
result.addContent(commentTagsToOutput(null, doc,
deprs[0].inlineTags(), false)
);
}
}
}
} else {
MemberDoc member = (MemberDoc) doc;
if (Util.isDeprecated((ProgramElementDoc) doc)) {
result.addContent(HtmlTree.SPAN(HtmlStyle.deprecatedLabel,
new StringContent(configuration.getText("doclet.Deprecated"))));
result.addContent(RawHtml.nbsp);
if (deprs.length > 0) {
Content body = commentTagsToOutput(null, doc,
deprs[0].inlineTags(), false);
if (!body.isEmpty())
result.addContent(HtmlTree.SPAN(HtmlStyle.deprecationComment, body));
}
} else {
if (Util.isDeprecated(member.containingClass())) {
result.addContent(HtmlTree.SPAN(HtmlStyle.deprecatedLabel,
new StringContent(configuration.getText("doclet.Deprecated"))));
result.addContent(RawHtml.nbsp);
}
}
}
return result;
} | 8 |
@Override
public void onDeath() {
if (Math.random() <= 0.35) // 35% prob. spawning ghost
{
boolean left = Math.random() < 0.5;
Game.world.addEntity(new Ghost(left ? 0 : Game.world.width, Game.world.height / 2), false);
}
super.onDeath();
} | 2 |
@Override
public int hashCode() {
int hash = 0;
hash += (rolidRol != null ? rolidRol.hashCode() : 0);
return hash;
} | 1 |
public void levelBuilder(){
if(Game.building){
if(input.mousePressed){
if(!input.isKeyDown(KeyEvent.VK_SHIFT)){
Tile t = new Tile((input.mouseX)/32, (input.mouseY-this.insets.top)/32, TileType.BRICK);
tiles.add(t);
t.Init(gh);
}else{
ArrayList<Tile> toRemove = new ArrayList<Tile>();
for(Tile t:this.tiles){
if(t.Position.x < input.mouseX-insets.left+insets.right && t.Position.x+32 > input.mouseX-insets.left-insets.right && (t.Position.y < input.mouseY-this.insets.top+insets.bottom && t.Position.y+32+this.insets.top+insets.bottom > input.mouseY)){
toRemove.add(t);
}
}
for(Tile t:toRemove){
tiles.remove(t);
}
}
}
}
} | 9 |
public boolean gridValid(char[][] board, int start_row, int start_column) {
int[] countPerNumber = new int[9];
clearCounts(countPerNumber);
for (int i = start_row; i < start_row + 3; i++) {
for (int j = start_column; j < start_column + 3; j++) {
if (board[i][j] != '.') {
int curInt = (int) board[i][j];
countPerNumber[curInt - 1]++;
}
}
}
return overTwoTimes(countPerNumber);
} | 3 |
@Override
public ServerModel buildCity(BuildCityRequest request, CookieParams cookie) throws InvalidMovesRequest, ClientModelException {
if(request == null) {
throw new InvalidMovesRequest("Error: invalid build city request");
}
ServerModel serverGameModel = serverModels.get(cookie.getGameID());
//execute
int playerIndex = request.getPlayerIndex();
Player player = serverGameModel.getPlayers().get(playerIndex);
int x = request.getCityLocation().getX();
int y = request.getCityLocation().getY();
String direction = request.getCityLocation().getDirectionStr();
City city = new City(playerIndex, x, y , direction);
serverGameModel.getMap().getCities().add(city);
serverGameModel.incrementVersion();
ArrayList<Settlement> settlements = serverGameModel.getMap().getSettlements();
for (int i = 0; i < settlements.size(); i++) {
VertexLocation loc = settlements.get(i).getLocation().getNormalizedLocation();
if (settlements.get(i).getLocation().getHexLoc().getX() == x &&
settlements.get(i).getLocation().getHexLoc().getY() == y &&
settlements.get(i).getLocation().getDir().getDirectionStr().equals(direction)) {
settlements.remove(i);
break;
}
if (loc.getHexLoc().getX() == x &&
loc.getHexLoc().getY() == y &&
loc.getDir().getDirectionStr().equals(direction)) {
settlements.remove(i);
break;
}
}
player.decrementCities();
player.incrementVictoryPoints();
player.incrementSettlements();
//3 ore 2wheat
int newOre = player.getResources().getOre() - 3;
int newWheat = player.getResources().getWheat() - 2;
player.getResources().setOre(newOre);
player.getResources().setWheat(newWheat);
serverGameModel.getBank().ore += 3;
serverGameModel.getBank().wheat += 2;
checkForWinner(serverGameModel,playerIndex);
return serverGameModel;
} | 8 |
@Test
public void testBook() throws Exception {
//Create query arguments. TicketQueryArgs is used for external client with human readable parameters.
TicketQueryArgs query = new TicketQueryArgs();
query.setDate(LocalDate.now());
query.setDepartureStation("北京南");
query.setDestinationStation("南京南");
query.setTrainNumber("G101");
query.setSeatType(-1);
query.setCount(1);
TestTicketPool pool = this.createTicketPool();
//Because book is the only operation which may change data, so in the future, toTicketPoolQueryArgs, book and toTicket will
//be executed by different disruptor consumers.
//Convert query to pool query. pool query is only used inside pool system and holds seat, train as ids or java references.
TicketPoolQueryArgs poolQuery = pool.toTicketPoolQueryArgs(query);
TicketPoolTicket[] poolTickets = pool.book(poolQuery);
//Convert pool ticket to human readable ticket.
Ticket[] tickets = pool.toTicket(poolTickets);
Assert.assertEquals(1, tickets.length);
Ticket ticket = tickets[0];
Assert.assertEquals(LocalDate.now(), ticket.getDepartureDate());
Assert.assertEquals("北京南", ticket.getDepartureStation());
Assert.assertEquals("南京南", ticket.getDestinationStation());
Assert.assertEquals("G101", ticket.getTrainNumber());
} | 0 |
private void generateCallArgArray(Node node, Node argChild, boolean directCall)
{
int argCount = 0;
for (Node child = argChild; child != null; child = child.getNext()) {
++argCount;
}
// load array object to set arguments
if (argCount == 1 && itsOneArgArray >= 0) {
cfw.addALoad(itsOneArgArray);
} else {
addNewObjectArray(argCount);
}
// Copy arguments into it
for (int i = 0; i != argCount; ++i) {
// If we are compiling a generator an argument could be the result
// of a yield. In that case we will have an immediate on the stack
// which we need to avoid
if (!isGenerator) {
cfw.add(ByteCode.DUP);
cfw.addPush(i);
}
if (!directCall) {
generateExpression(argChild, node);
} else {
// If this has also been a directCall sequence, the Number
// flag will have remained set for any parameter so that
// the values could be copied directly into the outgoing
// args. Here we want to force it to be treated as not in
// a Number context, so we set the flag off.
int dcp_register = nodeIsDirectCallParameter(argChild);
if (dcp_register >= 0) {
dcpLoadAsObject(dcp_register);
} else {
generateExpression(argChild, node);
int childNumberFlag
= argChild.getIntProp(Node.ISNUMBER_PROP, -1);
if (childNumberFlag == Node.BOTH) {
addDoubleWrap();
}
}
}
// When compiling generators, any argument to a method may be a
// yield expression. Hence we compile the argument first and then
// load the argument index and assign the value to the args array.
if (isGenerator) {
short tempLocal = getNewWordLocal();
cfw.addAStore(tempLocal);
cfw.add(ByteCode.CHECKCAST, "[Ljava/lang/Object;");
cfw.add(ByteCode.DUP);
cfw.addPush(i);
cfw.addALoad(tempLocal);
releaseWordLocal(tempLocal);
}
cfw.add(ByteCode.AASTORE);
argChild = argChild.getNext();
}
} | 9 |
public static int getPlatform()
{
String osName = System.getProperty("os.name").toLowerCase();
if(osName.contains("win")) return 2;
if(osName.contains("mac")) return 3;
if(osName.contains("solaris")) return 1;
if(osName.contains("sunos")) return 1;
if(osName.contains("linux")) return 0;
if(osName.contains("unix")) return 0;
return 4;
} | 6 |
public void setAlstromeria(int alstromeria) {
this.alstromeria = alstromeria;
} | 0 |
public static boolean cambiarLetrasOrden(char[] pActual, char[] pNueva) throws Exception {
char [] abecedario = "abcdefghijklmnopqrstuvwxyz".toCharArray();
int [] comprobarPActual = new int[abecedario.length];
int [] comprobarPNueva = new int[abecedario.length];
int contador = 0;
for (int i = 0; i < pActual.length; i++) {
for (int j = 0; j < comprobarPActual.length; j++) {
if (pActual[i] == abecedario[j]) {
comprobarPActual[j]++;
}
}
}
for (int i = 0; i < pNueva.length; i++) {
for (int j = 0; j < comprobarPNueva.length; j++) {
if (pNueva[i] == abecedario[j]) {
comprobarPNueva[j]++;
}
}
}
for (int i = 0; i < comprobarPActual.length; i++) {
if (comprobarPActual[i] == comprobarPNueva[i]) {
contador = contador + comprobarPActual[i];
}
}
if (contador == pActual.length) {
puntuacion = puntuacion + 5;
return true;
}
return false;
} | 9 |
@Override
public boolean checkGrammarTree(GrammarTree grammarTree,
SyntaxAnalyser syntaxAnalyser) throws GrammarCheckException {
syntaxAnalyser.setOperionName("slice");
GrammarTree tree = grammarTree.getSubNode(0);
if (tree == null
|| (tree.getSiblingAmount() != 1 && tree.getSiblingAmount() != 3)) {
GrammarCheckException exception = new GrammarCheckException(
"Error: the 'slice' subsentence is not format");
syntaxAnalyser.addErrorMsg(exception.getMessage());
throw exception;
}
checkToken(tree, TokenType.IDENTIFIER, null, true, syntaxAnalyser);
String dimensionName = tree.getValue().getToken();
syntaxAnalyser.addDimensionLevelInfo(dimensionName, "");
if (tree.hasNext()) {
tree = tree.next();
checkToken(tree, TokenType.KEYWARD, "as", true, syntaxAnalyser);
tree = tree.next();
checkToken(tree, TokenType.IDENTIFIER, null, true, syntaxAnalyser);
String dimensionNickname = tree.getValue().getToken();
syntaxAnalyser.addDimensionNickName(dimensionName, dimensionNickname);
}else{
}
return true;
} | 4 |
public int compareTo(final ComparableNumber o) {
if (number.getClass().equals(o.getNumber().getClass())) {
return ((Comparable) number).compareTo((Comparable) o.getNumber());
} else {
return new Double(number.doubleValue()).compareTo(o.getNumber().doubleValue());
}
} | 1 |
private static void readFromFile(String filename) throws IOException {
BufferedReader br = null;
String line;
if(filename == null){
System.out.println("No file path specified!");
return;
}
File AddFile = new File(filename);
if(!AddFile.exists())
{
System.out.println("File " + filename + " not found!");
return;
}
try
{
FileInputStream file = new FileInputStream(new File(filename));
InputStreamReader InputReader = new InputStreamReader(file);
br = new BufferedReader(InputReader);
while((line = br.readLine()) != null){
String[] tokens = line.split(",");
if(tokens.length == 3){
int bit1 = Integer.parseInt(tokens[0]) & (int)Math.pow(2, Integer.parseInt(tokens[1])-1);
int bit2 = Integer.parseInt(tokens[0]) & (int)Math.pow(2, Integer.parseInt(tokens[2])-1);
if( (bit1>0 && bit2>0) || (bit1 == bit2))
System.out.println("true");
else
System.out.println("false");
//System.out.println("" + bit1 + " " + bit2);
}
else{
System.out.println("ERROR: Incorrect formatting");
}
}
}
finally{
br.close();
}
} | 7 |
public void createMapping(Class<?> aClass) throws ClassValidationException {
CSVEntity annotation = aClass.getAnnotation(CSVEntity.class);
if (annotation == null) {
logger.severe("Class " + aClass.getName() + " is not annotated with " + CSVEntity.class.getName() + " annotation");
return;
}
if (!classMapping.containsKey(aClass)) {
MappingRules mappingRules = new MappingRules();
Field[] fields = aClass.getDeclaredFields();
for (Field f : fields) {
//omit ignored fields
if(f.isAnnotationPresent(CSVFieldIgnore.class)) {
continue;
}
String csvFieldName = f.getName();
if (f.isAnnotationPresent(CSVField.class)) {
String annotatedName = f.getAnnotation(CSVField.class).csvFieldName();
if (!"".equals(annotatedName)) {
csvFieldName = annotatedName;
}
}
mappingRules.addMapping(f, csvFieldName);
logger.log(Level.INFO, ("Added mapping class: " + aClass.getName() + ": " + f.getName() + " <-> " + csvFieldName));
}
classMapping.put(aClass, mappingRules);
} else {
logger.log(Level.WARNING, "Class {0} is already present in mapping", aClass.getName());
}
} | 7 |
public void renderBackground() {
for(int c = 0; c < 25; c++) {
if(c == 0) {
batch.draw(groundTiles[0], c * 32, 0);
}
else {
batch.draw(groundTiles[1], c * 32, 0);
}
}
for(int r = 1; r < 4; r++) {
for(int c = 0; c < 25; c++) {
batch.draw(backgroundLight, c * 32, r * 32);
}
}
for(int c = 0; c < 25; c++) {
batch.draw(backgroundTransition, c * 32, 32 * 4);
}
for(int r = 9; r < 20; r++) {
for(int c = 0; c < 25; c++) {
batch.draw(backgroundDark, c * 32, r * 32);
}
}
} | 7 |
@MethodAnnotation
public void doNothing()
{
} | 0 |
private void btn_aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_aceptarActionPerformed
if (lab_modo.getText().equals("Alta")){
if (camposCompletos()){
ocultar_Msj();
insertar();
menuDisponible(true);
modoConsulta();
updateTabla();
}
else{
mostrar_Msj_Error("Por favor, complete todos los campos solicitados");
}
}
else{
if (lab_modo.getText().equals("Baja")){
if (!field_id_loc.getText().equals("")){
if(!existe(Integer.parseInt(field_id_loc.getText()))){
mostrar_Msj_Error("Ingrese una ID que se encuentre registrado en el sistema");
field_id_loc.requestFocus();
}
else{
ocultar_Msj();
eliminar();
menuDisponible(true);
modoConsulta();
vaciarCampos();
updateTabla();
}
}
else{
mostrar_Msj_Error("Por favor, complete todos los campos solicitados");
}
}
else{
if (lab_modo.getText().equals("Modificación")){
if (!field_id_loc.getText().equals("")){
if(!existe(Integer.parseInt(field_id_loc.getText()))){
mostrar_Msj_Error("Ingrese una ID que se encuentre registrado en el sistema");
field_id_loc.requestFocus();
}
else{
if (camposCompletos()){
ocultar_Msj();
modificar();
menuDisponible(true);
modoConsulta();
updateTabla();
}
else{
mostrar_Msj_Error("Por favor, complete todos los campos solicitados");
}
}
}
else{
mostrar_Msj_Error("Por favor, complete todos los campos solicitados");
}
}
}
}
}//GEN-LAST:event_btn_aceptarActionPerformed | 9 |
public String saveOrder() throws Exception {
String ret = "";
orderSQL = "INSERT INTO ORDERS(BUYER_NAME,";
orderSQL += " SHIPPING_ADRESS, SHIPPING_ZIPCODE, SHIPPING_CITY)";
orderSQL += " VALUES(?,?,?,?)";
try {
// load the driver and get a connection
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url);
// turn off autocommit to handle transactions yourself
con.setAutoCommit(false);
orderPstmt = con.prepareStatement(orderSQL);
orderPstmt.setString(1, buyerName);
orderPstmt.setString(2, shippingAddress);
orderPstmt.setString(3, shippingZipcode);
orderPstmt.setString(4, shippingCity);
orderPstmt.execute();
// now handle all items in the cart
ret = saveOrderItems();
sb.clear();
if (ret.equals("")) {
con.commit();
} else {
con.rollback(); // end the transaction
}
} catch (Exception e) {
try {
con.rollback(); // failed, rollback the database
} catch (Exception ee) {
}
throw new Exception("Error saving Order", e);
} finally {
try {
rs.close();
} catch (Exception e) {
}
try {
stmt.close();
} catch (Exception e) {
}
try {
orderPstmt.close();
} catch (Exception e) {
}
try {
orderItemPstmt.close();
} catch (Exception e) {
}
try {
con.close();
} catch (Exception e) {
}
}
return ret;
} | 8 |
public void imprimeArbol(Nodo E){
if(E==null) return;
ArrayDeque<Nodo> currentlevel,nextlevel;
currentlevel=new ArrayDeque<Nodo>();
nextlevel=new ArrayDeque<Nodo>();
currentlevel.add(E);
while(!currentlevel.isEmpty()){
Nodo currNode=currentlevel.poll();
if(currNode!=null){
for(int i=0;i<currNode.tamSangria;i++) System.out.print(" ");
currNode.muestra();
if(currNode.izq!=null){
currNode.izq.tamSangria=currNode.tamSangria+1;
nextlevel.add(currNode.izq);
}
if(currNode.der!=null){
currNode.der.tamSangria=currNode.tamSangria+1;
nextlevel.add(currNode.der);
}
if(currNode.sig!=null){
currNode.sig.tamSangria=currNode.tamSangria+1;
nextlevel.add(currNode.sig);
}
}
if(currentlevel.isEmpty()){
System.out.println();
ArrayDeque<Nodo> c;
c=currentlevel;
currentlevel=nextlevel;
nextlevel=c;
}
}
} | 8 |
public static void main(String[] args) {
CommandLineParser parser = new DefaultParser();
Options options = new Options();
final Logger logger = LoggerFactory.getLogger(Application.class);
logger.info("Application for generating web-pages");
options.addOption("m", "metrics", false, "Activate metrics");
options.addOption("p", "properties", true, "Enable your properties");
options.addOption(Option.builder("f")
.numberOfArgs(2)
.argName("in-folder out-folder")
.required()
.desc("required two folders")
.build());
options.addOption("d", "dry run", false, "Enable dry run");
try {
CommandLine commandLine = parser.parse(options, args);
if (commandLine.hasOption("f")) {
final File inFolder = new File(commandLine.getOptionValues("f")[0]);
final File outFolder = new File(commandLine.getOptionValues("f")[1]);
if (!inFolder.isDirectory()) {
logger.error("Input folder does not exist: "
+ inFolder.getAbsolutePath());
System.exit(1);
}
if (!outFolder.isDirectory()) {
logger.error("Output folder does not exist: "
+ outFolder.getAbsolutePath());
System.exit(1);
}
try {
String settingsName;
if (commandLine.hasOption("p")) {
settingsName = commandLine.getOptionValue("p");
} else {
settingsName = MAIN_PROPERTIES;
}
boolean dryRun = false;
if (commandLine.hasOption("d")) {
dryRun = true;
}
FilesystemWalker app = new FilesystemWalker(settingsName, dryRun);
if (commandLine.hasOption("m")) {
app.activateMetrics();
}
app.processFolder(inFolder, outFolder.getAbsolutePath(), false);
} catch (IOException ex) {
logger.error("Fail: ", ex);
}
}
} catch (ParseException ex) {
logger.error("Fail, parse error: ", ex);
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("web-template", options);
}
} | 8 |
public BigInteger getNumberOfTransactions() {
return numberOfTransactions;
} | 0 |
static byte[] getImage(OP code) {
int retID=code.resID;
ClassFile cf=(ClassFile)cf_orig.clone();
// set return type
int otsize=cf.tsize;
cf.tsize=retID_patchback;
cf.write((byte)retID);
cf.tsize=otsize;
String retName;
if ((retID<8))
retName=OP.specialTypes[20+retID].getName();
else if (retID==9)
retName="java.lang.Void";
else
retName=code.resType.getName();
// set return class
otsize=cf.tsize;
cf.tsize=retIDC_patchback;
cf.writeShort(cf.getIndex(retName,8));
cf.tsize=otsize;
// add the evaluate method
cf.newMethod(eval_methods[retID],null);
code.compile(cf);
return cf.getImage();
}; | 2 |
@Test
public void addBookingTest() {
Student s = null;
try {
s = familyService.findStudent(3);
} catch (InstanceNotFoundException e) {
assertTrue("Student not found", false);
}
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Calendar cb = Calendar.getInstance();
try {
cb.setTime(sdf.parse("27/10/2014"));
} catch (ParseException e) {
assertTrue("Bad format to calendar", false);
}
try {
bookingService.create(new Booking(cb, s, bookingService
.getDiningHall().get(0)));
} catch (DuplicateInstanceException | MaxCapacityException e) {
assertTrue("Booking has already been created", false);
} catch (NotValidDateException e) {
e.printStackTrace();
}
Student ss = null;
try {
ss = bookingService.find(2).getStudent();
assertEquals(ss, s);
assertEquals(bookingService.find(2).getDate(), cb);
assertEquals(bookingService.find(2).getDiningHall(), bookingService
.getDiningHall().get(0));
} catch (InstanceNotFoundException e) {
assertTrue("Booking not found", false);
}
} | 5 |
private void placeNewOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_placeNewOrderButtonActionPerformed
// TODO add your handling code here:
// When place order button is pushed
// Check if subtotal and totals have been changed
if (!"£0.00".equals(subTotLabel.getText()) && !"£0.00".equals(totalLabel.getText()))
{
// if subtotal and total fields have been updated - place order
ArrayList<String[]> suppliers = new ArrayList<>();
for (int x = 0; x < orderTable.getRowCount(); x++ )
{
if (orderTable.getValueAt(x, 5) != null) {
String[] orderInfo = {orderTable.getValueAt(x, 5).toString(),orderTable.getValueAt(x, 0).toString(),orderTable.getValueAt(x, 4).toString()};
suppliers.add(orderInfo);
//showMessageDialog(null, orderLines.get(x)); - DEBUG
}
}
Comparator<String[]> arrayCompare = new Comparator<String[]>() {
public int compare(String[] first, String[] second) {
return first[0].compareTo(second[0]);
}
};
suppliers.sort(arrayCompare);
int currentOrder = -1;
String lastSupplier = "";
Helper.openConnection();
for (String[] supply: suppliers)
{
// create order if needed
if(!supply[0].equals(lastSupplier) )
{
String query = "insert into torder Values(default,now(),'Raised','" + loginID + "',(select supplier_id from tsupplier where name ='" + supply[0] + "'),'')";
Helper.updateDatabase(query);
String selectQuery = "select last_insert_id()";
ResultSet rs = Helper.selectFromDatabase(selectQuery);
try
{
while (rs.next())
{
currentOrder = rs.getInt(1);
}
}
catch (Exception ex)
{
}
}
//set current supplier to last supplier
lastSupplier = supply[0];
//Insert orderline
String query = "insert into torder_line Values (" + currentOrder + ",'" + supply[1] + "'," + Integer.parseInt(supply[2]) + ")";
Helper.updateDatabase(query);
}
Helper.closeConnection();
showMessageDialog(null, "New Order Created.");
// return to and update notifications
//Clear order form
// Create defaultTableModel object
DefaultTableModel dm = (DefaultTableModel)orderTable.getModel();
// Clear displayed table of contents
dm.getDataVector().removeAllElements();
// set row count back to 100
dm.setRowCount(100);
// Update table
dm.fireTableDataChanged();
// clear results table
//Create an empty string to query database so all products are displayed when order form is reopened
//open connection to database
Helper.openConnection();
String value = "";
ResultSet rs = Helper.searchAllByKey(value);
// populate results table to show search results
Helper.populateTable(resultsTable, rs);
// close connection to database
Helper.closeConnection();
// clear search field
orderSearchText.setText("");
// Return user to the notifications screen.
newOrderPanel.setVisible(false);
pendingOrderPanel.setVisible(false);
reportPanel.setVisible(false);
searchProductPanel.setVisible(false);
notificationPanel.setVisible(true);
adminPanel.setVisible(false);
passwordPanel.setVisible(false);
updateNotifications();
}
// else advise user that they need to add an item to order before it can be placed.
else
{
showMessageDialog(null, "You must add a product to the order before placing the order!");
}
}//GEN-LAST:event_placeNewOrderButtonActionPerformed | 8 |
static List<UnixTimeInterval> parseIntervals(Map<String, Object> params) {
List<UnixTimeInterval> intervals = new ArrayList<UnixTimeInterval>();
Integer intervalIndex = null;
Boolean isStart = null;
UnixTimeInterval interval = null;
for(String key : params.keySet()) {
intervalIndex = null;
interval = null;
Matcher startMatcher = startPattern.matcher(key);
isStart = startMatcher.matches();
if(isStart) {
intervalIndex = Integer.parseInt(startMatcher.group(1));
} else {
Matcher endMatcher = endPattern.matcher(key);
if(endMatcher.matches()) {
intervalIndex = Integer.parseInt(endMatcher.group(1));
}
}
if(intervalIndex != null) {
if(intervals.size() < intervalIndex) {
interval = new UnixTimeInterval();
intervals.add(interval);
} else {
interval = intervals.get(intervalIndex-1);
}
Long value = (Long)params.get(key);
if(isStart) {
interval.setStart(value);
} else {
interval.setEnd(value);
}
}
}
Collections.sort(intervals);
return intervals;
} | 6 |
private void updateEnemies() {
for (int i = 0; i < enemyList.size(); i++) {
enemyList.get(i).update();
if (enemyList.get(i).isArrived() || enemyList.get(i).isDestroyed()) {
if (enemyList.get(i).isDestroyed()) {
GameInstance.credits += enemyList.get(i).getValue();
GameFrame.creditsLabel.setText("Credits: " + GameInstance.credits);
}
if (enemyList.get(i).isArrived()) {
gameOver = true;
}
map.clearEnemy(enemyList.get(i));
enemyList.remove(i);
i--;
}
}
} | 5 |
protected void runLoop2() {
int numKeys = 0;
try {
log.info("going into selector");
numKeys = selector.select();
log.info("coming out with keys="+numKeys);
} catch (IOException e) {
log.log(Level.WARNING, "Having trouble with a channel", e);
}
Set<SelectionKey> keySet = selector.selectedKeys();
Iterator<SelectionKey> iter = keySet.iterator();
while (iter.hasNext()) {
try {
SelectionKey theKey = iter.next();
log.info("in loop iter.next="+theKey+" isVal="+theKey.isValid()+" acc="
+theKey.isAcceptable()+" read="+theKey.isReadable());
if(theKey.isAcceptable()) {
SocketChannel temp = server.accept();
if(temp != null) {
serverChannel = temp;
serverChannel.configureBlocking(false);
log.info("register serverChannel");
serverChannel.register(selector, SelectionKey.OP_READ);
}
} else if(theKey.isReadable()) {
log.info("reading bytes");
buf.clear();
int bytes = serverChannel.read(buf);
log.info("read bytes="+bytes);
iter.remove();
if(bytes < 0)
theKey.cancel();
//keySet.remove(theKey);
synchronized(client) {
log.info("waiting for write");
receivedWrite = true;
client.notify();
}
synchronized(client) {
log.info("received write but not close yet, wait for client to call close");
if(!closeHappened)
client.wait();
}
log.info("done waiting for close, it happened");
}
} catch(Throwable e) {
log.log(Level.WARNING, "Processing of key failed, but continuing channel manager loop", e);
}
}
keySet.clear();
} | 8 |
public Result combine(EvaluationCtx context, List parameters,
List policyElements) {
boolean atLeastOne = false;
AbstractPolicy selectedPolicy = null;
Iterator it = policyElements.iterator();
while (it.hasNext()) {
AbstractPolicy policy =
((PolicyCombinerElement)(it.next())).getPolicy();
// see if the policy matches the context
MatchResult match = policy.match(context);
int result = match.getResult();
// if there is an error in trying to match any of the targets,
// we always return INDETERMINATE immediately
if (result == MatchResult.INDETERMINATE)
return new Result(Result.DECISION_INDETERMINATE,
match.getStatus(),
context.getResourceId().encode());
if (result == MatchResult.MATCH) {
// if this isn't the first match, then this is an error
if (atLeastOne) {
List code = new ArrayList();
code.add(Status.STATUS_PROCESSING_ERROR);
String message = "Too many applicable policies";
return new Result(Result.DECISION_INDETERMINATE,
new Status(code, message),
context.getResourceId().encode());
}
// if this was the first applicable policy in the set, then
// remember it for later
atLeastOne = true;
selectedPolicy = policy;
}
}
// if we got through the loop and found exactly one match, then
// we return the evaluation result of that policy
if (atLeastOne)
return selectedPolicy.evaluate(context);
// if we didn't find a matching policy, then we don't apply
return new Result(Result.DECISION_NOT_APPLICABLE,
context.getResourceId().encode());
} | 5 |
private void installApplication_androidButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_installApplication_androidButtonActionPerformed
if (selectedDevice != null)
new InstallApplicationMenu(logger, debug, adbController, settings, parser, selectedDevice).setVisible(true);
else
logger.log(Level.ERROR, " [Application Installer] No device was selected. Please select a device and try again...");
}//GEN-LAST:event_installApplication_androidButtonActionPerformed | 1 |
public void deleteElement(String value) {
int codeValue = Math.abs(value.hashCode() % length);
if (exists(value)) {
hashTable[codeValue].deleteElement(value);
}
} | 1 |
private static boolean unitTestParseAssemble (
String test_url
) {
MuteableURL m_url = new MuteableURL(test_url);
String result = m_url.getURLString();
System.out.println("TEST URL: " + test_url);
System.out.println(" RESULT: " + result);
if (test_url == null) {
System.out.println("INVALID TEST: NULL");
System.out.println("");
return false;
} else if (test_url.equals(result)) {
System.out.println("PASSED");
System.out.println("");
return true;
} else {
System.out.println("--FAILED");
System.out.println("");
return false;
}
} | 2 |
private final void waitForButton(
@SuppressWarnings("hiding") final String text) {
try {
synchronized (Button.class) {
if (this.master.isInterrupted()) {
return;
}
revalidate(true, true);
this.pressed = null;
if (Thread.currentThread() != this.master) {
this.master.interrupt();
}
Button.class.wait();
if (this.master.isInterrupted()) {
destroy();
}
}
} catch (final InterruptedException e) {
this.master.interrupt();
}
if (this.pressed == Button.ABORT) {
destroy();
}
this.mainFrame.getContentPane().removeAll();
this.mainFrame.add(this.wait);
this.wait.setText(text);
revalidate(true, false);
} | 5 |
public static Res cResultHelper(String expr) {
// the helper function return number of true combination
// as well as the number of false combination
// do some string parsing
int n = expr.length() / 2 + 1; // number of bit
Res[][] s = new Res[n][n];
// initialize the table
for ( int d = 0 ; d != n; ++d ){
if ( expr.charAt(d * 2) == '1' ) {
s[d][d] = new Res(1, 0);
} else {
s[d][d] = new Res(0, 1);
}
}
// compute the table from bottom up
for ( int l=2; l <= n; ++l ) {
// l indicates the length expr we want to compute
for (int i=0; i <= n-l; ++i) {
// i is the start position of the sub expr
// the index of sub is i -> i+l-1
Res ret = new Res(0, 0);
for ( int j=0; j != l-1; ++j) {
ret.add(combine ( s[i][i+j], s[i+j+1][i+l-1], expr.charAt((i+j)*2 +1) ));
}
// System.out.println(String.format("computing %d -> %d, #t: %d #f: %d", i,i+l-1,ret.cTrue,ret.cFalse));
s[i][i+l-1] = ret;
}
}
return s[0][n-1];
} | 5 |
private void remove(int i) {
if (i == 1) {
firstElement = firstElement.getNextElement();
} else if (i > 1) {
Element tmpf = firstElement;
Element tmps = firstElement.getNextElement();
Element tmpt = firstElement.getNextElement().getNextElement();
int count = 2;
while (tmpt.getNextElement() != null) {
if (count == i) {
tmpf.setNextElement(tmpt);
return;
}
tmpf = tmps;
tmps = tmpt;
tmpt = tmpt.getNextElement();
count++;
}
if (i == count + 1) {
tmps.setNextElement(null);
}
}
} | 5 |
public void act(){
if (show){
if (counter >= 2){
counter = 0;
trans -= 30;
if (trans >= 0){
bg.setTransparency (trans);
}
else{
m.removeObject (this);
}
}
else{
counter++;
}
this.setImage (bg);
}else{
this.setImage (blank);
}
} | 3 |
public int varianceLookback( int optInTimePeriod,
double optInNbDev )
{
if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) )
optInTimePeriod = 5;
else if( ((int)optInTimePeriod < 1) || ((int)optInTimePeriod > 100000) )
return -1;
if( optInNbDev == (-4e+37) )
optInNbDev = 1.000000e+0;
else if( (optInNbDev < -3.000000e+37) || (optInNbDev > 3.000000e+37) )
return -1;
return optInTimePeriod-1;
} | 6 |
protected int partition(int attIdx, int[] index, int l, int r) {
double pivot = m_Instances.instance(index[(l + r) / 2]).value(attIdx);
int help;
while (l < r) {
while ((m_Instances.instance(index[l]).value(attIdx) < pivot) && (l < r)) {
l++;
}
while ((m_Instances.instance(index[r]).value(attIdx) > pivot) && (l < r)) {
r--;
}
if (l < r) {
help = index[l];
index[l] = index[r];
index[r] = help;
l++;
r--;
}
}
if ((l == r) && (m_Instances.instance(index[r]).value(attIdx) > pivot)) {
r--;
}
return r;
} | 8 |
public void refresh() {
for (int iteration = 0; iteration < panes.size(); iteration++) {
final Pane pane = panes.get(iteration);
pane.refresh();
//need to fix issue with small panes (index out of range)
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (pane.buffer[x][y] != null) {
screen.putCharacter(x, y, pane.buffer[x][y]);
}
}
}
}
screen.refresh();
} | 4 |
public void compExecTime() {
double newExeTime;
double newCost;
dEval = 0;
dTime = 0;
dCost = 0;
for (int i = 0; i < iClass; i++) {
newExeTime = 0;
// System.out.print("Cost[" + i + "]");
for (int j = 0; j < iSite; j++) {
if (dmAlloc[i][j] != -1) {
if (dmAlloc[i][j] < 1) {
newExeTime = 0;
} else {
newExeTime = (dmDist[i][j] * dmPrediction[i][j])
/ dmAlloc[i][j];
if (newExeTime > dDeadline + 1) {
newExeTime = Double.MAX_VALUE;
}
}
}
if (newExeTime > dDeadline + 1) {
// System.out.println("newExeTime - dDeadline="+ (newExeTime
// - dDeadline -1));
newCost = Double.MAX_VALUE;
} else {
newCost = dmDist[i][j] * dmPrediction[i][j]
* daPrice[j];
}
dTime += newExeTime;
dCost += newCost;
dEval += dmCost[i][j] - dCost;
dmExeTime[i][j] = newExeTime;
dmCost[i][j] = newCost;
// System.out.print(dmCost[i][j] + ", ");
}
// System.out.println();
}
for (int i = 0; i < iClass; i++) {
System.out.print("Time[" + i + "]");
for (int j = 0; j < iSite; j++) {
System.out.print(dmExeTime[i][j] + ", ");
}
System.out.println();
}
// System.out.println("AllTime = " + dTime + " AllCost = " + dCost);
// System.out.println();
} | 8 |
public void moveHuman(final Direction dir,
final ActionListener terrifyHumanCallback,
final ActionListener healHumanCallback)
{
if (maze.hasDoorAt(dir, location))
{
location = new Location(location, dir);
invader.pickupStrategy(maze.getStrategy(location));
maze.visit(location);
stopAttackingHuman();
if (citizen != null && shouldHealGruman)
{
startHealingGruman();
}
final Gruman oldCitizen = citizen;
citizen = maze.getGruman(location);
if (citizen != null)
{
stopHealingHuman();
startAttackingHuman(terrifyHumanCallback);
}
else if (oldCitizen != null && shouldHealHuman) // citizen went from
// non-null to null
{
startHealingHuman(healHumanCallback);
}
}
updateStatus();
} | 6 |
public void draw(Graphics g, boolean filled) {
g.setColor(myColor);
if (filled) {
g.fillOval(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
} else {
g.drawOval(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
}
} | 1 |
public Node getNode(String idRef) throws IDrefNotInSentenceException {
if (terminals.containsKey(idRef))
return terminals.get(idRef);
else if (nonterminals.containsKey(idRef))
return nonterminals.get(idRef);
else throw new IDrefNotInSentenceException("idRef: " + idRef + " not in Sentence: " + getId());
} | 2 |
@Override
public void displayAllStates(List<GameState> AllStates){
final String newline = "<br>";
String output = "<html>";
for(GameState gameState: AllStates){
int[] PlayerRoles = gameState.AllPlayers();
for(int i = 0; i < PlayerRoles.length; i++){
output += "(" + (i+1) + " " + RunFileGame.getPlayerName(i+1);
if(PlayerRoles[i] < 0) output += " Dead";
switch(PlayerRoles[i]){
case 1: output += " Villager";
break;
case 2: output += " Seer";
break;
case -1: output += " Villager";
break;
case -2: output += " Seer";
break;
}
if(PlayerRoles[i] >= 3) output += " " + (PlayerRoles[i] - 2) + "-Wolf";
if(PlayerRoles[i] <= -3) output += " " + (-1 * (PlayerRoles[i] + 2)) + "-Wolf";
output += ")";
}
output += newline;
}
output += "</html>";
JScrollPane ScrPane = new JScrollPane(new JLabel(output));
final JDialog dialog = new JDialog(null, "Quantum Werewolves", Dialog.ModalityType.APPLICATION_MODAL);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setLocationRelativeTo(null);
JPanel somePanel = new JPanel();
somePanel.setLayout(new BorderLayout());
somePanel.add(new JLabel("This is a list of all currently possible gamestates:"),BorderLayout.NORTH);
somePanel.add(ScrPane, BorderLayout.CENTER);
JButton button = new JButton("Ok");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dialog.setVisible(false);
}
});
somePanel.add(button, BorderLayout.SOUTH);
dialog.add(somePanel);
dialog.pack();
dialog.setSize(new Dimension(600,325));
somePanel.setSize(new Dimension(600,300));
somePanel.setMaximumSize(new Dimension(600,300));
ScrPane.setMaximumSize(new Dimension(600,300));
ScrPane.setPreferredSize(new Dimension(600,300));
somePanel.setPreferredSize(new Dimension(600,300));
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
} | 9 |
public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
} | 9 |
static void client_server_closes() {
final TCPClientLoop client_loop = new TCPClientLoop();
client_loop.start();
Callback.TCPClient client = new Callback.TCPClient() {
public void onConnect (TCPClientLoop l, SocketChannel sc) {
assert(l == client_loop);
byte [] bytes = new byte[NUM2];
bytes[0] = 0x02;
numWritten = 0;
client_loop.write(sc, this, bytes);
}
public void onData (TCPClientLoop l, SocketChannel c, ByteBuffer b) {
assert(l == client_loop);
fail("client_s_close received data");
}
public void onWrite (TCPClientLoop l, SocketChannel sc, ByteBuffer b, int pos, int num) {
assert(l == client_loop);
assert(num <= NUM2);
numWritten += num;
}
public void onClose (TCPClientLoop l, SocketChannel c) {
pass("'server close' onClose");
l.stopLoop();
clientShutdown();
}
public void onEOF (TCPClientLoop l, SocketChannel sc) {
pass("'server close' onEOF");
}
int errNo = 0;
public void check (String mes) {
switch (errNo) {
case 0:
if ("Connection reset by peer".equals(mes) || "Broken pipe".equals(mes)) {
pass("'server close' : "+errNo+" : "+mes);
} else {
fail ("'server close' : "+errNo+" : "+mes);
}
break;
case 1:
case 2:
if ("Socket is not connected".equals(mes)){
pass("'server close' : "+errNo+" : "+mes);
} else {
fail ("'server close' : "+errNo+" : "+mes);
}
break;
default:
fail ("'server close' : "+errNo+" : "+mes);
}
errNo++;
}
public void onError (TCPClientLoop l, SocketChannel sc, Throwable ioe) {
// behaviour is weird if the server closes socket unexpectantly
// read will fail and not return -1 (Connection reset)
// write will fail (broken pipe)
//
// socket.closed, connected, shutdown won't indicate the proper state.
check(ioe.getMessage());
l.shutdown(sc, this, TCPClientLoop.Shutdown.SHUT_RDWR);
l.close(sc, this);
}
};
client_loop.createTCPClient(client, "127.0.0.1", PORT);
} | 6 |
public int getValue() {
return value; //You may need to change this
} | 0 |
public IrcMessage(IrcClient client, MessageTypes type, String rawmessage)
{
this.Client = client;
this.Type = type;
this.RawMessage = rawmessage;
} | 0 |
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.