def save_to_file(loc, X_img, file_name, name=None):
    top, right, bottom, left = loc
    face_img = X_img[top - 15:bottom + 15, left - 15:right + 15]
    pil_image = Image.fromarray(face_img)
    if name is None:
        pil_image.save(file_name + "/" + (hashids.Hashids(salt=str(uuid.uuid4()), )).encode(1, 2, 3) + ".jpg")
    else:
        pil_image.save(file_name + "/" + name + (hashids.Hashids(salt=str(uuid.uuid4()), )).encode(1, 2, 3) + ".jpg")
Exemple #2
0
    def refund(self):
        ret = self.getcustomer()

        if ret:
            for val in ret:
                req = {}
                req['txamt'] = int(val.get('txamt'))
                req['syssn'] = val.get('syssn')
                req['out_trade_no'] = int(time.time() * 10000)
                req['txdtm'] = datetime.datetime.now().strftime(
                    "%Y-%m-%d %H:%M:%S")
                #print 'val',str(val.get('userid')) == '11751'

                if str(val.get('userid')) == '11751':
                    sign = create_sign(req, TEST_APP['key'])
                    request = urllib.urlencode(req)
                    data = post(self.url, request, sign)
                else:
                    userid = val.get('userid')
                    submchnt = hashids.Hashids('qfpay').encode(11751, userid)
                    req['mchid'] = submchnt
                    sign = create_sign(req, TEST_APP['key'])
                    request = urllib.urlencode(req)
                    data = post(self.url, request, sign)
                if data.get('respcd') == '0000':
                    #print '0000s'%data
                    print 'order: %s refund success!' % req.get('syssn')
                else:
                    print 'fail%s' % data
                    print 'order: %s  refund fail! retry' % req.get('syssn')
        else:
            print '没有退款的交易!'
Exemple #3
0
    def __init__(self,
                 docker_,
                 pki_: pki.PKI,
                 stacks,
                 redis,
                 salt,
                 docker_registry='example.com',
                 flag_prefix='CTF',
                 instance_timeout=60,
                 gateway_timeout=120,
                 gateway_image='chad-gateway',
                 gateway_domain='chad-gw.sys.hacktrinity.org',
                 traefik_network='traefik',
                 network_plugin='weaveworks/net-plugin:latest_release'):
        self.ids = hashids.Hashids(salt, min_length=10)
        self.flags = util.FlagGenerator(prefix=flag_prefix)

        self.docker = docker_
        self.pki = pki_
        self.stacks = stacks
        self.redis = redis
        self.instance_timeout = instance_timeout
        self.gateway_timeout = gateway_timeout
        self.docker_registry = docker_registry
        self.gateway_image = gateway_image
        self.gateway_domain = gateway_domain
        self.traefik_network = self.docker.networks.get(traefik_network)
        self.network_plugin = network_plugin
Exemple #4
0
 def __hashids(self):
     """
     返回Hashids对象
     """
     return hashids.Hashids(SALT,
                            min_length=16,
                            alphabet='abcdefghijklmnopqrstuvwxyz1234567890')
def hashid(_id, length=6):
    '''
        用户/题目ID哈希算法
    '''
    KEY = 'yuhi.xyz'
    hasher = hashids.Hashids(salt=KEY, min_length=length)
    return hasher.encode(_id)  # 返回哈希结果
Exemple #6
0
def _create_id_hasher():
    global ID_HASHER
    if not ID_ENCRYPTION_KEY:
        raise exceptions.ConfigurationRequired(
            'You must set apilib.ID_ENCRYPTION_KEY prior to using EncryptedId fields'
        )
    ID_HASHER = hashids.Hashids(salt=ID_ENCRYPTION_KEY, min_length=8)
Exemple #7
0
    def determine_ticket_ID(self):
        """Determine ticket id either from existing subject line or from uid

        If the Subject line contains an ID, it is taken. If it doesn't, a new one is generated.
        """
        hashid = hashids.Hashids(salt=self.config.idSalt,
                                 alphabet=self.config.idAlphabet,
                                 min_length=self.config.idMinLength)

        # See if hashid is set in headers
        if self.parsed["X-Jicket-HashID"] is not None:
            self.tickethash = self.parsed["X-Jicket-HashID"]
            self.ticketid = hashid.decode(self.parsed["X-Jicket-HashID"])
        else:
            idregex = "\\[#%s([%s]{%i,}?)\\]" % (re.escape(
                self.config.idPrefix), re.escape(
                    self.config.idAlphabet), self.config.idMinLength)
            match = re.search(idregex, self.subject)
            if match:
                self.tickethash = match.group(1)
                self.ticketid = hashid.decode(self.tickethash)
            else:
                self.tickethash = hashid.encode(self.uid)
                self.ticketid = self.uid

        self.prefixedhash = self.config.idPrefix + self.tickethash
Exemple #8
0
 def trade(self,submchnt=''):
     print "----------------swipe trade-------------------------"
     out_trade_sn = int(time.time()*10000)
     req = {}
     code  = 2 #raw_input('alipay(1) or weixin(2):')
     userid  = raw_input('userid(default 11751):')
     if userid:
         submchnt = hashids.Hashids('qfpay').encode(11751,int(userid))
     if code == "1":
         busicd = '800108'
     else:
         busicd = '800208'
     req['txamt'] = raw_input('pay_amt:')
     req['auth_code'] = raw_input('auth_code:')
     req['out_trade_no'] = out_trade_sn
     req['pay_type'] = busicd
     req['txcurrcd'] = 'CNY'
     req['trade_name'] = '点餐收款xxxxxxxxxxxxxxxxx======'
     req['txdtm'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
     if submchnt:
         req['mchid'] = submchnt
     sign = create_sign(req,TEST_APP['key'])
     request  = urllib.urlencode(req)
     #print 'self.req: ', self.request_url
     result = post(self.request_url,request,sign)
     return result
Exemple #9
0
async def connect(sid, environ):
    '''
        连接事件
        @param string sid 连接标识号
        @param object environ
    '''
    global appConfig
    try:
        appId = environ['aiohttp.request'].query['app_id']
        token = environ['aiohttp.request'].query['token']
        loginId = environ['aiohttp.request'].query['loginId']
        pl = environ['aiohttp.request'].query['pl']
    except Exception as e:
        appId = None
        token = None
        loginId = None
        pl = None
        app.logger.debug(e)

    if appId == None or token == None or loginId == None or pl == None or pl not in pls:
        app.logger.debug('auth arg fail {0} {1} {2} {3} {4}'.format(appId, token, loginId, pl, pl not in pls))
        return False

    if appId not in appConfig:
        app.logger.debug('auth app_id fail {0}'.format(appId))
        return False

    hids = hashids.Hashids(salt=appId + str(appConfig[appId]['app_secret']), min_length=8, alphabet='abcdefghijklmnopqrstuvwxyz')
    userId = hids.decode(token)[0]
    if isinstance(userId, int) and userId > 0:
        return True
    return False
 def test_hashid_override_with_minimum_alphabet(self):
     alphabet = "0123456789abcdef"
     h = hashids.Hashids(alphabet=alphabet)
     a = Hashid(5, alphabet=alphabet, hashids=h)
     self.assertIsInstance(a, Hashid)
     self.assertEqual(a.id, 5)
     self.assertEqual(a.hashid, h.encode(5))
     self.assertEqual(a._alphabet, alphabet)
Exemple #11
0
 def __init__(self):
     super(HashIdsObfuscationBackend, self).__init__()
     available_settings = ['salt', 'min_length', 'alphabet']
     dikt = {}
     for setting in available_settings:
         conf = stentor_conf.OBFUSCATION_SETTINGS.get(setting, None)
         if conf:
             dikt[setting] = conf
     self.hashids = hashids.Hashids(**dikt)
Exemple #12
0
    def __init__(self, page):
        self.page = page
        self.hash = hashids.Hashids(salt=hex(id(self)), min_length=9)
        self.hash_cluster_list = []
        self.clusters = []

        self.tokens = matcher.tok.tokenize(self.page)

        self.clusterize()
        self.adjust_clusters()
        self.cluster_format()
Exemple #13
0
def encode(identifier: int, salt: Optional[str] = DEFAULT_SALT) -> str:
    """
    Hashes the given text into a unique (collision free), short, and reproducible hash-code...

    :param identifier: Any non-negative integer to generate hash from...
    :param salt: Hash salt [for reproducible and collision-free results]...

    :return:
    """
    hashids_processor = hashids.Hashids(salt=salt)
    hashed_value = hashids_processor.encode(identifier)
    return hashed_value
Exemple #14
0
 def __init__(self, min_length: int, alphabet='abcdefghijklmnopqrstuvwxyz') -> str:
     """
     :param min_length: 生成hash值字符串的最小长度
     """
     self.min_length = min_length
     # 盐值,使用项目的SECRET_KEY作为盐
     self.salt = SECRET_KEY
     self.alphabet = alphabet
     self._hashids = hashids.Hashids(
         salt=self.salt, alphabet=self.alphabet,
         min_length=self.min_length
     )
Exemple #15
0
def art():
    try:
        db = get_db()
        h = hashids.Hashids(salt=app.config['HASH_SALT'])

        # Attempt to obtain the quid id
        decoded_tuple = h.decode(request.args['q'])
        quiz_id = int(decoded_tuple[0])
        quiz = handler.get_art_quiz(db, quiz_id)

    except (KeyError, IndexError, handler.HandlerError, ValueError):
        return redirect_to_art()

    return render_template('art.html', items=quiz.items, quiz_url=request.url)
Exemple #16
0
 def update_connected_instruments(self):
     """Update the list of connected instruments
     in self.__connected_instruments and return this list."""
     hid = hashids.Hashids()
     ports_to_test = self.active_ports
     logger.info('%d ports to test', len(ports_to_test))
     # We check every active port and try for a connected SARAD instrument.
     connected_instruments = []  # a list of instrument objects
     # NOTE: The order of tests is very important, because the only
     # difference between RadonScout and DACM GetId commands is the
     # length of reply. Since the reply for DACM is longer than that for
     # RadonScout, the test for RadonScout has always to be made before
     # that for DACM.
     # If ports_to_test is specified, only that list of ports
     # will be checked for instruments,
     # otherwise all available ports will be scanned.
     for family in SaradInst.products:
         if family['family_id'] == 1:
             family_class = DosemanInst
         elif family['family_id'] == 2:
             family_class = RscInst
         elif family['family_id'] == 5:
             family_class = DacmInst
         else:
             continue
         test_instrument = family_class()
         test_instrument.family = family
         ports_with_instruments = []
         logger.info(ports_to_test)
         for port in ports_to_test:
             logger.info("Testing port %s for %s.", port,
                         family['family_name'])
             test_instrument.port = port
             if test_instrument.type_id and test_instrument.serial_number:
                 device_id = hid.encode(test_instrument.family['family_id'],
                                        test_instrument.type_id,
                                        test_instrument.serial_number)
                 test_instrument.set_id(device_id)
                 logger.info('%s found on port %s.', family['family_name'],
                             port)
                 connected_instruments.append(test_instrument)
                 ports_with_instruments.append(port)
                 if (ports_to_test.index(port) + 1) < len(ports_to_test):
                     test_instrument = family_class()
                     test_instrument.family = family
         for port in ports_with_instruments:
             ports_to_test.remove(port)
     self.__connected_instruments = connected_instruments
     return connected_instruments
    def generate_reset_code(uob):
        unique = False
        while unique == False:
            hash_obj = hashids.Hashids(salt=uuid.uuid4().get_hex())
            hid = hash_obj.encode(random.randint(0, 99), random.randint(0, 99))
            objs = PasswordManagement.objects.filter(
                reset_code=hid)  # just check the database to make sure
            if len(objs) == 0:
                unique = True
        pm = PasswordManagement()
        pm.reset_code = hid
        pm.expiry_datetime = datetime.datetime.now() + datetime.timedelta(
            seconds=20 * 60)
        pm.user = uob
        pm.save()

        return hid
Exemple #18
0
 def __init__(self, token, mongodb_host, mongodb_port):
     super().__init__()
     self.token = token
     self.MAX_MSG_LEN = 2000
     self.admin = "asm"
     self.hasher = hashids.Hashids(salt="cEDH league")
     self.logger = logging.getLogger('discord')
     self.logger.setLevel(logging.INFO)
     handler = logging.handlers.RotatingFileHandler(filename='discord.log',
                                                    encoding='utf-8',
                                                    mode='w',
                                                    backupCount=1,
                                                    maxBytes=1000000)
     handler.setFormatter(
         logging.Formatter(
             '%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
     self.logger.addHandler(handler)
     self.db = MongoClient(mongodb_host, mongodb_port).rankdb
    def __init__(
            self,
            basedir="/home/rkube/Projects/learning_xgc/logs/ml_data_case_2",
            model_name=None,
            model_dims=None,
            loss_fun=None,
            optim=None,
            lr_start=None,
            batch_size=None,
            slurm_id=None,
            epochs=None):

        assert (isdir(basedir))
        hid = hashids.Hashids(min_length=10)

        self.basedir = basedir

        if model_name is None:
            print("gridsearch_params: model_name not set")
        if model_dims is None:
            print("gridsearch_params: model_name not set")
        if loss_fun is None:
            print("gridsearch_params: loss_fun not set")
        if optim is None:
            print("gridsearch_params: optim not set")
        if lr_start is None:
            print("gridsearch_params: lr_start not set")
        if batch_size is None:
            print("gridsearch_params: lr_start not set")
        if epochs is None:
            print("gridsearch_params: lr_start not set")

        # Get a unique run id
        self._hparams = {
            "run_id": hid.encode(int(time.time())),
            "model_name": model_name,
            "model_dims": model_dims,
            "loss_fun": loss_fun,
            "optim": optim,
            "lr_start": lr_start,
            "batch_size": batch_size,
            "slurm_id": slurm_id,
            "epochs": epochs
        }
    def test_modelserializer_with_prefix(self):
        class TrackSerializer(serializers.ModelSerializer):
            id = HashidSerializerCharField(source_field="tests.Track.id")

            class Meta:
                model = Track
                fields = ("id",)

        salt = Track._meta.get_field("id").salt
        alphabet = Track._meta.get_field("id").alphabet
        min_length = Track._meta.get_field("id").min_length
        reference = hashids.Hashids(salt=salt, min_length=min_length, alphabet=alphabet)

        track = Track.objects.create()
        expected = 'albumtrack:' + reference.encode(1)
        self.assertEqual(track.id, expected)

        serializer = TrackSerializer(track)
        self.assertEqual(serializer.data["id"], expected)
Exemple #21
0
 def test_close(self):
     '''
     订单关闭: 测试冲正订单(/trade/v1/close)
     条件: 
     操作: 
     预期: 
     '''
     url = '%s/trade/v1/close' % QT_API
     import hashids
     userid = 10205
     submchnt = hashids.Hashids('qfpay').encode(11751, userid)
     param = {
         'txamt': 10,
         'mchid': submchnt,
         'syssn': '20160803998485',
         'txdtm': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
     }
     sign = create_sign(param, TEST_APP['key'])
     req = urllib.urlencode(param)
     data = post(url, req, sign)
     print data
     '''
Exemple #22
0
    def unzip_promo_code(promo_code, goods_code, type_len=4):
        promo_code = promo_code[2:]
        # 优惠码是否在黑名单里
        if redis_pool.sismember('mchnt_api_forbid_code', promo_code):
            raise ParamError('该优惠码已禁止使用')

        # 优惠码是否存在
        # code: 1,2,3,4 无限制使用的优惠码
        # code: 5,6,7,8 同一商户只能使用一次
        try:
            hids = hashids.Hashids(
                config.PROMO_KEYS[goods_code][0],
                alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789')
            code, userid, amt = hids.decode(promo_code)
            code_type, code = (code - 1) / type_len, (code %
                                                      type_len) or type_len
        except:
            log.debug(traceback.format_exc())
            raise ParamError('优惠码不存在')
        log.info('code:%s userid:%s amt:%s' % (code, userid, amt))

        return code_type, code, amt
Exemple #23
0
def hashid(_id, length=6):
    key = 'yuhi.xyz'
    hasher = hashids.Hashids(salt=key, min_length=length)
    return hasher.encode(_id)  # 返回哈希结果
Exemple #24
0
import hashids
HASH_IDS = hashids.Hashids(
    salt='cr+2488qp=f^jb8r13j@wwsq2mxyqmh#zi_y603=-)zjahxvd2')
Exemple #25
0
def _h(salt):
    return hashids.Hashids(salt)
def category(request, cat_slug=None, template_name="category.html"):

    all_cats = CustomCats().cats()
    hasher = hashids.Hashids('salty cats')
    random.seed()

    # TODO: Shoehorning this into Tendenci's directory system was a mistake because we don't need to be updating individual entries from the website since that would create discontinuity with the Google Sheet, which should be the Source of Truth. Well, "mistake" is harsh. It makes sense and still functions just fine, but it's not an optimal arrangement if I'm trying to reduce reliance on the CMS and use tools that are natural best fits for specific types of data.
    # cat_obj = DirectoryCategory.objects.filter(slug=cat)
    # directories = Directory.objects.filter(Q(sub_cat__in=cat_obj))

    directories_list = []
    directories = {}

    with open('lib/drone_hangar/static/google/directory.json', 'r') as f:
        directories_list = json.loads(f.read())

    directories = {
        hasher.encode(random.randint(1, 100000)): d
        for d in directories_list if slugify(d['category']) == cat_slug
    }

    if cat_slug == "rentals":
        with open('lib/drone_hangar/static/airbnb/airbnb_data.json', 'r') as f:
            directories.update(json.loads(f.read()))

    for i, d in enumerate(directories.keys()):
        picture_url = get_images_for_entry(directories[d].get('name'))
        web = ""

        if directories[d].get('website'):
            web = directories[d].get('website').strip('http://').strip(
                'https://').strip('www.').rstrip('/')

        services = directories[d].get('filters-services')

        directories[d].update({
            'slug':
            slugify(directories[d]['name']),
            'picture_url':
            f'http://localhost/{picture_url}',
            'web':
            web,
            'sorting':
            json.dumps({
                "category": all_cats[cat_slug]['headline'],
                "filters": {
                    'services': services,
                },
                "sorts": {
                    "name": directories[d]['name']
                }
            })
        })

    with open('lib/custom_directories/output.txt', 'w') as f:
        f.write(json.dumps(directories))

    # Get info for sorting.
    sorting_controller = {
        'callToAction':
        'Welcome to our searchable directory. Click the buttons or start typing below to find what you seek.',
        'noResultsMsg':
        'Looks like there\'s nothing that meets that requirement.'
    }

    context = {
        'cat': cat_slug,
        'hero': all_cats[cat_slug]['hero'],
        'focus': all_cats[cat_slug]['focus'],
        'size': all_cats[cat_slug]['size'],
        'headline': all_cats[cat_slug]['headline'],
        'directories': directories,
        'sorting_controller': sorting_controller,
        'all_cats': all_cats
    }

    context.update({'full_context': context})

    return render_to_resp(request=request,
                          template_name=template_name,
                          context=context)
Exemple #27
0
def set_exercise_slug(sender, instance, **kwargs):
    if not instance.slug:
        h = hashids.Hashids(salt=settings.HASHIDS_SALT)
        instance.slug = h.encode(instance.id)
        instance.save()
Exemple #28
0
def hex2dec(string_num):
    return str(int(string_num.upper(), 16))


base = [str(x)
        for x in range(10)] + [chr(x) for x in range(ord('a'),
                                                     ord('a') + 6)]


def dec2hex(string_num):
    num = int(string_num)
    mid = []
    while True:
        if num == 0: break
        num, rem = divmod(num, 16)
        mid.append(base[rem])

    return ''.join([str(x) for x in mid[::-1]])


ALPHABET = 'abcdef1234567890'
hashid = hashids.Hashids(alphabet=ALPHABET)
for i in range(1, 99999):
    userid = i
    s = hashid.encode(userid)
    print(s)
    print(userid, s, hex2dec(s), dec2hex(hex2dec(s)),
          hashid.decode(dec2hex(hex2dec(s))))

    # print(s.encode('hex'))
Exemple #29
0
def _sample_stage_token_hashid():
    return hashids.Hashids(salt='SampleStageToken', min_length=5)
Exemple #30
0
def decode_permalink_id(key: str, salt: str) -> int:
    obj = hashids.Hashids(salt, min_length=HASHIDS_MIN_LENGTH)
    ids = obj.decode(key)
    if len(ids) == 1:
        return ids[0]
    raise KeyValueParseKeyError(_("Invalid permalink key"))