def WritingOff(request, id_number): try: project = Object.objects.get(id=int(id_number)) except ObjectDoesNotExist: return HttpResponse('Об’єкт не існує.<br>Спробуйте інший id.') if request.method == 'POST': form = WritingOffForm(request.POST) if form.is_valid(): cd = form.cleaned_data act = Activity(time_stamp=dt.now(), aim = project, type='Списання', actor=Custom.myUser.objects.get(username=request.user.username)) act.save() project.save() for (k, v) in cd.items(): if k=='material': v = unicode(v[1:-1].replace('u\'', '').replace('\'', '')) attr_assign = AttributeAssignment(attr_name=k, attr_value=v, attr_label=form.fields[k].label, event_initiator=act, aim=project) attr_assign.save() return HttpResponseRedirect('/') else: return render(request, 'AddOnTs.html', {'form': form, 'errors': form.errors}) else: ps_code = get_attrib_assigns('Приймання на постійне зберігання', project, 'PS_code') inventory_number = get_attrib_assigns('Інвентарний облік', project, 'inventory_number') spec_inventory_numb = get_attrib_assigns('Спеціальний інвентарний облік', project, 'spec_inventory_numb') ts_code = get_attrib_assigns('Приймання на тимчасове зберігання', project, 'TS_code') data = {'name': project.name, 'is_fragment': project.is_fragment, 'amount': project.amount, 'note': project.note, 'PS_code': ps_code, 'inventory_number': inventory_number, 'spec_inventory_numb': spec_inventory_numb, 'TS_code': ts_code, } form = WritingOffForm(initial=data) return render(request, 'AddOnTs.html', {'form': form, 'label': 'Списати об’єкт'})
def FromPSToTS(request, id_number): try: project = Object.objects.get(id=int(id_number)) except ObjectDoesNotExist: return HttpResponse('Об’єкт не існує.<br>Спробуйте інший id.') if request.method == 'POST': form = FromPStoTSForm(request.POST) if form.is_valid(): cd = form.cleaned_data act = Activity(time_stamp=dt.now(), aim = project, type='Видача предметів з Постійного зберігання на Тимчасове зберігання', actor=Custom.myUser.objects.get(username=request.user.username)) act.save() project.save() for (k, v) in cd.items(): if k=='material': v = unicode(v[1:-1].replace('u\'', '').replace('\'', '')) attr_assign = AttributeAssignment(attr_name=k, attr_value=v, attr_label=form.fields[k].label, event_initiator=act, aim=project) attr_assign.save() return HttpResponseRedirect('/') else: return render(request, 'AddOnTs.html', {'form': form, 'errors': form.errors}) else: ps_code = get_attrib_assigns('Приймання на постійне зберігання', project, 'PS_code') inventory_number = get_attrib_assigns('Інвентарний облік', project, 'inventory_number') data = {'name': project.name, 'is_fragment': project.is_fragment, 'amount': project.amount, 'date_creation': project.date_creation, 'place_of_creation': project.place_of_creation, 'author': project.author, 'technique': project.technique, 'material': project.material.decode('unicode-escape').split(', '), 'size': project.size, 'description': project.description, 'note': project.note, 'condition': project.condition, 'condition_descr': project.condition_descr, 'PS_code': ps_code, 'inventory_number': inventory_number, } form = FromPStoTSForm(initial=data) return render(request, 'AddOnTs.html', {'form': form, 'label': 'Видати об’єкт з ПЗ на ТЗ'})
def get(self, *args): respo = self.response.out.write output = self.dbg respo ("<html><head><title>Test</title></head><body>") if (self.request.path.endswith('/clean')): output ("Begin Clean Up") self.cleanUp() output ("Cleaning up done") return output("Now let's go") billList = [('Cort', '75.5'), ('Balls', '15')] output ("BillList: ", billList) allacts = Activity.all() for act in allacts: bill = act.bill for entry in bill: output ("Entry:", entry, ",", lb = False) output() output ("acts:", act.key().id(), "Total Expense:", act.expense, "Expanse Bill: ", bill) mem = Membership.all().get() output ("New activity") act = Activity(name = "test act", duration=2.0, organizer = mem.user, club = mem.club, bill = billList, expense = '100' ) output ("Expense:", act.expense) output ("Bill:", act.bill) output ("Now, put") key = act.put() output ("Act Saved: ", act.is_saved(), "Key is ", key, " Id is", key.id()) respo("</body></html>")
def TempSave(request, id_number=0): try: project = Object.objects.get(id=int(id_number)) except ObjectDoesNotExist: if id_number != 0: return HttpResponse('Об’єкт не існує.<br>Спробуйте інший id.') else: project = Object(name='Новий') if request.method == 'POST': form = TempSaveForm(request.POST, request.FILES) if form.is_valid(): cd = form.cleaned_data act = Activity(time_stamp=dt.now(), aim=project, type='Приймання на тимчасове зберігання', actor=Custom.myUser.objects.get(username=request.user.username)) act.save() project.reason = cd['reason'] project.save() for (k, v) in cd.items(): if k=='material': v = unicode(v[1:-1].replace('u\'', '').replace('\'', '')) attr_assign = AttributeAssignment(attr_name=k, attr_value=v, attr_label=form.fields[k].label, event_initiator=act, aim=project) attr_assign.save() return HttpResponseRedirect('/') else: return render(request, 'AddOnTs.html', {'form': form}) else: data = {'name': project.name, 'is_fragment': project.is_fragment, 'amount': project.amount, 'date_creation': project.date_creation, 'place_of_creation': project.place_of_creation, 'author': project.author, 'technique': project.technique, 'material': project.material.decode('unicode-escape').split(', '), 'size': project.size, 'condition': project.condition, 'condition_descr': project.condition_descr, 'description': project.description, 'price': project.price, 'note': project.note} form = TempSaveForm(initial=data) return render(request, 'AddOnTs.html', {'form': form, 'label': 'Прийняти об’єкт на ТЗ'})
def activity(r, u='', action='', group=''): timestamp = datetime.now().strftime('%Y%m%d%H%M%S') act = Activity(believer=u, group=group, timestamp=timestamp, action=action, ipaddress=IP(r), source='web', category='track') act.save(True) return 'OK'
def login_User(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user != None: if user.is_active == True: userprofile = user.userprofile login(request, user) messages.success(request, 'Welcome, %s!' % (username)) Activity.log_activity("ACTIVITY_LOGIN", user.userprofile) next_url = request.GET.get('next', URL_HOME) if "//" in next_url and re.match(r'[^\?]*//', next_url): next_url = settings.LOGIN_REDIRECT_URL return redirect(next_url) else: messages.error(request, "You haven't activated your account yet. Please check your email.") else: messages.error(request, 'Invalid Login credentials. Please try again.') next_path = request.GET.get('next', URL_HOME) form = AuthenticationForm() return render_to_response(HTML_LOGIN, {'form':form}, RequestContext(request, {'next': next_path}))
def _parse_activities_response(self, jsonBody): """ """ activities = [] data = json.loads(str(jsonBody)) for activity in data['data']: # Create a new activity a = Activity(id=activity['id'], version=activity['version']) # Get the coords and set the geometry # Check first the geometry type # Handle MultiPoint geometries if activity['geometry']['type'].lower() == "multipoint": points = [] for coords in activity['geometry']['coordinates']: points.append(QgsPoint(coords[0], coords[1])) a.setGeometry(QgsGeometry.fromMultiPoint(points)) # Handle Point geometries if activity['geometry']['type'].lower() == "point": coords = activity['geometry']['coordinates'] a.setGeometry(QgsGeometry.fromPoint(QgsPoint(coords[0], coords[1]))) # Append it to the list activities.append(a) return activities
def chooseActivity(request): if request.method=='POST': #OK this is super not the way to do this, but oh well #also, may end up trying to add an activity and not be able to #super confusing probably, not at all the right way to do things pvalues=request.POST.copy() if not request.POST['activity']: if len(request.POST['add_activity']): newActivity=Activity(name=request.POST['add_activity']) newActivity.save(request) pvalues['activity']=newActivity.id aform=ActivityChooseForm(pvalues, request=request) if aform.is_valid(): aRating=aform.save(commit=False) aRating.preDateTime=datetime.datetime.now() aRating.save(request) rform=ActivityRatingForm(instance=aRating) pk=aRating.id redirectURL='/activity/'+str(pk)+'/rate/' return redirect(redirectURL) else: return render(request, 'activity/choose.html', {'aform':aform}) aform=ActivityChooseForm(request=request) return render(request, 'activity/choose.html',{'aform':aform})
def rateCivi(request): civi_id = request.POST.get('civi_id', '') rating = request.POST.get('rating', '') account = Account.objects.get(user=request.user) c = Civi.objects.get(id=civi_id) try: prev_act = Activity.objects.get(civi=c, account=account) except Activity.DoesNotExist: prev_act = None try: activity_data = { 'account': account, 'thread': c.thread, 'civi': c, } if rating == "vneg": c.votes_vneg = c.votes_vneg + 1 vote_val = 'vote_vneg' elif rating == "neg": c.votes_neg = c.votes_neg + 1 vote_val = 'vote_neg' elif rating == "neutral": c.votes_neutral = c.votes_neutral + 1 vote_val = 'vote_neutral' elif rating == "pos": c.votes_pos = c.votes_pos + 1 vote_val = 'vote_pos' elif rating == "vpos": # c.votes_vpos = c.votes_vpos + 1 vote_val = 'vote_vpos' activity_data['activity_type'] = vote_val c.save() if prev_act: prev_act.activity_type = vote_val prev_act.save() data = { 'civi_id':prev_act.civi.id, 'activity_type': prev_act.activity_type, 'c_type': prev_act.civi.c_type } else: act = Activity(**activity_data) act.save() data = { 'civi_id':act.civi.id, 'activity_type': act.activity_type, 'c_type': act.civi.c_type } return JsonResponse({'data' : data}) except Exception as e: return HttpResponseServerError(reason=str(e))
def register_activity(request, time='', data='', client=''): carrier, created = Carrier.objects.get_or_create(data=data) if carrier.is_registered(): Activity.create(time, client, carrier) return HttpResponse(status=200) else: return HttpResponse(status=403)
def auto_checkout(): active_checkins = Checkin.checkins.active() for checkin in active_checkins: auto_checkout_activity = Activity() auto_checkout_activity = checkin.checkin_activity auto_checkout_activity.time = datetime.datetime.now() auto_checkout_activity.save() checkin.checkout_activity = auto_checkout_activity checkin.save()
def create_activity(activity_type, lead=None, job=None): description = None lead_key = None job_key = None if job is not None and job.key is not None: job_key = job.key if lead is not None and lead.key is not None: lead_key = lead.key else: if job is not None and job.lead is not None: lead_key = job.lead if activity_type == 'LEAD_SENT': description = _build_lead_sent_description(lead.to_json()) elif activity_type == 'LEAD_READ': description = _build_lead_read_description(lead) elif activity_type == 'LEAD_CLICKED': description = _build_lead_clicked_description(lead) elif activity_type == 'LEAD_PENDING_PAYMENT': description = _build_lead_pending_payment_description(lead) elif activity_type == 'LEAD_CONVERTED': description = _build_lead_converted_description(lead) elif activity_type == 'JOB_CREATED': Activity.set_job_in_all_lead_activities(job) description = _build_job_created_description(job) elif activity_type == 'JOB_ASSIGNED': description = 'The job has been taken by a Flixer' elif activity_type == 'JOB_CANCELLED_BY_FLIXER': description = 'The job has been cancelled by the flixer' elif activity_type == 'JOB_CANCELLED_BY_PROPERTY_OWNER': description = 'The job has been cancelled by the property owner' elif activity_type == 'JOB_RESCHEDULED': description = 'The job has been rescheduled by the property owner' elif activity_type == 'JOB_PUBLISHING_STARTED': description = 'The job publishing has been started' elif activity_type == 'JOB_PUBLISHING_DONE': description = 'The job publishing has been done' elif activity_type == 'JOB_PUBLISHING_REDO_DONE': description = 'The job fixes publishing has been done' elif activity_type == 'JOB_REPROVED': description = 'The property owner has reproved the job' elif activity_type == 'JOB_APPROVED': description = 'The property owner has approved the job' elif activity_type == 'JOB_PUBLISHED_AT_VALUEGAIA': description = 'The job has been published at ValueGaia' elif activity_type == 'JOB_FINISHED': description = 'The job has been finished' if description is not None: Activity.create(description, activity_type, lead_key=lead_key, job_key=job_key) return True
def logout_User(request): # Update last_logout date field user = get_object_or_404(UserProfile, pk=request.user.userprofile.id) user.last_logout = datetime.now() user.save() Activity.log_activity("ACTIVITY_LOGOUT", request.user.userprofile) messages.success(request, "See you next time!") logout(request) return redirect(URL_HOME)
def challenge_count(player, days=None): """ Return the count of challenges played by player in the last x _days_. All challenges if days == None """ if not days: return Activity.get_player_activity(player).filter(action__contains='chall').count() start = datetime.now() - timedelta(days=days) return Activity.get_player_activity(player).filter( action__contains='chall', timestamp__gte=start).count()
def update_visibility(aid): """ Pulls the existing activity and then pushes it again """ logger.warning('update_visibility aid:%s' % aid) logger.warning('update_visibility aid:%s pulling' % aid) Activity.pull(aid, confirmed = False) logger.warning('update_visibility aid:%s pushing' % aid) push_activity(aid) logger.warning('update_visibility aid:%s pushed' % aid)
def Passport(request, id_number): try: project = Object.objects.get(id=int(id_number)) except ObjectDoesNotExist: if id_number != '0': return HttpResponse('Об’єкт не існує.<br>Спробуйте інший id.') else: project = Object(name='Новий') if request.method == 'POST': form = PassportForm(request.POST) if form.is_valid(): cd = form.cleaned_data project.save() act = Activity(time_stamp=dt.now(), aim = project, type='Науково-уніфікований паспорт', actor=Custom.myUser.objects.get(username=request.user.username)) act.save() for (k, v) in cd.items(): if k=='material': v = unicode(v[1:-1].replace('u\'', '').replace('\'', '')) attr_assign = AttributeAssignment(attr_name=k, attr_value=v, attr_label=form.fields[k].label, event_initiator=act, aim=project) attr_assign.save() return HttpResponseRedirect('/') else: return render(request, 'AddOnTs.html', {'form': form, 'errors': form.errors}) else: collection = get_attrib_assigns('Інвентарний облік', project, 'collection') ps_code = get_attrib_assigns('Приймання на постійне зберігання', project, 'PS_code') inventory_number = get_attrib_assigns('Інвентарний облік', project, 'inventory_number') spec_inventory_numb = get_attrib_assigns('Спеціальний інвентарний облік', project, 'spec_inventory_numb') old_inventory_numbers = get_attrib_assigns('Інвентарний облік' or 'Приймання на постійне зберігання',project, 'old_registered_marks') date_place_creation = ' '.join([project.date_creation, project.place_of_creation]) date_place_detection = ' '.join([project.date_detection, project.place_detection]) date_place_existence = ' '.join([project.date_existence, project.place_existence]) source = get_attrib_assigns('Приймання на постійне зберігання', project, 'source') classify = get_attrib_assigns('Інвентарний облік', project, 'classify') typology = get_attrib_assigns('Інвентарний облік', project, 'typology') metals = get_attrib_assigns('Спеціальний інвентарний облік', project, 'metals') stones = get_attrib_assigns('Спеціальний інвентарний облік', project, 'stones') bibliography = get_attrib_assigns('Інвентарний облік', project, 'bibliography') data = {'collection': collection, 'PS_code': ps_code, 'inventory_number': inventory_number, 'spec_inventory_numb': spec_inventory_numb, 'old_inventory_numbers': old_inventory_numbers, 'identifier': project.identifier, 'storage': project.storage, 'name': project.name, 'author': project.author, 'date_place_creation': date_place_creation, 'date_place_detection': date_place_detection, 'date_place_existence': date_place_existence, 'source': source, 'way_of_found': project.way_of_found, 'link_on_doc': project.link_on_doc, 'classify': classify, 'typology': typology, 'amount': project.amount, 'size': project.size, 'material': project.material.decode('unicode-escape').split(', '), 'technique': project.technique, 'metals': metals, 'stones': stones, 'description': project.description, 'condition': project.condition, 'condition_descr': project.condition_descr, 'recomm_for_restauration': project.recomm_for_restauration, 'transport_possibility': project.transport_possibility, 'price': project.price, 'bibliography': bibliography} form = PassportForm(initial=data) return render(request, 'AddOnTs.html', {'form': form, 'label': 'Створити науково-уніфікований паспорт об’єкта'})
def saveDataFromRequest(self, req_body): request_objs = req_body.splitlines() students = json.loads(request_objs[0]) activities = json.loads(request_objs[1]) comments = json.loads(request_objs[2]) Student.get_from_json(students) Comment.get_from_json(comments) Activity.get_from_json(activities)
def public_act(request): ret_data={} errors =[] if request.method=='POST': if 'user' in request.session: theme_act = request.POST.get('theme_act','') if not theme_act: errors.append('theme not exist') class_act = request.POST.get('class_act','') date_act = request.POST.get('date_act','') time_act = request.POST.get('time_act','') num_act = request.POST.get('num_act','') address_act = request.POST.get('address_act','') detail_act = request.POST.get('detail_act','') username = request.session['user'] date_time = date_act + " " + time_act userid = User.objects.get(name=username).id now = datetime.datetime.fromtimestamp(time.mktime(time. strptime(date_time, r"%Y/%m/%d %H:%M:%S"))) datess = str(now) print datess try: a = int(num_act) except Exception: ret_data["ret"] = 'no int' return HttpResponse(json.dumps(ret_data), content_type='application/json') print "now is " +str(datess) if len(errors) > 0: ret_data['ret'] = 'no theme' elif not num_act: ret_data['ret'] = 'no people_count' else: pub_data = Activity(category = class_act, theme = theme_act, begin_datatime = datess, people_count = num_act, details = detail_act, submit_peopleId = userid, location=address_act,joined_peopleId=userid) #total=len(Activity.objects.all())+1 pub_data.istimeout = 'n' pub_data.save() total = pub_data.id u=User.objects.get(id=userid) if u.uncompleted_id=='': u.uncompleted_id=str(total) else: u.uncompleted_id+=(','+str(total)) u.save() ret_data['ret'] = 'ok' else: ret_data['ret'] = 'failed' else: ret_data['ret'] = 'failed' return HttpResponse(json.dumps(ret_data), content_type='application/json')
def fund(row): ''' A funding of a new individual Takes in a list of a row in CSV.''' port_indi = Port_Indi() act = Activity() # Creating the new portfolio/individual port_indi.cash = row[2] port_indi.networth = row[2] port_indi.name = row[1] # Check to see if its an Individual or a Porfolio if row[0] == 'fund': port_indi.is_individual = False else: port_indi.is_individual = True #port_indi.last_quote = Quote() port_indi.last_activity = act port_indi.save() # Activity act = Activity() act.amount = row[2] act.act_type = "fund" act.port_indi1 = port_indi act.date = row[3].replace('-', '') act.save() # Referencing activity port_indi.last_activity = act port_indi.save() print str(port_indi) + ' HAS BEEN FUNDED'
def filterActivityData(dayOfActivityData): #filter walkingArray = [] runningArray = [] stationaryArray = [] carArray = [] unknownArray = [] lastobj = Activity(duration=0,type=1) sumDuration = 0 for actobj in dayOfActivityData: if actobj.type == 1: if lastobj.type == 1: if len(walkingArray) > 0: sumDuration = actobj.duration + walkingArray[len(walkingArray)-1] else: sumDuration = actobj.duration walkingArray.append(sumDuration) elif actobj.type == 2: if lastobj.type == 2: if len(runningArray) > 0: sumDuration = actobj.duration + runningArray[len(runningArray)-1] else: sumDuration = actobj.duration runningArray.append(sumDuration) elif actobj.type == 3: if lastobj.type == 3: if len(stationaryArray) > 0: sumDuration = actobj.duration + stationaryArray[len(stationaryArray)-1] else: sumDuration = actobj.duration stationaryArray.append(sumDuration) elif actobj.type == 4: if lastobj.type == 4: if len(carArray) > 0: sumDuration = actobj.duration + carArray[len(carArray)-1] else: sumDuration = actobj.duration carArray.append(sumDuration) else: if lastobj.type == 5: if len(unknownArray) > 0: sumDuration = actobj.duration + unknownArray[len(unknownArray)-1] else: sumDuration = actobj.duration unknownArray.append(sumDuration) lastobj = actobj lastobj.duration = actobj.duration lastobj.type = actobj.type filteredData = {"walking":walkingArray,"running":runningArray,"stationary":stationaryArray,"car":carArray,"unknown":unknownArray} return filteredData
def getActModel(self): aid, = self.urlcfg.analyze(self.request.path) if (aid): id = int(aid) return Activity.get_by_id(id) else: return None
def getActModel(self, id): try: iid = int(id) except: return None actobj = Activity.get_by_id(iid) return actobj
def refused_challenges(player): """ Return the count of refused challenges in the last week """ start = datetime.now() + timedelta(days=-7) return Activity.get_player_activity(player).filter(action__contains='chall-refused', timestamp__gte=start, user_from=player).count()
def pull_confirmed_activity_later(aid): """ Pulls the activity from confirmed users Will be called by task eta to be activity when + CONFIRMED_USER_PULL_HOURS """ success = Activity.pull(aid, confirmed = True) worked = 'successfully' if success else 'not successfully' return "pull_confirmed_activity_later on %s %s" % (str(aid), worked)
def post(self, request, format=None): date = request.DATA.get('date') try: activity = Activity.objects.get(name=request.DATA.get('activity')) except Activity.DoesNotExist: activity = Activity(name=request.DATA.get('activity'), average_price=0) activity.save() p = Process(date=request.DATA.get('date'), activity=activity, average_price=0) p.save() consumer_list = json.loads(request.DATA.get('list')) user_to_be_saved = [] total = 0 try: for num, i in enumerate(consumer_list): name = i.get('name') prepay = i.get('prepay') consume = i.get('consume') #check name user = User.objects.get(name=name) p.participants.add(user) #user money user.remain += prepay - consume user_to_be_saved.append(user) total += consume #send email except: print sys.exc_info() p.delete() return Response(status=404) #caculate the average price of process p.average_price =total/(num +1) #caculate the average price of activity if p.average_price == 0: activity.average_price = p.average_price else: activity.average_price = (p.average_price + activity.average_price)/2 p.save() for i in user_to_be_saved: i.save() return Response({"detail":"success"} ,status=200)
def check_activity_cards(user_id, friends=[], fofs=[], access_token=None): """ For a first time user, will check that the cards have activities from their friends & fofs populated """ user = User.get_by_id(user_id) if (not friends) and access_token: graph = facebook.GraphAPI(access_token) friends = graph.get_connections("me", "friends").get('data') #We check straight away that the friend & network cards are there friends = [friend['id'] for friend in friends] now = datetime.datetime.now() created_min = now - datetime.timedelta(hours=24) activities = col_get(ACTIVITY_, {'suggester_id' : {'$in' : friends + fofs}, 'created_on' : {'$gte' : created_min}}) match = {'user_id' : user.get('_id')} cs = col_get(CARDSTORE, match, find='one') cards = cs.get('cards', []) if cs else [] aids = [] for card in cards: id_ = card.get('id', '') if id_.startswith('a'): aids.append(id_) new_acts = [] for activity in activities: act_id = activity.get('_id') s_id = activity.get('suggester_id') vis = activity.get('visibility') expiry = activity.get('expiry') keen_ids = [keen.get('user_id') for keen in activity.get('keens')] if (act_id not in aids) and (expiry >= now) and (user_id not in keen_ids): if (s_id in friends) or (s_id in fofs and vis == 'fof') or (vis == 'n' and user.get('network')==activity.get('network')): new_acts.append(activity) aids.append(act_id) for act in new_acts: activity_timeline_dict = { "suggester_id" : act.get('suggester_id'), # "created_on" : activity['created_on'], "keyword" : act['keyword'], "id" : 'a'+str(act['_id']), #This has to be string to consistency "activity_hash" : act["hash"], "confirmed" : False, "visibility" : act.get('visibility'), "keen" : False, "expiry" : activity['expiry'] } Activity._push_activity_to_userid(user.get('_id'), activity_timeline_dict)
def lazy_login(sender, **kwargs): request=kwargs['request'] user=kwargs['user'] if request.user.is_active: #This is not at all where I want to put this code, but hopefully this should work for now more or less. #Damn I need to debug things! if Activity.objects.all_with_permission(request).count()==0: #first create default activities defActs=Activity.objects.filter(is_default=1) for act in defActs: act.pk=None act.is_default=0 act.save(request) Activity.reparent_all_my_session_objects(request.session, user) ActivityRating.reparent_all_my_session_objects(request.session, user, request)
def wrong_first_qotd(player): """ Check if the first answer to qotd was a wrong answer. """ activities = Activity.get_player_activity(player).filter(action__contains='qotd') if not activities.count() == 1: return False if activities[0].action == 'qotd-wrong': return True return False
def _parse_activities_response(self, jsonBody): """ """ activities = [] data = json.loads(str(jsonBody)) for activity in data["data"]: # Create a new activity a = Activity(id=activity["id"], version=activity["version"]) # Get the point coords and set the geometry coords = activity["geometry"]["coordinates"] a.setGeometry(QgsGeometry.fromPoint(QgsPoint(coords[0], coords[1]))) # Append it to the list activities.append(a) return activities
def challenges_played_today(player): """ Return the count of challenges played today """ today = datetime.now().date() activities = Activity.get_player_activity(player).filter(action__contains='chall', timestamp__gte=today) result = 0 for a in activities: if not 'refused' in a.action: result += 1 return result
def consecutive_qotd_correct(player): """ Return the count of correct qotd in a row Maximum: 10 (last ten) """ activities = Activity.get_player_activity(player).filter(action__contains='qotd').order_by('-timestamp')[:10] result = 0 for i in activities: if 'correct' in i.action: result += 1 else: return result return result
def addRecord(nameIn, activityIn, recordIn, yearIn, numberIn, moreInfoIn): #import the Activity and Record model from models.py from models import Activity, Record #get the ID of the record that is selected activityID = Activity.get(Activity.activityName == activityIn) #create record record = Record.create(person=nameIn, activity=activityID.id, record=recordIn, number=numberIn, year=yearIn, moreInformation=moreInfoIn) record.save()
def addTopic(): form = NewTopic() if form: data = request.form newTopic = Topic(Title = data['title'],content = data['content']) newPost = Post(content = data['content'],topic = data['title'],author = current_user.username) activity = Activity(name = current_user.username, type = 't', topic = newPost.topic) db.session.add(newTopic) db.session.add(newPost) db.session.add(activity) db.session.commit() return redirect(url_for('allTopics')) return redirect(url_for('allTopics'))
def test_post(self): resp = self.get_response('post', text='silowe html') self.assertEqual(200, resp.status_int, resp.text) self.assert_equals(self.activities_no_extras[0], util.trim_nulls(resp.json)) activities = Activity.query().fetch() self.assertEqual(1, len(activities)) self.assertEqual(self.source, activities[0].source) self.assert_equals( self.activities_no_extras[0], util.trim_nulls(json_loads(activities[0].activity_json))) self.assertEqual('silowe html', activities[0].html)
def get_session_id_by_activity(activity_id): """ Get the session ID that this activity_id is a part of. :param activity_id: ID of the activity_id. :type activity_id: Integer :returns: The project ID. :rtype: Integer """ activity = Activity.get_by_id(activity_id) return activity.session_id if activity else 0
def test_post_merge_comments(self): key = self.source.put() gr_facebook.now_fn().MultipleTimes().AndReturn(datetime(1999, 1, 1)) self.mox.ReplayAll() # existing activity with one of the two comments in MBASIC_ACTIVITIES existing_activity = copy.deepcopy(MBASIC_ACTIVITIES[1]) existing_activity['object']['replies'] = { 'totalItems': 1, 'items': [MBASIC_ACTIVITIES_REPLIES[1]['object']['replies']['items'][0]], } activity_key = Activity(id='tag:facebook.com,2013:456', activity_json=json_dumps(existing_activity)).put() # send MBASIC_HTML_POST to /post, check that the response and stored # activity have both of its comments resp = self.get_response('post', text=MBASIC_HTML_POST) self.assertEqual(200, resp.status_int, resp.text) self.assert_equals(MBASIC_ACTIVITY, resp.json) activity = activity_key.get() self.assert_equals(MBASIC_ACTIVITY, json_loads(activity.activity_json))
def consecutive_seens(player, timestamp): """ Return the count of consecutive seens for a player, until timestamp """ activities = Activity.get_private_activity(player).filter( action='seen').order_by('-timestamp')[0:100] today = timestamp.date() for i, activity in enumerate(activities): date = activity.timestamp.date() if date != today + timedelta(days=-i): return i return len(activities)
def getActivities(): from models import Activity #below is to create a new one # new_activity = Activity.create(name="Water Polo") # create a list. A dictionary isn't needed because we only have one type of values activitiesList = [] #iterate through activities in database for Activity in Activity.select(): #get activity name and add it to list activityName = Activity.activityName activitiesList.append(activityName) #return the activity list in a list format return activitiesList
def test_post(self): self.source.put() gr_facebook.now_fn().MultipleTimes().AndReturn(datetime(1999, 1, 1)) self.mox.ReplayAll() resp = self.get_response(f'post', text=MBASIC_HTML_POST) self.assertEqual(200, resp.status_int, resp.text) self.assertEqual(MBASIC_ACTIVITY, resp.json) activities = Activity.query().fetch() self.assertEqual(1, len(activities)) self.assertEqual(self.source.key, activities[0].source) self.assertEqual(MBASIC_ACTIVITY, json_loads(activities[0].activity_json))
def test_post_merge_comments(self): self.source.put() # existing activity with one of the two comments in HTML_VIDEO_COMPLETE existing_activity = copy.deepcopy(HTML_VIDEO_ACTIVITY) existing_activity['object']['replies'] = { 'totalItems': 1, 'items': [HTML_VIDEO_ACTIVITY_FULL['object']['replies']['items'][0]], } activity_key = Activity( id='tag:instagram.com,2013:789_456', activity_json=json_dumps(existing_activity)).put() # send HTML_VIDEO_COMPLETE to /post, check that the response and stored # activity have both of its comments resp = self.get_response('post', text=HTML_VIDEO_COMPLETE) self.assertEqual(200, resp.status_int, resp.text) self.assert_equals(HTML_VIDEO_ACTIVITY_FULL, resp.json) activity = activity_key.get() self.assert_equals(HTML_VIDEO_ACTIVITY_FULL, json_loads(activity.activity_json))
def consecutive_chall_won(player): """ Return the count of won challenges in a row Maximum: 10 (last ten) """ activities = Activity.get_player_activity(player).filter(action__contains='chall').order_by('-timestamp')[:10] result = 0 for i in activities: if 'won' in i.action and i.user_from.id == player.id: result += 1 else: return result return result
def authenticate(): user = User.query.filter_by(email=request.form.get('email')).first() if user is not None and user.verify_password(request.form.get('password')): login_user(user) user.last_login_at = datetime.now() activity = Activity(description='Logged into system', user_id=user.id) db.session.add(user) db.session.add(activity) db.session.commit() return redirect(url_for('admin.dashboard')) flash('Invalid username or password') return redirect(url_for('auth.login'))
def delete_record(record_model, id_number): """ Delete a record from database :param record_model: The model for which to delete a record. :type record_model: :func:`sqlalchemy.ext.declarative.declarative_base` :param id_number: Recond id. :type id_number: Integer :returns: Success. :rtype: Boolean """ try: instance = record_model.get_by_id(id_number) if isinstance(instance, Project): activities = Session.get('all', Activity.project_id == id_number) sessions = Session.get('all', Session.project_id == id_number) msg = 'Deleting sessions:' for session in sessions: msg = msg + '\r\n' + str(session) + (' PID {0}'.\ format(session.project_id) ) LOGGER.debug(msg) Activity.delete_many(activities) Session.delete_many(sessions) instance.delete() return True except SQLAlchemyError: log_msg = ('Delete record exception model {model_name!s} with ' 'id {id_number}.') log_msg = log_msg.format(model_name=record_model.__name__, id_number=id_number) LOGGER.exception(log_msg) return False
def test_post(self): source = Instagram.create_new(self.handler, actor={'username': '******'}) resp = app.application.get_response( '/instagram/browser/post?token=towkin', method='POST', text=HTML_VIDEO_COMPLETE) self.assertEqual(200, resp.status_int, resp.text) self.assertEqual(HTML_VIDEO_ACTIVITY_FULL, resp.json) activities = Activity.query().fetch() self.assertEqual(1, len(activities)) self.assertEqual(source.key, activities[0].source) self.assertEqual(HTML_VIDEO_ACTIVITY_FULL, json_loads(activities[0].activity_json))
def load_activities(session): # use u.activities - it has data about all activities with open("seed_data/u.activities") as csvfile: activities = csv.reader(csvfile, delimiter="|") for activity in activities: new_activity = Activity(title=activity[1], photo_url=activity[2], description=activity[3], category_id=activity[4], website_url=activity[5], google_map_url=activity[6]) print new_activity.title print new_activity.category_id session.add(new_activity) session.commit()
def test_reactions_bad_scraped_data(self): Activity(id='tag:fa.ke,2013:123_456', source=self.source, activity_json=json_dumps(self.activities[0])).put() bad_json = '<html><not><json>' self.mox.StubOutWithMock(FakeGrSource, 'merge_scraped_reactions') FakeGrSource.merge_scraped_reactions(bad_json, mox.IgnoreArg() ).AndRaise((ValueError('fooey'))) self.mox.ReplayAll() resp = self.post(f'reactions?id=tag:fa.ke,2013:123_456&{self.auth}', data=bad_json) self.assertEqual(400, resp.status_code) self.assertEqual("Scrape error: couldn't parse extras: fooey", resp.get_data(as_text=True))
def save(self, box: Box, activity: ap.BaseActivity) -> None: """Save an Activity in database""" current_app.logger.info(f"asked to save an activity {activity!r}") # Save remote Actor ap_actor = activity.get_actor() domain = urlparse(ap_actor.id) current_app.logger.debug(f"actor.id=={ap_actor.__dict__}") current_app.logger.debug(f"actor domain {domain.netloc} and " f"name {ap_actor.preferredUsername}") actor = Actor.query.filter(Actor.domain == domain.netloc, Actor.name == ap_actor.preferredUsername).first() # FIXME TODO: check if it still works with unknown remote actor if not actor: current_app.logger.debug("cannot find actor") actor = Actor.query.filter(Actor.url == ap_actor.id).first() if not actor: current_app.logger.debug(f"actor {ap_actor.id} not found") actor, user = create_remote_actor(ap_actor) db.session.add(user) db.session.add(actor) current_app.logger.debug("created one in DB") else: current_app.logger.debug(f"got local one {actor.url}") else: current_app.logger.debug(f"got remote one {actor.url}") # Save Activity act = Activity() act.payload = activity.to_dict() act.url = activity.id act.type = activity.type act.box = box.value # Activity is local only if the url starts like BASE_URL base_url = current_app.config["BASE_URL"] act.local = activity.id.startswith(base_url) act.actor_id = actor.id db.session.add(act) db.session.commit()
def newPost(): form = NewPost() topic = request.args.get('topic') if form.validate_on_submit(): data = request.form newPost = Post(content=data['content'], topic=topic, author=current_user.username) activity = Activity(name=current_user.username, type='p', topic=newPost.topic) db.session.add(newPost) db.session.add(activity) db.session.commit() return redirect(request.referrer) return redirect(request.referrer)
def get_project_id_by_activity(activity_id): """ Get the project ID that this activity_id is a part of. :param activity_id: ID of the activity_id. :type activity_id: Integer :returns: The project ID. :rtype: Integer """ try: activity = Activity.get_by_id(activity_id) except NoResultFound: return 0 return activity.project_id if activity else 0
def view_activity(activity_id): """ View activity :param activity_id: string :return: Render activity view or redirect to home page """ # Check if activity_id is a valid ObjectId and exists in DB if check_activity_id(activity_id): activity_data = Activity().view_activity(activity_id) if activity_data is None: flash('Activity not found', 'error') return redirect(url_for('index')) # Set imageURL for activity image activity_data['imageURL'] = set_imageURL(activity_id) user_session = session.get('user') # Check if a user is logged-in if user_session: userid = ObjectId(user_session['_id']['$oid']) user_data = list( mongo.db.users.find({'_id': ObjectId(userid)}, { '_id': 0, 'favourites': 1 })) # Check if activity is in current users favourites if 'favourites' in user_data[0]: user_favourites = user_data[0]['favourites'] if ObjectId(activity_id) in user_favourites: activity_data['inUsersFavourites'] = 'Y' else: activity_data['inUsersFavourites'] = 'N' else: # Current users favourites are empty activity_data['inUsersFavourites'] = 'N' else: # User is not logged-in activity_data['inUsersFavourites'] = 'U' return render_template( 'activity.html', page_title=('Things to Do and Places to Go: Activity View'), activity=activity_data, nav_link='Activities', categories=CATEGORIES) else: return redirect(url_for('index'))
def favourite_activity(activity_id, action): """ Add or remove activity from users Activity Favourites :param activity_id: string :param action: string '0' remove '1' add :return: Render activity view or redirect to home page """ # Check if activity_id is a valid ObjectId if not check_activity_id(activity_id): return redirect(url_for('index')) # Check if activity_id exists in mongoDB if not Activity().get_activity(activity_id): flash('Activity not found', 'error') return redirect(url_for('index')) user_session = session.get('user') # Check if a user is logged-in and set action variables if user_session: userid = ObjectId(user_session['_id']['$oid']) if action == '0' or action == '1': if action == '0': mongo_operator = '$pull' message = 'removed from' else: mongo_operator = '$push' message = 'added to' # Add / Remove activity_id from users favourites if mongo.db.users.update_one( {'_id': ObjectId(userid)}, {mongo_operator: { 'favourites': ObjectId(activity_id) }}): flash(f'Activity {message} your Activity Favourites', 'info') return redirect( url_for('view_activity', activity_id=activity_id)) else: flash('Favourites update failed', 'error') else: flash('Favourites update operation invalid', 'error') else: flash('You must be logged-in to use Favourites', 'error') return redirect(url_for('login')) return redirect(url_for('index'))
def load_activities(): """Reads in activities.txt and adds to database.""" # Read in activities.txt file and insert data with open('seed_data/activities.txt') as f: for row in f: row = row.strip() activity, time, pair, img = row.split('|') entry = Activity(act_name=activity, default_time=time, pair=int(pair), img=img) db.session.add(entry) db.session.commit()
def follow_user(user_id, follower_id): if user_id_in_db(user_id) and user_id_in_db(follower_id): exists = db.session.query(Follow).filter(Follow.user_id==user_id, Follow.follower_id==follower_id).first() is not None if not exists: db.session.add(Follow(user_id=user_id, follower_id=follower_id, follow_date=datetime.date.today())) follow_id = db.session.query(Follow.id).filter_by(user_id=user_id, follower_id=follower_id).first() db.session.add(Activity(user_id=follower_id, action_id=6, object_id=5, date_created=datetime.datetime.now(), target_id=user_id)) db.session.commit() return make_response(jsonify({"success" : "Followed user", "data" : follow_id}), 200) else: return make_response(jsonify({"error" : "Follow relationship already exists"}), 400) else: return make_response(jsonify({"error" : "Invalid user"}), 400)
def index(request): host = request.META['HTTP_HOST'] if 'localhost' in host: host_name = 'http://' + host + '/' else: host_name = 'https://' + host + '/' user_agent_info = request.META['HTTP_USER_AGENT'] user_agent = parse(user_agent_info) browser = user_agent.browser.family device = user_agent.device.family os = user_agent.os.family ip = get_client_ip(request) Activity(ip=ip, browser=browser, device=device, os=os).save() if user_agent.is_mobile: return render(request, 'form/mobile.html', {'host_name': host_name}) else: return render(request, 'form/static.html', {'host_name': host_name})
def update_actvity(id): payload = request.get_json() activity = Activity.get_by_id(id) if current_user.id == activity.creator.id: activity.name = payload['name'] if 'name' in payload else None activity.description = payload[ 'description'] if 'description' in payload else None activity.save() activity_dict = model_to_dict(activity) return jsonify( data=activity_dict, message=f'Successfully updated activity with id {activity.id}.', status=200), 200 else: return jsonify(data='Error: Forbidden', message='Penguins can only update their own activity.', status=403), 403
def action_list(activity_type, review_selected): if g.user is None: return redirect(url_for('welcome')) activity_type = int(activity_type) activities = Activity.all(g.site.id) active = None for activity in activities: if activity.activity_type == activity_type: active = activity if active is None: abort(404) page = max(int(request.args.get("page", "1")), 1) if review_selected is None or review_selected not in ("reviewed", "reviewing", "rejected"): review_selected = "reviewed" coordinators = Activist.coordinators(active.id) paginator = action_pagination(active, page, review_selected) for index in range(len(paginator.items)): paginator.items[index].author = User.by_id( paginator.items[index].user_id) g.user.is_coordinator = False for coordinator in coordinators: if g.user.id == coordinator.id: g.user.is_coordinator = True return render_template('action_list.html', activities=activities, active=active, section=ACTIVITIES_SECTION_NAME, coordinators=coordinators, review_selected=review_selected, paginator=paginator, tab=activity_type, base_url=url_for("action_list", activity_type=activity_type, review_selected=review_selected))
def add_review(ISBN): data_to_return = [] # exists = db.session.query(Book.ISBN).filter_by(ISBN=ISBN).scalar() is not None exists = db.session.query(Book.ISBN).filter_by(ISBN=ISBN).first() is not None if not exists: addBookToDB(ISBN) book = db.session.query(Book).filter(Book.ISBN==ISBN).first() if "reviewer_id" in request.form and "text" in request.form and "rating" in request.form: reviewer_id = request.form["reviewer_id"] book_id = book.book_id text = request.form["text"] rating = request.form["rating"] else: return make_response(jsonify({"error" : "Missing form data"}), 400) if rating in ("3.5", "4", "4.5", "5"): try: recs = book_recommender.recommend(ISBN) except Exception: pass else: rec_source_id = db.session.query(Book.book_id).filter(Book.ISBN==ISBN).first() for rec in recs: addBookToDB(rec) rec_book = db.session.query(Book).filter(Book.ISBN==rec).first() rec_book_id = rec_book.book_id if not rec_book.title == "N/A": addRecToDB(rec_book_id, rec_source_id, reviewer_id) if book is not None: db.session.add(Review(reviewer_id=reviewer_id, book_id=book_id, rating=rating, text=text)) review_id = db.session.query(Review.id).filter(Review.reviewer_id==reviewer_id, Review.book_id==book_id, Review.rating==rating, Review.text==text).first() db.session.add(Activity(user_id=reviewer_id, action_id=1, object_id=1, date_created=datetime.datetime.now(), target_id=book_id)) check_achievement(reviewer_id, REVIEW_ACH_TYPE) db.session.commit() return make_response( jsonify( {"review" : review_id} ), 201 ) else: return make_response( jsonify({"error" : "Failed to add review"}), 404)
def process_and_insert_data(data): # Turn user info into list of format: # ['steps', 'total_sleep', 'resting_hr', 'step_week_slope', 'sleep_week_slope', 'hr_week_slope', 'curr_health_score'] try: # Calculate current health score curr_health_score = calc_health_score( to_float(data.get('steps')), to_float(data.get('total_sleep')), to_float(data.get('resting_hr'))) ml_fields = [ 'steps', 'total_sleep', 'resting_hr', 'step_week_slope', 'sleep_week_slope', 'hr_week_slope' ] ml_input = [] # Put 'GET' request data into list for algorithm for field in ml_fields: if data.get(field) != 0: ml_input.append(to_float(data.get(field))) else: return 'Data is missing' ml_input.append(curr_health_score) prediction = make_prediction(ml_input) # Insert data into database model_data = Activity( date=to_str(data.get('date')), steps=to_float(data.get('steps')), user_id=to_str(data.get('user_id')), total_sleep=to_float(data.get('total_sleep')), resting_hr=to_float(data.get('resting_hr')), step_week_slope=to_float(data.get('step_week_slope')), sleep_week_slope=to_float(data.get('sleep_week_slope')), hr_week_slope=to_float(data.get('hr_week_slope')), curr_health_score=to_float(curr_health_score), health_score_in_week=prediction) db.session.add(model_data) db.session.commit() data = { 'prediction': prediction, 'curr_health_score': curr_health_score } return data except: return
def add_or_update_activity(activity, user): """ Insert new activity row into the database if it doesn't already exist and is not expired. If it exists but has been updated, update it in the database. Return "Inserted" if activity was inserted, "Updated" if updated, and False if neither. :param dict activity: an activity from WEconnect in JSON format\n :param background.models.User user: the user to which the activity belongs """ # Determines the start and end times and expiration date (if any) st, et, expiration = extract_params(activity) act_id = activity["activityId"] # Flag indicating whether or not the activity was inserted/updated status = False # If the activity already exists in the database, sees if it's been # modified recently. If yes, updates it. If not, ignores it. existing = session.query(Activity).filter( Activity.wc_act_id == act_id).first() if existing: modified = datetime.strptime(activity["dateModified"], weconnect.DATE_FMT) if modified >= datetime.now() - timedelta(days=1): existing.name = activity["name"] existing.expiration = expiration session.commit() status = "Updated" else: status = False else: # If the activity doesn't exist in the database, adds it. new = Activity(wc_act_id=act_id, name=activity["name"], expiration=expiration, user=user) session.add(new) session.commit() status = "Inserted" return status
def get(self, *args): path = self.request.path slug = lastWordOfUrl(path) if (slug): club = Club.getClubBySlug(slug) if (club): templatevars = dict(club = club ) user = users.get_current_user() membership = Membership.between (user, club) if (membership): templatevars['membership'] = membership elif (user and hasClubPrivilige(user, club, 'join')): #Could Join templatevars['action'] = memberurlconf.path(club.slug, user.email()) templatevars['userName'] = user.nickname() templatevars['userEmail'] = user.email() else: templatevars['loginUrl'] = users.create_login_url(self.request.uri) if (membership and hasClubPrivilige(user, club, 'newAct')): templatevars['newAct'] = urldict['ActivityNew'].path(slug) if (hasClubPrivilige(user, club, "edit")): templatevars['editurl'] = urldict['ClubEdit'].path(club.slug) mq = Membership.all() mq.filter ('club = ', club) memset = [] for mem in mq: if (hasClubPrivilige(user, club, "privGrant")): mem.privEdit = urldict['ClubPrivilige'].path(slug, mem.user.email()) memset.append(mem) templatevars['members'] = memset aq = Activity.all() aq.filter ('club = ', club) avpath = urldict['ActivityView'].path actlist = [] for act in aq: act.linkpath = avpath (act.key().id()) actlist.append (act) templatevars['acts'] = actlist self.response.out.write (render(self.template, templatevars, self.request.url) ) else: self.response.set_status(404) errorPage( self.response, "Club Not Found", listurlconf.path())