Getting python Cloud Endpoint Enum values on an Android client - android

I have a python class that inherits from Cloud Endpoints Enum and is included in a Message for transmission to an Android client.
class Status(messages.Enum):
SUCCESS = 1
NOT_IN_MATCH = 2
ALREADY_MATCHED = 3
FAILURE = 4
Is there anyway to get these constant strings ("SUCCESS", "NOT_IN_MATCH", "ALREADY_MATCHED", "FAILURE") in the Android client? I don't see them anywhere in the generated Java source code when I use get_client_lib.
Note: I have seen this post that gives a solution in Java. That is not applicable when using python Cloud Endpoints.

According to a Google Cloud Endoints dev this is not possible currently.
Unfortunately, there currently isn't [a way to get these constant strings in the Android client].

Related

Is there a way to get totalSupply of an ERC20 token using web3j java?

I'm developing an android app using android studio. I implemented web3j and successfully connected to ethereum using infura. I'm not sure how I can get the total supply of a specific coin.
Tried using the load method to load a specific tokens contract but was not able to get that to work.
Instead of using RPC nodes like Infura, I recommend that you use Moralis as it provides you with an easy API that you can call in Java. It's a basic REST API so you can call it in any other language too.
You can use this runContractFunction API here. And all you need to do is provide the input parameters as follows:
address: ERC20 token contract address
chain: the chain your ERC20 token exists
function_name: totalSupply
abi: the ABI of ERC20 token
Once you have all this setup, you'll be able to get the total supply in just a few lines of code.
Hope this helps out! :😊

How to deploy pre-trained model using sagemaker?

I have a pre-trained model that will translate text from English to Marathi. You can find it here...
git clone https://github.com/shantanuo/Word-Level-Eng-Mar-NMT.git
Clone and Run the notebook. I am looking for a way to deploy it so that users can use it as an API
The guidelines for deploying the model can be found here...
https://gitlab.com/shantanuo/dlnotebooks/blob/master/sagemaker/01-Image-classification-transfer-learning-cifar10.ipynb
I will like to know the steps to follow in order to deploy the model.
Is it possible to create an android app for this?
Great News! So your model has already been deployed when you created the endpoint. Make sure you DON'T run the sage.delete_endpoint(EndpointName=endpoint_name) at the end of the notebook!
Now you can call that endpoint via command line or an SDK like boto3.
To attach it to a public API endpoint I recommend leveraging API Gateway, Lambdas, and Sagemaker in something similar to this tutorial.
API Gateway will handle the hosting and security/tokens (if desired). After the http request hits API Gateway it needs to be caught by a designated lambda. The lambda's job is to verify the incoming data, call the Sagemaker endpoint, and return the response in the correct format.
Step 1: Build Lambda
To correctly deploy your lambda you will need to create a Serverless Framework Service.
1) First install Serverless Framework
2) Navigate to the directory where you want to store the API Gateway and Lambda files
3) In the command line run:
serverless create --template aws-python
4) Create a new file named lambdaGET.py to be deployed inside your lambda
lambdaGET.py
import os
import io
import boto3
import json
import csv
'''
endpoint_name here should be a string, the same as which was created
in your notebook on line:
endpoint_name = job_name_prefix + '-ep-' + timestamp
'''
ENDPOINT_NAME = endpoint_name
client = boto3.client('sagemaker-runtime')
# Or client = boto3.client('runtime.sagemaker') should also be acceptable
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
event = json.loads(json.dumps(event))
# I recommend you verify the data here although it is not critical
'''
I'm assuming your going to attach this to a GET in which case the
payload will be passed inside the "queryStringParameters"
'''
payload = event["queryStringParameters"]
print(payload)
response = client.invoke_endpoint(
EndpointName=ENDPOINT_NAME,
Body=payload,
ContentType='application/x-image',
Accept='Accept'
)
result = json.loads(response['Body'].read())
print(result)
'''
After the lambda has obtained the results in needs to correctly
format them to be passed across the API Gateway
'''
response = {
"isBase64Encoded": False,
"statusCode": 200,
"headers": {},
"body": json.dumps(result)
}
return response
Step 2: Build Serverless.yml
In this step you need to build the serverless file to deploy the lambda, API Gateway, and connect them together.
service: Word-Level-Eng-Mar-NMT
provider:
name: aws
runtime: python2.7
timeout: 30
stage: ${opt:stage, 'dev'}
region: ${opt:region, 'us-east-1'}
profile: ${opt:profile, 'default'}
apiName : Word-Level-Eng-Mar-NMT-${self:provider.stage}
environment:
region: ${self:provider.region}
stage: ${self:provider.stage}
stackTags:
Owner : shantanuo
Project : Word-Level-Eng-Mar-NMT
Service : Word-Level-Eng-Mar-NMT
Team : shantanuo
stackPolicy: # This policy allows updates to all resources
- Effect: Allow
Principal: "*"
Action: "Update:*"
Resource: "*"
iamRoleStatements:
- Effect: "Allow"
Action:
- "sagemaker:InvokeEndpoint"
Resource:
- "*"
# Note: Having * for the resource is highly frowned upon, you should change
# this to your acutal account number and EndpointArn when you get the chance
functions:
lambdaGET:
handler: lambdaGET.main
events:
- http:
method: GET
path: /translate
resp: json
Step 3: Deploy
1) In this step you will need to install Serverless Framework
2) Install AWS commmand line
3) Set up your AWS configure
4) Make sure your directories are setup correctly:
(lambdaGET.py and servless.yml should be in the same folder)
```
-ServiceDirectory
--- lambdaGET.py
--- serverless.yml
```
5) Navigate to the ServiceDirectory folder and in the command line run:
sls deploy
Step 4: Test
Your API can now be invoked using browsers or programs such as Postman
The base URL for all your services API endpoint can be found in console inside API Gateway > Service (in your case 'Word-Level-Eng-Mar-NMT') > Dashboard
Almost there... Now that you have the base URL you need to add the extention we placed on our endpoint: /translate
Now you can place this entire URL in Postman and send the same payload you were using in the creation and testing conducted in your notebooks. In your case it will be the file
test.jpg
TAAA DAAA!!
If your model was handling text or relatively small package size bits of information this would be the end of the story. Now because you are trying to pass an entire image it is possible that you will be over the size limit for API Gateway. In this case we will need to create an alternive plan that involves uploading the image to a public location (S3 bucket for example) and passing the URI via API. Then the lambda would have to retreive the image from the bucket and invoke the model. Still doable, just a little more complex.
I hope this helps.
The basic idea to deploy model to SageMaker is:
1) Containerize your model.
2) Publish your model to ECR repository and grant SageMaker necessary permissions.
3) Call CreateModel, CreateEndpointConfig and CreateEndpoint to deploy your model to SageMaker.
Per your notebook of training the model, you didn't use any SageMaker sdk to containerize your model automatically, so it is more complicated to start from scratch.
You may consider use any of the following sample notebooks with keras to containerize your model first:
https://github.com/awslabs/amazon-sagemaker-examples

Microsoft Azure Translator Android API not working

I was trying to make a text translator app using Microsoft-translator-API but I am not able to receive any response from this API, I always get this message:
[microsoft-translator-api] Error retrieving translation: Unable to resolve host "datamarket.accesscontrol.windows.net": No address associated with hostname
even I have given correct client Id and client secret Id.
I tried this link but I don't know where to put the JSON-Simple.jar file. I tried this link too but still with no success. I am pasting my code below:
public String translateText() throws Exception {
Translate.setClientId("whateveritis");
Translate.setClientSecret("whateveritis");
translatedText = Translate.execute(
userText.getText().toString(),
languages[sEnterLan.getSelectedItemPosition()],
languages[sTransLan.getSelectedItemPosition()]);
Language detectedLanguage = Detect.execute(userText.getText()
.toString());
this.detectedLanguage = detectedLanguage.getName(Language.ENGLISH);
return translatedText;
}
By calling above function I can receive the translated text into a string variable but every time I get an exception.
According to your code and reference links, I think you were using the third party Java wrapper boatmeme/microsoft-translator-java-api for MS Azure Translator API. However, it's an old Java wrapper which wrappered the old & unavailable APIs from the old site Azure datamarket. There is a notice at this site, and all origin APIs had been migrated to Azure subscription.
DataMarket and Data Services are being retired and will stop accepting new orders after 12/31/2016. Existing subscriptions will be retired and cancelled starting 3/31/2017. Please reach out to your service provider for options if you want to continue service.
So I suggested that you can try to refer to my answer for the other SO thread Microsoft Translator API Java, How to get client new ID with Azure to create a cognitive service for Translator Text API on Azure portal and use it via the new REST APIs.
Hope it helps.

Android to gae restlet example doesn't work on the Android side

I'm trying to run restlet's first application example - android to gae - but the value returned is alway null, showing a warning in Android's LogCat: Unable to find a converter for this representation : [application/json,UTF-8]
The specific code that returns null is this line:
Contact contact = resource.retrieve();
My Assumption that it's a conversion issue. If so, i'm surprised it's just a warning.
Any idea how to go from here?
Some notes:
I use restlet 2.1.4
I used curl to test the server side and it works great. Example: curl -i -X GET http://127.0.0.1:8888/contacts/123
To test Android against a local server, I use the following ip: 10.0.2.2
Yes, found a solution.
I just needed to register a converter - Specifically Jackson converter. Found the solution in the following SO answer: https://stackoverflow.com/a/5205993/435605
Engine.getInstance().getRegisteredConverters().add(new JacksonConverter());
The registration I did in Android's application class as it's a global registration.

HttpAuthorizer() for Pusher

I need a private channel on Pusher in order to enable a bunch of Android clients to communication with each other. Pusher was recommended to me, although it is really complicated. I've read all the docs many times, so I'm hoping someone (Mr. Leggetter?) could give me a hand.
I've installed the Pusher Android JAR on the client and am able to subscribe to public channels that I trigger from the "Event Creator" (very neat), but in order to get the private channel working, in order to trigger events, I need this:
HttpAuthorizer authorizer = new HttpAuthorizer("http://example.com/some_auth_endpoint");
PusherOptions options = new PusherOptions().setAuthorizer(authorizer);
Pusher pusher = new Pusher( YOUR_APP_KEY, options );
According to http://pusher.com/docs/authenticating_users, the HttpAuthorizer() needs a URL that points to an app server that is going to respond with a JSON authentication token. Do I have to set up my own app server to provide authentication, like the example at https://raw.github.com/pusher/pusher-android-example/master/src/com/pusher/android/example/MainActivity.java, or can Pusher provide this? This seems like something Pusher should provide.
In the Ruby server code example for my app (why is there no Java?) I see this: Pusher.url = "http://{key}:{secret}#api.pusherapp.com/apps/{app_id}". This URL, however, does not exist. I tried it in HttpAuthorizer() and got a java.io.FileNotFoundException. (I just found the "Enable Clients Events" checkbox under Settings - checking it did not help, but I'm guessing that's an important step.)
If I have to set up my own app server for authentication, I'd like to use Java with GAE. http://pusher.com/docs/authenticating_users#implementing_private_endpoints has a Python/GAE example, but no Java, and I don't know Python. Is there a library for this? Will https://github.com/marcbaechinger/gae-java-libpusher# do the trick? It doesn't seem like it would.
token. Do I have to set up my own app server to provide authentication, like the example at https://raw.github.com/pusher/pusher-android-example/master/src/com/pusher/android/example/MainActivity.java, or can Pusher provide this?
You need to set up your own authentication server. The point in this is to allow you to authenticate subscriptions. This means you can authenticate the user in any way you see fit, against any existing or new authentication mechanism you may use e.g. user sessions (more applicable to web apps) or authentication tokens your own application may provide upon initial connection (via some username/password login to your system).
In the Ruby server code example for my app (why is there no Java?) I see this: Pusher.url = "http://{key}:{secret}#api.pusherapp.com/apps/{app_id}". This URL, however, does not exist.
There is a Java server library but Pusher don't directly maintain that. It's a community contributed one.
I'm not sure where you got the URL from. Maybe from the Web API reference, but unless you are writing your own Pusher Web API library I wouldn't expect you to be using that URL directly. There are Pusher and contributed helper libraries for that sort of thing.
If I have to set up my own app server for authentication, I'd like to use Java with GAE. http://pusher.com/docs/authenticating_users#implementing_private_endpoints has a Python/GAE example, but no Java, and I don't know Python. Is there a library for this? Will https://github.com/marcbaechinger/gae-java-libpusher# do the trick?
Yes, you need to set up your own authentication server. You could create a client-side authorizer, but that would mean exposing your app_secret in client code - which you shouldn't do.
The PusherUtil class provides a number of helper methods that you could use to add subscription authentication support to the library. But - you are right - it doesn't appear to offer this functionality.
The Pusher Play module (also Java) does appear to have an appropriate method so this could be ported. See:
https://github.com/regisbamba/Play-Pusher#generating-the-authentication-string
I don't work for Pusher any more, but I would be happy to contribute to an improved Java library.

Categories

Resources