Wednesday, May 2, 2012

Editing .txt file Java

I need to to write a Java program that will write entered information in the console to a .txt file. If the .txt file already exists it will have to open it and write the additional information on another line. If the .txt file doesn't exist for a new "Lifter" it will create the .txt and write it in. Basically I don't know how to create a new .txt for each name entered and how to edit it if the person's .txt already exists. How would I go about doing that?



import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;

public class MeetPrinter {

public static void getInfo() {

Scanner scanner = new Scanner(System.in);
int question;
String firstName;
String lastName;
int squat;
int bench;
int lift;
String meetName;
do {

System.out.println("Enter first name: ");
firstName = scanner.next();

System.out.println("Enter Last Name: ");
lastName = scanner.next();

System.out.println("Enter new Meet Name: ");
meetName = scanner.next();

System.out.println("Enter max squat weight in kg: ");
squat = scanner.nextInt();

System.out.println("Enter max bench press in kg: ");
bench = scanner.nextInt();

System.out.println("Enter max deadlift in kg: ");
lift = scanner.nextInt();

System.out
.println("Enter '1' to enter more lifters or '2' if you are done entering.");
question = scanner.nextInt();
} while (question == 1);

try{
PrintWriter out = new PrintWriter("output.txt");
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100000);
out.println(lastName + ", " + firstName + " Record #: " + randomInt);
out.println("");
String meet = "Meet Name";
String sq = "SQ Max";
String bp = "BP Max";
String sub = "SUB Total";
String dl = "DL Max";
String tot = "Total";
out.printf("%20s %15s %18s %19s %18s %18s",meet ,sq,bp,sub,dl,tot);
out.println("");
out.printf("%20s", meetName);
out.printf("%10d (%6.2f)", squat, squat * 2.2);
out.printf("%10d (%6.2f)", bench, bench * 2.2);
float subPounds = (float) ((float)(squat + bench) * 2.2);
out.printf("%10d (%6.2f)", squat + bench, subPounds);
out.printf("%10d (%6.2f)", lift, lift * 2.2);
float tPounds = (float) ((float)(squat + bench + lift) * 2.2);
out.printf("%10d (%6.2f)", squat + bench + lift, tPounds);
out.close();
}catch(IOException e){
e.printStackTrace();
}
}

}




Load lots of large UIImages in UITableView

I'm using a UITableView to show lots of photos. I created a custom UITableViewCell , where are 4 UIButtons. Each button is used to represent an image. At one time it will be visible just 16 buttons (4 cells). There is no problem if i use lightweight images, but when i try to load photos(MB's) performance "suffers" very much. Which is the best way to load large photos/images ?





Why not to use Return statement in vb.net

I've been given some code to go through and find problems and things that could be improved and changed (it's a homework task, but this question is unrelated to the task itself), part of the code is:



Function CheckIfSameCell(ByVal FirstCellPosition As CellReference, ByVal SecondCellPosition As CellReference) As Boolean
Dim InSameCell As Boolean
InSameCell = False
If FirstCellPosition.NoOfCellsSouth = SecondCellPosition.NoOfCellsSouth And FirstCellPosition.NoOfCellsEast = SecondCellPosition.NoOfCellsEast Then
InSameCell = True
End If
CheckIfSameCell = InSameCell
End Function


I can't understand why the InSameCell is variable is created, when it can just be assigned to the function name CheckIfSameCell?



Or just use return statements:?



Function CheckIfSameCell(ByVal FirstCellPosition As CellReference, ByVal SecondCellPosition As CellReference) As Boolean
If FirstCellPosition.NoOfCellsSouth = SecondCellPosition.NoOfCellsSouth And FirstCellPosition.NoOfCellsEast = SecondCellPosition.NoOfCellsEast Then
Return True
End If
Return False
End Function


I can understand not returning the expression in the If statement directly, to increase readability.



I know that assigning a return value to the Function name doesn't exit the function, whereas Return does, but is it just a person's style, or is there any advantage to the first version (imo, the second is more readable)?





Hello World phonegap app crashing

Alright, I am trying to just get the demo working on their website, but when I try to install it and run on my phone, I get this exception in Eclipse:



05-01 13:10:49.637: E/AndroidRuntime(19669): java.lang.SecurityException: ConnectivityService: Neither user 10128 nor current process has android.permission.ACCESS_NETWORK_STATE.



I thought maybe it was because it was on WiFi, but it persisted after I disabled that as well. Does anyone know what is causing this? I am literally doing the bare minimum. This is my HTML:



<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.7.0rc1.js"></script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>




IIS7 HttpModule and ISAPI Filter execution order

I have a site using ISAPI Rewrite as well as a custom HttpModule that both do Url redirects and rewrites.



In IIS 6, everything worked fine: The ISAPI Rewrite filter would run first, followed by the HttpModule. In IIS 7 (Integrated mode) the order is now the reverse, which poses a problem.



My problem, specifically, is that the HttpModule has a condition where it will issue a Url rewrite using context.RewritePath. It will explicitly add "index.aspx" to the path if no document was provided, so a request to /test/ gets rewritten to /test/index.aspx.



At some point after the path is rewritten, the ISAPI Rewrite filter executes. We've got a rule that does the opposite of the module: a request to /test/index.aspx gets 301-redirected to /test/. Thus, we have an endless loop.



How is the execution order of HttpModules and ISAPI Filters determined in IIS 7? Can the order be changed? I found this question, but it didn't really help. I'm not a master of IIS 7, but I do understand to some extent that modules and ISAPI filters run "together". Unfortunately, they are still administered differently and I can't figure out how to force one to run before the other. Help!



Note: let's assume I cannot change the existing code. It worked in IIS 6. I just want to know if there's a way to make it work in IIS 7 Integrated mode.





set attribute from value of method

I am sure I am just doing this wrong, can someone point me in the right direction?



I need to set the value of effective_date to a modified format date



effective_date is an attribute of Request



class Request < ActiveRecord::Base

validates_uniqueness_of :effective_date

def format_date=(format_date)
date_a = format_date.split("/")
month, day, year = date_a
effective_date = Date.parse("#{year}-#{month}-#{day}")
end

def format_date
effective_date
end
end


Request.create(format_date: "04/21/2012") is not setting the value to effect_date





JavaScript Separating Axis Theorem

I'm trying to wrap my head around using the Separating Axis Theorem in JavaScript to detect two squares colliding (one rotated, one not). As hard as I try, I can't figure out what this would look like in JavaScript, nor can I find any JavaScript examples. Please help, an explanation with plain numbers or JavaScript code would be most useful.



PS This link helped the most so far Algorithm to detect intersection of two rectangles?



My understanding so far is I'm supposed to get the edge difference of both squares with a method as so, but this may be completely wrong:



// "a" is an entity with width, height, x, y, and an angle.
// Note: I have no clue how to process the Canvas angle into
// projected points on an axis to test a side.
getEdges: function(a) {
var top = {
x: a.x - (a.x + a.width),
y: a.y - a.y
},
bottom = {
x: a.x - (a.x + a.width),
y: a.y + a.height - (a.y + a.height)
},
left = {
x: a.x - a.x,
y: a.y - (a.y + a.height)
},
right = {
x: a.x - a.x,
y: a.y - (a.y + a.height)
};

return [top, right, left, bottom];
}




SOLR / LUCENE how to expand list into multi-valued fields?

I am indexing from a RDBMS. I have a column in a table with pipe separated values, and upon indexing I would like to transform these values into multi-valued fields. For example,



ColumnA (From RDBMS)
---------------------
apple|orange|banana


I want to transform this to,



SOLR Index
------------
Fruit=apple
Fruit=orange
Fruit=banana


Please help!





having issue in extracting an element from xml

I have a xml like this :



  <?xml version="1.0" encoding="UTF-8"?>
<InsertReceipts>
<receipts xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:string>
<![CDATA[ test]]>
</a:string>
</receipts>
</InsertReceipts>


I want to extract element a:string from this xml,but can't figure out to do this?



as i use XmlElement foo = (XmlElement)doc.SelectSingleNode("//a:string");



it gives a parsing error



Feedback and help appreciated





ASP.NET is HttpCookie a persistent or session type of cookie

I.e. the following cookie



        HttpCookie cookie = Request.Cookies["Cookie"];


is HttpCookie a persistent or session type of cookie





JavaScript print ignored by Chrome, Workaround?

I know it has been discussed here before, yet I found no practical solution/workaround for this, I'm hoping if someone has any idea how to resolve this problem!



Here's it is:



If you try to call window.print() method frequently within a single page(as if a user clicks on a print button) in google Chrome, the browser throws a warning message in the console, stating:




Ignoring too frequent calls to print()




And nothing happens! After several seconds, things go back to normal and print dialog appears the moment you call window.print() command again! To make matters worse, the good Chrome folks use exponential wait time for a page that calls print command, meaning the more user clicks on a button to print, the more he has to wait for the print dialog to appear!



This issue has been in chrome for quite some time (14 subsequent versions) and it is confirmed as being an Area-UI bug, I posted it again for google team yesterday hoping if someone from Chrome team can verify when this incredible annoying feature is going to be fixed!



However, what I'm looking for here is a workaround for this problem, is there anything I can do be able to get this working? My company is developing a highly transactional financial system with lots of reports that needs printing, and for just this one little glitch, the whole project is at risk of running in my favorite google Chrome browser!





how to retrieve value of a json check box using php

I have a json form field which has a check box as coded :



{"name":"Act","description":"Checkthis","type":"checkbox"}


can anyone tell me how to get this value of this check box IF it is checked using php



here is the form:



<iframe src='http://www.facebook.com/plugins/registration.php?
client_id=360&
redirect_uri=http://www.pingcampus.com/facebook_registration_plugin/store_user_data.php&
fields=[
{"name":"name"},
{"name":"email"},
{"name":"gender"},
{"name":"birthday"},
{"name":"captcha"},
{"name":"Act","description":"Checkthis","type":"checkbox"}
]'
scrolling="auto"
frameborder="no"
style="border:none"
allowTransparency="true"
width="500"
height="600">
</iframe>




Difference between const ref and const pointer, c++

I'd like to know what's the difference between const ref and const pointer in c++.
When I declare on something to be const ref, can I change it's VALUE?
or the const goes on the object?
Because I know that const pointer means you cannot change the POINTER but you can change the VALUE it points to.



for example:



const char& a; // ?
const char* a; // pointer is const




LPSTR conversion

This code is not compilable:



LPSTR a1 = "a1";
LPSTR lpResult = a1 + "a2";


How can I get a long pointer lpResult to the "a1a2" string?





db.savechanges and db.dispose conflict removes my newly created object reference

In my controller i am creating a new subcategory object and saving it to my database like this:



    [Authorize(Roles = "administrator")]
[HttpPost]
public ActionResult Create(CategoryViewModel viewmodel, HttpPostedFileBase Icon)
{
SubCategory subcategory = viewmodel.subcategory;

subcategory.Category = categorycontroller.getCategoryByName(viewmodel.SelectedValue);

if (Icon != null && Icon.ContentLength > 0)
{
// extract only the filename
var fileName = Path.GetFileName(Icon.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("../../Content/icons/"), fileName);
Icon.SaveAs(path);
subcategory.Icon = fileName;
}

if (ModelState.IsValid)
{
db.subcategories.Add(subcategory);
db.SaveChanges();
return RedirectToAction("Index");
}

return View(subcategory);
}


After debugging the application i noticed that the controller correctly saves all my data including the reference to a category object in my newly created subcategory.



problem is when i load the data from my db later on the subcategory object is missing its reference to my category object.



my viewmodel looks like this:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
using SkyLearn.Areas.Categories.Controllers;

namespace SkyLearn.Areas.Categories.Models
{
public class CategoryViewModel
{
public List<SelectListItem> PossibleValues { get; set; }
public string SelectedValue { get; set; }
public SubCategory subcategory { get; set; }

public CategoryController categorycontroller;

public CategoryViewModel()
{
PossibleValues = new List<SelectListItem>();
}
}
}


and my method on the category controller that finds the object:



public Category getCategoryByName(string categoryname)
{
foreach (Category cat in getCategories())
{
if (cat.Title == categoryname)
{
return cat;
}
}
return null;
}


why does my category object reference disappear guys? im in a blind





Why is peeking into BLOBs via getBytes(long pos, int length) so slow on an H2 database?

I have an application that needs to peek into blobs get out small numbers of bytes (via getBytes(long pos, int length)). The blobs are ~30MB. When I ask for bytes near the beginning of the blob, the performance is reasonable. When I ask for bytes near the end of the blob, the performance is much worse. Looking at the source code (JdbcBlob.java) it appears that the blob is read sequentially instead of randomly (via an input stream).



Does anybody know of any workarounds? I'm a huge H2 fan and this issue isn't a deal breaker but I think it could be improved.



Thanks





BlockingCollection auto executes my functions when I attempt to add them to list

            var tasks0 = new BlockingCollection<object>(new ConcurrentQueue<object>());
tasks0.Add(Fetch(APCounter));
tasks0.Add(Decode(APCounter));
tasks0.Add(ALURes(APCounter));
tasks0.Add(Memory(APCounter));
tasks0.Add(WriteB(APCounter));


var tasks1 = new BlockingCollection<object>(new ConcurrentQueue<object>());
tasks1.Add(Fetch(APCounter+1));
tasks1.Add(Decode(APCounter + 1));
tasks1.Add(ALURes(APCounter + 1));
tasks1.Add(Memory(APCounter + 1));
tasks1.Add(WriteB(APCounter + 1));


I don't want it execute the functions being added now. I'll do that manually later using the business logic. !!!





jQuery animate percent number?

Ive looked all over but I cant find how to use jQuery's .animate() function to animate a percentage I have.



I have a progress bar with a percent number above it. When the page loads I simply want the number to increase from 0 to a defined number lets say 67%. How do I animate the number so that it displays as 1%, 2%, 3% ...up to 67%?



Also something to note is I would like to use jQuery's .animate() function because I want to define the time it takes to get to 67%.





Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION

Could someone tell me what I'm doing wrong?



I want to display the users online on specific rooms only.



the code below is the function that calls my online.php this is under my chat.php
when I load the page this function also loads.



function whos_online(){
if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();}
else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("GET","online.php?room=<?php $_SESSION['room']?>",false);
xmlhttp.send();
document.getElementById("whos_online").innerHTML=xmlhttp.responseText;
}


ONLINE.PHP



this is the content of my online.php



<link rel="stylesheet" type="text/css" href="style.css" />
<?php

session_start();
include 'db.inc.php';

class WhosOnline{
$rn = $_GET['room'];
protected $get_status_query = "SELECT * FROM `online_users` WHERE `room` = '{$rn}'";
public function DisplayUsers(){
$get_current_status = mysql_query($this->get_status_query);
if(mysql_num_rows($get_current_status)!=0){
while($row_status = mysql_fetch_array($get_current_status)){
if($_SESSION['username']==true){
echo "<div class='online_margin'> <b>".base64_decode($row_status['username'])."</b></div><hr style='border: 0; border-top: solid 1px #D8D8D8;margin: 5px 10px 5px 10px;' />";
}
}
}
}
}

$Online = new WhosOnline;
$Online->DisplayUsers();
?>


Any help?





Validating a numeric only textbox

I've created a form based program that need some validation, all I need to to make sure the user can only enter numeric value in the distance text field



So far, I've checked that it's got something in it, if it has something then go on to validate it's numeric



else if (txtEvDistance.Text.Length == 0)
{
MessageBox.Show("Please enter the distance");
}
else if (cboAddEvent.Text //is numeric)
{
MessageBox.Show("Please enter a valid numeric distance");
}