I am using the positionning v2 API to locate some assetes using mac Addresses of Accesspoints. It is working well, but sometimes a mac address is not located where it is supposed to. So when I try to locate a position with 5-6 mac Addresses (the location of 1 mac Address is not correct), the API give me that message :
'title': 'Not Found', 'status': 404, 'code': 'E606404', 'action': 'The values provided in the request cannot produce any content for the response. The location of the WLANs and cells in the request is unknown or the locations of the radio measurements are so widely scattered that the location cannot be determined. Make sure that the network measurements are correct and consistent. Try allowing fallbacks area or any for cell positioning and singleWifi for WLAN positioning.', 'cause': 'Position not found'
How can I bypass that kind of error?
Here is the code :
data = {
"wlan": []
}
#for wifi in networks:
entry = {
"mac": "xx:xx:xx:xx:xx:xx",
"rss": -42
}
data["wlan"].append(entry)
entry1 = {
"mac": "yy:yy:yy:yy:yy:yy",
"rss": -54
}
data["wlan"].append(entry1)
entry2 = {
"mac": "zz:zz:zz:zz:zz:zz",
"rss": -76
}
data["wlan"].append(entry2)
#This mac address is not well located (400 kms difference from the real position)
#entry3 = {
# "mac": "vv:vv:vv:vv:vv:vv",
# "rss": -64
#}
#data["wlan"].append(entry3)
import json
import requests
headers = {"Content-Type": "application/json"}
url = "https://positioning.hereapi.com/v2/locate?apiKey=" + "my_api_key" + "&desired=altitude" + "&fallback=singleWifi"
print(data)
response = requests.post(url, headers=headers, data=json.dumps(data))
Could you please try with below sample code. And for best results please follow the tips defined in the document link:
Doc Link: https://developer.here.com/documentation/positioning-api/dev_guide/topics/tips-for-data-accuracy.html
import requests
import json
url = "https://positioning.hereapi.com/v2/locate?apiKey={your_api_key}&desired=altitude&fallback=singleWifi"
payload = json.dumps({
"wlan": [
{
"mac": "xxxxxx"
},
{
"mac": "xxxxxx"
}
]
})
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
Related
We are using a GTM container server.
We want to send different events from the back-end of our web application directly to our GTM server container.
The idea is to be able to activate tags that will send these events to different sources (Mixpanel, SendinBlue,...)
In the GTM server-side documentation we discovered that it is possible to use the measurement protocol used by Google Analytics.
To do this, you need to create or use a MeasurementProtocol client
So we created a new client with the path /mp/collect and tried to use the MeasurementProtocole for GA4 because we also use GA4 for Analytics.
https://developers.google.com/analytics/devguides/collection/protocol/ga4
But in the example request, it is asked for a measurementId and an apiSecret.
These are provided by GA.
What information should we give if we want to send the event to the GTM server client directly?
This is our script to test:
function myFunction() {
const measurementId = `G-XXXXXXX`;
const apiSecret = `FFFFFFFFFFFFDDDDDDDDD`;
UrlFetchApp.fetch(`https://xxxxx.xxxxxxxx.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}`, {
method: "POST",
payload: JSON.stringify({
"client_id": "client_id",
"events": [{
"name": "generate_lead",
"params": {
"currency": "USD",
"value": 99.99
}
}]
})
});
}
But we have this error
So to be able to send events from my back-end to sGTM (GTM Server container) I used this repo on Github:
https://github.com/square/server-to-server-gtm-client
1 - To install it you must download the template.tpl file from the repo.
2 - Then on sGTM you go at the bottom of the left menu and click on "Template"
3 - You must click on New in the Client Template section.
4 - After you can click on the three dot menu in the top right corner and select import.
5 - This is the moment where you import the template.tpl file you download before.
6 - Now you can click on "Client" item on the left menu and create a new Client
7 - For the client configuration select the template you created before.
8 - Then follow the readme of the repo on Github :-)
With this solution you will be able to send event from your back-end directly to the sGTM container (server).
You should give measurementId only. Without apiSecret.
Then if you are in gtm preview mode you should take X-Gtm-Server-Preview HTTP header (inside gtm preview mode find 3 dots in the upper right coner). You should add it in request.
Then you create mp client.
My python example:
# for GA4
import requests
import json
data = { "client_id": '111222333',
"events": [{"name":"page_view",
"params":{
"external_id": '123123123',
"action_source": "app"}
}]
}
data = json.dumps(data).encode("utf-8")
url = "https://yourserverdomain.com/mp?measurement_id=G-XXXXXXX"
headers = {
"x-gtm-server-preview" : "ASDADASDASDASFASFASFASFASF",
"Content-Type": "application/json",
"Origin": "https://google.com"
}
resp = requests.post(url, headers=headers, data=data)
print(resp.status_code)\
# for Facebook conversion API
url = "https://yourserverdomain.com/mp"
data = {"client_id": '123123',
"events":[{ "name":"PageView",
"params":{"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36",
"ip_override": "89.1.1.1",
"page_location":"https://google.com/",
"action_source": "app",
"external_id": "12345",
"user_data": { "email_address": 'asdasd',
"phone_number": "123",
"external_id": "12345",
"adress": {"country": "uk"}
}
}
}]
}
data = json.dumps(data).encode("utf-8")
headers = {
"x-gtm-server-preview" : "ASDASFDFAFASDFASDFASDFASDF=",
"Content-Type": "application/json",
"Origin": "https://google.com"
}
resp = requests.post(url, headers=headers, data=data)
print(resp.status_code)
If it still doesn't work, try path wuthout "collect", just "/mp".
In my experience, you will get 400 error if you have invalid event format (e.g. lost necessary params.
I am working with the prometheus pushgateway library and am having trouble sending information to it. The examples use cURL which work well, but when I try to do the equivalent with AXIOS in my node program it throws an error.
I tried setting up an express server to send the same request to. I wanted to analyze the (REQ) and see how it was displayed. It was mangled by body parser and I am kind of lost.
cat <<EOF | curl --data-binary #- http://pushgateway.example.org:9091/metrics/job/some_job/instance/some_instance
# TYPE some_metric counter
some_metric{label="val1"} 42
# TYPE another_metric gauge
# HELP another_metric Just an example.
another_metric 2398.283
EOF
I have tried a few different things in axios, none of which have worked
- https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format
request({
url: 'http://localhost:9091/metrics/job/interface_data',
method: 'POST',
body: 'datahere 10\n',
encoding: null
}, (error, response, body) => {
if (error) {
console.log(error)
} else {
console.log(response)
console.log('response, ', response.body)
}
})
Worked for me. The trick was encoding: null
This was working fine and suddenly stopped working. I'm not sure what exactly changed.
I need to download multiple images via URLs.
I'm using the following code:
https://plnkr.co/edit/nsxgwmNYUAVBRaXgDYys?p=preview
$http({
method:"GET",
url:"imageurl"
}).then(function(response){
saveAs(new Blob([response.data]), "image.jpg");
},function(err){
});
The files have different sizes, they are not 0 bytes.
For others coming here, check this solution.
What needed to be done was to add responseType: "blob" to the request:
$http({
method:"GET",
url:"imageurl",
responseType: "blob"
})
.then(...)
Here is the documentation for the responseType valid values, where it says the default is "" so the response is treated as text:
"": An empty responseType string is treated the same as "text", the default type (therefore, as a DOMString).
"blob:": The response is a Blob object containing the binary data.
Following code worked for me:
axios.get(`http://localhost:61078/api/values`, {
responseType: 'blob',
}).then(response => {
if (response) {
var FileSaver = require('file-saver');
FileSaver.saveAs(new Blob([response.data]), "image.png");
}
});
I'm trying to create a dashboard on Grafana using their backend API. I first test that my API token is set up by using GET and successfully get a return code of 200(shown below). I then try to use POST to create a simple dashboard but I keep getting a return code of 400. I'm pretty sure it has something to do with the payload I'm trying to send, but I have been unable to figure it out. Here is the link to the example page I'm using for their JSON format. http://docs.grafana.org/reference/http_api/
import requests
headers = {"Accept": "application/json","Content-Type": "application/json" ,"Authorization": "Bearer xxx"}
r = requests.get("http://www.localhost",headers=headers)
print(r.text)
print(r.status_code)
dashboard = {"id": None,
"title": "API_dashboard_test",
"tags": "[CL-5]",
"timezone": "browser",
"rows":"[{}]",
"schemaVersion": 6,
"version": 0
}
payload = {"dashboard": "%s" % dashboard}
url = "http://www.localhost/api/dashboards/db"
p = requests.post(url,headers=headers, data=payload)
print(p)
print(p.status_code)
print(p.text)
OUTPUT:
200
<Response [400]>
400
[{"classification":"DeserializationError","message":"invalid character 'd' looking for beginning of value"},{"fieldNames":["Dashboard"],"classification":"RequiredError","message":"Required"}]
The problem is that your object is not an actual json object.
You can use post method with json=YOUR_PYTHON_OBJECT
So to fix your code, change your dictionary to use just a regular python dictionary, use json=payload, rather than data=payload.
So refactoring your code, you will have:
import requests
headers = {"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer xxx"
}
r = requests.get("http://www.localhost", headers=headers)
print(r.text)
print(r.status_code)
dashboard = {"id": None,
"title": "API_dashboard_test",
"tags": ["CL-5"],
"timezone": "browser",
"rows": [{}],
"schemaVersion": 6,
"version": 0
}
payload = {"dashboard": dashboard}
url = "http://www.localhost/api/dashboards/db"
p = requests.post(url, headers=headers, json=payload)
print(p)
print(p.status_code)
print(p.text)
Note the differences in dashboard, for example, "rows" was changed from "[{}]" to just [{}] so that it is a python object (list with empty dictionary), rather than a string.
The output is
200
<Response [200]>
200
{"slug":"api_dashboard_test","status":"success","version":0}
I am reading documentation on vision API request schema. In image source, I only see option of using url of GCS image paths. Is it possible to use external image url like http://example.com/images/image01.jpg ?
Yes, this is working perfectly fine:
{
"requests": [
{
"features": [
{
"type": "WEB_DETECTION"
}
],
"image": {
"source": {
"imageUri": "http://i3.kym-cdn.com/photos/images/facebook/000/242/592/1c8.jpg"
}
}
}
]
}
Yes it can, but ONLY using google cloud storage urls. Try this:
{
"requests": [
{
"image": {
"source": {
gcsImageUri: 'gs://something.com/image',
},
},
"features": ...
"imageContext": ...
},
]
}
Yes, you can do this with any image as long as it is smaller than 4Mb. It does not have to be on Google Cloud Storage.
Here is an example using the Golang client library:
// Copyright 2016 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
// [START vision_quickstart]
// Sample vision-quickstart uses the Google Cloud Vision API to label an image.
package main
import (
"fmt"
"log"
// Imports the Google Cloud Vision API client package.
vision "cloud.google.com/go/vision/apiv1"
"golang.org/x/net/context"
)
func main() {
ctx := context.Background()
// Creates a client.
client, err := vision.NewImageAnnotatorClient(ctx)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
image := vision.NewImageFromURI("https://www.denaligrizzlybear.com/assets/images/scenic-denali.jpg")
labels, err := client.DetectLabels(ctx, image, nil, 10)
if err != nil {
log.Fatalf("Failed to detect labels: %v", err)
}
fmt.Println("Labels:")
for _, label := range labels {
fmt.Println(label.Description)
}
}
Here is the function on the Godoc:https://godoc.org/cloud.google.com/go/vision/apiv1#NewImageFromURI
The docs state:
NewImageFromURI returns an image that refers to an object in Google
Cloud Storage (when the uri is of the form "gs://BUCKET/OBJECT") or at
a public URL.
Answer for python users.
def detect_labels_uri(uri):
"""Detects labels in the file located in Google Cloud Storage or on the
Web."""
from google.cloud import vision
client = vision.ImageAnnotatorClient()
image = vision.types.Image()
image.source.image_uri = uri
response = client.label_detection(image=image)
labels = response.label_annotations
print('Labels:')
for label in labels:
print(label.description)
# [END vision_label_detection_gcs]
Yes you can use external image URL and even can use BASE64 image content also.
You can find the same in official documentation also.
Documentation URL : https://cloud.google.com/vision/docs/request#json_request_format
I have checked it with all available options and it is working fine for me.
Yes, Google Cloud Vision API DOES accept external URL images. I just used this image to get labels:
python label_sample.py -u "https://upload.wikimedia.org/wikipedia/commons/e/e6/Bleeding_finger.jpg"
Found label: red with 96.47 percent probability!!!!!!!!!!!
Found label: color with 95.46 percent probability!!!!!!!!!!!
Found label: pink with 92.15 percent probability!!!!!!!!!!!
Found label: finger with 91.06 percent probability!!!!!!!!!!!
Found label: hand with 90.45 percent probability!!!!!!!!!!!
Found label: nail with 73.23 percent probability!!!!!!!!!!!
Found label: lip with 73.09 percent probability!!!!!!!!!!!
Found label: jewellery with 68.84 percent probability!!!!!!!!!!!
Found label: produce with 68.39 percent probability!!!!!!!!!!!
Found label: macro photography with 67.86 percent probability!!!!!!!!!!!
You have to give it the url in proper format using urllib library and comment the part of opening an image like this:
url = url_file
opener = urllib.urlopen(url)
# with open(photo_file, 'rb') as image:
image_content = base64.b64encode(opener.read())