text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void printReaction(){
System.out.printf(""+molReactants.get(0).toStringf()+" + "+molReactants.get(1).toStringf()+" --> ");
System.out.printf(""+molProducts.get(0).toStringf());
for(int i=1; i< molProducts.size(); i++){
System.out.printf(" + "+molProducts.get(i).toStringf());
}
System.out.printf("\n");
} | 1 |
public void setArea(BackgroundColor c, int start, int end) {
int color = c.ordinal();
if (start < 0 || start >= 60 || end < 0 || end >= 60)
return;
for (int i = start; i < end; i++)
m_hasColor[color][i] = true;
repaint();
} | 5 |
public boolean compare(Predicate.Op op, Field val) {
IntField iVal = (IntField) val;
switch (op) {
case EQUALS:
return value == iVal.value;
case NOT_EQUALS:
return value != iVal.value;
case GREATER_THAN:
return value > iVal.value;
case GREATER_THAN_OR_EQ:
return value >= iVal.value;
case LESS_THAN:
return value < iVal.value;
case LESS_THAN_OR_EQ:
return value <= iVal.value;
case LIKE:
return value == iVal.value;
}
return false;
} | 7 |
private void setAction()
{
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String username = inputUser.getText();
String password = inputPass.getText();
User user = null;
if(username.length()!=0 && password.length()!=0)
{
try {
user = model.verifyLogin(username, password);
} catch (IOException e) {
e.printStackTrace();
}
if(user != null)
{
goToQuestionListMenu(user);
}else
{
new messagebox.ShowPopup("Username or Password incorrect.","Error!!!!!",0);
view.close();
}
}
inputUser.setText(null);
inputPass.setText(null);
}
});
exitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
view.close();
}
});
} | 4 |
@Override
public int multiply(int a, int b) {
return a * b;
} | 0 |
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null || head.next == null || m >= n) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
int curPos = 0;
ListNode pre = dummy;
while (curPos < m - 1 && pre != null) { // find m-1
pre = pre.next;
curPos++;
}
ListNode cur = pre.next;
ListNode post = cur.next;
curPos++;// now is m
ListNode next;
while (curPos < n && post != null) {
next = post.next;
post.next = cur;
cur = post;
post = next;
curPos++;
}
next = pre.next;
pre.next = cur;
next.next = post;
return dummy.next;
} | 7 |
@Override
public void onEnable() {
getConfig().options().copyDefaults(true);
saveConfig();
allDeaths = getConfig().getDouble("dropSkulls.allDeaths", 0);
killedByPlayer = getConfig().getDouble("dropSkulls.killedByPlayer", 1);
placeInKillerInv = getConfig().getBoolean("dropSkulls.placeInKillerInv", false);
tax = getConfig().getDouble("bounty.tax", 0.05D);
minimumBounty = getConfig().getDouble("bounty.minimum", 10);
huntedDropOnly = getConfig().getBoolean("bounty.huntedDropOnly", false);
canClaimOwn = getConfig().getBoolean("bounty.canClaimOwn", true);
getServer().getPluginManager().registerEvents(this, this);
getCommand("setname").setExecutor(new SetNameCommand());
getCommand("clearname").setExecutor(new ClearNameCommand());
getCommand("spawnhead").setExecutor(new SpawnHeadCommand(this));
getCommand("bounty").setExecutor(new BountyCommand(this));
if (getConfig().getBoolean("bounty.enabled")) {
bounties = setupEconomy();
if (bounties)
getLogger().info("Econ detected");
else
getLogger().info("Econ not detected");
}
if (bounties) {
if (getConfig().getString("datastorage").equalsIgnoreCase("mysql")) {
try {
dsi = new MySQLDataStorageImplementation(this, getConfig().getString("database.url"), getConfig().getString("database.username"), getConfig().getString("database.password"));
} catch (SQLException e) {
getLogger().log(Level.SEVERE, "Error connecting to mysql database", e);
bounties = false;
}
} else if (getConfig().getString("datastorage").equalsIgnoreCase("yaml")) {
try {
dsi = new YamlDataStorageImplementation(this);
} catch (IOException e) {
getLogger().log(Level.SEVERE, "Error setting up yaml storage", e);
bounties = false;
}
}
}
if (bounties)
getLogger().info("Bounties enabled");
else
getLogger().info("Bounties not enabled");
} | 8 |
public FileIO(String directory, String fi, boolean app){
log = new Logger();
s = System.getProperty("file.separator");
File dir = new File(directory);
if (!dir.exists()){
dir.mkdirs();
}
// get the path to the file
file = new File(directory + s, fi);
try {
if (!file.canWrite()){
file.createNewFile();
}
reader = new BufferedReader(new FileReader(file));
writer = new PrintWriter(new FileWriter(file, app));
} catch (FileNotFoundException e){
log.writeErr("Could not access file: " + file.getAbsolutePath() + "\nError was: " + e.getMessage());
} catch (IOException ex) {
log.writeErr("Could not read/write to file: " + file);
}
} | 4 |
private String getToken(boolean quoted) {
// Trim leading white spaces
while ((i1 < i2) && (Character.isWhitespace(chars[i1]))) {
i1++;
}
// Trim trailing white spaces
while ((i2 > i1) && (Character.isWhitespace(chars[i2 - 1]))) {
i2--;
}
// Strip away quotes if necessary
if (quoted) {
if (((i2 - i1) >= 2) && (chars[i1] == '"') && (chars[i2 - 1] == '"')) {
i1++;
i2--;
}
}
String result = null;
if (i2 > i1) {
result = new String(chars, i1, i2 - i1);
}
return result;
} | 9 |
public void click(final MenuItem CLICKED_ITEM) {
List<Transition> transitions = new ArrayList<>(items.size() * 2);
for (Parent node : items.keySet()) {
if (items.get(node).equals(CLICKED_ITEM)) {
// Add enlarge transition to selected item
ScaleTransition enlargeItem = new ScaleTransition(Duration.millis(300), node);
enlargeItem.setToX(5.0);
enlargeItem.setToY(5.0);
transitions.add(enlargeItem);
} else {
// Add shrink transition to all other items
ScaleTransition shrinkItem = new ScaleTransition(Duration.millis(300), node);
shrinkItem.setToX(0.0);
shrinkItem.setToY(0.0);
transitions.add(shrinkItem);
}
// Add fade out transition to every node
FadeTransition fadeOutItem = new FadeTransition(Duration.millis(300), node);
fadeOutItem.setToValue(0.0);
transitions.add(fadeOutItem);
}
// Add rotate and fade transition to main menu button
if (options.isButtonHideOnSelect()) {
RotateTransition rotateMainButton = new RotateTransition(Duration.millis(300), mainMenuButton);
rotateMainButton.setToAngle(225);
transitions.add(rotateMainButton);
FadeTransition fadeOutMainButton = new FadeTransition(Duration.millis(300), mainMenuButton);
fadeOutMainButton.setToValue(0.0);
transitions.add(fadeOutMainButton);
ScaleTransition shrinkMainButton = new ScaleTransition(Duration.millis(300), mainMenuButton);
shrinkMainButton.setToX(0.0);
shrinkMainButton.setToY(0.0);
transitions.add(shrinkMainButton);
} else {
RotateTransition rotateBackMainButton = new RotateTransition();
rotateBackMainButton.setNode(cross);
rotateBackMainButton.setToAngle(0);
rotateBackMainButton.setDuration(Duration.millis(200));
rotateBackMainButton.setInterpolator(Interpolator.EASE_BOTH);
transitions.add(rotateBackMainButton);
FadeTransition mainButtonFadeOut = new FadeTransition();
mainButtonFadeOut.setNode(mainMenuButton);
mainButtonFadeOut.setDuration(Duration.millis(100));
mainButtonFadeOut.setToValue(options.getButtonAlpha());
transitions.add(mainButtonFadeOut);
}
// Play all transitions in parallel
ParallelTransition selectTransition = new ParallelTransition();
selectTransition.getChildren().addAll(transitions);
selectTransition.play();
// Set menu state back to closed
setState(State.CLOSED);
mainMenuButton.setOpen(false);
} | 3 |
@Override
public GameState doAction(GameState state, Card card, int time) {
if(time == Time.DAY)
{
//Do nothing
}
else if(time == Time.DUSK)
{
PickTreasure temp = new PickTreasure();
state = temp.doAction(state, card, time);
}
else if(time == Time.NIGHT)
{
state = freedSlaveNightAction(state, card, true);
}
return state;
} | 3 |
protected void moveToNewLocation(int flag, double supp, double conf,
double dsupp, double dconf, double accuracy, int numCRs) {
switch (flag) {
case 0: // Increase support (north)
moveLocDataForIncSupp();
break;
case 1: // Increase support and confidence (north-east)
moveLocDataForIncSuppIncConf();
break;
case 2: // Increase confidence (east)
moveLocDataForIncConf();
break;
case 3: // Decrease support and increase confidence (south-east)
moveLocDataForIncSuppDecConf();
break;
case 4: // Decrease support (south))
moveLocDataForDecSupp();
break;
case 5: // Decrease support and confidence (south-west)
moveLocDataForDecSuppDecConf();
break;
case 6: // Decrease confidence (west)
moveLocDataForDecConf();
break;
case 7: // Increase support and decrease confidence (north-west)
moveLocDataForDecSuppIncConf();
break;
default:
JOptionPane.showMessageDialog(null,"Unexpected hill climbing " +
"error","HILL CLIMBING ERROR",JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
if (textArea==null) System.out.println("MOVE");
else textArea.append("MOVE\n");
// Proceed with move
hillClimbing(supp,conf,dsupp,dconf,accuracy,numCRs);
} | 9 |
public boolean stoppingStrategy(int[] bowl, int round) {
int choicesLeft, cutoff = 0;
boolean pickFlag = false;
choice++;
choicelist[choice] = bowl.clone();
if (round == 0) {
choicesLeft = nplayers - index - choice;
if((choice + 1) > Math.round((nplayers - index) / Math.E))
pickFlag = true;
} else {
choicesLeft = nplayers + 1 - choice;
if((choice + 1) > Math.round((nplayers + 1) / Math.E))
pickFlag = true;
}
for (int i = choice - 1, j = 0; i > -1 && j < Math.round(choicesLeft / (Math.E - 1)); i--, j++) {
if(bowlScore(choicelist[i]) > cutoff)
cutoff = bowlScore(choicelist[i]);
}
if((pickFlag && bowlScore(bowl) > cutoff) || (bowlScore(bowl) > (int) (9.0 * bowlSize)))
return true;
return false;
} | 9 |
@Override
public void onReceiveStart(long totalBytes) {
System.out.print(totalBytes);
} | 0 |
private static int search1(Cards[] hands, Cards board, int numhands, int[] wins, int[] ties, Cards remaining) {
int total = 0;
for (Card card1 : remaining) {
board.add(card1);
total = rankHands(hands, board, numhands, wins, ties, total);
board.remove(card1);
}
return total;
} | 1 |
private void btnExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportActionPerformed
String input = Utils.showFileChooser("Opslaan", "Tijdlijst");
if (!input.isEmpty()) {
boolean inverted = Utils.promptQuestion("Wilt u de tabel omgedraaid of precies zoals hierboven?", false, "Zoals hierboven", "Omgedraaid");
ExcelExporter.Export(tblTimesheet, new File(input.contains(".xls") ? input : input + ".xls"), inverted);
}
}//GEN-LAST:event_btnExportActionPerformed | 2 |
@Override
public void onMeasure(int width, int height) {
super.onMeasure(width, height);
int totalWidth = 0;
int totalHeight = 0;
if (children.size() == 0) {
totalHeight = 10; // TODO This is so bad, but if onMeasure is called before children are added...what can we do?
}
for (View child : children) {
child.measure(child.getLayoutParameters().getWidth(), child.getLayoutParameters().getHeight());
if (width == View.LayoutParameters.WRAP_CONTENT) {
totalWidth += child.getMeasuredWidth();
}
if (height == View.LayoutParameters.WRAP_CONTENT) {
if (child.getMeasuredHeight() > totalHeight) {
totalHeight = child.getMeasuredHeight();
}
}
}
int finalWidth = 0;
if (width == View.LayoutParameters.WRAP_CONTENT) {
finalWidth = totalWidth;
} else {
// Width must not be greater than the parent width
if (width > getParentWidth()) {
width = getParentWidth();
Debug.log("Specified width was too large, changing to match parent.");
}
finalWidth = width;
}
int finalHeight = 0;
if (height == View.LayoutParameters.WRAP_CONTENT) {
finalHeight = totalHeight;
} else {
// Height must not be greater than the parent height
if (height > getParentHeight()) {
height = getParentHeight();
Debug.log("Specified height was too large, changing to match parent for %s", getId());
}
finalHeight = height;
}
Debug.log("Setting in ViewGroup %s: Width=%s; Height=%s", getId(), finalWidth, finalHeight);
setMeasuredDimension(finalWidth, finalHeight);
} | 9 |
@Override
public void update() {
// If player wishes to skip screen
if(Keybind.CONFIRM.clicked()) {
// Remove current screen
splashImages.poll();
// Stop any sound effects playing
// Restart screen if a new one exists
if(!splashImages.isEmpty()) {
timer = 5f;
Camera.get().addScreenEffect(new TintEffect(new Vector4f(0f, 0f, 0f, 0f), 1f, true, Tween.IN));
// Proceed with setup swap
} else {
Camera.get().cancelAllEffects();
Theater.get().setSetup(new TitleMenu());
}
}
// Adjust fading and reduce timer
if(timer > 0f) {
timer -= Theater.getDeltaSpeed(0.025f);
// If a sound effect is to be played
if(timer < 4f && !dinged) {
//Ensemble.get().playSoundEffect(new SoundEffect("Just Like Make Game", 0.75f, false));
dinged = true;
}
// Start fading out
if(timer <= 1f && Camera.get().getTint().w == 0f) {
Camera.get().addScreenEffect(new TintEffect(new Vector4f(0f, 0f, 0f, 1f), timer, true, Tween.OUT));
}
} else {
// Remove current screen
splashImages.poll();
// Restart screen if a new one exists
if(!splashImages.isEmpty()) {
timer = 5f;
Camera.get().addScreenEffect(new TintEffect(new Vector4f(0f, 0f, 0f, 0f), 1f, true, Tween.IN));
// Proceed with setup swap
} else {
Theater.get().setSetup(new TitleMenu());
}
}
} | 8 |
public void combine(String IP_PORT,String apiKey){
DBService dbService = new DBService();
HashMap data = null;
if(link.contains("dgtle")){
PageDgtle pageDgtle = new PageDgtle();
data = pageDgtle.getInfo(this.link);
}
if(link.contains("huxiu")){
PageHuxiu pageHuxiu = new PageHuxiu();
data = pageHuxiu.getInfo(this.link);
}
if(link.contains("leiphone")){
PageLeiphone pageLeiphone = new PageLeiphone();
data = pageLeiphone.getInfo(this.link);
}
if(link.contains("36kr")){
PageKr36 pageKr36 = new PageKr36();
data = pageKr36.getInfo(this.link);
}
FileService fileService = new FileService();
ArrayList<String> bodyTxt = (ArrayList<String>) data.get("content");
ArrayList<String> bodyPic = (ArrayList<String>) data.get("bodyPicPieces");
String title = this.title;
String smalldesc = this.smalldesc;
String source = (String) data.get("source");
String releasetime = this.releasetime.length()>1?this.releasetime:(String) data.get("releasetime");
String curl = this.link;
String createtime = FormatTime.getCurrentFormatTime();
String classify = this.classify;
String smallurl = fileService.uploadPic(this.imgUrl, IP_PORT, apiKey);
String cont = contentMix(bodyTxt,bodyPic,IP_PORT,apiKey,curl);
String contId = fileService.uploadFile(createtime,cont,IP_PORT,apiKey);
MyLog.logINFO("contentId:" + contId);
if(smallurl.length()==0 || (smallurl.length()>33&&smallurl.contains("."))){
Debug.showDebut(this.imgUrl, smallurl);
dbService.insertNews(title,smalldesc,smallurl,source,releasetime,contId,classify,curl,createtime);
}
} | 8 |
public boolean removeCompletely(String name) {
Connection conn = null;
PreparedStatement ps = null;
try
{
conn = iConomy.getiCoDatabase().getConnection();
ps = conn.prepareStatement("DELETE FROM " + Constants.SQLTable + " WHERE username = ? LIMIT 1");
ps.setString(1, name);
ps.executeUpdate();
ps.clearParameters();
ps = conn.prepareStatement("DELETE FROM " + Constants.SQLTable + " WHERE account_name = ?");
ps.setString(1, name);
ps.executeUpdate();
} catch (Exception e) {
return false;
}
finally
{
if (ps != null) try {
ps.close();
} catch (SQLException ex) {
} if (conn != null) try {
conn.close();
} catch (SQLException ex) {
}
}
return true;
} | 5 |
public static void main(String[] args)
{
String[][] cartoons =
{
{ "Flintstones", "Fred", "Wilma", "Pebbles", "Dino" },
{ "Rubbles", "Barney", "Betty", "Bam Bam" },
{ "Jetsons", "George", "Jane", "Elroy", "Judy",
"Rosie", "Astro" },
{ "Scooby Doo Gang", "Scooby Doo", "Shaggy", "Velma",
"Fred", "Daphne" } };
for (int i = 0; i < cartoons.length; i++)
{
System.out.print(cartoons[i][0] + ": ");
for (int j = 1; j < cartoons[i].length; j++)
{
System.out.print(cartoons[i][j] + " ");
}
System.out.println();
}
log.debug("All Done");
} | 2 |
@Override
public String getGoTo() {
return null;//goToList;
} | 0 |
public void createFSFolders(int currentLevel, String currentPath) {
if (currentLevel > this.levels) {
return;
}
for (int i = 0; i < this.foldersPerLevel; i++) {
try {
String folderName = "l" + currentLevel + "-c" + (i + 1);
FileUtils.forceMkdir(new File(currentPath + folderName));
String newPath = currentPath + folderName;
// Save new folder path
this.folders.add(newPath.substring(this.fsFolder.length() - 1));
createFSFolders(currentLevel + 1, newPath + "/");
} catch (IOException e) {
logger.error("Error creating a folder.");
e.printStackTrace();
}
}
} | 3 |
private void fetchingEmails() {
/* Ab Java 7: try-with-resources mit automat. close benutzen! */
try {
/* Socket erzeugen --> Verbindungsaufbau mit dem Server */
clientSocket = new Socket(user.getServerAdress(), user.getPort());
/* Socket-Basisstreams durch spezielle Streams filtern */
outToServer = new DataOutputStream( clientSocket.getOutputStream( ));
inFromServer = new BufferedReader( new InputStreamReader(clientSocket.getInputStream()) );
/** valid ist der Rückgabewert der einzelnen Merhoden */
boolean valid = false;
valid = serverStatus();
/** Benutzer ok? */
if (valid) {
valid = fireUSER();
}
/** Passwort ok? */
if (valid) {
valid = firePASS();
}
/** Benutzer und Passwort ok */
if (valid) {
// writeToServer("LIST");
//
// readFromServer();
int amountOfMails = getAmountOfMailsByFireSTAT();
if (amountOfMails > 0) {
saveMailsLocalyByFireingUIDLandRETRandDELE(amountOfMails);
}
}
/** Verbindung schließen */
closeConnection();
} catch (IOException e) {
System.err.println("Connection aborted by server!");
}
} | 5 |
public String readString(int sz) throws IOException {
if (sz == 0) return null;
byte[] buf = new byte[sz];
int i = 0;
for (; i<sz; i++) {
int b = read();
if (b == 0) break;
buf[i] = (byte)b;
}
if (i == 0) return null;
return new String(buf, 0, i);
} | 4 |
public void setUserId(String userId) {
this.userId = userId;
} | 0 |
final public ASTN_Recipient N_Recipient() throws ParseException {
/*@bgen(jjtree) N_Recipient */
ASTN_Recipient jjtn000 = new ASTN_Recipient(JJTN_RECIPIENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
try {
N_PluginExp();
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
{if (true) return jjtn000;}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{if (true) throw (RuntimeException)jjte000;}
}
if (jjte000 instanceof ParseException) {
{if (true) throw (ParseException)jjte000;}
}
{if (true) throw (Error)jjte000;}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
}
}
throw new Error("Missing return statement in function");
} | 9 |
@SuppressWarnings("unchecked")
public static void unzip(String zipFileName, String extPlace) throws Exception {
try {
(new File(extPlace)).mkdirs();
File f = new File(zipFileName);
ZipFile zipFile = new ZipFile(zipFileName);
if((!f.exists()) && (f.length() <= 0)) {
throw new Exception("要解压的文件不存在!");
}
String strPath, gbkPath, strtemp;
File tempFile = new File(extPlace);
strPath = tempFile.getAbsolutePath();
java.util.Enumeration e = zipFile.getEntries();
while(e.hasMoreElements()){
org.apache.tools.zip.ZipEntry zipEnt = (ZipEntry) e.nextElement();
gbkPath=zipEnt.getName();
if(zipEnt.isDirectory()){
strtemp = strPath + File.separator + gbkPath;
File dir = new File(strtemp);
dir.mkdirs();
continue;
} else {
//读写文件
InputStream is = zipFile.getInputStream(zipEnt);
BufferedInputStream bis = new BufferedInputStream(is);
gbkPath=zipEnt.getName();
strtemp = strPath + File.separator + gbkPath;
//建目录
String strsubdir = gbkPath;
for(int i = 0; i < strsubdir.length(); i++) {
if(strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) {
String temp = strPath + File.separator + strsubdir.substring(0, i);
File subdir = new File(temp);
if(!subdir.exists())
subdir.mkdir();
}
}
FileOutputStream fos = new FileOutputStream(strtemp);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int c;
while((c = bis.read()) != -1) {
bos.write((byte) c);
}
bos.close();
fos.close();
bis.close();
}
}
zipFile.close();
} catch(Exception e) {
e.printStackTrace();
throw e;
}
} | 9 |
public Sprite(int[] pixels, int width, int height) {
this.pixels = pixels;
this.width = width;
this.height = height;
} | 0 |
public void addCSV(String absolutePath, int readMode) {
String s = "";
RosterDB newDB = readCSV (absolutePath);
for (Roster r: newDB.getRosters()) {
if (rosterExists (r) && (readMode == READ_MODE_ADD)) {
s += "Ignoriere doppelten Fahrtenleiter " + r.getGivenName() + " " + r.getFamilyName() + "\n";
}
else {
add (r.getFamilyName(), r.getGivenName(), r.getPhoneNumber(), r.getIsAspirant());
s += "Neuer Fahrtenleiter " + r.getGivenName() + " " + r.getFamilyName() + "\n";
}
}
setIsDataChanged (true);
JOptionPane.showMessageDialog(null,
s, "Fahrtenleiter importiert",
JOptionPane.OK_OPTION);
} | 3 |
private void buildBoard() {
int rows = polymino.boardRows();
int cols = polymino.boardCols();
if (board == null) {
board = new int[rows][cols];
}
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
if (polymino.getBoard()[row][col]) {
// wall
board[row][col] = -2;
} else {
// unoccupied
board[row][col] = -1;
}
}
}
for (PiecePart constraint : stack) {
int pieceRows = constraint.pieceRows();
int pieceCols = constraint.pieceCols();
int boardRow = constraint.boardRow();
int boardCol = constraint.boardCol();
int id = constraint.getPiece().getId();
for (int row = 0; row < pieceRows; ++row) {
for (int col = 0; col < pieceCols; ++col) {
if (constraint.occupied(row, col)) {
board[boardRow + row][boardCol + col] = id;
}
}
}
}
} | 8 |
public void attachHost(GridSimCore entity, PacketScheduler sched)
{
String msg = super.get_name() + ".attachHost(): Error - ";
if (entity == null)
{
System.out.println(msg + "the entity is null.");
return;
}
if (sched == null)
{
System.out.println(msg + "the packet scheduler is null.");
return;
}
Link link = entity.getLink();
sched.setBaudRate( link.getBaudRate() );
link.attach(this, entity);
linkTable.put( entity.get_name(), link.get_name() );
if (!schedTable.containsKey( link.get_name() )) {
schedTable.put(link.get_name(), sched);
}
hostTable.put( link.get_name(), entity.get_name() );
// recording ...
if (reportWriter_ != null)
{
StringBuffer sb = null;
sb = new StringBuffer("attach this ROUTER, to entity, ");
sb.append( entity.get_name() );
sb.append(", with packet scheduler, ");
sb.append( sched.getSchedName() );
super.write( sb.toString() );
}
} | 4 |
public int largestRectangleArea(int[] height) {
int maxRect = 0;
int[] moreHeight = new int[height.length+1];
for(int i=0; i<height.length; i++)
moreHeight[i] = height[i];
Stack<Integer> stack = new Stack<Integer>();
for(int i=0; i<moreHeight.length; i++){
if(!stack.isEmpty() && moreHeight[i] < moreHeight[stack.peek()]){
while(!stack.isEmpty() && moreHeight[i] < moreHeight[stack.peek()]){
int curHeight = moreHeight[stack.pop()];
if(stack.isEmpty()) maxRect = Math.max(maxRect, i * curHeight);
else maxRect = Math.max(maxRect, (i - stack.peek() - 1) * curHeight);
}
}
stack.push(i);
}
return maxRect;
} | 7 |
private void resize() {
width = getWidth();
height = getHeight();
if (width > 0 && height > 0) {
background.setCache(false);
flap.setCache(false);
background.setFitWidth(width);
background.setFitHeight(height);
flap.setFitWidth(width * 0.8461538462);
flap.setFitHeight(height * 0.407960199);
if (width < height) {
flap.setTranslateX(width * 0.0769230769);
flap.setTranslateY(width * 0.0769230769);
rotateFlap.setPivotY(width * 0.715);
} else {
flap.setTranslateX(height * 0.0447761194);
flap.setTranslateY(height * 0.0447761194);
rotateFlap.setPivotY(height * 0.460199005);
}
background.setCache(true);
flap.setCache(true);
flap.setCacheHint(CacheHint.ROTATE);
font = Font.font("Droid Sans Mono", background.getLayoutBounds().getHeight() * 0.7);
upperBackgroundText.setWidth(flap.getLayoutBounds().getWidth());
upperBackgroundText.setHeight(flap.getLayoutBounds().getHeight());
upperBackgroundText.setTranslateX(flap.getTranslateX());
upperBackgroundText.setTranslateY(flap.getTranslateY());
lowerBackgroundText.setWidth(flap.getLayoutBounds().getWidth());
lowerBackgroundText.setHeight(flap.getLayoutBounds().getHeight());
lowerBackgroundText.setTranslateX(flap.getTranslateX());
lowerBackgroundText.setTranslateY(0.4701492537 * background.getLayoutBounds().getHeight());
flapTextFront.setWidth(flap.getLayoutBounds().getWidth());
flapTextFront.setHeight(flap.getLayoutBounds().getHeight());
flapTextFront.setTranslateX(flap.getTranslateX());
flapTextFront.setTranslateY(flap.getTranslateY());
flapTextBack.setWidth(flap.getLayoutBounds().getWidth());
flapTextBack.setHeight(flap.getLayoutBounds().getHeight());
flapTextBack.setTranslateX(flap.getTranslateX());
flapTextBack.setTranslateY(flap.getTranslateY());
ctxUpperBackgroundText.setFont(font);
ctxLowerBackgroundText.setFont(font);
ctxTextFront.setFont(font);
ctxTextBack.setFont(font);
refreshTextCtx();
}
} | 3 |
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == cancelButton)
closeWindow();
else if (e.getSource() == okButton)
{
String name = (String) comboBoxUnitName.getSelectedItem();
double azimuth = Utility.stringToDouble(textFieldAzimuth.getText());
double elevation = Utility.stringToDouble(textFieldElevation.getText());
double rotation = Utility.stringToDouble(textFieldRotation.getText());
double width = Utility.stringToDouble(textFieldWidth.getText());
double height = Utility.stringToDouble(textFieldHeight.getText());
if ( azimuth == Double.MAX_VALUE
|| elevation == Double.MAX_VALUE
|| rotation == Double.MAX_VALUE
|| width == Double.MAX_VALUE
|| height == Double.MAX_VALUE )
JOptionPane.showMessageDialog(this, "Every item must have a valid number");
else
{
if (parentWindow != null)
{
// In case name was changed
if (toBeEdited != null)
parentWindow.removeUnit(toBeEditedName);
// Create new Unit and add it to parent
UnitVideoProjector unit = new UnitVideoProjector(name, azimuth, elevation, rotation, width, height);
parentWindow.addUnit(unit);
}
closeWindow();
}
}
} | 9 |
@Override
public MapConnector<String, Double> forceSynchronization() throws Exception {
try (Connection con = getConnectorInfo().getConnection()) {
forceClear();
int n = 0;
StringBuilder values = new StringBuilder();
String stm;
for (String s : getMap().keySet()) {
values = values.append("(").append("'").append(s).append("'").append(",").append(getMap().get(s)).append(")");
if (n + 1 != BLOCK_INSERT_COUNT && n + 1 != getMap().size() - 1) {
values = values.append(",");
}
n++;
if (n == BLOCK_INSERT_COUNT || n == getMap().size() - 1) {
stm = "INSERT INTO " + getConnectorInfo().getTableName() + "(key,value) VALUES " + values.toString() + ";";
try (PreparedStatement prepStm = con.prepareStatement(stm)) {
prepStm.execute();
}
values = new StringBuilder();
n = 0;
}
}
}
return this;
} | 5 |
private List<Subset> generateNeighborhood(BitSet S, int numNeighborhood)
throws Exception{
int counter = 0;
List<Subset> neighborhood = new ArrayList<Subset>();
int numAttribs = (m_classIndex == -1) ? m_numAttribs : m_numAttribs - 1;
if(numNeighborhood >= numAttribs){
for (int i = 0; i < m_numAttribs; i++) {
if(i == m_classIndex)continue;
BitSet aux = (BitSet)S.clone ();
aux.flip (i);
if(!m_vectorTabu.contains (aux)){
neighborhood.add (new Subset((BitSet)aux.clone (), ASEvaluator.evaluateSubset (aux)));
m_totalEvals ++;
}
}
}
else{
while (counter < numNeighborhood) {
BitSet aux = (BitSet)S.clone ();
int randomNumber = m_random.nextInt (m_numAttribs);
if(randomNumber == m_classIndex)
continue;
aux.flip (randomNumber);
if(!m_vectorTabu.contains (aux)){
neighborhood.add (new Subset((BitSet)aux.clone (), ASEvaluator.evaluateSubset (aux)));
m_totalEvals ++;
counter ++;
}
}
}
if(neighborhood.isEmpty ())
return null;
return bubbleSubsetSort (neighborhood);
} | 9 |
public static String getHash(String text) {
try {
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(text.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1, digest);
String hashtext = bigInt.toString(16);
// If needed, insert zeros to get 32 chars
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
} catch (Exception e) {
}
return null;
} | 2 |
public static final void compress(final File zippedFile,
final IOHandler ioHandler, final File... files) {
try {
if (!zippedFile.exists()) {
// create file write zip header
final OutputStream out = ioHandler.openOut(zippedFile);
final ZipOutputStream zipOut = new ZipOutputStream(out);
zipOut.close();
ioHandler.close(out);
}
final ZipFile zip = new ZipFile(zippedFile);
final ZipOutputStreams outs = ZipCompression
.openOut(zip, ioHandler);
final ZipOutputStream out = outs.zipOutputStream;
final java.nio.file.Path zipPath = zippedFile.toPath().getParent();
for (final File file : files) {
final String relName = zipPath.relativize(file.toPath())
.toString();
// System.out.println(relName);
final ZipEntry entry = new ZipEntry(relName);
final InputStream in = ioHandler.openIn(file);
final byte[] buff = new byte[16000];
int read;
out.putNextEntry(entry);
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
ioHandler.close(in);
out.closeEntry();
}
out.close();
zip.close();
ioHandler.close(outs.out);
// test
} catch (final IOException e) {
zippedFile.delete();
ioHandler.handleException(ExceptionHandle.TERMINATE, e);
}
} | 4 |
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
JTabbedPane contentPane = new JTabbedPane();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.add("Owners", ownerGui.getMainPanel());
contentPane.add("Models", modelGui.getMainPanel());
contentPane.add("Vehicles", vehicleGui.getMainPanel());
contentPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
int tabIndex = ((JTabbedPane) e.getSource()).getSelectedIndex();
switch (tabIndex) {
case 0:
ownerGui.update();
break;
case 1:
modelGui.update();
break;
case 2:
vehicleGui.update();
break;
}
}
});
JFrame frame = new JFrame();
frame.setTitle("OrgaTaxe");
frame.setContentPane(contentPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
URL imageURL = frame.getClass().getResource("/ressource/image/valid.png");
if (imageURL != null) {
frame.setIconImage(new ImageIcon(imageURL).getImage());
}
buildMenuBar(frame);
frame.pack();
frame.setVisible(true);
// Taxe JDialog
taxeTable.setModels(new TaxeTableModel());
taxeDialog = new JDialog(frame);
taxeDialog.getContentPane().add(taxeTable.getMainPanel());
taxeDialog.pack();
} | 8 |
public String getPrenom() {
return prenom;
} | 0 |
@Override
public void onDraw(Graphics G, int viewX, int viewY) {
if (X>viewX&&X<viewX+300&&Y>viewY&&Y<viewY+300)
{
G.setColor(Color.lightGray);
int deg = r.nextInt(360);
G.fillArc((int)(X-1)-viewX, (int)(Y-1)-viewY, 2, 2, deg, 15);
deg = r.nextInt(360);
G.fillArc((int)(X-2)-viewX, (int)(Y-2)-viewY, 4, 4, deg, 15);
G.setColor(Color.white);
deg = r.nextInt(360);
G.fillArc((int)(X-3)-viewX, (int)(Y-3)-viewY, 6, 6, deg, 15);
deg = r.nextInt(360);
G.fillArc((int)(X-4)-viewX, (int)(Y-4)-viewY, 8, 8, deg, 15);
}
} | 4 |
public User verifyUser(User user){
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
String url = "jdbc:derby:" + DBName;
Connection connection = DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sqlStatement = "SELECT * FROM users WHERE juser='" + user.getUsername() + "' AND jpassword='" + new String(user.getPassword()) + "'";
ResultSet rs = statement.executeQuery(sqlStatement);
if (rs.next()) {
user.setID(rs.getInt("uid"));
user.setValidLogin(true);
user.setNick(rs.getString("jnick"));
user.setLevel(rs.getInt("level"));
user.setCurrentExp(rs.getInt("currentExp"));
user.setrCoins(rs.getInt("rcoins"));
user.setvCoins(rs.getInt("vcoins"));
user.setPoints(rs.getInt("points"));
user.setLastLogin(rs.getTimestamp("jlastloggin"));
}
statement.close();
connection.close();
} catch (Exception e) {
new ServerResultFrame(e.getMessage());
}
return user;
} | 2 |
@Override
public void saveDefaultStudy(Study study) {
if(study == null) {
// If unsetting study, delete file
File f = new File("./studies/.defaultstudy");
f.delete();
return;
}
PrintWriter out = null;
try {
// Write study name to file
out = new PrintWriter("./studies/.defaultstudy");
out.print(study.getName());
} catch (FileNotFoundException ex) {
// Can't do anything about this.
Logger.getLogger(LocalConnection.class.getName()).log(Level.SEVERE, null, ex);
} finally {
// Close file.
if(out != null)
out.close();
}
} | 3 |
public List<Contact> getListOfTelephoneBookRecord() {
System.out.println("Telephone book: ");
List listOfContacts = new ArrayList();
try {
byte[] resp = getResponsesFromEFandSelectDF(DatabaseOfEF.EF_ADN);
for (int i = 1; i <= Converter.getSizes(resp)[2]; i++) {
Contact contact = new Contact(worker.readRecord(i, worker.getResponse(worker.select(DatabaseOfEF.EF_ADN.getFID()))));
contact.setIndex(i);
if (!contact.getPhoneNumber().equals("")) {
System.out.println(contact);
listOfContacts.add(contact); //add only relevant data to container
}
}
} catch (Exception ex) {
Logger.getLogger(CardManager.class.getName()).log(Level.SEVERE, null, ex);
}
return listOfContacts;
} | 3 |
public Object createObjectInstance(String name) throws Exception {
if (!loaded_component_classes.containsKey(name)) {
Logger.getLogger(GameScriptManager.class.getName()).log(Level.SEVERE, "Class not loaded: {0}.", name);
throw new JMException("Class not loaded: " + name);
}
Object ret = null;
try {
Class temp = loaded_component_classes.get(name);
ret = temp.newInstance();
} catch (IllegalAccessException e) {
Logger.getLogger(GameScriptManager.class.getName()).log(Level.SEVERE,
"Illegal Access Exception when creating object: {0}", name);
throw e;
} catch (InstantiationException e) {
Logger.getLogger(GameScriptManager.class.getName()).log(Level.SEVERE,
"Instantiation Exception when creating object: {0}", name);
throw e;
} catch (ExceptionInInitializerError e) {
Logger.getLogger(GameScriptManager.class.getName()).log(Level.SEVERE,
"Exception In Initializor Error when creating object: {0}", name);
throw e;
} catch (SecurityException e) {
Logger.getLogger(GameScriptManager.class.getName()).log(Level.SEVERE,
"Security Exception when creating object: {0}", name);
throw e;
}
return ret;
} | 5 |
static final void method1418(int i, int j, int k, boolean flag) {
if (!flag) {
anInt4310 = -73;
}
if (i != 1002) {
if (i == 1001) {
Class142_Sub6.method1255(k, j, 0x7fffffff, 11);
return;
}
if (i != 1011) {
if (i == 1006) {
Class142_Sub6.method1255(k, j, 0x7fffffff, 13);
return;
}
if (i == 1003) {
Class142_Sub6.method1255(k, j, 0x7fffffff, 14);
return;
}
} else {
Class142_Sub6.method1255(k, j, 0x7fffffff, 12);
}
return;
} else {
Class142_Sub6.method1255(k, j, 0x7fffffff, 10);
return;
}
} | 6 |
private void manageClients() {
manage = new Thread("Manage") {
public void run() {
while (running) {
sendToAll("/i/server");
sendStatus();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < clients.size(); i++) {
ServerClient c = clients.get(i);
if (!clientResponse.contains(c.getID())) {
if (c.attempt >= MAX_ATTEMPTS) {
disconnect(c.getID(), false);
} else {
c.attempt++;
}
} else {
clientResponse.remove(new Integer(c.getID()));
c.attempt = 0;
}
}
}
}
};
manage.start();
} | 5 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Site)) {
return false;
}
Site other = (Site) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} | 5 |
public static String max(String v1,String v2){
if(v1 != null && v2 == null){
return v1;
}
if(v2 != null && v1 == null){
return v2;
}
if(v1 == null && v2 == null){
return null;
}
ListItem v1c = parseVersion(v1);
ListItem v2c = parseVersion(v2);
if(v1c.compareTo(v2c) > 0){
return v1;
} else {
return v2;
}
} | 7 |
public void addList(String... items) {
String collector = "(list ";
for (String item : items)
collector += item + " ";
collector += ")";
arguments.add(collector);
} | 1 |
@Test
public void validationIntegerWithIntegerPositiveTest() {
view.getNumberOfPointsTextField().setText("1");
view.getNumberOfPointsTextField().getFocusListeners()[0].focusLost(focusEvent);
assertTrue(view.getDrawButton().isEnabled());
} | 0 |
@Override
public void channelCommand(MessageEvent<PircBotX> event) throws IllegalAccessException, SQLException, InstantiationException {
super.channelCommand(event);
if(Permissions.isModerator(user,event, true)){
if(args[1].equalsIgnoreCase("add")){
try {
addRegular(args[2], event);
} catch (SQLException e) {
e.printStackTrace();
}
}else if(args[1].equalsIgnoreCase("del") || args[1].equalsIgnoreCase("remove")){
try {
removeRegular(args[2], event);
} catch (SQLException e) {
e.printStackTrace();
}
}else if(args[1].equalsIgnoreCase("check")){
try {
if(isRegular(args[2])){
MessageSending.sendMessageWithPrefix(user + " " + args[2] + " is regular", user, event);
}else{
MessageSending.sendMessageWithPrefix(user + " " + args[2] + " is not regular", user, event);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
} | 9 |
@Override
public void setLogWriter(PrintWriter arg0) throws SQLException {
} | 0 |
public void run(){
try{
File file = new File("Sound.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(file);
Clip soundClip = AudioSystem.getClip();
soundClip.open(ais);
soundClip.start();
long millisecs = soundClip.getMicrosecondLength()/1000;
Thread.sleep(millisecs);
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
} | 1 |
public static DiagramComponent createOpenFromBoundaryCells(
final TextGrid grid,
final CellSet boundaryCells,
final int cellWidth,
final int cellHeight,
boolean allRound) {
if(boundaryCells.getType(grid) != CellSet.TYPE_OPEN) throw new IllegalArgumentException("This shape is closed and cannot be handled by this method");
if(boundaryCells.size() == 0) return null;
CompositeDiagramShape compositeShape = new CompositeDiagramShape();
TextGrid workGrid = new TextGrid(grid.getWidth(), grid.getHeight());
grid.copyCellsTo(boundaryCells, workGrid);
if(DEBUG) {
System.out.println("Making composite shape from grid:");
workGrid.printDebug();
}
CellSet visitedCells = new CellSet();
List<DiagramShape> shapes = new ArrayList<DiagramShape>(100);
for(TextGrid.Cell cell : boundaryCells) {
if(workGrid.isLinesEnd(cell)) {
CellSet nextCells = workGrid.followCell(cell);
shapes.addAll(growEdgesFromCell(workGrid, cellWidth, cellHeight, allRound, nextCells.getFirst(), cell, visitedCells));
break;
}
}
//dashed shapes should "infect" the rest of the shapes
boolean dashedShapeExists = false;
for(DiagramShape shape : shapes)
if(shape.isStrokeDashed())
dashedShapeExists = true;
for(DiagramShape shape : shapes) {
if(dashedShapeExists) shape.setStrokeDashed(true);
compositeShape.addToShapes(shape);
}
return compositeShape;
} | 9 |
public String getCode() {
return code;
} | 0 |
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=-25;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 Element getElement(int key) {
return this.elements.get(key);
} | 0 |
private static char getNrMinesBBCase(char[][] m, int r, int c) {
int n = 0;
if (m[r - 1][c] == MINE) {
n++;
}
if (m[r - 1][c + 1] == MINE) {
n++;
}
if (m[r][c + 1] == MINE) {
n++;
}
if (m[r + 1][c + 1] == MINE) {
n++;
}
if (m[r + 1][c] == MINE) {
n++;
}
if (m[r + 1][c - 1] == MINE) {
n++;
}
if (m[r][c - 1] == MINE) {
n++;
}
if (m[r - 1][c - 1] == MINE) {
n++;
}
return (char) ('0' + n);
} | 8 |
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in,
"ISO-8859-1"));
String line = "";
StringBuilder out = new StringBuilder();
OutputStreamWriter cout = new OutputStreamWriter(System.out,
"ISO-8859-1");
d: do {
line = br.readLine();
if (line == null || line.length() == 0)
break d;
int times = Integer.parseInt(line);
String nameCup = "";
for (int i = 0; i < times; i++) {
nameCup = br.readLine();
int nteams = Integer.parseInt(br.readLine());
HashMap<String, Integer> mapTeams = new HashMap<String, Integer>(
nteams);
Team[] teams = new Team[nteams];
int[][] valuesTeams = new int[nteams][8];
for (int j = 0; j < nteams; j++) {
mapTeams.put(line = br.readLine(), j);
teams[j] = new Team(line);
}
int nmatches = Integer.parseInt(br.readLine());
for (int j = 0; j < nmatches; j++) {
line = br.readLine();
String[] nameTeams = nameTeams(line);
int[] goals = goals(line);
int t1 = mapTeams.get(nameTeams[0]), t2 = mapTeams
.get(nameTeams[1]);
teams[t1].match(goals[0], goals[1]);
teams[t2].match(goals[1], goals[0]);
}
Arrays.sort(teams);
if (i != 0)
out.append("\n");
out.append(nameCup).append("\n");
for (int j = 0; j < valuesTeams.length; j++)
out.append((j + 1) + ") " + teams[j] + "\n");
}
} while (line != null && line.length() != 0);
cout.write(out.toString());
cout.flush();
} | 9 |
public CheckReport(File file) throws Exception {
this.file = file;
fileName = file.getName();
version = checkVersion(file);
} | 0 |
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(mainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(mainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(mainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(mainWindow.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 mainWindow().setVisible(true);
}
});
} | 6 |
public void sort(SortData[] paramArrayOfSortData, boolean paramBoolean)
{
int i = 1;
while (i != 0)
{
i = 0;
for (int j = 0; j < paramArrayOfSortData.length - 1; j++)
{
SortData localSortData1;
SortData localSortData2;
if (paramBoolean)
{
localSortData1 = paramArrayOfSortData[(j + 1)];
localSortData2 = paramArrayOfSortData[j];
}
else
{
localSortData1 = paramArrayOfSortData[j];
localSortData2 = paramArrayOfSortData[(j + 1)];
}
if (!localSortData1.isGreater(localSortData2))
continue;
localSortData1.swap(localSortData1, localSortData2);
i++;
}
}
} | 4 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
String action = request.getParameter("action");
String zone = request.getParameter("zone");
if(action==null){
out.print("Parameters Error");
}else if(action.equals("add") && zone!=""){
devops.dns.Zone newZone = new devops.dns.Zone();
if(newZone.addZone(zone)>0){
JSONObject json = new JSONObject();
json.put("status", "ok");
json.put("message", "add zone");
json.put("data", zone);
out.println(json.toString());
}else{
JSONObject json = new JSONObject();
json.put("status", "error");
json.put("message", "add zone");
json.put("data", zone);
out.println(json.toString());
}
}else if(action.equals("del") && zone!=""){
devops.dns.Zone newZone = new devops.dns.Zone();
if(newZone.delZone(zone)>0){
JSONObject json = new JSONObject();
json.put("status", "ok");
json.put("message", "delete zone");
json.put("data", "");
out.println(json.toString());
}else{
JSONObject json = new JSONObject();
json.put("status", "error");
json.put("message", "delete zone");
json.put("data", "");
out.println(json.toString());
}
}else if(action.equals("getlist")){
devops.dns.Zone newZone = new devops.dns.Zone();
List<HashMap> zonelist = newZone.getList();
Iterator it = zonelist.iterator();
JSONObject json = new JSONObject();
JSONArray jsonarray = new JSONArray();
while(it.hasNext()){
String zoneName = ((HashMap)it.next()).get("zone").toString();
jsonarray.put(zoneName);
}
json.put("status", "ok");
json.put("message", "get list ok");
json.put("data", jsonarray);
out.println(json.toString());
}
} | 9 |
void scoreRandTestThreshold(int maxLen, int minLen, Random rand, int threshold, int overlapChanges) {
// First sequence
int len1 = rand.nextInt(maxLen) + minLen;
String seq1 = randSeq(len1, rand);
if( verbose ) System.out.println("\nseq1:\t" + seq1);
// Second sequence
int over = rand.nextInt(len1 - minLen + 1);
int start = over;
String overlap = "", nonOverlap = "", seq2 = "";
int expectedScore = 0;
int len2 = rand.nextInt(maxLen - over);
if( rand.nextBoolean() ) {
// Second sequence (overlapping at the end of the first one)
overlap = seq1.substring(over);
overlapChanges = Math.min(overlapChanges, overlap.length());
overlap = change(overlap, overlapChanges, rand);
if( verbose ) System.out.println("over:\t" + overlap);
nonOverlap = randSeq(len2, rand);
seq2 = overlap + nonOverlap;
} else {
// Second sequence (overlapping at the beginning of the first one)
overlap = seq1.substring(0, over);
overlapChanges = Math.min(overlapChanges, overlap.length());
overlap = change(overlap, overlapChanges, rand);
if( verbose ) System.out.println("over:\t" + overlap);
nonOverlap = randSeq(len2, rand);
seq2 = nonOverlap + overlap;
start = -nonOverlap.length();
}
if( verbose ) System.out.println("seq2:\t" + seq2);
// Expected result
expectedScore = overlapChanges <= threshold ? overlap.length() - overlapChanges : 0;
if( verbose ) System.out.println("start:\t" + start + "\tthreshold: " + threshold + "\toverlapChanges: " + overlapChanges + "\tscore: " + expectedScore);
// Caclualte
score(seq1, seq2, start, threshold, expectedScore);
} | 7 |
@Override
public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) {
String broadcastMessage = "";
String broadcastStaffTag = "";
String broadcastRegularTag = "";
if (!isPlayer) {
sender.sendMessage(ChatColor.RED + "Run this command from ingame.");
return;
}
if (!player.hasPermission("mymessages.staffbroadcast")) {
player.sendMessage(ChatColor.RED + "Access denied.");
return;
}
if (args.length < 1) {
player.sendMessage(ChatColor.RED + "Usage: /" + commandName + " <message>");
return;
}
broadcastMessage += this.plugin.combineSplit(0, args, " ");
broadcastMessage = this.plugin.format(broadcastMessage);
broadcastStaffTag += this.plugin.getConfig().getString("broadcast.staff_tag");
broadcastStaffTag = this.plugin.format(broadcastStaffTag, player.getDisplayName());
broadcastRegularTag += this.plugin.getConfig().getString("broadcast.regular_tag");
broadcastRegularTag = this.plugin.format(broadcastRegularTag, player.getDisplayName());
if (broadcastMessage != null && broadcastStaffTag != null && broadcastRegularTag != null) {
for (Player plr : this.plugin.getServer().getOnlinePlayers()) {
if (plr.hasPermission("mymessages.broadcast.staff")) {
plr.sendMessage(broadcastStaffTag + ChatColor.RESET + " " + broadcastMessage);
} else {
plr.sendMessage(broadcastRegularTag + ChatColor.RESET + " " + broadcastMessage);
}
}
} else {
player.sendMessage(ChatColor.RED + "Error: Could not broadcast message.");
}
} | 8 |
public static Vector localSearch(Vector v) {
int tests = 0;
// Incrementally optimize this vector
v = v.clone(); // don't modify the original
double bestLength = v.length();
Vector bestVector = v.clone();
int[] increments = new int[] { -1, 2, -1 };
boolean improved = true;
while (improved) {
improved = false;
// n^2 search over coefficient length
cLoop: for(int j = 0; j < v.coef.length; j++) {
for(int inc1 : increments) {
v.coef[j] = v.coef[j] + inc1;
for(int i = 0; i < v.coef.length; i++) {
for(int inc2 : increments) {
v.coef[i] = v.coef[i] + inc2;
tests++;
if(v.length() > 0 && v.length() < bestLength) {
bestLength = v.length();
bestVector = v.clone();
improved = true;
System.out.println("[" + tests + "] Improved: "
+ bestLength);
break cLoop;
}
}
}
}
}
}
System.out.println("Tests: " + tests);
return bestVector;
} | 7 |
private static void setNull(PreparedStatement ps, int paramIndex) throws SQLException {
boolean useSetObject = false;
int sqlType = Types.NULL;
try {
DatabaseMetaData metaData = ps.getConnection().getMetaData();
String databaseProductName = metaData.getDatabaseProductName();
String jdbcDriverName = metaData.getDriverName();
if (databaseProductName.startsWith("Informix") || jdbcDriverName.startsWith("Microsoft SQL Server")) {
useSetObject = true;
} else if (databaseProductName.startsWith("DB2") || jdbcDriverName.startsWith("jConnect")
|| jdbcDriverName.startsWith("SQLServer") || jdbcDriverName.startsWith("Apache Derby")) {
sqlType = Types.VARCHAR;
}
} catch (Throwable ex) {
LOGGER.debug("获取JDBC驱动信息失败", ex);
}
if (useSetObject) {
ps.setObject(paramIndex, null);
} else {
ps.setNull(paramIndex, sqlType);
}
} | 8 |
public void setCenter(LatLng center) {
if (center == null)
throw new IllegalArgumentException("Window's center may not be null.");
this.center = center;
} | 1 |
private List<Player> getPlayersInChat(List<Player> list, String chat){
List<Player> newPlayerList = new ArrayList<Player>();
for (Player playeren : list){
if (plugin.playerChat.containsKey(playeren)){
if (plugin.playerChat.get(playeren).equals(chat)){
newPlayerList.add(playeren);
}
}else{
newPlayerList.add(playeren);
}
}
if (plugin.playerChat.containsValue(chat)){
for (Entry<Player, String> entry : plugin.playerChat.entrySet()) {
if (entry.getValue().equals(chat)) {
if (!list.contains(entry.getKey())){
newPlayerList.add(entry.getKey());
}
}
}
}
return newPlayerList;
} | 7 |
public Integer[] getLineSurvivalMove(Integer[] move, String type, int i,
String line) {
int j;
if(checkLineNeedSurvival(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 |
public void save() {
if (changed) {
/* Copy old File */
File source = new File(file.getPath());
String filePath = file.getPath();
File temp = new File(filePath.substring(0, filePath.length() - 4) + "_old.yml");
if (temp.exists())
temp.delete();
source.renameTo(temp);
/* Save */
FileConfiguration configFile = new YamlConfiguration();
for (String key : entries.keySet()) {
configFile.set(key, entries.get(key));
}
try {
configFile.save(file);
} catch (IOException e) {
e.printStackTrace();
}
}
} | 4 |
@Override
public void run() {
Graphics g = bstrategy.getDrawGraphics();
if(bstrategy.contentsLost() == false){
Insets insets = frame1.getInsets();
g.translate(insets.left, insets.top);
if(spkey == true){
speed = speed - 0.25;
}else{
speed = speed + 0.25;
}
if(speed < -6) speed = -6;
if(speed > 6) speed = 6;
cy = cy + (int)speed;
if(cy < 0) cy = 0;
g.clearRect(0, 0, 600, 400);
g.drawImage(pimage, 270, cy, frame1);
/*g.setColor(Color.BLUE);
g.fillOval(250, cy, 100, 100);
g.fillRect(0, 0, 100, 100);*/
/*g.setFont(new Font("Serif", Font.PLAIN, 40));
g.drawString("こんちわ Hello!", 100, 100);
drawStringCenter("こんちわ Hello!", 100, g);
g.setFont(new Font("SansSerif", Font.PLAIN, 60));
g.drawString("こんちわ Hello!", 100, 140);
drawStringCenter("こんちわ Hello!", 160, g);
g.setFont(new Font("Monospaced", Font.PLAIN, 40));
g.drawString("こんちわ Hello!", 100, 180);
g.setFont(new Font("Dialog", Font.PLAIN, 40));
g.drawString("こんちわ Hello!", 100, 220);
g.setFont(new Font("DialogInput", Font.PLAIN, 40));
g.drawString("こんちわ Hello!", 100, 260);
g.setFont(new Font("DHP行書体", Font.PLAIN, 40));
g.drawString("こんちわ Hello!", 100, 300);*/
bstrategy.show();
g.dispose();
System.out.println(cy + "." + speed);
}
} | 5 |
public void actualiza() {
//Determina el tiempo que ha transcurrido desde que el Applet inicio su ejecución
long tiempoTranscurrido = System.currentTimeMillis() - tiempoActual;
//Guarda el tiempo actual
tiempoActual += tiempoTranscurrido;
//Actualiza la animación con base en el tiempo transcurrido
if (direccion != 0) {
barril.actualiza(tiempoTranscurrido);
}
//Actualiza la animación con base en el tiempo transcurrido para cada malo
if (click) {
banana.actualiza(tiempoTranscurrido);
}
//Actualiza la posición de cada malo con base en su velocidad
//banana.setPosY(banana.getPosY() + banana.getVel());
if (banana.getPosX() != 50 || banana.getPosY() != getHeight() - 100) {
semueve = false;
}
if (click) { // si click es true hara movimiento parabolico
banana.setPosX(banana.getPosX() + banana.getVelX());
banana.setPosY(banana.getPosY() - banana.getVelY());
banana.setVelY(banana.getVelY() - gravity);
}
if (direccion == 1) { // velocidad de las barrils entre menos vidas menor el movimiento
barril.setPosX(barril.getPosX() - vidas - 2);
}
else if (direccion == 2) {
barril.setPosX(barril.getPosX() + vidas + 2);
}
} | 7 |
@Override
public Label predict(Instance instance) {
// TODO Auto-generated method stub
double sumOdd = 0;
double sumEven = 0;
for (Integer index: instance.getFeatureVector().getVector().keySet()) {
if (index % 2 == 0) {
sumOdd += instance.getFeatureVector().get(index);
}
else if (index % 2 == 1) {
sumEven += instance.getFeatureVector().get(index);
}
}
if (sumOdd >= sumEven) {
return new ClassificationLabel(1);
}
else {
return new ClassificationLabel(0);
}
} | 4 |
private void setUp() {
File tmpUser = null;
File tmpMusic = null;
try{
tmpUser = new File("res/users.data");
tmpMusic = new File("res/musics.data");
this.setuserFileOut(new FileOutputStream(tmpUser));
this.setUserFileIn(new FileInputStream(tmpUser));
this.setMusicFileOut(new FileOutputStream(tmpMusic));
this.setMusicFileIn(new FileInputStream(tmpMusic));
} catch (FileNotFoundException e) {
if(!tmpUser.exists())
try {
tmpUser.createNewFile();
this.setuserFileOut(new FileOutputStream(tmpUser));
this.setUserFileIn(new FileInputStream(tmpUser));
} catch (IOException e1) {
e1.printStackTrace();
}
else if(!tmpMusic.exists())
try {
tmpMusic.createNewFile();
this.setMusicFileOut(new FileOutputStream(tmpMusic));
this.setMusicFileIn(new FileInputStream(tmpMusic));
} catch (IOException e2) {
e.printStackTrace();
}
} catch (Exception eof) {
this.setMusicBuffer(new HashMap<String, PersistentMusic>());
this.setUserBuffer(new HashMap<Email, PersistentUser>());
}
try {
setUserDbOut(new ObjectOutputStream(userFileOut));
setUserDbIn(new ObjectInputStream(userFileIn));
setMusicDbOut(new ObjectOutputStream(this.getMusicFileOut()));
setMusicDbIn(new ObjectInputStream(this.getMusicFileIn()));
} catch (IOException e) {
e.printStackTrace();
}
} | 7 |
public int getAno() {
return ano;
} | 0 |
@SuppressWarnings("static-access")
private void ROUND10() {
enemises.clear();
System.out.println("Round10!!!!!!");
for (int i = 0; i < level.getWidth(); i++) {
for (int j = 0; j < level.getHeight(); j++) {
if ((level.getPixel(i, j) & 0x0000FF) == 2) {
Transform monsterTransform = new Transform();
monsterTransform.setTranslation((i + 0.5f) * Game.getLevel().SPOT_WIDTH, 0.4375f, (j + 0.5f) * Game.getLevel().SPOT_LENGTH);
enemises.add(new Enemies(monsterTransform));
}
}
}
} | 3 |
public void render() {
// Get the loaded materials and initialise necessary variables
Material[] materials = coinMesh.materials;
Material material;
Triangle drawTriangle;
int currentMaterial = -1;
int triangle = 0;
// For each triangle in the object
for (triangle = 0; triangle < coinMesh.triangles.length;) {
// Get the triangle that needs to be drawn
drawTriangle = coinMesh.triangles[triangle];
// Activate a new material and texture
currentMaterial = drawTriangle.materialID;
material = (materials != null && materials.length > 0 && currentMaterial >= 0) ? materials[currentMaterial]
: defaultMtl;
material.apply();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, material.getTextureHandle());
// Draw triangles until material changes
GL11.glBegin(GL11.GL_TRIANGLES);
while (triangle < coinMesh.triangles.length && drawTriangle != null
&& currentMaterial == drawTriangle.materialID) {
GL11.glTexCoord2f(drawTriangle.texture1.x,
drawTriangle.texture1.y);
GL11.glNormal3f(drawTriangle.normal1.x, drawTriangle.normal1.y,
drawTriangle.normal1.z);
GL11.glVertex3f((float) drawTriangle.point1.pos.x,
(float) drawTriangle.point1.pos.y,
(float) drawTriangle.point1.pos.z);
GL11.glTexCoord2f(drawTriangle.texture2.x,
drawTriangle.texture2.y);
GL11.glNormal3f(drawTriangle.normal2.x, drawTriangle.normal2.y,
drawTriangle.normal2.z);
GL11.glVertex3f((float) drawTriangle.point2.pos.x,
(float) drawTriangle.point2.pos.y,
(float) drawTriangle.point2.pos.z);
GL11.glTexCoord2f(drawTriangle.texture3.x,
drawTriangle.texture3.y);
GL11.glNormal3f(drawTriangle.normal3.x, drawTriangle.normal3.y,
drawTriangle.normal3.z);
GL11.glVertex3f((float) drawTriangle.point3.pos.x,
(float) drawTriangle.point3.pos.y,
(float) drawTriangle.point3.pos.z);
triangle++;
if (triangle < coinMesh.triangles.length)
drawTriangle = coinMesh.triangles[triangle];
}
GL11.glEnd();
}
} | 8 |
private void sendData(APDU apdu, byte[] buffer, short len) {
apdu.setOutgoing();
if (len > (short)254) {
apdu.setOutgoingLength((short)254);
apdu.sendBytesLong(buffer, remainingDataOffset, (short)254);
remainingDataOffset += 254;
remainingDataLength = (short)(len - 254);
ISOException.throwIt((short)(SW_MORE_DATA + ((remainingDataLength > 254) ? 254 : remainingDataLength)));
} else {
apdu.setOutgoingLength(len);
apdu.sendBytesLong(buffer, remainingDataOffset, len);
}
} | 2 |
public <V> Adapter.Setter<V> makeSetter(String methodName, Class<V> _class) {
try {
T version = (T) start.get().newVersion;
final Method method = version.getClass().getMethod(methodName, _class);
return new Adapter.Setter<V>() {
public void call(V value) {
try {
Transaction me = Thread.getTransaction();
Locator oldLocator = start.get();
T version = (T) oldLocator.fastPath(me);
if (version != null) {
method.invoke(version, value);
return;
}
ContentionManager manager = Thread.getContentionManager();
Locator newLocator = new Locator(me, (Copyable)factory.create());
version = (T) newLocator.newVersion;
LocalReadSet readSet = LocalReadSet.getLocal();
readSet.release(Adapter.this); // don't conflict with self
while (true) {
oldLocator.writePath(me, manager, newLocator);
if (!me.isActive()) {
throw new AbortedException();
}
method.invoke(version, value);
if (Adapter.this.start.compareAndSet(oldLocator, newLocator)) {
return;
}
oldLocator = Adapter.this.start.get();
}
} catch (IllegalAccessException e) {
throw new PanicException(e);
} catch (InvocationTargetException e) {
throw new PanicException(e);
}
}};
} catch (NoSuchMethodException e) {
throw new PanicException(e);
}
} | 7 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WithListAnnotated withList = (WithListAnnotated) o;
if (list != null ? !list.equals(withList.list) : withList.list != null) return false;
return true;
} | 5 |
public void update(){
if (remainingTime == 0) {
this.frame.getPanPara().getButPause().setVisible(false);
this.frame.getPanPara().getButGeneration().setVisible(true);
this.frame.getPanPara().getTfStep().setEnabled(true);
this.frame.getPanPara().getTfStepNumber().setEnabled(true);
this.frame.getPanPara().getSlStepSpeed().setEnabled(true);
this.frame.getPanPara().getSliderNumber().setEnabled(true);
this.frame.getPanPara().getButStepValid().setVisible(true);
this.frame.getPanPara().getButStepValid().setEnabled(true);
this.frame.getPanPara().getCbFireMode().setVisible(false);
this.frame.getPanPara().getCbInvasionMode().setVisible(false);
this.frame.getPanMenu().getInfectItem().setEnabled(false);
this.frame.getPanMenu().getFireItem().setEnabled(false);
this.frame.getPanPara().getRadioPanel().setVisible(false);
if (!(BOLObj.getTab().getX() > 49 && BOLObj.getTab().getY() > 49)) {
this.frame.getPanPara().getButGeneration().setEnabled(false);
}
if (!(BOLObj.getTab().getX() > 49 && BOLObj.getTab().getY() > 49)) {
this.frame.getPanPara().getButNext().setEnabled(false);
}
this.frame.getPanProgBar().setProgressNumber(0);
this.frame.getPanMenu().getGeneItem().setEnabled(false);
this.frame.getPanMenu().getPlayItem().setEnabled(false);
this.frame.getPanMenu().getPauseItem().setEnabled(false);
remainingTime = 0;
this.actualStepNumber = 0;
timer.stop();
} else {
this.frame.setTabToShow(this.BOLObj.getUpdatedTab().getTab(), this.BOLObj.getUpdatedTab().getX(), this.BOLObj.getUpdatedTab().getY());
BOLObj.setTab(frame.getTabToShow(), frame.getGridWidth(), frame.getGridLength());
BOLObj.CheckTab();
this.frame.getPanGraphic().repaint();
this.updateBOLObject(BOLObj);
this.frame.getPanProgBar().setProgressNumber((int)(((double)actualStepNumber * 100.0)/(stepNumber/+ 1)));
HashMap countResult = BOLObj.getCaseCounter().CountStateGridCase(BOLObj, frame);
int nbMaxTabCase = BOLObj.getTab().getX()* BOLObj.getTab().getY();
DecimalFormat df = new DecimalFormat("#.###");
this.frame.getPanText().setNbStep("Tour : " + (actualStepNumber) + "/" + stepNumber);
String a = df.format((double)Integer.valueOf(countResult.get(Etat.jeunePousse).toString())/(double)nbMaxTabCase);
this.frame.getPanText().setNbJeunePousse("JP : " + a);
String b = df.format((double)Integer.valueOf(countResult.get(Etat.arbuste).toString())/(double)nbMaxTabCase);
this.frame.getPanText().setNbArbuste("Arbu. : " + b);
String c = df.format((double)Integer.valueOf(countResult.get(Etat.arbre).toString())/(double)nbMaxTabCase);
this.frame.getPanText().setNbArbre("Arbre : " + c);
if (this.frame.getPanText().getNbFeu().isEnabled()) {
this.frame.getPanText().setNbFeu("Feu : " + df.format((double)Integer.valueOf(countResult.get(Etat.feu).toString())/(double)nbMaxTabCase));
}
if (this.frame.getPanText().getNbInfecte().isEnabled()) {
this.frame.getPanText().setNbInfecte("Inf. : " + df.format((double)Integer.valueOf(countResult.get(Etat.infecte).toString())/(double)nbMaxTabCase));
}
String[] csvSave = {a, b, c, df.format((double)Integer.valueOf(countResult.get(Etat.vide).toString())/(double)nbMaxTabCase)};
this.BOLObj.getCountStateGridCase().add(csvSave);
this.frame.getPanText().repaint();
int now = this.actualStepNumber++;
int elapsed = now - lastUpdate;
remainingTime -= elapsed;
lastUpdate = now;
}
} | 7 |
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
String data = "{\"data\": [\"id\", \"nombre\", \"primer apellido\", \"segundo apellido\", \"email\"]}";
return data;
} catch (Exception e) {
throw new ServletException("ClienteGetpagesJson: View Error: " + e.getMessage());
}
} | 1 |
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
logger.info("detail servlet doGet:" + request.getRemoteAddr());
userLogInTest(request, response);
String option = "bogus";
String key = "0";
Enumeration<String> paramz = request.getParameterNames();
while (paramz.hasMoreElements()) {
String name = (String) paramz.nextElement();
String[] valuez = null;
try {
valuez = request.getParameterValues(name);
} catch(Exception exception) {
valuez = new String[1];
valuez[0] = "exception";
}
if (name.equals(Constant.STUNT)) {
option = valuez[0];
} else if (name.equals(Constant.KEY)) {
key = valuez[0];
} else {
logger.warning("unknown param:" + name + ":");
}
}
VideoTitleService vts = new VideoTitleServiceImpl();
if (option.equals(Constant.INSERT)) {
//empty
} else if (option.equals(Constant.DELETE)) {
vts.deleteVideoTitle(new Long(key));
} else if (option.equals(Constant.EDIT)) {
VideoTitle editTarget = vts.selectVideoTitle(new Long(key));
request.setAttribute(Constant.EDIT_TARGET, editTarget);
}
try {
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/video_detail.jsp");
requestDispatcher.forward(request, response);
} catch(Exception exception) {
exception.printStackTrace();
}
} | 8 |
public Object nextValue() throws JSONException {
char c = this.nextClean();
String string;
switch (c) {
case '"':
case '\'':
return this.nextString(c);
case '{':
this.back();
return new JSONObject(this);
case '[':
this.back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuilder sb = new StringBuilder();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = this.next();
}
this.back();
string = sb.toString().trim();
if ("".equals(string)) {
throw this.syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
} | 7 |
public void addItemsToOrderCombobox() {
orderComboboxItems.clear();
String item = "";
if (driver.getPersonDB().getCustomerList().size() > 0) {
for (Order order : driver.getOrderDB().getCustomerOrderList()) {
if (order.getPerson() == person) {
item = "ID:\t" + order.getId() + " \t " + "Date: " + order.getDateString() + "";
orderComboboxItems.add(item);
}
}
orderComboBox.setSelectedIndex(orderComboBox.getItemCount() - 1);
}
else {
orderComboBox.setSelectedItem(null);
}
revalidate();
repaint();
} | 3 |
public boolean isBoxInFrustum(float F0, float F1, float F2, float F3, float F4, float F5) {
final float frustum00F0 = frustum[0][0] * F0;
final float frustum01F1 = frustum[0][1] * F1;
final float frustum02F2 = frustum[0][2] * F2;
return !(frustum00F0 + frustum01F1 + frustum02F2 + frustum[0][3] <= 0
&& frustum[0][0] * F3 + frustum01F1 + frustum02F2 + frustum[0][3] <= 0
&& frustum00F0 + frustum[0][1] * F4 + frustum02F2 + frustum[0][3] <= 0
&& frustum[0][0] * F3 + frustum[0][1] * F4 + frustum02F2 + frustum[0][3] <= 0
&& frustum00F0 + frustum01F1 + frustum[0][2] * F5 + frustum[0][3] <= 0
&& frustum[0][0] * F3 + frustum01F1 + frustum[0][2] * F5 + frustum[0][3] <= 0
&& frustum00F0 + frustum[0][1] * F4 + frustum[0][2] * F5 + frustum[0][3] <= 0
&& frustum[0][0] * F3 + frustum[0][1] * F4 + frustum[0][2] * F5 + frustum[0][3] <= 0);
} | 7 |
public void paint(java.awt.Graphics g) {
super.paint(g);
int fillX = 0;
int fillY = 0;
int w = getWidth();
int h = getHeight();
FontInfo fi = getFontInfo();
int round = ((fi.decoration & FontInfo.ROUND) != 0) ? 1 : 0;
if((fi.decoration & FontInfo.SHADOW) != 0){
g.setColor(fi.shadow);
g.drawLine(2+round, h-1, w-1-round, h-1);
g.drawLine(w-1, 2+round, w-1, h-1-round);
g.drawLine(w-1-round, h-1-round, w-1-round, h-1-round);
w--;
h--;
}
int fillW = w;
int fillH = h;
if((fi.decoration & FontInfo.BORDER) != 0){
g.setColor(fi.border);
if((fi.decoration & FontInfo.LEFT) != 0){
g.drawLine(0, round, 0, h-round-1);
fillX++;
fillW--;
}
if((fi.decoration & FontInfo.RIGHT) != 0) {
g.drawLine(w-1, round, w-1, h-round-1);
fillW--;
}
if((fi.decoration & FontInfo.TOP) != 0){
g.drawLine(round, 0, w-round-1, 0);
fillY++;
fillH--;
}
if((fi.decoration & FontInfo.BOTTOM) != 0){
g.drawLine(round, h-1, w-round-1, h-1);
fillH--;
}
}
if(fi.background != null && (fi.decoration & FontInfo.COMPACT) == 0){
g.setColor(fi.background);
g.fillRect(fillX, fillY, fillW, fillH);
}
g.setColor(fi.foreground);
} | 9 |
public static boolean binarySearch(ArrayList<Integer> s, int x)
{
//For later
ArrayList<Integer> sub = new ArrayList<Integer>();
//corner cases
if (s.size() == 0)
{
return false;
}
else
{
//If its equal to the middle then return true
int middle = s.size()/2;
if(s.get(middle) == x)
{
return true;
}
else
{
if(x<s.get(middle))
{
//up to not including middle
for (int i =0; i<middle; i++)
{
sub.add(s.get(i));
}
}
else
{
//everything after middle
for (int i= middle+1; i<s.size(); i++)
{
sub.add(s.get(i));
}
}
return binarySearch(sub, x);
}
}
} | 5 |
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int testCases = in.nextInt();
while (testCases > 0) {
System.out.println(totalChoc(in.nextInt(), in.nextInt(), in.nextInt()));
testCases--;
}
} | 1 |
private String stringHashMap()
{
String str = "";
for(Equivalence equ : equivs.values())
{
str = str + equ + ln;
}
return str.trim();
} | 1 |
@Override
public void putAll(Map<? extends String, ? extends String> m)
{
Set<? extends String> nuKeys = m.keySet();
for (String s : nuKeys)
{
String value = m.get(s);
put(s, value);
}
} | 4 |
String value(ResourceBundle bundle, K key) {
// Build name
String name = key.name();
String fallback = name;
if (key instanceof Message) {
String[] args = ((Message) key).args();
if ((args != null) && (args.length > 0)) { // anonym index
boolean first = true;
for (String arg : args) {
fallback += (first ? "({" : "},{") + arg;
name += (first ? '(' : ',') + arg;
first = false;
}
name += ')';
fallback += "})";
}
}
if (bundle == null) {
return fallback;
}
try {
return bundle.getString(name);
} catch (MissingResourceException noFullName) {
try {
return bundle.getString(key.name());
} catch (MissingResourceException noName) {
return fallback;
}
}
} | 9 |
public ClassNode[] getInheritors(MethodID id) {
ClassNode c = getClass(id.owner);
List<ClassNode> inheritors = new LinkedList<ClassNode>();
classLoop: for (ClassNode c2 : getClasses().values()) {
ClassNode[] inherited = (c.access & ACC_INTERFACE) == 0 ? getHierarchy(c2)
: getInterfaces(c2);
int index = ArrayUtil.searchArray(inherited, c);
if (index >= 0) {
for (Object mo : c2.methods) {
MethodNode m2 = (MethodNode) mo;
if (m2.name.equals(id.name) && m2.desc.equals(id.desc)
&& !inheritors.contains(c2)) {
inheritors.add(c2);
continue classLoop;
}
}
}
}
return inheritors.toArray(new ClassNode[0]);
} | 7 |
public void setPassword(String password) {
this.password = password;
} | 0 |
@Override
public Boolean existsOne(String strTabla, int id) throws Exception {
int result = 0;
Statement oStatement;
try {
oStatement = (Statement) oConexionMySQL.createStatement();
String strSQL = "SELECT count(*) FROM " + strTabla + " WHERE 1=1";
ResultSet rs = oStatement.executeQuery(strSQL);
while (rs.next()) {
result = rs.getInt("COUNT(*)");
}
return (result > 0);
} catch (SQLException e) {
throw new Exception("mysql.existsOne: Error en la consulta: " + e.getMessage());
}
} | 2 |
public void stopListeningForCheaters() {
try {
cheaterSub.remove();
} catch (Exception e) {
// do nothing
}
cheaterSub = null;
} | 1 |
public static void main(String[] args) throws Exception {
DatabaseManager.getSingleton().addDatabase(DatabaseConnection.create("127.0.0.1", "lolserver", "lollol", "server"), "info");
DatabaseConnection c = DatabaseManager.getSingleton().getConnection("info");
BufferedReader br = new BufferedReader(new FileReader("npcs.txt"));
List<int[]> list = new ArrayList<int[]>();
System.out.println("Building list from file...");
long started = System.currentTimeMillis();
while(true) {
String line = br.readLine();
if(line == null) {
break;
}
String[] split = line.split(" ");
list.add(new int[] { Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), 0, 0 });
}
long elapsed = System.currentTimeMillis() - started;
System.out.println("Read from file and built list in "+elapsed+"ms");
List<PreparedStatement> psl = new ArrayList<PreparedStatement>();
started = System.currentTimeMillis();
System.out.println("Building statement list...");
for(int[] i : list) {
psl.add(c.getStatement("INSERT INTO npcspawn VALUES('"+i[0]+"', '"+i[1]+"', '"+i[2]+"', '"+i[3]+"', '"+i[4]+"');"));
}
elapsed = System.currentTimeMillis() - started;
System.out.println("Built list in "+elapsed+"ms");
System.out.println("Executing "+psl.size()+" insert statements");
started = System.currentTimeMillis();
for(PreparedStatement ps : psl) {
ps.execute();
}
elapsed = System.currentTimeMillis() - started;
System.out.println("Inserted in "+elapsed+"ms");
System.out.println("Done!");
} | 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.