def parse_arguments(): """Get all arguments as a dict object""" custom_config = config.read() arguments = docopt(__doc__, version='Montanus %s' % __version__) logger.debug(custom_config) conf_file = arguments.get('--with-conf') if conf_file is not None: conf_config = config.read(conf_file) for (k, v) in conf_config.items(): if v is not None: custom_config[k] = v logger.debug(arguments) command_config = { 'templates_path': arguments.get('<templates_path>'), 'static_files_path': arguments.get('--with-static-files-path') \ if arguments.get('-with-static-files-path') is not None \ else arguments.get('<templates_path>'), 'delete_source': arguments.get('--delete'), 'protocol': arguments.get('--with-protocol'), 'domains': arguments.get('--with-domains').split(',') \ if arguments.get('--with-domains') is not None \ else None, 'md5_len': int(arguments.get('--with-md5-len')), 'md5_concat_by': arguments.get('--with-md5-concat-by') } logger.debug(command_config) for (k, v) in command_config.items(): if v is not None: custom_config[k] = v logger.debug(custom_config) return DictWrapper(custom_config)
def read_config_fill_queue(): from glob import glob from os import chdir, getcwd from os.path import realpath global config # restore the current directory at the end of the function prev_dir = getcwd() chdir(config["config_path"]) path_program_dict = {} for config_path in glob("*.conf"): config = configparser.ConfigParser() config.read(config_path) section = config.sections()[0] kwargs = dict(config[section]) kwargs["name"] = section try: prog_path = realpath(config[section]["path"]) del kwargs["path"] except KeyError: logging.error("%s is missing the path configuartion key", config_path) continue if prog_path in path_program_dict: logging.warn("%s in %s has already been referenced by %s", prog_path, config_path, path_program_dict[prog_path].config_document) else: prog = Program(prog_path, **kwargs) path_program_dict[prog.path] = prog heappush(priority_queue, prog) chdir(prev_dir)
def runVdsm(baseDir="/usr/share/vdsm/", configFilePath="/etc/vdsm/vdsm.conf", loggerConfigurationPath='/etc/vdsm/logger.conf'): """ Starts a VDSM instance in a new thread and returns a tuple ``(ClientIF, Thread Running VDSM)`` """ if pwd.getpwuid(os.geteuid())[0] != "vdsm": raise Exception("You can't run vdsm with any user other then 'vdsm'.") sys.path.append(baseDir) from config import config from logging import config as lconfig import clientIF loggerConfFile = loggerConfigurationPath lconfig.fileConfig(loggerConfFile) log = logging.getLogger('vds') config.read(configFilePath) cif = clientIF.clientIF(log) t = threading.Thread(target = cif.serve) t.setDaemon(True) t.start() return (cif, t)
def main(): configfile = None opts, args = getopt.getopt(sys.argv[1:], 'C:h', ['help']) for opt, val in opts: if opt == '-C': configfile = val elif opt in ['-h', '--help']: usage() else: print("unknown option:", opt, file=sys.stderr) usage() config.read(configfile) wave.check_wavesdir() if args == []: action = lambda: Pmpd().run_in_foreground() elif args == ['start']: action = lambda: Pmpd().start() elif args == ['stop']: action = lambda: Pmpd().stop() elif args == ['restart']: action = lambda: Pmpd().restart() elif args[0] == 'run': action = lambda: Pmpd().run_wave(args[1]) else: print("unknown command:", args[0], file=sys.stderr) usage() action() return 0
def testWriteProperty(self): """testWriteProperty: set a property, write config file, then read it back""" set_value = '45' settings = {} settings['image_size_x'] = set_value config.store(settings) config.read() read_value = config.settings['image_size_x'] self.assertEqual(set_value, read_value)
def __init__(self): config.read('configuracion.conf') endpoint = config.get('default', 'confi_odoo') self.db = config.get(endpoint, 'db') self.username = config.get(endpoint, 'user') self.password = config.get(endpoint, 'password') url = config.get(endpoint, 'url') common = xmlrpclib.ServerProxy('http://{}/xmlrpc/2/common'.format(url), allow_none=True) self.uid = common.authenticate(self.db, self.username, self.password, {}) self.models = xmlrpclib.ServerProxy( 'http://{}/xmlrpc/2/object'.format(url), allow_none=True)
def main(): print 'pwserverd starting' # Parse the arguments parser = OptionParser() parser.add_option("-c", "--config", dest="config_file", default="/etc/pwserverd.cfg", help="use the specified configuration file") (options, args) = parser.parse_args() # Read the configuration file config.read([options.config_file]) # Set things up factory = PasswordProtocolFactory() listeners = [l.strip() for l in config.get('main', 'listeners').split(',')] for listener in listeners: ltype = config.get(listener, 'type').strip().upper() if ltype == 'TCP': port = config.getint(listener, 'port') interface = '127.0.0.1' if config.has_option(listener, 'interface'): interface = config.get(listener, 'interface') print 'listening on interface %s port %s' % (interface, port) reactor.listenTCP(port, factory, interface=interface) elif ltype == 'UNIX': mode = 0644 if config.has_option(listener, 'mode'): mode = int(config.get(listener, 'mode'), 0) socket = config.get(listener, 'socket') wantpid = True if config.has_option(listener, 'wantPID'): wantpid = config.getboolean(listener, 'wantPID') print 'listening on socket %s' % socket reactor.listenUNIX(socket, factory, mode=mode, wantPID=wantpid) else: print 'unknown listener type %s for listener %s' % (ltype, listener) reactor.run()
def main(basepath=None): if basepath == None: if (len(sys.argv) == 2): basepath = sys.argv[1] else: print "Must supply basedir of gallery" return False # sys.exit(1) config.read() gallery = Gallery(basepath) if gallery.scanDirs(): gallery.deleteIndex() gallery.createAlbums() log("Done.")
def initForms(self): settings = config.read() self.image_size_x.SetValue(int(settings['image_size_x'])) self.image_size_y.SetValue(int(settings['image_size_y'])) self.thumbnail_size_x.SetValue(int(settings['thumbnail_size_x'])) self.thumbnail_size_y.SetValue(int(settings['thumbnail_size_y'])) self.image_quality.SetValue(int(settings['image_quality'])) self.thumbnail_quality.SetValue(int(settings['thumbnail_quality'])) self.album_cols.SetValue(int(settings['album_cols'])) self.album_rows.SetValue(int(settings['album_rows'])) self.gallery_path.SetValue(settings['gallery_path']) self.image_extensions.SetValue(settings['image_extensions']) self.thumbnail_suffix.SetValue(settings['thumbnail_suffix']) self.tmp_first.SetValue(settings['tmp_first']) self.tmp_prev.SetValue(settings['tmp_prev']) self.tmp_index.SetValue(settings['tmp_index']) self.tmp_next.SetValue(settings['tmp_next']) self.tmp_last.SetValue(settings['tmp_last']) self.rebuild_thumbnails.SetValue(settings['rebuild_thumbnails'])
def flush(cls, release_type, release_version): if release_type == None and release_version == None: settings = config.read() settings['first_run'] = True config.write(settings) if release_type != None: if release_version != None: release_info_dict = releases.getInfo(release_type, release_version) release_plist_name = utilities.createcachefilename(release_info_dict['prefix'], release_info_dict['version']) cached_file_path = utilities.getcachefile(release_plist_name) if os.path.exists(cached_file_path) == True: logging_helper.getLogger().info('Removing version manifest ('+release_plist_name+')...') manager.RemovePackageManifest(cached_file_path) else: type_versions = versions.get(release_type) for version in type_versions: release_version_info = releases.getInfo(release_type, version) cls.flush(release_type, release_version_info['name']) else: types = releases.get() for type_name in types: cls.flush(type_name, None)
def main(): """ Usage: register-to-engine.py [-f | --force] [-p PORT | --port PORT] OVIRT_ENGINE """ port = None force = False try: opts, args = getopt.getopt(sys.argv[1:], "hfp:", ["help", "force", "port="]) if len(args) != 1: usage() sys.exit(USAGE_ERROR) newVdcHostName = args[0] for o, v in opts: if o in ("-h", "--help"): usage() sys.exit(SUCCESS) elif o in ("-p", "--port"): try: port = int(v) except ValueError: sys.stderr.write('invalid port: %s\n' % v) sys.exit(INVALID_PORT_ERROR) elif o in ("-f", "--force"): force = True except getopt.GetoptError as e: sys.stderr.write("ERROR: %s\n" % (e.msg)) usage() sys.exit(USAGE_ERROR) config.read(VDSM_REG_CONF_FILE) if not port: try: port = config.get('vars', 'vdc_host_port') except ConfigParser.NoOptionError: sys.stderr.write("Failed to retrieve port number " "from config file: %s\n" % VDSM_REG_CONF_FILE) sys.exit(CONF_FILE_READ_ERROR) try: vdcHostName = config.get('vars', 'vdc_host_name') except ConfigParser.NoOptionError: vdcHostName = None if not force and vdcHostName and "NONE" != vdcHostName.upper(): sys.stdout.write('Node already configured to Engine %s\n' % vdcHostName) sys.stdout.write('Do you want to reset and use %s (yes/NO): ' % newVdcHostName) ans = sys.stdin.readline() if "YES" != ans.strip().upper(): sys.exit(0) if not isHostReachable(newVdcHostName, port): if not isHostReachable(newVdcHostName, port, ssl=False): sys.stderr.write('Engine %s ' % newVdcHostName + ' is not reachable by HTTP or HTTPS\n') sys.exit(OVIRT_ENGINE_NOT_REACHABLE_ERROR) if not deployUtil.setVdsConf("vdc_host_name=%s" % newVdcHostName, VDSM_REG_CONF_FILE): sys.exit(CONF_FILE_WRITE_ERROR) if not deployUtil.setVdsConf("vdc_host_port=%s" % port, VDSM_REG_CONF_FILE): sys.exit(CONF_FILE_WRITE_ERROR) out, err, rv = deployUtil.setService("vdsm-reg", "restart") if rv != 0: sys.stderr.write("Failed to restart vdsm-reg service: ") sys.stderr.write("(%s, %s, %s)\n" % (rv, out, err)) sys.exit(VDSM_REG_RESTART_FAILED_ERROR) sys.exit(SUCCESS)
def cfg(request): """Set config and return object.""" config.read("./tests/config.ini") config.fit_optical_density = request.param # Previously returning different results yield config
def calibrate(conf_path): config.read(conf_path) startt = time.time() calib_img_paths = sorted( glob( os.path.join( config.get('calibration').get('frames_path'), config.get('calibration').get('template')))) if config.get('calibration').get('results').get('save'): if not os.path.exists( config.get('calibration').get('results').get('path')): os.makedirs(config.get('calibration').get('results').get('path')) criteria = ( cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, config.get('calibration').get('criteria').get('corners_max_it'), config.get('calibration').get('criteria').get('corners_eps')) PATTERN = tuple(config.get('calibration').get('pattern')) objp = np.zeros((PATTERN[0] * PATTERN[1], 3), np.float32) objp[:, :2] = np.mgrid[0:PATTERN[0], 0:PATTERN[1]].T.reshape(-1, 2) objpoints = [] imgpoints = [] IMG_SIZE = None for i_f, calib_f in enumerate(calib_img_paths, start=1): print '[{}] [INFO] Processing frame \'{}\'..'.format( time.strftime("%H:%M:%S"), os.path.basename(calib_f)) break_flag = False for el in config.get('calibration').get('excluded'): if str(el) in os.path.basename(calib_f): print '[{}] [INFO] Frame is in excluded list. Ignoring.'.format( time.strftime("%H:%M:%S")) break_flag = True break if break_flag: continue tmp_start = time.time() img = cv2.imread(calib_f) if IMG_SIZE is None: IMG_SIZE = img.shape[:2][::-1] else: if img.shape[:2][::-1] != IMG_SIZE: print '[{}] [WARNING] Image shape is inconsistent!'.format( time.strftime("%H:%M:%S")) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, corners = cv2.findChessboardCorners(gray, PATTERN, None) if ret == True: objpoints.append(objp) cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria) imgpoints.append(corners) if config.get('calibration').get('results').get('save'): cv2.drawChessboardCorners(img, PATTERN, corners, True) cv2.imwrite( os.path.join( config.get('calibration').get('results').get('path'), os.path.basename(calib_f)), img) print '[{}] [INFO] Frame processed in {} sec.'.format( time.strftime("%H:%M:%S"), time.time() - tmp_start) criteria = ( cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, config.get('calibration').get('criteria').get('cam_mtx_max_it'), config.get('calibration').get('criteria').get('cam_mtx_eps')) print '[{}] [INFO] Calculating camera matrix..'.format( time.strftime("%H:%M:%S")) _, camera_mtx, dist, rvecs, tvecs = cv2.calibrateCamera( objpoints, imgpoints, IMG_SIZE, None, None, None, None, 0, criteria) err_sum = 0.0 for i in xrange(len(objpoints)): imgpts, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], camera_mtx, dist) err_sum += cv2.norm(imgpoints[i], imgpts, cv2.NORM_L2) / len(imgpts) print '[{}] [INFO] Re-projection error: {}'.format( time.strftime("%H:%M:%S"), err_sum / len(objpoints)) print '[{}] [INFO] Calculating new camera matrix..'.format( time.strftime("%H:%M:%S")) camera_mtx_new, _ = cv2.getOptimalNewCameraMatrix( camera_mtx, dist, IMG_SIZE, 0.8, IMG_SIZE, centerPrincipalPoint=True) res = {'cmtx': camera_mtx, 'cmtx_new': camera_mtx_new, 'dist': dist} np.save( os.path.join('calibrations', config.get('calibration').get('out_name')), res) print '[{}] [INFO] Calibration done in {} sec. Resluts saved in \'calibrations/{}.npy\''.format( time.strftime("%H:%M:%S"), time.time() - startt, config.get('calibration').get('out_name'))
#!/usr/bin/env python # -*- coding: utf-8 -*- from bot import Bot import logging from config import config # Create config object '''config = ConfigParser.ConfigParser() config.optionxform = str config.read('config.ini')''' # Enable logging logging.basicConfig(format='[%(asctime)s] [%(levelname)s] [ %(name)s ] - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) def main(): print config bot = Bot(name=config['name']) # Run the bot thread bot.run() if __name__ == '__main__':
def main_func(): global cfggui # TODO: still needed? Set the rlimits # resource.setrlimit(resource.RLIMIT_DATA, (2*1024*1024, resource.RLIM_INFINITY)) # Set some defaults here. configfile = consts.CFGFILE logfile = None logext = False logloc = False withgui = True cfggui = False try: opts, _ = getopt(argv[1:], "hv", [ "help", "config=", "logfile=", "logext", "logloc", "no-gui", "cfg-gui" ]) except GetoptError as err: # print help information and exit: errmsg = str( err) # will print something like "option -a not recognized" print(errmsg) console.info(errmsg) usage() exit(2) for o, a in opts: if o == "--config": configfile = a elif o in ["-?", "-h", "--help"]: usage() exit(2) elif o == "--no-gui": log.debug("gui disabled.") withgui = False elif o == "--cfg-gui": cfggui = True elif o == '--logfile': logfile = a elif o == "--logext": logext = True elif o == "--logloc": logloc = True elif o == '-v': showversion() exit() else: assert False, "unhandled option" logging.basicConfig( format= "%(asctime)s.%(msecs).3d:%(thread)d:%(levelname)s:%(name)s:%(message)s", datefmt="%d.%m.%Y %H:%M:%S", level=logging.DEBUG, filename=logfile) # maxBytes=1024*1024, backupCount=7) #config defaults infstr = "" try: config.read([configfile]) except: # find a valid config logerrorexception() cfggui = True infstr = "invalid configfile" os.unlink(configfile) if os.path.isfile(consts.CFGFILEBAK) and os.path.getsize( consts.CFGFILEBAK): os.system("cp %s %s" % (consts.CFGFILEBAK, consts.CFGFILE)) infstr += ", restored from %s" % (consts.CFGFILEBAK) else: os.system("cp %s %s" % (consts.CFGFILEFACTORY, consts.CFGFILE)) infstr += ", restored from %s" % (consts.CFGFILEFACTORY) # try again - or fail config.read([configfile]) if logext: config.set(consts.SECTION, consts.LOGEXT, "True") if logloc: config.set(consts.SECTION, consts.LOGLOC, "True") infomsg("loading RTP subsystem") loadmodule("rtp") if withgui or cfggui: infomsg("loading GUI subsystem") loadmodule("gui") if cfggui: cfg_main(infstr) else: try: app_main(withgui) except ZsiposException as e: if withgui: cfg_main(str(exc_info()[1])) else: raise e
# Contact vdsm running on localhost over xmlrpc (possibly over ssl) # # Dan Kenigsberg <*****@*****.**> import xmlrpclib import subprocess import sys VDSM_DIR = '/usr/share/vdsm' VDSM_CONF = '/etc/vdsm/vdsm.conf' try: sys.path.append(VDSM_DIR) from config import config sys.path.pop() config.read(VDSM_CONF) except: # VDSM not available raise ImportError('local vdsm not found'), None, sys.exc_info()[2] def getTrustStorePath(): tsPath = None if config.getboolean('vars', 'ssl'): tsPath = config.get('vars', 'trust_store_path') return tsPath def getLocalVdsName(tsPath): p = subprocess.Popen(['/usr/bin/openssl', 'x509', '-noout', '-subject', '-in', '%s/certs/vdsmcert.pem' % tsPath], stdout=subprocess.PIPE, close_fds=True) out, err = p.communicate()
f_desde = f_hasta - timedelta(hours=12) else: f_desde = ultimo_update[0] f_hasta = datetime.utcnow() - timedelta(hours=3) db.SetDatos([f_hasta], 0) ##################################################################### #Para usar en produccion fi = f_desde.strftime('%Y-%m-%d %H:%M:%S') ff = f_hasta.strftime('%Y-%m-%d %H:%M:%S') #Para usar en modo test #fi = '2019-01-01 01:10:11' #ff = '2019-01-01 22:10:11' ##################################################################### config.read(path_config) endpoint = config.get('default', 'confi_chasqui') conection = {} conection['host'] = config.get(endpoint, 'url') conection['port'] = config.get(endpoint, 'puerto') idvendedor = config.get(endpoint, 'idvendedor') mw = Adapter_Chasqui(conection) param = {} param['email'] = config.get(endpoint, 'email') param['password'] = config.get(endpoint, 'password') ret_token = Login(mw, param, debug) if ret_token != -1: if Syncro(mw, 'start', idvendedor, ret_token, debug): CrearPedidos(mw, fi, ff, idvendedor, ret_token, debug)
for exposure in range(exposure_low, exposure_high, increment): # Set new exposure newExposure = ueye.DOUBLE(exposure) ret = ueye.is_Exposure(cam.handle(), ueye.IS_EXPOSURE_CMD_SET_EXPOSURE, newExposure, ueye.sizeof(newExposure)) time.sleep(0.05) img = ImageFunctions.capture_image(cam=cam, gripper_height=500) puck_list = QR_Scanner(img) print(puck_list) # Checking exposure d = ueye.DOUBLE() retVal = ueye.is_Exposure(cam.handle(), ueye.IS_EXPOSURE_CMD_GET_EXPOSURE, d, 8) if retVal == ueye.IS_SUCCESS: print('Currently set exposure time %8.3f ms' % d) # Position returns as None if no QR-code is found if puck_list: exposure_values.append(exposure) exposure = str(median(exposure_values)) config = configparser.ConfigParser() config.read('cam_adjustments.ini') cfgfile = open('cam_adjustments.ini', 'w') # Updating the value for exposure config.set('EXPOSURE', 'exposure', exposure) config.write(cfgfile) cfgfile.close()
parser.error("file {0} found and will not overwrite, try --force".format(outfile)) print('Inputs Valid') #============================================================================== # deal with the filetype options #============================================================================== try: tp = determineFileType(infile) except (ValueError, NotImplementedError): # could not determine the type, die parser.error("Could not determine the file type and flag not given: {0}".format(infile)) print('Determined input file type to be: {0}'.format(tp)) if tp == 'configfile': d = config.read(infile) elif tp == 'mbpfile': d = burst.read(infile) elif tp == 'contextfile': d = context.read(infile) elif tp == 'hiresfile': d = hires.read(infile) elif tp == 'datatimes': d = datatimes.read(infile) else: raise(ValueError()) if options.force and os.path.isfile(os.path.expanduser(outfile)): os.remove(outfile) d.write(outfile, hdf5=options.hdf5)
def main(conf_path): config.read(conf_path) video = cv2.VideoCapture(config.get('app').get('source')) if config.get('app').get('frames').get('save'): if not os.path.exists(config.get('app').get('frames').get('path')): os.makedirs(config.get('app').get('frames').get('path')) if config.get('app').get('fd').get('save'): if not os.path.exists(config.get('app').get('fd').get('path')): os.makedirs(config.get('app').get('fd').get('path')) predictor_age = None predictor_gender = None if config.get('app').get('age').get('enable'): if config.get('app').get('age').get('type') == 'Rothe': from descriptors.Rothe_age import predictor predictor_age = predictor(config) elif config.get('app').get('age').get('type') == 'Levi': from descriptors.Levi_age import predictor predictor_age = predictor(config) if config.get('app').get('gender').get('enable'): if config.get('app').get('gender').get('type') == 'Rothe': from descriptors.Rothe_gender import predictor predictor_gender = predictor(config) elif config.get('app').get('gender').get('type') == 'Levi': from descriptors.Levi_gender import predictor predictor_gender = predictor(config) if config.get('app').get('undistortion').get('enabled'): calibrations = np.load( config.get('app').get('undistortion').get('calibs'))[()] detector = dlib.get_frontal_face_detector() frames_counter = 1 cv2.namedWindow('stream', cv2.WINDOW_NORMAL) try: while True: ret, frame = video.read() if not ret: print '[{}] [INFO] No more frames. Exiting.'.format( time.strftime("%H:%M:%S")) break print '[{}] [INFO] Processing frame #{}..'.format( time.strftime("%H:%M:%S"), frames_counter) if config.get('app').get('undistortion').get('enabled'): if config.get('app').get('undistortion').get('method') == 1: frame = undist_1(frame, calibrations['cmtx'], calibrations['dist']) elif config.get('app').get('undistortion').get('method') == 2: frame = undist_1(frame, calibrations['cmtx'], calibrations['dist'], calibrations['cmtx_new']) elif config.get('app').get('undistortion').get('method') == 3: frame = undist_2(frame, calibrations['cmtx'], calibrations['dist'], calibrations['cmtx_new']) else: print '[{}] [WARNING] Illegal undistortion method chosen. Leaving frame as is.'.format( time.strftime("%H:%M:%S")) if config.get('app').get('frames').get('save'): cv2.imwrite( os.path.join( config.get('app').get('frames').get('path'), str(frames_counter).zfill(5) + '.png'), frame) if config.get('app').get('downsample').get('enable'): msize = tuple( config.get('app').get('downsample').get('max_size')) if frame.shape[0] * frame.shape[1] > msize[0] * msize[1]: frame = cv2.resize(frame, msize) start = time.time() if config.get('app').get('fd').get('upsample'): dets = detector(frame, 1) else: dets = detector(frame) end = time.time() print '[{}] [INFO] {} faces detected (took {} sec.)'.format( time.strftime("%H:%M:%S"), len(dets), end - start) bboxes = [] for i_d, d in enumerate(dets, start=1): print '[{}] [INFO] Processing face #{}'.format( time.strftime("%H:%M:%S"), i_d) face = frame[d.top():d.bottom(), d.left():d.right(), :] if config.get('app').get('fd').get('save'): cv2.imwrite( os.path.join( config.get('app').get('fd').get('path'), 'frame{}_face{}.png'.format( str(frames_counter).zfill(5), str(i_d).zfill(2))), face) cv2.rectangle(frame, (d.left(), d.top()), (d.right(), d.bottom()), (0, 255, 0), 3) txt = [] if config.get('app').get('gender').get('enable'): print '[{}] [INFO] gender identification..'.format( time.strftime("%H:%M:%S")) gender, t = predictor_gender.predict( frame, (d.top(), d.bottom(), d.left(), d.right())) print '[{}] [INFO] Gender: {} (took {} sec.)'.format( time.strftime("%H:%M:%S"), gender, t) txt.append(str(gender)) if config.get('app').get('age').get('enable'): print '[{}] [INFO] age identification..'.format( time.strftime("%H:%M:%S")) age, t = predictor_age.predict( frame, (d.top(), d.bottom(), d.left(), d.right())) print '[{}] [INFO] Age: {} (took {} sec.)'.format( time.strftime("%H:%M:%S"), age, t) txt.append(str(age)) cv2.putText(frame, ','.join(txt), (d.left(), d.top()), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2) cv2.imshow('stream', frame) cv2.waitKey(500) frames_counter += 1 except KeyboardInterrupt: print '[{}] [INFO] Interrupted. Exiting.'.format( time.strftime("%H:%M:%S")) cv2.destroyAllWindows() exit()
except ImportError: # python3 import xmlrpc.client as xmlrpclib import subprocess import sys from spacewalk.common.usix import raise_with_tb VDSM_DIR = '/usr/share/vdsm' VDSM_CONF = '/etc/vdsm/vdsm.conf' try: sys.path.append(VDSM_DIR) from config import config sys.path.pop() config.read(VDSM_CONF) except: # VDSM not available raise_with_tb(ImportError('local vdsm not found'), sys.exc_info()[2]) def getTrustStorePath(): tsPath = None if config.getboolean('vars', 'ssl'): tsPath = config.get('vars', 'trust_store_path') return tsPath def getLocalVdsName(tsPath): p = subprocess.Popen([ '/usr/bin/openssl', 'x509', '-noout', '-subject', '-in',
import enum from sqlalchemy import Column, String, Integer, create_engine from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy.ext.declarative import declarative_base from config import config config.read() base = declarative_base() def create_session(user, password, host, database_name): engine = create_engine("mysql+mysqlconnector://{}:{}@{}:3306/{}".format(user, password, host, database_name)) se = sessionmaker(bind=engine, autocommit=True) # https://farer.org/2017/10/28/sqlalchemy_scoped_session session = scoped_session(se) return session @enum.unique class status(enum.IntEnum): new, downloaded, uploaded, error = range(1, 5) class channel(base): __tablename__ = "channel" id = Column(Integer, primary_key=True) name = Column(String(255)) url = Column(String(255)) class task(base): __tablename__ = "tasks" id = Column(String(255), primary_key=True)
def main(argv=None): "Starting point for skeinforge engine." parser = argparse.ArgumentParser(description='Skeins a 3D model into slicedModel.') parser.add_argument('file', help='The file to skein. Files accepted: stl, obj, gts, and svg. Or sliced model files produced by SkeinforgeEngine.') parser.add_argument('-c', metavar='config', help='Configuration for skeinforge engine.', default='skeinforge_engine.cfg') parser.add_argument('-p', metavar='profile', help='Profile for the skeining.') parser.add_argument('-o', metavar='output', help='Output filename. Overrides other export filename settings.') parser.add_argument('-r', metavar='reprocess', help='Comma seperated list of plugins to reprocess a sliced model file. The export plugin is automatically appended.') if argv is None: argv = sys.argv[1:] args = parser.parse_args(argv) if args.c == None: logger.error('Invalid or missing configuration file.') return config.read(args.c) logLevel = config.get('general', 'log.level') logging.basicConfig(level=logLevel, format='%(asctime)s %(levelname)s (%(name)s) %(message)s') defaultProfile = config.get('general', 'default.profile') if defaultProfile != None: config.read(defaultProfile) profileName = config.get('profile', 'name') if args.p != None: config.read(args.p) if profileName == 'default': profileName = os.path.splitext(os.path.basename(args.p))[0] logger.info("Profile: %s", profileName) inputFilename = args.file if not os.path.isfile(inputFilename): logger.error('File not found: %s', inputFilename) return logger.info("Processing file: %s", os.path.basename(inputFilename)) exportedSlicedModelExtension = config.get('export', 'export.slicedmodel.extension') if inputFilename.endswith(exportedSlicedModelExtension): slicedModel = pickle.load(open(inputFilename)) slicedModel.runtimeParameters = RuntimeParameters() inputFilename = inputFilename.replace('.'+exportedSlicedModelExtension, '') else: slicedModel = SlicedModel() if args.o != None: slicedModel.runtimeParameters.outputFilename = args.o if args.r != None: pluginSequence = args.r.split(',') if 'export' not in pluginSequence: pluginSequence.append('export') else: pluginSequence = config.get('general', 'plugin.sequence').split(',') if inputFilename.endswith(exportedSlicedModelExtension) and 'carve' in pluginSequence: logger.error('Reprocessing a sliced model file with carve is not possible. Please process the original file or choose a different reprocessing sequence.') return logger.debug("Plugin Sequence: %s", pluginSequence) if slicedModel.runtimeParameters.profileMemory: memory_tracker.track_object(slicedModel) memory_tracker.create_snapshot('Start') slicedModel.runtimeParameters.profileName = profileName slicedModel.runtimeParameters.inputFilename = inputFilename getCraftedTextFromPlugins(pluginSequence[:], slicedModel) slicedModel.runtimeParameters.endTime = time.time() logger.info('It took %s seconds to complete.', timedelta(seconds=slicedModel.runtimeParameters.endTime - slicedModel.runtimeParameters.startTime).total_seconds()) if slicedModel.runtimeParameters.profileMemory: memory_tracker.create_snapshot('End') if config.getboolean('general', 'profile.memory.print.summary'): memory_tracker.tracker.stats.print_summary() if config.getboolean('general', 'profile.memory.export.data'): memory_tracker.tracker.stats.dump_stats('%s.memory_tracker.dat' % inputFilename) if config.getboolean('general', 'profile.memory.export.html'): from pympler.classtracker_stats import HtmlStats HtmlStats(tracker=memory_tracker.tracker).create_html('%s.memory_tracker.html' % inputFilename) return slicedModel