def create_team(self, **kwargs): if not kwargs.get('name'): kwargs['name'] = petname.Generate(2, ' ', letters=10).title() if not kwargs.get('slug'): kwargs['slug'] = slugify(six.text_type(kwargs['name'])) if not kwargs.get('organization'): kwargs['organization'] = self.organization return Team.objects.create(**kwargs)
def create_environment(project, **kwargs): name = kwargs.get('name', petname.Generate(3, ' ', letters=10)[:64]) env = Environment.objects.create( organization_id=project.organization_id, project_id=project.id, name=name, ) env.add_project(project, is_hidden=kwargs.get('is_hidden')) return env
def random_hostname(self, params): """Return a random hostname.""" while True: new_hostname = petname.Generate(2, "-") try: Node.objects.get(hostname=new_hostname) except Node.DoesNotExist: return new_hostname return ""
class U2fRestSerializer(serializers.Serializer): deviceName = serializers.CharField( label='Device name', required=False, max_length=60, default=lambda: petname.Generate(2, ' ', letters=10).title(), ) challenge = serializers.CharField(required=True, ) response = serializers.CharField(required=True, )
def __init__(self, *, output=None, source, project: Project, remote=None) -> None: container_name = petname.Generate(3, "-") super().__init__( output=output, source=source, project=project, container_name=container_name, remote=remote, )
def model_setup_run(setup=(hidden_size, repeat, lr, weight_decay, batch_size), epochs=epochs, n_atoms=n_atoms, criteria=nn.SmoothL1Loss(), trainset=trainset, testset=testset, test_batch_size=test_batch_size, name=name, init_state_path=init_state_path, ReInitialized_MODEL=ReInitialized_MODEL): name = petname.Generate(3, ' ', 10) hidden_size, repeat, lr, weight_decay, batch_size = setup module = nn.Linear(hidden_size, hidden_size) batch_size = int(batch_size) input_module = nn.Linear(n_atoms * 3, hidden_size) output_module = nn.Linear(hidden_size, n_atoms * 3) model = modular_nn(input_module, module, repeat, output_module) if ReInitialized_MODEL: torch.save(model.state_dict(), init_state_path) print(model) r2, a, b, RMSE, MSE, val_loss, name = \ train_over_hyperparameters(model, init_state_path, trainset, testset, criteria, lr=lr, weight_decay=weight_decay, epochs=epochs, batch_size=batch_size, test_batch_size=test_batch_size, name=name, cuda=True, parallel=True, verbose=True) if args.save_model: torch.save(model.state_dict(), args.model_path + '/' + name + '.model') # %% Logging run LOGGING_FILE = 'bookkeeping.json' line = dict(name=name, lr=lr, weight_decay=weight_decay, epochs=epochs, batch_size=batch_size, test_batch_size=test_batch_size, hidden_size=hidden_size, repeat=repeat, search_method=args.search_method, R2=r2, slope=a, intercept=b, RMSE=RMSE, MSE=MSE, validation_loss=val_loss) try: df = pd.read_json(LOGGING_FILE) except ValueError: df = pd.DataFrame() df = df.append(line, ignore_index=True) df.to_json(LOGGING_FILE) return RMSE
def __init__(self, snap_output, tar_filename, project_options, server=_DEFAULT_IMAGE_SERVER): self._snap_output = snap_output self._tar_filename = tar_filename self._project_options = project_options self._container_name = 'snapcraft-{}'.format(petname.Generate(3, '-')) self._server = server
def generate_bmc_names(apps, schema_editor): BMC = apps.get_model("maasserver", "BMC") generated_names = [] for bmc in BMC.objects.all(): while True: bmc.name = petname.Generate(2, "-") if bmc.name not in generated_names: bmc.save() generated_names.append(bmc.name) break
def create_environment(self, **kwargs): project = kwargs.get('project', self.project) name = kwargs.get('name', petname.Generate(3, ' ', letters=10)[:64]) env = Environment.objects.create( organization_id=project.organization_id, project_id=project.id, name=name, ) env.add_project(project) return env
def set_random_name(self): """Set a random `name`.""" while True: self.name = petname.Generate(2, "-") try: self.save() except ValidationError: pass else: break
def create_repo(project, name=None, provider=None, integration_id=None, url=None): repo = Repository.objects.create( organization_id=project.organization_id, name=name or "{}-{}".format(petname.Generate(2, "", letters=10), random.randint(1000, 9999)), provider=provider, integration_id=integration_id, url=url, ) return repo
def generate_captcha(): import uuid import base64 import petname #TODO refactor avec feed pour le safe uuid r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes) verify = petname.Generate(1) r.setex(r_uuid, TIME_OUT_CAPTCHA, verify) return image.generate(verify), r_uuid
def create_environment(project, **kwargs): name = kwargs.get("name", petname.Generate(3, " ", letters=10)[:64]) organization = kwargs.get("organization") organization_id = organization.id if organization else project.organization_id env = Environment.objects.create(organization_id=organization_id, project_id=project.id, name=name) env.add_project(project, is_hidden=kwargs.get("is_hidden")) return env
class U2fRestSerializer(serializers.Serializer): deviceName = serializers.CharField( label="Device name", required=False, allow_null=True, allow_blank=True, max_length=60, default=lambda: petname.Generate(2, " ", letters=10).title(), ) challenge = serializers.CharField(required=True) response = serializers.CharField(required=True)
def create_race_data(): data = { "name": petname.Generate(3), "boat_type_id": random.randint(1, db.session.query(BoatType).count()), "start_time": arrow.now().int_timestamp + 10, "private": 1, "start_loc_id": random.randint(1, db.session.query(Location).count()), "finish_loc_id": random.randint(1, db.session.query(Location).count()), "user_id": random.randint(1, db.session.query(User).count()) } return data
def create_project(self, **kwargs): if not kwargs.get('name'): kwargs['name'] = petname.Generate(2, ' ').title() if not kwargs.get('slug'): kwargs['slug'] = slugify(six.text_type(kwargs['name'])) if not kwargs.get('team'): kwargs['team'] = self.team if not kwargs.get('organization'): kwargs['organization'] = kwargs['team'].organization return Project.objects.create(**kwargs)
def __init__(self, snap_output, tar_filename, project_options, remote=None): self._snap_output = snap_output self._tar_filename = tar_filename self._project_options = project_options container_name = 'snapcraft-{}'.format(petname.Generate(3, '-')) if remote: self._verify_remote(remote) self._container_name = '{}:{}'.format(remote, container_name) else: self._container_name = container_name
def create_team(organization, **kwargs): if not kwargs.get('name'): kwargs['name'] = petname.Generate(2, ' ', letters=10).title() if not kwargs.get('slug'): kwargs['slug'] = slugify(six.text_type(kwargs['name'])) members = kwargs.pop('members', None) team = Team.objects.create(organization=organization, **kwargs) if members: for user in members: Factories.create_team_membership(team=team, user=user) return team
def run_exercise(): env_name = 'MountainCar-v0' run_name = petname.Generate(3, '-') print "Starting {} run {}".format(env_name, run_name) environment = gym.make(env_name) agent = GradientSarsaAgent(environment) print print "Starting training" environment.monitor.start('runs/{}/{}/'.format(env_name, run_name)) run_episodes(environment, agent, episodes=100)
def get_unique_id(availability_func: Callable) -> str: """Generate a unique sample id. The availability function should return a matching result given an id if it already exists. """ while True: random_id = petname.Generate(3, separator="") if availability_func(random_id) is None: return random_id else: LOG.debug(f"{random_id} already used - trying another id")
def create_team(organization, **kwargs): if not kwargs.get("name"): kwargs["name"] = petname.Generate(2, " ", letters=10).title() if not kwargs.get("slug"): kwargs["slug"] = slugify(six.text_type(kwargs["name"])) members = kwargs.pop("members", None) team = Team.objects.create(organization=organization, **kwargs) if members: for user in members: Factories.create_team_membership(team=team, user=user) return team
def create_organization(self, name=None, owner=None, **kwargs): if not name: name = petname.Generate(2, ' ', letters=10).title() org = Organization.objects.create(name=name, **kwargs) if owner: self.create_member( organization=org, user=owner, role='owner', ) return org
def create_alert_rule_trigger( alert_rule, label=None, threshold_type=AlertRuleThresholdType.ABOVE, alert_threshold=100, resolve_threshold=10, ): if not label: label = petname.Generate(2, " ", letters=10).title() return create_alert_rule_trigger(alert_rule, label, threshold_type, alert_threshold, resolve_threshold)
def create_project(organization=None, teams=None, **kwargs): if not kwargs.get("name"): kwargs["name"] = petname.Generate(2, " ", letters=10).title() if not kwargs.get("slug"): kwargs["slug"] = slugify(six.text_type(kwargs["name"])) if not organization and teams: organization = teams[0].organization project = Project.objects.create(organization=organization, **kwargs) if teams: for team in teams: project.add_team(team) return project
def my_func(*args, **kwargs): process_number = petname.Generate(2, '-') while True: try: return func(process_number, *args, **kwargs) except KeyboardInterrupt: print("Keyboard interrupt in worker", process_number) return except Exception as e: print( "Error in worker {}:\n\t{}\n\tRestarting in 3 seconds...". format(process_number, repr(e))) sleep(3)
def __init__(self, *, output=None, source, project_options, metadata=None, remote=None): container_name = petname.Generate(3, '-') super().__init__(output=output, source=source, project_options=project_options, metadata=metadata, container_name=container_name, remote=remote)
def add_family(self, name: str, panels: List[str], priority: str='standard') -> models.Family: """Add a new family to the database.""" # generate a unique family id while True: internal_id = petname.Generate(2, separator='') if self.family(internal_id) is None: break else: LOG.debug(f"{internal_id} already used - trying another id") db_priority = PRIORITY_MAP[priority] new_family = self.Family(internal_id=internal_id, name=name, priority=db_priority) new_family.panels = panels return new_family
def _create_container(self): try: remote_tmp = petname.Generate(2, '-') check_call(['lxc', 'remote', 'add', remote_tmp, self._server]) check_call([ 'lxc', 'launch', '-e', '{}:ubuntu/xenial/{}'.format(remote_tmp, self._project_options.deb_arch), self._container_name ]) yield finally: check_call(['lxc', 'stop', self._container_name]) check_call(['lxc', 'remote', 'remove', remote_tmp])
def __init__(self, *, project, echoer) -> None: self.project = project self.echoer = echoer # Once https://github.com/CanonicalLtd/multipass/issues/220 is # closed we can prepend snapcraft- again. self.instance_name = petname.Generate(2, '-') self.project_dir = shlex.quote(project.info.name) if project.info.version: self.snap_filename = '{}_{}_{}.snap'.format( project.info.name, project.info.version, project.deb_arch) else: self.snap_filename = '{}_{}.snap'.format(project.info.name, project.deb_arch)
def _start_servers(self, transport, num_servers, num_topics): topics = [petname.Generate(3, "_") for _i in range(num_topics)] topics_iter = itertools.cycle(topics) for i in range(num_servers): topic = topics_iter.next() server_name = 'profiler_server' LOG.info("Starting server %s topic %s" % (server_name, topic)) target = messaging.Target(topic=topic, server=server_name) pr = multiprocessing.Process(target=self._start_server, args=(transport, target, self.messages_received)) pr.start() self.server_processes.append(pr) self.context['servers'].append((topic, server_name))