def evcb(self, x, _y): # print("evcb", self, x, y) if x == "Nein": mon = datetime.date.today() if mon == self.mon: return self.mon = mon mon = utils.monYYYY(self.mon) dia = MDDialog(size_hint=(.8, .4), title="Monatsauswahl", text="Arbeitsblatt senden vom " + mon + "?", text_button_cancel="Nein", text_button_ok="Ja", events_callback=self.evcb) dia.open() else: dataDir = utils.getDataDir() excel = arbExcel.ArbExcel(utils.monYY(self.mon), dataDir, self) excelFile, title = excel.makeExcel() if os.name == "posix": import android_email mail = android_email.AndroidEmail() mon = utils.monYYYY(self.mon) mail.send(recipient=app.menu.ids.emailadresse.text, subject="Arbeitsblatt vom " + mon, text="Anbei das Arbeitsblatt von " + app.menu.ids.vorname.text + " " + app.menu.ids.nachname.text + " vom " + mon + ".", attachment=excelFile)
def storeImages(self, newImgs): # tuples to list, skip if image_url=row[7] is already set unsavedImgs = [list(row) for row in newImgs if not row[7].startswith("http")] # don't store already saved images again in gphoto: savedImgs = [list(row) for row in newImgs if row[7].startswith("http")] photo_objs = [{"filepath": utils.getDataDir() + "/images/" + row[6], "desc": row[6][0:row[6].index(".jpg")]} for row in unsavedImgs] # if len(photo_objs) > 0: # self.gphoto.upload_photos(photo_objs) pcnt = len(photo_objs) for i, photo_obj in enumerate(photo_objs): self.message(f"Speichere Bild {i + 1} von {pcnt}") if self.useGoogle: self.gphoto.upload_photos([photo_obj]) else: self.serverIntf.upload_photos([photo_obj]) for i, row in enumerate(unsavedImgs): old_image_path = row[6] new_image_path = photo_objs[i]["id"] new_image_url = photo_objs[i]["url"] self.dbinst.update_imagepath(old_image_path, new_image_path, new_image_url, row[4], row[5]) row[6] = new_image_path row[7] = new_image_url # store all of them in gsheets (duplicates removed by gsheet script) # or in Locationsserver DB unsavedImgs.extend(savedImgs) return unsavedImgs, photo_objs
def build(self): if os.name == "posix": perms = [ "android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE" ] haveperms = acquire_permissions(perms) dataDir = utils.getDataDir() os.makedirs(dataDir, exist_ok=True) db = dataDir + "/arbeitsblatt.db" print("db path", db) xconn = sqlite3.connect(db) familie.conn = xconn arbExcel.conn = xconn app.conn = xconn global conn conn = xconn initDB(xconn) self.menu = Menu(name="Menu") self.root = Page() self.root.sm.add_widget(self.menu) self.tage["0"] = self.root.sm.current_screen self.path = None return self.root
def do_capture(self, lat, lon): self.lat = lat self.lon = lon lat_round = str(round(lat, self.stellen)) lon_round = str(round(lon, self.stellen)) self.filename = lat_round + "_" + lon_round + "_" + time.strftime( "%Y%m%d_%H%M%S") + ".jpg" self.filepath = utils.getDataDir() + "/images/" + self.filename if platform != "android": from plyer import filechooser cwd = os.getcwd() path = filechooser.open_file( title="Bitte ein Bild auswählen", path=self.path, multiple=False, filters=[["Photos", "*.jpg", "*.jpeg"]], preview=True) os.chdir(cwd) if not path: self.app.show_daten(False) return path = path[0] self.path = os.path.dirname(path) shutil.copyfile(path, self.filepath) self.change_image() return try: self.app.camera.take_picture(filename=self.filepath, on_complete=self.camera_callback) except NotImplementedError: self.app.msgDialog("OS-Spezifisch", "Kamera ist nur auf Android verfügbar")
def getConn(self): connMap = getattr(threadLocal, "connMap", None) if connMap is None: connMap = {} dbname = self.baseJS.get("db_name") conn = connMap.get(dbname, None) if conn is None: db = utils.getDataDir() + "/" + dbname conn = sqlite3.connect(db) connMap[dbname] = conn return conn
def build(self): if platform == 'android': perms = ["android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.CAMERA", "android.permission.ACCESS_FINE_LOCATION"] haveperms = utils.acquire_permissions(perms) self.gps = plyer.gps self.gps.configure(self.gps_onlocation, self.gps_onstatus) import my_camera self.camera = my_camera.MyAndroidCamera() Window.bind(on_keyboard=self.popScreen) os.makedirs(utils.getDataDir() + "/images", exist_ok=True) self.markerMap = {} self.settings_cls = SettingsWithSidebar self.curMarker = None self.relocated = 0 self.dialog = None self.baseConfig = config.Config() self.error = self.baseConfig.getErrors() if self.error: Clock.schedule_once(self.show_error, 2) self.store = JsonStore("base.json") self.root = Page() try: base = self.store.get("base")["base"] self.baseConfig.getBase(self.base) except: base = self.baseConfig.getNames()[0] print("base", base) print("----------- /data/user/0/de.adfcmuenchen.abstellanlagen") utils.walk("/data/user/0/de.adfcmuenchen.abstellanlagen") # print("----------- cwd", os.getcwd()) # utils.walk(".") # print("------------getDataDir", utils.getDataDir()) # utils.walk(utils.getDataDir()) # print("------------getExternalFilesDir", utils.getExternalFilesDir()) # utils.walk(utils.getExternalFilesDir()) self.executor = ThreadPoolExecutor(max_workers=1) self.future = None laststored = self.getConfigValue("gespeichert") if not laststored: self.setConfigValue("gespeichert", time.strftime("%Y.%m.%d %H:%M:%S")) self.useGoogle = bool(self.getConfigValue("useGoogle")) self.setup(base) return self.root
def getImage(self, basename, maxdim): print("getImage", basename, maxdim) # getImage 48.08127_11.52709_20200525_165425.jpg 200 200 filename = utils.getDataDir() + f"/images/{maxdim}_{basename}" if os.path.exists(filename): return filename tablename = self.tabellenname + "_images" req = f"/getimage/{tablename}/{basename}?maxdim={maxdim}" resp = self.reqWithRetry("GET", req) if resp.status != 200: print("getImage resp", resp.status, resp.reason) return None img = resp.read() with open(filename, "wb") as f: f.write(img) return filename
def korrektur(self, *args): try: with conn: c = conn.cursor() c.execute("delete from arbeitsblatt") except OperationalError: pass if self.path is None: path = filechooser.open_file( title="Bitte ein Arbeitsblatt auswählen", path="C:/", multiple=False, filters=[["Excel", "*.xlsx"]], preview=False) if not path: return self.path = path[0] dataDir = utils.getDataDir() self.korrExcel = arbExcel.ArbExcel("00.00", dataDir, self) self.korrExcel.readExcel(self.path)
def setDaten(self): # gc.collect() # get images for lat/lon mv = self.app.mapview self.lat, self.lon = mv.lat, mv.lon img_tuples = self.dbinst.get_images(self.lat, self.lon) imlist = [] thumbnaildim = int(self.app.getConfigValue("thumbnaildim", "200")) for tuple in img_tuples: # (image_path, None) or (mediaId, image_url) if tuple[1]: if hasattr(self.app, "gphoto"): img = self.app.gphoto.getImage(tuple[0], thumbnaildim) else: img = self.app.serverIntf.getImage(tuple[0], thumbnaildim) if img is None: self.app.message("Kann Bild nicht laden") else: imlist.append((img, tuple[0])) else: imlist.append((utils.getDataDir() + "/images/" + tuple[0], None)) # photo_image must be the last or the only one imlist.append((utils.getCurDir() + "/images/" + utils.camera_icon, None)) imlist2 = [] for p in imlist: if os.path.exists(p[0]): imlist2.append(p) else: print("cannot access", p[0]) # raise Exception("cannot access " + p) self.image_list = imlist2 # get daten for lat/lon values = self.dbinst.get_daten(self.lat, self.lon) print("daten values", values, self.lat, self.lon) self.setValues(values) if values is not None: self.lat = values["lat"] self.lon = values["lon"]
def __init__(self): configDir = utils.getDataDir() self.configs = {} self.errors = [] for dir in set([configDir, "."]): self.file_list = sorted(glob.glob(dir + "/config/*.json")) for f in self.file_list: try: with open(f, "r", encoding="UTF-8") as jsonFile: confJS = json.load(jsonFile) try: self.checkSyntax(confJS, syntax) except Exception as e: utils.printEx("Kann Datei " + f + " nicht parsen:", e) self.errors.append("Kann Datei " + f + " nicht parsen:" + str(e)) continue nm = confJS.get("name") self.configs[nm] = confJS print("gelesen:", f, nm) except Exception as e: utils.printEx("Fehler beim Lesen von " + f, e)
import pandas as pd import datetime import numpy as np import utils def readStockBasics(): stock_basics_path = os.path.join(dataDir, 'stock-basics.csv') if not os.path.exists(stock_basics_path): stockBasics_df = ts.get_stock_basics() stockBasics_df.to_csv(stock_basics_path, index_label='code') return stockBasics_df else: return pd.read_csv(stock_basics_path, index_col='code') dataDir = utils.getDataDir() stockBasics_df = readStockBasics() def formatStr(str, len_expect): real_len = len(str) if real_len >= len_expect: return str asciiLen = 0 for ch in str: asciiLen = (ord(ch) < 128 and asciiLen + 1 or asciiLen + 2) if asciiLen >= len_expect: return str return str.rjust(real_len + len_expect - asciiLen) def printStockPrice(price_df): iter = price_df.iterrows()
def initDB(self, app): self.app = app self.baseJS = app.baseJS self.aliasname = None self.tabellenname = self.baseJS.get("db_tabellenname") self.stellen = self.baseJS.get("gps").get("nachkommastellen") self.colnames = {} self.floatcols = {} db = utils.getDataDir() + "/" + self.baseJS.get("db_name") colnames = [ "creator", "created", "modified", "lat", "lon", "lat_round", "lon_round" ] floatcols = [3, 4, 5, 6] fields = [ "creator TEXT", "created TEXT", "modified TEXT", "lat REAL", "lon REAL", "lat_round STRING", "lon_round STRING" ] for i, feld in enumerate(self.baseJS.get("daten").get("felder")): name = feld.get("name") colnames.append(name) type = sqtype[feld.get("type")] if type == "REAL": floatcols.append(i + 7) fields.append(name + " " + type) fields.append("PRIMARY KEY (lat_round, lon_round) ON CONFLICT REPLACE") stmt1 = "CREATE TABLE IF NOT EXISTS " + self.tabellenname + "_daten (" + ", ".join( fields) + ")" conn = self.getConn() with conn: c = conn.cursor() c.execute(stmt1) self.colnames["daten"] = colnames self.floatcols["daten"] = floatcols fields = [ "creator TEXT", "created TEXT", "lat REAL", "lon REAL", "lat_round STRING", "lon_round STRING", "image_path STRING", "image_url STRING", "PRIMARY KEY (image_path) ON CONFLICT REPLACE" ] stmt1 = "CREATE TABLE IF NOT EXISTS " + self.tabellenname + "_images (" + ", ".join( fields) + ")" stmt2 = "CREATE INDEX IF NOT EXISTS latlonrnd_images ON " + self.tabellenname + "_images (lat_round, lon_round)" with conn: c = conn.cursor() c.execute(stmt1) c.execute(stmt2) self.colnames["images"] = [ "creator", "created", "lat", "lon", "lat_round", "lon_round", "image_path", "image_url" ] self.floatcols["images"] = [2, 3, 4, 5] if self.baseJS.get("zusatz", None) is None: return colnames = [ "nr", "creator", "created", "modified", "lat", "lon", "lat_round", "lon_round" ] floatcols = [4, 5, 6, 7] fields = [ "nr INTEGER PRIMARY KEY", "creator TEXT", "created TEXT", "modified TEXT", "lat REAL", "lon REAL", "lat_round STRING", "lon_round STRING" ] for i, feld in enumerate(self.baseJS.get("zusatz").get("felder")): name = feld.get("name") colnames.append(name) type = sqtype[feld.get("type")] if type == "REAL": floatcols.append(i + 8) fields.append(name + " " + type) fields.append( "UNIQUE(creator, created, modified, lat_round, lon_round) ON CONFLICT REPLACE" ) stmt1 = "CREATE TABLE IF NOT EXISTS " + self.tabellenname + "_zusatz (" + ", ".join( fields) + ")" stmt2 = "CREATE INDEX IF NOT EXISTS latlonrnd_zusatz ON " + self.tabellenname + "_zusatz (lat_round, lon_round)" with conn: c = conn.cursor() c.execute(stmt1) c.execute(stmt2) self.colnames["zusatz"] = colnames self.floatcols["zusatz"] = floatcols