Ejemplo n.º 1
0
def user_by_username(username):
    query = Query("_User")
    query.equal_to('username', username)
    user = query.first()
#    if user is not None:
#        showo_inDict(user)
    return user
Ejemplo n.º 2
0
def get_user_file(start, end):
    global ufCount
    ufCount = 0
    formType = 'UserFile'
    dateStr = start.strftime('%Y-%m-%d')
    rc = checkWriteState(dateStr, formType)
    if rc:
        print 'already batch inserted'
        return
    print '开始存储 ' + dateStr + ' ' + formType + ' 的数据'
    #判断今天是不是已经搞定了
    ufObj = Object.extend('UserFile')
    ufQuery = Query(ufObj)
    ufQuery.greater_than_or_equal_to('createdAt',start)
    ufQuery.less_than_or_equal_to('createdAt',end)

    def uf_call_back(lst):
        global ufCount
        writeList =  []
        for item in lst:
            ufMap = {}
            ufMap['openId'] = item.get('openId')
            ufMap['fileType'] = item.get('fileType')
            ufMap['srcId'] = item.id
            ufMap['createdAt'] = item.created_at
            ufMap['updatedAt'] = item.updated_at
            writeList.append(ufMap)
        ufCount = ufCount + len(writeList)
        if len(writeList) > 0:
            loadUserFile(writeList)
    map_query(ufQuery, 1000, uf_call_back)
    print '本次一共存储了' + str(ufCount) + '条纪录' #一共存储了多少
    finishLoadData(dateStr, formType, ufCount)
Ejemplo n.º 3
0
def is_exit(str):
    global category
    global type_name
    query = Query('Reading')
    query.equal_to('source_url', str)
    querys = query.find()
    return len(querys) > 0
Ejemplo n.º 4
0
def showApi():
    """给前端提供api接口
        id -> 提供id页的日记,每页50条日记
        user_id -> 提供该user_id的所有日记
    """
    id = int(request.args.get('id', 1))
    user_id = int(request.args.get('user_id', 0))
    try:
        # 如果没有提供user_id,即user_id为0
        if user_id is 0:
            posts = Query(Tian).ascending('post_no').limit(50).skip(50*(id-1)).find()
        else:
            posts = Query(Tian).equal_to('user_id', user_id).limit(500).find()
        code = 200
    except LeanCloudError as e:
        posts = []
        code = '500' + str(e.code)
    data = {
        'code': code,
        'results': [post.dump() for post in posts]
    }
    res = make_response(jsonify(data))
    res.headers['Access-Control-Allow-Origin'] = '*'
    res.headers['Access-Control-Allow-Method'] = 'POST'
    return res
Ejemplo n.º 5
0
def query_proxy_item():
    proxy_list = []
    query = Query(Proxy_Item)
    for i in query.find():
        if isinstance(i, Proxy_Item):
            proxy_list.append(i)
    return proxy_list
Ejemplo n.º 6
0
def catit():
    request_cat_ids = request.form['cats'].split(',')
    photoid = request.form['photoid']
    
    photo = Query(Photo).get(photoid)
    print photo.get('name')
    cat_relation = photo.relation('category')
    previousCats = cat_relation.query().find()

    # Remove previous category
    for cat in previousCats:
        cat_relation.remove(cat)
    
    # Set new category
    for catid in request_cat_ids:
        cat = Query(Category).get(catid)
        print cat.get('name')
        if cat:
            cat_relation.add(cat)

    # photo.set('featured', True if (featured == 'true') else False)

    photo.save()

    alreadyCategorizedCount = Query.do_cloud_query('select count(*) from Photo where category != null').count
    
    return json.dumps({'status':'OK', 'count': alreadyCategorizedCount, 'photoid': photoid});
Ejemplo n.º 7
0
def run():
    while 1:
        query = Query(Business)
        query.equal_to('geo_point', None)

        current_business = query.first()
        temp = current_business.address.values()
        current_address = " ".join(temp).replace("(", " ").replace(")", " ").replace(u'号', " ")

        try:
            lat, lon = get_coordinates(current_address)
            if lat == None or lon == None:
                print(1)
                lat, lon = get_coordinates(temp[1]+" "+temp[0]+" "+temp[2])
            if lat == None or lon == None:
                print(2)
                lat, lon = get_coordinates(temp[0] + " " + temp[1])
            if lat == None or lon == None:
                print(3)
                lat, lon = get_coordinates(current_address[:current_address.find(u'号')])
            if lat == None or lon == None:
                print(4)
                lat, lon = get_coordinates(temp[0]+" "+temp[2])
            if lat == None or lon == None:
                print(5)
                lat, lon = get_coordinates(current_address.translate(None, string.digits))
        except (ValueError, TypeError):
            lat = 0
            lon = 0
            print("ERROR: ", current_business.attributes)
            print("----------------------------------------------")

        point = GeoPoint(latitude=lat, longitude=lon)
        current_business.set("geo_point", point)
        current_business.save()
Ejemplo n.º 8
0
def sync_local():
    files = [ f for f in os.listdir(SYNC_DIR) if os.path.isfile(os.path.join(SYNC_DIR, f)) ]
    for f in files:
        fileName = f
        filePath = os.path.join(SYNC_DIR, f)
        if not (fileName.endswith('.jpeg') or fileName.endswith('.png') or fileName.endswith('.jpeg')):
            continue

        print('\n' + filePath)
        
        # 计算照片模糊 Hash 值
        im = Image.open(filePath)
        hash_meta = dhash(im)
        
        # 查询 LeanCloud,从本地移除重复照片
        query = Query(Photo)
        query.equal_to('dhash', hash_meta)
        results = query.find()
        if len(results) != 0:
            print "duplicate: (local=%s, leancloud=%s)" % (fileName, results[0].get('url'))
            os.rename(filePath, os.path.join(SYNC_DIR_DUPLICATED, fileName))
            continue

        # keep original file name for use in case
        originFileName = fileName

        millis = int(round(time.time() * 1000))
        hashFileName = hashids.encode(millis) + fileName[fileName.rfind('.')+1 :]
        os.rename(filePath, os.path.join(SYNC_DIR, hashFileName))

        # 解析 meta 信息
       	meta = parseImageMeta(hashFileName, im)
        # 保存链接与 meta 到 LeanCloud
        avosPhoto = savePhoto(meta)
Ejemplo n.º 9
0
def is_exit(str):
    query = Query('DailySentence')
    query.equal_to('dateline', str)
    querys = query.find()
    size = len(querys)
    # print size
    return size
Ejemplo n.º 10
0
def pic(message):
    cmd, text = parse_cmd_text(message.text)
    url = None
    base_url = 'http://7xqh4i.com1.z0.glb.clouddn.com/pic'
    if text != None:
        url = base_url + str(text)
        pic_num = text
    else:
        query = Query(Pic)
        pics = query.find()
        bolcks = [pic.get('pid') for pic in pics]
        pic_num = None
        size_of_images = 330  # 0~size_of_images
        while pic_num == None or str(pic_num) in bolcks:
            pic_num = random.randint(0, size_of_images)
        url = base_url + str(pic_num)
    bot.sendChatAction(chat_id=message.chat.id,
                       action=telegram.ChatAction.UPLOAD_PHOTO)

    def send_photo_task():
        bot.sendPhoto(chat_id=message.chat.id,
                      photo=url + '.jpg',
                      caption=pic_num)

    t = threading.Thread(target=send_photo_task)
    t.start()
Ejemplo n.º 11
0
def alias_filter(message):
    text = message.text
    query = Query(Alias)
    alises = query.find()
    if len(alises) == 0:
        return
    catch = False
    aliases_dict = {x.get('key'): x.get('value') for x in alises}
    keys = [x.get('key') for x in alises]
    # make the longer key be replaced first
    matches = sorted(re.findall('|'.join(keys), text),
                     key=lambda x: len(x),
                     reverse=True)
    if len(matches) > 0:
        catch = True
    if len(matches) == 1:
        if aliases_dict.get(matches[0]) == ('@' + message.from_user.username):
            return
    for m in matches:
        if '@' in aliases_dict.get(m):
            prefix = ' '
            if (prefix + m) in text:
                text = text.replace(m, aliases_dict.get(m) + ' ')
            else:
                text = text.replace(m, prefix + aliases_dict.get(m) + ' ')
        else:
            text = text.replace(m, aliases_dict.get(m))

    if catch == True:
        text = get_nickname(message.from_user) + ': ' + text
        bot.sendMessage(chat_id=message.chat.id, text=text)
Ejemplo n.º 12
0
def getPositionLeanCloud():
    Position = Object.extend('Position')
    position = Query(Position)
    position.select('position')
    query_list = position.find()
    #    print (str(query_list[0]))
    return query_list
Ejemplo n.º 13
0
def user():
    page = force_int(request.args.get('page', 1), 1)
    page_size = 10

    q = Query("_User")

    search_form = SearchAccountForm()

    keyword = None
    if request.method == 'GET':
        search_form.keyword.data = keyword = request.args.get('keyword', '')

    if search_form.validate_on_submit():
        keyword = search_form.keyword.data.strip()

    if keyword:
        if "@" in keyword:
            q = q.startswith("email", keyword)
        else:
            q = q.startswith("username", keyword)

    users = q.skip((page - 1) * page_size).limit(page_size).find()
    count = q.count()
    pages = count / page_size + 1

    return render_template('admin/user.html', users=users, form=search_form, count=count, pages=pages, page=page)
Ejemplo n.º 14
0
def query_proxy_item():
    proxy_list = []
    query = Query(Proxy_Item)
    for i in query.find():
        if isinstance(i, Proxy_Item):
            proxy_list.append(i)
    return proxy_list
def changeServerFileName(position,newName):
  query = Query(allPictures)
  query.equal_to('position', position)
  pictures = query.find()
  pictureSelect =  pictures[0]
  pictureSelect.set('image_src', newName)
  pictureSelect.save()
def queryOneDataByPosition(position):
    query = Query(allPictures)
    query.equal_to('position', position)
    pictures = query.find()
    if len(pictures) > 0:
      return pictures[0].get('image_src')
    return ""
Ejemplo n.º 17
0
def delete(task_id):
    st = Query(SmsTask).equal_to('user_id', request.user.get('id')).get(task_id)
    if not st: abort(404)

    st.destroy()
    flash(u'删除成功', 'danger')
    return redirect(url_for('index'))
Ejemplo n.º 18
0
def add():
	try:
		key_data = request.json['key']
		ch2o_data= request.json['ch2o']
		tem_data = request.json['tem']
		hum_data = request.json['hum']
		noi_data = request.json['noise']
		pm_data  = request.json['pm']
	except:
		return jsonify(error='json')
	query = Query(DeviceKey)
	try:
		device=query.get(key_data)
		index = device.get('index')
		name  = device.get('name')
		print 'Add Data',index,name
		control(index,pm_data)
		test_data = test_esp(ch2o=ch2o_data, t=tem_data, h=hum_data, noise=noi_data, pm=pm_data, key=key_data,name=name,index =index)
		try:
			test_data.save()
			
		except:
			return jsonify(error='save')
		upload_time =datetime.now().strftime('%Y-%m-%d %H:%M:%S')
		device.set('uploadtime',upload_time)
		try:
			device.save()
			print index,'save at',upload_time
		except:
			return jsonify(error ='staus save error')
		return jsonify(status ='succeed')
	except:
		return jsonify(error = 'key')
Ejemplo n.º 19
0
def json_index(index):
	print 'get result from index',index
	try:
		query =Query(DeviceKey)
		query.equal_to('index',index)
		devicekey=query.first()
		key=devicekey.id
		lat = devicekey.get('lat')
		lng = devicekey.get('lng')
	except:
		return jsonify(error='invalid index')
	try:
		data=get_latest(key)
	except:
		return jsonify(error='no data',key=key)
	ch2o = data.get('ch2o')
	if ch2o ==65535:
			ch2o=0
	ch2o =round(ch2o*1.32/1000,2)
	data.set('ch2o',ch2o)
	tem	=round(data.get('t')/10.0-40.0,1)
	hum 	=data.get('h')
	nosie   =data.get('noise')
	pm	=data.get('pm')
	ch2o	=data.get('ch2o')
	return jsonify(key = key,tem=tem,hum=hum,noise=nosie,pm=pm,ch2o=ch2o,createdAt=data.created_at,index=index,heze_rate= 80,tem_od=23.3,hum_od=12,pm_od=100,longitude=lng,latitude=lat)
Ejemplo n.º 20
0
def traverse_point(subject, point_type, items, parent=None, prefix=''):
    for i, el in enumerate(items):
        # print prefix, i, el.label.a.string,
        is_leaf = el.ul is None
        origin_url = el.label.a['href']
        data = {
            'origin_url': origin_url,
            'is_leaf': is_leaf,
            'type': point_type,
            'order': i,
            'subject': subject,
            'text': el.label.a.string
        }

        query = Query(Point)
        query.equal_to('origin_url', origin_url)
        try:
            point = query.first()
        except LeanCloudError:
            point = Point(**data)
        else:
            for k, v in data.items():
                point.set(k, v)
        if parent:
            point.set('parent', parent)
        point.save()

        if not is_leaf:
            traverse_point(subject, point_type, el.ul, point, '--' + prefix)
Ejemplo n.º 21
0
    def post(self, process_id):
        patient_medical_id = request.jsondata.get("patient_medical_id")
        result_json = request.jsondata.get("result_json")
        creater_id = request.jsondata.get("creater_id")
        patient_medical = Query(PatientMedical).get(patient_medical_id)
        processes = json.loads(patient_medical.get("processes_json"))
        for index, process in enumerate(processes):
            if process.get("process_id") == process_id:
                medical_process = Query(MedicalProcess).get(process_id)
                patient_medical_process = PatientMedicalProcess()
                patient_medical_process.set("patient_medical", patient_medical)
                patient_medical_process.set("result_json", result_json)
                patient_medical_process.set("process", medical_process)
                patient_medical_process.set("creater_id", creater_id)
                patient_medical_process.save()

                process["head"] = patient_medical_process.id
                patient_medical.set("processes_json", json.dumps(processes))
                patient_medical.save()

                # 如果是第0个,说明是填写的第一个过程,要去除第一张卡片的第一项作为患者需求
                if index == 0:
                    patient_requirement = json.loads(result_json).get("cards")[0].get("items")[0].get("value")
                    patient_medical.set("patient_requirement", patient_requirement)
                    patient_medical.save()

                return {}
        else:
            abort(404, message="不匹配")
Ejemplo n.º 22
0
    def post(self):
        """
        验证打开病历填写页面的人的身份
        :return:
        """
        process_id = request.jsondata.get("process_id")
        patient_medical_id = request.jsondata.get("patient_medical_id")
        doctor_id = request.jsondata.get("doctor_id")
        patient_id = request.jsondata.get("patient_id")

        patient_medical = Query(PatientMedical).get(patient_medical_id)

        if doctor_id != -1:
            if patient_medical.get("receive_doctor_id") != doctor_id:
                abort(403, message=u"token和主治医生不是同一人")
        if patient_id != -1:
            if patient_medical.get("patient_id") != patient_id:
                abort(403, message=u"open_id和患者不是同一人")
        processes = json.loads(patient_medical.get("processes_json"))

        for process in processes:
            if process.get("process_id") == process_id:
                return {}
        else:
            abort(400, message=u"过程和病历不匹配")
Ejemplo n.º 23
0
def uploadUser():
  username = genPhoneNum()
  deviceId = genID()
  providerName = random.choice(("中国移动", "中国联通", "中国电信"))
  model = random.choice(('MX4 Pro', 'MI 4 LTE', 'SM-G9009W'))
  sdkVersion = random.choice(('19', '17', '21'))
  releaseVersion = random.choice(('4.3', '4.4.4', '4.1.2'))

  user = User()
  query = Query(User) 
  query.equal_to('username', username)

  if(query.find()):
    username = genPhoneNum()

  user.set("username", username)
  user.set("password", "123456")
  user.set("deviceId", deviceId)
  user.set("providerName", providerName)
  user.set("model", model)
  user.set("sdkVersion", sdkVersion)
  user.set("releaseVersion", releaseVersion)
  user.set("value", 0)
  user.sign_up()

  user.set("mobilePhoneNumber", username)
  user.save()
Ejemplo n.º 24
0
def show(year, month):
    month = float(month)
    start, end = get_month_id(year, month), get_month_id(year, month + 0.5)
    if end is None:
        end = 1e10
    if start is None:
        abort(404)
    chinese_num = dict(enumerate(u'一二三四五六七八九', start=1))
    chinese_num.update({10: '十', 11: '十一', 12: '十二'})
    chinese_month = chinese_num.get(int(month))
    if float(month) > int(month):
        chinese_month += u'月份下'
    else:
        chinese_month += u'月份上'
    try:
        topics = Query(Topic).less_than("pid", end).greater_than('pid', start)
        top_topics = topics.descending('reply_num').limit(20).find()
        users = [
            topic.get('author_name') for topic in topics.limit(800).find()
        ]
        users.extend(
            topic.get('author_name')
            for topic in topics.limit(800).skip(800).find())
        counter = collections.Counter(users).most_common(20)
    except LeanCloudError, e:
        if e.code == 101:
            topics = []
        else:
            raise e
Ejemplo n.º 25
0
def checkIfConfirmationCodeMatches(**params):
    print "check if confirmation code matches starts"
    if 'email' in params and 'code' in params:
        try:
            email = params['email']
            print "email: " + email
            code = params['code']
            print "code: " + code
            ConfirmationCode = Object.extend('ConfirmationCode')
            twentyMinutesAgo = datetime.datetime.now() - datetime.timedelta(
                minutes=20)
            print(twentyMinutesAgo)
            query1 = ConfirmationCode.query
            query2 = ConfirmationCode.query
            query3 = ConfirmationCode.query
            query1.equal_to('email', email)
            query2.equal_to('code', code)
            query3.greater_than_or_equal_to('updatedAt', twentyMinutesAgo)
            query12 = Query.and_(query1, query2)
            query = Query.and_(query12, query3)
            query_list = query.find()
            print "check if confirmation code matches ends"

            if len(query_list) == 0:
                return False
            else:
                return True
        except Exception as e:
            print e
            print "check if confirmation code matches ends"
            raise LeanEngineError('系统错误:无法验证验证码')
    else:
        print "email and code cannot be empty"
        print "check if confirmation code matches ends"
        raise LeanEngineError('邮箱以及验证码都不能为空')
Ejemplo n.º 26
0
def test_pointer_query():
    foo = Object.create('Foo')
    bar = Object.create('Bar')
    bar.save()
    foo.set('bar', bar)
    foo.save()

    q = Query('Foo').equal_to('bar', bar)
    assert len(q.find()) == 1

    inner_query = leancloud.Query('Post')
    inner_query.exists("image")
    query = leancloud.Query('Comment')
    query.matches_query("post", inner_query)
    assert query.dump() == {
        'where': {
            'post': {
                '$inQuery': {
                    'className': 'Post',
                    'where': {
                        'image': {
                            '$exists': True
                        }
                    }
                }
            }
        }
    }
Ejemplo n.º 27
0
def result_index(index):
    print 'get result from index', index
    try:
        query = Query(DeviceKey)
        query.equal_to('index', index)
        devicekey = query.first()
        device_name = devicekey.get('name_cn')
        key = devicekey.id
    except:
        return jsonify(error='invalid index')
    try:
        data = get_latest(key)
        hour = data.created_at.hour + 8
        ch2o = data.get('ch2o')
        if ch2o == 65535:
            ch2o = 0
        ch2o = round(ch2o * 1.32 / 1000, 2)
        data.set('ch2o', ch2o)
    except:
        return jsonify(error='invalid key')
    try:
        local_time = utc2local(data.created_at)
    except:
        print 'local time change error'
        local_time = data.created_a
    #pm =average_pm(24,key)
    pm = min_pm(key)
    noise = min_noise(key)
    return render_template('result.html',
                           esp_test=data,
                           local_time=local_time,
                           pm=pm,
                           noise=noise,
                           index=index,
                           device_name=device_name)
def create_demo_application(table_name='DemoApplication'):
    all_real_app = get_all_real_applications()
    DbTable = Object.extend(table_name)

    for index, app in enumerate(all_real_app):
        db_table = DbTable()
        relation = app.relation('tracker')
        # query = Query(DbTable)
        query = relation.query()
        user_list = query.find()
        relation = db_table.relation('tracker')
        for user in user_list:
            ADbTable = Object.extend('Tracker')
            query = Query(ADbTable)
            query.equal_to('objectId',user.id)
            result_list = query.find()
            if result_list:
                tracker = result_list[0]
                relation.add(tracker)
            else:
                print 'tracker not exists and objectId is: %s' %(str(user.id))

        db_table.set('app_name',app.get('app_name'))
        db_table.set('origin_name',app.get('name'))
        db_table.save()
Ejemplo n.º 29
0
def tuchuang_callback():
    code = request.args.get('code')
    if not code:
        abort(404)

    url = 'https://github.com/login/oauth/access_token'
    config = current_app.config
    params = {
        'client_id': config.get('client_id'),
        'client_secret': config.get('client_secret'),
        'code': code,
    }
    result = requests.get(url, params, headers={'Accept': 'application/json'})
    data = result.json()
    params = {"access_token": data.get('access_token')}
    result = requests.get('https://api.github.com/user', params)

    github_user = result.json()
    current_app.logger.debug('result: %s' % github_user)

    try:
        query = Query(GitHubUser)
        user = query.equal_to('email', github_user.get('email')).first()

        session['user'] = leanobject_to_dict(user)
        flash(u'欢迎回来!', category='success')
        return redirect(url_for('.tuchuang_index', result=result.text))
    except LeanCloudError as e:
        _register(github_user)
        flash(u'恭喜你注册成功,请填写七牛资料', category='success')
        return redirect(url_for('.info'))
Ejemplo n.º 30
0
def test_pointer_query():  # type: () -> None
    foo = Object.create("Foo")
    bar = Object.create("Bar")
    bar.save()
    foo.set("bar", bar)
    foo.save()

    q = Query("Foo").equal_to("bar", bar)
    assert len(q.find()) == 1

    inner_query = leancloud.Query("Post")
    inner_query.exists("image")
    query = leancloud.Query("Comment")
    query.matches_query("post", inner_query)
    assert query.dump() == {
        "where": {
            "post": {
                "$inQuery": {
                    "className": "Post",
                    "where": {
                        "image": {
                            "$exists": True
                        }
                    }
                }
            }
        }
    }
Ejemplo n.º 31
0
def queryOneDataByPosition(position):
    query = Query(allPictures)
    query.equal_to('position', position)
    pictures = query.find()
    if len(pictures) > 0:
        return pictures[0].get('image_src')
    return ""
Ejemplo n.º 32
0
def validate_weuser():
    code = request.args.get('code')
    if code:
        url = str.format(
            'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code'
            % (wechat.conf.appid, wechat.conf.appsecret, str(code)))
    else:
        return None
    resp = requests.get(url)
    authorize_result = json.loads(resp.text)
    openid = authorize_result.get('openid')
    token = authorize_result.get('access_token')
    # userinfo = wechat.get_user_info(openid)
    if openid:
        logger.debug("wechat openId: %s, token: %s", openid, str(token))
    else:
        logger.debug("wechat openid invalidated!!!")
    try:
        query = Query(WeUsers)
        query.equal_to('openid', openid)
        wuser = query.find()
        if len(wuser) > 0:
            wuser = wuser[0]
        else:
            logger.debug('try to retrieve userinfo')
            wechathandler.get_user_info(openid, token)
            # wuser = wechathandler.retrieve_weuser(openid)
        return wuser
    except leancloud.LeanCloudError:
        logger.warning("WeUser not found")
Ejemplo n.º 33
0
def delete(**params):
    if 'cid' not in params:
        return {'code': 301, 'message': '参数错误:卡片ID不存在'}
    if 'uid' not in params:
        return {'code': 302, 'message': '参数错误:用户ID不存在'}
    card_id = params['cid']
    user_id = params['uid']
    try:
        query = Query(Card)
        query.include('user')
        card = query.get(card_id)
        if card is not None:
            user = card.get('user')
            if user.get('objectId') == user_id:
                _card = Card.create_without_data(card_id)
                _card.set('hidden', True)
                _card.save()
                return {'code': 200, 'message': 'ok'}
            else:
                result = {'code': 401, 'message': '没有权限'}
                return result
        else:
            result = {'code': 400, 'message': '卡片不存在'}
            return result
    except LeanCloudError as e:
        result = {'code': e.code, 'message': e.error}
        return result
Ejemplo n.º 34
0
def alias_filter(message):
    text = message.text
    query = Query(Alias)
    alises = query.find()
    if len(alises) == 0:
        return
    catch = False
    aliases_dict = {x.get('key'): x.get('value') for x in alises}
    keys = [x.get('key') for x in alises]
    # make the longer key be replaced first
    matches = sorted(re.findall('|'.join(keys), text), key=lambda x: len(x), reverse=True)
    if len(matches) > 0:
        catch = True
    if len(matches) == 1:
        if aliases_dict.get(matches[0]) == ('@' + message.from_user.username):
            return
    for m in matches:
        if '@' in aliases_dict.get(m):
            prefix = ' '
            if (prefix + m) in text:
                text = text.replace(m, aliases_dict.get(m) + ' ')
            else:
                text = text.replace(m, prefix + aliases_dict.get(m) + ' ')
        else:
            text = text.replace(m, aliases_dict.get(m))

    if catch == True:
        text = get_nickname(message.from_user) + ': ' + text
        bot.sendMessage(chat_id=message.chat.id,
                        text=text)
Ejemplo n.º 35
0
    def process_sj_range(item):
        code = item['code'].strip()
        if not code:
            return
        data = {
            'page_num': int(item['page_num']),
            'code': code,
            'type': 'sj',
            'subject': item['subject']
        }

        query = Query(Range)
        query.equal_to('code', code)
        query.equal_to('type', 'sj')
        try:
            one = query.first()
        except LeanCloudError:
            one = Range()
            last_page_num = 0
            one.set('state', 0)
        else:
            last_page_num = one.get('page_num')
            if last_page_num != data['page_num']:
                one.set('state', 0)
            else:
                one.set('state', 1)
        for k, v in data.items():
            one.set(k, v)
        one.set('last_page_num', last_page_num)
        one.save()
        return item
Ejemplo n.º 36
0
def get_readys():
    '''
    返回当前准备好的人
    '''
    user_query = Query(User)
    user_query.equal_to('ready', True)
    return user_query.find()
Ejemplo n.º 37
0
def uploadG3s():
    query = Query(User) 
    query.exists("username")
    results = query.find()

    for i in range (0, 10):
        uploadG3(results)  
Ejemplo n.º 38
0
def changeServerFileName(position, newName):
    query = Query(allPictures)
    query.equal_to('position', position)
    pictures = query.find()
    pictureSelect = pictures[0]
    pictureSelect.set('image_src', newName)
    pictureSelect.save()
Ejemplo n.º 39
0
def get_daily_checkin(start, end):
    global dcCount
    dcCount = 0
    formType = 'DailyCheckIn'
    dateStr = start.strftime('%Y-%m-%d')
    rc = checkWriteState(dateStr, formType)
    if rc:
        print 'already batch inserted'
        return
    print '开始存储 ' + dateStr + ' ' + formType + ' 的数据'
    ckObj = Object.extend('DailyCheckIn')
    ckQuery = Query(ckObj)
    ckQuery.greater_than_or_equal_to('createdAt',start)
    ckQuery.less_than_or_equal_to('createdAt',end)
    def call_back(lst):
        global dcCount
        writeList =  []
        for item in lst:
            ufMap = {}
            ufMap['openId'] = item.get('openId')
            ufMap['checkTime'] = item.get('checkTime')
            ufMap['srcId'] = item.id
            ufMap['createdAt'] = item.created_at
            ufMap['updatedAt'] = item.updated_at
            writeList.append(ufMap)
        dcCount = dcCount + len(writeList)
        if len(writeList) > 0:
            loadDailyCheckIn(writeList)
    map_query(ckQuery, 1000, call_back)
    finishLoadData(dateStr, formType, dcCount)
Ejemplo n.º 40
0
    def get_tracker_of_app(self, app_id=""):
        try:
            self.tracker_list = []
            # user = self.user.become(self.session_token)
            Application = Object.extend("Application")
            query = Query(Application)
            # query.equal_to('user', user)

            # app_id = 'demo 55f7e36f60b2fe7115171b4b'
            print "@@@@@@@@@@@@@@@@@@" + app_id
            query.equal_to("app_id", app_id)
            app_list = query.find()

            if len(app_list) != 1:
                return []
            the_app = app_list[0]

            # Tracker = Object.extend('BindingInstallation')
            # query = Query(Tracker)
            # query.equal_to('application', the_app)
            # app_list = query.find()
            relation = the_app.relation("tracker")
            print relation,
            return 1
        except LeanCloudError, e:
            print e
            return 0
Ejemplo n.º 41
0
def result_index(index):
	print 'get result from index',index
	try:
		query =Query(DeviceKey)
		query.equal_to('index',index)
		devicekey=query.first()
		device_name = devicekey.get('name_cn')
		key=devicekey.id
	except:
		return jsonify(error='invalid index')
	try:
		data=get_latest(key)
		hour=data.created_at.hour+8
		ch2o = data.get('ch2o')
		if ch2o ==65535:
			ch2o=0
		ch2o =round(ch2o*1.32/1000,2)
		data.set('ch2o',ch2o)
	except:
		return jsonify(error='invalid key')
	try:
		local_time=utc2local(data.created_at)
	except:
		print 'local time change error'
		local_time = data.created_a
	#pm =average_pm(24,key)
	pm =min_pm(key)
	noise = min_noise(key)
	return render_template('result.html', esp_test=data,local_time=local_time,pm=pm,noise=noise,index=index,device_name = device_name)
Ejemplo n.º 42
0
def test_save_date(): # type: () -> None
    DateObject = Object.extend('DateObject')
    now = datetime.now()

    d = DateObject(date=now)
    d.save()
    server_date = Query(DateObject).get(d.id).get('date')
    assert now.isoformat().split('.')[0] == server_date.isoformat().split('.')[0]
Ejemplo n.º 43
0
def averageStars(movie):
    sum = 0
    query = Query('Review')
    try:
        reviews = query.find()
    except leancloud.LeanCloudError, e:
        print e
        raise e
Ejemplo n.º 44
0
def test_cloud_query():
    q = Query(GameScore)
    result = q.do_cloud_query('select count(*), * from GameScore where score<11', ['score'])
#     results = result.results
#     assert all(obj in game_scores for obj in results)
#     assert all(obj in results for obj in game_scores)
    assert result.count == 10
    assert result.class_name == 'GameScore'
Ejemplo n.º 45
0
def xu(message):
    query = Query(Haha)
    haha = query.first()
    life = int(haha.get('life')) + 1
    haha.increment('life', 1)
    haha.save()
    reply = get_nickname(message.from_user) + ' 续了 1 秒,excited! 已经续了 ' + str(life) + ' 秒了。'
    bot.sendMessage(chat_id=message.chat.id, text=reply)
Ejemplo n.º 46
0
def editobj(**params):
    from leancloud import Object
    TestObject = Object.extend('TestObject')
    from leancloud import Query
    query = Query(TestObject)
    testObject = query.get('557fd90ee4b0d02dc2e3e342')
    testObject.set('foo', 'edit')
    testObject.save()
Ejemplo n.º 47
0
def test_save_date():
    DateObject = Object.extend("DateObject")
    now = datetime.now()

    d = DateObject(date=now)
    d.save()
    server_date = Query(DateObject).get(d.id).get("date")
    assert now.isoformat().split(".")[0] == server_date.isoformat().split(".")[0]
Ejemplo n.º 48
0
def clear_feed(name, day):
    oldest = datetime.now() - timedelta(days=day)
    query = Query(Feed)
    query.equal_to('name', name).less_than("time", oldest)
    for e in query.find():
        print('delete old feed: %s (%s)' %
              (e.get('title').encode('utf-8'), e.get('time')))
        e.destroy()
Ejemplo n.º 49
0
def device_status():
    try:
        query = Query(DeviceKey)
        query.ascending('index')
        devices = query.find()
    except:
        jsonify(status='find error')
    return render_template('status.html', devices=devices)
Ejemplo n.º 50
0
def averageStars(movie):
    sum = 0
    query = Query('Review')
    try:
        reviews = query.find()
    except leancloud.LeanCloudError, e:
        print e
        raise e
Ejemplo n.º 51
0
def query_proxy():
    proxy_list = []
    query = Query(Proxy)
    query.select('src')
    reslut = query.find()
    for i in reslut:
        proxy_list.append(i.get('src'))
    return proxy_list
Ejemplo n.º 52
0
def query_proxy():
    proxy_list = []
    query = Query(Proxy)
    query.select('src')
    reslut = query.find()
    for i in reslut:
        proxy_list.append(i.get('src'))
    return proxy_list
Ejemplo n.º 53
0
def get_all_feed(name):
    try:
        query = Query(Feed)
        query.equal_to('name', name).descending("time")
        return query.find()
    except LeanCloudError, e:
        if e.code == 101: return []
        else: raise (e)
Ejemplo n.º 54
0
def getOnePictureByPosition(position):
    query = Query(allPictures)
    query.equal_to('position', position)
    pictures = query.find()
    if len(pictures) > 0:
        return pictures[0]
    else:
        return None
Ejemplo n.º 55
0
def test_save_date(): # type: () -> None
    DateObject = Object.extend('DateObject')
    now = datetime.now()

    d = DateObject(date=now)
    d.save()
    server_date = Query(DateObject).get(d.id).get('date')
    assert now.isoformat().split('.')[0] == server_date.isoformat().split('.')[0]
Ejemplo n.º 56
0
Archivo: v2.py Proyecto: fbigun/v2sub
def sub():
    try:
        v2url = Query(V2info).add_descending('createdAt').first()
    except LeanCloudError as e:
        print(e)
        context = None
    else:
        context = v2url.get('urls_vmess_paser')
    return context
Ejemplo n.º 57
0
def xu(message):
    query = Query(Haha)
    haha = query.first()
    life = int(haha.get('life')) + 1
    haha.increment('life', 1)
    haha.save()
    reply = get_nickname(
        message.from_user) + ' 续了 1 秒,excited! 已经续了 ' + str(life) + ' 秒了。'
    bot.sendMessage(chat_id=message.chat.id, text=reply)
Ejemplo n.º 58
0
def getType(type_name):
    query = Query('HJWordStudyCategory')
    query.equal_to('name', type_name)
    querys = query.find()
    if len(querys) > 0:
        data = querys[0]
        return data.get('type_code')
    else:
        print 'not exit'
Ejemplo n.º 59
0
def test_pointer_query():
    foo = Object.create('Foo')
    bar = Object.create('Bar')
    bar.save()
    foo.set('bar', bar)
    foo.save()

    q = Query('Foo').equal_to('bar', bar)
    assert len(q.find()) == 1
Ejemplo n.º 60
0
def test_cloud_query():
    q = Query(GameScore)
    result = q.do_cloud_query(
        'select count(*), * from GameScore where score<11', ['score'])
    #     results = result.results
    #     assert all(obj in game_scores for obj in results)
    #     assert all(obj in results for obj in game_scores)
    assert result.count == 10
    assert result.class_name == 'GameScore'