Beispiel #1
0
def test_redirect():
    srv_mock.long = get_random_string()
    key = get_random_string()
    response = client.get(f'/{key}', allow_redirects=False)
    assert srv_mock.long == response.headers.get('location')
    assert srv_mock.key == key
    assert response.status_code == 308
Beispiel #2
0
 def get_random_data(self):
     self.data.clear()
     self.data['code'] = get_random_number(0, 10000)
     self.data['citizens'] = get_random_number(500, 500000)
     self.data['name'] = get_random_string(size=8)
     self.data['country'] = get_random_string(size=7)
     return self.data
async def test_elongate():
    key = get_random_string()
    storage_mock.url = get_random_string()

    url = await url_shortener.elongate(key)

    assert url == storage_mock.url
    assert key == storage_mock.key
Beispiel #4
0
def insert_customer():
    customr_name = utils.get_random_string()
    customer_email = utils.get_random_string()
    customer_password = utils.get_random_string()
    customer_active = utils.get_random_boolean()
    utils.execute(
        """INSERT INTO customer (name, email, password, active) VALUES ('{CUSTOMER_NAME}', '{CUSTOMER_EMAIL}', '{CUSTOMER_PASSWORD}', '{CUSTOMER_ACTIVE}');"""
        .format(CUSTOMER_NAME=customr_name,
                CUSTOMER_EMAIL=customer_email,
                CUSTOMER_PASSWORD=customer_password,
                CUSTOMER_ACTIVE=customer_active))
    advance_time()
Beispiel #5
0
    def __init__(self,\
                 shape,\
                 nummap,\
                 numfactors,\
                 learning_rate,\
                 w,\
                 s):
        print 'in __init__ gated_convolution'
        self.shape = shape
        self.nummap = nummap
        self.numfactors = numfactors
        self.w = w
        self.s = s
        self.scope1 = 'conv1' + get_random_string()
        self.scope2 = 'conv2' + get_random_string()

        #Xavier init
        self.xavier_init = tf.contrib.layers.xavier_initializer()

        self.declare_lowlvl_vars()

        #Declare input variables
        self.x = tf.placeholder(shape=shape, dtype=tf.float32)
        self.y = tf.placeholder(shape=shape, dtype=tf.float32)

        #Corrupt input data
        corrupted_x = self.corrupt_data(self.x, .5)
        corrupted_y = self.corrupt_data(self.y, .5)

        #Get conv factors
        factors_x = self.get_factors_via_convolution(corrupted_x,
                                                     self.numfactors,
                                                     self.w,
                                                     self.s,
                                                     self.scope1)
        factors_y = self.get_factors_via_convolution(corrupted_y,
                                                     self.numfactors,
                                                     self.w,
                                                     self.s,
                                                     self.scope2)

        #Get hidden factors
        self.assert_dims(factors_x, factors_y, shape, self.w, self.s)
        hidden, factors_h = self.get_hidden_factors(factors_x, factors_y)

        #Get the recon losses
        recon_x_loss, self.recon_x_ = self.get_recon_loss_x(self.x, self.shape, factors_y, factors_h, self.w, self.s)
        recon_y_loss, self.recon_y_ = self.get_recon_loss_y(self.y, self.shape, factors_x, factors_h, self.w, self.s)

        #Optimizer
        self.recon_loss = recon_x_loss + recon_y_loss
        self.update_model_recon = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(self.recon_loss)
Beispiel #6
0
 def genRandomValueForFSID(self, fsid):
     retval = self.getRandomValueForFSID(fsid)
     if not retval:
         retval = utils.get_time18() + utils.get_random_string()
         self.storage.set(self.prefix + str(fsid), retval,
                          time=3600)  #随机数1个小时超时
     return retval
Beispiel #7
0
def create_weight(session, weight_unit):
    weight = Weight()
    weight.weight_unit = weight_unit
    weight.weight_value = utils.get_random_string(10)
    session.add(weight)
    session.commit()
    return weight
Beispiel #8
0
def insert_recipe():
    """ When the user clicks to add the new recipe """
    recipes = mongo.db.recipes
    image = request.files['image']
    path = ""

    """ Checks if there is an image and if that image is of the allowed filetype """
    if image and allowed_file(image.filename):
        """ Sets the path with the image and a random string to make it unique, then saves the image to that path """
        path = "static/images/" + get_random_string() + image.filename
        image.save(path)

    """ Takes the prep_time and cooking_time from the form as integers then adds them together to get the total time """
    prep_time = int(request.form.get('prep_time'))
    cooking_time = int(request.form.get('cooking_time'))
    total_time = prep_time + cooking_time

    """ Takes the required fields from the form and makes a new entry to the database """
    """ Sets the image to the path if the image exists and is allowed, if not it will set the image to none """
    recipes.insert_one(
        {
            'recipe_name': request.form.get('recipe_name'),
            'recipe_description': request.form.get('description'),
            'prep_time': prep_time,
            'cooking_time': cooking_time,
            'total_time': total_time,
            'difficulty': request.form.get('difficulty'),
            'serves': request.form.get('serves'),
            'recipe_image': f"{path}" if path else None,
            'ingredients': request.form.getlist('ingredients'),
            'methods': request.form.getlist('methods')
        }
    )
    """ Once created redirects to the Home Page """
    return redirect(url_for('get_recipes'))
Beispiel #9
0
 def get_unique_file_id(self):
     while True:
         random_string = utils.get_random_string(24)
         if random_string not in self.temp_files:
             if random_string not in self.uploaded_files:
                 self.temp_files[random_string] = None
                 return random_string
Beispiel #10
0
def generate_lines(times=1):
    lines = ""
    sample_line = "<object name='%s'/>"
    for _ in xrange(times):
        lines += sample_line % get_random_string(
            create_count_max_lines_per_xml)
    return lines
Beispiel #11
0
def create_meme(message, text, ban):
    print(ban)
    if ban:
        text = 'nao introsa vc ta banido parça'
    background = random.choice(caveras)
    image = Image.open('blank_cavera/' + background)
    draw = ImageDraw.Draw(image)
    width, height = image.size
    font_size = int(width / 10)
    #print(font_name)
    x, y = (width / 2), 200
    white = 'rgb(255, 255, 255)'
    print(text)
    texts = split_message(text)
    for line in texts:
        font_name = random.choice(fonts)
        font = ImageFont.truetype(font_name,
                                  size=font_size + random.randint(-20, 20))
        a, b, c = random.randint(0, 255), random.randint(0,
                                                         255), random.randint(
                                                             0, 255)
        color = 'rgb(%d, %d, %d)' % (a, b, c)
        diff = len(line) * font_size / 4 + random.randint(-100, 100)
        draw_border(draw, line, font, white, x - diff, y)
        draw.text((x - diff, y), line, fill=color, font=font)
        y += 60
    name = get_random_string(10) + '.png'
    image.save('caveroes/' + name)
    return name
Beispiel #12
0
def writer(entries_count, size=100, address='127.0.0.1', port=9110):
    d = DistributedDict(address, port)
    prefix = get_random_string(lenght=6)
    stub_value = 'a' * size
    for key in range(entries_count):
        d[prefix + str(key)] = stub_value
    return timer()
Beispiel #13
0
    def _submit_page(self):
        action = ActionChains(self._driver)
        action.move_by_offset(55, 105)
        action.click()
        action.perform()

        # Get started btn
        btn = '//*[@id="content"]/div/div[2]/div/div[2]/table/tbody/tr/td[1]/div/div[1]/div[2]/button'
        self._driver.find_element_by_xpath(btn).click()

        page_name = self._driver.find_element_by_xpath('//*[@id="BUSINESS_SUPERCATEGORYPageNameInput"]')
        fp_name = utils.get_random_string()
        self._delay_typing(page_name, fp_name)
        category = self._driver.find_element_by_xpath('//*[@id="js_6"]/input')
        self._delay_typing(category, 'home decor')
        sleep(random() + 1)
        for i in range(6):
            category.send_keys(Keys.ARROW_UP)
        category.send_keys(Keys.ENTER)

        # Continue btn
        self._driver.find_element_by_xpath('//*[@id="content"]/div/div[2]/div/div[2]/table/tbody/tr/td[1]/div/div[2]/div[5]/button/div/div').click()

        try:
            # Picture skip btn
            self._driver.find_element_by_xpath('//*[@id="content"]/div/div[2]/div[2]/a').click()
        except NoSuchElementException:
            self._driver.get('https://www.facebook.com/pages/?category=your_pages')
            soup = BeautifulSoup(self._driver.page_source)
            links = soup.find_all('a', attrs={'href': re.compile(fp_name[1:].replace(' ', '-'))})
            self._driver.get(links[0])
def main():
    run_id = sys.argv[1]
    max_duration = 30  # seconds
    min_time = 0.017  # seconds
    max_time = 0.2  # seconds
    overwrite = True
    if os.path.exists(f'{run_id}.gif'):
        overwrite = input("gif exists, overwrite? (y/n)")
        if overwrite.lower() != "y":
            overwrite = False

    if run_id is None or run_id == "":
        all_subdirs = [os.path.join("images", d) for d in os.listdir('images')]
        run_id = max(all_subdirs, key=os.path.getmtime)
    print(f"run_id: {run_id}")
    files = os.listdir(run_id)
    files.sort(key=natural_keys)
    [files.append(files[-1]) for _ in range(10)]
    print("loading images...")
    images = [
        imageio.imread(os.path.join(run_id, filename)) for filename in files
    ]
    duration = min(max(max_duration / len(files), min_time), max_time)
    print(f"frame duration: {duration}")
    print(f"number of images: {len(files)}")
    print(f"gif length: {duration * len(files)} seconds")
    print("Saving gif...")
    if not overwrite:
        run_id = run_id + "_" + get_random_string(2)
    imageio.mimsave(f'{run_id}.gif', images, duration=duration)
async def test_shorten():
    url = get_random_string()
    retention = timedelta(days=random.randrange(1, 1000))
    storage_mock.key = get_random_string()
    now = datetime.utcnow()

    key = await url_shortener.shorten(url, retention)

    assert storage_mock.key == key
    assert storage_mock.url == url

    delta = storage_mock.create_date - now
    if delta < timedelta(seconds=0):
        delta = -delta
    assert delta < timedelta(seconds=1)
    assert storage_mock.expiry_date == storage_mock.create_date + retention
Beispiel #16
0
def update_category():
    rand_id = utils.get_random_number(1, utils.count_rows("category"))
    rand_name = utils.get_random_string()
    utils.execute(
        """update category set name = '{RAND_NAME}' where id = {RAND_ID};""".
        format(RAND_NAME=rand_name, RAND_ID=rand_id))
    advance_time()
Beispiel #17
0
 def genRandomValueForFSID(self, fsid):
     self.cleanup()
     retval = self.storage.get(str(fsid), '')
     if not retval:
         retval = utils.get_time18() + utils.get_random_string()
         self.storage[str(fsid)] = retval
     return retval
Beispiel #18
0
def create_customer(session):
    customerAddres = CustomerAddres()
    customerAddres.customer_address_zipcode = utils.get_random_string(12)
    customerAddres.customer_address_street = utils.get_random_string(80)
    session.add(customerAddres)
    session.flush()
    customer = Customer()
    customer.customer_created = utils.get_random_date_create()
    customer.customer_cpf = utils.get_random_string(13)
    customer.customer_email = utils.get_random_string(60)
    customer.customer_name = utils.get_random_string(80)
    customer.customer_address = customerAddres
    customer_pool.append(customer)
    session.add(customer)
    session.commit()
    session.flush()
    return customer, customerAddres
Beispiel #19
0
def start(update, context):
    user = db.get_user_by_chat_id(chat_id=update.effective_chat.id)
    if user is None:
        username = update.message.from_user.first_name
        client_id = get_random_string(32)

        logger.debug('Ottengo il pin...')

        headers = {'accept': 'application/json'}
        data = {
            'strong': True,
            'X-Plex-Product': config.plex_app_name,
            'X-Plex-Client-Identifier': client_id
        }
        
        r = requests.post('https://plex.tv/api/v2/pins', headers=headers, data=data)
        reply_json = r.json()
        logger.debug(reply_json)

        auth_id     = reply_json['id']
        auth_code   = reply_json['code']

        f = furl('https://app.plex.tv/auth')
        f.args['clientID'] = client_id
        f.args['code'] = auth_code
        f.args['context[device][product]'] = config.plex_app_name

        plex_url = f.url

        plex_url = plex_url[:24] + "#" + plex_url[24:]

        message = '''
Benvenuto %s.
Visto che è la tua prima volta con me, c'è bisogno che tu acceda a Plex.
Per favore, segui i passi qua sotto:
''' % (username)

        keyboard = [
            [ InlineKeyboardButton('1) Apri Plex.tv ed effettua il login', url=plex_url) ],
            [ InlineKeyboardButton('2) Verifica il login', callback_data='login_with_plex') ]
        ]
        reply_markup = InlineKeyboardMarkup(keyboard)

        logger.debug(reply_markup)

        context.user_data['user'] = {
            'username': username,
            'chat_id': update.message.from_user.id,
            'client_id': client_id,
            'auth_id': auth_id,
            'auth_code': auth_code,
            'handler': update.message.from_user.username,
        }

        context.bot.send_message(chat_id=update.effective_chat.id, text=message, reply_markup=reply_markup).message_id

    else:
        context.bot.send_message(chat_id=update.effective_chat.id, text="Bentornato/a, %s, per favore utilizza il comando /menu" % user.username)
Beispiel #20
0
def insert_product():
    product_name = utils.get_random_string()
    product_cost = utils.get_random_number(0, 1000)
    product_amount = utils.get_random_number(0, 10000)
    utils.execute(
        """INSERT INTO product (name, cost, amount) VALUES ('{PRODUCT_NAME}', {PRODUCT_COST}, {PRODUCT_AMOUNT});"""
        .format(PRODUCT_NAME=product_name,
                PRODUCT_COST=product_cost,
                PRODUCT_AMOUNT=product_amount))
    advance_time()
Beispiel #21
0
 def get_hidden_action_factors(self, actions_onehot, target_shape):
     num_outs = reduce(lambda x, y: x * y, target_shape)
     scope = get_random_string()
     action_factors = slim.fully_connected(slim.flatten(actions_onehot),
                                           num_outs,
                                           activation_fn=None,
                                           biases_initializer=None,
                                           scope=scope)
     action_factors = tf.reshape(action_factors, shape=[-1] + target_shape)
     return action_factors, scope
Beispiel #22
0
def test_post_ok():
    srv_mock.short = get_random_string()
    long_url = get_long_url(random.randrange(200, 2000))
    retention_days = random.randrange(1, 1000)
    response = client.post(f'/?days={retention_days}',
                           long_url.encode('utf-8'))
    assert srv_mock.url == long_url
    assert srv_mock.retention == timedelta(days=retention_days)
    assert response.status_code == 200
    assert response.text == api.LINK_TEMPLATE.format(srv_mock.short)
Beispiel #23
0
def create_brand(session):
    global brand_pool
    new = _get_value_from_pool(brand_pool)
    if new is not None:
        return new
    brand = Brand()
    brand.brand_name = utils.get_random_string(80)
    brand_pool.append(brand)
    session.add(brand)
    session.commit()
    return brand
 def test_get_random_string_2(self):
     import random
     origin_using_sysrandom = utils.using_sysrandom
     origin_random = utils.random
     utils.using_sysrandom = False
     utils.random = random
     try:
         assert len(utils.get_random_string()) == 12
     finally:
         utils.using_sysrandom = origin_using_sysrandom
         utils.random = origin_random
Beispiel #25
0
    def __init__(self, db, autocommit=False, autoflush=False, **options):
        self.app = db.get_app()
        self.db = db
        self._model_changes = {}

        # session 唯一 id
        self.sid = get_random_string(length=8)
        orm.Session.__init__(
            self, autocommit=autocommit, autoflush=autoflush,
            bind=db.engine,
            binds=db.get_binds(self.app), **options)
def update_postgres_env_file(env_file):
    changes = []

    if not env_file.get("POSTGRES_USER"):
        env_file["POSTGRES_USER"] = "******" % get_random_string(16)
        changes.append("User:       %s" % env_file["POSTGRES_USER"])

    if not env_file.get("POSTGRES_PASSWORD"):
        env_file["POSTGRES_PASSWORD"] = "******" % get_random_string(80)
        changes.append("Password:   %s" % env_file["POSTGRES_PASSWORD"])

    if changes:
        env_file.save()
        print(
            "PostgreSQL configuration file has been updated with following database settings:"
        )
        print()
        print("\n".join(changes))
    else:
        print("PostgreSQL configuration file is up to date.")
 def test_get_random_string_2(self):
   import random
   origin_using_sysrandom = utils.using_sysrandom
   origin_random = utils.random
   utils.using_sysrandom = False
   utils.random = random
   try:
     assert len(utils.get_random_string()) == 12
   finally:
     utils.using_sysrandom = origin_using_sysrandom
     utils.random = origin_random
    def test_sync_sends_random_string(self, client, service_helper, leak_tracker):
        leak_tracker.set_initial_object_list()

        message = utils.get_random_string(16)

        client.send_message(message)

        event = service_helper.wait_for_eventhub_arrival(None)
        assert event.message_body == message

        leak_tracker.check_for_leaks()
Beispiel #29
0
def create_weight_unit(session):
    global weight_unit_pool
    new = _get_value_from_pool(weight_unit_pool)
    if new is not None:
        return new
    weight_unit = WeightUnit()
    weight_unit.weight_unit = utils.get_random_string(5)
    weight_unit_pool.append(weight_unit)
    session.add(weight_unit)
    session.commit()
    return weight_unit
Beispiel #30
0
def create_product_size(session):
    global product_size_pool
    new = _get_value_from_pool(product_size_pool)
    if new is not None:
        return new
    product_size = ProductSize()
    product_size.product_size_description = utils.get_random_string(150)
    product_size_pool.append(product_size)
    session.add(product_size)
    session.commit()
    return product_size
Beispiel #31
0
class OrderModel(Document):

    customer = ReferenceField(CustomerModel)
    item_ids = ListField(DictField(required=True))
    amount = IntField()
    status = StringField(required=True, max_length=50)
    date_created = DateTimeField(default=datetime.today())
    date_updated = DateTimeField(default=datetime.today())
    created_by = ReferenceField(AdminModel)
    order_id = StringField(required=True,
                           max_length=50,
                           default=get_random_string(6))
Beispiel #32
0
    def __init__(self, config_location, **kwargs):
        if not config_location.endswith("/"):
            config_location += "/"

        self.built_in_types_map = kwargs.get("types_map", SWIFT_TYPES_MAP)
        self.persist_output = kwargs.get("persist_output", False)
        self.output = None
        self.config_location = config_location
        self.file_names = []
        self.parsed_values = []
        self.file_name_key = utils.get_random_string(50)
        self.__load_files()
Beispiel #33
0
def gen_filename(file_ext):

    name = "%s%s" % (
        get_random_string(30),
        file_ext
    )

    filename = os.path.join(
        get_today_dir(),
        name
    )
    return filename
Beispiel #34
0
 def post(self, request):
     form = CreateResumeForm(request.POST)
     if form.is_valid():
         resume = form.save(commit=False)
         resume.user = request.user
         resume.access_url = get_random_string(16)
         resume.save()
         return HttpResponseRedirect(reverse('resume:update_resume',
                                             args=(resume.name,)))
     else:
         messages.error(request, 'Please correct the errors below.')
         return render(request, 'create_resume.html', {'form': form})
Beispiel #35
0
 def _get_init_db_session(self):
     """
     初始化session,往数据库session表插入session记录
     往浏览器写入sessionid
     :raise gen.Return: session_key, 字符串
     """
     while True:
         session_key = get_random_string()
         try:
             yield self.db.execute("INSERT INTO session (session_key, session_data) VALUES (%s,%s)",
                                   (session_key, Json({})))
             self.set_cookie('sessionid', session_key)
             raise gen.Return(session_key)
         except IntegrityError:
             continue
def git_create_branch(directory, git_hash, branch=None, checkout=True):
    """Creates a new branch based on a given hash. Optionally allows for specifiying
    branch name, but will generate a random branch name if none specified. Optionally
    allows to create branch without checking it out.
    """
    if not branch:
        branch = utils.get_random_string()
    if checkout:
        git_string = 'git -C {directory} checkout -b {branch} {git_hash}'.format(directory=directory,
                                                                                 git_hash=git_hash,
                                                                                 branch=branch)
    else:
        git_string = 'git -C {directory} branch {branch} {git_hash}'.format(directory=directory,
                                                                            git_hash=git_hash,
                                                                            branch=branch)
    output = get_Popen_output(git_string)
    if output:
        return branch
    return False
Beispiel #37
0
    def cast(val):
      if isinstance(val, basestring):
        if self.is_base64(val):
          mimetype = self.get_base64_mimetype(val)
          base64_string = self.get_base64_content(val)
          base64_decoded = base64.b64decode(base64_string)
          base64_string = None
          bucket = os.environ.get('GCS_BUCKET_NAME',
            app_identity.get_default_gcs_bucket_name())
          filename = utils.get_random_string(12)
          filename += str(calendar.timegm(time.gmtime()))

          import cloudstorage as gcs

          acl = None
          if self.acl:
            acl = {'x-goog-acl': self.acl}
          with gcs.open('/%s/%s' % (bucket, filename), 'w',
                        content_type=mimetype, options=acl) as gcs_file:
            gcs_file.write(base64_decoded)

          if self._local:
            return '%s/%s/%s' % (self.base_path, bucket, filename)
          access_token, _ = self.get_access_token()
          medialink_url = '%s/%s/o/%s' % (self.base_path, bucket, filename)
          medialink = urlfetch.fetch(
            method=urlfetch.GET,
            url=medialink_url,
            headers={
              'Authorization': 'Bearer %s' % access_token,
            })
          if medialink.status_code >= 200 and medialink.status_code < 300:
            return utils.decode_json(medialink.content)['mediaLink']
          return None
        elif URL_REGEX.findall(val):
          return val
        elif LOCAL_URL_REGEX.findall(val):
          return val
        else:
          raise datastore_errors.BadValueError('Expected Base64 string or '
                                               'URL, got %r.' % val)
      else:
        raise datastore_errors.BadValueError('Expected string, got %r.' % val)
 def test_get_random_string(self):
   assert len(utils.get_random_string()) == 12
Beispiel #39
0
def generate_lines(times = 1):
    lines = ""
    sample_line = "<object name='%s'/>"
    for _ in xrange(times):
        lines += sample_line % get_random_string(create_count_max_lines_per_xml)
    return lines
Beispiel #40
0
def _upload(instance, filename, path):
    today = datetime.datetime.now()
    randname = utils.get_random_string()
    file_nm, file_ex = os.path.splitext(filename)
    return path % (instance.post.author.id, today.year, today.month, today.day, randname, file_ex)
Beispiel #41
0
 def __init__(self, *args, **kwargs):
     initial = kwargs.get('initial', {})
     initial['token_value'] = utils.get_random_string()
     super(TokenAdminForm, self).__init__(*args, **kwargs)