flask restplus path variable default value - swagger

How to set the default value for a path variable with Flask restplus?
For example, with the below:
#api.route('/calendars/coordinates/<string:latitude>/<string:longitude>/years/<string:year>')
class DailyCalendarHandler(Resource):
get_parser = reqparse.RequestParser()
get_parser.add_argument('timezone', type=str, default='Asia/Calcutta', help='Example: Asia/Calcutta', location='args', required=True)
get_parser.add_argument('encoding', type=str, default='devanagari', help='Example: iast, devanagari, kannada, tamil', location='args',
required=True)
#api.expect(get_parser)
def get(self, latitude, longitude, year):
args = self.get_parser.parse_args()
city = City("", latitude, longitude, args['timezone'])
How do I set default for year, latitude and longitude?
If it were a request variable, one could do the below:
get_parser = reqparse.RequestParser()
get_parser.add_argument('output_transliteration', location='args', default='devanagari', help='devanagari/slp1/iast/hk/wx/itrans/kolkata/velthuis')

You can define multiple URL rules above your class and define defaults for arguments. Something like:
#api.route('/calendars/coordinates', defaults={'latitude':123, 'longitude': 56})
#api.route('/calendars/latitude/<string:latitude>/longitude/<string:longitude>/years/<string:year>')
class DailyCalendarHandler(Resource):
def get(self, latitude, longitude, year='2017'):

Related

Telegraf config file - substrings and converting hexadecimal to int for ingestion

I have incoming BLE beacon data from a gateway in the following format:
{"msg":"advData","gmac":"94A408B02508","obj":
[
{"type":32,"dmac":"AC233FE0784F","data1":"0201060303F1FF1716E2C56DB5DFFB48D2B060D0F5A71096E000000000C564","rssi":-45,"time":"2022-10-13 02:46:24"},
{"type":32,"dmac":"AC233FE078A1","data1":"0201060303F1FF1716E2C56DB5DFFB48D2B060D0F5A71096E000000000C564","rssi":-42,"time":"2022-10-13 02:46:26"}
]
}
and I want to extract the attributes gmac, dmac, rssi, and process attribute data1 and ingest these into influxdb via a telegraf config file.
I can successfully ingest gmac, dmac, and rssi using the below telegraf config:
## Data format to consume.
## Each data format has its own unique set of configuration options, read
## more about them here:
## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md
data_format = "json_v2"
tagexclude = ["topic"]
[[inputs.mqtt_consumer.json_v2]]
measurement_name = "a"
timestamp_path = "obj.#.time"
timestamp_format = "unix"
[[inputs.mqtt_consumer.json_v2.tag]]
path = "gmac"
rename = "g"
[[inputs.mqtt_consumer.json_v2.tag]]
path = "obj.#.dmac"
rename = "d"
[[inputs.mqtt_consumer.json_v2.field]]
path = "obj.#.rssi"
type = "int"
rename = "r"
However, I'm not sure how to process the data1 attribute where I need to (1) extract characters 15 and 16 and convert this from a hexadecimal value to an integer, and (2) extract characters 13 and 14 and convert each hexadecimal value to an integer before combining them together as a float (character 13 is the whole number component, character 14 is the decimal component).
Can anybody provide some guidance here?
Many thanks!
Got it working thanks to some help over at Influx Community, I've pasted the relevant section of the telegraf config file if this is of help to anyone else:
data_format = "json_v2"
tagexclude = ["topic"]
[[inputs.mqtt_consumer.json_v2]]
measurement_name = "a"
timestamp_path = "obj.#.time"
timestamp_format = "unix"
[[inputs.mqtt_consumer.json_v2.tag]]
path = "gmac"
# g is gateway MAC address
rename = "g"
[[inputs.mqtt_consumer.json_v2.tag]]
path = "obj.#.dmac"
# d is beacon MAC address
rename = "d"
[[inputs.mqtt_consumer.json_v2.field]]
path = "obj.#.rssi"
type = "int"
# r is RSSI of beacon
rename = "r"
[[inputs.mqtt_consumer.json_v2.field]]
path = "obj.#.data1"
data_type = "string"
[[processors.starlark]]
namepass = ["a"]
source = '''
def apply(metric):
data1 = metric.fields.pop("data1")
tempWhole = int("0x" + data1[26:28], 0)
tempDecimal = int("0x" + data1[28:30], 0)
tempDecimal = tempDecimal / 100
# t is temperature of chip to two decimal points precision
metric.fields["t"] = tempWhole + tempDecimal
# b is battery level in mV
metric.fields["b"] = int("0x" + data1[30:34], 0)
return metric
'''

How to pass required arguments in Google colab (Notebook)

I use google colab for execution.
In the following code, as all the arguments are passed by default. I can pass the args as an empty list, which can be seen from the last line:
DEFAULT_ENV_NAME = "PongNoFrameskip-v4"
MEAN_REWARD_BOUND = 19.5
parser.add_argument("--cuda", default=True, action="store_true", help="Enable cuda")
parser.add_argument("--env", default=DEFAULT_ENV_NAME,
help="Name of the environment, default=" + DEFAULT_ENV_NAME)
parser.add_argument("--reward", type=float, default=MEAN_REWARD_BOUND,
help="Mean reward boundary for stop of training, default=%.2f" % MEAN_REWARD_BOUND)
args = parser.parse_args(args = [])
when I use print(args) I got:
Namespace(cuda=True, env='PongNoFrameskip-v4', reward=19.5)
Also when I execute the following code:
DEFAULT_ENV_NAME = "PongNoFrameskip-v4"
parser.add_argument("-m", "--model", required=True, help="Model file to load")
parser.add_argument("-e", "--env", default=DEFAULT_ENV_NAME,
help="Environment name to use, default=" + DEFAULT_ENV_NAME)
parser.add_argument("-r", "--record", help="Directory to store video recording")
parser.add_argument("--no-visualize", default=True, action='store_false', dest='visualize',
help="Disable visualization of the game play")
args = parser.parse_args(args=['dqn_model'])
I am getting errors in syntax, which is because of the last line. I need to send required values for model argument (say dqn_model).
What is the correct syntax for passing the arguments?
I tried the following which gave me errors:
args = parser.parse_args(args=['dqn_model'])
args = parser.parse_args(args=[model='dqn_model'])
args = parser.parse_args(args=[m='dqn_model'])
this worked out for me
use :
args = argparse.Namespace(cuda="Argument=required",env="PongNoFrameskip-v4",reward=19.5)
make sure you have added all the argument keys with their respective value.

Using a single pattern to capture multiple values containing in a file in lua script

i have a text file that contains data in the format YEAR, CITY, COUNTRY. data is written as one YEAR, CITY, COUNTRY per line. eg -:
1896, Athens, Greece
1900, Paris, France
Previously i was using the data hard coded like this
local data = {}
data[1] = { year = 1896, city = "Athens", country = "Greece" }
data[2] = { year = 1900, city = "Paris", country = "France" }
data[3] = { year = 1904, city = "St Louis", country = "USA" }
data[4] = { year = 1908, city = "London", country = "UK" }
data[5] = { year = 1912, city = "Stockholm", country = "Sweden" }
data[6] = { year = 1920, city = "Antwerp", country = "Netherlands" }
Now i need to read the lines from the file and get the values in to the private knowledge base "local data = {} "
Cant figure out how to capture multiple values using a single pattern from the data in the file.
My code so far is
local path = system.pathForFile( "olympicData.txt", system.ResourceDirectory )
-- Open the file handle
local file, errorString = io.open( path, "r" )
if not file then
-- Error occurred; output the cause
print( "File error: " .. errorString )
else
-- Read each line of the file
for line in file:lines() do
local i, value = line:match("%d")
table.insert(data, i)
-- Close the file
io.close(file)
end
file = nil
Given that you read a line like
1896, Athens, Greece
You can simply obtain the desired values using captures.
https://www.lua.org/manual/5.3/manual.html#6.4.1
Captures: A pattern can contain sub-patterns enclosed in parentheses; they describe captures. When a match succeeds, the
substrings of the subject string that match captures are stored
(captured) for future use. Captures are numbered according to their
left parentheses. For instance, in the pattern "(a*(.)%w(%s*))", the
part of the string matching "a*(.)%w(%s*)" is stored as the first
capture (and therefore has number 1); the character matching "." is
captured with number 2, and the part matching "%s*" has number 3.
As a special case, the empty capture () captures the current string
position (a number). For instance, if we apply the pattern "()aa()" on
the string "flaaap", there will be two captures: 3 and 5.
local example = "1896, Athens, Greece"
local year, city, country = example:match("(%d+), (%w+), (%w+)")
print(year, city, country)

Why JAX-WS generates wrapper for all method arguments?

I am trying to generate web service interface using jax-ws, but i am getting a methods with wrapper class for all arguments instead of arguments list. For example:
#SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
#WebResult(name = "ResendControlsToDmiResponse", targetNamespace = "http://tempuri.org/", partName = "parameters")
#WebMethod(operationName = "ResendControlsToDmi", action = "http://tempuri.org/ResendControlsToDmi")
#Generated(value = "org.apache.cxf.tools.wsdlto.WSDLToJava", date = "2014-01-30T16:01:26.266+02:00")
public ResendControlsToDmiResponse resendControlsToDmi(
#WebParam(partName = "parameters", name = "ResendControlsToDmiData", targetNamespace = "http://tempuri.org/")
ResendControlsToDmiData parameters
);
Can't understand why it's happening and how to generate method with corredct signature.
There rules about the naming of the part elements as they related to the operation name. In your case, it looks like the operation is named resendControlsToDmi, but the incoming data part/element is named ResendControlsToDmiData. Remove the Data off the end of that and it may change. The response element is properly ResendControlsToDmiResponse.

Django-Admin Exception Value: 'DeclarativeFieldsMetaclass' object is not iterable

I have one form in forms.py
class EmailForm(forms.Form):
recipient = forms.CharField(max_length=14, min_length=12,
widget=forms.TextInput(attrs=require))
message = forms.CharField(max_length=140, min_length=1,
widget=forms.Textarea(attrs={'cols': 30, 'rows': 5}))
and my site url is
admin.autodiscover()
urlpatterns = patterns('', (r'^admin/(.*)',
include(admin.site.urls)),)
now I want it to be shown on admin interface
I tried so far
First attempt
from myapps.forms import EmailForm
class EmailAdmin(admin.ModelAdmin):
form = EmailForm
did not work Exception Value:
'DeclarativeFieldsMetaclass' object is not iterable
Second attempt
and now I followed http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contri...
but could not get help
class EmailAdmin(admin.ModelAdmin):
def my_view(self,request):
return admin_my_view(request,self)
def get_urls(self):
urls = super(SmsAdmin, self).get_urls()
my_urls = patterns('',(r'^my_view/
$',self.admin_site.admin_view(self.my_view)))
return my_urls + urls
def admin_my_view(request, model_admin):
opts = model_admin.model._meta
admin_site = model_admin.admin_site
has_perm = request.user.has_perm(opts.app_label \
+ '.' + opts.get_change_permission())
context = {'admin_site': admin_site.name,
'title': "My Custom View",
'opts': opts,
'root_path': '/%s' % admin_site.root_path,
'app_label': opts.app_label,
'has_change_permission': has_perm}
template = 'admin/demo_app/admin_my_view.html'
return render_to_response(template,
context,context_instance=RequestContext(request))
admin.site.register(EmailForm,EmailAdmin)
and when I run server and type on browser localhost:8000/admin
and hit enter button
Exception Value:
'DeclarativeFieldsMetaclass' object is not iterable
and second time just after first time when I again enter then it show
me the admin page but I can't see my EmailAdmin in admin interface..
Just help me or suggest me any link.
Thanks
(This is my attempt at reformatting your model code):
class EmailForm(forms.Form):
recipient = forms.CharField(max_length=14, min_length=12,
widget=forms.TextInput(attrs=require))
message = forms.CharField(max_length=140, min_length=1,
widget=forms.Textarea(attrs={'cols': 30, 'rows': 5}))
I would put my money on the bit that says "attrs=require" -- if that's not a typo.
What you want instead is something like this:
recipient = forms.CharField(max_length=14, min_length=12,
widget=forms.TextInput(), required=True)

Resources