Esempio n. 1
0
    def profile(self):
        if request.args.get('id') and current_user.has_role('admin'):
            user = get_object_or_404(User, id=request.args.get('id'))
        else:
            user = current_user

        if request.method == "POST":
            for setting in request.form:
                if request.form[setting]:
                    user.settings[setting] = request.form[setting]

            user.save()

            for setting in request.form:
                if not request.form[setting]:
                    user.settings.pop(setting, None)

            user.save()

        if current_user.has_role('admin') and user.id != current_user.id:
            return render_template(
                "user/profile_admin.html",
                available_settings=User.get_available_settings(),
                user=user)
        else:
            return render_template(
                "user/profile.html",
                available_settings=User.get_available_settings(),
                user=user)
Esempio n. 2
0
    def __init__(self, *args, **kwargs):
        super(OneShotAnalytics, self).__init__(*args, **kwargs)

        if hasattr(self, 'settings'):
            for setting_id, setting in self.settings.items():
                User.register_setting(setting_id, setting['name'],
                                      setting['description'])
Esempio n. 3
0
def user_test(wholeTree=True):
    patrik = User()
    patrik.login("patrikch", "123456")
    print(patrik.is_logged)
    print(str(patrik))
    tree = patrik.project_tree
    printTree(tree)
Esempio n. 4
0
    def profile(self):
        if request.args.get('id') and current_user.has_role('admin'):
            user = get_object_or_404(User, id=request.args.get('id'))
        else:
            user = current_user

        if request.method == "POST":
            for setting in request.form:
                if request.form[setting]:
                    user.settings[setting] = request.form[setting]

            user.save()

            for setting in request.form:
                if not request.form[setting]:
                    user.settings.pop(setting, None)

            user.save()

        if current_user.has_role('admin') and user.id != current_user.id:
            return render_template(
                "user/profile_admin.html",
                available_settings=User.get_available_settings(),
                user=user)
        else:
            return render_template(
                "user/profile.html",
                available_settings=User.get_available_settings(),
                user=user)
Esempio n. 5
0
    def __init__(self, login, password,
                 like_per_day=1000,
                 media_max_like=10,
                 media_min_like=0,
                 follow_per_day=0,
                 follow_time=5 * 60 * 60,
                 unfollow_per_day=0,
                 comments_per_day=0,
                 tag_list=['cat', 'car', 'dog'],
                 max_like_for_one_tag=5,
                 log_mod=0):

        super(InstaBot, self).__init__()

        self.time_in_day = 24 * 60 * 60
        # Like
        self.like_per_day = like_per_day
        if self.like_per_day != 0:
            self.like_delay = self.time_in_day / self.like_per_day

        # Follow
        self.follow_time = follow_time
        self.follow_per_day = follow_per_day
        if self.follow_per_day != 0:
            self.follow_delay = self.time_in_day / self.follow_per_day

        # Unfollow
        self.unfollow_per_day = unfollow_per_day
        if self.unfollow_per_day != 0:
            self.unfollow_delay = self.time_in_day / self.unfollow_per_day

        # Comment
        self.comments_per_day = comments_per_day
        if self.comments_per_day != 0:
            self.comments_delay = self.time_in_day / self.comments_per_day

        # Don't like if media have more than n likes.
        self.media_max_like = media_max_like
        # Don't like if media have less than n likes.
        self.media_min_like = media_min_like
        # Auto mod seting:
        # Default list of tag.
        self.tag_list = tag_list
        # Get random tag, from tag_list, and like (1 to n) times.
        self.max_like_for_one_tag = max_like_for_one_tag

        self.media_by_tag = []

        log_string = 'Insta Bot v1.1 start at %s:' % \
                     (datetime.datetime.now().strftime("%d.%m.%Y %H:%M"))
        logger.info(log_string)

        session = requests.Session()
        # create a new user and log the user into the session
        self.user = User(session, login, password)
        self.user.login()
        self.API = API(self.user)

        signal.signal(signal.SIGTERM, self.cleanup)
        atexit.register(self.cleanup)
Esempio n. 6
0
    def __init__(self, *args, **kwargs):
        super(OneShotAnalytics, self).__init__(*args, **kwargs)

        if hasattr(self, "settings"):
            for setting_id, setting in self.settings.items():
                User.register_setting(setting_id, setting["name"],
                                      setting["description"])
Esempio n. 7
0
def user_test(wholeTree=True):
    patrik = User()
    patrik.login("patrikch","123456")
    print(patrik.is_logged)
    print(str(patrik))
    tree = patrik.project_tree
    printTree(tree)
Esempio n. 8
0
def create_user(username,
                password,
                admin=False,
                permissions=DEFAULT_PERMISSIONS):
    permissions["admin"] = admin
    u = User(username=username, permissions=permissions)
    u = set_password(u, password)
    return u.save()
Esempio n. 9
0
 def _auth(self, *args):
     """注册函数"""
     data_header = args[0]
     username = data_header["username"]
     password = data_header["password"]
     obj = User()
     status = obj.enroll(username, password)
     if status == 651:
         obj.create_directory()  # 创建用户家目录
     self.send_msg(status)
Esempio n. 10
0
def create_user(username):
    user = User(username=username, permissions=DEFAULT_PERMISSIONS)
    user.api_key = User.generate_api_key()
    user.password = urandom(24).encode('hex')
    user.session_token = generate_session_token(user)
    user.enabled = True
    user.save()
    return user
Esempio n. 11
0
def signup():
    if current_user.is_authenticated:
        return redirect(url_for('web.index'))
    form_data = {}
    if request.method == 'POST':
        validation_result = validate_registration_form(request.form.to_dict())
        if ValidationResults.SUCCESS in validation_result:
            try:
                user = User(request.form)
                token = s.dumps(user.email,
                                salt=current_app.config.get('MAIL_SALT'))
                msg = generate_confirmation_mail(user.email, token)
                mail.send(msg)
                add_new_user(user)
                session['email_to_confirm'] = user.email
                return redirect(url_for('web.finish_signup'))
            except Exception as ex:
                flash(str(ex))
        for message in validation_result:
            flash(message.value)
        form_data = request.form
    return render_template(
        'signup.html',
        google_client_key=current_app.config.get('GOOGLE_CLIENT_KEY'),
        form_data=form_data)
Esempio n. 12
0
 def parse_user(self, user_string: str):
     user_elements = user_string.replace("\n", "").split('::')
     return User(user_id=int(user_elements[0]),
                 gender=Gender(user_elements[1]),
                 age=Age(int(user_elements[2])),
                 occupation=Occupation(int(user_elements[3])),
                 zipcode=Zipcode(user_elements[4]))
Esempio n. 13
0
def set_password(user, password):
    user.password = generate_password_hash(password,
                                           method='pbkdf2:sha256:20000')
    user.api_key = User.generate_api_key()
    user.session_token = generate_session_token(user)
    userLogger.info("User password changed : %s", user.username)
    return user
Esempio n. 14
0
def register(msg):
    print(msg)
    #username password
    #创建一个属于这个用户的家目录,把用户名的密码写在userinfo
    #记录用户的初试磁盘配额,记录文件大小,记录用户当前所在的目录
    user_obj = User(msg['name'])  #记录用户的信息
    os.mkdir(user_obj.home)  #创建一个家目录
Esempio n. 15
0
 def new_test(self):
     self.add_new = AddTestDialog()
     self.main_window.setDisabled(True)
     self.add_new.show()
     if self.add_new.exec_():
         self.user = User(self.add_new.name, self.add_new.age,
                          self.add_new.gender)
         self.main_window.setDisabled(False)
         self.main_window.testing.setDisabled(False)
         self.main_window.testing.answer.setDisabled(True)
         self.main_window.testing.test_info.name.setText("     " +
                                                         self.user.name)
         self.main_window.testing.test_info.age.setText("     " +
                                                        str(self.user.age))
         self.main_window.testing.test_info.gender.setText(
             "     " + str(self.user.gender.value))
         self.main_window.testing.test_info.procedure.setText(
             "     " + str(self.add_new.procedure.value))
         if self.add_new.procedure == ProcedureType.BASIC:
             self.main_window.testing.test_info.iterations.setText(
                 "     " + str(self.add_new.iterations))
             self.main_window.testing.test_info.grid.setText("     5x5")
             self.main_window.testing.test_info.resH.setText(
                 "     45 degrees (H)")
             self.main_window.testing.test_info.resV.setText(
                 "     45 degrees (V)")
         self.b0.setDisabled(True)
         self.b1.setDisabled(False)
Esempio n. 16
0
 def __init__(self, **kwargs):
     if kwargs:
         from core.user import User
         self.user = User(**kwargs)
         self.base_data = dict(all_fuc=self.frame.allow_fuc,
                               all_column=self.frame.allow_column)
     pass
Esempio n. 17
0
    def from_dict(cls, data: dict, magicnumber: str = None) -> 'Block':
        """ Convert from dictionary for deserialize. """

        parent = None
        if data['parent'] is not None:
            parent = DummyBlock(
                data['index'] - 1,
                magicnumber,
                base64.b64decode(data['parent']),
            )

        result = cls(parent)

        if data['key'] is not None:
            result.key = base64.b64decode(data['key'])

        if data['closer'] is not None:
            result.closer = User.from_pem(data['closer'])

        result.timestamp = data['timestamp']

        if data['signature'] is not None:
            result.signature = base64.b64decode(data['signature'])

        result.messages = [Message.from_dict(m) for m in data['messages']]

        return result
Esempio n. 18
0
 def create_user(self, name, password, phone, role='USER'):
     print(role)
     self.session.add(
         User(user_name=name,
              true_name=name,
              telephone=phone,
              password_md=password,
              role=role))
Esempio n. 19
0
def commen_user_menu(user_data, user):
    """
    :param user_data:<list> 包含所有用户账号的列表
    :param user:<core.user.User object> 用户实例
    :return:None
    这个函数用来和普通用户交互,并分发功能。或者让管理员也可以使用这个系统
    """
    # 初始化一个交易中心实例
    tc = TradingCenter(user)
    print("当前余额为%s" % user.balances)
    while True:
        print("""
            请输入序号选择功能
            1. 购物
            2. 转账
            3. 提现
            4. 还款
            5. 查询流水
            6. 退出
            """)
        choice = input(">>>").strip()
        if choice == "1":
            # 用户输入的值为1时,初始化一个购物车实例,调用购物方法
            shopping = ShoppingCar(user.balances, tc)
            shopping.display_menu()

        elif choice == "2":
            # 用户输入的值为2时,判断用户是否存在,如果存在,调用交易中心的转账方法
            outer_user = input("请输入转入账户的账户名:")
            if outer_user in user_data:
                money = input_int("请输入转账金额:")
                tc.transfer(User(outer_user), money)
            else:
                # 不存在则提示用户
                print("账户不存在,请重新输入!")
        elif choice == "3":
            # 如果用户的输入值为3 ,调用交易中心的提现方法
            money = input_int("请输入提现金额:")
            tc.cash_out(money)

        elif choice == "4":
            # 如果用户的输入值为4,调用交易中心的还款方法
            money = input_int("还款金额")
            tc.reimbursement(money)

        elif choice == "5":
            # 调用交易中心的显示日志的方法
            tc.display_user()
        elif choice == "6":
            # 用户选择退出时,退出程序
            access_log.info("用户%s退出程序" % user.account)
            # 这里休眠0.1秒是为了 输出的日志消息 不会影响用户的输入
            sleep(0.1)
            exit()
        else:
            # 用户输入错误时提示用户
            print("输入的选项有误,请重新输入!")
Esempio n. 20
0
    def from_dict(cls, data: dict) -> 'Message':
        """ Convert from dictionary for deserialize. """

        return cls(
            User.from_pem(data['user']),
            data['namespace'],
            data['payload'],
            base64.b64decode(data['signature']),
        )
Esempio n. 21
0
def register(msg):
    user_obj = User(msg['username'])
    pickle_path = os.path.join(settings.pickle_path, msg['username'])
    with open(pickle_path, 'wb') as f:
        pickle.dump(user_obj, f)
    os.mkdir(user_obj.home)
    with open(settings.user_info, 'a') as f:
        f.write('%s|%s|%s\n' % (msg['username'], msg['password'], pickle_path))
    return True, pickle_path
Esempio n. 22
0
 def test_user_project_tree(self):
     """User folder-project tree should be different"""
     patrik = User()
     patrik.login("patrikch","123456")
     tree = patrik.project_tree
     self.assertEqual(1,len(tree))
     self.assertEqual("root",tree[0].name)
     self.assertEqual(4,len(tree[0].children))
     self.assertEqual("d",tree[0].children[0].type)
     self.assertEqual("d",tree[0].children[1].type)
     self.assertEqual("d",tree[0].children[2].type)
     self.assertEqual("p",tree[0].children[3].type)
     self.assertEqual(6,len(tree[0].children[0].children))
     self.assertEqual("d",tree[0].children[0].children[0].type)
     self.assertEqual("d",tree[0].children[0].children[1].type)
     self.assertEqual("p",tree[0].children[0].children[2].type)
     self.assertEqual("p",tree[0].children[0].children[3].type)
     self.assertEqual("p",tree[0].children[0].children[4].type)
     self.assertEqual("p",tree[0].children[0].children[5].type)        
Esempio n. 23
0
 def test_user_project_tree(self):
     """User folder-project tree should be different"""
     patrik = User()
     patrik.login("patrikch", "123456")
     tree = patrik.project_tree
     self.assertEqual(1, len(tree))
     self.assertEqual("root", tree[0].name)
     self.assertEqual(4, len(tree[0].children))
     self.assertEqual("d", tree[0].children[0].type)
     self.assertEqual("d", tree[0].children[1].type)
     self.assertEqual("d", tree[0].children[2].type)
     self.assertEqual("p", tree[0].children[3].type)
     self.assertEqual(6, len(tree[0].children[0].children))
     self.assertEqual("d", tree[0].children[0].children[0].type)
     self.assertEqual("d", tree[0].children[0].children[1].type)
     self.assertEqual("p", tree[0].children[0].children[2].type)
     self.assertEqual("p", tree[0].children[0].children[3].type)
     self.assertEqual("p", tree[0].children[0].children[4].type)
     self.assertEqual("p", tree[0].children[0].children[5].type)
Esempio n. 24
0
 def _login(self, *args):
     """登陆函数"""
     data_header = args[0]
     username = data_header["username"]
     password = data_header["password"]
     ret = User.login(username, password)
     if ret["status"] == 654:
         self.user["type"] = "用户"
         self.user["user_id"] = ret["obj"].id
         self.user["user_path"] = ret["obj"].home_path
     self.send_msg(ret["status"])
Esempio n. 25
0
 def get_user_obj(self, username):
     """获取用户对象"""
     status = 611
     obj = None
     obj_list = User.get_all_obj()  # 通过类名获取该类下的所有对象
     for obj in obj_list:
         if username == obj.username:
             status = 654
             obj = obj
             return {"status": status, "obj": obj}
     return {"status": status, "obj": obj}
Esempio n. 26
0
    def close(self,
              user: User,
              key: bytes,
              timestamp: int = None,
              signature: bytes = None) -> 'Block':
        """ Close this block and create next block.


        Can't close already closed block.

        >>> root = Block.make_root(User.generate())
        >>> root.is_closed()
        True
        >>> root.close(User.generate(), b'hello')
        Traceback (most recent call last):
            ...
        core.errors.BlockAlreadyClosedError
        """

        if self.is_closed():
            raise errors.BlockAlreadyClosedError()

        if not self.verify_key(key):
            raise errors.InvalidKeyError()

        if timestamp is None:
            timestamp = int(time.time() * 1000)

        if signature is not None:
            if not user.verify_raw(
                    timestamp.to_bytes(8, 'big') + key, signature):
                raise errors.InvalidSignatureError()
            self.signature = signature
        else:
            self.signature = user.sign_raw(timestamp.to_bytes(8, 'big') + key)

        self.timestamp = timestamp
        self.key = key
        self.closer = user

        return Block(self)
Esempio n. 27
0
 def _auth(self, conn, data_header):
     """注册功能"""
     username = data_header["username"]
     password = data_header["password"]
     user_obj = User()
     ret = user_obj.enroll(username, password, action_logger)
     if ret == 651:
         user_obj.create_directory()
         user_obj.save()
     self.send_msg(conn, ret)
Esempio n. 28
0
 def _login(self, conn, data_header):
     """登陆功能"""
     username = data_header["username"]
     password = data_header["password"]
     ret = User.login(username, password, action_logger)
     if ret["status"] == 654:
         self.user_info[conn] = {}
         self.user_info[conn]["obj"] = ret["obj"]
         home_path = os.path.join(settings.USER_DIRECTORY_DIR,
                                  ret["obj"].username)
         self.user_info[conn]["home"] = home_path
     self.send_msg(conn, ret["status"])
Esempio n. 29
0
 def user_regester(username, password, phone=''):
     from core import CMS
     setting = CMS.setting_info('system')
     if 'regester_admin' in setting.keys():
         setting = setting['regester_admin']
         from core.user import User
         login = CMS(
             User(ident=setting['username'], pwd=setting['password']))
         is_regester = login.UserMod().create(username, password, phone)
         if not is_regester['success']:
             raise Exception('Unknow error cant create user')
         return {'success': True}
     else:
         raise Exception('setup regester fuc first!')
Esempio n. 30
0
    def profile(self):
        if request.args.get("id") and current_user.has_role("admin"):
            user = get_object_or_404(User, id=request.args.get("id"))
        else:
            user = current_user

        if request.method == "POST":
            for setting in request.form:
                if request.form[setting]:
                    user.settings[setting] = request.form[setting]

            user.save()

            for setting in request.form:
                if not request.form[setting]:
                    user.settings.pop(setting, None)

            user.save()

        groups = Group.objects(members__in=[user.id])
        all_groups = Group.objects()
        if current_user.has_role("admin") and user.id != current_user.id:
            return render_template(
                "user/profile_admin.html",
                available_settings=User.get_available_settings(),
                user=user,
                groups=groups,
                all_groups=all_groups,
            )
        else:
            return render_template(
                "user/profile.html",
                available_settings=User.get_available_settings(),
                user=user,
                groups=groups,
                all_groups=all_groups,
            )
Esempio n. 31
0
def register(msg):
    # username, password
    # 创建一个属于这个用户的家目录
    # 把用户名密码写进userinfo文件里,记录用户名
    # 记录用户的初始磁盘配额,并记录下来
    # 记录文件大小
    # 记录用户当前所在的目录
    user_obj = User(msg['username'])  # 记录用户的信息在内存里
    pickle_path = os.path.join(settings.pickle_path, msg['username'])
    with open(pickle_path, 'wb') as f:
        pickle.dump(user_obj, f)
    os.mkdir(user_obj.home)  # 创建一个属于这个用户的对象
    with open(settings.user_info, 'a') as f:
        f.write('%s|%s|%s' % (msg['username'], msg['pwd'], pickle_path))
    return True
Esempio n. 32
0
def register(msg):
    # 创建一个属于这个用的家目录,并记录下来
    # 记录用户的初始磁盘配额
    # 记录文件大小
    # 记录用户当前所在的目录
    user_obj = User(msg['name'])
    pickle_path = os.path.join(settings.pickle_path, msg['username'])
    with open(pickle_path, 'wb') as f:
        pickle.dump(user_obj, f)
    os.mkdir(user_obj.home)

    # 把用户名密码写进userinfo文件里,并记录用户名
    with open(settings.user_info, 'a') as f:
        f.write('{}|{}|{}'.format(msg['username'], msg['password'],
                                  pickle_path))
    return True
Esempio n. 33
0
def register(msg):
    """登录认证
     1.创建一个该用户的家目录,并记录下来
     2.把用户名和密码写进userinfo文件里,记录用户名
     3.记录用户的的磁盘配额
     4.记录文件大小
     5.记录用户当前所在的目录
    """
    user_obj = User(msg['username'])  # 记录用户的信息在内存里 # 传入name参数
    pickle_path = os.path.join(settings.pickle_path, msg['username'])
    with open(pickle_path, 'wb') as f:
        pickle.dump(user_obj, f)
    os.mkdir(user_obj.home)  # 创建属于这个用户的家目录 在home文件夹下
    with open(settings.user_info, 'a') as f:
        f.write('%s|%s|%s' % (msg['username'], msg['password'], pickle_path))
    return True
Esempio n. 34
0
    def __init__(self, *args, **kwargs):
        super(OneShotAnalytics, self).__init__(*args, **kwargs)

        if hasattr(self, 'settings'):
            for setting_id, setting in self.settings.iteritems():
                User.register_setting(setting_id, setting['name'], setting['description'])
Esempio n. 35
0
 try:  
     conn.close()
     if id == 'EMPTY':
         logging.warn('HTTP server gives EMPTY id')
         continue
 except Exception, e:
     logging.warning("*****\n*****\n***** conn.close() ----------- "+ str(e))
     if conn:
         logging.warning("conn = %s" % str(conn))
         conn.close()
         continue
     else:
         logging.warning("conn = %s" % str(conn))
         continue
 try:
     user = User(id)
     profile = user.get_or_create_profile()
    # logging.debug('Create User id = %s\n' % id )
     try:
         user_session_list = user.get_session_list()
     except RequestFailedError:
         logging.debug("User id = %s --- query session" % user.get_id())
         user.query_session()
         continue
     print 'User id = %s --- lenght session list = %d' % (user.get_id(), len(user.session_list) )
     for session in user.session_list:
         try:
             logging.debug(session)
             logging.debug('++++++++++++++++++++++++++\n')
             logging.debug("user.get_id() = %s  session.current_player_id - %s" % (user.get_id(), session.current_player_id.encode("UTF-8") ))
             if user.get_id() == session.current_player_id.encode("UTF-8"):
Esempio n. 36
0
 def test_user_was_logged(self):
     """User should has been logged"""
     patrik = User()
     patrik.login("patrikch","123456")
     self.assertEqual(True,patrik.is_logged)
Esempio n. 37
0
def login(**kwargs): 
	# authorize a user based on the request body (if the user isn't already logged in)
	user = User.auth(**(request.get_json())) if not g.user else g.user
	return jsonify(fbid=user.fbid,**kwargs) if user else abort(403)
Esempio n. 38
0
def before():
	# authorize a user based on the fbid, fbAcessToken stored in the cookies
	g.user = User.auth(fbid=request.cookies.get('fbid'),
		fbAccessToken=request.cookies.get('fbAccessToken'))
Esempio n. 39
0
    def parse(self):
        def get_agree(line):
            if "Strongly Agree" in line:
                return 5
            elif "Strongly Disagree" in line:
                return 1
            elif "Disagree" in line:
                return 2
            elif "Neutral" in line:
                return 3
            elif "Agree" in line:
                return 4
            else:
                return -999

        with open(self.survey_uri) as survey_data:
            current_question = 0
            current_user = None
            for line in survey_data:
                line = line.strip()
                if len(line) == 0:
                    continue

                if line[:5] == "PAGE ":
                    continue
                # Parse current question
                if line[0] == "Q" and (line[2] == ":" or line[3] == ":"):
                    qid = line.split(":")[0][1:]
                    try:
                        qid = int(qid)
                        if qid in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
                            current_question = qid
                        else:
                            print "ERROR: Question ID Parse Failed", line
                    except:
                        print "ERROR: Question ID Parse Failed", line
                # Question 1
                elif "What is your DS ProD member number?" in line:
                    user_id = line.split(" ")[-1].replace("/", "")
                    for x_user in self.users:
                        if x_user.user_id == user_id:
                            print "SOMEONE TOOK THIS TWICE", user_id
                            exit
                    current_user = User(user_id)
                    self.users.add(current_user)
                elif "what you put on Meetup" in line:
                    current_user.name = line[line.find(")") + 1 :].strip()
                #        elif "Go change your DS ProD Meetup photo" in line:
                #            self.users[user_id]["photo"] = ... #TODO:hit API to grab pic, to send to match?
                elif current_question == 2:
                    current_user.career_stage = line
                elif current_question == 3:
                    skills = line.split("-")
                    for level in current_user.methods.get_levels():
                        level_txt = current_user.methods.txt(level)
                        if level_txt in line:
                            skill = skills[0].strip()[:-1]
                            current_user.broad_skills.append_at_level(level, skill)
                            continue
                elif current_question == 4:
                    for level in current_user.geogs.get_levels():
                        level_txt = current_user.geogs.txt(level)
                        geog = line[: line.find(level_txt)].strip()
                        if level_txt in line:
                            current_user.geogs.append_at_level(level, geog)
                    if line[:5] == "Other":
                        current_user.geogs.append_at_level("Other", line[line.find(")") + 1 :].strip())
                elif current_question == 5:
                    current_user.gender = line
                elif current_question == 6:
                    for level in current_user.skills.get_levels():
                        level_txt = current_user.skills.txt(level)
                        if level_txt in line:
                            skill = line[: line.find(level_txt)].strip()
                            current_user.skills.append_at_level(level, skill)
                            continue
                elif current_question == 7:
                    if "Respondent skipped this question" in line:
                        continue
                    if "n/a" in line:
                        continue
                    slen = len("Software 1 ")
                    package = line[slen:].strip()
                    current_user.software.append(package)
                elif current_question == 8:
                    for level in current_user.methods.get_levels():
                        level_txt = current_user.methods.txt(level)
                        if level_txt in line:
                            skill = line[: line.find(level_txt)].strip()
                            current_user.methods.append_at_level(level, skill)
                            continue
                elif current_question == 9:
                    response = line[11:]
                    if line[:8] == "Analysis":
                        current_user.analysis.append(response)
                    elif line[:8] == "Industry":
                        current_user.industry.append(response)
                elif current_question == 10:
                    if "In my industry" in line:
                        current_user.prefs.append_at_level(get_agree(line), "industry")
                    if "That I can mentor" in line:
                        current_user.prefs.append_at_level(get_agree(line), "i_mentor")
                    if "At my skill level" in line:
                        current_user.prefs.append_at_level(get_agree(line), "at_skill_level")
                    if "That will mentor me" in line:
                        current_user.prefs.append_at_level(get_agree(line), "mentor_me")
                    if "That are quite similar to me" in line:
                        current_user.prefs.append_at_level(get_agree(line), "similar")
                    if "That are quite different from me" in line:
                        current_user.prefs.append_at_level(get_agree(line), "different")

        for user in self.users:
            print user
        return len(self.users) > 0
Esempio n. 40
0
def main():
    '''
        Тест: Игра двух конкретных игроков.
        1 - Игрок1 рисует;
        2 - Игрок2 угадывает;
        3 - Игрок2 рисует;
    '''
    try:
        logging.basicConfig(level=logging.DEBUG)
        log = logging.getLogger('main')
        user1 = User('1003')
        user2 = User('1004')
        u2_list = user2.get_session_list()
        u1_list = user1.get_session_list()
        print "user is=%s lenght session list = %d" % (user2.get_id(), len(user2.get_session_list()))
        for session in u2_list:
            print session
            print "-------------"
            user2.update_session(session, 'A' * 25)
            session = user2.get_session(session.id)
            logging.debug(session)
            user1.update_session(session, 'A' * 25)
            session = user2.get_session(session.id)
            logging.debug(session)
            user1.update_session(session, 'A' * 25)
            session = user2.get_session(session.id)
   
    except RequestFailedError, err_rfe:   
        print '-----------RequestFailedError!-----------' 
Esempio n. 41
0
def create_user(saml_name_id, saml_user_data):

    u = User(username=saml_name_id)
    u.save()
    u = adjust_permissions(u, saml_user_data)
    return u
Esempio n. 42
0
         break
 except urllib2.HTTPError, exception:
     resp.close()
     logging.info('*****\n*****\n***** GET HTTPSERVER RESPONSE------HTTP error %d' % exception.code)
     continue
 except urllib2.URLError, exception:
     resp.close()
     logging.info("*****\n*****\n***** GET HTTPSERVER RESPONSE -----------URLError: %s" % exception.reason.args[1])
     resp = ''
     continue
 except Exception, e:
     resp.close()
     logging.warning("*****\n*****\n***** GET HTTPSERVER RESPONSE "+ str(e))
     continue
 try:
     user = User(id)
     logging.debug('Create User id = %s\n' % id )
     user.query_session()
    # sec = random.randrange(1,5)
     time.sleep(2)
     user_session_list = user.get_session_list()
     quantity_sessions = len(user.session_list)
     while len(user.session_list) == 0:
         time.sleep(2)
         user_session_list = user.get_session_list()
     print 'User id = %s --- lenght session list = %d' % (user.get_id(), len(user.session_list) )
     while len(user.session_list) < 10:
         quantity_sessions = len(user.session_list)
         user.query_session()
         while len(user.session_list) != (quantity_sessions +1):
             logging.debug('user id = %s ---- len(user.session_list) = %d ---- quantity_sessions = %d\n' 
Esempio n. 43
0
class InstaBot(object):
    """
    Instagram bot v 1.0
    like_per_day=1000 - How many likes set bot in one day.

    media_max_like=10 - Don't like media (photo or video) if it have more than
    media_max_like likes.

    media_min_like=0 - Don't like media (photo or video) if it have less than
    media_min_like likes.

    tag_list = ['cat', 'car', 'dog'] - Tag list to like.

    max_like_for_one_tag=5 - Like 1 to max_like_for_one_tag times by row.

    log_mod = 0 - Log mod: log_mod = 0 log to console, log_mod = 1 log to file,
    log_mod = 2 no log.

    https://github.com/LevPasha/instabot.py
    """
    # List of user_id, that bot follow
    bot_follow_list = []

    # Other.
    media_by_tag = 0

    # For new_auto_mod
    next_iteration = {"Like": 0, "Follow": 0, "Unfollow": 0, "Comments": 0}

    def __init__(self, login, password,
                 like_per_day=1000,
                 media_max_like=10,
                 media_min_like=0,
                 follow_per_day=0,
                 follow_time=5 * 60 * 60,
                 unfollow_per_day=0,
                 comments_per_day=0,
                 tag_list=['cat', 'car', 'dog'],
                 max_like_for_one_tag=5,
                 log_mod=0):

        super(InstaBot, self).__init__()

        self.time_in_day = 24 * 60 * 60
        # Like
        self.like_per_day = like_per_day
        if self.like_per_day != 0:
            self.like_delay = self.time_in_day / self.like_per_day

        # Follow
        self.follow_time = follow_time
        self.follow_per_day = follow_per_day
        if self.follow_per_day != 0:
            self.follow_delay = self.time_in_day / self.follow_per_day

        # Unfollow
        self.unfollow_per_day = unfollow_per_day
        if self.unfollow_per_day != 0:
            self.unfollow_delay = self.time_in_day / self.unfollow_per_day

        # Comment
        self.comments_per_day = comments_per_day
        if self.comments_per_day != 0:
            self.comments_delay = self.time_in_day / self.comments_per_day

        # Don't like if media have more than n likes.
        self.media_max_like = media_max_like
        # Don't like if media have less than n likes.
        self.media_min_like = media_min_like
        # Auto mod seting:
        # Default list of tag.
        self.tag_list = tag_list
        # Get random tag, from tag_list, and like (1 to n) times.
        self.max_like_for_one_tag = max_like_for_one_tag

        self.media_by_tag = []

        log_string = 'Insta Bot v1.1 start at %s:' % \
                     (datetime.datetime.now().strftime("%d.%m.%Y %H:%M"))
        logger.info(log_string)

        session = requests.Session()
        # create a new user and log the user into the session
        self.user = User(session, login, password)
        self.user.login()
        self.API = API(self.user)

        signal.signal(signal.SIGTERM, self.cleanup)
        atexit.register(self.cleanup)

    def cleanup(self):
        # Unfollow all bot follow
        if len(self.bot_follow_list) > 0:
            for f in self.bot_follow_list:
                log_string = "Try to unfollow: %s" % (f[0])
                logger.info(log_string)
                self.API.unfollow(f[0])
                self.bot_follow_list.remove(f)

        # Logout
        if self.user.login_status:
            self.user.logout()

    def new_auto_mod(self):
        # ------------------- Get media_id -------------------
        if len(self.media_by_tag) == 0:
            self.media_by_tag = self.API.get_media_id_by_tag(random.choice(self.tag_list))

        media = Media(self.user, self.tag_list)
        # ------------------- Like -------------------
        like_bot = LikeBot(self.user, media, self.media_max_like, self.media_min_like)
        like_bot.run(3)
        # ------------------- Follow -------------------
        follow_bot = FollowBot(self.user, media)
        follow_bot.run(3)
        # ------------------- Comment -------------------
        comment_maker = CommentMaker()
        comment_bot = CommentBot(self.user, media, comment_maker)
        comment_bot.run(3)
        # ------------------- Unfollow All -------------------
        self.new_auto_mod_unfollow()
        # ------------------- Unfollow Non Folbacks -------------------
        # self.new_auto_mod_unfollow()

        # Bot iteration in 1 sec
        # print("Tic!")

    def new_auto_mod_unfollow(self):
        if time.time() > self.next_iteration["Unfollow"] and \
                        self.unfollow_per_day != 0 and len(self.bot_follow_list) > 0:
            for f in self.bot_follow_list:
                if time.time() > (f[1] + self.follow_time):

                    log_string = "Try to unfollow: %s" % (f[0])
                    logger.info(log_string)

                    if self.API.unfollow(f[0]):
                        self.bot_follow_list.remove(f)
                        self.next_iteration["Unfollow"] = time.time() + self.add_time(self.unfollow_delay)

    def add_time(self, time):
        """ Make some random for next iteration"""
        return time * 0.9 + time * 0.2 * random.random()
Esempio n. 44
0
           continue
       else:
           logging.warning("resp = %s" % resp)
           continue
   except Exception, e:
       logging.warning("*****\n*****\n***** GET HTTPSERVER RESPONSE "+ str(e))
       if resp:
           logging.warning("resp = %s" % resp)
           resp.close()
           continue
       else:
           logging.warning("resp = %s" % resp)
           continue
 #      sys.exit(-1)
   try:
       user = User(id)
       logging.debug('Create User id = %s\n' % id )
       session_list = user.get_session_list()
       quantity_sessions = len(user.session_list)
       logging.info("user id = %s len(user.session_list = %d)" % (user.get_id, quantity_sessions))
       if quantity_sessions < 1:
           continue
       else:
           for session in user.session_list:
               try:
                   logging.debug(session)
                   logging.debug('++++++++++++++++++++++++++\n')
                   logging.debug("user.get_id() = %s  session.current_player_id - %s" % (user.get_id(), session.current_player_id.encode("UTF-8") ))
                   if user.get_id() == session.current_player_id.encode("UTF-8"):
                       user.update_session(session, 'A' * 25600)
               except RequestFailedError, err_rfe:
Esempio n. 45
0
 def reset_api(self, id):
     user = get_object_or_404(User, id=id)
     user.api_key = User.generate_api_key()
     user.save()
     flash("API key reset", "success")
     return redirect(request.referrer)
Esempio n. 46
0
def set_password(user, password):
    user.password = generate_password_hash(
        password, method='pbkdf2:sha256:20000')
    user.api_key = User.generate_api_key()
    user.session_token = generate_session_token(user)
    return user
Esempio n. 47
0
def get_authorization( auth ):
	'''Check request for valid authentication data. The data can be either a
	session previuosly started with /login or authentication data. provided for
	example by a HTTP Basic authentication.

	:param auth: The authentication data in case session based authentication is
					 *not* used. Even if a session exist, this data has higher
					 priority than the session data.

	:returns: If successfull a valid User object is returned.
	'''
	username = None
	password = None

	if not auth:
		# We got no login data.
		# Assign the name »public« to the user which will also put hin into the
		# »public« group
		if 'username' in session and 'password' in session:
			username = session['username']
			password = session['password']
			print([ username, password ])
		else:
			username = '******'
	else:
		username = auth.username
		password = auth.password
		
	# Check if the username might be valid as protection
	# against SQL injection
	for c in username:
		if not c in username_chars:
			raise KeyError( 'Bad username in header.' )

	query = '''select id, salt, passwd, vcard_uri, realname, email, access
			from lf_user where name = "%s"''' % username

	# Get userdata from database
	db = get_db()
	cur = db.cursor()
	cur.execute( query )
	dbdata = cur.fetchone()

	if not dbdata:
		# User does not exist. Return error
		raise KeyError( 'User does not exist.' )

	id, salt, passwd, vcard_uri, realname, email, access = dbdata
	send_passwdhash = ( sha512( password + str(salt) ).digest() \
			if auth else b64decode(password) ) \
			if passwd else None
	
	if passwd != send_passwdhash:
		# Password is invalid. Return error
		raise KeyError( 'Invalid password.' )

	# At this point we are shure that we got a valid user with a valid password.
	# So lets get the userdata.
	# First set, what we already know:
	user = User( id=id, name=username, vcard_uri=vcard_uri, groups={},
			realname=realname, email=email, access=access, password_hash=passwd )
	
	# Then get additional data:
	query = '''select g.id, g.name from lf_user_group ug
			left outer join lf_group g on ug.group_id = g.id
			where ug.user_id = %s ''' % id
	cur.execute(query)
	for id, name in cur.fetchall():
		user.groups[id] = name

	# Return user information
	return user
Esempio n. 48
0
    def answer_q(self,respondent_id,question_id,answer_text_dict,answers):
#        print "answers",answers
        for answer in answers:
#            print answer.keys()

            if respondent_id in self.respondent_id_to_user:
                current_user = self.respondent_id_to_user[respondent_id]

            answer_row = answer['row']
            if answer["row"] == u"0":
                question_text = "Other"
            else:
                question_text = answer_text_dict[answer_row]

            answer_text = None
            answer_col = None

            if 'text' in answer:
                answer_text = answer['text']
            if 'col' in answer:
                answer_col = answer['col']
                answer_text = answer_text_dict[answer_col]

            if question_id == 1:
                if "What is your DS ProD member number?" in question_text:
                    user_id = answer_text
                    for x_user in self.users:
                        if x_user.user_id == user_id:
                            print "SOMEONE TOOK THIS TWICE", user_id
                            exit
                    current_user = User(user_id)
                    self.users.add(current_user)
                    self.respondent_id_to_user[respondent_id] = current_user
                elif "what you put on Meetup" in question_text:
                    current_user.name = answer_text
            elif question_id == 2:
                current_user.career_stage = question_text
            elif question_id == 3:
                for level in current_user.methods.get_levels():
                    level_txt = current_user.methods.txt(level)
                    if level_txt in answer_text:
                        skill = question_text
                        current_user.broad_skills.append_at_level(level, skill)
            elif question_id == 4:
                for level in current_user.geogs.get_levels():
                    level_txt = current_user.geogs.txt(level)
                    geog = question_text
                    if level_txt in answer_text:
                        current_user.geogs.append_at_level(level,geog)
                if question_text == "Other":
                    current_user.geogs.append_at_level("Other", question_text)
            elif question_id == 5:
                current_user.gender = question_text
            elif question_id == 6:
                for level in current_user.skills.get_levels():
                    level_txt = current_user.skills.txt(level)
                    if level_txt in answer_text:
                        skill = question_text
                        current_user.skills.append_at_level(level,skill)
            elif question_id == 7:
                package = answer_text
                current_user.software.append(package)
            elif question_id == 8:
                for level in current_user.methods.get_levels():
                    level_txt = current_user.methods.txt(level)
                    if level_txt in answer_text:
                        skill = question_text
                        current_user.methods.append_at_level(level, skill)
            elif question_id == 9:
                if "Analysis" in question_text:
                    current_user.analysis.append(answer_text)
                elif "Industry" in question_text:
                    current_user.industry.append(answer_text)
            elif question_id == 10:
                if "In my industry" in question_text:
                    current_user.prefs.append_at_level(self.get_agree(answer_text),"industry")
                if "That I can mentor" in question_text:
                    current_user.prefs.append_at_level(self.get_agree(answer_text),"i_mentor")
                if "At my skill level" in question_text:
                    current_user.prefs.append_at_level(self.get_agree(answer_text),"at_skill_level")
                if "That will mentor me" in question_text:
                    current_user.prefs.append_at_level(self.get_agree(answer_text),"mentor_me")
                if "That are quite similar to me" in question_text:
                    current_user.prefs.append_at_level(self.get_agree(answer_text),"similar")
                if "That are quite different from me" in question_text:
                    current_user.prefs.append_at_level(self.get_agree(answer_text),"different")
Esempio n. 49
0
def create_user(username, password, permissions=DEFAULT_PERMISSIONS):
    u = User(username=username, permissions=permissions)
    u = set_password(u, password)
    return u.save()
Esempio n. 50
0
           continue
       else:
           logging.warning("resp = %s" % resp)
           continue
   except Exception, e:
       logging.warning("*****\n*****\n***** GET HTTPSERVER RESPONSE "+ str(e))
       if resp:
           logging.warning("resp = %s" % resp)
           resp.close()
           continue
       else:
           logging.warning("resp = %s" % resp)
           continue
 #      sys.exit(-1)
   try:
       user = User(id)
       logging.debug('Create User id = %s\n' % id )
       user.query_session()
       sec = random.randrange(3, 7)
       time.sleep(sec)
       user_session_list = user.get_session_list()
       quantity_sessions = len(user.session_list)
       while len(user.session_list) == 0:
           sec = random.randrange(3, 7)
           time.sleep(sec)
           user_session_list = user.get_session_list()
       print 'User id = %s --- lenght session list = %d' % (user.get_id(), len(user.session_list) )
       while len(user.session_list) < 10:
           quantity_sessions = len(user.session_list)
           user.query_session()
           while quantity_sessions >= len(user.session_list):
Esempio n. 51
0
def load_user(user_id):
    print "user:", user_id
    try:
        return User.get(user_id)
    except:
        return None
Esempio n. 52
0
 def reset_api(self):
     current_user.api_key = User.generate_api_key()
     current_user.save()
     flash("API key reset", "success")
     return redirect(request.referrer)
Esempio n. 53
0
def main546():
    '''
        Тест: Игра случайного игрока. Игрок пытается сделать ход в каждой сессии из его списка сессий
    '''
    logging.basicConfig(level=logging.DEBUG)
    log = logging.getLogger('main')
    while True:
        try:
           # resp = urllib2.urlopen('http://localhost:8000')
            
            conn = None
            conn = httplib.HTTPConnection('localhost:8000')
            conn.request('GET', "")
            response = conn.getresponse()
            status = response.status
            print status
            id = response.read()
            conn.close()
            if id == 'EMPTY':
                logging.warn('HTTP server gives EMPTY id')
                continue
            
           # id = resp.read()
          #  resp.close()
           # if id == 'EMPTY':
           #     logging.warn('HTTP server gives EMPTY id')
           #     break
            user = User(id)
            logging.debug('Create User id = %s\n' % id )
            quantity_sessions = len(user.session_list)
            logging.debug('user quantity sessions = %d' % quantity_sessions)
            user.query_session()
            time.sleep(5)
            user_session_list = user.get_session_list()
            logging.debug('!!!user quantity sessions = %d' % len(user.session_list))
            if len(user.session_list) == 0:
                continue
            else:
                for session in user.session_list:
                    try:
                        logging.debug(session)
                        logging.debug('++++++++++++++++++++++++++\n')
                        user.update_session(session, 'Test_URL')
                    except RequestFailedError:
                        print 'UPDATE SESSION-----------RequestFailedError!-----------'
                        continue
            #break
        except RequestFailedError:     
            print '-----------RequestFailedError!-----------'
        except ConnectionError:
            print '-----------ConnectionError!-----------'
        except InvalidArgumentError:
            print '-----------InvalidArgumentError!-----------'
        except Exception, e:
                logging.warning("*****\n*****\n***** GET HTTPSERVER RESPONSE "+ str(e))
                if conn:
                    logging.warning("conn = %s" % str(conn))
                    conn.close()
                    continue
                else:
                    logging.warning("conn = %s" % str(conn))
                    continue