Exemplo n.º 1
0
 def startmonth(self, summary):
   """ Start new month """
   
   self.writeperiod('monthsummaryfile', 'monthtodate')
   summary['monthtodate']['ah'][3] = 0  # zero number of samples for av 
   summary['monthtodate'] = deepcopy(summary['current'])
   filecopy(config['files']['summaryfile'],config['files']['summaryfile']+ self.printtime[0:8])
Exemplo n.º 2
0
    def startmonth(self, summary):
        """ Start new month """

        self.writeperiod("monthsummaryfile", "monthtodate")
        summary["monthtodate"]["ah"][3] = 0  # zero number of samples for av
        summary["monthtodate"] = deepcopy(summary["current"])
        filecopy(config["files"]["summaryfile"], config["files"]["summaryfile"] + self.printtime[0:8])
Exemplo n.º 3
0
def initmain(soc):
    """ initialise main loop, soc is SOC to start battery DOD to"""
    summary = logsummary.summary
    printtime = int(time.strftime("%Y%m%d%H%M%S ", time.localtime()))
    #  print (int(summary['current']['timestamp']),printtime)
    while printtime < int(summary['current']['timestamp']):
        print(printtime, summary['current']['timestamp'])
        print("Error: Current time before last sample time")
        time.sleep(30)
        printtime = int(time.strftime("%Y%m%d%H%M%S", time.localtime()))

    filecopy(config['files']['summaryfile'],
             config['files']['summaryfile'] + "R" + str(int(printtime)))
    if soc > config['battery']['capacity']:
        print("Battery DOD must be less than Battery Capacity")

    else:
        if soc < 0:
            batdata.soc = summary['current']['ah'][0]
            batdata.socadj = summary['current']['dod'][0]
        else:
            batdata.soc = soc
            batdata.socadj = soc
            summary['current']['dod'][3] = 0
        summary['current']['dod'][
            3] = -100  # flag don't adjust leakage current
        prevtime = logsummary.currenttime
Exemplo n.º 4
0
 def backup(self):
     if not autosub.BCKPATH:
         message = 'No backup/restore folder in config defined.'
     elif not os.path.exists(autosub.BCKPATH):
         message = 'Backup/restore folder does not exists.'
     elif not os.access(autosub.BCKPATH, os.W_OK):
         message = 'No write acess to backup location.<BR> Make shure the autosub user(or on Synology the group sc-media) has write access!'
     else:
         dest = os.path.join(
             autosub.BCKPATH,
             os.path.splitext(os.path.split(autosub.CONFIGFILE)[1])[0] +
             '.bck')
         try:
             filecopy(autosub.CONFIGFILE, dest)
             src = os.path.join(autosub.CONFIGPATH, 'database.db')
             filecopy(src, os.path.join(autosub.BCKPATH, 'database.bck'))
             log.info("Config and Database backuped to %s" %
                      autosub.BCKPATH)
             message = 'Succesfull backup of the config and database files to:<BR> %s' % autosub.BCKPATH
         except Exception as error:
             log.error(error.message)
             message = error.message
     tmpl = PageTemplate(file="interface/templates/home.tmpl")
     tmpl.message = message.encode('ascii', 'ignore')
     tmpl.displaymessage = "Yes"
     tmpl.modalheader = "Information"
     return str(tmpl)
Exemplo n.º 5
0
 def restore(self):
     cfg_src = os.path.join(
         autosub.BCKPATH,
         os.path.splitext(os.path.split(autosub.CONFIGFILE)[1])[0] + '.bck')
     bck_src = os.path.join(autosub.BCKPATH, 'database.bck')
     if not autosub.BCKPATH:
         message = 'No backup/restore folder in config defined.'
     elif not os.path.exists(autosub.BCKPATH):
         message = 'Backup/restore folder does not exists.'
     elif not os.path.isfile(cfg_src):
         message = '%s not found to restore!' % cfg_src
     elif not os.path.isfile(bck_src):
         message = '%s not found to restore!' % src_src
     else:
         try:
             filecopy(cfg_src, autosub.CONFIGFILE)
             filecopy(bck_src,
                      os.path.join(autosub.CONFIGPATH, 'database.db'))
             initDb()
             log.info("Config and Database restored from %s" %
                      autosub.BCKPATH)
             message = 'Succesfully restored the config and database from:<BR> %s' % autosub.BCKPATH
         except Exception as error:
             message = error.message
     tmpl = PageTemplate(file="interface/templates/home.tmpl")
     tmpl.message = message.encode('ascii', 'ignore')
     tmpl.displaymessage = "Yes"
     tmpl.modalheader = "Information"
     return str(tmpl)
Exemplo n.º 6
0
  def startmonth(self, summary):
    """ Start new month """

    self.writeperiod('monthsummaryfile', 'monthtodate')
    summary['monthtodate']['ah'][3] = 0  # zero number of samples for av
    summary['monthtodate'] = deepcopy(summary['current'])
    filecopy(config['files']['summaryfile'],config['files']['summaryfile']+ self.printtime[0:8])
Exemplo n.º 7
0
def test_tabber(filename, test1, test2):

    name2 = '%s.a' % filename
    name3 = '%s.b' % filename

    # copy name -> name.a and run test1 on name.a
    filecopy(filename, name2)
    cmd = 'python tab.py %s %s' % (test1, name2)
    print("Command: ", cmd)
    os.system(cmd)

    # load both files
    lines_a = open(filename, 'rb').readlines()
    lines_b = open(name2, 'rb').readlines()

    # now, a straight diff should show changes
    df = list(unified_diff(lines_a, lines_b))
    if len(df) == 0:
        print("*** ERROR - expected a change when tabifying %s" % filename)
        sys.exit(1)
    #else:
    #	print ''.join(df)

    # however, after lstripping each line, they should be
    # equal again
    lines_a = list(map(string.lstrip, lines_a))
    lines_b = list(map(string.lstrip, lines_b))

    df = list(unified_diff(lines_a, lines_b))
    if len(df) != 0:
        print("*** ERROR - not the same after %s %s" % (test1, filename))
    else:
        print('OK - leading whitespace changed as expected.')

    # copy name -> name.b and run test2 on name.b
    filecopy(name2, name3)
    cmd = 'python tab.py %s %s' % (test2, name3)
    print("Command: ", cmd)
    os.system(cmd)

    # now original & name3 should be identical
    lines_a = open(filename, 'rb').readlines()
    lines_b = open(name3, 'rb').readlines()

    df = list(unified_diff(lines_a, lines_b))
    if len(df) != 0:
        print("*** ERROR - lossage after %s %s" % (test2, filename))
        sys.exit(1)
    else:
        print("OK - no changes after %s -> %s" % (test1, test2))
Exemplo n.º 8
0
    def test_remove_component(self):
        path = os.path.join("trial1", "gold", "trial1.json")
        bagfilepath = os.path.join(self.bag.bagdir, 'data', path)
        bagmdpath = os.path.join(self.bag.bagdir, 'metadata', path,
                                 "nerdm.json")
        self.assertFalse(os.path.exists(bagfilepath))
        self.assertFalse(os.path.exists(bagmdpath))
        self.assertFalse(os.path.exists(os.path.dirname(bagmdpath)))
        self.assertFalse(os.path.exists(os.path.dirname(bagfilepath)))

        # add and remove data and metadata
        self.bag.add_data_file(path, os.path.join(datadir, "trial1.json"))
        self.assertTrue(os.path.exists(bagfilepath))
        self.assertTrue(os.path.exists(bagmdpath))

        self.assertTrue(self.bag.remove_component(path))
        self.assertFalse(os.path.exists(bagfilepath))
        self.assertFalse(os.path.exists(bagmdpath))
        self.assertFalse(os.path.exists(os.path.dirname(bagmdpath)))
        self.assertTrue(os.path.exists(os.path.dirname(bagfilepath)))

        # add and remove just metadata
        self.bag.init_filemd_for(path,
                                 write=True,
                                 examine=os.path.join(datadir, "trial1.json"))
        self.assertFalse(os.path.exists(bagfilepath))
        self.assertTrue(os.path.exists(bagmdpath))

        self.assertTrue(self.bag.remove_component(path))
        self.assertFalse(os.path.exists(bagfilepath))
        self.assertFalse(os.path.exists(bagmdpath))
        self.assertFalse(os.path.exists(os.path.dirname(bagmdpath)))
        self.assertTrue(os.path.exists(os.path.dirname(bagfilepath)))

        # just a data file exists
        self.assertFalse(
            os.path.exists(os.path.join(self.bag.bagdir, "data",
                                        "trial1.json")))
        filecopy(os.path.join(datadir, "trial1.json"),
                 os.path.join(self.bag.bagdir, "data", "trial1.json"))
        self.assertTrue(
            os.path.exists(os.path.join(self.bag.bagdir, "data",
                                        "trial1.json")))
        self.assertTrue(self.bag.remove_component("trial1.json"))
        self.assertFalse(
            os.path.exists(os.path.join(self.bag.bagdir, "data",
                                        "trial1.json")))
Exemplo n.º 9
0
def template(file):
	if not check_install(DEFAULT_DIRNAME): return False
	file_abs = os.path.abspath(file);
	os.chdir(DEFAULT_DIRNAME)
	config = load_config(DEFAULT_CONFIG)

	if "template" in config: 
		answer = raw_input("[WARNING] template file \""+config['template']+"\" already installed, "+
						   "this action will overwrite it with "+file+". Continue? [y/n]: ")
		if answer != 'y': return False


	config['template'] = file
	filecopy(file_abs, os.path.basename(file))

	write_config(config)
	return True
Exemplo n.º 10
0
def deamon(soc=-1):
    """ Main loop, gets battery data, gets summary.py to do logging"""

    try:
        import summary
        logsummary = summary.Summary()
        summary = logsummary.summary
        printtime = time.strftime("%Y%m%d%H%M%S ", time.localtime())
        while int(printtime) <= int(summary['current']['timestamp']):
            print(printtime, summary['current']['timestamp'])
            print("Error: Current time before last sample time")
            time.sleep(30)
            printtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
        batdata = Readings()  # initialise batdata after we have valid sys time
        alarms = Alarms(batdata)  # initialise alarms

        print(str(printtime))
        filecopy(config['files']['summaryfile'],
                 config['files']['summaryfile'] + "R" + str(int(printtime)))
        if soc > config['battery']['capacity']:
            print("Battery DOD must be less than Battery Capacity")

        else:
            if soc < 0:
                batdata.soc = summary['current']['ah'][0]
                batdata.socadj = summary['current']['dod'][0]
            else:
                batdata.soc = soc
                batdata.socadj = soc
                summary['current']['dod'][3] = 0
            summary['current']['dod'][
                3] = -100  # flag don't adjust leakage current
            prevtime = logsummary.currenttime
            prevbatvoltage = batdata.batvoltsav[numcells]
            #    logsummary.startday(summary)
            #    logsummary.starthour(summary)

            while True:
                try:
                    for i in range(config['sampling']['samplesav']):
                        #          printvoltage = ''
                        #          for i in range(numcells+1):
                        #            printvoltage = printvoltage + str(round(batdata.batvolts[i],3)).ljust(5,'0') + ' '
                        #         print (printvoltage)
                        batdata.getraw()

                        #          if batdata.batvoltsav[numcells] >= 55.2 and prevbatvoltage < 55.2:  # reset SOC counter?
                        #          print batdata.socadj/(float(summary['current']['dod'][3])*24.0)
                        if batdata.batvoltsav[numcells] < config['battery']['vreset'] \
                        and prevbatvoltage >= config['battery']['vreset'] \
                        and summary['current']['dod'][3] != 0 \
                        and -batdata.currentav[0] < config['battery']['ireset']:  # reset SOC counter?

                            if summary['current']['dod'][3] <= 0:
                                socerr = 0
                            else:
                                socerr = batdata.socadj / (
                                    float(summary['current']['dod'][3]) * 24.0)
                                socerr = max(socerr, -0.01)
                                socerr = min(socerr, 0.01)
                            config['battery']['ahloss'] = config['battery'][
                                'ahloss'] - socerr / 2
                            batconfigdata = SafeConfigParser()
                            batconfigdata.read('battery.cfg')
                            batconfigdata.set('battery', 'ahloss',
                                              str(config['battery']['ahloss']))
                            with open('battery.cfg', 'w') as batconfig:
                                batconfigdata.write(batconfig)
                            batconfig.closed

                            batdata.soc = 0.0
                            batdata.socadj = 0.0
                            summary['current']['dod'][3] = 0
                        else:
                            batdata.soc = batdata.soc + batdata.batah
                            batdata.socadj = batdata.socadj + batdata.batahadj
                        batdata.ah = batdata.ah + batdata.batah
                        batdata.inahtot = batdata.inahtot + batdata.inah
                        batdata.pwrbattot = batdata.pwrbattot + batdata.pwrbat
                        batdata.pwrintot = batdata.pwrintot + batdata.pwrin
                    prevbatvoltage = batdata.batvoltsav[numcells]
                    # check alarms
                    alarms.scanalarms(batdata)
                    # update summaries
                    logsummary.update(summary, batdata)
                    if logsummary.currenttime[4] != logsummary.prevtime[
                            4]:  # new minute
                        loadconfig()
                        logsummary.updatesection(summary, 'hour', 'current')
                        logsummary.updatesection(summary, 'alltime', 'current')
                        logsummary.updatesection(summary, 'currentday',
                                                 'current')
                        logsummary.updatesection(summary, 'monthtodate',
                                                 'current')
                        logsummary.updatesection(summary, 'yeartodate',
                                                 'current')
                        logsummary.writesummary()
                        batdata.ah = 0.0
                        batdata.ahadj = 0.0
                        batdata.inahtot = 0.0
                        batdata.pwrbattot = 0.0
                        batdata.pwrintot = 0.0
                        for i in range(batdata.numiins):
                            batdata.kWhin[i] = 0.0
                            batdata.kWhout[i] = 0.0
                        for i in range(numcells):
                            batdata.baltime[i] = 0

                    if logsummary.currenttime[3] != logsummary.prevtime[
                            3]:  # new hour
                        logsummary.starthour(summary)

                    if logsummary.currenttime[3] < logsummary.prevtime[
                            3]:  # newday
                        logsummary.startday(summary)

                    if logsummary.currenttime[1] != logsummary.prevtime[
                            1]:  # new month
                        logsummary.startmonth(summary)

                    if logsummary.currenttime[0] != logsummary.prevtime[
                            0]:  # new year
                        logsummary.startyear(summary)

                except KeyboardInterrupt:
                    sys.stdout.write('\n')
                    logsummary.close()
                    sys.exit(9)
                    break
    except Exception as err:
        log.critical(err)
        raise
Exemplo n.º 11
0
def deamon(soc=-1):
  """ Main loop, gets battery data, gets summary.py to do logging"""
  try:
    import summary
    logsummary = summary.Summary()
    summary = logsummary.summary
    printtime = time.strftime("%Y%m%d%H%M%S ", time.localtime())
    while int(printtime) <= int(summary['current']['timestamp']):
      print(printtime,summary['current']['timestamp'])
      print ("Error: Current time before last sample time")
      time.sleep(30)
      printtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
    batdata = Readings()  # initialise batdata after we have valid sys time
    alarms = Alarms(batdata,summary) # initialise alarms

    print (str(printtime))
    filecopy(config['files']['summaryfile'],config['files']['summaryfile']+"R" + str(int(printtime)))
    if soc > config['battery']['capacity']:
      print ("Battery DOD must be less than Battery Capacity")

    else:
      if soc < 0:
         batdata.soc = summary['current']['ah'][0]
         batdata.socadj = summary['current']['dod'][0]
      else:
        batdata.soc = soc
        batdata.socadj = soc
        summary['current']['dod'][3] = 0
      summary['current']['dod'][3] = -100 # flag don't adjust leakage current
      prevtime = logsummary.currenttime
      prevbatvoltage = batdata.batvoltsav[numcells]
  #    logsummary.startday(summary)
  #    logsummary.starthour(summary)


      while True:
        try:
          for i in range(config['sampling']['samplesav']):
  #          printvoltage = ''
  #          for i in range(numcells+1):
  #            printvoltage = printvoltage + str(round(batdata.batvolts[i],3)).ljust(5,'0') + ' '
  #         print (printvoltage)
            batdata.getraw()

  #          if batdata.batvoltsav[numcells] >= 55.2 and prevbatvoltage < 55.2:  # reset SOC counter?
  #          print batdata.socadj/(float(summary['current']['dod'][3])*24.0)
            if batdata.batvoltsav[numcells] < config['battery']['vreset'] \
            and prevbatvoltage >= config['battery']['vreset'] \
            and summary['current']['dod'][3] != 0 \
            and -batdata.currentav[0] < config['battery']['ireset']:  # reset SOC counter?

              if summary['current']['dod'][3] <= 0 :
                socerr=0
              else:
                socerr=batdata.socadj/(float(summary['current']['dod'][3])*24.0)
                socerr=max(socerr,-0.01)
                socerr=min(socerr,0.01)
              config['battery']['ahloss']=config['battery']['ahloss']-socerr/2
              batconfigdata=SafeConfigParser()
              batconfigdata.read('battery.cfg')
              batconfigdata.set('battery','ahloss',str(config['battery']['ahloss']))
              with open('battery.cfg', 'w') as batconfig:
                batconfigdata.write(batconfig)
              batconfig.closed

              batdata.soc = 0.0
              batdata.socadj = 0.0
              summary['current']['dod'][3] = 0
            else:
              batdata.soc = batdata.soc + batdata.batah
              batdata.socadj = batdata.socadj +batdata.batahadj
            batdata.ah = batdata.ah + batdata.batah
            batdata.inahtot = batdata.inahtot + batdata.inah
            batdata.pwrbattot = batdata.pwrbattot + batdata.pwrbat
            batdata.pwrintot = batdata.pwrintot + batdata.pwrin
          prevbatvoltage = batdata.batvoltsav[numcells]
  # check alarms
          alarms.scanalarms(batdata)
  # update summaries
          logsummary.update(summary, batdata)
          if logsummary.currenttime[4] != logsummary.prevtime[4]:  # new minute
            loadconfig()
            logsummary.updatesection(summary, 'hour', 'current')
            logsummary.updatesection(summary, 'alltime','current')
            logsummary.updatesection(summary, 'currentday','current')
            logsummary.updatesection(summary, 'monthtodate', 'current')
            logsummary.updatesection(summary, 'yeartodate', 'current')
            logsummary.writesummary()
            batdata.ah = 0.0
            batdata.ahadj = 0.0
            batdata.inahtot = 0.0
            batdata.pwrbattot = 0.0
            batdata.pwrintot = 0.0
            for i in range(batdata.numiins):
              batdata.kWhin[i] = 0.0
              batdata.kWhout[i] = 0.0
            for i in range(numcells):
              batdata.baltime[i]=0


          if logsummary.currenttime[3] != logsummary.prevtime[3]:  # new hour
            logsummary.starthour(summary)

          if logsummary.currenttime[3] < logsummary.prevtime[3]: # newday
            logsummary.startday(summary)

          if logsummary.currenttime[1] != logsummary.prevtime[1]: # new month
            logsummary.startmonth(summary)

          if logsummary.currenttime[0] != logsummary.prevtime[0]: # new year
            logsummary.startyear(summary)

        except KeyboardInterrupt:
          sys.stdout.write('\n')
          logsummary.close()
          sys.exit(9)
          break
  except Exception as err:
    log.critical(err)
    raise
Exemplo n.º 12
0
 def handle(self, *args, **options):
     try:
         version = options.pop('version')[0]
         url = "https://github.com/stephanekirsch/e-colle/tarball/" + version
         try:
             with urlopen(url) as fichier, open(
                     os.path.join("..", "e-colle.tar.gz"),
                     "wb") as fichier_zip:
                 self.stdout.write(
                     "téléchargement de la version {} de e-colle".format(
                         version))
                 self.stdout.write("progression: 0.0%", ending="\r")
                 taille = fichier.getheader('Content-Length')
                 taille = int(taille) if taille is not None else 3000000
                 taille = int(taille)
                 CHUNK = 32 * 1024
                 progress = 0
                 efface = 4
                 while True:
                     chunk = fichier.read(CHUNK)
                     if not chunk:
                         break
                     else:
                         progress += CHUNK
                         progress = min(taille, progress)
                         pourcent = "progression: {:.2f}%".format(
                             100 * progress / taille)
                         self.stdout.write(pourcent, ending="\r")
                         fichier_zip.write(chunk)
                 self.stdout.write("\ntéléchargement terminé")
         except HTTPError:
             raise CommandError(
                 "la version précisée: {} n'existe pas".format(version))
         # décompression du fichier zip
         archive_zip = tarfile.open(os.path.join("..", "e-colle.tar.gz"),
                                    "r:gz")
         archive_zip.extractall("..")
         # on renomme le nouveau e-colle
         reps = [
             f for f in os.listdir("..") if not os.path.isfile(f)
             and f.startswith("stephanekirsch-e-colle")
         ]
         os.rename(os.path.join("..", reps[0]),
                   os.path.join("..", "e-colle-new"))
         # on récupère les données de config de l'ancien e-colle pour les passer au nouveau.
         self.stdout.write("copie des données de configuration")
         from ecolle.settings import DEFAULT_ADMIN_PASSWD, DEFAULT_SECRETARIAT_PASSWD, EMAIL_ADMIN, EMAIL_SECRETARIAT, IP_FILTRE_ADMIN,\
         IP_FILTRE_ADRESSES, DATABASES, BDD, IMAGEMAGICK, ALLOWED_HOSTS, INTERNAL_IPS, SECRET_KEY, TIME_ZONE, HEURE_DEBUT, HEURE_FIN, INTERVALLE
         try:
             from ecolle.settings import GESTION_ADMIN_BDD
         except exception:
             GESTION_ADMIN_BDD = False
         db = DATABASES["default"]
         with open(os.path.join("..", "e-colle-new", "ecolle", "config.py"),
                   "wt",
                   encoding="utf8") as fichier:
             fichier.write(
                 "DEFAULT_ADMIN_PASSWD = '{}' # mot de passe de l'utilisateur administrateur\n"
                 .format(DEFAULT_ADMIN_PASSWD))
             fichier.write(
                 "DEFAULT_SECRETARIAT_PASSWD = '{}' # mot de passe de l'utilisateur secrétariat\n"
                 .format(DEFAULT_SECRETARIAT_PASSWD))
             fichier.write(
                 "EMAIL_ADMIN = '{}' # email de l'utilisateur administateur\n"
                 .format(EMAIL_ADMIN))
             fichier.write(
                 "EMAIL_SECRETARIAT = '{}' # email de l'utilisateur secrétariat\n"
                 .format(EMAIL_SECRETARIAT))
             fichier.write(
                 "IP_FILTRE_ADMIN = {} # filtrage IP pour l'utilisateur administrateur\n"
                 .format(IP_FILTRE_ADMIN))
             fichier.write("IP_FILTRE_ADRESSES = (")
             taille = len(IP_FILTRE_ADRESSES)
             ip_filtre_adresses = ",".join("'" + ip + "'"
                                           for ip in IP_FILTRE_ADRESSES)
             if taille == 1:
                 ip_filtre_adresses += ","
             fichier.write(ip_filtre_adresses)
             fichier.write(
                 ") # si IP_FILTER_ADMIN vaut True, liste des IPS autorisées pour l'utilisateur admin (REGEXP)\n"
             )
             fichier.write(
                 "GESTION_ADMIN_BDD = {} # autorise l'admin a effectuter des opérations sur la BDD (nettoyage entre 2 années + backup/restore)\n"
                 .format(GESTION_ADMIN_BDD))
             fichier.write(
                 "DB_ENGINE = '{}' # base de données (mysql ou postgresql ou sqlite3)\n"
                 .format(BDD))
             fichier.write(
                 "DB_USER = '******' # nom de l'utilisateur qui a les droits sur la base de données\n"
                 .format(db['USER']))
             fichier.write(
                 "DB_NAME = '{}' # nom de la base de données (ou du fichier .db pour SQLite)\n"
                 .format(db['NAME']))
             fichier.write(
                 "DB_PASSWORD = '******' # mot de passe pour se connecter à la base de données\n"
                 .format(db['PASSWORD']))
             fichier.write(
                 "DB_HOST = '{}' # adresse locale de la base de données\n".
                 format(db['HOST']))
             fichier.write(
                 "DB_PORT = '{}' # port de la BDD, vide par défaut. À renseigner si la BDD se trouve sur un port particulier\n"
                 .format(db['PORT']))
             fichier.write(
                 "IMAGEMAGICK = {} # utilisation de ImageMagick pour faire des miniatures de la première page des pdf programmes de colle\n"
                 .format(IMAGEMAGICK))
             fichier.write(
                 "ALLOWED_HOSTS = {} # liste des noms de domaine autorisés pour accéder à e-colle\n"
                 .format(ALLOWED_HOSTS))
             fichier.write(
                 "INTERNAL_IPS = {} # liste des IP autorisées pour accéder en interne à e-colle quand debug est True\n"
                 .format(INTERNAL_IPS))
             fichier.write(
                 "SECRET_KEY = '{}' # clé secrète aléatoire de 50 caractères\n"
                 .format(SECRET_KEY))
             fichier.write(
                 "TIME_ZONE = '{}' # fuseau horaire\n".format(TIME_ZONE))
             fichier.write(
                 "HEURE_DEBUT = {} # heure de début des colles (en minutes depuis minuit)\n"
                 .format(HEURE_DEBUT))
             fichier.write(
                 "HEURE_FIN = {} # heure de fin des colles (en minutes depuis minuit)\n"
                 .format(HEURE_FIN))
             fichier.write(
                 "INTERVALLE = {} # intervalle entre 2 créneaux (en minutes)"
                 .format(INTERVALLE))
         self.stdout.write("copie terminée")
         self.stdout.write(
             "sauvegarde de la base de données pour avoir un point de sauvegarde en cas d'échec de la mise à jour"
         )
         try:
             backup = Backup()
             backup.handle(backup_media=False, **options)
         except Exception as e:
             self.stdout.write(
                 "Échec de la sauvegarde de la base de données:")
             self.stdout.write(str(e))
             self.stdout.write(
                 "La sauvegarde a échoué, voulez-vous poursuivre?")
             poursuite = input(
                 "Attention si la mise à jour échoue vous risquez de ne pas pouvoir revenir en arrière (o/N)"
             )
             if poursuite != "" and poursuite in "oO":
                 poursuite = True
             else:
                 poursuite = False
         else:
             poursuite = True
         if poursuite:  # si la sauvegarde de la base de données a réussi ou si on s'en passe, on met à jour la migration
             self.stdout.write(
                 "Mise à jour de la structure de la base de données")
             chemin = os.path.join("..", "e-colle-new", "manage.py")
             subprocess.run(["python3", chemin, "migrate"])
             # on copie les fichiers media/backup:
             self.stdout.write("copie des fichiers media/backup")
             repertoires = ['programme', 'image', 'photos']
             for rep in repertoires:
                 source = os.path.join("media", rep)
                 target = os.path.join("..", "e-colle-new", "media", rep)
                 for file in os.listdir(source):
                     filecopy(os.path.join(source, file), target)
             source = "backup"
             target = os.path.join("..", "e-colle-new", "backup")
             for file in os.listdir(source):
                 filecopy(os.path.join(source, file), target)
             # on renomme e-colle-bak l'ancien réperoire et e-colle le nouveau
             os.rename(os.path.join("..", "e-colle"),
                       os.path.join("..", "e-colle-bak"))
             os.rename(os.path.join("..", "e-colle-new"),
                       os.path.join("..", "e-colle"))
     except Exception as e:
         self.stdout.write(str(e))
         self.stdout.write(
             "la mise à jour n'a pas pu aller jusqu'au bout. Si la migration a eu lieu,\n\
             et que e-colle ne fonctionne plus à cause de la base de données\n\
             il est recommandé d'effacer le répertoire 'e-colle',\n\
             renommer 'e-colle' le répertoire 'e-colle-bak', effacer la base de données,\n\
             la recréer et d'utiliser les commandes migrate et restore.")
     else:
         self.stdout.write("la mise a jour a été effectuée avec succès.\n\
             l'ancien répertoire e-colle s'appelle désormais e-colle-bak\n\
             Si jamais ça ne fonctionne pas, vous pouvez revenir à l'état précédent\n\
             en effaçant le répertoire 'e-colle', renommant 'e-colle' le répertoire 'e-colle-bak'\n\
             effaçant la base de données, la recréer et utiliser les commandes migrate et restore\n\
             Pour que les modifications soient prises en compte en production,\n\
             il faut redémarrer le logiciel serveur.")
     finally:
         self.stdout.write("nettoyage")
         self.clean()
Exemplo n.º 13
0
    array1 = get_pic('image1.jpg')
    while True:
        # start = time() # Used for measuring processing time.

        # Get second image for comparison:
        camera.capture('image2.jpg')
        array2 = get_pic('image2.jpg')

        # Subtract rgb values (numpy arrays make this easy; standard arrays
        # don't allow for pairwise subtraction and iterating abs() over the
        # result like this):
        diff = abs(array2-array1)

        # If a bird was found, save image and increment image number.
        if count_pixels(diff) > BIRD_SIZE::
            filecopy('image2.jpg', 'bird{}.jpg'.format((str(n).zfill(4))))
            n += 1 

        # Transfer image2 to image1 to prepare for the next comparison:
        rename('image2.jpg', 'image1.jpg')
        array1 = array2

        # print(time()-start) # Print processing time.

        # Pause before taking next photo:
        sleep(DELAY)
except KeyboardInterrupt:
    # Use CTRL + C to stop photographing.
    print('Canceled.')
finally:
    # Camera preview is full screen, so we need to shut it off
from meresco.components import readConfig

from seecr.test.integrationtestcase import IntegrationState
from seecr.test.utils import getRequest, postRequest, postMultipartForm
from seecr.test.portnumbergenerator import PortNumberGenerator

from oas.utils import parseHeaders
from oas.namespaces import xpath

mydir = dirname(abspath(__file__))
projectDir = dirname(dirname(mydir))
documentationDir = join(projectDir, 'doc')
defaultSolrDataDir = join(documentationDir, 'solr-data')
docExampleScriptPath = join(documentationDir, 'public', 'example_client.py')
myExampleScriptPath = join(mydir, 'example_client.py')
filecopy(docExampleScriptPath, myExampleScriptPath)
from example_client import upload

class OasIntegrationState(IntegrationState):

    def __init__(self, stateName, tests=None, fastMode=False):
        IntegrationState.__init__(self, stateName, tests=tests, fastMode=fastMode)
        self.testdataDir = join(dirname(mydir), 'data/integration')
        stateDataDir = join(dirname(mydir), 'data', stateName)
        if isdir(stateDataDir):
            self.testdataDir = stateDataDir

        self.solrDataDir = join(self.integrationTempdir, "solr")
        self.owlimDataDir = join(self.integrationTempdir, "owlim")
        self.httpDataDir = join(mydir, "httpdata")
        system('mkdir --parents ' + self.solrDataDir)