コード例 #1
0
ファイル: meveme.py プロジェクト: hendrikfrentrup/GAETools
    def post(self):

        definition = self.request.get('definition')
        challenger = self.request.get('challenger')
        challenger_email = self.request.get('challenger_email')
        stake = self.request.get('stake')
        duration = self.request.get('duration')
        unique_id = self.request.cookies.get('unique_id')
        if unique_id:
            if self.request.get('oath'):  # == 'yes'
                new_challenge = Challenge(
                )  #parent=ndb.Key("Book", guestbook_name or "*notitle*")
                new_challenge.definition = definition
                new_challenge.challenger = challenger
                new_challenge.challenger_email = challenger_email
                # check for stake to be a number!
                new_challenge.stake = float(stake)
                new_challenge.originator_ID = unique_id  #int(unique_id)
                new_challenge.enddate = datetime.now() + timedelta(
                    weeks=int(duration))
                new_challenge.put()

                self.redirect('/created')

                if challenger_email:
                    to_addr = challenger_email
                    base_url = "http://meveme-prototype-v01.appspot.com/signup"
                    if not mail.is_email_valid(to_addr):
                        # Return an error message...
                        logging.infor(
                            "Signup confirmation not sent, email invalid!")

                    message = mail.EmailMessage()
                    message.sender = "*****@*****.**"  #user.email()
                    message.subject = "You've been challenged!"
                    message.to = to_addr
                    message.body = """
                        Hey, you've been challenged to {0}:
                        
                        {1}
                        
                        Check out your challenge at:
                        {2}
                    """.format(stake, definition, base_url)

                    message.send()

            else:
                self.render('create.html',
                            example=definition,
                            errors=['You need to show us you are serious!'],
                            email=challenger,
                            amount=stake,
                            color='#FF0000')
        else:
            self.redirect('login.html', username="******")
コード例 #2
0
ファイル: meveme.py プロジェクト: hendrikfrentrup/GAETools
    def post(self):
    
        definition = self.request.get('definition')
        challenger = self.request.get('challenger')
        challenger_email = self.request.get('challenger_email')
        stake = self.request.get('stake')
        duration = self.request.get('duration')
        unique_id = self.request.cookies.get('unique_id')
        if unique_id:
            if self.request.get('oath'):# == 'yes'
                new_challenge = Challenge() #parent=ndb.Key("Book", guestbook_name or "*notitle*")
                new_challenge.definition = definition
                new_challenge.challenger = challenger
                new_challenge.challenger_email = challenger_email
                # check for stake to be a number!
                new_challenge.stake = float(stake)
                new_challenge.originator_ID = unique_id #int(unique_id)
                new_challenge.enddate = datetime.now() + timedelta(weeks=int(duration))
                new_challenge.put()
                
                self.redirect('/created')
                
                if challenger_email:
                    to_addr = challenger_email
                    base_url = "http://meveme-prototype-v01.appspot.com/signup"
                    if not mail.is_email_valid(to_addr):
                        # Return an error message...
                        logging.infor("Signup confirmation not sent, email invalid!")

                    message = mail.EmailMessage()
                    message.sender = "*****@*****.**" #user.email()
                    message.subject = "You've been challenged!"
                    message.to = to_addr
                    message.body = """
                        Hey, you've been challenged to {0}:
                        
                        {1}
                        
                        Check out your challenge at:
                        {2}
                    """.format(stake, definition, base_url)

                    message.send()
                
            else:
                self.render('create.html', example=definition, errors=['You need to show us you are serious!'],
                                           email=challenger, amount=stake, color='#FF0000')
        else:
            self.redirect('login.html', username = "******" )
コード例 #3
0
def main(args):
    # load the config
    logging.info(f'Load the config from "{args.config_path}".')
    config = Box.from_yaml(filename=args.config_path)
    saved_dir = Path(config.main.saved_dir)
    if not saved_dir.is_dir():
        saved_dir.mkdir(parents=True)

    # copy the config
    loggging.info(f'Save the config to "{config.main.save_dir}".')
    with open(saved_dir / 'config.yaml', 'w+') as f:
        yaml.dump(config.to_dict(), f, default_flow_style=False)

    # fix the random seed
    random.seed(config.main.random_seed)
    torch.manual_seed(random.getstate()[1][1])
    torch.cuda.manual_seed_all(random.getstate()[1][1])
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False

    # device
    logging.info('Create the device.')
    if 'cuda' in config.trainer.kwargs.device and not torch.cuda.is_available(
    ):
        raise ValueError("The cuda is not available.")
    device = torch.device(config.trainer.kwargs.device)

    # dataset
    logging.info('Create the training and validation datasets.')
    data_dir = Path(config.dataset.kwargs.data_dir)
    config.dataset.kwargs.update(data_dir=data_dir, type='train')
    train_dataset = _get_instance(src.data.datasets, config.dataset)
    config.dataset.kwargs.update(data_dir=data_dir, type='valid')
    valid_dataset = _get_instance(src.data.datasets, config.dataset)

    # dataloader
    logging.info('Create the training and validation dataloaders.')
    cls = getattr(src.data.datasets, config.dataset.name)
    train_batch_size, valid_batch_size = config.dataloader.kwargs.pp(
        'train_batch_size'), config.dataloader.kwargs.pop('valid_batch_size')
    config.dataloader.kwargs.update(collate_fn=getattr(cls, 'collate_fn',
                                                       None),
                                    batch_size=train_batch_size)
    train_dataloader = _get_instance(src.data.dataloader, config.dataloader,
                                     train_dataset)
    config.dataloader.kwargs.update(batch_size=valid_batch_size)
    valid_dataloader = _get_instance(src.data.dataloader, config.dataloader,
                                     valid_dataset)

    # net
    logging.infor('Create the network architecture.')
    net = _get_instance(src.model.nets, config.net)

    # loss
    logging.info('Create the loss functions and the corresponding weights')
    loss_fns, loss_weights = [], []
    defaulted_loss_fns = [
        loss_fn for loss_fn in dir(torch.nn) if 'Loss' in loss_fn
    ]
    for config_loss in config.losses:
        if config_loss.name in defaulted_loss_fns:
            loss_fn = _get_instance(torch.nn, config_loss)
        else:
            loss_fn = _get_instance(src.model.losses, config.loss)
        loss_fns.append(loss_fn)
        loss_weights.append(config_loss.weight)

    # metric
    logging.info('Create the metric functions.')
    metric_fns = [
        _get_instance(src.model.metrics, config_metric
                      for config_metric in config_metrics)
    ]

    # optimizer
    logging.info('Create the optimizer')
    optimizer = _get_instance(torch.optim, config.optimizer, net.parameters())

    # learning rate scheduler
    logging.info('Create the learning rate scheduler')
    lr_scheduler = _get_instance(
        torch.optim.lr_scheduler, config.lr_scheduler,
        optimizer) if config.get('lr_scheduler') else None

    # logger
    logging.info('Create the logger')
    config.logger.kwargs.update(log_dir=saved_dir / 'log',
                                net=net,
                                dummy_input=torch.randn(
                                    tuple(config.logger.kwargs.dummy_input)))
    logger = _get_instance(src.callbacks.loggers, config.logger)

    # monitor
    logging.info('Create the monitor')
    config.monitor.kwargs.update(checkpoints_dir=saved_dir / 'checkpoints')
    monitor = _get_instance(src.callbacks.monitor, config.monitor)

    # trainer
    logging.info('Create the trainer.')
    kwargs = {
        'device': device,
        'train_dataloader': train_dataloader,
        'vliad_dataloader': valid_dataloader,
        'net': net,
        'loss_fns': loss_fns,
        'loss_weights': loss_weights,
        'metric_fns': metric_fns,
        'optimizer': optimizer,
        'lr_scheduler': lr_scheduler,
        'logger': logger,
        'monitor': monitor
    }
    config.trainer.kwargs.update(kwargs)
    trainer = _get_instance(src.runner.trainer, config.trainer)

    # load previous checkpoint
    loaded_path = config.main.get('loaded_path')
    if loaded_path:
        logging.info(f'Load the previous checkpoint from "{loaded_path}.')
        trainer.load(Path(loaded_path))
        logging.info('Resume training')
    else:
        logging.info('Start training.')
    trainer.train()
    logging.info('End training')
コード例 #4
0
ファイル: meveme.py プロジェクト: hendrikfrentrup/GAETools
    def post(self):

        fullname = self.request.get('name')
        email = self.request.get('email')
        username = self.request.get('username')
        password = self.request.get('password')
        repeat = self.request.get('repeat')

        # check if username is alphanumeric ('[^\w-]+$' or '[\W-]+$')
        valid_username = re.match('^[\w-]+$', username) is not None
        valid_password = re.match('^[\w-]+$', password) is not None

        logging.info('Username Valid: {0}'.format(valid_username))
        logging.info('Password Valid: {0}'.format(valid_password))

        # check if password is correctly repeated
        if password == repeat and valid_username and valid_password:

            # check if username exists already  # check if User with username exists
            users_query = User.query(User.username == username)
            user = users_query.fetch(1)
            if user:
                logging.info('User exists')
                self.write("Username is already in use, sorry!")
            else:
                # check if email exists already
                users_query = User.query(User.email == email)
                user = users_query.fetch(1)
                if user:
                    logging.info('Email exists')
                    self.write("Email is already in use, sorry!")
                else:
                    new_user = User()
                    new_user.fullname = fullname
                    new_user.email = email
                    new_user.username = username
                    new_user.password = password
                    new_user.put()

                    template_values = {
                        'name': fullname,
                        'email': email,
                    }

                    template = JINJA_ENVIRONMENT.get_template('signedup.html')
                    self.response.write(template.render(template_values))

                    #########################################################
                    # put this in it's own function'
                    #########################################################
                    to_addr = email
                    base_url = "http://meveme-prototype-v01.appspot.com/login"
                    if not mail.is_email_valid(to_addr):
                        # Return an error message...
                        logging.infor(
                            "Signup confirmation not sent, email invalid!")

                    message = mail.EmailMessage()
                    message.sender = "*****@*****.**"  #user.email()
                    message.to = to_addr
                    message.subject = "Your account has been created!"
                    message.body = """
                        Welcome to Meveme!

                        Your account has been created, congratulations!
                        
                        Come on and login at:
                        %s
                    """ % base_url

                    message.send()

        else:
            errors = []
            if not valid_username:
                errors.append("Please use a normal username!")
            if not valid_password:
                errors.append("Please use a normal password!")
            if not password == repeat:
                errors.append('Passwords need to be identical!')

            self.render('signup.html',
                        name=self.request.get('name'),
                        email=self.request.get('email'),
                        username=self.request.get('username'),
                        password="",
                        errors=errors)
コード例 #5
0
logging.info('x = {}, eps = {}, N accepted = {} (total {})'.format(
    x, eps, n, N_x))
# define std for chains
std = np.std(accepted, axis=0)
logging.info('std for each parameter:{}'.format(std))
for n_job in job_folders:
    np.savetxt(os.path.join(n_job, 'std'), [std])
# Randomly choose starting points for Markov chains
for i in range(N_params):
    unique, counts = np.unique(accepted[:, i], return_counts=True)
    logging.info(
        f'Number of unique values for {i+1} parameter: {len(unique)} {counts}')
replace = False
if N_chains > n:
    replace = True
    logging.infor("random choice with replacing")
random_ind = np.random.choice(n, N_chains, replace=replace)
C_start = accepted[random_ind]
dist_init = dist[random_ind]
np.set_printoptions(precision=4)
logging.info('starting parameters for MCMC chains:\n{}'.format(C_start))
for i, n_job in enumerate(job_folders):
    np.savetxt(os.path.join(n_job, 'C_start'), C_start[i])
    np.savetxt(os.path.join(n_job, 'dist_init'), C_start[i])
    if chain_with_limits:
        np.savetxt(os.path.join(n_job, 'C_limits'), C_limits)

logging.info(
    '2D smooth marginals with {} bins per dimension'.format(num_bin_kde))
if mirror:
    mirrored_data, _ = pp.mirror_data_for_kde(accepted, C_limits[:, 0],
コード例 #6
0
ファイル: datacode 1.py プロジェクト: ecotyper/ctp
 def close_connection(self):
     self.connection.close()
     logging.infor("成功关闭Rabbitmq服务器")
コード例 #7
0
ファイル: meveme.py プロジェクト: hendrikfrentrup/GAETools
    def post(self):

        fullname = self.request.get('name')
        email = self.request.get('email')
        username = self.request.get('username')
        password = self.request.get('password')
        repeat = self.request.get('repeat')
        
        # check if username is alphanumeric ('[^\w-]+$' or '[\W-]+$')
        valid_username = re.match('^[\w-]+$', username) is not None
        valid_password = re.match('^[\w-]+$', password) is not None
        
        logging.info('Username Valid: {0}'.format(valid_username))
        logging.info('Password Valid: {0}'.format(valid_password))
        
        # check if password is correctly repeated
        if password==repeat and valid_username and valid_password:
        
            # check if username exists already  # check if User with username exists
            users_query = User.query(User.username == username)
            user = users_query.fetch(1)
            if user:
                logging.info('User exists')
                self.write("Username is already in use, sorry!")
            else:    
                # check if email exists already
                users_query = User.query(User.email == email)
                user = users_query.fetch(1)
                if user:
                    logging.info('Email exists')
                    self.write("Email is already in use, sorry!")
                else:                         
                    new_user = User()
                    new_user.fullname = fullname
                    new_user.email = email
                    new_user.username = username
                    new_user.password = password
                    new_user.put()

                    template_values = {
                        'name': fullname,
                        'email': email,
                    }

                    template = JINJA_ENVIRONMENT.get_template('signedup.html')
                    self.response.write(template.render(template_values))
                    
                    #########################################################
                    # put this in it's own function'
                    #########################################################
                    to_addr = email
                    base_url = "http://meveme-prototype-v01.appspot.com/login"
                    if not mail.is_email_valid(to_addr):
                        # Return an error message...
                        logging.infor("Signup confirmation not sent, email invalid!")

                    message = mail.EmailMessage()
                    message.sender ="*****@*****.**" #user.email()
                    message.to = to_addr
                    message.subject = "Your account has been created!"
                    message.body = """
                        Welcome to Meveme!

                        Your account has been created, congratulations!
                        
                        Come on and login at:
                        %s
                    """ % base_url

                    message.send()


        else:
            errors=[]
            if not valid_username:
                errors.append("Please use a normal username!")
            if not valid_password:
                errors.append("Please use a normal password!")
            if not password==repeat:
                errors.append('Passwords need to be identical!')

            self.render('signup.html', name=self.request.get('name'),
                                   email=self.request.get('email'),
                                   username=self.request.get('username'),
                                   password="",
                                   errors=errors)
コード例 #8
0
	  	
	 trim_loc = self.trimLocation(venue_json['location'])
	 trim_loc['lat'] = int(math.floor(float(lat)))
	 trim_loc['lng'] = int(math.floor(float(lng)))
	 
	 entry = { 'timestamp' : checkin_json['createdAt'],
	 		   'location' : trim_loc
	 		 }
	 		 
	 for old_entry.history.insert(0, db.Text(json.dumps(entry)))
	   old_entry = json.loads(old_entry)
	   old_location = old_entry['location']
	   location = entry['location']
	   if self.geoDistance(old_location, location) > 2:
	   	 logging.infor('User is traveling from %s to %s' &
	   	 			  (self.makeRegionName(old_location, location),
	   	 			   self.makeRegionName(location)))
	   	 self.IS_TRAVELING = True
	   	 break
	   	 
	fh_user.history.insert(0, db.Text(json.dumps(entry)))
	if len(fh_user.history) > self.MOVING_AVG_WINDOW:
	  fh_user.history.pop()
	  
	recent_checkins = client.checkins.recent(params={'ll': latlng})
	if not fh_user.friends:
	  fh_user.friends = "{}"
	friend_map = json.loads(fh_user.friends)
	
	close_friend_tuples = []
	
コード例 #9
0
def what_is_the_ip(ip, log):
    logging.info('Telnet to console with ip %s',ip)
    console = pexpect.spawn('telnet %s' % (ip))
    console.logfile = log
    k = 0
    i = console.expect([pexpect.TIMEOUT, pexpect.EOF, SWITCH_LOGIN, \
        PWD_PROMPT, PX_POWER_PROMPT, PX2_POWER_PROMPT, APC_POWER_PROMPT], 10)
    if i==0 or i==1:
        console.sendline('')
        m = console.expect([pexpect.TIMEOUT, pexpect.EOF, SWITCH_LOGIN], 5)
        if m==0 or m==1:
            logging.info('Unknown IP')
            result_dict[ip] = {'device':'Unknown','login':''}
            #ipdistinguish.create(ip=ip,device='Unknown')
        if m==2:
            logging.infor('Found a Switch')
            result_dict[ip] = {'device':'Switch','login':''}
            #ipdistinguish.create(ip=ip,device='Switch')
    if i==2:
        logging.info('Found a Switch')
        result_dict[ip] = {'device':'Switch','login':''}
        #ipdistinguish.create(ip=ip,device='Switch')
    if i==3:
        console.sendline(console_pwd_list[k])
        j = console.expect([pexpect.TIMEOUT, pexpect.EOF, PWD_PROMPT, CONSOLE_PROMPT, 'Bad'], 5)
        while j >= 0:
            if j==0 or j==1:
                logging.info("Weird console")
                result_dict[ip] = {'device':'UnknownConsole','login':''}
                #ipdistinguish.create(ip=ip,device='UnknownConsole')
                break
            if j==2:
                logging.info("Invalid pwd [%s] try another one", \
                        console_pwd_list[k])
                k = k + 1
                if k > 3:
                    break
                pass
            if j==3:
                console.sendline('terminal length 0')
                console.expect(CONSOLE_PROMPT)
                console.sendline('show line | include TTY')
                console.expect(CONSOLE_PROMPT)
                temp = console.before
                if temp:
                    logging.info("Found a Console")
                    result_dict[ip] = {'device':'Console','login':''}
                    #ipdistinguish.create(ip=ip,device='Console')
                break
            if j==4:
                logging.info('wrong pwd for console')
                result_dict[ip] = {'device':'Console','login':''}
                #ipdistinguish.create(ip=ip,device='Console')
                break
            console.sendline(console_pwd_list[k])
            j = console.expect([pexpect.TIMEOUT, pexpect.EOF, PWD_PROMPT, CONSOLE_PROMPT, 'Bad'], 5)
    if i==4 or i==5 or i==6:
        logging.info("Found Power Slot")
        result_dict[ip] = {'device':'PowerSlot','login':''}
        #ipdistinguish.create(ip=ip,device='PowerSlot')

    console.close()
    '''
    temp_ip = ipdistinguish.get(ipdistinguish.ip==ip)
    if str(temp_ip.device).lower() == 'switch':
        logging.info("Try to get the password of switch")
        success = loginIlabDB(ip,log)
        if not(success):
            login3Attempts(ip,log)
    '''
    if result_dict[ip]['device'].lower() == 'switch':
        logging.info("Try to get the password of switch")
        success = loginIlabDB(ip,log)
        if not(success):
            login3Attempts(ip,log)
    return