def do_GET(self): log = self.server.log log.debug("GET from %s:%d" % self.client_address) log.debug("Request: %s" % self.path) urlparts = urlparse.urlsplit(self.path) query = urlparse.parse_qs(urlparts.query) if urlparts.path in ('/boot', '/linux'): if 'uuid' in query: uuids = query['uuid'] for uuid in uuids: uuid = uuid.upper().strip() authorized = self.server.uuids.get(uuid, False) log.info( 'UUID %s is %s' % (uuid, authorized and 'authorized' or 'rejected')) if authorized: break else: authorized = False log.warn('Request does not specify a UUID') if authorized: response = '\n\n' # HTTP protocol, line feed after headers # dummy generation of a tester number tester = sum([to_int('0x%s' % x) for x in uuid.split('-')]) clientname = 'Tester-%03d' % (tester & 0xFF) log.info("UUID %s is assigned as %s" % (uuid, clientname)) response += 'Client: %s\n' % clientname filename = 'define_filename_here' if urlparts.path == '/linux': response += 'File: %s\n' % filename self.send_response(200, 'Ok') self.wfile.write(response) return self.send_error(401, 'Not authorized') return
def do_GET(self): log = self.server.log log.debug("GET from %s:%d" % self.client_address) log.debug("Request: %s" % self.path) urlparts = urlparse.urlsplit(self.path) query = urlparse.parse_qs(urlparts.query) if urlparts.path in ('/boot', '/linux'): if 'uuid' in query: uuids = query['uuid'] for uuid in uuids: uuid = uuid.upper().strip() authorized = self.server.uuids.get(uuid, False) log.info('UUID %s is %s' % ( uuid, authorized and 'authorized' or 'rejected')) if authorized: break else: authorized = False log.warn('Request does not specify a UUID') if authorized: response = '\n\n' # HTTP protocol, line feed after headers # dummy generation of a tester number tester = sum([to_int('0x%s' % x) for x in uuid.split('-')]) clientname = 'Tester-%03d' % (tester & 0xFF) log.info("UUID %s is assigned as %s" % (uuid, clientname)) response += 'Client: %s\n' % clientname filename = 'define_filename_here' if urlparts.path == '/linux': response += 'File: %s\n' % filename self.send_response(200, 'Ok') self.wfile.write(response) return self.send_error(401, 'Not authorized') return
def r2_matrix_element(n, l, ml, ms, n2, l2, ml2, ms2): """ Compute the matrix element <n2 l2 | r^2 | n l>. """ # nuclear.fis.ucm.es/PDFN/documentos/Nilsson_Doct.pdf if ml != ml2 or ms != ms2 or (n - n2) % 2 != 0 or (n - n2) > 2: return 0.0 # If d were a half-integer, then we couldn't have both sigma! and (d-1-sigma)! make sense. This seems to tell me that # if N-l isn't even, the matrix element must vanish. This sort of makes sense given UCM's notation lowercase n for my d, probably # similar to hydrogen atom's n. if (n - l) % 2 != 0 or (n2 - l2) % 2 != 0: return 0.0 # Beyond this point, we don't look at ms or ms2 anymore, so all spins are integers. Only p is half-integer. d, d2, mu, nu, sigma are integers. p = 0.5 * (l + l2 + 3) mu = util.to_int(p - l2 - 0.5) nu = util.to_int(p - l - 0.5) d = util.to_int(0.5 * (n - l) + 1) # UCM's lowercase n d2 = util.to_int(0.5 * (n2 - l2) + 1) sum = 0.0 for sigma in range( max(0, d2 - mu - 1, d - nu - 1), min(d - 1, d2 - 1) + 1 ): # guess range based on criterion that all 5 inputs to factorials should be >=0 ln_term = ln_gamma(p + sigma + 1) - ( ln_fac(sigma) + ln_fac(d2 - 1 - sigma) + ln_fac(d - 1 - sigma) + ln_fac(sigma + mu - d2 + 1) + ln_fac(sigma + nu - d + 1)) term = math.exp(ln_term) sum = sum + term ln_stuff = ln_fac(d2 - 1) + ln_fac(d - 1) - (ln_gamma(d2 + l2 + 0.5) + ln_gamma(d + l + 0.5)) if mu < 0 or nu < 0: print( "negative mu or nu in r2_matrix_element -- this shoudln't happen") print("p,d,mu,nu=", p, d, mu, nu) print("n,l,ml,ms, n2,l2,ml2,ms2=", n, l, ml, ms, " ", n2, l2, ml2, ms2) ln_stuff2 = ln_fac(mu) + ln_fac(nu) result = sum * math.exp(0.5 * ln_stuff + ln_stuff2) if (d + d2) % 2 != 0: result = -result # ... Note that this is the only place where a sign can occur. The gamma function inside the sum is always # positive, because both sigma and p are nonnegative. # ECM has a (unitful?) factor of b^2, but doesn't include that factor in their sample expressions for <N|...|N+2>. # They define b as sqrt(hbar/m*omega0), so when we compute energies in units of hbar*omega0, this should not be an issue. return result
def __init__(self, protocol_name, post_interval=None): """Initializer for the class RESTThread.""" threading.Thread.__init__(self, name=protocol_name) self.setDaemon(True) self.queue = Queue.Queue() self.protocol_name = protocol_name self.post_interval = to_int(post_interval) self.lastpost = 0
def main(): if len(sys.argv) < 3: usage() print 'ERROR: min 3 arguments' exit(1) port_name = sys.argv[1] command = sys.argv[2] mae = MaestroSerial(port_name,9600) if command == 'settarget': channel = to_int(3, 0, 23, 'channel') value = to_int(4, 0, 3000, 'value') if channel == None or value == None: exit(1) mae.set_target(channel, value) elif command == 'setspeed': channel = to_int(3, 0, 23, 'channel') value = to_int(4, 0, 3000, 'value') if channel == None or value == None: exit(1) mae.set_speed(channel, value) elif command == 'setmultiple': channel = to_int(3, 0, 23, 'channel') value1 = to_int(4, 0, 3000, 'value1') value2 = to_int(5, 0, 3000, 'value2') value3 = to_int(6, 0, 3000, 'value3') mae.set_multiple(channel,(value1,value2,value3)) pass elif command == 'getposition': channel = to_int(3, 0, 23, 'channel') if channel == None: exit(1) res = mae.get_position(channel) print res elif command == 'getmoving': res = mae.get_moving() print res else: usage() print "ERROR: Unknown command" return
def set(self, cursor=None, facebook_id=None, user_id=None, venue_id=None, name=None, address=None, country=None, phone=None, email=None, email_verified=None, category_id=None, headline=None, tonight=None, website=None, facebook=None, twitter=None, v_facebook_id=None, twitter_id=None, twitter_token=None, twitter_secret=None, lat=None, lon=None, official=None, verified=None, customer_spend=None, authenticated=None, creator_version=None, **kwargs): data = {'name': name, 'address': address, 'country': country, 'phone': phone, 'email': email, 'email_verified': util.to_bool(email_verified), 'category_id': util.to_int(category_id), 'headline': headline, 'tonight': tonight, 'website': website, 'facebook': facebook, 'twitter': twitter, 'facebook_id': v_facebook_id, 'twitter_id': twitter_id, 'twitter_token': twitter_token, 'twitter_secret': twitter_secret, 'lat': util.to_float(lat), 'lon': util.to_float(lon), 'official': util.to_bool(official), 'verified': util.to_bool(verified), 'customer_spend': util.to_float(customer_spend), 'authenticated': util.to_bool(authenticated), 'creator': user_id, 'creator_version': creator_version} columns = [] values = [] for key, val in data.iteritems(): if val != None: columns.append(key) values.append(val) if venue_id: qry = {'update': 'venues', 'set_values': columns, 'where': 'id = ?'} values.append(venue_id) cursor.execute(util.query(**qry), values) else: qry = {'insert_into': 'venues', 'columns': columns} cursor.execute(util.query(**qry), values) cursor.execute(util.query(last_id=True)) return int(cursor.fetchone().identity)
def main(): if len(sys.argv) < 3: usage() print 'ERROR: min 3 arguments' exit(1) port_name = sys.argv[1] command = sys.argv[2] legs = Legs(port_name,9600) if command == 'updatestatus': ls = legs.get_status() ls.print_status() elif command == 'setall': speed = to_int(3, 0, 3000, 'speed') value = to_int(4, 0, 3000, 'value') ls = LegsStatus() ls.set(value,value,value,value,value,value,value,value,value,value,value,value,value,value,value,value,value,value) legs.set_all(speed, ls) elif command == 'setrand': speed = to_int(3, 0, 3000, 'speed') value = to_int(4, 0, 3000, 'value') offset = value-1500 ls = LegsStatus() ls.set( 1500,1500+offset,1500+offset*10, 1500,1500,1500, 1500,1500,1500, 1500,1500,1500, 1500,1500,1500, 1500,1500,1500) legs.set_all_sync(speed, ls) else: usage() print "ERROR: Unknown command"
def main(self): #Limpiamos consola, imprimimos las instrucciones #y pedimos una opcion clear() self.__instruc() print(" Presione:") print(" 1.- Para comenzar") print(" 0.- Para salir") option=to_int(input(" Ingrese su opcion: ")) if option==1: #Iniciar el juego clear() self.table.begin() elif option == 0: #Salir del juego exit() else: # Volver a mostrar el menu self.main()
def __init__(self, host=SERVER_DEFAULT, port=PORT_DEFAULT): self.host = host self.port = to_int(port) self._conn = ClientConnection(self.host, self.port, timeout=REQUEST_TIMEOUT)
def set(self, cursor=None, facebook_id=None, twitter_token=None, facebook=None, twitter=None, forename=None, surname=None, age=None, birth_day=None, birth_month=None, birth_year=None, gender=None, employee=None, country=None, language=None, email=None, top5=None, twitter_id=None, twitter_secret=None, save_locally=None, app_version=None, iphone_model=None, ios_version=None, last_facebook=None, last_twitter=None, **kwargs): if not facebook_id: raise cherrypy.HTTPError(403) qry = {'select': 'COUNT(id) AS count', 'table': 'users', 'where': 'facebook_id = ?'} cursor.execute(util.query(**qry), (facebook_id,)) res = cursor.fetchone().count data = {'twitter_id': twitter_id, 'twitter_token': twitter_token, 'twitter_secret': twitter_secret, 'facebook': facebook, 'twitter': twitter, 'forename': forename, 'surname': surname, 'age': util.to_int(age), 'birth_day': util.to_int(birth_day), 'birth_month': util.to_int(birth_month), 'birth_year': util.to_int(birth_year), 'gender': gender, 'employee': util.to_bool(employee), 'country': country, 'language': language, 'email': email, 'top5': util.to_bool(top5), 'save_locally': util.to_bool(save_locally), 'app_version': app_version, 'iphone_model': iphone_model, 'ios_version': ios_version, 'last_login': util.now(), 'last_facebook': util.to_bool(last_facebook), 'last_twitter': util.to_bool(last_twitter)} columns = [] values = [] for key, val in data.iteritems(): if val != None: columns.append(key) if val is not True and val is not False: values.append(val) else: if val: values.append('1') else: values.append('0') values.append(facebook_id) if res: qry = {'update': 'users', 'set_values': columns, 'where': 'facebook_id = ?'} cursor.execute(util.query(**qry), values) else: columns.append('facebook_id') columns.append('joined') values.append(util.now()) qry = {'insert_into': 'users', 'columns': columns} cursor.execute(util.query(**qry), values) qry = {'select': 'id', 'table': 'users', 'where': 'facebook_id = ?', 'order_by': 'id', 'limit': 1} cursor.execute(util.query(**qry), (facebook_id,)) user_id = cursor.fetchone().id return self.retrieve(cursor=cursor, user_id=user_id)
class BaseConfig: """Base configuration""" load_dotenv(".env") """ General """ FLASK_ENV = os.getenv("FLASK_ENV", "development") DEFAULT_COLLECTION_INTERVAL = {"hours": 1} ENV_NAME = os.getenv("ENV_NAME", socket.gethostname()) DEFAULT_PROJECTION = "wgs84" """ Sentry """ SENTRY_ENABLED = to_bool(os.getenv("SENTRY_ENABLED")) SENTRY_DSN = os.getenv("SENTRY_DSN", None) SENTRY_LEVEL = os.getenv("SENTRY_LEVEL", 40) SENTRY_EVENT_LEVEL = os.getenv("SENTRY_EVENT_LEVEL", 40) SENTRY_ENV_NAME = os.getenv("SENTRY_ENV_NAME", ENV_NAME) SENTRY_RELEASE = f"{project}-{version}" """ Datadog """ DATADOG_ENABLED = to_bool(os.getenv("DATADOG_ENABLED")) DATADOG_API_KEY = os.getenv("DATADOG_API_KEY", os.getenv("DD_API_KEY", None)) DATADOG_APP_KEY = os.getenv("DATADOG_APP_KEY", os.getenv("DD_APP_KEY", None)) DATADOG_DEFAULT_TAGS = { "environment": ENVIRONMENT_MAP.get(FLASK_ENV, FLASK_ENV), "service_name": project, "service_version": version, } """ Config """ CONFIG_BASEPATH = "./config" COLLECTOR_CONFIG_PATH = abs_path(*os.getenv('COLLECTOR_CONFIG_PATH', CONFIG_BASEPATH+"/collector.yaml").rsplit("/", 1)) # type: ignore # noqa COLLECTOR_CONFIG_PATH = abs_path(CONFIG_BASEPATH, "collector.yaml") COLLECTOR_CONFIG = load_config(COLLECTOR_CONFIG_PATH) PARSER_CONFIG_PATH = abs_path(CONFIG_BASEPATH, "parsers.yaml") PARSER_CONFIG = load_config(PARSER_CONFIG_PATH) QUERY_PATH = abs_path(CONFIG_BASEPATH, "templates/queries") EXPORT_PATH = abs_path(CONFIG_BASEPATH, "templates/exports") """ Logging """ LOG_LEVEL = os.getenv("LOG_LEVEL", 20) LOG_FORMAT = os.getenv("LOG_FORMAT", "funcname") WEB_LOG_REQUESTS = to_bool(os.getenv("WEB_LOG_REQUESTS", True)) WEB_LOG_RESPONSES = to_bool(os.getenv("WEB_LOG_RESPONSES", True)) WEB_LOG_SAMPLE_FRAC = float(os.getenv("WEB_LOG_SAMPLE_FRAC", 0.5)) WEB_LOG_SLOW_RESPONSE_THRESHOLD = float(os.getenv("WEB_LOG_SLOW_RESPONSE_THRESHOLD", 3)) # seconds # noqa CELERY_LOG_LEVEL = os.getenv("CELERY_LOG_LEVEL", LOG_LEVEL) CELERY_LOG_FORMAT = os.getenv("CELERY_LOG_FORMAT", LOG_FORMAT) """ --------------- Database --------------- """ DATABASE_DRIVER = os.getenv("DATABASE_DRIVER", "mongodb") DATABASE_USERNAME = os.getenv("DATABASE_USERNAME", None) DATABASE_PASSWORD = os.getenv("DATABASE_PASSWORD", None) DATABASE_HOST = os.getenv("DATABASE_HOST", "localhost") DATABASE_PORT = os.getenv("DATABASE_PORT", 27017) DATABASE_NAME = os.getenv("DATABASE_NAME", "default") DATABASE_AUTHENTICATION_SOURCE = "admin" DATABASE_URI = os.getenv("DATABASE_URI", None) REPLICA_SET = os.getenv("REPLICA_SET", None) # DATABASE_UUID_REPRESENTATION = "standard" # DATABASE_CONNECT = os.getenv("DATABASE_CONNECT", False) """ Celery """ BROKER_URL = os.getenv("CELERY_BROKER_URL", "redis://localhost:6379/0") CELERY_TASK_LIST = ["celery_queue.tasks"] CELERYD_TASK_TIME_LIMIT = to_int(os.getenv( "CELERYD_TASK_TIME_LIMIT", 60 * 60 * 12 )) # 12 hours CELERY_TASK_SERIALIZER = "json" CELERY_ACCEPT_CONTENT = ["json"] # CELERYD_MAX_TASKS_PER_CHILD = to_int(os.getenv("CELERYD_MAX_TASKS_PER_CHILD", 1000)) # CELERYD_MAX_MEMORY_PER_CHILD = to_int(os.getenv("CELERYD_MAX_MEMORY_PER_CHILD", 250000)) # 250MB # noqa CELERY_ENABLE_REMOTE_CONTROL = False # required for sqs CELERY_SEND_EVENTS = False # required for sqs CELERY_DEFAULT_QUEUE = f"{project}-default" # sqs queue name CELERY_ROUTES = ("celery_queue.routers.hole_direction_router",) CELERY_TASK_CREATE_MISSING_QUEUES = to_bool(os.getenv( "CELERY_TASK_CREATE_MISSING_QUEUES", False )) CELERY_TASK_ALWAYS_EAGER = to_bool(os.getenv("CELERY_TASK_ALWAYS_EAGER", False)) """ Celery Beat """ CELERYBEAT_SCHEDULER = "redbeat.RedBeatScheduler" CELERYBEAT_LOAD_ENDPOINTS: bool = to_bool(os.getenv("CELERYBEAT_LOAD_ENDPOINTS", True)) CELERYBEAT_MAX_LOOP_INTERVAL: int = to_int(os.getenv("CELERYBEAT_MAX_LOOP_INTERVAL", 30)) REDBEAT_REDIS_URL = os.getenv("IHS_CRON_URL") REDBEAT_KEY_PREFIX = f"{project}:" REDBEAT_LOCK_TIMEOUT = CELERYBEAT_MAX_LOOP_INTERVAL * 5 """ API """ API_CLIENT_TYPE = os.getenv("IHS_CLIENT_TYPE", "legacy") API_BASE_URL = os.getenv("IHS_URL") API_USERNAME = os.getenv("IHS_USERNAME") API_PASSWORD = os.getenv("IHS_PASSWORD") API_APP_KEY = os.getenv("IHS_APP_KEY") API_SYNC_WINDOW_MINUTES = os.getenv("IHS_SYNC_WINDOW_MINUTES", 1440 * 7) API_HEADERS = { "Username": API_USERNAME, "Password": API_PASSWORD, "Application": API_APP_KEY, } API_WSDL_DIR = abs_path(CONFIG_BASEPATH, "wsdl") API_WSDLS = { "session": abs_path(API_WSDL_DIR, "{version}/Session.wsdl"), "querybuilder": abs_path(API_WSDL_DIR, "{version}/QueryBuilder.wsdl"), "exportbuilder": abs_path(API_WSDL_DIR, "{version}/ExportBuilder.wsdl"), } API_DOMAIN = "US" TASK_BATCH_SIZE = to_int(os.getenv("IHS_TASK_BATCH_SIZE", 50)) SIMULATE_EXPENSIVE_TASKS = to_bool(os.getenv("IHS_SIMULATE_EXPENSIVE_TASKS", False)) @property def show(self): return [x for x in dir(self) if not x.startswith("_")] @property def api_params(self): return { key.lower().replace("api_", ""): getattr(self, key) for key in dir(self) if key.startswith("API_") } @property def datadog_params(self): return { key.lower().replace("datadog_", ""): getattr(self, key) for key in dir(self) if key.startswith("DATADOG_") } @property def sentry_params(self): return { key.lower().replace("sentry_", ""): getattr(self, key) for key in dir(self) if key.startswith("SENTRY_") } @property def endpoints(self): return self.COLLECTOR_CONFIG.endpoints @property def functions(self): return self.COLLECTOR_CONFIG.functions @property def database_params(self): return { key.lower().replace("database_", ""): getattr(self, key) for key in dir(self) if key.startswith("DATABASE_") } def database_uri(self, hide_password=False, include_auth_source=True): db = self.database_params username = db.get("username") password = "******" if hide_password else db.get("password") auth_source = ( f"?authSource={db.get('authentication_source')}" if include_auth_source else "" ) if self.REPLICA_SET: replica_set = ( f"?replicaSet={self.REPLICA_SET}" if not auth_source else f"&replicaSet={self.REPLICA_SET}" ) else: replica_set = "" driver = db.get("driver", "") host = db.get("host", "") port = db.get("port", "") dbname = db.get("name", "") at = "@" if username else "" colon = ":" if username is not None else "" username = username or "" password = password or "" return f"{driver}://{username}{colon}{password}{at}{host}:{port}/{dbname}{auth_source}{replica_set}" # noqa def __repr__(self): """ Print configuration summary """ hr = "-" * shutil.get_terminal_size().columns + "\n" tpl = "{name:>25} {value:<50}\n" string = "" string += tpl.format(name="app config:", value=APP_SETTINGS) string += tpl.format(name="flask app:", value=FLASK_APP) string += tpl.format(name="flask env:", value=self.FLASK_ENV) string += tpl.format( name="backend:", value=self.database_uri(hide_password=True, include_auth_source=False), ) string += tpl.format(name="broker:", value=self.BROKER_URL) # string += tpl.format(name="result broker:", value=self.CELERY_RESULT_BACKEND) string += tpl.format(name="collector:", value=self.API_BASE_URL) return hr + string + hr