def handle_options(parser): args = parser.parse_args() api_setup(args.config_file) if args.original_service == "": cloudDB = get_available_db_services("cloudDB") print(json.dumps(cloudDB, indent=4)) args.original_service = raw_input( "Please the CloudDB service name to migrate from : ") if args.original_database == "": cloudb_databases = get_available_database("cloudDB", args.original_service) print(json.dumps(cloudb_databases, indent=4)) args.original_database = raw_input( "Please tell me which database to migration from service %s : " % (args.original_service)) if args.destination_service == "": enterpriseDB = get_available_db_services("enterpriseDB") print(json.dumps(enterpriseDB, indent=4)) args.destination_service = raw_input( "Please the Enterprise Database Service to migrate to : ") if args.destination_database == "": args.destination_database = args.original_database if args.destination_security_group == "": if args.silent_migration: args.destination_security_group = random_name.generate_name() print( "[INFO] Defining a random security group name as you are in silent_migration mode : %s" % (args.destination_security_group)) else: enterprisedb_groups = enterprise_get_security_groups( args.destination_service) print(json.dumps(enterprisedb_groups, indent=4)) args.destination_security_group = raw_input( "Please the Enterprise Database Service Security Group to set IP restrictions to : " ) if args.destination_security_group == "": args.destination_security_group = random_name.generate_name() print( "[INFO] Defining a random security group name as you defined an empty security group name : %s" % (args.destination_security_group)) if args.destination_user_password == "": args.destination_user_password = randomStringDigits(12) + str( random_with_N_digits(2)) print("[INFO] Starting Migration with parameters: ") print("") print(args) print("") print("") print("-------") return args
def enterprise_create_security_group(service_name, security_group_name=""): if enterpise_security_group_exists(service_name, security_group_name): print( "[INFO] %s security group already exists for service %s - Skipping" % (security_group_name, service_name)) else: if security_group_name == "": if not silent_migration: security_group_name = raw_input( "Please input the Security Group name to create : ") if security_group_name == "": security_group_name = random_name.generate_name() print( "[INFO] Empty security group name set for service %s so we decided to create a random one : %s" % (service_name, security_group_name)) print("[INFO] Setting up a new security group (%s) for service %s" % (security_group_name, service_name)) result = client.post( "/cloudDB/enterprise/cluster/" + service_name + "/securityGroup", clusterId=service_name, name=security_group_name, ) return security_group_name
def register_sensor(request): if request.method == 'POST': email = request.POST.get('email') if isinstance(email, list): email = email[0] sensor_name = request.POST.get('sensor_name') lat = request.POST.get('lat') lon = request.POST.get('lon') address = request.POST.get('address') serial = request.POST.get('serial') description = request.POST.get('description') error = verify_email(email) if error: return error if not sensor_name: sensor_name = random_name.generate_name() # If a sensor with the email already exists issue an error try: user = User.objects.get(email=email) return Response({"error": "The email %s is already registered with a sensor" % email}, status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: # Creat the new user with transaction.atomic(): username = User.objects.make_random_password(length=10) password = User.objects.make_random_password(length=10) user = User(username=username, password=password, email=email, is_active=False) user.save() # Add sensor information sensor = Sensor(account=user, sensor_name=sensor_name, lat=lat, lon=lon, address=address, serial=serial, description=description) sensor.save() # Send Verification email verification_code = User.objects.make_random_password(length=40) verify = SensorVerification(account=user, verification_code=verification_code) verify.save() mail = VerificaitonEmail(user.email, verification_code) mail.send() return Response({ 'email': user.email, 'username': user.username, 'id': user.id, 'verified': verify.verified, 'message': 'New sensor is registered. A verification email is sent to the email provided. ' + 'Please verify the sensor.', }, status=status.HTTP_201_CREATED)
def get_sandbox_id(templates, manifests, all_experiments, auto): # Generate a sandbox name and ask the user what they want theirs to be called. manifest_hash = hashlib.md5(manifests.encode()).digest() manifest_hash = anybase32.encode(manifest_hash, anybase32.ZBASE32).decode() pr_ids = "-".join( [ f"{repo}{opts.ref}" for repo, opts in templates.items() if opts.ref != DEFAULT_BRANCH ] ) # if we are in auto mode (non interactive) just generate a random sandbox ID name if auto: return random_name.generate_name() fragments = ( re.sub(r"[^\w\s]", "", os.getenv("BIOMAGE_NICK", os.getenv("USER", ""))), pr_ids if pr_ids else manifest_hash, ) sandbox_id = "-".join([bit for bit in fragments if bit]).lower()[:26] # Ask the user to provide one if they want click.echo() click.echo(click.style("Give a sandbox ID.", fg="yellow", bold=True)) click.echo( "The sandbox ID must be no more than 26 characters long, consist of " "lower case alphanumeric characters, or `-`, and must\n" "start and end with an alphanumeric character. A unique ID generated from " "the contents of the deployments and your pinning\n" "choices has been provided as a default." ) while True: questions = [ { "type": "input", "name": "sandbox_id", "message": "Provide an ID:", "default": sandbox_id, } ] click.echo() sandbox_id = prompt(questions) sandbox_id = sandbox_id["sandbox_id"] if sandbox_id in [experiment["experimentId"] for experiment in all_experiments]: click.echo( click.style( "Your ID is the same with the name of an experiment. " "Please use another name", fg="red", ) ) elif SANDBOX_NAME_REGEX.match(sandbox_id) and len(sandbox_id) <= 26: return sandbox_id else: click.echo(click.style("Please, verify the syntax of your ID", fg="red"))
def __generate_initial_content(self): print('Generating content') main_user_photo = model.Image( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'saar.jpg')) main_user = model.User('Saar Raz', main_user_photo, model.User.GENDER_MALE) main_user_photo = model.Image( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'saar.jpg')) photo0 = model.Image( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'matan.jpg')) friend = model.User('Matan Raviv', photo0, model.User.GENDER_MALE) model.friends.append(friend) photo1 = model.Image( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uria.jpg')) friend = model.User('Uria Shaul-Mandel', photo1, model.User.GENDER_MALE) model.friends.append(friend) photo2 = model.Image( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'dvir.jpg')) friend = model.User('Dvir Mordechai-Navot', photo2, model.User.GENDER_MALE) model.friends.append(friend) photo2 = model.Image( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'angela.jpg')) friend = model.User('Angela Merkel', photo2, model.User.GENDER_MALE) friend.birthday = datetime.datetime.today() model.friends.append(friend) photo2 = model.Image( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bar.jpg')) friend = model.User('Bar Rafaeli', photo2, model.User.GENDER_MALE) friend.birthday = datetime.datetime.today() model.friends.append(friend) for i in range(2000): gender = random.choice( [model.User.GENDER_FEMALE, model.User.GENDER_MALE]) model.random_people.append( model.User( random_name.generate_name( gender == model.User.GENDER_MALE), random_name.generate_pic(gender == model.User.GENDER_MALE), gender)) model.User.set_main_user(main_user) for i in range(15): self.post( random.choice(self._bots).generate( random.choice(model.friends), datetime.datetime.now() - datetime.timedelta( seconds=random.random() * datetime.timedelta(days=1).total_seconds()))) threading.Thread(target=self.periodically).start()
def clean(self): if not isinstance(self, EmbeddedDocument): self.modified = datetime.now() if hasattr(self, 'name') and self.name is None: name = random_name.generate_name(separator='-') setattr(self, 'name', name) LOG.warn("{} is anonymous. Using random name: {}".format( self.__class__.__name__, name)) for key, val in self._fields.items(): if isinstance(val, ReferenceField): getattr(self, key) # assure that referenced document exists self._id = self.get_pk()
def __init__(self, testSessionId=None, args=None, verbose=False, workspace_path='.'): self.args = args self.testSessionId = testSessionId or random_name.generate_name( separator='_', lists=[random_name.ADJECTIVES, random_name.ANIMALS]) self.setup_logging() self.docker_client = docker.from_env() self.sequence = 0 self.verbose = verbose self.workspace_path = path.abspath( path.join(os.getcwd(), workspace_path)) for curr_signal in [signal.SIGTERM, signal.SIGINT]: signal.signal(curr_signal, handle_signal)
async def upload(request): session_id = random_name.generate_name() session_path = app.config.UPLOAD_DIR + "/" + session_id + "/" if not os.path.exists(session_path): os.makedirs(session_path) else: # lazy, very lazy return response.text( "Session conflict! Refresh the page and try again.", status=409) for file_item in request.files.keys(): uploaded_file = request.files.get(file_item) async with aiofiles.open(session_path + uploaded_file.name, 'wb') as f: await f.write(uploaded_file.body) f.close() return response.json({"session_id": session_id})
def fit(final_model=False): ''' Fits the model ''' mapped_data = data.get_mapped_data(limit=MAX_SAMPLES) x_train, x_test, y_train, y_test, sw_train, sw_test = train_test_split( mapped_data['x'], mapped_data['y'], mapped_data['sw'], test_size=0.1, random_state=0) x_train, x_val, y_train, y_val, sw_train, sw_val = train_test_split( x_train, y_train, sw_train, test_size=0.1, random_state=0) if final_model: x_train = mapped_data['x'] y_train = mapped_data['y'] sw_train = mapped_data['sw'] num = str(len([i for i in os.walk(MODEL_DIR)])) MODEL_NAME = num + '-' + random_name.generate_name() print(MODEL_NAME) model = make_model(input_dim=len(x_train[0])) model.compile('adam', loss='mse', metrics=['mse']) model.fit( x=x_train, y=y_train, sample_weight=sw_train, batch_size=BATCH_SIZE, epochs=EPOCHS, verbose=1, validation_data=(x_val, y_val, sw_val), callbacks=[ EarlyStopping(patience=5) ] ) y_pred = model.predict(x_test) mse = mean_squared_error(y_test, y_pred, sample_weight=sw_test) losses = { 'mse': mse, 'rmse': mse ** 0.5 } print(losses) save_model(model, MODEL_NAME, losses) make_player_models(model, MODEL_NAME, final_model=final_model)
def fit(final_model=False): num = str(len([i for i in os.walk(MODEL_DIR)])) MODEL_NAME = num + '-' + random_name.generate_name() print(MODEL_NAME) mapped_data = data.get_mapped_data(limit=MAX_SAMPLES) x_train, x_test, y_train, y_test, sw_train, sw_test = train_test_split( mapped_data['x'], mapped_data['y'], mapped_data['sw'], test_size=0.1, random_state=0) x_train, x_val, y_train, y_val, sw_train, sw_val = train_test_split( x_train, y_train, sw_train, test_size=0.1, random_state=0) regressor = make_model() logging.debug('Fitting...') regressor.fit( x_train, y_train, sample_weight=sw_train, eval_metric='rmse', eval_set=[(x_val, y_val)], sample_weight_eval_set=[sw_val], early_stopping_rounds=10, verbose=True ) y_pred = regressor.predict(x_test) mse = mean_squared_error(y_test, y_pred, sample_weight=sw_test) losses = { 'mse': mse, 'rmse': mse ** 0.5 } print(losses) save_model(regressor, MODEL_NAME, losses) make_player_models(regressor, MODEL_NAME, final_model=final_model)
def login(l): l.client.post("/login", { "username": random_name.generate_name(), "passwd": "" })
def get_tmp(cls): path = os.path.join(Paths.NHA_WORK, random_name.generate_name()) pathlib.Path(path).mkdir(parents=True, exist_ok=False) return cls(path, disposable=True)
def mule_name(self, mule_alias: str = None): return '{}-mule'.format(mule_alias or random_name.generate_name())
import random_name class Rectangle: #define the rectangle class def __init__(self, name, length, width): #initiate the constructor and attributes self.name = name self.length = length self.width = width def area(self): #method to calculate the area of a rectangle area = self.length * self.width return area def is_square( self ): #method that returns true if rectangle is also a square / else - false if self.length == self.width: return True else: return False #test cases a1 = random.randrange(1, 100) a2 = random.randrange(1, 100) rect = Rectangle(random_name.generate_name(), a1, a2) rectArea = str(rect.area()) btext.success("The area of {0} is: {1}".format(random_name.generate_name(), rectArea)) input("Press enter to continue")
from colorama import init, Fore, Back import random import random_name init() print(Back.CYAN + Fore.YELLOW + "Hello, my name is", random_name.generate_name()) print(Back.BLACK + "Choose a number between 0 and a 100 and I'll try to guess it:") choice = input() x = random.randint(0, 101) print("I guessed ", x) if choice == x: print(Back.GREEN + "Hey, I got it!") else: print(Back.RED + "Darn, I'll get it next time.")
def __init__(self, **kwargs): super().__init__(alias='anon-{alias}-{dt}'.format( alias=random_name.generate_name(separator='_'), dt=datetime.now().strftime(DateFmt.SYSTEM)), **kwargs)
#Pardhu Gorripati import colorise import random_name colorList = ['purple', 'red', 'green', 'cyan', 'blue', 'yellow'] for eachColor in colorList: colorise.set_color(eachColor) print('\n',random_name.generate_name()) colorise.set_color() input("Press ENTER to continue!")