def show_records(args): persons = Person.select(Person.full_name, Person.birthday).distinct().order_by( Person.full_name) for person in persons: age = calculate_age(person.birthday) print(person.full_name, person.birthday, age)
def teachers_view(): teachers_data = query_db( 'select t.id, d.name as departament_name, ' 'd.institute, t.name, t.gender, t.birth_date, ' 't.phone_number from teachers as t ' 'join departaments as d on t.departament_id = d.id ') teachers_sch = TeachersSchema(many=True).load(teachers_data).data for t in teachers_sch: birth_date = datetime.strptime(t.pop('birth_date'), '%Y-%m-%d') t['age'] = calculate_age(birth_date) return jsonify(teachers_sch)
def students_view(): students_data = query_db( 'select s.id, s.name, g.name as group_name, g.course, ' 's.gender, s.birth_date, s.phone_number, d.name as departament_name ' 'from students as s ' 'join groups as g on s.group_id = g.id ' 'join departaments as d on d.id = g.departament_id') students_sch = StudentsSchema(many=True).load(students_data).data for s in students_sch: birth_date_string = s.pop('birth_date', None) if birth_date_string: birth_date = datetime.strptime(birth_date_string, '%Y-%m-%d') s['age'] = calculate_age(birth_date) else: s['age'] = None return jsonify(students_sch)
def serialize_towns_percentile(import_group): towns = {} for citizen in import_group: citizen_town = citizen.town citizen_age = calculate_age(citizen.birth_date) if not (citizen_town in towns.keys()): towns[citizen_town] = [] towns[citizen_town].append(citizen_age) result = [] for town in towns.keys(): new_stat = {} np_ages = array(towns[town]) new_stat['town'] = town new_stat['p50'] = round( percentile(np_ages, 50, interpolation='linear'), 2) new_stat['p75'] = round( percentile(np_ages, 75, interpolation='linear'), 2) new_stat['p99'] = round( percentile(np_ages, 99, interpolation='linear'), 2) result.append(new_stat) return result
def write_dicom(ods, anon_values, out_dir, grouping): file_meta = Dataset() file_meta.MediaStorageSOPClassUID = 'Secondary Capture Image Storage' file_meta.MediaStorageSOPInstanceUID = str(anon_values['sopID']) file_meta.ImplementationClassUID = '0.0' file_meta.TransferSyntaxUID = ods.file_meta.TransferSyntaxUID if "TransferSyntaxUID" in ods.file_meta else "0.0" ds = FileDataset(anon_values['studyID'], {}, file_meta=file_meta, preamble=ods.preamble) ds.StudyInstanceUID = str(anon_values['studyID']) ds.SeriesInstanceUID = str(anon_values['seriesID']) ds.SOPInstanceUID = str(anon_values['sopID']) ds.SOPClassUID = 'Secondary Capture Image Storage' ds.AccessionNumber = str(anon_values['accession']) ds.PatientID = str(anon_values['mrn']) ds.StudyID = str(anon_values['studyID']) ds.PatientName = str(anon_values['mrn']) ds.ReferringPhysicianName = "" ds.StudyDate = "000000" ds.StudyTime = "000000" ds.PatientBirthTime = "000000.000000" ds.PatientBirthDate = "00000000" ds.PatientAge = utils.calculate_age( ods.StudyDate, ods.PatientBirthDate) if ( "StudyDate" in ods and "PatientBirthDate" in ods) else "" ds.PatientSex = ods.PatientSex if "PatientSex" in ods else "" ds.StudyDescription = ods.StudyDescription if "StudyDescription" in ods else "" ds.SeriesDescription = ods.SeriesDescription if "SeriesDescription" in ods else "" ds.Modality = ods.Modality if "Modality" in ods else "" ds.SeriesNumber = ods.SeriesNumber if "SeriesNumber" in ods else "" ds.InstanceNumber = ods.InstanceNumber if "InstanceNumber" in ods else "" ds.PlanarConfiguration = ods.PlanarConfiguration if "PlanarConfiguration" in ods else "" ds.ViewPosition = ods.ViewPosition if "ViewPosition" in ods else "" ds.PatientOrientation = ods.PatientOrientation if "PatientOrientation" in ods else "" ds.SamplesPerPixel = ods.SamplesPerPixel if "SamplesPerPixel" in ods else "" ds.PhotometricInterpretation = ods.PhotometricInterpretation if "PhotometricInterpretation" in ods else "" ds.PixelRepresentation = ods.PixelRepresentation if "PixelRepresentation" in ods else "" ds.ImagerPixelSpacing = ods.ImagerPixelSpacing if "ImagerPixelSpacing" in ods else "" ds.HighBit = ods.HighBit if "HighBit" in ods else "" ds.BitsStored = ods.BitsStored if "BitsStored" in ods else "" ds.BitsAllocated = ods.BitsAllocated if "BitsAllocated" in ods else "" ds.Columns = ods.Columns if "Columns" in ods else "" ds.Rows = ods.Rows if "Rows" in ods else "" ds.SpecificCharacterSet = ods.SpecificCharacterSet if "SpecificCharacterSet" in ods else "" ds.SecondaryCaptureDeviceManufctur = 'Python 3.X' ds.PresentationLUTShape = ods.PresentationLUTShape if "PresentationLUTShape" in ods else "" ds.KVP = ods.KVP if "KVP" in ods else "" ds.XRayTubeCurrent = ods.XRayTubeCurrent if "XRayTubeCurrent" in ods else "" ds.ExposureTime = ods.ExposureTime if "ExposureTime" in ods else "" ds.Exposure = ods.Exposure if "Exposure" in ods else "" ds.ExposureControlMode = ods.ExposureControlMode if "ExposureControlMode" in ods else "" ds.RelativeXRayExposure = ods.RelativeXRayExposure if "RelativeXRayExposure" in ods else "" ds.FocalSpots = ods.FocalSpots if "FocalSpots" in ods else "" ds.AnodeTargetMaterial = ods.AnodeTargetMaterial if "AnodeTargetMaterial" in ods else "" ds.BodyPartThickness = ods.BodyPartThickness if "BodyPartThickness" in ods else "" ds.CompressionForce = ods.CompressionForce if "CompressionForce" in ods else "" ds.PaddleDescription = ods.PaddleDescription if "PaddleDescription" in ods else "" ds.BurnedInAnnotation = "" ds.DistanceSourceToDetector = ods.DistanceSourceToDetector if "DistanceSourceToDetector" in ods else "" ds.DistanceSourceToPatient = ods.DistanceSourceToPatient if "DistanceSourceToPatient" in ods else "" ds.PositionerPrimaryAngle = ods.PositionerPrimaryAngle if "PositionerPrimaryAngle" in ods else "" ds.PositionerPrimaryAngleDirection = ods.PositionerPrimaryAngleDirection if "PositionerPrimaryAngleDirection" in ods else "" ds.PositionerSecondaryAngle = ods.PositionerSecondaryAngle if "PositionerSecondaryAngle" in ods else "" ds.ImageLaterality = ods.ImageLaterality if "ImageLaterality" in ods else "" ds.BreastImplantPresent = ods.BreastImplantPresent if "BreastImplantPresent" in ods else "" ds.Manufacturer = ods.Manufacturer if "Manufacturer" in ods else "" ds.ManufacturerModelName = ods.ManufacturerModelName if "ManufacturerModelName" in ods else "" ds.EstimatedRadiographicMagnificationFactor = ods.EstimatedRadiographicMagnificationFactor if "EstimatedRadiographicMagnificationFactor" in ods else "" ds.DateOfLastDetectorCalibration = ods.DateOfLastDetectorCalibration if "DateOfLastDetectorCalibration" in ods else "" filename = utils.clean_string('m' + str(anon_values['mrn']) + '_a' + str(anon_values['accession']) + '_st' + str(anon_values['studyID']) + "_se" + str(anon_values['seriesID']) + "_i" + str(anon_values['sopID']) + "_" + str(ds.SeriesNumber) + "_" + str(ds.InstanceNumber) + "_" + str(ds.Modality) + "_" + str(ds.ViewPosition) + ".dcm") # Create study directory, if it doesn't already exist. if grouping == 'a': utils.make_dirs(os.path.join(out_dir, str(anon_values['accession']))) out_path = os.path.join(out_dir, str(anon_values['accession']), filename) elif grouping == 's': utils.make_dirs(os.path.join(out_dir, str(anon_values['studyID']))) out_path = os.path.join(out_dir, str(anon_values['studyID']), filename) elif grouping == 'm': utils.make_dirs(os.path.join(out_dir, str(anon_values['mrn']))) out_path = os.path.join(out_dir, str(anon_values['mrn']), filename) else: out_path = os.path.join(out_dir, filename) if 'PixelData' in ods: ds.PixelData = '' pixel_array = ods.pixel_array f = h5py.File('{}.hdf5'.format(out_path[0:-4])) f.create_dataset("pixel_array", pixel_array.shape, data=pixel_array, dtype=str(pixel_array.dtype), compression="gzip", shuffle=True) ds.save_as(out_path, write_like_original=False)
def rankings(): all_races_messages = calculate_races_messages() all_races = all_races_messages[0] all_messages = all_races_messages[1] len_all_races = all_races_messages[2] len_all_messages = all_races_messages[3] users = db.users Email = "" profile_pic = "" facebook_name = "" logged_in = False if "email" in session: Email = session["email"] logged_in = True if "profile_pic" in session: profile_pic = session["profile_pic"] if "facebook_name" in session: facebook_name = session["facebook_name"] try: user = users.find_one({"Email": session["email"]}) get_image = user.get("image", None) session["facebook_name"] = user.get("facebook_name", "") if get_image != None: session[ "profile_pic"] = "static/img/profile_images/" + get_image + "?r=" + str( randint(1, 10000000)) var = session["profile_pic"] if "?" in var: var = var.split("?")[0] var = ROOT_DIR + "/" + var (width, height) = get_size(var) else: (width, height) = (0, 100) except: (width, height) = (0, 100) get_html = print_html(profile_pic, facebook_name, height, Email) # Retrieve the sorted data to calculate ranks full_data = users.find({}, { "Name": 1, "DOB": 1, "elo_rating": 1, "cgpa_rating": 1 }).sort("elo_rating", pymongo.DESCENDING) all_data = [] ct = 0 for user in full_data: ct += 1 cur_data = {} rating = user.get("elo_rating", 1000) cgpa_rating = user.get("cgpa_rating", 0) name = user.get("Name", "") full_name = "" if name == "": name = False else: name_prefix = name.get("prefix", "") name_first = name.get("first_name", "") name_middle = name.get("middle_name", "") name_last = name.get("last_name", "") if name_prefix == "" and name_last == "" and name_middle == "" and name_first == "": name = False else: full_name = name_prefix + " " + name_first + " " + name_middle + " " + name_last full_name = full_name.split() full_name = " ".join(full_name) name = True dob = user.get("DOB", False) age = 0 if dob != False: date_of_birth = {} date_of_birth["date"] = dob.get("date", "") date_of_birth["month"] = dob.get("month", "") date_of_birth["year"] = dob.get("year", "") if date_of_birth["date"] == "" or date_of_birth[ "month"] == "" or date_of_birth["year"] == "": dob = "Enter your Date of Birth" else: age = calculate_age(date_of_birth) # Update all the data for showing cur_data["name"] = full_name cur_data["age"] = age cur_data["rating"] = rating cur_data["cgpa_rating"] = cgpa_rating cur_data["rank"] = ct all_data.append(cur_data) return render_template("ranking.html", get_html=Markup(get_html), profile_pic=profile_pic, facebook_name=facebook_name, email=Email, all_races=all_races, len_all_races=len_all_races, all_messages=all_messages, len_all_messages=len_all_messages, all_data=all_data, logged_in=logged_in)
match = re.search(SEASON_SEASON_TYPE_TEAM_ID_REGEX, src_path) if not match: continue season, season_type_id, team_id = (match.group(1), match.group(2), match.group(3)) season_type = CONFIG['game_types'][int(season_type_id)] team = CONFIG['teams'][int(team_id)] roster = json.loads(open(src_path).read()) print("+ Loading %d players from %s %s %s roster" % (len(roster), season, team, season_type)) for plr in roster: single_plr = dict() single_plr['player_id'] = int(plr['id']) single_plr['first_name'] = plr['firstname'] single_plr['last_name'] = plr['surname'] if int(plr['id']) in player_name_corrections: correct_player_name(single_plr) single_plr['position'] = plr['position'] single_plr['hand'] = plr['stick'] if 'dateOfBirth' in plr: single_plr['dob'] = plr['dateOfBirth'] single_plr['age'] = calculate_age(single_plr['dob']) if plr['nationalityShort'] in iso_country_codes: single_plr['iso_country'] = iso_country_codes[plr['nationalityShort']] else: print("Nationality abbreviation not recognized: %s" % plr['nationalityShort']) single_plr['iso_country'] = 'n/a' all_players[single_plr['player_id']] = single_plr all_players = dict(sorted(all_players.items())) open(tgt_path, 'w').write(json.dumps(all_players, indent=2))
def userhome(): users = db.users all_races_messages = calculate_races_messages() all_races = all_races_messages[0] all_messages = all_races_messages[1] len_all_races = all_races_messages[2] len_all_messages = all_races_messages[3] user = users.find_one({"Email":session["email"]}) check_registered = "Unregistered" if "DOB" in user: check_registered = "Registered" profile_pic = user.get("profile_pic",None) facebook_name = user.get("facebook_name",None) image = user.get("image","") if image == "": session["profile_pic"] = profile_pic (width, height) = (0,100) else: session["profile_pic"] = "static/img/profile_images/" + image + "?r=" + str(randint(1,10000000)) var = session["profile_pic"] if "?" in var : var = var.split("?")[0] var = ROOT_DIR + "/" + var (width, height) = (0,100) session["facebook_name"] = facebook_name get_html = print_html(session["profile_pic"],session["facebook_name"],height,session["email"]) participation = user.get("participation",False) if participation != False: participation = participation.split(",") podiums = user.get("podiums",False) if podiums != False: podiums = podiums.split(",") name = user.get("Name","") full_name = "" if name == "": name = False else: name_prefix = name.get("prefix","") name_first = name.get("first_name","") name_middle = name.get("middle_name","") name_last = name.get("last_name","") if name_prefix == "" and name_last == "" and name_middle == "" and name_first == "": name = False else: full_name = name_prefix + " " + name_first + " " + name_middle + " " + name_last full_name = full_name.split() full_name = " ".join(full_name) name = True name_alias = user.get("name_alias","Enter your Alias") Mobile = user.get("Mobile","Enter your Mobile Number") address = user.get("address","Enter your Address") full_address = "" map_address = "" if address != "Enter your Address": address_part_one = address.get("address1","") address_part_two = address.get("address2","") address_part_three = address.get("state","") address_part_four = address.get("country","") full_address = address_part_one + ", " + address_part_two + ", " + address_part_three + ", " + address_part_four map_address = address_part_two + ", " + address_part_three + ", " + address_part_four emergency_contact = user.get("emergency_contact","Enter your Emergency Contact") relation = "" relation_name = "" relation_contact = "" if emergency_contact != "Enter your Emergency Contact": relation = emergency_contact.get("relation","") relation_name = emergency_contact.get("relation_name","") relation_contact = emergency_contact.get("relation_contact_number","") emergency_contact = True else: emergency_contact = False dob = user.get("DOB",False) age = 0 if dob != False: date_of_birth = {} date_of_birth["date"] = dob.get("date","") date_of_birth["month"] = dob.get("month","") date_of_birth["year"] = dob.get("year","") if date_of_birth["date"] == "" or date_of_birth["month"] == "" or date_of_birth["year"] == "": dob = "Enter your Date of Birth" else: age = calculate_age(date_of_birth) blood_group = user.get("Blood Group",False) nationality = user.get("Nationality",False) reg_id = str(user.get("_id","")) path_id_proof = user.get("id_proof","") download_id_proof = "" download_rider_insurance = "" download_rider_id_proof = "" if path_id_proof != "": download_id_proof = "id_proof." + path_id_proof.split(".")[1] path_id_proof = "/static/id_proof/" + path_id_proof path_rider_insurance = user.get("rider_insurance_certificate","") if path_rider_insurance != "": download_rider_insurance = "medical_insurance_certificate." + path_rider_insurance.split(".")[1] path_rider_insurance = "/static/rider_insurance_certificate/" + path_rider_insurance path_rider_id_proof = user.get("rider_id_proof","") if path_rider_id_proof != "": download_rider_id_proof = "rider_id_proof." + path_rider_id_proof.split(".")[1] path_rider_id_proof = "/static/rider_id_proof/" + path_rider_id_proof allergy = user.get("Allergy",False) if allergy != False: allergy = allergy.split(",") bike_details = user.get("bike_details",False) bike_brand = "" bike_size = "" bike_style = [] bike_brand_other_input = "" if bike_details != False: bike_brand = bike_details.get("bike_brand","") bike_size = bike_details.get("bike_size","") bike_style = bike_details.get("bike_style",[]) if bike_style != []: bike_style = ",".join(bike_style) bike_brand_other_input = bike_details.get("bike_brand_other_input","") riding_style = user.get("riding_style",[]) if riding_style == []: check_riding_style = False else: check_riding_style = True sponsors = user.get("sponsors",False) if sponsors != False: sponsors = sponsors.split(",") team_name = user.get("team_name",False) rider_type = user.get("rider_type",False) uci_status = user.get("uci_status",False) uci_id = "" if uci_status != False: if uci_status == "yes": uci_id = user.get("uci_id","") jersey_size = user.get("Jerseey size",False) # check for fully registered or not form_personal_profile = user.get("form_personal_profile",False) form_rider_profile = user.get("form_rider_profile",False) form_medical_profile = user.get("form_medical_profile",False) form_bike_profile = user.get("form_bike_profile",False) form_race_profile = user.get("form_race_profile",False) forms_not_completed = [] if form_personal_profile == False: form_not_completed = {} form_not_completed["name"] = "Form Personal Profile" form_not_completed["url"] = "/form_personal_profile" forms_not_completed.append(form_not_completed) if form_race_profile == False: form_not_completed = {} form_not_completed["name"] = "Form Race Profile" form_not_completed["url"] = "/form_race_profile" forms_not_completed.append(form_not_completed) if form_bike_profile == False: form_not_completed = {} form_not_completed["name"] = "Form Bike Profile" form_not_completed["url"] = "/form_bike_profile" forms_not_completed.append(form_not_completed) if form_rider_profile == False: form_not_completed = {} form_not_completed["name"] = "Form Rider Profile" form_not_completed["url"] = "/form_rider_profile" forms_not_completed.append(form_not_completed) if form_medical_profile == False: form_not_completed = {} form_not_completed["name"] = "Form Medical Profile" form_not_completed["url"] = "/form_medical_profile" forms_not_completed.append(form_not_completed) dream_bike = user.get("dream_bike","Complete the form") dream_bike_brand = user.get("dream_bike_brand","Complete the form") first_bike = user.get("first_bike","Complete the form") often_rides = user.get("often_rides","Complete the form") fav_trail = user.get("fav_trail","Complete the form") dream_trail = user.get("dream_trail","Complete the form") best_exp = user.get("best_exp","Complete the form") return render_template( "dashboard.html", profile_pic = session["profile_pic"], facebook_name = facebook_name, email = session["email"], check_registered = check_registered, all_races = all_races, len_all_races = len_all_races, all_messages = all_messages, len_all_messages = len_all_messages, width = width, height = height, get_html = Markup(get_html), participation = participation, podiums = podiums, full_name = full_name, name_alias = name_alias, Mobile = Mobile, full_address = full_address, relation = relation, relation_name = relation_name, relation_contact = relation_contact, name = name, emergency_contact = emergency_contact, age = age, reg_id = reg_id, nationality = nationality, blood_group = blood_group, path_id_proof = path_id_proof, path_rider_insurance = path_rider_insurance, download_rider_insurance = download_rider_insurance, download_id_proof = download_id_proof, allergy = allergy, bike_brand = bike_brand, bike_style = bike_style, bike_size = bike_size, map_address = map_address, bike_brand_other_input = bike_brand_other_input, bike_details = bike_details, riding_style = riding_style, check_riding_style = check_riding_style, sponsors = sponsors, team_name = team_name, rider_type = rider_type, jersey_size = jersey_size, uci_status = uci_status, uci_id = uci_id, path_rider_id_proof = path_rider_id_proof, download_rider_id_proof = download_rider_id_proof, forms_not_completed = forms_not_completed, total_forms_completed = 5 - len(forms_not_completed), percentage_completion = (5 - len(forms_not_completed))*20, dream_bike = dream_bike, dream_bike_brand = dream_bike_brand, first_bike = first_bike, often_rides = often_rides, fav_trail = fav_trail, dream_trail = dream_trail, best_exp = best_exp )
e = {} try: # in case no value is found for the "kg" and "cm" keys in .yaml bmi = round(d['kg'] / (d['cm'] * 0.01)**2, 1) e['bmi'] = str(bmi).replace('.', ',') e['broca'] = d['cm'] - 100 except TypeError: pass # http://stackoverflow.com/questions/6288892/convert-datetime-format try: dob = datetime.strptime(d['dob'], '%d.%m.%Y') e['alter'] = calculate_age(dob) except TypeError: pass heartref = pd.read_csv(arguments['<ref>']) try: # http://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value valuepick = min(heartref['kg'], key=lambda x:abs(x-d['kg'])) if d['geschlecht'] == 'f': a = heartref[heartref['kg'] == valuepick][['low female', 'high female']] # http://stackoverflow.com/questions/16729574/how-to-get-a-value-from-a-cell-of-a-data-frame result = tuple(a.iloc[0]) if d['geschlecht'] == 'm':
", ".join([str(s) for s in player_data[key][pd_item]]))) if not player_data[key]: continue # setting up data dictionary for personal player attributes basic_values = dict() basic_values['player_id'] = player_id basic_values['team'] = team # retaining single (and most recent) value for personal player attribute for attr in TO_COLLECT: basic_values[attr] = list(player_data[key][attr])[-1] # calculating player age current_season = get_season() if current_season == season: basic_values['age'] = calculate_age(basic_values['date_of_birth']) else: # if we're not aggregating data for the current season, calculate age for # mid-point (i.e. turn of the year) in season of interest basic_values['age'] = calculate_age(basic_values['date_of_birth'], "%d-12-31" % season) # turning status code into different player type statuses if basic_values['status'][0] == 't': basic_values['u23'] = True else: basic_values['u23'] = False if basic_values['status'][1] == 't': basic_values['u20'] = True else: basic_values['u20'] = False