Esempio n. 1
0
def gen_doc(doc='cpf'):
    if doc == 'cpf':
        return rstr.rstr('1234567890', 11)
    elif doc == 'cnpj':
        return rstr.rstr('1234567890', 14)
    elif doc == 'rg':
        return rstr.rstr('1234567890', 10)
 def test_add_contacts(self):
     #用上面的方法生成shelve文件,就可以直接引用了
     db=shelve.open('cookies')
     cookies = db['cookie']
     db.close()
     #开始正常访问
     self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
     for cookie in cookies:
         if 'expiry' in cookie.keys():
             cookie.pop('expiry')
         self.driver.add_cookie(cookie)
     self.driver.refresh()
     # time.sleep(3)
     element = self.driver.find_element(By.CSS_SELECTOR, ".index_service_cnt_itemWrap:nth-child(1)")
     element.click()
     time.sleep(2)
     #利用rstr生成随机字符串
     username=rstr.rstr('abcdefghijklmn')
     memberAdd_acctid=rstr.rstr('1234567890',1,10)
     #用exrex类和正则表达式生成手机号
     memberAdd_phone=exrex.getone(r'(13[0-9]|14[5|7]|15[4]|18[0-9]|17[5-8])(\d{8})')
     #模拟用户操作添加成员
     self.driver.find_element(By.CSS_SELECTOR,'#username').send_keys(username)
     self.driver.find_element(By.CSS_SELECTOR,'#memberAdd_acctid').send_keys(memberAdd_acctid)
     self.driver.find_element(By.CSS_SELECTOR,'#memberAdd_phone').send_keys(memberAdd_phone)
     self.driver.find_element(By.CSS_SELECTOR,'.js_member_editor_form>div:nth-child(3)>a:nth-child(2)').click()
     #如果保存成功该元素的文本信息是“保存成功”
     text=self.driver.find_element(By.CSS_SELECTOR, '#js_tips').text
     assert text == "保存成功"
Esempio n. 3
0
    def insert_random_seller(self, repeat=qsellers):
        ''' Inserir registros com valores randomicos '''

        seller_list = []
        for _ in range(repeat):
            d = gen_timestamp(2014, 2015) + '+00'
            fname = names.get_first_name()
            lname = names.get_last_name()
            email = fname[0].lower() + '.' + lname.lower() + '@example.com'
            birthday = gen_timestamp() + '+00'
            active = rstr.rstr('01', 1)
            internal = rstr.rstr('01', 1)
            commissioned = rstr.rstr('01', 1)
            commission = 0.01
            seller_list.append(
                (gen_cpf(), fname, lname, email, gen_phone(), birthday, active, internal, commissioned, commission, d, d))
        try:
            self.db.cursor.executemany("""
            INSERT INTO vendas_seller (cpf, firstname, lastname, email, phone, birthday, active, internal, commissioned, commission, created, modified)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
            """, seller_list)
            self.db.commit_db()
            print("Inserindo %s registros na tabela vendas_seller." % repeat)
            print("Registros criados com sucesso.")
        except sqlite3.IntegrityError:
            print("Aviso: O email deve ser único.")
            return False
Esempio n. 4
0
def gen_doc(doc='cpf'):
    if doc == 'cpf':
        return rstr.rstr('1234567890', 11)
    elif doc == 'cnpj':
        return rstr.rstr('1234567890', 14)
    elif doc == 'rg':
        return rstr.rstr('1234567890', 10)
Esempio n. 5
0
def get_negative_samples(target_regex, regex_set, set_size):
    neg_samples = set()
    early_stop_cnt = 0
    while len(neg_samples) < set_size:
        random_regex = random.choice(regex_set)
        if early_stop_cnt == 30:
            break
        if target_regex == random_regex:
            early_stop_cnt += 1
            continue
        target_dfa = str2regexp(target_regex).toDFA()
        random_dfa = str2regexp(random_regex).toDFA()
        negative_dfa = ~target_dfa & random_dfa
        if negative_dfa.witness() is None:
            rand_str = rstr.rstr([rstr.rstr('0123', 0, 4) for _ in range(30)],
                                 7)
            if not membership(target_regex, rand_str):
                neg_samples.add(rand_str)
                continue
            early_stop_cnt += 1
            continue
        neg_samples.add(negative_dfa.witness())
    neg_samples = list(neg_samples)
    neg_samples.sort()
    return neg_samples
Esempio n. 6
0
def generateSPNegative(alphabet, minWordLength, maxWordLength, sampleAmount, checkForbidden):
    # GENERATE POSITIVE SAMPLES
    negSamples = []
    samplePerLength = []
    while len(samplePerLength)<(sampleAmount*minWordLength):
        word = rstr.rstr(alphabet,minWordLength)
        # check if word is forbidden
        forbidden = checkForbidden(word)
        if forbidden:
            samplePerLength.append(word)
    x = minWordLength+1
    negSamples+=samplePerLength
    samplePerLength = []
    while x < maxWordLength:
        word = rstr.rstr(alphabet, x)
        # check if word is forbidden
        forbidden = checkForbidden(word)
        if forbidden:
            samplePerLength.append(word)
            print(word, x, maxWordLength,len(samplePerLength), sampleAmount)
        if len(samplePerLength) == sampleAmount:
            x += 1
            negSamples+=samplePerLength
            samplePerLength = []
    return negSamples
Esempio n. 7
0
def gerar_telefone():
    """
    Pega um telefone aleatório no formato (xx) xxxxx-xxxx
    """

    return '({0} {1}-{2})'.format(rstr.rstr('1234567890', 2),
                                  rstr.rstr('1234567890', 5),
                                  rstr.rstr('1234567890', 4))
Esempio n. 8
0
 def generateProperEmail():
     improperDotPattern = re.compile(
         '^\.')  # to verify if dot is not on beginning of returned string
     while True:
         email = '{0}{1}@{2}.{3}'.format(
             choice(string.ascii_letters),
             rstr.rstr(string.ascii_letters + string.digits + '-_.', 2, 20),
             rstr.rstr(string.ascii_letters + string.digits),
             choice(['pl', 'com', 'net', 'uk', 'gov', 'us']))
         if not improperDotPattern.match(email):
             return email
Esempio n. 9
0
def createMatch():
    global accounts_df, config
    password = str(request.args.get('password'))
    symbol = str(rstr.rstr('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 3))
    maximum = str(request.args.get('maximum'))

    pass
    if (password == "Queteimporta123" and symbol != None and maximum != None):
        unlockwallet()

        new_token = subprocess.Popen([
            'cleos', '-u',
            str(config['JUNGLEENDPOINT']), 'push', 'action',
            str(config['CONTRACTOWNER']), 'create',
            '[ ' + str(config['CONTRACTOWNER']) + ', "' + str(maximum) + ' ' +
            str(symbol) + '"]', '-p',
            str(config['CONTRACTOWNER']) + '@active'
        ],
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.STDOUT)
        new_token_out, new_token_err = new_token.communicate()
        if (str(new_token_out).find("transaction executed") >= 0):
            issue = subprocess.Popen([
                'cleos', '-u',
                str(config['JUNGLEENDPOINT']), 'push', 'action',
                str(config['CONTRACTOWNER']), 'issue',
                '[ ' + str(config['CONTRACTOWNER']) + ', "' + str(maximum) +
                ' ' + str(symbol) + '", "issue tokens"]', '-p',
                str(config['CONTRACTOWNER']) + '@active'
            ],
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.STDOUT)
            issue_out, issue_err = issue.communicate()
            if (str(issue_out).find("transaction executed") >= 0):
                match = str(rstr.rstr('0123456789', 10))
                new_match = pd.DataFrame({
                    'uid': [],
                    'account': [],
                    'start_time': [],
                    'balance': []
                })
                new_match.to_csv(match + '.csv', index=False)
                config['TOKEN'] = symbol
                with open('configuration.yml', 'w') as f:
                    yaml.dump(config, f)
                response = {"match": match}
            else:
                response = {"error": "error issuing tokens"}
        else:
            response = {"error": new_token_out}

    response = str(response).replace("\'", "\"")
    return response
Esempio n. 10
0
 def generateWrongEmail():
     improperCharacters = '\():;"><[]@~ \t\n\r\x0b\x0c'
     case = randint(1, 2)
     if case == 1:
         return '{0}@{1}.{2}'.format(
             rstr.rstr(string.printable,
                       include=choice(improperCharacters),
                       exclude='\n\t\r"'),
             rstr.rstr(string.printable,
                       include=choice(improperCharacters),
                       exclude='\n\t\r"'),
             choice(['pl', 'com', 'net', 'uk', 'gov', 'us']))
     else:
         return rstr.rstr(string.printable, exclude='\n\t\r"')
Esempio n. 11
0
    def test_message_len(self):
        message_len = Message.MAX_MESSAGE_LEN + 1
        self.message = Message(rstr.rstr(string.ascii_letters,
                                         message_len))
        self.assertEqual(len(self.message.message), Message.MAX_MESSAGE_LEN)

        message_len = Message.MAX_MESSAGE_LEN
        self.message = Message(rstr.rstr(string.ascii_letters,
                                         message_len))
        self.assertEqual(len(self.message.message), Message.MAX_MESSAGE_LEN)

        message_len = Message.MAX_MESSAGE_LEN - 1
        self.message = Message(rstr.rstr(string.ascii_letters,
                                         message_len))
        self.assertEqual(len(self.message.message), message_len)
Esempio n. 12
0
def gerar_cpf():
    """
    Pega uma string com 11 caracteres númericos para
    representar o CPF de forma aleatória.
    """

    return rstr.rstr('1234567890', 11)
Esempio n. 13
0
def gen_urls():
    reg_str = 'ABC'
    reg_str = r'[A-Z]\d[A-Z] \d[A-Z]\d'
    reg_str = '!"#$%&\'()*+,-./@:;<=>[\\]^_`{|}~'
    #reg_str = "((https?://|ftp://|www\.|[^\s:=]+@www\.).*?[a-z_\/0-9\-\#=&])(?=(\.|,|;|\?|\!)?(\"|'|«|»|\[|\s|\r|\n|$))"
    #reg_str = "https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,}"
    #reg_str = "http?[12345]"
    #reg_str = "(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?"
    #reg_str = "(\b(https?)://)?www\.[-A-Za-z0-9+?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]"
    reg_str = "^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$"
    reg_str = 'http://{0}.{1}/{2}/?{3}'.format(rstr.domainsafe(),
                                               rstr.letters(3), rstr.urlsafe(),
                                               rstr.urlsafe())
    #reg_str = "((https?://)?)www\.(([a-z_0-9\-\#=&]{4,10})\.){1,3}(com|cn|org|edu|com\.cn|net|xin|cc|tech|top|info|gov)"
    #reg_str = "((https?://)?)(www\.)?(([a-z_0-9\-]{4,10})\.){1,3}(com|cn|org|edu|com\.cn|net|xin|cc|tech|top|info|gov)"
    #reg_str = "((https?://)?)(www\.)?(([a-z_0-9\-]{4,10})\.){1,2}(com|cn|org|edu|com\.cn|net|xin|cc|tech|top|info|gov)"

    #reg_str = "((https?://)?)(www\.)?(([a-z_0-9\-]{3,6})\.){1,2}(com|cn|org|edu|com\.cn|net|xin|cc|tech|top|info|gov)"

    #reg_str_1 = "((https?://)?)(www\.)?(([a-z_0-9\-]{4,8})\.){1}(com|cn|org|edu|com\.cn|net|xin|cc|tech|top|info|gov)"
    #reg_str_2 = "((https?://)?)(www\.)?(([a-z_0-9\-]{3,4})\.){2}(com|cn|org|edu|com\.cn|net|xin|cc|tech|top|info|gov)"

    s = rstr.rstr(reg_str, 6, 20)
    s = rstr.xeger(reg_str)
    #print s
    return s
Esempio n. 14
0
 def part_format_generator(self, size, part_number):
     print("---- PART NUMBER GEN FUNCTION START ------")
     if part_number == 1:
         print("for part 1 mode")
         part_number_generated = ''.join(
             rstr.rstr("abcdefghijklmABCDEFGHIJKLM01234", size))
         print("part number generated 1", part_number_generated)
         print("---- PART NUMBER GEN FUNCTION END ------")
         return part_number_generated
     elif part_number == 2:
         print("for part 2 mode")
         part_number_generated = ''.join(
             rstr.rstr("nopqrstuvwxyzNOPQRSTUVWXYZ56789", size))
         print("part number generated 2", part_number_generated)
         print("---- PART NUMBER GEN FUNCTION END ------")
         return part_number_generated
 def generate(self):
     if self.enum:
         return random.choice(self.enum)
     elif self.pattern:
         return rstr.xeger(self.pattern)
     else:
         return rstr.rstr(string.letters+string.digits,self.minLength,self.maxLength)
Esempio n. 16
0
class DataGenerator:
    phoneNumberReg = r'^[1-9][0-9]{8,12}(#[0-9]{1,6}?$)'
    mobileNumberReg = r'^[1-9][0-9]{8,12}$'
    improperPhoneNumberRegs = [
        r'^\+[1-9][0-9]{0,2} 0[0-9]{8,12}(#[0-9]{1,6}?$)',
        r'^[0-9]{8,12}(#[0-9]{1,6}?$)',
        r'^\+[1-9][0-9]{3,4} [1-9][0-9]{8,12}(#[0-9]{1,6}?$)',
        r'^\+[1-9][0-9]{0,2} [1-9][0-9]{13,15}(#[0-9]{1,6}?$)'
    ]
    improperMobileNumberRegs = [
        r'^\+[1-9][0-9]{0,2} 0[0-9]{8,12}$',
        r'^\+[1-9][0-9]{3,5} [1-9][0-9]{8,12}$',
        r'^\+[1-9][0-9]{0,2} [1-9][0-9]{13,15}$'
    ]

    @staticmethod
    def generateProperName(minLength=1, maxLength=35):
        return rstr.rstr(string.ascii_letters, minLength,
                         maxLength).strip().replace('  ', '')

    def generateWrongName(self, maxLength=35):
        case = randint(1, 2)
        if case == 1:
            improperCharacters = '!@#$%^&*()_+=[]{}\|/?;:.,><`~'
            return 'chars', \
                   rstr.rstr(string.ascii_letters + " '-" + string.digits, 1, maxLength,
                             include=choice(improperCharacters)).strip()
        else:
            return 'length', \
                   self.generateProperName(minLength=maxLength + 1, maxLength=maxLength + 5)
 def generate(self):
     if self.enum:
         return random.choice(self.enum)
     elif self.pattern:
         return rstr.xeger(self.pattern)
     else:
         return rstr.rstr(string.letters + string.digits, self.minLength,
                          self.maxLength)
Esempio n. 18
0
 def big_key_nonce_generator(self):
     print("---- BIG KEY NONCE GEN FUNCTION START ------")
     self.big_key_original = rstr.rstr(
         'azertyuiopmlkjhgfdsqwxcvbnAZERTYUIOPMLKJHGFDSQWXCVBN0123456789',
         16000)
     self.big_key_modified = self.big_key_original
     print("big key original : ", self.big_key_original[:15])
     print("big key original len : ", len(self.big_key_original))
     print("big key modified len : ", len(self.big_key_modified))
     self.big_nonce_original = rstr.rstr(
         'azertyuiopmlkjhgfdsqwxcvbnAZERTYUIOPMLKJHGFDSQWXCVBN0123456789',
         16000)
     self.big_nonce_modified = self.big_nonce_original
     print("big nonce original : ", self.big_nonce_original[:15])
     print("big nonce original len : ", len(self.big_nonce_original))
     print("big nonce modified len : ", len(self.big_nonce_modified))
     print("---- BIG KEY NONCE GEN FUNCTION END ------")
     return self.big_key_original, self.big_nonce_original
def get_dict(passport, hull, have_object=True):
    """
    {"24631331976_defa3bb61f_k.jpg668058":{
        "fileref":"",
        "size":668058,
        "filename":"24631331976_defa3bb61f_k.jpg",
        "base64_img_data":"",
        "file_attributes":{},
        "regions":{
            "0":{
                "shape_attributes":{
                    "name":"polygon",
                    "all_points_x":[916,913,905,889,868,836,809,792,789,784,777,769,767,777,786,791,769,739,714,678,645,615,595,583,580,584,595,614,645,676,716,769,815,849,875,900,916,916],
                    "all_points_y":[515,583,616,656,696,737,753,767,777,785,785,778,768,766,760,755,755,743,728,702,670,629,588,539,500,458,425,394,360,342,329,331,347,371,398,442,504,515]
                    },
                "region_attributes":{}
                }
            }
        },
    ......
    }
    """
    result = {}
    img_name = rstr.rstr(string.ascii_lowercase, 10) + ".jpg"
    print(img_name)
    h, w = passport.shape[:2]
    size = h * w
    all_points_x = list([int(x[0][0]) for x in hull])
    all_points_y = list([int(x[0][1]) for x in hull])
    dict = {
        "fileref": "",
        "size": size,
        "filename": img_name,
        "base64_img_data": "",
        "file_attributes": {},
        "regions": {
            "0": {
                "category_id": 0,
                "shape_attributes": {
                    "name": "polygon",
                    "all_points_x": all_points_x,
                    "all_points_y": all_points_y
                },
                "region_attributes": {}
            }
        }
    }

    if not have_object:
        dict["regions"]["0"]["category_id"] = 1

    result[img_name + str(size)] = dict
    return img_name, result
Esempio n. 20
0
 def add_new_subdir(self):
     max_retries = 5
     retry_count = 0
     while True:
         retry_count += 1
         if retry_count > max_retries:
             raise Exception(
                 'cannot generate an unused subdir. check if random is working as expected'
             )
         new_subdir = rstr(digits + ascii_lowercase + ascii_uppercase, 10)
         if new_subdir not in self._subdirs_:
             self._subdirs_.append(new_subdir)
             break
Esempio n. 21
0
    def handle(self, *args, **options):
        u""" Заполнение данных по шаблону """

        try:
            count = options['count']
            assert count <= 300
        except AssertionError:
            raise CustomCommandError

        departments = Department.objects.all()

        for i in xrange(0, count):
            first_name = rstr.rstr(u'АБВГДЕЗИКЛМНОПРСТУФХЭЮЯ',
                                   random.randint(4, 16))
            last_name = rstr.rstr(u'АБВГДЕЗИКЛМНОПРСТУФХЭЮЯ',
                                  random.randint(4, 16))

            self.stdout.write(u'Добавление :{} {}'.format(
                first_name, last_name))

            #  TODO: Can't bulk create a multi-table inherited model
            Employees(
                first_name=first_name,
                last_name=last_name,
                date_birth=datetime.datetime.today(),
                phone_number='+' + rstr.rstr('1234567890', 12),
                department=random.choice(departments),
                employment_date=random_date(datetime.date(1999, 12, 12),
                                            datetime.date(2017, 01, 01)),
                date_of_dismissal=random_date(datetime.date(2017, 01, 01),
                                              datetime.date(2050, 01, 01)),
                position=random.randint(PositionEnum.ADMINISTRATOR,
                                        PositionEnum.BROKER),
                username=first_name + '_' + last_name,
                password=rstr.rstr(string.ascii_uppercase + string.digits, 10),
                email=first_name + '@employee.com').save()

        self.stdout.write(u'{} записей было добавлено'.format(count))
Esempio n. 22
0
    def toMask(self, loitgfont, txt, otherlines=False):
        if loitgfont.fontpath == '/home/loitg/Downloads/fonts/fontss/receipts/westgate/PKMN-Mystery-Dungeon.ttf' and any(c in txt for c in ['<','>',';','!','$','#','&','/','`','~','@','%','^','*','.']):
            return None, None
        if loitgfont.fontpath == '/home/loitg/Downloads/fonts/fontss/receipts/general_fairprice/LEFFC2.TTF' and any(c.isdigit() for c in txt):
            return None, None
        if (loitgfont.fontpath == '/home/loitg/Downloads/fonts/fontss/receipts/general_fairprice/PRINTF Regular.ttf')\
             or (loitgfont.fontpath == '/home/loitg/Downloads/fonts/fontss/receipts/dotted/fake receipt.ttf'):
            txt = txt.upper()
        above = rstr.rstr('ABC0123456789abcdef ', len(txt))
        below = rstr.rstr('ABC0123456789abcdef ', len(txt))
        multilines = above + '\n' + txt + '\n' + below
        if otherlines:
            txt_arr, _, bbs = self.renderfont.render_multiline(loitgfont.font, multilines , 0.3, 0.2, 1)
#             angle = np.random.rand() * 3 + 3
#             if np.random.rand() < 0.5: angle = -angle
#             txt_arr= rotate_bound(txt_arr,angle)
        else:
            txt_arr, _, bbs = self.renderfont.render_multiline(loitgfont.font, multilines , 0.05, 0.5, 1)
#             angle = np.random.randn() * 2
#             if np.random.rand() < 0.5 and abs(angle) > 1 and abs(angle) < 10:
#                 txt_arr= rotate_bound(txt_arr,angle)

        angle = np.random.randn() * 3
        if np.random.rand() < 0.4:
            txt_arr= rotate_bound(txt_arr,angle)            
        
        newwidth = int(txt_arr.shape[1]*loitgfont.getRatio())
        if np.random.rand() < 0.4:
            found = re.search( r'\d\.\d\d', txt)
            if found:
                newwidth *= 2
            elif any(c in txt for c in receiptgenline.TOTAL_KEYS) or \
                any(c.upper() in txt for c in receiptgenline.TOTAL_KEYS):
                newwidth *= 2
        txt_arr = cv2.resize(txt_arr,(newwidth, txt_arr.shape[0]))
        return txt_arr, txt
Esempio n. 23
0
def create_regular_expression(a1, a2, a3, a4):
    """
    creates regular expression: digits+a1+digits+a2+digits+a3+digits+a4+digits
    notice - the default length of rstr is 1-10 (so the avg is 5) so the expression should
    be in length of 9*5=  45 +-
    :param a1: first separator
    :param a2: second separator
    :param a3: third separator
    :param a4: fourth separator
    :return: regular expression: [1-9]+a1+[1-9]+a2+[1-9]+a3+[1-9]+a4+[1-9]+
    """
    temp = rstr.rstr(string.digits)
    temp += rstr.rstr(a1)
    temp += rstr.rstr(string.digits)
    temp += rstr.rstr(a2)
    temp += rstr.rstr(string.digits)
    temp += rstr.rstr(a3)
    temp += rstr.rstr(string.digits)
    temp += rstr.rstr(a4)
    temp += rstr.rstr(string.digits)
    return temp
Esempio n. 24
0
def generateSPPositive(alphabet, sampleAmount, checkForbidden, minWordLength, maxWordLength):
    # GENERATE POSITIVE SAMPLES
    posSamples = []
    samplePerLength = []
    x = minWordLength
    while x < maxWordLength:
        word = rstr.rstr(alphabet, x)
        # check if word is forbidden
        forbidden = checkForbidden(word)
        if not forbidden:
            samplePerLength.append(word)
            print(word, x, maxWordLength,len(samplePerLength), sampleAmount)        
        if len(samplePerLength) == sampleAmount:
            x += 1
            posSamples+=samplePerLength
            samplePerLength = []
    return posSamples
Esempio n. 25
0
    def insert_random_product(self, repeat=qproducts):
        product_list = []
        for i in range(repeat):
            imported = rstr.rstr('01', 1)
            # escolha personalizada de produtos fora de linha
            if i % 26 == 0:
                if i > 0:
                    outofline = '1'
                else:
                    outofline = '0'
            else:
                outofline = '0'

            ncm = gen_ncm()
            brand = random.randint(1, 20)
            price = float(gen_decimal(4, 2))

            ipi = 0

            if imported == '1':
                ipi = float(gen_ipi())
                if ipi > 0.5:
                    ipi = ipi - 0.5

            stock = random.randint(1, 999)
            stock_min = random.randint(1, 20)

            f = io.open('products.txt', 'rt', encoding='utf-8')
            linelist = f.readlines()

            product = linelist[i].split(',')[0]
            product_list.append(
                (imported, outofline, ncm, brand, product, price, ipi, stock, stock_min))
        try:
            self.db.cursor.executemany("""
            INSERT INTO vendas_product (imported, outofline, ncm, brand_id, product, price, ipi, stock, stock_min)
            VALUES (?,?,?,?,?,?,?,?,?)
            """, product_list)
            self.db.commit_db()
            print("Inserindo %s registros na tabela vendas_product." % repeat)
            print("Registros criados com sucesso.")
        except sqlite3.IntegrityError:
            print("Aviso: O produto deve ser único.")
            return False
Esempio n. 26
0
def g():
    if request.method == 'POST':

        desturl = request.form["desturl"]

        parsed_url = urlparse(desturl)

        real_filename = parsed_url.path.split('/')[-1].strip()

        if parsed_url.scheme:
            filename = rstr.rstr('abcdef0123456789', 8, 12)
            try:
                urlretrieve(desturl, filename)
            except:
                #abort(401, "Something went wrong")
                pass

            crypt_filename = filename + file_ext
            stream = open(filename, "rb")

            try:
                gpg.encrypt_file(stream,
                                 passphrase=passphrase,
                                 recipients=None,
                                 symmetric='AES256',
                                 output=crypt_filename,
                                 armor=False)
            except:
                #abort(401, "Something went wrong")
                pass

            move(crypt_filename, 'download')
            stream.close()
            os.remove(filename)

            return render_template("download.html",
                                   crypt_filename=crypt_filename,
                                   real_filename=real_filename)

        return "This is not a URL: " + desturl
    else:
        return "error"
def gen_phone():
    return '({0}) {1}-{2}'.format(
        rstr.rstr('1234567890', 2),
        rstr.rstr('1234567890', 4),
        rstr.rstr('1234567890', 4))
Esempio n. 28
0
def randstr(len):
    return rstr.rstr(_RSTRSET, len)
Esempio n. 29
0
def gen_doc(length=11):
    return rstr.rstr('1234567890', length)
Esempio n. 30
0
def randomstring():
    return rstr(digits + ascii_lowercase + ascii_uppercase, 10)
Esempio n. 31
0
File: main.py Progetto: dalma6/tutti
"""
    get params:
        limit -- number of items per page
        with_all_regions -- do we want items from all regions of Switzerland
"""
params = {
    'limit': '30',
    'with_all_regions': 'true',
}

"""
    generate a random string out of alphabet letters and digits in format 7-4-4-4-12 
    where e.g. 7 is the number of characters in a substring
"""
pattern = 'abcdefghijklmnopqrstuvwxyz0123456789'
x_tutti_hash = rstr.rstr(pattern, 7) + '-' + rstr.rstr(pattern, 4) + '-' + rstr.rstr(pattern, 4) + '-' \
               + rstr.rstr(pattern, 4) + '-' + rstr.rstr(pattern, 12)
"""
    headers for the get request:
        X-Tutti-Hash -- session token
"""
headers = {
    'X-Tutti-Hash': x_tutti_hash,
    'Accept-Encoding': 'gzip, deflate'
}

"""
    send first get request to the api, get info about items and dump them into a .txt file
"""
with open('out.txt', 'w') as outfile:
    g.go("https://www.tutti.ch/api/v10/list.json?" + urllib.parse.urlencode(params), headers=headers)
def gen_phone():
    # gera um telefone no formato (xx) xxxx-xxxx
    return '({0}) {1}-{2}'.format(
        rstr.rstr('1234567890', 2),
        rstr.rstr('1234567890', 4),
        rstr.rstr('1234567890', 4))
def gen_cpf():
    # gera uma string com 11 caracteres numericos
    return rstr.rstr('1234567890', 11)
Esempio n. 34
0
def gen_ncm():
    return rstr.rstr('123456789', 8)
Esempio n. 35
0
 def test_rstr(self):
     assert re.match(r"^[ABC]+$", rstr.rstr("ABC"))
Esempio n. 36
0
 def generate_new_password(self):
     return rstr.rstr(string.digits+string.ascii_letters, 6, 6)
def gen_cpf():
    return rstr.rstr('1234567890', 11)
Esempio n. 38
0
 def generateProperName(minLength=1, maxLength=35):
     return rstr.rstr(string.ascii_letters, minLength,
                      maxLength).strip().replace('  ', '')
Esempio n. 39
0
                rstr.rstr(string.printable,
                          include=choice(improperCharacters),
                          exclude='\n\t\r"'),
                choice(['pl', 'com', 'net', 'uk', 'gov', 'us']))
        else:
            return rstr.rstr(string.printable, exclude='\n\t\r"')

    def generateProperPhoneNumber(self):
        return rstr.xeger(self.phoneNumberReg)

    def generateWrongPhoneNumber(self):
        case = randint(1, 2)
        if case == 1:
            return rstr.xeger(choice(self.improperPhoneNumberRegs))
        else:
            return rstr.rstr(string.printable,
                             include=choice(string.ascii_letters),
                             exclude='\n\t\r"')

    def generateProperMobileNumber(self):
        return rstr.xeger(self.mobileNumberReg)

    def generateWrongMobileNumber(self):
        case = randint(1, 2)
        if case == 1:
            return rstr.xeger(choice(self.improperMobileNumberRegs))
        else:
            return rstr.rstr(string.printable,
                             include=choice(string.ascii_letters),
                             exclude='\n\t\r"')