Getting tweets of a specific user with public metrics - twitter

I've been trying to get a specific users last tweets and the public metrics of it. In playgrounds i can easily get it but when i use tweepy i can't get public metrics.
import tweepy
auth = tweepy.OAuth2BearerHandler("token")
api = tweepy.API(auth)
client = tweepy.Client("token")
allTweets = client.get_users_tweets(900437084321832960,tweet_fields=['public_metrics',])
print(allTweets)
this returns only text and id but not public metrics
{
"id": "id",
"text": "text"
},

Related

How do I modify the example json in swagger?

I'm trying to modify the sample json shown to test in swagger if a POST works or doesn't work. From where should I modify this?
That is, I would have to modify the json that is displayed when we press "Try out".
To be more precise, the json to test the post is the following:
{
"Cliente": 0,
"CantidadRegistros": 0,
"TotalesPrimerVencimiento": 0,
"TotalesSegundoVencimiento": 0,
"Detalle": [
{
"Consorcio": 0,
"UnidadFuncional": 0,
"Periodo": "string",
"Propietario": "string",
"Ubicacion": "string",
"Email": "string",
"FechaPrimerVencimiento": "2021-12-15",
"ImportePrimerVencimiento": 0,
"FechaSegundoVencimiento": "2021-12-15",
"ImporteSegundoVencimiento": 0,
"CodigoDePagoElectronico": "string",
"CodigoDeBarras": "string"
}
]
}
What I would like to modify is the format in which the date is displayed. Currently it is dd-mm-yyyy and I want to modify it to dd/mm/yyyy
Tried modifying this with the following DisplayFormat code but it didn't work for me:
[JsonPropertyName("FechaSegundoVencimiento")]
[FromQuery(Name = "FechaSegundoVencimiento")]
[ModelBinder(BinderType = typeof(DateTimeModelBinder))]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime? DueDate2 { get; set; }
I hope your help! Thanks!
The supported and out of the box way to do this, is by using XML comments, generating documentation files on build and having Swashbuckle read these comments:
Model:
public class Product
{
/// <summary>
/// The name of the product
/// </summary>
/// <example>Men's basketball shoes</example>
public string Name { get; set; }
// ...
Startup:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", ...);
var filePath = Path.Combine(System.AppContext.BaseDirectory, "Your.App.xml");
c.IncludeXmlComments(filePath);
}
If memory serves me right, this generates one example per model property. So if you reuse models between different APIs and want different examples, you'll need to branch out to other libraries.
I have used mattfrear/Swashbuckle.AspNetCore.Filters, where you can annotate your methods with [SwaggerRequestExample(typeof(...)] and [SwaggerResponseExample(typeof(...))], where ... can provide an example object that will be serialized to JSON, but note that in various cases they recommend to use Swashbuckle's built-in way.
However, you say:
Currently it is dd-mm-yyyy and I want to modify it to dd/mm/yyyy
Don't. There's no predefined date format for JSON, but most APIs accept ISO-8601(ish) formats by default. Don't go make that culture-specific.

display and update current user credentials with real time firebase database in xamarin forms

I'm creating a booking car app and I'm struggling with update driver car infos. I'm using a real time database with firebase and I want to display the current driver infos and give him to possibility to change his current car informations. I don't know how to display only the current logged driver infos. I read a lot of posts about the same topic but all were using auth with email. I also tried
await firebase.Child("Driver Vehicules").Child(auth.CurrentUser)
but it shows an error. How do I get only the current logged user url in Firebase? The following code display all the users, not just a single one.
public async Task<List<CarAndDriverDisplayInfos>> GetDriverInfos()
{
return (await firebase
.Child("Driver Vehicules")
.OnceAsync<CarAndDriverDisplayInfos>()).Select(item => new CarAndDriverDisplayInfos
{
FNameDriver = item.Object.FNameDriver,
LNameDriver = item.Object.LNameDriver,
CTypeDriver = item.Object.CTypeDriver,
CModelDriver = item.Object.CModelDriver,
YCarDriver = item.Object.YCarDriver,
ImageCarUrl = item.Object.ImageCarUrl,
ImageDriverUrl = item.Object.ImageDriverUrl,
CarIdDriver = item.Object.CarIdDriver,
PersonId = item.Object.PersonId
}).ToList();
}
protected async override void OnAppearing()
{
base.OnAppearing();
var Driver = await firebaseHelper.GetDriverInfos();
lstPersons.ItemsSource = Driver;
}

In JAVA code, not running in the Google environment, how does one use a trained translation model?

I seem to be missing something obvious, I think. We've been using the Google Translation API for a while now, and now we want to "upgrade" to a custom trained model instead of the default nmt.
We've uploaded our texts, trained it, and now have a model. In the predict tab on the Google console, it works great. so, now what?
This is the code that we use today:
translate = TranslateOptions
.newBuilder()
.setCredentials(ServiceAccountCredentials.fromStream(googleCredentials))
.build()
.getService();
translate.translate(
text,
TranslateOption.sourceLanguage(fromLng),
TranslateOption.targetLanguage(toLng),
TranslateOption.model(model));
where model is "nmt" (or "base")... should I just be able to drop in my newly trained model code that was created when the training finished? When I try, it comes back with a 400 error and the message:
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Invalid Value",
"reason" : "invalid"
} ],
"message" : "Invalid Value"
Trying different code as documented here: https://cloud.google.com/translate/docs/quickstart-client-libraries-v3
yields other errors like: "INFO: Failed to detect whether we are running on Google Compute Engine."
Where am I going wrong?
here we go... for the next person looking to do this:
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-automl</artifactId>
<version>0.97.0-beta</version>
</dependency>
code:
private PredictionServiceClient predictionClient;
private ModelName modelName;
public GoogleTranslationServiceTrained(final byte[] googleCredentials) throws IOException {
super();
PredictionServiceSettings settings = PredictionServiceSettings
.newBuilder()
.setCredentialsProvider(new CredentialsProvider() {
#Override
public Credentials getCredentials() throws IOException {
return ServiceAccountCredentials.fromStream(new ByteArrayInputStream(googleCredentials));
}
}).build();
// Instantiate client for prediction service.
predictionClient = PredictionServiceClient.create(settings);
// Get the full path of the model.
modelName = ModelName.of("xxxx", "us-central1", "yyy");
}
public String getRemoteTranslate(String text) {
TextSnippet textSnippet = TextSnippet.newBuilder().setContent(text).build();
// Set the payload by giving the content of the file.
ExamplePayload payload = ExamplePayload.newBuilder().setTextSnippet(textSnippet).build();
// Additional parameters that can be provided for prediction
Map<String, String> params = new HashMap<>();
PredictResponse response = predictionClient.predict(modelName, payload, params);
TextSnippet translatedContent = response.getPayload(0).getTranslation().getTranslatedContent();
return StringEscapeUtils.unescapeHtml4(translatedContent.getContent());
}

How to get Country,State,County and City from SmartyStreet API?

I tried using example API but seems some of the parameters missing.
This is the API I tried.
public W_AddressStateCity GetAddressStateCityInfo(W_CustomerAddress oAddress)
{
W_AddressStateCity oAddStateCity = new W_AddressStateCity();
var client = new ClientBuilder(AuthID, AuthToken).BuildUsStreetApiClient();
var lookup = new Lookup
{
Street = oAddress.AddressStreetAddress1,
Street2 = oAddress.AddressStreetAddress2,
City = oAddress.AddressCity,
State = oAddress.AddressState,
ZipCode = oAddress.AddressZipCode
};
try
{
client.Send(lookup);
}
catch (SmartyException ex)
{
// Console.WriteLine(ex.Message);
// Console.WriteLine(ex.StackTrace);
}
var candidates = lookup.Result;
oAddStateCity.Country = candidates[0].Metadata.Country;
oAddStateCity.State = candidates[0].Metadata.State;
oAddStateCity.County = candidates[0].Metadata.CountyName;
oAddStateCity.City = candidates[0].Metadata.City;
return oAddStateCity;
}
Only CountyName is available in candidates. The address is always validated before fed into this API.
How I could read Country, State and City ?
I want to read that information from the API, nit from my provided address.
I assume you are referring to the "US Street Address API". SmartyStreets has multiple APIs.
If you look at the US Street Address API documentation on the SmartyStreets site you can see an Example Output - Valid Address section that shows you the common data that is returned.
In the "components" object you can see the city_name and state_abbreviation. If you look in the "metadata" object you can see the county_name.
If you are hitting the "US Street Address API" then all addresses will have "USA" as the country. There is no need to return that. If you use the "International Street Address API" you will have country information included.

How Data is posted (POST) to Service in Servicestack , is it through URL?

I have complex requstDto which composed of other list of DTO's (Entity framework Entities) like
[Route("/demoservice/{Userdemo}/{EmployerDemoid}/{ReportDemo}/{DemoselectedDataList}/", "POST")]
public class ReportDemo : IReturn<String>
{
public List<selectedidList> selectedDataList{ get; set; }
}
where UserReport is follows
public class UserReport
{
public string UserName { get; set; }
public Datetime CreatedON{ get; set; }
}
when i try to post to request it gives me following error
A potentially dangerous Request.Path value was detected from the client (:)
i think it gives error due to : in CreatedON field ( for time part).
is the post values are also sent through URL to ServiceStack URL ? if yes
1) what if we have very large and complex requestDTO resulting into large number of characters (greater than allowed )in URL?
2) how to make above scenario work as ":" is reserved and cant be sent through URL?
3) How to see request URL Generated from client ?
My Client code in MVC.net is
var client = new JsonServiceClient(ConfigurationManager.AppSettings["applicationUrl"])
{
//for windows authentication
Credentials = CredentialCache.DefaultCredentials
};
var result = client.Post (new ReportDemo
{
UserName = model.UserName,
EmployerID = model.EmployerID,
Report = model.Report,
selectedDataList =userReportViewModel.selectedDataList
});
Thanks in advance,
Amol
Only the /path/info of the Url should be specified in the [Route]. Ideally routes should use a human-readable logically-structured Url that refers to a "Resource" (noun). See the SeviceStack REST Events Example for different examples.
Routes should also never include complex types and any variable that isn't on the [Route] is automatically sent in the HTTP Request Body for POST requests or the QueryString from GET Requests.
For a User Report like this I would choose a URL that identifies the report, if the report has a name like "Demo Report" I would use a path info like:
[Route("/reports/demo")]
public class ReportDemo : IReturn<String> { ... }
Otherwise if this is a Report for Users you may instead want to use something like:
[Route("/users/{UserName}/reports/demo")]
public class ReportDemo : IReturn<String> { ... }
You can check what url is used by using the Reverse Routing Extension methods, e.g:
var request = ReportDemo { UserName = "Foo", ... };
request.ToPostUrl().Print(); //= /users/Foo/reports/demo
Now you can send your Request with any property not in the Route getting POST'ed to the above url, e.g:
string result = client.Post (new ReportDemo {
UserName = userReportViewModel.UserName,
EmployerID = userReportViewModel.EmployerID,
Report = userReportViewModel.Report,
selectedDataList =userReportViewModel.selectedDataList
});
If your Report does return a string you can use IReturn<string> however if it returns a Response DTO you'll want to use that instead, e.g IReturn<ReportDemoResponse>.

Resources