finding twitter4j retweet rate limit - java

I would like to know how to find in java a rate limit for specific function in twitter4j
twitter.retweetStatus(lstatusId);
I would like to know how to check if im passing the rate limit for retweeting.

You can add following piece of code to check for rate limit status, you would need to provide for specific url, for example if you are fetching "statuses/retweets_of_me" then your url-to-get-rate-limit-status-of would be "statuses/retweets_of_me"
You would need to find mapping to Rest API url for each of your streaming API call and use that url to get the rate limit status.
if (twitter.getRateLimitStatus().get(<<url-to-get-rate-limit-status-of>>).getRemaining() == 0) {
System.out.println("Adding wait of - " + twitter.getRateLimitStatus().get(<<url-to-get-rate-limit-status-of>>).getSecondsUntilReset() + " seconds");
Thread.sleep(twitter.getRateLimitStatus().get(<<url-to-get-rate-limit-status-of>>).getSecondsUntilReset()*1000);
}
Hope this helps.

Related

How to set multiple metrics for setDailyMetric method while sending request to Business Profile Performance API?

Following this link getDailyMetricsTimeSeries, I wanna have all the metrics in one request, since I have many locations for every client, it does not seem to be professional if I send one separate request for every single metric.
before in Google My business V4.9 we could use "ALL" to request all available metrics. Unfortunately, this is not working with the new API. Can I get ALL the metrics in ONE single request from Google Business Profile Performance API?
Here is my code in JAVA:
supposing that the variable business_profile_performance is the initialiser global parameters via its Builder and also takes care of authentication.
try {
BusinessProfilePerformance.Locations.GetDailyMetricsTimeSeries metricReport =
business_profile_perfomance.locations().
getDailyMetricsTimeSeries("My locationID" ).
setDailyMetric(dailyMetric).
setDailyRangeStartDateYear(Integer.valueOf("the desired start Year")).
setDailyRangeStartDateMonth(Integer.valueOf(" the desired start Month" )).
setDailyRangeStartDateDay(Integer.valueOf(" the desired start Day ")).
setDailyRangeEndDateYear(Integer.valueOf("the desired End Year" )).
setDailyRangeEndDateMonth(Integer.valueOf(" the desired End Month")).
setDailyRangeEndDateDay(Integer.valueOf("the desired End Day"));
GetDailyMetricsTimeSeriesResponse response = metricReport.execute();
if (!response.isEmpty()) {
System.out.println(dailyMetric + " Response == " + response);
}
} catch (Exception e) {
System.out.println(e);
}
I used a list for my dailyMetric variable, and using a for loop it takes turn as photo below:
If setting dailyMetric to "CALL_CLICKS" works and setting it to "CALL_CLICKS,WEBSITE_CLICKS" does not work, it would seem that the new API does not support that use case anymore.

how to extend the get values while using Google Analytics Data API (GA4) in java to get count of screenPageViews?

I appreciate your attention to my ask.
When I use the below java code to get information from google analytics, it shows just 10 values of pages...
Actually, the total page on my website is 37 pages and I would like to get total values from ga4.
I just started study programming 2 months ago.
Please help me to solve it.
private void testUpdateGoogleAnalyticsApi() {
String ga4PropertyId = Container.config.getGa4PropertyId();
try (AlphaAnalyticsDataClient analyticsData = AlphaAnalyticsDataClient.create()) {
RunReportRequest request = RunReportRequest.newBuilder()
.setEntity(Entity.newBuilder().setPropertyId(ga4PropertyId))
.addDimensions(Dimension.newBuilder().setName("pagePath"))
.addMetrics(Metric.newBuilder().setName("screenPageViews"))
.addDateRanges(DateRange.newBuilder().setStartDate("2020-12-01").setEndDate("today")).build();
// Make the request
RunReportResponse response = analyticsData.runReport(request);
System.out.println("Report result:");
for (Row row : response.getRowsList()) {
System.out.printf("%s, %s%n", row.getDimensionValues(0).getValue(), row.getMetricValues(0).getValue());
}
} catch (IOException e) {
e.printStackTrace();
}
}
If the limit parameter in the RunReportRequest is unspecified, the RunReportResponse will contain only 10 rows. For this report, this means you will only see 10 pages paths in the API's report even though a larger number of pages (37) exist for your website.
The solution is to use the "setLimit" method on RunReportRequest's Builder. For example, please update the request's builder to the following to return up to 10,000 rows.
RunReportRequest request = RunReportRequest.newBuilder()
.setEntity(Entity.newBuilder().setPropertyId(ga4PropertyId))
.addDimensions(Dimension.newBuilder().setName("pagePath"))
.addMetrics(Metric.newBuilder().setName("screenPageViews"))
.addDateRanges(DateRange.newBuilder().setStartDate("2020-12-01").setEndDate("today"))
.setLimit(10000L).build();
There is documentation on this API's pagination mechanism here. Pagination specifies how many rows you would like to see in the response. In this case, the number of pages from your website.
The setLimit method controls the number of rows in the report response and is documented on github here.

HERE Api: How do I request PDE data for Safety_Alerts layer without getting Bad Request?

I am creating an Android App that accesses the HERE Platform Data Extension Api (= PDE). Therefore I first load a map centering on my current location. This works fine so far. Then I try to load data from the PDE for the layer "SAFETY_ALERTS", but I get a 400 Error there with the message "tilexy lists 992 tiles but the limit is 64 tiles".
I am not sure where this "tilexy" comes from. I already researched through as much documentation of the PDE as I could find online, but I couldn't find an answer.
Set<String> layers = new HashSet<>(Arrays.asList("SAFETY_ALERTS"));
GeoBoundingBox bbox = map.getBoundingBox();
final PlatformDataRequest request = PlatformDataRequest.createBoundingBoxRequest(layers, bbox);
request.execute(new PlatformDataRequest.Listener<PlatformDataResult>() {
#Override
public void onCompleted(PlatformDataResult platformDataResult, PlatformDataRequest.Error error) {
if (error == null) {
//do something
} else {
//show error --> Here is where I get
}
I expected to get a PlatformDataItemCollection, which is a List of PlatformDataItems (they implement Map). Instead I got the 400-Error.
Does somebody know where this error comes from and can help me fix my mistake?
As per the error message, it would be advisable to check the API call as it seems that more than 64 coordinates has been passed in tilexy parameter in the rest call. tilexy is a string, which is passed in comma separated sequence of tilex,tiley pairs for the requested tiles. The tilex and tiley values are described in the "tile" resource.
please refer following documentation for more reference
developer.here.com/documentation/platform-data/topics/example-tiles.html
Happy Coding..!!

Encog - EarlyStoppingStrategy with validation set

I would like to stop training a network once I see the error calculated from the validation set starts to increase. I'm using a BasicNetwork with RPROP as the training algorithm, and I have the following training iteration:
double validationError = 999.999;
while(!stop){
train.iteration(); //weights are updated here
System.out.println("Epoch #" + epoch + " Error : " + train.getError()) ;
//I'm just comparing to see if the error on the validation set increased or not
if (network.calculateError(validationSet) < validationError)
validationError = network.calculateError(validationSet);
else
//once the error increases I stop the training.
stop = true ;
System.out.println("Epoch #" + epoch + "Validation Error" + network.calculateError(validationSet));
epoch++;
}
train.finishTraining();
Obviously this isn't working because the weights have already been changed before figuring out if I need to stop training or not. Is there anyway I can take a step back and use the old weights?
I also see the EarlyStoppingStrategy class which is probably what I need to use by using the addStrategy() method. However, I really don't understand why the EarlyStoppingStrategy constructor takes both the validation set and the test set. I thought it would only need the validation set and the test set shouldn't be used at all until I test the output of the network.
Encog's EarlyStoppingStrategy class implements an early stopping strategy according to this paper:
Proben1 | A Set of Neural Network Benchmark Problems and Benchmarking Rules
(a full cite is included in the Javadoc)
If you just want to stop as soon as a validation set's error no longer improves you may just want to use the Encog SimpleEarlyStoppingStrategy, found here:
org.encog.ml.train.strategy.end.SimpleEarlyStoppingStrategy
Note, that SimpleEarlyStoppingStrategy requires Encog 3.3.

Best way to time something in Selenium

I'm writing some Selenium tests in Java, and I'm mostly trying to use verifications instead of assertions because the things I'm checking aren't very dependent so I don't want to abort if one little thing doesn't work. One of the things I'd like to keep an eye on is whether certain Drupal pages are taking forever to load. What's the best way to do that?
Little example of the pattern I'm using.
selenium.open("/m");
selenium.click("link=Android");
selenium.waitForPageToLoad("100000");
if (selenium.isTextPresent("Epocrates")) {
System.out.println(" Epocrates confirmed");
} else {
System.out.println("Epocrates failed");
}
Should I have two "waitForPagetoLoad" statements (say, 10000 and 100000) and if the desired text doesn't show up after the first one, print a statement? That seems clumsy. What I'd like to do is just a line like
if (timeToLoad>10000) System.out.println("Epocrates was slow");
And then keep going to check whether the text was present or not.
waitForPageToLoad will wait until the next page is loaded. So you can just do a start/end timer and do your if:
long start = System.currentTimeMillis();
selenium.waitForPageToLoad("100000");
long timeToLoad= (System.currentTimeMillis()-start);
if (timeToLoad>10000) System.out.println("Epocrates was slow");
Does your text load after the page is loaded? I mean, is the text inserted dynamically? Otherwise the text should be present as soon as the page was loaded.
selenium.isTextPresent
doesn't wait. It only checks the currently available page.
The best method to wait for something in Selenium is as follow:
Reporter.log("Waiting for element '" + locator + "' to appear.");
new Wait()
{
public boolean until()
{
return selenium.isElementPresent(locator);
}
}.wait("The element '" + locator + "' did not appear within "
+ timeout + " ms.", timeout);
The Waiter is part of selenium you only have to import it.
Also here is a framework that you can use. It's opensource, handles mostly everything and can be easily expanded.
https://sourceforge.net/projects/webauthfw/
Use it well and give us credit hehe. :)
Cheers,
Gergely.
In a Selenium integration test, I did it like so, using nano-time and converting to a double to get seconds:
long endTime = System.nanoTime();
long duration = (endTime - startTime);
Reporter.log("Duration was: " + ((double)duration / 1000000000.0) + " seconds.", true);
assertTrue( duration >=0 || duration <= 1000, "Test that duration of default implicit
timeout is less than 1 second, or nearly 0.");

Categories