Issue in getting the Time of creation of a tweet - twitter

I'm using Tweetsharp library to display the latest 5 tweets posted by a user. I've created an app at dev/twitter and got the required tokens. I want to show the time lapsed since the tweet was posted. But the "tweet.CreatedDate" method from the Tweetsharp library is provides a time 5-6 hrs before the time of tweeting.
public DataSet GenerateTweetDataSet()
{
string time = "";
int hrs = 0, mins = 0;
int days = 0;
TwitterService service = new TwitterService(ConsumerKey, ConsumerSecret);
service.AuthenticateWith(AccessToken, AccessTokenSecret);
ListTweetsOnUserTimelineOptions tweetoptions = new ListTweetsOnUserTimelineOptions();
tweetoptions.Count = 5;
tweetoptions.ScreenName = _twitter.ScreenName;
var tweets = service.ListTweetsOnUserTimeline(tweetoptions);
DataTable TweetsTable = new DataTable();
TweetsTable.Columns.Add("Text");
TweetsTable.Columns.Add("DateTime");
TweetsTable.Columns.Add("Id");
if (tweets != null)
foreach (var tweet in tweets)
{
string UserName = tweet.User.ScreenName;
string TweetText = tweet.Text;
DateTime tweetDate = tweet.CreatedDate;
DateTime currentDate = DateTime.Now;
time = (currentDate - tweetDate).Days.ToString();
TimeSpan t1 = currentDate.Subtract(tweetDate);
mins = (Int32)t1.TotalMinutes;
hrs = (Int32)t1.TotalHours;
days = (Int32)t1.TotalDays;
if (mins < 60)
{
time = mins + " mins ago";
}
else if (mins > 60 && hrs <= 24)
{
time = hrs + " hours ago";
}
else if (hrs > 24 && days < 365)
{
time = days + " days ago";
}
else if (days > 365)
{
time = "over a year ago";
}
long id = tweet.Id;
TweetsTable.Rows.Add(TweetText, time, id);
}
DataSet ds = new DataSet();
ds.Tables.Add(TweetsTable);
return ds;
}
Can someone please point where I'm going wrong or how to fix this issue.
If not then, is there a better/simpler way to get the tweets? Any sample code without using any API library?
Any help will be appreciated.

Literal litAuthor = (Literal)e.Item.FindControl("litAuthor");
Literal litTime = (Literal)e.Item.FindControl("litTime");
HyperLink btnTwitter = (HyperLink)e.Item.FindControl("btnTwitter");
TwitterStatus twitterStatus = (TwitterStatus)e.Item.DataItem;
if (litAuthor != null)
{
if (twitterStatus != null)
{
TimeSpan diff = DateTime.Now - twitterStatus.CreatedDate;
if (diff.Days > 0)
{
litTime.Text = twitterStatus.CreatedDate.ToString("dd MMM yyyy");
}
else if (diff.Hours < 24)
{
litTime.Text = diff.Hours.ToString() + "h";
}
else
{
litTime.Text = diff.Minutes.ToString() + "m";
}
litAuthor.Text = twitterStatus.Author.ScreenName;
btnTwitter.Text = twitterStatus.Text;
btnTwitter.NavigateUrl = "http://twitter.com/" + twitterStatus.User.ScreenName + "/statuses/" + twitterStatus.IdStr;
}
}

Related

how to store that json data into array, after using jsonserialization iam getting that data

let jsonResult1:NSDictionary = NSJSONSerialization.JSONObjectWithData(da!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
println(jsonResult1)
getting below data in console
{
0 = {
"consulting_dr" = "DR.Appaji .";
"current_bed_nr" = 0;
"current_room_nr" = 0;
"discharge_date" = "03/03/2015 00:00";
"encounter_date" = "02/03/2015 12:45";
"encounter_nr" = 201503024000;
info = "";
"item_description" = "";
name = "Mrs. mythily S";
pdob = "01/08/1976";
pid = 100004;
psex = f;
pyear = "38 Years";
};
1 = {
dosage = 1;
drdate = "25/08/2014";
drnotes = "";
drugclass = Tablet;
duration = "5 day";
frequency = "";
medicine = "ACECLOFENAC+PARACETAMOL";
route = Oral;
tcomplients = "";
};
2 = {
BMI = "A:1:{s:4:\"SPO2\";s:1:\"1\";}";
BSA = "A:1:{s:4:\"SPO2\";s:1:\"1\";}";
"Dystolic_bp" = 29;
Height = 24;
Pulse = 26;
Respiration = 27;
"Systolic_bp" = 28;
Temp = 25;
Weight = 22;
dosage = 1;
drdate = "25/08/2014";
drnotes = "";
drugclass = Tablet;
duration = "5 day";
frequency = "";
medicine = RABEPRAZOLE;
route = Oral;
tcomplients = "";
};
}
how to store this in array
That is a Dictionary. It is easy to get just the data without the keys.
In Objective-C it would be :
NSArray *allData = [jsonResult1 allValues];
For swift it should be like: (not sure about syntax)
var allData = jsonResult1.allValues()
If you're up for it, you should give SwiftyJSON a try.
https://github.com/SwiftyJSON/SwiftyJSON
I've recently used it for an application that deals with a ton of JSON responses from a web service and SwiftyJSON has made it super easy for me to deal with JSON data in Swift. It will convert NSData to Dictionaries or Arrays seamlessly for you.

iOS-fail of get value

I use objectForKey to get value from an xml file but not its failed. Here is parts of the xml data
{
"__name" = root;
destination = CIVC;
message = {
"co2_emissions" = "<p>CO<sub>2</sub> emissions saved by this BART trip: <strong>9.8 pounds.</strong> Read more</p>";
legend = "bikeflag: 1 = bikes allowed. 0 = no bikes allowed. transfercode: blank = no transfer, N = normal transfer, T = timed transfer, connecting trains will wait up to five minutes for transferring passengers. S = scheduled transfer, connecting trains will not wait for transferring passengers if there is a delay.";
};
origin = ASHB;
"sched_num" = 34;
schedule = {
after = 2;
before = 2;
date = "Jan 6, 2014";
request = {
trip = (
{
"_clipper" = "1.40";
"_destTimeDate" = "01/06/2014";
"_destTimeMin" = "11:52 AM";
"_destination" = CIVC;
"_fare" = "3.75";
"_origTimeDate" = "01/06/2014 ";
"_origTimeMin" = "11:27 AM";
"_origin" = ASHB;
leg = {
"_bikeflag" = 1;
"_destTimeDate" = "01/06/2014";
"_destTimeMin" = "11:52 AM";
"_destination" = CIVC;
"_line" = "ROUTE 7";
"_order" = 1;
"_origTimeDate" = "01/06/2014";
"_origTimeMin" = "11:27 AM";
"_origin" = ASHB;
"_trainHeadStation" = MLBR;
"_trainIdx" = 29;
"_transfercode" = "";
};
},
and here is my code to get the origin,destination, sched_num, date, _destTimeDate
origin, destination, sched_num, date work well
self.DepartLabel.text = [dic objectForKey:#"origin"];
self.ArriveLabel.text = [dic objectForKey:#"destination"];
self.SchednumLabel.text = [dic objectForKey:#"sched_num"];
self.DateLabel.text = [[dic objectForKey:#"schedule"] objectForKey:#"date"];
self.TimeLabel.text = [[[[dic objectForKey:#"schedule"] objectForKey:#"request"]objectForKey:#"trip"]objectForKey:#"_destTimeDate"];
Only the _destTimeDate doest work. How to get this value?
If this is the output of your NSDictionary then you need to grab the first index.
self.TimeLabel.text = [[[[[dic objectForKey:#"schedule"] objectForKey:#"request"] objectForKey:#"trip"] objectAtIndex:0 ] objectForKey:#"_destTimeDate"];
or as Martin R pointed out you can do it like this as well
dic[#"schedule"][#"request"][#"trip"][0][#"_destTimeDate"]

Export to excel losses leading zero in mvc4

i am working on mvc4 project.I have having issue with export to excel code.I have employee id that is varchar field... and have leading zero ie : 0289707,2909878 etc..
So when i export data to excel it looses leading zero..
So how do i export data as it is ??
Controller code is as below :
public ActionResult ExportToExcel(string strStartDate, string strEndDate)
{
try
{
GridView gridView = new GridView();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "EmployeeReport " + Helper.GetBrazilTime(DateTime.UtcNow).ToString() + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
gridView.AllowPaging = false;
DateTime startDate = Convert.ToDateTime(strStartDate);
DateTime endDate = Convert.ToDateTime(strEndDate);
if (Helper.CurrentCulture == "pt-BR")
{
startDate = new DateTime(startDate.Year, startDate.Month, startDate.Day, 0, 0, 0, DateTimeKind.Utc);
endDate = new DateTime(endDate.Year, startDate.Month, endDate.Day, 0, 0, 0, DateTimeKind.Utc);
}
gridView.DataSource = ReportExecutor.GetEmployeeReportExportData(startDate, endDate);
gridView.DataBind();
//This will change the header background color
gridView.HeaderRow.Style.Add("background-color", "#FFFFFF"); //
//This will apply style to gridview header cells
for (int index = 0; index < gridView.HeaderRow.Cells.Count; index++)
{
gridView.HeaderRow.Cells[index].Style.Add("background-color", "#778899"); //Light Slate Gray
gridView.HeaderRow.Cells[index].Style.Add("foreground-color", "#ffffff"); // White
}
gridView.HeaderRow.Cells[0].Text = #Resources.Resource.ShopName;
gridView.HeaderRow.Cells[1].Text = #Resources.Resource.MachineName;
gridView.HeaderRow.Cells[2].Text = #Resources.Resource.ProjectIDName;
gridView.HeaderRow.Cells[3].Text = #Resources.Resource.BaseActivity;
gridView.HeaderRow.Cells[4].Text = #Resources.Resource.EmployeeID;
gridView.HeaderRow.Cells[5].Text = #Resources.Resource.EmployeeName;
gridView.HeaderRow.Cells[6].Text = #Resources.Resource.RunTime;
gridView.HeaderRow.Cells[7].Text = #Resources.Resource.SetUp;
gridView.HeaderRow.Cells[8].Text = #Resources.Resource.TearDown;
gridView.HeaderRow.Cells[9].Text = #Resources.Resource.Work;
gridView.HeaderRow.Cells[10].Text = #Resources.Resource.Rework;
gridView.HeaderRow.Cells[11].Text = #Resources.Resource.LunchHours;
gridView.HeaderRow.Cells[12].Text = #Resources.Resource.MaintenanceHours;
gridView.HeaderRow.Cells[13].Text = #Resources.Resource.QualityProblemHours;
gridView.HeaderRow.Cells[14].Text = #Resources.Resource.LOMHours;
gridView.HeaderRow.Cells[15].Text = #Resources.Resource.UDCIdle;
gridView.HeaderRow.Cells[16].Text = #Resources.Resource.UDCOthers;
gridView.HeaderRow.Cells[17].Text = #Resources.Resource.ActualShiftHours;
gridView.HeaderRow.Cells[18].Text = #Resources.Resource.Overtime;
int index2 = 1;
//This will apply style to alternate rows
foreach (GridViewRow gridViewRow in gridView.Rows)
{
//gridViewRow.Attributes.Add("class", "textmode");
gridViewRow.BackColor = Color.White;
if (index2 <= gridView.Rows.Count)
{
if (index2 % 2 != 0)
{
for (int index3 = 0; index3 < gridViewRow.Cells.Count; index3++)
{
gridViewRow.Cells[index3].Style.Add("background-color", "#e6e6fa");// Lavender
//gridViewRow.Cells[index3].Style.Add("class", "textmode");// Apply text style to all rows
}
}
}
index2++;
}
gridView.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
catch
{
}
return null;
}
For i As Integer = 0 To GridView1.Rows.Count - 1
//Apply text style to each Row.cell
//The attribute must be "text" not "textmode" and it must be applied to the cells
For j As Integer = 0 To GridView1.Rows(i).Cells.Count - 1
GridView1.Rows(i).Cells(j).Attributes.Add("class", "text");
Next
Next

Sequentially ordered NSMutableArray - replacing breaks in order

I've been having a mind blank over this problem, so I thought maybe some of you could shed a light on the situation.
To cut a long story short, I am building an app that fetches a school student's timetable from a server, parses it, and displays it in a table view. Each student has 7 periods per day, and there are 10 days in the timetable spanning across a fortnight (5 days in Week A, 5 days in Week B).
However the problem lies where some students have free periods - that is, they do not have a class during that period. Because the server does not take free periods into account, some students might return 70 total periods in the fortnight, whereas another might return 66.
Cutting to the chase here...
I have an ordered NSMutableArray full of NSDictionaries. A typical object in the array would look like this when outputted to the console:
{
weekday = 12;
period = 1;
room = "Room D404";
title = "English Extension";
},
I need to figure out where there is a break in the order, and if so, insert an object into it to fill the blank. Let me give you an example:
{
dayweek = 12;
period = 1;
room = "Room D404";
title = "English Extension";
},
{
dayweek = 12;
period = 2;
room = "Room W285";
title = "Modern History";
},
{
dayweek = 12;
period = 3;
room = "Room W187";
title = "Maths Extension 1";
},
{
dayweek = 12;
period = 4;
room = "Room W370";
title = Economics;
},
{
dayweek = 12;
period = 6;
room = "Room D301";
title = "English Advanced";
},
{
dayweek = 12;
period = 7;
room = "Room W282";
title = "Studies of Religion";
},
{
dayweek = 13;
period = 1;
room = "Room W370";
title = Economics;
},
There is no object where period = 5, so I need to add one. Is what I'm saying hard to understand? Sorry if it is.
Thanks in advance!
This fills in missing periods from 1 to the last existing on a day. It does not fill days to a given minimum of periods.
NSMutableArray periods; // from somewhere else
NSUInteger count = [periods count];
NSUInteger currentPeriod = 0;
NSUInteger currentDayweek = 0;
for (NSUInteger i = 0; i < count; ++i)
{
NSDictionary *periodDescription = periods[i];
NSUInteger dayweek = [periodDescription[#"dayweek"] unsignedIntegerValue];
if (dayweek != currentDayweek) {
// another day
currentPeriod = 0;
currentDayweek = dayweek;
}
NSUInteger period = [periodDescription[#"period"] unsignedIntegerValue];
currentPeriod += 1;
while (period > currentPeriod) {
NSDictionary *fillIn = #{ #"dayweek" : #(dayweek), #"period" : #(currentPeriod), #"room" : #"cafeteria", #"title" = "taking a break" };
[periods insertObject:fillIn atIndex:i];
currentPeriod += 1;
i += 1;
count += 1;
}
}
If you do not want to fill morning hours before the first existing period, add this directly before the while loop:
if (currentPeriod == 1)
currentPeriod = period;
Note: Typed in browser, errors are probable.
Try this and let me know if you are getting any issues
for (int i = 1; i<=self.arrayForRows.count; i++)
{
if ([[[self.arrayForRows objectAtIndex:i]valueForKey:#"period"] intValue] == i)
{
}
else
{
// Insert Here as [self.arrayForRows insertObject:yourObject atIndex:i];
i=i-1;
}
}
This is only a partial answer, but too long to post as a comment.
The purpose of this snippet is only to identify missing periods with a minimal amount of code. You would need to do it in a loop for all days of the fortnight, of course.
To do this you can use predicates:
// For each day create a list of all periods.
// This is just a hard coded example
NSArray *allPeriodsForDay = #[#(1),#(2),#(3),#(4),#(5),#(6)];
// Get an array of the periods actually in the list
// It will look like this: #[#(1),#(2),#(4),#(5),#(6)]; // Period 3 missing
NSArray *studentsPeriods = [periodRecords valueForKey: #"period"];
// Build a predicate to identify period(s) not in list
NSPredicate *freePredicate = [NSPredicate predicateWithFormat:#"not self in %#", studentsPeriods];
NSArray *freePeriods = [allPeriodsForDay filteredArrayUsingPredicate:freePredicate];
freePeriods now contains a list of the "missing" periods in the students' schedule for that day.
You can then create a new NSDictionary and add it to the list. Then sort it all by the period field.

Convert int val to format "HH:MM:SS" using JDK1.4

What is the most efficient method of converting an int val to its string counterpart in this format - "HH:MM:SS"
10 becomes 00:00:10
70 becomes 00:01:10
3610 becomes 01:00:10
I need this to be JDK1.4 compliant.
What I've come up with is a series of if statements and then constructing a string based on the current int val. This is not very efficient. Is there a better way?
Instead of a heap of code, how about just one line?
String time = new SimpleDateFormat("HH:mm:ss")
{{setTimeZone(TimeZone.getTimeZone("UTC"));}}.format(new Date(3610 * 1000)); // "01:00:10"
p.s. I never fails to amaze me just how much code some people write to do the simplest of things
The timezone is set to UTC, because SimpleDateFormat uses your locale to format the date. For example my timezone is GMT+10 and if I format new Date(0), the time part is "10:00:00".
For those who don't recognise that odd syntax where the timezone is being set, it's an anonymous class with an "instance block", which gets executed on construction, after the constructor has finished.
You need to clarify your definition of "efficient". To me efficient is "doesn't requiring to reinvent the wheel myself". Which means using libraries (yes, java.util.Calendar is quite outdated, but still better than coding it yourself):
int yourIntInSeconds = 3610;
Calendar dayStart = Calendar.getInstance();
dayStart.set(Calendar.HOUR_OF_DAY, 0);
dayStart.set(Calendar.MINUTE, 0);
dayStart.set(Calendar.SECOND, 0);
// also reset subsecond values if plan to display those
dayStart.add(Calendar.SECOND, yourIntInSeconds);
System.out.println(
new SimpleDateFormat("HH:mm:ss").format(
new Date(dayStart.getTimeInMillis())
)
);
All of Calendar, Date and SimpleDateFormat are compatible with JDK 1.4.
This is what I do:
private static final String LONG_DURATION_FMT = "%d:%02d:%02d";
private static final String SHORT_DURATION_FMT = "%d:%02d";
public static String formatSecondsAsDuration(long seconds) {
final long h = seconds / 3600;
final long remainder = seconds % 3600;
final long m = remainder / 60;
final long s = remainder % 60;
if (h > 0) {
return String.format(LONG_DURATION_FMT, h, m, s);
} else {
return String.format(SHORT_DURATION_FMT, m, s);
}
}
But using a StringBuffer instead of String.format could be faster. Just try it.
How about this (I made it in my last project):
public static String formatTime(long totalSeconds)
{
int hours, minutes, remainder, totalSecondsNoFraction;
double seconds;
// Calculating hours, minutes and seconds
String s = Double.toString(totalSeconds);
String [] arr = s.split("\\.");
totalSecondsNoFraction = Integer.parseInt(arr[0]);
hours = totalSecondsNoFraction / 3600;
remainder = totalSecondsNoFraction % 3600;
minutes = remainder / 60;
seconds = remainder % 60;
if(arr[1].contains("E")) seconds = Double.parseDouble("." + arr[1]);
else seconds += Double.parseDouble("." + arr[1]);
// Formatting the string that conatins hours, minutes and seconds
StringBuilder result = new StringBuilder(".");
String sep = "", nextSep = " and ";
if(seconds > 0)
{
result.insert(0, " seconds").insert(0, seconds);
sep = nextSep;
nextSep = ", ";
}
if(minutes > 0)
{
if(minutes > 1) result.insert(0, sep).insert(0, " minutes").insert(0, minutes);
else result.insert(0, sep).insert(0, " minute").insert(0, minutes);
sep = nextSep;
nextSep = ", ";
}
if(hours > 0)
{
if(hours > 1) result.insert(0, sep).insert(0, " hours").insert(0, hours);
else result.insert(0, sep).insert(0, " hour").insert(0, hours);
}
return result.toString();
}

Resources