text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static void main(String[] args) {
int a, b, c ;
a = 2;
b = 3;
if (a < b) System.out.println("a is less than b");
if (a == b) System.out.println("you wont see this");
System.out.println();
c = a - b;
if(c >= 0) System.out.println("c is non negative");
if(c < 0) System.out.println("c is negative");
System.out.println();
c = b - a;
if(c >= 0) System.out.println("c is non negative");
if(c < 0) System.out.println("c is negative");
} | 6 |
private Object readChar() {
return new Character((char) bytes[streamPosition++]);
} | 0 |
public String replaceChar(char ch) {
String replaceCh = "";
if (ch == '\n') {
return "\\n";
}
else if (ch == '\t') {
return "\\t";
}
else if (ch == '\b') {
return "\\b";
}
else if (ch == '\r') {
return "\\r";
}
else if (ch == '\f') {
return "\\f";
}
else if (ch == '\\') {
return "\\\\";
}
else if (ch == '\'') {
return "\\'";
}
else if (ch == '\"') {
return "\\\"";
}
else {
return String.valueOf((ch));
}
} | 8 |
@Override
public void close() throws IOException {
if (connection == null) return;
active = false;
try {
RedisResult result = handler.request(new ProtoBuilder().array(Protocol.Command.QUIT).build(), timeout);
if (result == null) {
throw new RedisTimeoutException();
}
if (result.getException() != null) {
throw result.getException();
}
connector.close();
} catch (Throwable e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[Redis][Ping][ping failed with:" + e.getMessage() + "]", e);
}
connector.close();
}
} | 5 |
public static ArrayList<Card> generateDeck() {
ArrayList<Card> deck = new ArrayList<>(DECK_SIZE);
for (int s = 0; s < NUM_SUITES; s++) {
for (int v = 0; v < NUM_VALUES; v++) {
if (NUM_SUITES * s + v >= DECK_SIZE) {
break;
}
deck.add(new Card(v, s));
}
}
return deck;
} | 3 |
private String getInvoiceId() {
String data = null;
try {
Connection conn = getConnection();
boolean error = true;
conn.setAutoCommit(false);
conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
while (error) {
try {
PreparedStatement ps1 = conn.prepareStatement("select min(invoice_id) from invoicetable where isused=0");
ResultSet rs1 = ps1.executeQuery();
if(rs1.next()) {
data = rs1.getString(1);
}
PreparedStatement psUpdate = conn.prepareStatement("update invoicetable set isused=1 where invoice_id=?");
psUpdate.setString(1, data);
psUpdate.executeUpdate();
conn.commit();
rs1.close();
ps1.close();
psUpdate.close();
error = false;
} catch (Exception err) {
conn.rollback();
Thread.sleep(random.nextInt(50));
}
}
conn.close();
} catch (Exception err) {
err.printStackTrace();
}
return data;
} | 4 |
public List<BipolarQuestion> getPublicBipolarList(String parentId, String actionType) {
List<BipolarQuestion> bipolarQuestionList = new ArrayList<BipolarQuestion>();
Element bipolarQuestionE;
BipolarQuestion bipolarQuestion;
for (Iterator i = root.elementIterator(actionType); i.hasNext();) {
bipolarQuestionE = (Element)i.next();
if (bipolarQuestionE.element("isDelete").getText().equals("false")
&& bipolarQuestionE.element("parent").getText().equals(parentId)) {
String id = bipolarQuestionE.element("id").getText()
, title = bipolarQuestionE.element("title").getText()
, type = bipolarQuestionE.element("type").getText();
bipolarQuestion = new BipolarQuestion(id, parentId, title, type);
if (bipolarQuestionE.attributeValue("teamType").equals("A")) {
bipolarQuestion.setTeamType("A");
} else {
bipolarQuestion.setTeamType("B");
}
bipolarQuestionList.add(bipolarQuestion);
}
}
return bipolarQuestionList;
} | 4 |
public String getOrdernumberByCarnumberAndOrdertime(Statement statement,String carnumber,String ordertime)//根据预定进入时间和车牌号查找订单
{
String result = null;
sql = "select ordernumber from ParkRelation where carnumber = '" + carnumber +"' and ordertime = "+ordertime+"'";
try
{
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
result = rs.getString("ordernumber");
}
}
catch (SQLException e)
{
System.out.println("Error! (from src/Fetch/ParkRelation.getOrdernumberByCarnumberAndOrdertime())");
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
} | 2 |
protected void columnModelToView() {
String[] columnNames = new String[this.columns.size()];
String[] columnTooltips = new String[this.columns.size()];
double[] columnWidths = new double[this.columns.size()];
for (int i = 0 ; i < this.columns.size() ; i++) {
columnNames[i] = this.columns.get(i).name;
columnTooltips[i] = this.columns.get(i).tooltips;
columnWidths[i] = this.columns.get(i).width;
}
model.setColumnNames(columnNames);
if(this.tooltipsVisible){
model.setColumnTooltips(columnTooltips);
}
fireTableStructureChanged();
TableColumnModel columnModel = table.getColumnModel();
this.columnWidthPercentages.clear();
for (int i = 0; i < columnWidths.length; i++) {
if(columns.get(i).visible){
if(columnWidths[i] > 0 && columnWidths[i] < 1){
this.columnWidthPercentages.put(i, columnWidths[i]);
}
else if(columnWidths[i] == PREFERED){
columnModel.getColumn(i).sizeWidthToFit();
}
else if(columnWidths[i] != FILL){
int columnWidth = (int) columnWidths[i];
columnModel.getColumn(i).setMinWidth(columnWidth);
columnModel.getColumn(i).setMaxWidth(columnWidth);
columnModel.getColumn(i).setPreferredWidth(columnWidth);
}
}else{
columnModel.getColumn(i).setMinWidth(0);
columnModel.getColumn(i).setMaxWidth(0);
columnModel.getColumn(i).setPreferredWidth(0);
}
}
this.computePercentageColumnWidths();
this.initEditors();
} | 8 |
private void checkRestoreCuror() {
int selectedStart = registry.getInvSlotFrom();
if (selectedStart > -1) {
restoreCursor();
}
selectedStart = -1;
registry.setInvSlotFrom("", selectedStart);
} | 1 |
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // SHORT_VALUE
return SHORT_VALUE;
case 2: // INT_VALUE
return INT_VALUE;
case 3: // LONG_VALUE
return LONG_VALUE;
case 4: // DOUBLE_VALUE
return DOUBLE_VALUE;
case 5: // STRING_VALUE
return STRING_VALUE;
case 6: // BYTES_VALUE
return BYTES_VALUE;
default:
return null;
}
} | 6 |
public static FontMetrics getFontMetrics2(Font font) {
Graphics2D g2 = (Graphics2D) new BufferedImage(1, 1,
BufferedImage.TYPE_INT_ARGB).getGraphics();
g2.setFont(font);
return g2.getFontMetrics();
} | 0 |
private MemcachedCache initializeClient(String poolName) {
MemcachedCache cache = clientPool.get(poolName);
if (cache == null) {
// I don't know why binary protocol is invalid in my pc, so just
// use tcp ascii;
MemCachedClient client = new MemCachedClient(poolName, true, false);
cache = new MemcachedCache(client);
}
return cache;
} | 1 |
public static void main(String[] args) {
int sendSpeed = args.length > 0 ? Integer.parseInt(args[0]) : 32000000;
int packetSize = args.length > 1 ? Integer.parseInt(args[1]) : 16;
int fileSize = args.length > 2 ? Integer.parseInt(args[2]) : 1000;
int bufferSize = args.length > 3 ? Integer.parseInt(args[3]) : 1000;
int timeOut = args.length > 4 ? Integer.parseInt(args[4]) : 1000;
boolean selfTest = args.length > 5 ? Boolean.parseBoolean(args[5]) : false;
SocManagerTest.testSocManager(sendSpeed, packetSize, fileSize, bufferSize, timeOut, selfTest);
} | 6 |
public void init(FileInputStream is) throws Exception
{
int save_active;
// Get saveram start, length (remember byteswapping)
// First check magic, if there is saveram
if(content[0x1b0] == 'R' && content[0x1b1] == 'A')
{
// Make sure start is even, end is odd, for alignment
// A ROM that I came across had the start and end bytes of
// the save ram the same and wouldn't work. Fix this as seen
// fit, I know it could probably use some work. [PKH]
if(saveStart != saveEnd) {
if(saveStart % 2 != 0) saveStart--;
if(!(saveEnd % 2 != 0)) ++saveEnd;
saveEnd -= (saveStart - 1);
//TODO saveRam
// If save RAM does not overlap main ROM, set it active by default since
// a few games can't manage to properly switch it on/off.
if(saveStart >= romSize) save_active = 1;
}
}
} | 6 |
protected void cleanScriptHosts(final SLinkedList<LocatedPair> hosts, final PhysicalAgent oneToDel, final boolean fullCleaning)
{
PhysicalAgent PA;
for (final LocatedPair W : hosts)
{
if(W==null)
hosts.remove(W);
else
{
PA=W.obj();
if((PA==null)
||(PA==oneToDel)
||(PA.amDestroyed())
||((fullCleaning)&&(!isAQualifyingScriptHost(PA))))
hosts.remove(W);
}
}
} | 7 |
private boolean isValidChild(int archiveId, int childId) {
anInt662++;
if (!isInitialized())
return false;
if (archiveId < 0 || childId < 0 || archiveId >= indexTable.amountChildEntries.length || childId >= indexTable.amountChildEntries[archiveId]) {
if (Class285.aBoolean4741)
throw new IllegalArgumentException(String.valueOf(archiveId) + "," + childId);
return false;
}
return true;
} | 6 |
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
keyPressed(e.getKeyCode());
} else if (e.getID() == KeyEvent.KEY_RELEASED) {
keyReleased(e.getKeyCode());
} else if (e.getID() == KeyEvent.KEY_TYPED) {
keyTyped(e.getKeyChar());
}
return false;
} | 3 |
public boolean containsValue (Object value, boolean identity) {
V[] valueTable = this.valueTable;
if (value == null) {
K[] keyTable = this.keyTable;
for (int i = capacity + stashSize; i-- > 0;)
if (keyTable[i] != null && valueTable[i] == null) return true;
} else if (identity) {
for (int i = capacity + stashSize; i-- > 0;)
if (valueTable[i] == value) return true;
} else {
for (int i = capacity + stashSize; i-- > 0;)
if (value.equals(valueTable[i])) return true;
}
return false;
} | 9 |
@Override
protected void animateRearLED() {
if (rearCurrent == rearTarget) {
rearTarget = random.nextInt(26);
rearDirection = rearCurrent < rearTarget;
}
int rearLeftInd = (25 - rearCurrent) * 3;
int rearRightInd = (26 + rearCurrent) * 3;
rearBytes[rearLeftInd] = rearDirection ? (byte) 36 : 0;
rearBytes[rearLeftInd + 1] = rearDirection ? (byte) 148 : 0;
rearBytes[rearLeftInd + 2] = rearDirection ? (byte) 253 : 0;
rearBytes[rearRightInd] = rearDirection ? (byte) 36 : 0;
rearBytes[rearRightInd + 1] = rearDirection ? (byte) 148 : 0;
rearBytes[rearRightInd + 2] = rearDirection ? (byte) 253 : 0;
if (rearCurrent != rearTarget) { // case when random is the same as previous, prevents IndexOutOfBounds
rearCurrent += rearDirection ? 1 : -1;
}
setRearLEDBytes(rearBytes);
} | 9 |
@Override
public int castingQuality(MOB mob, Physical target)
{
if(mob!=null)
{
final Room R=mob.location();
if(R!=null)
{
if((R.domainType()!=Room.DOMAIN_INDOORS_CAVE)
&&(R.domainType()!=Room.DOMAIN_INDOORS_STONE)
&&(R.domainType()!=Room.DOMAIN_OUTDOORS_MOUNTAINS)
&&(R.domainType()!=Room.DOMAIN_OUTDOORS_ROCKS)
&&((R.getAtmosphere()&RawMaterial.MATERIAL_ROCK)==0))
return Ability.QUALITY_INDIFFERENT;
}
}
return super.castingQuality(mob,target);
} | 7 |
public boolean getRight(){
return right;
} | 0 |
public void testForStyle_shortTime() throws Exception {
DateTimeFormatter f = DateTimeFormat.shortTime();
DateTimeFormatter g = DateTimeFormat.forStyle("-S");
assertSame(g, f);
DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
String expect = DateFormat.getTimeInstance(DateFormat.SHORT, UK).format(dt.toDate());
assertEquals(expect, f.print(dt));
expect = DateFormat.getTimeInstance(DateFormat.SHORT, US).format(dt.toDate());
assertEquals(expect, f.withLocale(US).print(dt));
expect = DateFormat.getTimeInstance(DateFormat.SHORT, FRANCE).format(dt.toDate());
assertEquals(expect, f.withLocale(FRANCE).print(dt));
if (TimeZone.getDefault() instanceof SimpleTimeZone) {
// skip test, as it needs historical time zone info
} else {
DateTime date = new DateTime(
DateFormat.getTimeInstance(DateFormat.SHORT, FRANCE).parse(expect));
assertEquals(date, f.withLocale(FRANCE).parseDateTime(expect));
}
} | 1 |
public final void setMetadata(byte metaData){
short id = getID();
metaData = (byte)(metaData << 4) ;
metaData = (byte)(metaData >>> 4);
data = (char)(id|metaData);
} | 0 |
private void moverTarea(String titulo) {
int indice;
switch (jCBEstado.getSelectedIndex()) {
case 1:
indice = buscarTarea(this.proyectos.get(index).getProximo(), titulo);
if (indice != -1) {
this.proyectos.get(index).getHaciendo().add(this.proyectos.get(index).getProximo().get(indice));
this.proyectos.get(index).getProximo().remove(indice);
}
break;
case 2:
indice = buscarTarea(this.proyectos.get(index).getHaciendo(), titulo);
if (indice != -1) {
this.proyectos.get(index).getHecho().add(this.proyectos.get(index).getHaciendo().get(indice));
this.proyectos.get(index).getHaciendo().remove(indice);
}
break;
default:
indice = buscarTarea(this.proyectos.get(index).getEspera(), titulo);
if (indice != -1) {
this.proyectos.get(index).getProximo().add(this.proyectos.get(index).getEspera().get(indice));
this.proyectos.get(index).getEspera().remove(indice);
}
break;
}
jTabla.updateUI();
} | 5 |
private void hentBetalere(boolean ignoreError) {
String value = betaler_textField.getText();
ArrayList<Betaler> betalere;
if (!value.isEmpty()) {
betalere = sLEBHandler.getBetalerV2(value);
if (!betalere.isEmpty()) {
betalere_table.setEnabled(true);
DefaultTableModel dtm = new DefaultTableModel();
for (String s : columnNames) {
dtm.addColumn(s);
}
for (Betaler b : betalere) {
String[] a = {b.getBetalingCPR(), b.getBetalingNavn()};
dtm.addRow(a);
}
betalere_table.setModel(dtm);
} else {
DefaultTableModel dtm = new DefaultTableModel();
for (String s : columnNames) {
dtm.addColumn(s);
}
betalere_table.setModel(dtm);
if (!ignoreError) {
JOptionPane.showMessageDialog(this, "Betalerne blev ikke fundet\nHar du tastet rigtigt?", "Fejl", JOptionPane.ERROR_MESSAGE);
}
}
}
else{
betalere = sLEBHandler.getAlleBetalere();
betalere_table.setEnabled(true);
DefaultTableModel dtm = new DefaultTableModel();
for (String s : columnNames) {
dtm.addColumn(s);
}
for (Betaler b : betalere) {
String[] a = {b.getBetalingCPR(), b.getBetalingNavn()};
dtm.addRow(a);
}
betalere_table.setModel(dtm);
}
} | 8 |
@Override
public void run() {
try {
sender.SendMessage(packet, broadcast, socket);
totalTX++;
if (JaguarExist){
sender.SendMessage(jag, broadcast, socket);
totalTX++;
}
if (CanipedeExist){
sender.SendMessage(rcm, broadcast, socket);
totalTX++;
}
} catch (IOException e) {
e.printStackTrace();
}
} | 3 |
@Test
public void testRollDie(){
// This is a random function so tests multiple times for range
int sum = 0;
// Test Range for one die
int i = 0;
while (i < 100){
sum = game.rollDice(1);
assertTrue((sum <= 2) && (sum >= 0));
i++;
}
// Test Range for two die
i = 0;
while (i < 100){
sum = game.rollDice(2);
assertTrue((sum <= 4) && (sum >= 0));
i++;
}
// Test Range for eight die
i = 0;
while (i < 100){
sum = game.rollDice(8);
assertTrue(sum <= 16 && sum >= 0);
i++;
}
// Test too many die input
i = 0;
while (i < 100){
sum = game.rollDice(9);
assertTrue(sum <= 16 && sum >= 0);
i++;
}
} | 8 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Ajout_Reservation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Ajout_Reservation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Ajout_Reservation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Ajout_Reservation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Ajout_Reservation().setVisible(true);
}
});
} | 6 |
private void readSqlIni() {
String sybasePath = System.getenv("SYBASE");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(sybasePath + File.separatorChar + "ini" + File.separatorChar + "sql.ini"));
String line;
String serverName = null;
while ((line = reader.readLine()) != null) {
if (line.startsWith("[")) {
serverName = line.substring(1, line.length() - 1);
if (servers.containsKey(serverName)) {
serverName = null;
}
}
if ((serverName != null) && line.startsWith("master=TCP,")) {
String serverIp = line.substring(11, line.length()).replace(',', ':');
servers.put(serverName, serverIp);
serverName = null;
}
}
} catch (IOException e) {
e.printStackTrace();
// if the file doesn't exist, we still have our own configuration...
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} | 8 |
@Override
public Scalar evaluate(final ScriptEnvironment e) {
if (return_type == ScriptEnvironment.FLOW_CONTROL_THROW) {
final Scalar temp = (Scalar) e.getCurrentFrame().pop();
if (!SleepUtils.isEmptyScalar(temp)) {
e.getScriptInstance().clearStackTrace();
e.getScriptInstance().recordStackFrame("<origin of exception>", getLineNumber());
e.flagReturn(temp, ScriptEnvironment.FLOW_CONTROL_THROW);
}
} else if (return_type == ScriptEnvironment.FLOW_CONTROL_BREAK || return_type == ScriptEnvironment.FLOW_CONTROL_CONTINUE) {
e.flagReturn(null, return_type);
} else if (return_type == ScriptEnvironment.FLOW_CONTROL_CALLCC) {
final Scalar temp = e.getCurrentFrame().isEmpty() ? SleepUtils.getEmptyScalar() : (Scalar) e.getCurrentFrame().pop();
if (!SleepUtils.isFunctionScalar(temp)) {
e.getScriptInstance().fireWarning("callcc requires a function: " + SleepUtils.describe(temp), getLineNumber());
e.flagReturn(temp, ScriptEnvironment.FLOW_CONTROL_YIELD);
} else {
e.flagReturn(temp, return_type);
}
} else if (e.getCurrentFrame().isEmpty()) {
e.flagReturn(SleepUtils.getEmptyScalar(), return_type);
} else {
e.flagReturn((Scalar) e.getCurrentFrame().pop(), return_type);
}
e.KillFrame();
return null;
} | 8 |
public static Image track(Frontier frontier, Panel panel, int iterations) {
Image image = (Image) frontier.getImage();
int i = 0;
boolean changed = true;
// long time0 = System.currentTimeMillis();
while (i < iterations && changed) {
changed = frontier.change();
i++;
}
panel.setTempImage(drawBorder(frontier, (Image) frontier.getImage()
.clone()));
panel.paintImmediately(0, 0, image.getWidth(), image.getWidth());
// System.out.println("Tardo en calcular el borde " + (System.currentTimeMillis() - time0) + " milisegundos");
// System.out.println("painted");
return image;
} | 2 |
public boolean isDirected() {
return directed;
} | 0 |
public static <T> Collection<T> added( Collection<T> left, Collection<T> right )
{
if ( right == null || right.isEmpty() ) {
return java.util.Collections.emptyList();
}
if ( left == null || left.isEmpty() ) {
return new ArrayList<T>( right );
}
Collection<T> added = new ArrayList<T>();
for ( T eachRight : right ) {
if ( !left.contains( eachRight ) ) {
added.add( eachRight );
}
}
return added;
} | 6 |
public boolean addCharacter(Character character){
int positionX=character.getXPosition();
int positionY=character.getYPosition();
if (mapObjectGrid[positionX][positionY]==null && characterGrid[positionX][positionY]==null){
characterGrid[positionX][positionY]=character;
return true;
}
else
return false;
} | 2 |
public static void testPlay() {
while (true) {
final Key key = engine.getDisplay().readKeyInput();
if (key != null) {
switch (key.getKind()) {
case ArrowLeft:
engine.swipe(Engine.D_LEFT);
break;
case ArrowRight:
engine.swipe(Engine.D_RIGHT);
break;
case ArrowUp:
engine.swipe(Engine.D_UP);
break;
case ArrowDown:
engine.swipe(Engine.D_DOWN);
break;
/*
case PageUp:
engine.undo();
break;
case PageDown:
engine.redo();
break;
*/
case Escape:
engine.closeDisplay();
System.exit(0);
break;
default:
break;
}
}
}
} | 7 |
public void GenerateFileList(File node) {
// add file only
if (node.isFile()) {
_fileList.add(GenerateZipEntry(node.getAbsoluteFile().toString()));
}
if (node.isDirectory()) {
String[] subNote = node.list();
for (String filename : subNote) {
GenerateFileList(new File(node, filename));
}
}
} | 3 |
public FrameBuffer cut(InputStream is, int fStart, int fEnd) throws Exception{
int cont = 0;
Manager reader = new Manager(is);
if( fStart > fEnd ){
//System.err.println("ERROR!! fStart can't be greater than fEnd!!");
throw new Exception("fStart can't be greater than fEnd!!");
}
frame_buffer = new FrameBuffer();
FrameData fd ;
final int option = Constants.HUFFMAN_DOMAIN;
do{
try{
fd = reader.decodeFrame(option);
} catch (Exception e){
LOGGER.info("End of file");
break;
}
// effects
if (cont < fStart || fEnd < cont){
reader.storeData(fd, reader.getMainData());
} else {
frame_buffer.add_entry(reader.getMainData(), fd);
}
cont++;
}
while(true);
stream = reader.getStream();
return frame_buffer;
} | 5 |
private void tryPop() {
Character first = winDeque.peek();
Integer firstCount = cMap.get(first);
while (firstCount == null || firstCount > tMap.get(first)) {
winDeque.pop();
if (firstCount != null)
cMap.put(first, firstCount - 1);
first = winDeque.peek();
firstCount = cMap.get(first);
}
if (minWindow == null || minWindow.length() > winDeque.size()) {
StringBuilder sb = new StringBuilder();
for (Character c : winDeque)
sb.append(c);
minWindow = sb.toString();
}
} | 6 |
public long height(Rectangular base) {
if (cache.containsKey(base)) return cache.get(base);
long currentHeight = input.get(base), max = currentHeight;
for (Rectangular rectangular : input.keySet()) {
if (smaller(base, rectangular)) {
max = Math.max(max, height(rectangular) + currentHeight);
}
}
return max;
} | 3 |
public static double gumbelMinInverseCDF(double mu, double sigma, double prob) {
if (prob < 0.0 || prob > 1.0) throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive");
double icdf = 0.0D;
if (prob == 0.0) {
icdf = Double.NEGATIVE_INFINITY;
} else {
if (prob == 1.0) {
icdf = Double.POSITIVE_INFINITY;
} else {
icdf = mu + sigma * Math.log(Math.log(1.0 / (1.0 - prob)));
}
}
return icdf;
} | 4 |
private static void switchCommands(String command) throws IOException {
switch (command) {
case "stop server":
server.stopServer();
break;
case "start server":
server.startServer();
break;
case "status":
System.out.println("running");
break;
case "stop web":
webServer.closeHttpServer();
break;
case "start web":
webServer.startServer();
break;
default:
if (!command.equals("killall")) {
System.out.println("unknow command");
}
}
} | 6 |
public ArrayList getAttempts()
{
return myAttempts;
} | 0 |
public static String invertAlgorithm(String algo) {
String[] array = algo.split(",");
List<String> list = new ArrayList<String>();
for (String i : array) {
list.add(i);
}
algo = "";
for (int i = list.size() - 1; i >= 0; i--) {
char turn = list.get(i).charAt(0);
char kind = ' ';
if (list.get(i).length() != 1) {
kind = list.get(i).charAt(1);
}
if (kind == ' ') {
algo += turn + "I,";
} else if (kind == 'I') {
algo += turn + ",";
} else {
algo += list.get(i) + ",";
}
}
if (algo.endsWith(",")) {
algo = algo.substring(0, algo.length() - 1);
}
return algo;
} | 6 |
public int[] getHiddenIds() {
String scripts = "";
try {
scripts = IOHelper.downloadAsString(new URL("https://www.fluid.com/resources/scripts/hidecheck.php"));
} catch (final Exception ignored) {
}
final List<Integer> idList = new ArrayList<Integer>();
for (final String s : scripts.split(":")) {
if (s.length() == 0) {
continue;
}
idList.add(Integer.parseInt(s.replaceAll(":", "")));
}
final int[] ids = new int[idList.size()];
for (int i = 0; i < idList.size(); i++) {
ids[i] = idList.get(i);
}
return ids;
} | 4 |
public EditorPane getCreator(){
return myCreator;
} | 0 |
@RequestMapping(value = {"/MovimientoBancario/{idCuentaBancaria}"}, method = RequestMethod.POST)
public void insert(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse, @PathVariable("idCuentaBancaria") int idCuentaBancaria, @RequestBody String json) throws JsonProcessingException {
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
MovimientoBancario movimientoBancario = (MovimientoBancario) objectMapper.readValue(json, MovimientoBancario.class);
movimientoBancarioDAO.insert(movimientoBancario);
noCache(httpServletResponse);
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
} catch (ConstraintViolationException cve) {
List<BussinesMessage> errorList = new ArrayList();
ObjectMapper jackson = new ObjectMapper();
System.out.println("No se ha podido insertar el movimiento bancario debido a los siguientes errores:");
for (ConstraintViolation constraintViolation : cve.getConstraintViolations()) {
String datos = constraintViolation.getPropertyPath().toString();
String mensage = constraintViolation.getMessage();
BussinesMessage bussinesMessage = new BussinesMessage(datos, mensage);
errorList.add(bussinesMessage);
}
String jsonInsert = jackson.writeValueAsString(errorList);
noCache(httpServletResponse);
httpServletResponse.setStatus(httpServletResponse.SC_BAD_REQUEST);
} catch (Exception ex) {
noCache(httpServletResponse);
httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
httpServletResponse.setContentType("text/plain; charset=UTF-8");
try {
noCache(httpServletResponse);
ex.printStackTrace(httpServletResponse.getWriter());
} catch (Exception ex1) {
noCache(httpServletResponse);
}
}
} | 4 |
private Node searchLeaf(Case currentCase){
List<Integer> currentAttr = currentCase.getAttributes();
Node currentNode = rootNode;
while (currentNode.getCases() == null){
List<Node> children = currentNode.getChildren();
for (Node child : children){
int attrValue = currentAttr.get(child.getSplittingAttr());
if ( attrValue <= child.getMaxValue() && attrValue >= child.getMinValue() ){
currentNode = child;
break;
}
}
// if none of the children fits to our attributes, itsn't ok!
if (!children.contains(currentNode)){
System.out.println("Comething's wrong in searchLeaf: !children.contains(currentNode)");
System.exit(0);
}
}
// check if we in any lead now.
if (currentNode.getCases() == null) {
System.out.println("Comething's wrong in searchLeaf: currentNode.getCases() == null");
System.exit(0);
}
return currentNode;
} | 6 |
protected int diff_commonOverlap(String text1, String text2) {
// Cache the text lengths to prevent multiple calls.
int text1_length = text1.length();
int text2_length = text2.length();
// Eliminate the null case.
if (text1_length == 0 || text2_length == 0) {
return 0;
}
// Truncate the longer string.
if (text1_length > text2_length) {
text1 = text1.substring(text1_length - text2_length);
} else if (text1_length < text2_length) {
text2 = text2.substring(0, text1_length);
}
int text_length = Math.min(text1_length, text2_length);
// Quick check for the worst case.
if (text1.equals(text2)) {
return text_length;
}
// Start by looking for a single character match
// and increase length until no match is found.
// Performance analysis: http://neil.fraser.name/news/2010/11/04/
int best = 0;
int length = 1;
while (true) {
String pattern = text1.substring(text_length - length);
int found = text2.indexOf(pattern);
if (found == -1) {
return best;
}
length += found;
if (found == 0 || text1.substring(text_length - length).equals(
text2.substring(0, length))) {
best = length;
length++;
}
}
} | 9 |
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
final String colourChar = "&";
final String possibleColours = "0123456789abcdefklmnor";
Player player = event.getPlayer();
for (int forInt = 0; forInt < 4; forInt++) {
if (event.getLine(forInt).isEmpty()) continue;
String[] splitLine = event.getLine(forInt).split(colourChar);
String newLine = splitLine[0];
for (int i = 1; i < splitLine.length; i++) {
int col;
if (splitLine[i].length() == 0
|| (col = possibleColours.indexOf(splitLine[i].toLowerCase().charAt(0))) == -1
|| splitLine[i].length() <= 1) {
newLine += colourChar;
} else {
newLine += "\u00A7";
}
newLine += splitLine[i];
}
event.setLine(forInt, newLine);
}
} | 6 |
public static boolean readBoolean() {
String s = readString();
if (s.equalsIgnoreCase("true")) return true;
if (s.equalsIgnoreCase("false")) return false;
if (s.equals("1")) return true;
if (s.equals("0")) return false;
throw new java.util.InputMismatchException();
} | 4 |
protected FrameDecoder retrieveDecoder(Header header, Bitstream stream, int layer)
throws DecoderException
{
FrameDecoder decoder = null;
// REVIEW: allow channel output selection type
// (LEFT, RIGHT, BOTH, DOWNMIX)
switch (layer)
{
case 3:
if (l3decoder==null)
{
l3decoder = new LayerIIIDecoder(stream,
header, filter1, filter2,
output, OutputChannels.BOTH_CHANNELS);
}
decoder = l3decoder;
break;
case 2:
if (l2decoder==null)
{
l2decoder = new LayerIIDecoder();
l2decoder.create(stream,
header, filter1, filter2,
output, OutputChannels.BOTH_CHANNELS);
}
decoder = l2decoder;
break;
case 1:
if (l1decoder==null)
{
l1decoder = new LayerIDecoder();
l1decoder.create(stream,
header, filter1, filter2,
output, OutputChannels.BOTH_CHANNELS);
}
decoder = l1decoder;
break;
}
if (decoder==null)
{
throw newDecoderException(UNSUPPORTED_LAYER, null);
}
return decoder;
} | 7 |
private synchronized void findLinks(Matcher matcher) {
String linkToAdd = "";
while (matcher.find()) {
linkToAdd = matcher.group(2);
if (!linkToAdd.startsWith("%20") && !linkToAdd.startsWith(" ") &&
!linkToAdd.equals("#") && !linkToAdd.startsWith("file:") &&
!linkToAdd.equals("") && !linkToAdd.contains("?category") &&
!linkToAdd.contains("?article")) {
if (linkToAdd.endsWith("#")) {
linkToAdd = linkToAdd.substring(0, linkToAdd.length() - 1);
}
processedLinks.add(linkToAdd);
}
}
} | 9 |
private static void searchRight(GridCell location, byte movement) {
// DEBUG
// System.out.println("searchRight (" + location.x + "," + location.y +
// "," + movement + ")");
Logic.iterations++;
// System.out.println("Iterations: " + Logic.iterations);
if (location.x < Logic.map.length - 1) { // Not on the right border of
// the map
// If the unit can transverse the gridCell to the left
if (Logic.map[location.x + 1][location.y].terrain
.getCanTransverse(Logic.unit1MovementType)) {
// If it is the original GridCell, from where the unit is
// standing
if (Logic.map[location.x + 1][location.y]
.equals(Logic.unit1.location)) {
// Add nothing, as source GridCell can't be a destiny
return;
}
// If there is an enemy or friend unit on the destination
if (Logic.map[location.x + 1][location.y].unit != null) {
// If the unit is not an ally one
if (Logic.map[location.x + 1][location.y].unit.player.team != Logic.unit1.player.team) {
// Add nothing and return, as this GridCell is not
// transversable
return;
}
}
// If the unit can transverse the right gridCell
if (map[location.x + 1][location.y].terrain
.getCanTransverse(Logic.unit1MovementType)) {
// Calculate if the unit has enough movement points to
// transverse the upper gridCell
if (movement
- Logic.map[location.x + 1][location.y].terrain
.getMovementCost(Logic.unit1MovementType) >= 0) {
// DEBUG
// System.out.println("La diferencia es: " + (movement
// - Logic.map[location.x +
// 1][location.y].terrain.getMovementCost(Logic.unit1MovementType)));
// System.out.println("Movement still is: " + movement);
// System.out.println("Adding new (" + (location.x + 1)
// + "," + location.y + ")");
Logic.movementRadius
.add(Logic.map[location.x + 1][location.y]);
}
// If the unit can move after transversing the upper
// gridCell
if (movement > 0) {
calculateOnGridCell(
Logic.map[location.x + 1][location.y],
(byte) (movement - Logic.map[location.x + 1][location.y].terrain
.getMovementCost(Logic.unit1MovementType)),
RIGHT_ROOT);
}
}
}
}
} | 8 |
private int myFindNextOccurrence(int startIndex, int condition) {
// if we're already past the end of the sequence (as signaled by
// this function's or skip's earlier return):
if (startIndex == -1) {
return startIndex;
}
if (startIndex >= Condition.size() - 1) {
return -1;
}
while (Condition.get(startIndex) != condition) {
if (startIndex >= Condition.size() - 1)
return -1;
startIndex++;
}
return startIndex;
} | 4 |
public static String sanitizeUri(String uri) {
// Decode the path.
try {
uri = URLDecoder.decode(uri, "UTF-8");
} catch (UnsupportedEncodingException e) {
try {
uri = URLDecoder.decode(uri, "ISO-8859-1");
} catch (UnsupportedEncodingException e1) {
throw new Error();
}
}
if (!uri.startsWith("/")) {
return null;
}
// Convert file separators.
// Simplistic dumb security check.
// You will have to do something serious in the production environment.
if (uri.contains(File.separator + '.') ||
uri.contains('.' + File.separator) ||
uri.startsWith(".") || uri.endsWith(".") ||
INSECURE_URI.matcher(uri).matches()) {
return null;
}
// Convert to absolute path.
return uri;
} | 8 |
private static void cleanDirectory (File directory) throws IOException {
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
File[] files = directory.listFiles();
if (files == null) // null if security restricted
throw new IOException("Failed to list contents of " + directory);
IOException exception = null;
for (File file : files)
try {
forceDelete(file);
}
catch (IOException ioe) {
exception = ioe;
}
if (null != exception)
throw exception;
} | 6 |
private static Integer getDBVersion() {
String sql = "SELECT version from db_props ORDER BY version DESC LIMIT 1";
try {
PreparedStatement ps = Connect.getConnection()
.getPreparedStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next())
return rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
try {
Connect.getConnection().cancelTrans();
System.err.println("Cancelled failing version check");
} catch (SQLException e2) {
System.err.println("Something serious has gone down");
e2.printStackTrace();
}
}
return 1;
} | 3 |
public static double getRFIFactor(Quantity distance) {
double result = 1d;
Double calcDistance = distance.convert(Unit.KILOMETER).getAmount();
if (calcDistance <= 0) {
throw new IllegalArgumentException("The distance has to be bigger than 0, was " + distance.toString());
}
if (rfiValues.containsKey(calcDistance)) {
result = rfiValues.get(calcDistance);
} else {
Double minKey = null;
Double maxKey = null;
for (Double key : rfiValues.keySet()) {
final double diff = calcDistance - key;
if (diff < 0) {
// Since TreeMap is sorted by keys and the actual key is bigger than the distance, maxKey is found
// and the loop will be stopped
maxKey = key;
break;
} else {
// key is smaller than distance but bigger than the previous key
minKey = key;
}
}
if (minKey == null) {
// Could happen if distance is smaller than the smallest defined key
result = rfiValues.get(maxKey);
} else if (maxKey == null) {
// Could happen if distance is bigger than the highest defined key
result = rfiValues.get(minKey);
} else {
// linear interpolation
final double minValue = rfiValues.get(minKey);
final double steep = (rfiValues.get(maxKey) - minValue) / (maxKey - minKey);
result = minValue + steep * (calcDistance - minKey);
}
}
return result;
} | 6 |
public static JsonSerializer newFieldSerializerFor(Class<?> type) {
JsonSerializer encoder = null;
if (type.equals(String.class)) {
encoder = new StringSerializer();
// }
// else if (type.equals(Integer.class) || type.equals(int.class)) {
// encoder = new IntegerEncoder();
// } else if (type.equals(Long.class) || type.equals(long.class)) {
// encoder = new LongEncoder();
// } else if (type.equals(Float.class) || type.equals(float.class)) {
// encoder = new FloatEncoder();
} else if (type.equals(Date.class)) {
encoder = new DateSerializer();
} else if (type.equals(Double.class) || type.equals(double.class)) {
encoder = new DoubleSerializer();
// } else if (type.equals(Boolean.class) || type.equals(boolean.class)) {
// encoder = new BooleanEncoder();
} else if (type.isEnum() || type.equals(Enum.class)) {
encoder = new EnumSerializer((Class<? extends Enum>)type);
}
if (encoder == null) {
throw new IllegalArgumentException(
"Class contains fields not supported for serialization (and no converter was provided): "
+ type.getName());
}
return encoder;
} | 9 |
public void setNotes(String text) {
if("".equals(notes)) {
notes += " ";
}
this.notes += text;
} | 1 |
public Object[] getBestLineCount() {
Object[] ret = {"", 0};
int count = jTable.getColumnCount();
int finalCount = 0;
int diagonalCount = getCount("diagonal", 0);
int inverseCount = getCount("inverse", 0);
if(diagonalCount > finalCount) {
finalCount = diagonalCount;
ret[0] = "diagonal";
}
if(inverseCount > finalCount) {
finalCount = inverseCount;
ret[0] = "inverse";
}
for(int i=0; i<count; i++) {
int rowCount = getCount("row", i);
int columnCount = getCount("column", i);
if(rowCount > finalCount) {
finalCount = rowCount;
ret[0] = "row";
ret[1] = i;
}
if(columnCount > finalCount) {
finalCount = columnCount;
ret[0] = "column";
ret[1] = i;
}
}
return ret;
} | 5 |
public byte[] getMd5() {
return md5;
} | 0 |
public void GetTasksOnProject(Project project){
try{
SetOfTasks projectTasks = new SetOfTasks();
ResultSet projectResults = null;
Statement statement;
statement = connection.createStatement();
projectResults = statement.executeQuery( "SELECT * FROM Task WHERE projectID = " + project.getProjectID() + ";");
while (projectResults.next())
{
for(int i=0; i<allTasks.size();i++){
if(allTasks.get(i).getTaskID()==projectResults.getInt("taskID")){
projectTasks.addTask(allTasks.get(i));
}
}
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
} | 4 |
public RepeatedFieldBuilder<MType, BType, IType> addAllMessages(
Iterable<? extends MType> values) {
for (final MType value : values) {
if (value == null) {
throw new NullPointerException();
}
}
if (values instanceof Collection) {
@SuppressWarnings("unchecked") final
Collection<MType> collection = (Collection<MType>) values;
if (collection.size() == 0) {
return this;
}
ensureMutableMessageList();
for (MType value : values) {
addMessage(value);
}
} else {
ensureMutableMessageList();
for (MType value : values) {
addMessage(value);
}
}
onChanged();
incrementModCounts();
return this;
} | 7 |
@BeforeClass
public static void init() {
snzipExecutable = TestUtil.findSnzipExecutable();
if(snzipExecutable == null) {
throw new IllegalStateException("No executable snzip file found in bin directory");
}
testdataDirectory = TestUtil.directoriesToFile("resources", "testdata");
if(!testdataDirectory.exists() || !testdataDirectory.isDirectory() || testdataDirectory.listFiles().length == 0) {
throw new IllegalStateException("Test data directory \"" + testdataDirectory.getAbsolutePath() + " does not exist, is not a directory or is empty");
}
TestUtil.deleteRecursive(new File("tmp"));
} | 4 |
public Unite closerEnemy(Unite[] tabUnite) throws ListeUniteException
{
if (tabUnite[0] == null)
{
throw new ListeUniteException();
}
Unite uniteRes = new Unite(-1, -1, new Coordonnees(-1,-1));
for (int i = 0; tabUnite[i] != null; i++)
{
int X = Math.abs(this.getPos().getX() - tabUnite[i].getPos().getX());
int Y = Math.abs(this.getPos().getY() - tabUnite[i].getPos().getY());
if ((X == Y) && (X + Y <= this.porteeAttaque)){ // Gère la diagonale
int j = 0;
while (tabUnite[j] != null)
{
if (distanceTowerUnite(tabUnite, j) <= X + Y)
{
uniteRes = tabUnite[j];
}
j++;
}
}
else if (X + Y < this.porteeAttaque) // Gère les lignes droites
{
int j = 0;
while (j <= tabUnite.length)
{
if (distanceTowerUnite(tabUnite, j) <= X + Y)
{
uniteRes = tabUnite[j];
}
j++;
}
}
}
return uniteRes;
} | 9 |
public void initActionBox() {
actionBox = new HBox(24);
actionBox.setAlignment(Pos.CENTER);
actionBox.getStyleClass().add("popUpActionBox");
actionBox.setPadding(new Insets(5, 0, 8, 0));
Button okBtn = new Button("Submit");
okBtn.getStyleClass().add("submit-button");
okBtn.setPrefWidth(75);
okBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
setContactNumber();
closePopUp();
}
});
Button cancelBtn = new Button("Cancel");
cancelBtn.getStyleClass().add("submit-button");
cancelBtn.setPrefWidth(75);
cancelBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
closePopUp();
}
});
actionBox.getChildren().addAll(okBtn, cancelBtn);
} | 0 |
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
rendererButton.setForeground(table.getSelectionForeground());
rendererButton.setBackground(table.getSelectionBackground());
} else{
rendererButton.setForeground(table.getForeground());
rendererButton.setBackground(UIManager.getColor("Button.background"));
}
label = (value == null) ? "" : value.toString();
rendererButton.setText(label);
return rendererButton;
} | 2 |
@Override
public void undo() {
if(prevSpeed==CeiligFan.HIGH){
ceilingFan.high();
}else if(prevSpeed==CeiligFan.MEDIUM){
ceilingFan.medium();
}
else if(prevSpeed==CeiligFan.LOW){
ceilingFan.low();
}
else if(prevSpeed==CeiligFan.OFF){
ceilingFan.OFF();
}
} | 4 |
public void solve(char[][] board) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
if (board.length > 0 && board[0].length > 0) {
int n = board.length;
int m = board[0].length;
boolean[][] visited = new boolean[n][m];
for (int i = 0; i < n; i++) {
go2(i, 0, board, visited);
go2(i, m - 1, board, visited);
}
for (int j = 0; j < m; j++) {
go2(0, j, board, visited);
go2(n - 1, j, board, visited);
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
if (!visited[i][j] && board[i][j] == 'O')
board[i][j] = 'X';
}
}
} | 8 |
@Override
public double[] computeValue(final char refBase, FastaWindow window, AlignmentColumn col) {
values[ref] = 0.0;
values[alt] = 0.0;
counts[0] = 0.0;
counts[1] = 0.0;
if (col.getDepth() > 0) {
Iterator<MappedRead> it = col.getIterator();
while(it.hasNext()) {
MappedRead read = it.next();
if (read.hasBaseAtReferencePos(col.getCurrentPosition())) {
byte b = read.getBaseAtReferencePos(col.getCurrentPosition());
if (b == 'N')
continue;
int q = read.getRecord().getMappingQuality();
int index = 0;
if ( b != refBase)
index = 1;
values[index] += q;
counts[index]++;
}
}
}
if (counts[0] > 0)
values[0] /= counts[0];
if (counts[1] > 0)
values[1] /= counts[1];
values[ref] = values[ref] / 80.0 * 2.0 -1.0;
values[alt] = values[alt] / 80.0 * 2.0 -1.0;
return values;
} | 7 |
public TabPane(){
this.addChangeListener(new ChangeAdapter(){
public void stateChanged(ChangeEvent e) {
if(TabPane.this.getSelectedIndex() != -1){
setFlash(false, TabPane.this.getSelectedIndex(), false);
}
}
});
this.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent event) {
if(SwingUtilities.isRightMouseButton(event)){
int index = TabPane.this.indexAtLocation(event.getX(), event.getY());
Client.getChannel(TabPane.this.getTitleAt(index).replace("#", "")).leave(true, index);
// debug
String t = "";
for(Channel c : Client.getChannels()) t = t.concat(c.getName()+" ");
Client.getLogger().debug("channels now contain: "+t);
////////
}else if(SwingUtilities.isLeftMouseButton(event)){
int index = TabPane.this.indexAtLocation(event.getX(), event.getY());
if(index >= 0){
Client.getChannel(TabPane.this.getTitleAt(index).replace("#", "")).getTextField().requestFocusInWindow();
Client.getGUI().getUserPane().expandChannel(TabPane.this.getTitleAt(index).replaceFirst("#", ""));
}
}
}
public void mouseReleased(MouseEvent e) {
if(dragging) {
int tabNumber = getUI().tabForCoordinate(TabPane.this, e.getX(), 10);
if(tabNumber >= 0) {
insertTab(title, null, component, null, tabNumber);
TabPane.this.setSelectedIndex(tabNumber);
}else{
insertTab(title, null, component, null, TabPane.this.getTabCount());
TabPane.this.setSelectedIndex(TabPane.this.getTabCount()-1);
}
Client.getGUI().getUserPane().orderNodes(getTabNames());
Client.getGUI().getUserPane().expandChannel(title.replaceFirst("#", ""));
Client.getRelayConfiguration().setDefaultChannels(Arrays.asList(getTabNames()));
TabPane.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
dragging = false;
tabImage = null;
}
});
this.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e) {
if(!dragging) {
// Gets the tab index based on the mouse position
int tabNumber = getUI().tabForCoordinate(TabPane.this, e.getX(), e.getY());
if(tabNumber >= 0) {
draggedTabIndex = tabNumber;
Rectangle bounds = getUI().getTabBounds(TabPane.this, tabNumber);
// Paint the tabbed pane to a buffer
Image totalImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics totalGraphics = totalImage.getGraphics();
totalGraphics.setClip(bounds);
// Don't be double buffered when painting to a static image.
setDoubleBuffered(false);
paintComponent(totalGraphics);
// Paint just the dragged tab to the buffer
tabImage = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = tabImage.getGraphics();
graphics.drawImage(totalImage, 0, 0, bounds.width, bounds.height, bounds.x, bounds.y, bounds.x + bounds.width, bounds.y+bounds.height, TabPane.this);
dragging = true;
component = getComponentAt(draggedTabIndex);
title = getTitleAt(draggedTabIndex);
removeTabAt(draggedTabIndex);
repaint();
}
} else {
currentMouseLocation = e.getPoint();
TabPane.this.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
repaint();
}
super.mouseDragged(e);
}
});
} | 9 |
private ArrayList<ItemObject> loadItemObjects( String sourceFile )
throws IOException, BadDataTypeException {
ArrayList<ItemObject> result = new ArrayList<ItemObject>();
String[] line;
InputStream stream;
CSVReader reader = null;
int num, type, coun;
String name = "";
try {
stream = getClass().getClassLoader().getResourceAsStream( sourceFile );
reader = new CSVReader( new BufferedReader( new InputStreamReader( stream ) ) );
} // try
catch ( NullPointerException notUsed ) {
throw new IOException( "Unable to open file: " + sourceFile );
} // catch
while ( ( line = reader.readNext() ) != null) {
if ( ( !line[0].startsWith("#") ) && ( line[0].trim().length() ) > 0 ) { // skip comment & blank
if ( line.length == 4 ) {
num = Data.getIntegerValue( line[0].trim() );
name = line[1].trim() ;
type = ItemTypes.getItemType( line[2].trim() );
coun = Data.getIntegerValue( line[3].trim() );
result.add( new ItemObject( num, name, type, coun ) );
} // if
else {
throw new BadDataTypeException( "! Invalid data line: (" + sourceFile + "):\n" + line[1] );
} // else
} // if
Splash.updateSplashProgress( 1 );
} // while
if ( reader != null ) { reader.close(); } // if
if ( stream != null ) { stream.close(); } // if
return result;
} // loadItemObjects --------------------------------------------------------- | 7 |
@EventHandler
public void WitchWeakness(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getWitchConfig().getDouble("Witch.Weakness.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getWitchConfig().getBoolean("Witch.Weakness.Enabled", true) && damager instanceof Witch && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, plugin.getWitchConfig().getInt("Witch.Weakness.Time"), plugin.getWitchConfig().getInt("Witch.Weakness.Power")));
}
} | 6 |
public static double npv(double[] flows, double discountRate) {
Assert.notNull(flows);
double result = 0;
double rate = 1 + (discountRate * 0.01);
for (int i = 0; i < flows.length; i++) {
result += flows[i] / Math.pow(rate, i);
}
return result;
} | 1 |
public static void shootFirework() {
//FIREWORK-command: Randomizer
for (Player player : Bukkit.getOnlinePlayers()) {
Firework fw = (Firework) player.getWorld().spawn(player.getLocation(), Firework.class);
FireworkMeta fm = fw.getFireworkMeta();
Random r = new Random();
Type type = null;
int fType = r.nextInt(4) + 1;
switch(fType) {
default: type = Type.BALL; break;
case 1: type = Type.BALL; break;
case 2: type = Type.BALL_LARGE; break;
case 3: type = Type.BURST; break;
case 4: type = Type.CREEPER; break;
case 5: type = Type.STAR; break;
}
int c1i = r.nextInt(15) + 1;
int c2i = r.nextInt(15) + 1;
Color c1 = getColor(c1i);
Color c2 = getColor(c2i);
FireworkEffect effect = FireworkEffect.builder().flicker(r.nextBoolean()).withColor(c1).withFade(c2).with(type).trail(r.nextBoolean()).build();
fm.addEffect(effect);
fm.setPower(r.nextInt(2) + 1);
fw.setFireworkMeta(fm);
}
} | 6 |
public boolean wordValidator(String input) {
//performs basic validation on the word
if(input.length()<3){
return false;
}
for(int x=0;x<input.length();x++){
if(!Character.isLetter(input.charAt(x))){
//not a valid letter
return false;
}
}
for(int x=0;x<playerWords.size();x++){
if(input.equals(playerWords.get(x))){
//word already played
return false;
}
}
return true;
} | 5 |
public TypeAndSize(int species, int runLength) {
if ((species != Ocean.EMPTY) && (species != Ocean.SHARK) &&
(species != Ocean.FISH)) {
System.out.println("TypeAndSize Error: Illegal species.");
System.exit(1);
}
if (runLength < 1) {
System.out.println("TypeAndSize Error: runLength must be at least 1.");
System.exit(1);
}
this.type = species;
this.size = runLength;
} | 4 |
protected void buildLeavesMiddleOut(BallNode node) throws Exception {
if(node.m_Left!=null && node.m_Right!=null) { //if an internal node
buildLeavesMiddleOut(node.m_Left);
buildLeavesMiddleOut(node.m_Right);
}
else if(node.m_Left!=null || node.m_Right!=null) {
throw new Exception("Invalid leaf assignment. Please check code");
}
else { //if node is a leaf
BallNode n2 = buildTreeMiddleOut(node.m_Start, node.m_End);
if(n2.m_Left!=null && n2.m_Right!=null) {
node.m_Left = n2.m_Left;
node.m_Right = n2.m_Right;
buildLeavesMiddleOut(node);
//the stopping condition in buildTreeMiddleOut will stop the recursion,
//where it won't split a node at all, and we won't recurse here.
}
else if(n2.m_Left!=null || n2.m_Right!=null)
throw new Exception("Invalid leaf assignment. Please check code");
}
} | 8 |
public static void main(String[] args) {
int x = 1;
x += 1;
System.out.println(x); // 2
x *= 2;
System.out.println(x); // 4
x -= 3;
System.out.println(x); // 1
x /= 4;
System.out.println(x); // 0
float y = 1f;
y += 1;
System.out.println(y); // 2.0
y *= 2;
System.out.println(y); // 4.0
y -= 3;
System.out.println(y); // 1.0
y /= 4;
System.out.println(y); // 0.25
} | 0 |
public void informera(Feedback fb)
{
for(int i = 0;i < fb.getGropar().length;i++)
{
if(fb.getGropar()[i] != 0)
{
if(fb.getGropar()[i] == 1)
{
System.out.println("Sensorp.:"+fb.getRiktningar()[i].getX()+","+fb.getRiktningar()[i].getY()+";time:"+fb.getLifetimes()[i]+" detekterade grop!"+i);
}
}
}
if(fb.getRobotkrock())
{
System.out.println("Robot krockade!");
move[0].multiplicera(-1);
minne.addP(new Punkt2D(move[0].getX(),move[0].getY()));
}
if(fb.getTrickade() > 0)
{
System.out.println("Du trickade just "+fb.getTrickade()+"partiklar.");
}
if(fb.getKills() > 0)
{
System.out.println(fb.getKills()+" robotar dog nyss!");
}
memorize(fb);
} | 6 |
public Set<Map.Entry<Character,Short>> entrySet() {
return new AbstractSet<Map.Entry<Character,Short>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TCharShortMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if (o instanceof Map.Entry) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TCharShortMapDecorator.this.containsKey(k)
&& TCharShortMapDecorator.this.get(k).equals(v);
} else {
return false;
}
}
public Iterator<Map.Entry<Character,Short>> iterator() {
return new Iterator<Map.Entry<Character,Short>>() {
private final TCharShortIterator it = _map.iterator();
public Map.Entry<Character,Short> next() {
it.advance();
char ik = it.key();
final Character key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik );
short iv = it.value();
final Short v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv );
return new Map.Entry<Character,Short>() {
private Short val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry
&& ( ( Map.Entry ) o ).getKey().equals(key)
&& ( ( Map.Entry ) o ).getValue().equals(val);
}
public Character getKey() {
return key;
}
public Short getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Short setValue( Short value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<Character,Short> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
Character key = ( ( Map.Entry<Character,Short> ) o ).getKey();
_map.remove( unwrapKey( key ) );
modified = true;
}
return modified;
}
public boolean addAll( Collection<? extends Map.Entry<Character, Short>> c ) {
throw new UnsupportedOperationException();
}
public void clear() {
TCharShortMapDecorator.this.clear();
}
};
} | 8 |
private void processChallengeResponse(HttpServletRequest request, HttpServletResponse response) {
try {
String base64_key = request.getParameter(CommunityConstants.BASE64_PUBLIC_KEY);
String base64_response = request.getParameter(CommunityConstants.CHALLENGE_RESPONSE);
/**
* First the easy cases -- do we even _know_ about this key? If not,
* no need to do crypto.
*
* This may also happen if we 1) just pruned the database, 2) and this user was in the middle of a refresh
* (although this is pretty unlikely)
*/
if (CommunityDAO.get().isRegistered(base64_key) == false) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
logger.finer("Challenge request with unknown key, dropping (unauthorized) " + request.getRemoteAddr());
return;
}
if (recentChallenges.containsKey(base64_key) == false) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
logger.finer("Challenge request without recent issue, dropping (unauthorized) " + request.getRemoteAddr());
return;
}
long originalChallenge = recentChallenges.get(base64_key);
byte[] key_bytes = Base64.decode(base64_key);
if (key_bytes == null) {
logger.warning("Couldn't decode key bytes from " + request.getRemoteAddr() + " / " + base64_key);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
byte[] response_bytes = Base64.decode(base64_response);
if (response_bytes == null) {
logger.warning("Couldn't decode challenge response from " + request.getRemoteAddr() + " / " + base64_response);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(key_bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey pub = null;
try {
pub = factory.generatePublic(pubKeySpec);
} catch (InvalidKeySpecException e) {
logger.warning("Couldn't decode valid public key from " + request.getRemoteAddr() + " / " + base64_response);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(pub);
sig.update(ByteManip.ltob(originalChallenge + 1));
if (sig.verify(response_bytes)) {
logger.fine("Signature verified, generating response " + request.getRemoteAddr());
generateAndSendKeyList(request, response);
} else {
logger.warning("Key failed challenge/response. Expected: " + (originalChallenge + 1) + " received signature didn't verify from " + request.getRemoteAddr());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
logger.severe(e.toString());
} catch (InvalidKeyException e) {
System.err.println(e);
e.printStackTrace();
} catch (SignatureException e) {
System.err.println(e);
e.printStackTrace();
}
} | 9 |
@Override
public void validate() {
if (adname == null) {
addActionError("Please Enter Ad Name");
}
if (url == null) {
addActionError("Please Enter Ad url");
}
if (adtext == null) {
addActionError("Please Enter Ad Text");
}
} | 3 |
public double calcWindow(boolean printWindow){
if(points.size() == 0) return 0;
WindowChart wc = new WindowChart("Window");
double x1 = this.lowBound[0];
double x2 = this.upperBound[0];
double y1 = this.lowBound[1];
double y2 = this.upperBound[1];
int iterations = 0;
double totalWeight = 0.0;
int recurseIterations = 0;
for(double x = x1; x <= x2; x = x + this.xgridGranularity){
for(double y = y1; y <= y2; y = y + this.ygridGranularity){
double distFromPoint;
double tileWeight = 0.0;
double[] currPoint = new double[2];
double contribution;
List<Double> nearby = new ArrayList<Double>();
for(int i = 0; i < this.points.size(); i++){
iterations++;
currPoint[0] = x;
currPoint[1] = y;
distFromPoint = GPSLib.getDistanceBetween(this.points.get(i).getCoords(),currPoint);
contribution = (-Init.CoverageWindow.SPACE_WEIGHT / Init.CoverageWindow.SPACE_RADIUS) * distFromPoint + Init.CoverageWindow.SPACE_WEIGHT;
if(contribution > Init.CoverageWindow.SPACE_TRIM){
contribution /= 100; //convert to probability so getAggProb function can work properly
nearby.add(contribution * this.points.get(i).getTimeRelevance(
Init.CoverageWindow.CURRENT_TIMESTAMP,
Init.CoverageWindow.REFERENCE_TIMESTAMP,
Init.CoverageWindow.TEMPORAL_DECAY));
}
}
double[] aggResults = new double[2];
aggResults[0] = 0;
aggResults[1] = 0;
List<Double> empty = new ArrayList<Double>();
this.trimNearby(nearby);
this.getAggProbability(aggResults,empty,nearby);
recurseIterations += aggResults[1];
if(aggResults[0] > 0)
tileWeight = aggResults[0] * 100;
else
tileWeight = 0.0;
if(printWindow){ wc.addData(currPoint,new double[]{tileWeight}); }
if(tileWeight > 100){
Init.DebugPrint("size of nearby: " + nearby.size(), 1);
Init.DebugPrint("non-opt print overflow of space weight: greater probabilty than possible", 1);
Init.DebugPrint("tileWeight: " + tileWeight, 1);
}
totalWeight += tileWeight;
}
}
if(printWindow){ wc.plot(); }
double maxWeight = ((x1 - x2) / xgridGranularity) * ((y1 - y2) / ygridGranularity) * Init.CoverageWindow.SPACE_WEIGHT;
double windowProb = totalWeight / maxWeight * 100;
Init.DebugPrint("maxWeight: " + maxWeight,3);
Init.DebugPrint("totalWeight: " + totalWeight,3);
Init.DebugPrint("#iterations: " + iterations,3);
Init.DebugPrint("#recurse iterations: " + recurseIterations,3);
Init.DebugPrint("Window Prob: " + windowProb,3);
return windowProb;
} | 9 |
public void kick(String userName){
String nickname = "";
//find the client that you want to kick
for(int i = 0; i < clients.size(); i++){
if(clients.get(i).getUser().getName().equals(userName)){
nickname = clients.get(i).getUser().getNickname();
//Removes client login privileges
clients.get(i).setIsAuthorized(false);
try {
//closes the socket
clients.get(i).s.close();
} catch (IOException e) {
serverMsg = serverMsgPrefix + "Kicking user failed\n";
}
serverMsg = serverMsgPrefix + userName + " has been kicked\n";
}
}
//goes through each contact and removes deauthorized account from their contact lists
for(Client c : clients){
if(!c.getUser().getNickname().equals(nickname))
c.sendMsg(nickname + "&1003");
}
} | 5 |
public void setFunSueldo(Integer funSueldo) {
this.funSueldo = funSueldo;
} | 0 |
public void setY(double _y) {
y = _y;
} | 0 |
public static void main(String[] args) {
int x,y,r,proceso;
x=Integer.parseInt(JOptionPane.showInputDialog("Ingrese el valor del entero X"));
y=Integer.parseInt(JOptionPane.showInputDialog("Ingrese el valor del entero Y"));
if (x<=0 || x>255)
{
r=-1;
JOptionPane.showMessageDialog(null,"Resultado "+r);
}
else
{
int[] arreglo=new int[y];
arreglo[0]=x;
for (int i = 1;i<arreglo.length; i++)
{
proceso=x/(i+1);
arreglo[i]=proceso;
}
for (int i = 0; i < arreglo.length; i++)
{
if(i==(y-1))
{
JOptionPane.showMessageDialog(null,"Resultado "+arreglo[i]);
}
}
}
} | 5 |
private void writeToDict(String dictFilename) {
// 4MB max, 22-bit offsets
dict = new byte[4 * 1024 * 1024];
dictSize = 0;
writeWordsRec(roots);
System.out.println("Dict Size = " + dictSize);
try {
FileOutputStream fos = new FileOutputStream(dictFilename);
fos.write(dict, 0, dictSize);
fos.close();
} catch (IOException ioe) {
System.err.println("Error writing dict file:" + ioe);
}
} | 1 |
private boolean recoursiveAdd(Node<T> parent, Node<T> index, Node<T> newNode) {
if (parent == null || index == null || newNode == null)
return false;
// System.out.println("Current:"+index.value+" new:"+newNode.value);
if (newNode.compareTo(index) == 0) {
// the new node will take the place of the
// node with the same value
newNode.setLeft(index);
// the right subtree of the current node
// will be the new right subtree of the new node
newNode.setRight(index.getRight());
// Update the parent child with the new node
if (index.equals(parent.getLeft()))
parent.setLeft(newNode);
else
parent.setRight(newNode);
// update the current node
index.setRight(null);
}
if (newNode.compareTo(index) < 0) {
if (index.getLeft() == null)
index.setLeft(newNode);
else
return recoursiveAdd(index, index.getLeft(), newNode);
}
if (newNode.compareTo(index) > 0) {
if (index.getRight() == null)
index.setRight(newNode);
else
return recoursiveAdd(index, index.getRight(), newNode);
}
return true;
} | 9 |
public boolean checkSpam(String channel) {
long now = System.currentTimeMillis();
if (lastAction > now - 2000) {
spam++;
if (spam == 2) {
sendButlerMessage(channel, "Bitte _NICHT spammen_ und fluten.");
} else if (spam == 3) {
disconnect();
return true;
}
} else {
spam -= (now - lastAction) / 2000;
if (spam < 0) {
spam = 0;
}
}
lastAction = now;
return false;
} | 4 |
@Before
public void setUp() {
this._instance = new NewYearsDay();
this._years = new LinkedList<Integer>();
for (int year = 1974; year < 2021; year++)
this._years.add(year);
this._newYearsDayUnitedStates = new HashMap<Integer, GregorianCalendar>();
for (int year : this._years) {
GregorianCalendar christmasDayUnitedStates = new GregorianCalendar(year, 0, 1);
switch (year){
case 1978:
case 1984:
case 1989:
case 1995:
case 2006:
case 2012:
case 2017:
christmasDayUnitedStates.add(GregorianCalendar.DATE, 1);
}
this._newYearsDayUnitedStates.put(year, christmasDayUnitedStates);
}
} | 9 |
public void run() {
while(Run.running){
try {
screen.update();
screen.paint();
fps.fpsPlus();
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} | 2 |
public void setStatic(final boolean flag) {
if (this.isDeleted) {
final String s = "Cannot change a field once it has been marked "
+ "for deletion";
throw new IllegalStateException(s);
}
int mod = methodInfo.modifiers();
if (flag) {
mod |= Modifiers.STATIC;
} else {
mod &= ~Modifiers.STATIC;
}
methodInfo.setModifiers(mod);
this.setDirty(true);
} | 2 |
private static double[] getResistPoints(int lineNumber, double[] highPrices) {
double[] rPoints = new double[lineNumber];
for(int i =0;i<lineNumber-1;i++){
double price = 0;
for(int j=-28;j<=0;j++){
if((i+j>=0) && (i+j<lineNumber-1) && highPrices[i+j]>price){
price =highPrices[i+j];
rPoints[i]=price;
}
}
}
return rPoints;
} | 5 |
public void setAddress(String address) {
this.address = address;
} | 0 |
public boolean matches( Class<?> clazz )
{
return this.a.matches( clazz ) || this.b.matches( clazz );
} | 2 |
public String mode_string()
{
switch (h_mode)
{
case STEREO:
return "Stereo";
case JOINT_STEREO:
return "Joint stereo";
case DUAL_CHANNEL:
return "Dual channel";
case SINGLE_CHANNEL:
return "Single channel";
}
return null;
} | 4 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.