How do I use an input to call a function? [duplicate] - python

This question already has answers here:
How to access (get or set) object attribute given string corresponding to name of that attribute
(3 answers)
Closed 2 years ago.
how can I make a print to change to the input value?
import cryptowatch as cw
time = input("Time:") #15m, 1h , 1d
x = cw.markets.get("KRAKEN:ATOMEUR", ohlc = True, periods = [time])
print(x.of_15m[1][4]))
for example:
time = input("Time:") #1h
print(x.of_1h[1][4])
or:
time = input("Time:") #1d
print(x.of_1d[1][4])
EDIT:
I leave more information
cryptowatch-sdk
https://github.com/cryptowatch/cw-sdk-python
Module file where the functions are:(line 255)
https://github.com/cryptowatch/cw-sdk-python/blob/master/cryptowatch/resources/markets.py

I couldn't really test this properly since I don't have cryptowatch installed, but I think it would work. It uses the user's input to determine the name of an x object attribute, and then uses getattr() to retrieve its current value.
import cryptowatch as cw
time = input("Time:")
x = cw.markets.get("KRAKEN:ATOMEUR", ohlc=True, periods=[time])
interval = getattr(x, 'of_'+time, None)
if interval is not None:
print(interval[1][4])
else:
print('Error: unknown time', time)

Related

'dict' object has no attribute 'mean'. Problems using statistics.mean(list with numbers) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
I am trying something new with flask, Python and the arduino. I want to measure things with the arduino, calculate and save some values through phyton and put it on display through flask.
Right now I can make sure that the arduino receives and gives information and the displaying to a localhost worked. However I want to calculate the average of a list that contain numbers (ints, floats and doubles)
However when I try to use statistics.mean(recorded_humidities) or any other recorded_ list I get hit with a error which is:
app.py, line 63, in greenhouse_dashboard
average_humidity = statistics.mean(recorded_humidities)
AttributeError: 'dict' object has no attribute 'mean'`
I can make a list in a seperate file, fill in some random numbers and then I can use the statistics.mean(list_name) just fine
I am confused what is happening here and I do not know what I can do or did wrong so I am hoping to find a answer here.
Here is the full code where values get calculated:
import statistics
import sensor
from flask import Flask
from flask import render_template
from datetime import datetime
statistics = {}
recorded_humidities = []
recorded_temperatures = []
recorded_klux = []
minimal_humidites = 0
minimal_temperatures = 0
minimal_klux = 0
max_humidites = 0
max_temperatures = 0
max_klux = 0
average_humidity = 0
average_temperatures = 0
average_klux = 0
def current_time():
rightNow = datetime.now()
time = rightNow.strftime("%d %B %Y, %H:%M:%S")
time = time.lstrip('0')
time = time.lower()
day = rightNow.strftime("%A")
return "It is " + time + " on a " + day + "."
def current_humidity():
humidity = sensor.humidity
return humidity
def current_temperature():
temperature = sensor.temperature
return temperature
def current_klux():
klux = sensor.klux
return klux
app = Flask(__name__)
#app.route('/')
def greenhouse_dashboard():
recorded_humidities.append(current_humidity())
recorded_temperatures.append(current_temperature())
recorded_klux.append(current_klux())
#current values
#statistics["current_time"] = current_time()
#statistics["current_klux"] = current_klux()
#statistics["current_temperature"] = current_temperature()
#statistics["current_humidity"] = current_humidity()
#average values
average_humidity = statistics.mean(recorded_humidities) #fake value
average_temperatures = 2 #goes wrong
average_klux = 3 #goes wrong
#max values
max_humidites = max(recorded_humidities)
max_temperatures = max(recorded_temperatures)
max_klux = max(recorded_klux)
#min values
minimal_humidites = min(recorded_humidities)
minimal_temperatures = min(recorded_temperatures)
minimal_klux = min(recorded_klux)
return render_template('general.html',
time = current_time(),
humidity = current_humidity(),
temperature = current_temperature(),
klux = current_klux(),
average_klux = average_klux,
average_temperature = average_temperatures,
average_humidity = average_humidity,
min_klux = minimal_klux,
min_temperature = minimal_temperatures,
min_humidity = minimal_humidites,
max_klux = max_klux,
max_temperature = max_temperatures,
max_humidity = max_humidites)
I barely use stackoverflow but I want to use it more. if I should do certain things because it is handy or I made a mistake in giving information or setting up this question then please tell me so since I do want to use this correctly and want to help other in the end as well.
thank you in advance.
You need to either rename the statistics dictionary, or alias the statistics module import.
Solution One - Rename the statistics dict:
# statistics = {}
statistics_dict = {}
Solution Two - Alias the statistics module (not recommended):
# import statistics
import statistics as stats

Google Earth Engine python

I am trying to import nighttime light data on qgis and I keep getting invalid syntax at the last line of my code (Map. centerObject(sydney, 5))
Here is my code
import ee
from ee_plugin import Map
sydney_shp_path = ('Users/macbookpro/Downloads/OpenNightLights-master 2/onl/tutorials/files/city_of_sydney_shapefile')
night_img = ee.ImageCollection("NOAA/VIIRS/DNB/MONTHLY_V1/VCMSLCFG").filterDate('2018-01-01','2018-12-31').select('avg_rad')
NL_mean = night_img.mean()
nightclass = NL_mean.gt(5).add(NL_mean.gt(50)).add(NL_mean.gt(100))
nightclass = nightclass.updateMask(nightclass.neq(0))
Map.addLayer(nightclass.clip(sydney), ({'min':1, 'max':100}, 'VIIRS 2018', 'Nightlight')
Map.centerObject(sydney, 5)
Method Map.addLayer is not closed properly.
I am guessing method takes two parameters one return value of clip and another tuple.
Set center of map Map.setCentre()

Updating a set with another returns NONE [duplicate]

This question already has answers here:
Why doesn't a python dict.update() return the object?
(11 answers)
python setdefault(key,set())).update(... returns None
(1 answer)
Why does dict(k=4, z=2).update(dict(l=1)) return None in Python? [duplicate]
(3 answers)
Closed last year.
Trying to sum to sets from 2 different txt files with very similar content.
examplet of content:
https://articulo.mercadolibre.com.ar/MLA-1113638999-placa-de-video-colorful-gt710-nf-1gb-ddr3-garantia-oficial-_JM;Placa De Video Colorful Gt710 Nf 1gb Ddr3 Garantia Oficial;gold_special;True;6999
https://articulo.mercadolibre.com.ar/MLA-795327882-placa-de-video-geforce-gt-710-1gb-ddr3-pc-gamer-gt710-dx12-_JM;Placa De Video Geforce Gt 710 1gb Ddr3 Pc Gamer Gt710 Dx12;gold_special;True;7499
I'm trying to do that with the following code (simplifaction of the original):
with open("gt-710.txt","r") as f:
a = f.readlines()
with open("gt-7102.txt","r") as f:
b = f.readlines()
c = set(a).update(set(b))
print(c)
The output i'm getting constantly is NONE, I tried printing each set without updating and they do so properly, but once I try to sume them up they return NONE.
update method of set returns None. So what you can do is use a instead of the output of that line;
a = set(a)
a.update(set(b))
Or better yet I would do
c = set(a) | set(b)

How to write regular expression Python [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 3 years ago.
I'd like to return the value of left battery capacity parsed from the given string. It means I want to get CurrentCapacity / MaxCapacity.
data = '''
"SuperMaxCapacity" =0
"MaxCapacity": +4540;
'CurrentCapacity'= 2897,
"LegacyBatteryInfo" = {"Amperage"=18446744073709550521,"Flags"=4,"Capacity"=4540,"Current"=2897,"Voltage"=7283,"Cycle Count"=406}
"MegaMaxCapacity" = 6700
'''
This will do the job quite nicely, and will get the match, even though your data input format is quite iffy:
import re
data = '''
"SuperMaxCapacity" =0
"MaxCapacity": +4540;
'CurrentCapacity'= 2897,
"LegacyBatteryInfo" = {"Amperage"=18446744073709550521,"Flags"=4,"Capacity"=4540,"Current"=2897,"Voltage"=7283,"Cycle Count"=406}
"MegaMaxCapacity" = 6700
'''
max_capacity = re.search(r"[\"']MaxCapacity.*?[:=].*?(\d+)", data).group(1)
current_capacity = re.search(r"[\"']CurrentCapacity.*?[:=].*?(\d+)", data).group(1)
print("Max capacity:", max_capacity)
print("Current capacity:", current_capacity)
Output:
Max capacity: 4540
Current capacity: 2897

Python - insert variable when defining a name [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 6 years ago.
I have a relatively stupid question which I am not able to formulate very well (and I think it explains why I am not finding any answer)
I would like to calculate the mean, minimum, and maximum of a panda series in my dataframe for many variable (let's say age and weight)
dataframe.age.min()
dataframe.age.max()
dataframe.age.mean()
dataframe.weight.min()
dataframe.weight.max()
dataframe.weight.mean()
I would like to create some kind of loop, which would do something like:
list = ['age','weight']
for x in list:
min-"x" = dataframe.x.min()
max-"x" = dataframe.x.max()
mean-"x" = dataframe.x.mean()
I would like to have variables called min-age, max-age, mean-age
I don't understand how to define a function, and how to insert in the name min-"x" the name of my variable (x)...
Use describe on you dataframe then manipulate the index.
dfd = df.describe().stack()
dfd.index = dfd.index.to_series().str.join('-')
count-age 10.000000
count-weight 10.000000
mean-age -0.200662
mean-weight 0.298352
std-age 1.175323
std-weight 0.901915
min-age -1.778043
min-weight -0.860798
25%-age -1.144173
25%-weight -0.488076
50%-age -0.092748
50%-weight 0.294160
75%-age 0.276348
75%-weight 0.892405
max-age 1.670823
max-weight 1.680473
dtype: float64

Categories