hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
qsc_code_num_words_quality_signal
int64
qsc_code_num_chars_quality_signal
float64
qsc_code_mean_word_length_quality_signal
float64
qsc_code_frac_words_unique_quality_signal
float64
qsc_code_frac_chars_top_2grams_quality_signal
float64
qsc_code_frac_chars_top_3grams_quality_signal
float64
qsc_code_frac_chars_top_4grams_quality_signal
float64
qsc_code_frac_chars_dupe_5grams_quality_signal
float64
qsc_code_frac_chars_dupe_6grams_quality_signal
float64
qsc_code_frac_chars_dupe_7grams_quality_signal
float64
qsc_code_frac_chars_dupe_8grams_quality_signal
float64
qsc_code_frac_chars_dupe_9grams_quality_signal
float64
qsc_code_frac_chars_dupe_10grams_quality_signal
float64
qsc_code_frac_chars_replacement_symbols_quality_signal
float64
qsc_code_frac_chars_digital_quality_signal
float64
qsc_code_frac_chars_whitespace_quality_signal
float64
qsc_code_size_file_byte_quality_signal
float64
qsc_code_num_lines_quality_signal
float64
qsc_code_num_chars_line_max_quality_signal
float64
qsc_code_num_chars_line_mean_quality_signal
float64
qsc_code_frac_chars_alphabet_quality_signal
float64
qsc_code_frac_chars_comments_quality_signal
float64
qsc_code_cate_xml_start_quality_signal
float64
qsc_code_frac_lines_dupe_lines_quality_signal
float64
qsc_code_cate_autogen_quality_signal
float64
qsc_code_frac_lines_long_string_quality_signal
float64
qsc_code_frac_chars_string_length_quality_signal
float64
qsc_code_frac_chars_long_word_length_quality_signal
float64
qsc_code_frac_lines_string_concat_quality_signal
float64
qsc_code_cate_encoded_data_quality_signal
float64
qsc_code_frac_chars_hex_words_quality_signal
float64
qsc_code_frac_lines_prompt_comments_quality_signal
float64
qsc_code_frac_lines_assert_quality_signal
float64
qsc_codepython_cate_ast_quality_signal
float64
qsc_codepython_frac_lines_func_ratio_quality_signal
float64
qsc_codepython_cate_var_zero_quality_signal
bool
qsc_codepython_frac_lines_pass_quality_signal
float64
qsc_codepython_frac_lines_import_quality_signal
float64
qsc_codepython_frac_lines_simplefunc_quality_signal
float64
qsc_codepython_score_lines_no_logic_quality_signal
float64
qsc_codepython_frac_lines_print_quality_signal
float64
qsc_code_num_words
int64
qsc_code_num_chars
int64
qsc_code_mean_word_length
int64
qsc_code_frac_words_unique
null
qsc_code_frac_chars_top_2grams
int64
qsc_code_frac_chars_top_3grams
int64
qsc_code_frac_chars_top_4grams
int64
qsc_code_frac_chars_dupe_5grams
int64
qsc_code_frac_chars_dupe_6grams
int64
qsc_code_frac_chars_dupe_7grams
int64
qsc_code_frac_chars_dupe_8grams
int64
qsc_code_frac_chars_dupe_9grams
int64
qsc_code_frac_chars_dupe_10grams
int64
qsc_code_frac_chars_replacement_symbols
int64
qsc_code_frac_chars_digital
int64
qsc_code_frac_chars_whitespace
int64
qsc_code_size_file_byte
int64
qsc_code_num_lines
int64
qsc_code_num_chars_line_max
int64
qsc_code_num_chars_line_mean
int64
qsc_code_frac_chars_alphabet
int64
qsc_code_frac_chars_comments
int64
qsc_code_cate_xml_start
int64
qsc_code_frac_lines_dupe_lines
int64
qsc_code_cate_autogen
int64
qsc_code_frac_lines_long_string
int64
qsc_code_frac_chars_string_length
int64
qsc_code_frac_chars_long_word_length
int64
qsc_code_frac_lines_string_concat
null
qsc_code_cate_encoded_data
int64
qsc_code_frac_chars_hex_words
int64
qsc_code_frac_lines_prompt_comments
int64
qsc_code_frac_lines_assert
int64
qsc_codepython_cate_ast
int64
qsc_codepython_frac_lines_func_ratio
int64
qsc_codepython_cate_var_zero
int64
qsc_codepython_frac_lines_pass
int64
qsc_codepython_frac_lines_import
int64
qsc_codepython_frac_lines_simplefunc
int64
qsc_codepython_score_lines_no_logic
int64
qsc_codepython_frac_lines_print
int64
effective
string
hits
int64
695579af900de69250d3b0d15ec3f825c2990c7f
18,839
py
Python
PacELF_Phase3/scripts/csvColumnToXMLFile.py
pacelf/pacelf
cd9f3608843eaf7d9dff6e20e06ee4bf773467e3
[ "MIT" ]
null
null
null
PacELF_Phase3/scripts/csvColumnToXMLFile.py
pacelf/pacelf
cd9f3608843eaf7d9dff6e20e06ee4bf773467e3
[ "MIT" ]
2
2021-10-06T01:58:48.000Z
2022-02-18T04:52:34.000Z
PacELF_Phase3/scripts/csvColumnToXMLFile.py
pacelf/pacelf
cd9f3608843eaf7d9dff6e20e06ee4bf773467e3
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # This program is designed to create XML sidecar files for harvesting metadata into Mediaflux. # # Author: Jay van Schyndel # Date: 02 May 2017. # # Significant modifications done by: Daniel Baird # Date: 2018 and early 2019 # # Scenario. Metadata is stored in an MS Excel file in various columns. # Excel has been used to create a new column representing the metadata in the required XML format. # The file is then saved as a CSV. # This program will open the CSV file, read the appropriate column and save the XML into a sidecar file based on the name of the data file. # Note the program assumes there is a header row in the CSV file. It skips processesing the first row. # # new example: python ./scripts/csvColumnToXMLFile.py "./rawdata/excel/PacELF Phases 1_2_3 13Dec2018.csv" "/Users/pvrdwb/projects/PacELFDocs/PacELFphase3/" ../docs --location="HardcopyLocation2018" # # old example: python csvColumnToXMLFile.py rawSpreadsheet/PacELF_Phase_1_AND_2.csv ~/projects/PacELFDocs/PacELF\ PDFs ./docs # import os import re import sys import csv import shutil import argparse parser = argparse.ArgumentParser(description="Create XML sidecar files from a CSV file") parser.add_argument( "metadata_csv", metavar="metadataCSV", help="CSV file containing the XML" ) parser.add_argument( "src_folder", metavar="sourceFolder", help="directory containing the source files" ) parser.add_argument( "dest_folder", metavar="destinationFolder", help="Path of the destination folder" ) parser.add_argument( "--title", metavar="titleColumn", help="Column containing the title", default="Title", ) parser.add_argument( "--xml", metavar="xmlColumn", help="Column containing the XML", default="XML" ) parser.add_argument( "--access", metavar="accessColumn", help="Column containing the Access Rights", default="Access Rights", ) parser.add_argument( "--type", metavar="accessColumn", help="Column containing the Type", default="Type" ) parser.add_argument( "--file", metavar="fileColumn", help="Column containing the data file name", default="PDF", ) parser.add_argument( "--location", metavar="primaryLocationColumn", help="Column containing the primary hardcopy location", default="Hardcopy Locations", ) try: args = parser.parse_args() except: sys.exit(0) print("Processing CSV file: ", args.metadata_csv) # this is all the location typos we've found loc_replacements = {} loc_replacements[r"JCU WHOCC Ichimori collectoin"] = r"JCU WHOCC Ichimori collection" loc_replacements[r"JCU WHOCC Ichimori Collection"] = r"JCU WHOCC Ichimori collection" loc_replacements[r"JCU WHOCC ICHIMORI Collection"] = r"JCU WHOCC Ichimori collection" loc_replacements[r"JCU WHO Ichimori Collection"] = r"JCU WHOCC Ichimori collection" loc_replacements[r"JCU WHO Ichimori collection"] = r"JCU WHOCC Ichimori collection" loc_replacements[r"JCU WHO CC Ichimori Collection"] = r"JCU WHOCC Ichimori collection" loc_replacements[r"JCUWHOCC Ichimori collection"] = r"JCU WHOCC Ichimori collection" loc_replacements[r"JCUWHOCC Ichimori Collection"] = r"JCU WHOCC Ichimori collection" loc_replacements[r"Ichimori Collection"] = r"JCU WHOCC Ichimori collection" loc_replacements[r"JCU WHOCC Nagasaki Collection"] = r"JCU WHOCC Ichimori collection" loc_replacements[r"JCU WHOCC Nagasaki collection"] = r"JCU WHOCC Ichimori collection" loc_replacements[r"WHO DPS Suva"] = r"WHO DPS Fiji" loc_replacements[r"WHO HQ Geneva"] = r"WHO Geneva" # ----------------------------------------------------------------------------- def clean_hc_location(loc): if loc in loc_replacements: return loc_replacements[loc] else: return loc # ----------------------------------------------------------------------------- def clean_xml_content(xml_string): """ Given some xml in string form that we got right from the spreadsheet, clean it up """ for old_loc in loc_replacements: old = r"<hardcopy_location>([^<]*)" + old_loc + r"([^<]*)</hardcopy_location>" new = ( r"<hardcopy_location>\1" + loc_replacements[old_loc] + r"\2</hardcopy_location>" ) xml_string = re.sub(old, new, xml_string) return xml_string # ----------------------------------------------------------------------------- def get_location_info(location): locations = {} locations[ "JCU WHOCC Ichimori collection" ] = "James Cook University, Bldg 41 Rm 207, Townsville, Queensland 4811, Australia" locations[ "JCU WHOCC" ] = "James Cook University, Bldg 41 Rm 207, Townsville, Queensland 4811, Australia" locations[ "JCU Cairns (PMG)" ] = "James Cook University, Bldg E1 Rm 003C, Cairns, Queensland 4870, Australia" locations[ "WHO DPS Fiji" ] = "World Health Organization, Level 4, Provident Plaza One, Downtown Boulevard, 33 Ellery Street, Suva, Fiji" locations[ "WHO WPRO Manila" ] = "P.O. Box 2932, United Nations Ave. cor. Taft Ave, 1000 Manila, Philippines" locations["WHO Geneva"] = "Avenue Appia 20, 1202 Geneva, Switzerland" locations[ "JCU library" ] = "James Cook University, Eddie Koiko Mabo library, Bldg 18, Townsville, Queensland 4811, Australia" return locations[location] # ----------------------------------------------------------------------------- with open(args.metadata_csv, "rb") as csvfile: metadataReader = csv.DictReader(csvfile, delimiter=",") counts = { "rows": 0, "docs": 0, "restrict": 0, "hc": 0, "restrict_hc": 0, "write_err": 0, "copy_err": 0, "sidecar_err": 0, "no_doc": 0, "doc_missing": 0, "sidecars": 0, } for row in metadataReader: counts["rows"] += 1 # Skipping first row as it contains the header row. if counts["rows"] > 1: real_file = row[args.file] xml_content = row[args.xml] # clean the XML (this part is special to the specific data we're getting) xml_content = clean_xml_content(xml_content) doc_access = row[args.access] doc_type = row[args.type] hc_location = ( row[args.location].split(";")[0].strip() ) # semicolon separated list -- get the first one hc_location = clean_hc_location(hc_location) doc_title = row[args.title] # bail if there's no title if doc_title == "": continue else: # print("LOOKING: " + doc_title) counts["docs"] += 1 pass # destination for the xml file flat_file_name, file_ext = os.path.splitext(real_file) # maybe there are subdirs in the file name, we'll flatten those out flat_file_name = flat_file_name.replace("/", "#") # copy the file there # maybe we have to fake up the content coz it's restricted or something fake_content = False if doc_access == "Restricted" and doc_type == "Hardcopy" and hc_location: # it's a restricted hardcopy with a location counts["restrict_hc"] += 1 fake_content = "".join( [ 'The document "', doc_title, '" is unavailable due to data sensitivity, publisher restrictions or is not digitised. ', "Please e-mail pacelf@jcu.edu.au or write to:\n\n ", get_location_info(hc_location), "\n\nto negotiate gaining access to this item.", ] ) elif ( doc_access == "Restricted" and doc_type == "Hardcopy" and not hc_location ): # it's a restricted hardcopy with no location counts["restrict_hc"] += 1 fake_content = "".join( [ 'The document "', doc_title, '" is unavailable due to data sensitivity, publisher restrictions or is not digitised. ', "Please e-mail pacelf@jcu.edu.au to negotiate gaining access to this item.", ] ) elif doc_access != "Restricted" and doc_type == "Hardcopy" and hc_location: # it's an unrestricted hardcopy with a location counts["hc"] += 1 fake_content = "".join( [ 'The document "', doc_title, '" is not available in digital format. ', "A copy is held at:\n\n ", get_location_info(hc_location), "\n\nplease write or email pacelf@jcu.edu.au to request a copy.", ] ) elif ( doc_access != "Restricted" and doc_type == "Hardcopy" and not hc_location ): # it's an unrestricted hardcopy with no location counts["hc"] += 1 fake_content = "".join( [ 'The document "', doc_title, '" is not available in digital format. ', "Please e-mail pacelf@jcu.edu.au to request a copy.", ] ) elif doc_access == "Restricted" and doc_type != "Hardcopy": # it's a restricted PDF counts["restrict"] += 1 fake_content = "".join( [ 'The document "', doc_title, '" is unavailable due to data sensitivity, publisher restrictions or is not digitised. ', "Please e-mail pacelf@jcu.edu.au to negotiate gaining access to this item.", ] ) elif flat_file_name == "": # any other situation where there's no doc counts["no_doc"] += 1 fake_content = "".join( [ 'The document "', doc_title, '" is not available in digital format. ', "Please e-mail pacelf@jcu.edu.au to discuss access.", ] ) if flat_file_name == "": flat_file_name = "PacELF_Phase2_" + str(counts["rows"]) # # by now have fake content to use, or we expect the doc to be available. # # destination for the real file real_dest_file = os.path.join(args.dest_folder, flat_file_name + file_ext) # destination for the proxy document (.txt extension) fake_dest_path = os.path.join(args.dest_folder, flat_file_name + ".txt") if fake_content: # write the fake content, if we have it try: file = open(fake_dest_path, "w") file.write(fake_content) file.close() # print(unicode('PROXIED: ') + unicode(doc_title)) except ValueError as e: counts["write_err"] += 1 print("Couldn't write content to: " + real_dest_file) print(e) else: # we didn't have fake content, so use the real doc/pdf real_file_path = os.path.join(args.src_folder, real_file) if real_file == "": print('No doc file specified for "' + doc_title + '"') counts["no_doc"] += 1 continue # try to copy the file -------- # first let's get some common error versions of the filename fn_to_try = [real_file_path] fn_to_try.append( re.sub(r"\.pdf$", r" .pdf", real_file_path) ) # space before the pdf fn_to_try.append(re.sub(r"\\", r"/", real_file_path)) # other slashes fn_to_try.append(re.sub(r"$", r".pdf", real_file_path)) # add .pdf fn_to_try.append( re.sub( r"Multicountry Pacific", r"multicountry pacific", real_file_path ) ) # upper case fn_to_try.append( re.sub( r"Mulitcountry Pacific", r"multicountry pacific", real_file_path ) ) # typo & upper case # some straight fixes fn_to_try.append( re.sub( r"\\\.pdf$", r"PDF version\.pdf", re.sub( r"Mulitcountry Pacific", r"multicountry pacific", real_file_path, ), ) ) # two fixes fn_to_try.append( re.sub( r"PacELF_102", r"PacELF_102 Jarno et al 2006", real_file_path ) ) # add author fn_to_try.append( re.sub( r"PacELF_448", r"PacELF_448 Andrews et al 2012 PLOS PATHOGENS ", real_file_path, ) ) fn_to_try.append( re.sub( r"PacELF_493", r"PacELF_493 Brelsfoard et al 2008 PLOS NTDs Interspecific hybridization South Pacific filariasis vectors", real_file_path, ) ) fn_to_try.append( re.sub( r"PacELF_508", r"PacELF_508 Burkot et al 2013 MAL J Barrier screens", real_file_path, ) ) fn_to_try.append( re.sub( r"PacELF_314", r"PacELF_314 Stolk et al 2013 PLOS NTDs", real_file_path, ) ) fn_to_try.append( re.sub( r"PacELF_317", r"PacELF_317 Debrah et al 2006 PLOS PATHOGENS Doxycycline reduces VGF and improves pathology LF", real_file_path, ) ) fn_to_try.append( re.sub( r"PacELF_319", r"PacELF_319 Hooper et al 2014 PLOS NTDs Asseesing progress in reducing at risk population after 13 years", real_file_path, ) ) fn_to_try.append( re.sub( r"\\2001-05 PRG Fiji May-Jun 2011\\", r"/2011-05 PRG Fiji May-Jun 2011/", real_file_path, ) ) fn_to_try.append( re.sub( r"PacELF_414 WPRO PMM 2011 report_2011 Oct 31\.pdf", r"PacELF_414 WPRO PMM 2011 report_2011 Oct 31 PDF version.pdf", real_file_path, ) ) fn_to_try.append( re.sub( r"Multicountry Pacific/PacELF_585", r"French Polynesia/PacELF_585", real_file_path, ) ) fn_to_try.append( re.sub( r"Manson-Bahr 1912 FIlariasis and elephantiasis in Fiji LSHTM b21356658", r"Manson-Bahr 1912 FIlariasis and elephantiasis in Fiji LSHTM b21356658", real_file_path, ) ) # find the first that is a file for pth in fn_to_try: if os.path.isfile(pth): break # try copying that if os.path.isfile(pth): try: shutil.copyfile(pth, real_dest_file) # print(' COPIED: ' + doc_title) except shutil.Error as e: counts["copy_err"] += 1 print("Could not copy doc: " + pth) print(e) else: print( "Could not find doc file for title: '" + doc_title + "', file: " + pth ) counts["doc_missing"] += 1 # # Now we've got content there, make the xml sidecar file # xml_dest_file = flat_file_name + ".xml" xml_dest_path = args.dest_folder + "/" + xml_dest_file try: file = open(xml_dest_path, "w") file.write(xml_content) file.close() counts["sidecars"] += 1 except ValueError as e: counts["sidecar_err"] += 1 print("Oops, this one is dodgy: " + xml_dest_path) print("ValueError: ", e) print("\nSummary:") print( "".join( [ " ", str(counts["rows"]), " rows read: ", str(counts["docs"]), " documents processed, ", str(counts["sidecars"]), " metadata sidecars produced;", "\n ", str(counts["hc"]), " hard copies, ", str(counts["restrict"]), " restricted docs, ", str(counts["restrict_hc"]), " restricted hard copies;", "\n ", str(counts["copy_err"]), " copy errors, ", str(counts["write_err"]), " write errors, ", str(counts["sidecar_err"]), " sidecar errors, ", str(counts["doc_missing"]), " docs not locatable, ", str(counts["no_doc"]), " docs not listed.", "\n", ] ) )
37.157791
197
0.49578
1,970
18,839
4.600508
0.228426
0.021185
0.025157
0.024385
0.388613
0.366435
0.344147
0.339181
0.310493
0.29626
0
0.022933
0.400499
18,839
506
198
37.231225
0.779529
0.144116
0
0.3257
0
0.002545
0.294829
0.007297
0
0
0
0
0
1
0.007634
false
0.002545
0.015267
0
0.033079
0.02799
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
69566d12c06529c48fecd538d7a1ad6d03fffd43
1,147
py
Python
authenticationCwProject/authenticationCwApp/views.py
cs-fullstack-2019-spring/django-authentication-cw-bettyjware11
0afa675b0b6602a89ecfff9ee29a62c95f677de6
[ "Apache-2.0" ]
null
null
null
authenticationCwProject/authenticationCwApp/views.py
cs-fullstack-2019-spring/django-authentication-cw-bettyjware11
0afa675b0b6602a89ecfff9ee29a62c95f677de6
[ "Apache-2.0" ]
null
null
null
authenticationCwProject/authenticationCwApp/views.py
cs-fullstack-2019-spring/django-authentication-cw-bettyjware11
0afa675b0b6602a89ecfff9ee29a62c95f677de6
[ "Apache-2.0" ]
null
null
null
from django.shortcuts import render from django.shortcuts import HttpResponse from .forms import FoodFitnessForm from django.contrib.auth.models import User # function to test with def index(request): return HttpResponse("You made it.") # function to create new user def createUser(request): form = FoodFitnessForm(request.POST or None) context = { "form": form } if request.method == "POST": print(request.POST) User.objects.create_user(request.POST["username"], request.POST["calories"], request.POST["date"]) return render(request, "authenticationCwApp/confirmUser.html") return render(request, 'authenticationCwApp/createUser.html', context) # function to confirm new user def confirmUser(request): form = FoodFitnessForm(request.GET or None) context = { "form": form } if request.method == 'GET': User.objects.create_user(request.GET["username"], "", request.GET["calories"], request.GET["date"]) form.save() return HttpResponse("New Food Calorie Tracker Created!!!!!") return render(request, "authenticationCwApp/confirmUser.html", context)
28.675
107
0.70619
133
1,147
6.075188
0.360902
0.068069
0.070545
0.141089
0.289604
0.220297
0.089109
0.089109
0
0
0
0
0.173496
1,147
39
108
29.410256
0.852321
0.068003
0
0.153846
0
0
0.198122
0.100469
0
0
0
0
0
1
0.115385
false
0
0.153846
0.038462
0.461538
0.038462
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
695785b2963244eb85ab885b374aa8c222d96191
98
py
Python
ex.047.mostraNumerosPares.py
romulorm/cev-python
b5c6844956c131a9e4e02355459c218739ebf8c5
[ "MIT" ]
null
null
null
ex.047.mostraNumerosPares.py
romulorm/cev-python
b5c6844956c131a9e4e02355459c218739ebf8c5
[ "MIT" ]
null
null
null
ex.047.mostraNumerosPares.py
romulorm/cev-python
b5c6844956c131a9e4e02355459c218739ebf8c5
[ "MIT" ]
null
null
null
# Conta somente números pares for c in range(2, 51, 2): print(c, end=' ') print("Acabou!")
14
30
0.602041
16
98
3.6875
0.8125
0
0
0
0
0
0
0
0
0
0
0.052632
0.22449
98
6
31
16.333333
0.723684
0.27551
0
0
0
0
0.119403
0
0
0
0
0
0
1
0
false
0
0
0
0
0.666667
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
3
695934996d2e79a5c72ef6834b5be0584eb22c99
4,763
py
Python
csv-manipulation/csv-merge.py
bohnacker/data-manipulation
a46cdfdeca8d242038b118509c20b1eb39ea5b36
[ "MIT" ]
2
2020-06-05T15:57:50.000Z
2020-06-30T12:59:00.000Z
csv-manipulation/csv-merge.py
bohnacker/data-manipulation
a46cdfdeca8d242038b118509c20b1eb39ea5b36
[ "MIT" ]
null
null
null
csv-manipulation/csv-merge.py
bohnacker/data-manipulation
a46cdfdeca8d242038b118509c20b1eb39ea5b36
[ "MIT" ]
null
null
null
from __future__ import print_function # A script to help you with manipulating CSV-files. This is especially necessary when dealing with # CSVs that have more than 65536 lines because those can not (yet) be opened in Excel or Numbers. # This script works with two files from ourworldindata.org: # https://ourworldindata.org/age-structure and https://ourworldindata.org/gender-ratio # This script MERGES two CSVs. # # Usage: # - Adjust filenames and delimiters. # - Variable matchColumns: names of the matching columns in the first CSV # - Variable withColumns: names of the matching columns in the second CSV # - Variable copyColumns: which columns from the second CSV should be copied # to the first. If copyColumns is [], it copies all cloumns except # what's defined in the variable 'withColumn' # Examples: # copyColums = ['latitude', 'longitude'] Will copy those two columns # copyColums = [] Will copy all columns # --------------------------------------------- # Change the parameters according to your task: # Give the name of the CSV file where you want to add columns readFileName1 = 'worlddata-median-age.csv' # <--- Adjust here # What delimiter is used in this CSV? Usually ',' or ';' readDelimiter1 = ',' # <--- Adjust here (have a look in your source CSV) # Give the name of the CSV file that gives additional values readFileName2 = 'worlddata-share-population-female.csv' # <--- Adjust here # What delimiter is used in this CSV? Usually ',' or ';' readDelimiter2 = ',' # <--- Adjust here (have a look in your source CSV) # The result will be a new CSV file: writeFileName = 'worlddata_merged.csv' # <--- Adjust here (has to be different than readFileName1) # You can give a different delimiter for the result. writeDelimiter = ',' # <--- Adjust here (';' is usually good) matchColumns = ['Code', 'Year'] # <--- Adjust here withColumns = ['Code', 'Year'] # <--- Adjust here copyColumns = ['PercentFemale'] # <--- Adjust here # # Second example for merging longitude/latitude data to a file with countries # readFileName1 = 'wintergames_winners.csv' # readDelimiter1 = ';' # readFileName2 = 'longitude-latitude.csv' # readDelimiter2 = ',' # writeFileName = 'wintergame_winners_merged.csv' # writeDelimiter = ';' # matchColumns = ['NOC'] # withColumns = ['IOC'] # copyColumns = ['latitude', 'longitude'] # ---------------------------------------------- # No need to change anything from here on ... import csv from collections import OrderedDict readFile1 = open(readFileName1) reader1 = csv.DictReader(readFile1, delimiter=readDelimiter1) rows1 = list(reader1) readFile2 = open(readFileName2) reader2 = csv.DictReader(readFile2, delimiter=readDelimiter2) rows2 = list(reader2) writeFile = open(writeFileName, 'w') writer = csv.writer(writeFile, delimiter=writeDelimiter) # This writes the field names to the result.csv headings1 = list(reader1.fieldnames) if copyColumns == []: copyColumns = list(filter(lambda x: x != withColumn, reader.fieldnames)) writer.writerow(headings1 + copyColumns) # create dict from second csv to speed up finding stuff print('Preparing merge') print('----------------------') dic = {} unique = True for row in rows2: key = tuple(row[x] for x in withColumns) # for col in withColumns: # key = key + row[col] + '__' if key != '': if key in dic: unique = False else: dic[key] = row if (not unique): print('Warning: The columns "%s" in the second CSV has duplicate values which could result in incorrect matching.' % withColumns) print('----------------------') print('Merging') failed = [] numRows = 0 perc = 0 for i, row in enumerate(rows1): if float(i) / len(rows1) > perc: print('#', end='') perc = perc + 0.01 values = [] val = tuple(row[x] for x in matchColumns) # for col in matchColumns: # val = val + row[col] + '__' for key in headings1: values.append(row[key]) for key in copyColumns: try: values.append(dic[val][key]) except: if (not val in failed): failed.append(val) writer.writerow(values) print('\n----------------------') print('%d value(s) could not be found in the second CSV, so matching was not possible for every row.' % len(failed)) print("These values couldn't be matched:") print(failed[:100]) if (len(failed) > 100): print('... and %d more' % (len(failed) - 100))
33.780142
131
0.618728
567
4,763
5.174603
0.365079
0.030675
0.01636
0.014315
0.103613
0.103613
0.093388
0.05726
0.05726
0.034083
0
0.013611
0.244174
4,763
140
132
34.021429
0.801389
0.4789
0
0.031746
0
0.031746
0.186392
0.053196
0
0
0
0
0
1
0
false
0
0.047619
0
0.047619
0.190476
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
695982e3be224fdcb410f0b1f9e5e2d7fef87d2d
1,713
py
Python
crawler/configs.py
debasishbai/Tender-Crawler
b721f197236bee4a69e0f403101a159af5924dda
[ "MIT" ]
null
null
null
crawler/configs.py
debasishbai/Tender-Crawler
b721f197236bee4a69e0f403101a159af5924dda
[ "MIT" ]
1
2021-06-30T07:28:21.000Z
2021-06-30T07:28:21.000Z
crawler/configs.py
debasishbai/Tender-Crawler
b721f197236bee4a69e0f403101a159af5924dda
[ "MIT" ]
null
null
null
go_to_tender_page = "Live Tenders" search_bar = "#sr_buyer_chzn > a > span" all_dept_names = "#sr_buyer_chzn > div > ul > li:nth-of-type(n+1)" search_button = '#frm_sr > div.actionBtn > input[type="button"]:nth-child(1)' type_name = '#sr_buyer_chzn > div > div > input[type="text"]' scroll_down = "window.scrollTo(0, document.body.scrollHeight);" lister_scope = "#tblSummary > tbody > tr:nth-of-type(2n+2)" tender_count = "#uipage > div.bpanel > div.uisummary > form > div:nth-child(1)" page_count = "#selMQ6_chzn > div > ul > li" work_name_scope = "#tblSummary > tbody > tr:nth-of-type(2n+3)" work_name = "td" tender_no = "td:nth-child(4)" action = "td:nth-child(2) > a" show_form = "#action-links > ul > li:nth-child(1) > a" details_page = "body > div.panel > div.bpanel.p_false > div.info > table > tbody > tr:nth-child(1) > td:nth-child(4) > a" show_hidden_css = "body > div.panel > div.bpanel > div.summary > form > div.right > a" random_click = "td:nth-child(3)" details_scope = { "Name of Work": "#descOfWorkspan", "Tender No": "#tenderNumberspan", "EMD": "#emdspan", "Amount of Contract (PAC)": "#estimatedCostspan", "Cost of Document": "#formFeespan", "Purchase of Tender Start Date": "#recvOfAppFromDatespan", "Purchase of Tender End Date": "#recvOfAppToDatespan", "Bid Submission End Date": "#receiptOfTendToDatespan" } next_page = "#uipage > div.bpanel > div.uisummary > form > div.paginationLinks > div > a:nth-of-type(n+2)" settings = "chrome://settings-frame/content" enable_autodownload = "#content-settings-page > div.content-area > section:nth-child(13) > div > div:nth-child(1) > label > span > span:nth-child(1)" finish = "#content-settings-overlay-confirm"
50.382353
150
0.683596
251
1,713
4.533865
0.422311
0.077329
0.047452
0.024605
0.154657
0.11775
0.11775
0.057996
0
0
0
0.013605
0.141856
1,713
33
151
51.909091
0.760544
0
0
0
0
0.16129
0.719206
0.124927
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
695a580d9dfe172ab929a611ecc5c4b39192aa4c
2,590
py
Python
authors/apps/profiles/serializers.py
andela/ah-jumanji-
a304718929936dd4a759d737fb3570d6cc25fb76
[ "BSD-3-Clause" ]
1
2018-12-23T15:31:54.000Z
2018-12-23T15:31:54.000Z
authors/apps/profiles/serializers.py
andela/ah-jumanji-
a304718929936dd4a759d737fb3570d6cc25fb76
[ "BSD-3-Clause" ]
26
2018-11-27T09:13:15.000Z
2021-06-10T20:58:57.000Z
authors/apps/profiles/serializers.py
andela/ah-jumanji-
a304718929936dd4a759d737fb3570d6cc25fb76
[ "BSD-3-Clause" ]
2
2019-01-10T22:14:28.000Z
2019-11-04T07:33:43.000Z
""" Module serializes `Profile` model :generates JSON from fields in `Profile` model """ import logging from rest_framework import serializers from authors.apps.authentication.serializers import UserSerializer from authors.apps.profiles.models import Profile, Following logger = logging.getLogger(__name__) class ProfileSerializer(serializers.ModelSerializer): """ Generate JSON from `Profile model """ class Meta: """ Map fields in `Profile` model with serializer's JSON params """ model = Profile # Collect all the fields in `Profile` model fields = '__all__' # read only fiels - not editable read_only_fields = [ 'user', ] def update(self, instance, prof_data): """ Update profile items """ # For every item provided in the payload, # amend the profile accordingly for (key, value) in prof_data.items(): setattr(instance.profile, key, value) instance.save() return instance class BasicProfileSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() following = serializers.SerializerMethodField() class Meta: model = Profile fields = ('user', 'bio', 'profile_photo', 'following') def get_user(self, obj): """ return the username of user :param obj: :return: """ return obj.user.username def get_following(self, obj): """ get current logged in user and verify if they are followers :param obj: :return: """ requester = self.context['user'] logger.debug("*" * 100) logger.debug(requester) # get or create a profile for the current user # this will return a queryset of length 1 profile = Profile.objects.get_or_create(user=requester) profile = profile[0] return profile.is_followed(obj.user) class FollowingSerializer(serializers.ModelSerializer): follower = UserSerializer() followed = UserSerializer() class Meta: model = Following exclude = ('id', 'modified') class FollowedSerializer(serializers.ModelSerializer): followed = UserSerializer() class Meta: model = Following exclude = ('id', 'modified', 'follower') class FollowersSerializer(serializers.ModelSerializer): follower = UserSerializer() class Meta: model = Following exclude = ('id', 'modified', 'followed')
24.903846
71
0.62471
257
2,590
6.22179
0.396887
0.037523
0.035022
0.037523
0.11132
0.11132
0.11132
0.11132
0.077548
0
0
0.002697
0.28417
2,590
103
72
25.145631
0.859763
0.2139
0
0.291667
1
0
0.04882
0
0
0
0
0
0
1
0.0625
false
0
0.083333
0
0.541667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
695aa8899e70c364dd37a9eae8fc436359e8c4b2
1,849
py
Python
users/forms.py
hrbhat/twissandra
e2c16eac29b3c77065555da269b7974898e9f80e
[ "Apache-2.0" ]
308
2015-01-04T20:05:10.000Z
2022-03-09T17:15:52.000Z
users/forms.py
hrbhat/twissandra
e2c16eac29b3c77065555da269b7974898e9f80e
[ "Apache-2.0" ]
10
2016-01-02T20:29:03.000Z
2020-06-05T16:45:20.000Z
users/forms.py
hrbhat/twissandra
e2c16eac29b3c77065555da269b7974898e9f80e
[ "Apache-2.0" ]
109
2015-02-01T11:25:24.000Z
2022-03-18T12:18:13.000Z
from django import forms import cass class LoginForm(forms.Form): username = forms.CharField(max_length=30) password = forms.CharField(widget=forms.PasswordInput(render_value=False)) def clean(self): username = self.cleaned_data['username'] password = self.cleaned_data['password'] try: user = cass.get_user_by_username(username) except cass.DatabaseError: raise forms.ValidationError(u'Invalid username and/or password') if user.password != password: raise forms.ValidationError(u'Invalid username and/or password') return self.cleaned_data def get_username(self): return self.cleaned_data['username'] class RegistrationForm(forms.Form): username = forms.RegexField(regex=r'^\w+$', max_length=30) password1 = forms.CharField(widget=forms.PasswordInput(render_value=False)) password2 = forms.CharField(widget=forms.PasswordInput(render_value=False)) def clean_username(self): username = self.cleaned_data['username'] try: cass.get_user_by_username(username) raise forms.ValidationError(u'Username is already taken') except cass.DatabaseError: pass return username def clean(self): if ('password1' in self.cleaned_data and 'password2' in self.cleaned_data): password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 != password2: raise forms.ValidationError( u'You must type the same password each time') return self.cleaned_data def save(self): username = self.cleaned_data['username'] password = self.cleaned_data['password1'] cass.save_user(username, password) return username
35.557692
83
0.663602
209
1,849
5.746411
0.277512
0.109908
0.149875
0.076603
0.452123
0.412157
0.334721
0.334721
0.289759
0.199833
0
0.010722
0.243375
1,849
51
84
36.254902
0.847748
0
0
0.357143
0
0
0.118983
0
0
0
0
0
0
1
0.119048
false
0.357143
0.047619
0.02381
0.452381
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
695b6b62546eaa04ce79f4261d88a6eb1b8a86ea
16,047
py
Python
script/python/assoc_sclrt_kernels_spliceai_eval_top_hits.py
HealthML/faatpipe
8292df4f34c99f035756a1acbd2c79055f652958
[ "Apache-2.0" ]
2
2021-12-06T09:00:52.000Z
2022-03-03T15:03:51.000Z
script/python/assoc_sclrt_kernels_spliceai_eval_top_hits.py
HealthML/faatpipe
8292df4f34c99f035756a1acbd2c79055f652958
[ "Apache-2.0" ]
null
null
null
script/python/assoc_sclrt_kernels_spliceai_eval_top_hits.py
HealthML/faatpipe
8292df4f34c99f035756a1acbd2c79055f652958
[ "Apache-2.0" ]
null
null
null
import os # os.environ["OMP_NUM_THREADS"] = "16" import logging logging.basicConfig(filename=snakemake.log[0], level=logging.INFO) import pandas as pd import numpy as np # seak imports from seak.data_loaders import intersect_ids, EnsemblVEPLoader, VariantLoaderSnpReader, CovariatesLoaderCSV from seak.scoretest import ScoretestNoK from seak.lrt import LRTnoK, pv_chi2mixture, fit_chi2mixture from pysnptools.snpreader import Bed import pickle import sys from util.association import BurdenLoaderHDF5 from util import Timer class GotNone(Exception): pass # set up the covariatesloader covariatesloader = CovariatesLoaderCSV(snakemake.params.phenotype, snakemake.input.covariates_tsv, snakemake.params.covariate_column_names, sep='\t', path_to_phenotypes=snakemake.input.phenotypes_tsv) # initialize the null models Y, X = covariatesloader.get_one_hot_covariates_and_phenotype('noK') null_model_score = ScoretestNoK(Y, X) null_model_lrt = LRTnoK(X, Y) # set up function to filter variants: def maf_filter(mac_report): # load the MAC report, keep only observed variants with MAF below threshold mac_report = pd.read_csv(mac_report, sep='\t', usecols=['SNP', 'MAF', 'Minor', 'alt_greater_ref']) if snakemake.params.filter_highconfidence: vids = mac_report.SNP[(mac_report.MAF < snakemake.params.max_maf) & (mac_report.Minor > 0) & ~(mac_report.alt_greater_ref.astype(bool)) & (mac_report.hiconf_reg.astype(bool))] else: vids = mac_report.SNP[(mac_report.MAF < snakemake.params.max_maf) & (mac_report.Minor > 0) & ~(mac_report.alt_greater_ref.astype(bool))] # this has already been done in filter_variants.py # load the variant annotation, keep only variants in high-confidece regions # anno = pd.read_csv(anno_tsv, sep='\t', usecols=['Name', 'hiconf_reg']) # vids_highconf = anno.Name[anno.hiconf_reg.astype(bool).values] # vids = np.intersect1d(vids, vids_highconf) return mac_report.set_index('SNP').loc[vids] def get_regions(): # load the results, keep those below a certain p-value results = pd.read_csv(snakemake.input.results_tsv, sep='\t') kern = snakemake.params.kernels if isinstance(kern, str): kern = [kern] pvcols_score = ['pv_score_' + k for k in kern ] pvcols_lrt = ['pv_lrt_' + k for k in kern] statcols = ['lrtstat_' + k for k in kern] results = results[['gene', 'n_snp', 'cumMAC', 'nCarrier'] + statcols + pvcols_score + pvcols_lrt] # get genes below threshold genes = [results.gene[results[k] < 1e-7].values for k in pvcols_score + pvcols_lrt ] genes = np.unique(np.concatenate(genes)) if len(genes) == 0: return None # set up the regions to loop over for the chromosome regions = pd.read_csv(snakemake.input.regions_bed, sep='\t', header=None, usecols=[0 ,1 ,2 ,3, 5], dtype={0 :str, 1: np.int32, 2 :np.int32, 3 :str, 5:str}) regions.columns = ['chrom', 'start', 'end', 'name', 'strand'] regions['strand'] = regions.strand.map({'+': 'plus', '-': 'minus'}) regions = regions.set_index('name').loc[genes] regions = regions.join(results.set_index('gene'), how='left').reset_index() return regions # genotype path, vep-path: assert len(snakemake.params.ids) == len (snakemake.input.bed), 'Error: length of chromosome IDs does not match length of genotype files' geno_vep = zip(snakemake.params.ids, snakemake.input.bed, snakemake.input.vep_tsv, snakemake.input.ensembl_vep_tsv, snakemake.input.mac_report, snakemake.input.h5_lof, snakemake.input.iid_lof, snakemake.input.gid_lof) # get the top hits regions_all = get_regions() if regions_all is None: logging.info('No genes pass significance threshold, exiting.') sys.exit(0) # where we store the results stats = [] i_gene = 0 # enter the chromosome loop: timer = Timer() for i, (chromosome, bed, vep_tsv, ensembl_vep_tsv, mac_report, h5_lof, iid_lof, gid_lof) in enumerate(geno_vep): if chromosome.replace('chr','') not in regions_all.chrom.unique(): continue # set up the ensembl vep loader for the chromosome spliceaidf = pd.read_csv(vep_tsv, sep='\t', usecols=['name', 'chrom', 'end', 'gene', 'max_effect', 'DS_AG', 'DS_AL', 'DS_DG', 'DS_DL', 'DP_AG', 'DP_AL', 'DP_DG', 'DP_DL'], index_col='name') # get set of variants for the chromosome: mac_report = maf_filter(mac_report) filter_vids = mac_report.index.values # filter by MAF keep = intersect_ids(filter_vids, spliceaidf.index.values) spliceaidf = spliceaidf.loc[keep] spliceaidf.reset_index(inplace=True) # filter by impact: spliceaidf = spliceaidf[spliceaidf.max_effect >= snakemake.params.min_impact] # set up the regions to loop over for the chromosome regions = regions_all.copy() # discard all genes for which we don't have annotations gene_ids = regions.name.str.split('_', expand=True) # table with two columns, ensembl-id and gene-name regions['gene'] = gene_ids[1] # this is the gene name regions['ensembl_id'] = gene_ids[0] regions.set_index('gene', inplace=True) genes = intersect_ids(np.unique(regions.index.values), np.unique(spliceaidf.gene)) # intersection of gene names regions = regions.loc[genes].reset_index() # subsetting regions = regions.sort_values(['chrom', 'start', 'end']) # check if the variants are protein LOF variants, load the protein LOF variants: ensemblvepdf = pd.read_csv(ensembl_vep_tsv, sep='\t', usecols=['Uploaded_variation', 'Gene']) # this column will contain the gene names: genes = intersect_ids(np.unique(ensemblvepdf.Gene.values), regions.ensembl_id) # intersection of ensembl gene ids ensemblvepdf = ensemblvepdf.set_index('Gene').loc[genes].reset_index() ensemblvepdf['gene'] = gene_ids.set_index(0).loc[ensemblvepdf.Gene.values].values # set up the merge ensemblvepdf.drop(columns=['Gene'], inplace=True) # get rid of the ensembl ids, will use gene names instead ensemblvepdf.rename(columns={'Uploaded_variation': 'name'}, inplace=True) ensemblvepdf['is_plof'] = 1. ensemblvepdf = ensemblvepdf[~ensemblvepdf.duplicated()] # if multiple ensembl gene ids map to the same gene names, this prevents a crash. # we add a column to the dataframe indicating whether the variant is already annotated as protein loss of function by the ensembl variant effect predictor spliceaidf = pd.merge(spliceaidf, ensemblvepdf, on=['name', 'gene'], how='left', validate='one_to_one') spliceaidf['is_plof'] = spliceaidf['is_plof'].fillna(0.).astype(bool) # initialize the loader # Note: we use "end" here because the start + 1 = end, and we need 1-based coordiantes (this would break if we had indels) eveploader = EnsemblVEPLoader(spliceaidf['name'], spliceaidf['chrom'].astype('str') + ':' + spliceaidf['end'].astype('str'), spliceaidf['gene'], data=spliceaidf[['max_effect', 'is_plof', 'DS_AG', 'DS_AL', 'DS_DG', 'DS_DL', 'DP_AG', 'DP_AL', 'DP_DG', 'DP_DL']].values) # set up the variant loader (splice variants) for the chromosome plinkloader = VariantLoaderSnpReader(Bed(bed, count_A1=True, num_threads=4)) plinkloader.update_variants(eveploader.get_vids()) plinkloader.update_individuals(covariatesloader.get_iids()) # set up the protein LOF burden loader bloader_lof = BurdenLoaderHDF5(h5_lof, iid_lof, gid_lof) bloader_lof.update_individuals(covariatesloader.get_iids()) # set up the splice genotype + vep loading function def get_splice(interval): try: V1 = eveploader.anno_by_interval(interval, gene=interval['name'].split('_')[1]) except KeyError: raise GotNone if V1.index.empty: raise GotNone vids = V1.index.get_level_values('vid') V1 = V1.droplevel(['gene']) temp_genotypes, temp_vids = plinkloader.genotypes_by_id(vids, return_pos=False) temp_genotypes -= np.nanmean(temp_genotypes, axis=0) G1 = np.ma.masked_invalid(temp_genotypes).filled(0.) ncarrier = np.sum(G1 > 0.5, axis=0) cummac = mac_report.loc[vids].Minor # spliceAI max score weights = V1[0].values.astype(np.float64) is_plof = V1[1].values.astype(bool) splice_preds_all = V1.iloc[:,2:] splice_preds_all.columns = ['DS_AG', 'DS_AL', 'DS_DG', 'DS_DL', 'DP_AG', 'DP_AL', 'DP_DG', 'DP_DL'] # "standardized" positions -> codon start positions # pos = V1[0].values.astype(np.int32) return G1, vids, weights, ncarrier, cummac, is_plof, splice_preds_all # set up the protein-LOF loading function def get_plof(interval): try: G2 = bloader_lof.genotypes_by_id(interval['name']).astype(np.float) except KeyError: G2 = None return G2 # set up the test-function for a single gene def test_gene(interval, seed): pval_dict = {} pval_dict['gene'] = interval['name'] called = [] def pv_score(GV): pv = null_model_score.pv_alt_model(GV) if pv < 0.: pv = null_model_score.pv_alt_model(GV, method='saddle') return pv def call_score(GV, name, vids=None): if name not in pval_dict: pval_dict[name] = {} called.append(name) pval_dict[name] = {} # single-marker p-values pval_dict[name]['pv_score'] = np.array([pv_score(GV[:,i,np.newaxis]) for i in range(GV.shape[1])]) # single-marker coefficients beta = [ null_model_score.coef(GV[:,i,np.newaxis]) for i in range(GV.shape[1]) ] pval_dict[name]['beta'] = np.array([x['beta'][0,0] for x in beta]) pval_dict[name]['betaSd'] = np.array([np.sqrt(x['var_beta'][0,0]) for x in beta]) if vids is not None: pval_dict[name]['vid'] = vids def call_lrt(GV, name, vids=None): if name not in pval_dict: pval_dict[name] = {} called.append(name) # get gene parameters, test statistics and and single-marker regression weights lik = null_model_lrt.altmodel(GV) pval_dict[name]['nLL'] = lik['nLL'] pval_dict[name]['sigma2'] = lik['sigma2'] pval_dict[name]['lrtstat'] = lik['stat'] pval_dict[name]['h2'] = lik['h2'] logdelta = null_model_lrt.model1.find_log_delta(GV.shape[1]) pval_dict[name]['log_delta'] = logdelta['log_delta'] pval_dict[name]['coef_random'] = null_model_lrt.model1.getPosteriorWeights(logdelta['beta'], logdelta=logdelta['log_delta']) if vids is not None: pval_dict[name]['vid'] = vids # load splice variants G1, vids, weights, ncarrier, cummac, is_plof, splice_preds_all = get_splice(interval) # keep indicates which variants are NOT "protein LOF" variants, i.e. variants already identified by the ensembl VEP keep = ~is_plof # these are common to all kernels pval_dict['vid'] = vids pval_dict['weights'] = weights pval_dict['MAC'] = cummac pval_dict['nCarrier'] = ncarrier pval_dict['not_LOF'] = keep for col in splice_preds_all.columns: pval_dict[col] = splice_preds_all[col].values.astype(np.float32) # single-variant p-values: call_score(G1, 'variant_pvals') # single variant p-values and coefficients estimated independently call_lrt(G1.dot(np.diag(np.sqrt(weights), k=0)), 'variant_pvals') # single variant coefficients estimated *jointly* after weighting # sanity checks assert len(vids) == interval['n_snp'], 'Error: number of variants does not match! expected: {} got: {}'.format(interval['n_snp'], len(vids)) assert cummac.sum() == interval['cumMAC'], 'Error: cumMAC does not match! expeced: {}, got: {}'.format(interval['cumMAC'], cummac.sum()) # do a score burden test (max weighted), this is different than the baseline! G1_burden = np.max(np.where(G1 > 0.5, np.sqrt(weights), 0.), axis=1, keepdims=True) call_score(G1_burden, 'linwb') call_lrt(G1_burden, 'linwb') # linear weighted kernel G1 = G1.dot(np.diag(np.sqrt(weights), k=0)) # do a score test (linear weighted) call_score(G1, 'linw', vids=vids) call_lrt(G1, 'linw') # load plof burden G2 = get_plof(interval) if G2 is not None: call_score(G2, 'LOF') call_lrt(G2, 'LOF') if np.any(keep): # merged (single variable) G1_burden_mrg = np.maximum(G2, G1_burden) call_score(G1_burden_mrg, 'linwb_mrgLOF') call_lrt(G1_burden_mrg, 'linwb_mrgLOF') # concatenated ( >= 2 variables) # we separate out the ones that are already part of the protein LOF variants! G1 = np.concatenate([G1[:, keep], G2], axis=1) call_score(G1, 'linw_cLOF', vids=np.array(vids[keep].tolist() + [-1])) call_lrt(G1, 'linw_cLOF') else: logging.info('All Splice-AI variants for gene {} where already identified by the Ensembl variant effect predictor'.format(interval['name'])) return pval_dict, called logging.info('loaders for chromosome {} initialized in {:.1f} seconds.'.format(chromosome, timer.check())) # run tests for all genes on the chromosome for _, region in regions.iterrows(): try: gene_stats, called = test_gene(region, i_gene) except GotNone: continue # build the single-variant datafame single_var_columns = ['gene', 'vid', 'weights', 'MAC', 'nCarrier', 'not_LOF', 'DS_AG', 'DS_AL', 'DS_DG', 'DS_DL', 'DP_AG', 'DP_AL', 'DP_DG', 'DP_DL'] sv_df = pd.DataFrame.from_dict({k: gene_stats[k] for k in single_var_columns}) sv_df['pv_score'] = gene_stats['variant_pvals']['pv_score'] # single-variant p-values estimated independently sv_df['coef_random'] = gene_stats['variant_pvals']['coef_random'] # single-variant coefficients estimated jointly after weighting sv_df['beta'] = gene_stats['variant_pvals']['beta'] # single-variant coeffcients estimated independently *without* weighting sv_df['betaSd'] = gene_stats['variant_pvals']['betaSd'] # standard errors for the single-variant coefficients estimated independently *without* weighting sv_df['pheno'] = snakemake.params.phenotype out_dir = os.path.join(snakemake.params.out_dir_stats, region['name']) os.makedirs(out_dir, exist_ok=True) sv_df.to_csv(out_dir + '/variants.tsv.gz', sep='\t', index=False) for k in called: if k == 'variant_pvals': continue results_dict = gene_stats[k] df_cols = ['pv_score', 'coef_random', 'beta', 'betaSd', 'vid'] # parts of the dict that have lenght > 1 df = pd.DataFrame.from_dict(data={k: results_dict[k] for k in df_cols if k in results_dict}) df['gene'] = gene_stats['gene'] df['pheno'] = snakemake.params.phenotype df.to_csv(out_dir + '/{}.tsv.gz'.format(k), sep='\t', index=False) # other cols ['nLL', 'sigma2', 'lrtstat', 'h2', 'log_delta'] other_cols = {k: v for k, v in results_dict.items() if k not in df_cols} other_cols['gene'] = gene_stats['gene'] other_cols['pheno'] = snakemake.params.phenotype pickle.dump(other_cols, open(out_dir + '/{}_stats.pkl'.format(k), 'wb')) i_gene += 1 logging.info('tested {} genes...'.format(i_gene)) timer.reset()
42.228947
271
0.645541
2,173
16,047
4.598251
0.202945
0.020016
0.016813
0.003503
0.179243
0.132706
0.110889
0.096677
0.081465
0.076261
0
0.010103
0.228952
16,047
380
272
42.228947
0.797462
0.200287
0
0.114155
0
0
0.114707
0
0
0
0
0
0.013699
1
0.03653
false
0.009132
0.054795
0
0.127854
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
695bd5a3034969d8612674c32efea1218548dce0
4,741
py
Python
animations/dafP1.py
TristanCacqueray/demo-render
4c8403e684165e5e75c046ee023c1f794a6650a8
[ "Apache-2.0" ]
9
2018-02-19T14:17:12.000Z
2021-03-27T14:46:28.000Z
animations/dafP1.py
TristanCacqueray/demo-render
4c8403e684165e5e75c046ee023c1f794a6650a8
[ "Apache-2.0" ]
null
null
null
animations/dafP1.py
TristanCacqueray/demo-render
4c8403e684165e5e75c046ee023c1f794a6650a8
[ "Apache-2.0" ]
null
null
null
#!/bin/env python # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import yaml from utils.animation import Animation, run_main from utils.audio import SpectroGram, AudioMod p = """ formula: | z.imag = fabs(z.imag); z = cdouble_powr(z, mod); z = cdouble_add(z, c); z = cdouble_log(z); kernel: mean-distance kernel_params: "double mod" kernel_params_mod: - mod mod: 1 xyinverted: True gradient: render_data/Solankii Gradients for Gimp/Gradient-#21.ggr c_imag: -0.13422671142194348 c_real: 0.298544669649099 i_step: 0.012438114469344182 julia: true map_center_imag: 0.298544669649099 map_center_real: -0.1217885969525993 map_radius: 0.12438114469344182 r_step: 0.012438114469344182 radius: 51.16156978094776 """ class Demo(Animation): def __init__(self): self.scenes = [ [4000, None], [3500, self.ending], [3286, self.zoom], [2526, self.verse4], [2025, self.verse3], [1770, self.verse2], [1520, self.tr1], [754, self.verse1], [0, self.intro], ] super().__init__(yaml.load(p)) def setAudio(self, audio): self.audio = audio self.spectre = SpectroGram(audio.audio_frame_size) self.audio_events = { "low": AudioMod((0, 12), "max", decay=10), "mid": AudioMod((152, 483), "max", decay=5), "hgh": AudioMod((12, 456), "avg"), } def ending(self, frame): self.params["c_imag"] -= 4e-5 * self.low + 1e-4 * self.mid + 1e-5 self.params["grad_freq"] += 2e-1 * self.hgh def zoom(self, frame): if self.scene_init: self.imag_mod = self.logspace(self.params["c_imag"], 0.9187686207968877) self.rad_mod = self.logspace(self.params["radius"], 0.03) self.freq_mod = self.logspace(self.params["grad_freq"], 0.20) self.params["grad_freq"] = self.freq_mod[self.scene_pos] self.params["radius"] = self.rad_mod[self.scene_pos] if frame < 3400: self.params["c_imag"] = self.imag_mod[self.scene_pos] else: self.params["c_imag"] -= 4e-5 * self.low + 1e-4 * self.mid def verse4(self, frame): if self.scene_init: self.rad_mod = self.logspace(self.params["radius"], 3606) self.params["radius"] = self.rad_mod[self.scene_pos] self.params["c_imag"] += 5e-6 * self.low self.params["c_real"] -= 5e-6 * self.mid def verse3(self, frame): if self.scene_init: self.rad_mod = self.logspace(self.params["radius"], 556) self.params["radius"] = self.rad_mod[self.scene_pos] self.params["c_imag"] += 8e-5 * self.mid self.params["c_real"] -= 1e-5 * self.low self.params["grad_freq"] += 1e-2 * self.hgh def verse2(self, frame): if self.scene_init: self.base_real = self.params["c_real"] self.params["c_imag"] -= 8e-5 * self.low self.params["grad_freq"] += 1e-2 * self.mid # self.params["c_real"] += 1e-4 * self.mid # self.params["c_real"] += 1e-4 * self.mid def tr1(self, frame): if self.scene_init: self.rad_mod = self.logspace(self.params["radius"], 129) self.params["radius"] = self.rad_mod[self.scene_pos] self.params["grad_freq"] -= 1e-2 * self.low self.params["c_imag"] += 1e-4 * self.mid def verse1(self, frame): if self.scene_init: self.rad_mod = self.linspace(self.params["radius"], 0.1) self.params["radius"] = self.rad_mod[self.scene_pos] self.params["c_imag"] += 4e-5 * self.low self.params["c_real"] += 1e-4 * self.mid self.params["grad_freq"] += 2e-2 * self.hgh def intro(self, frame): if self.scene_init: self.base_real = self.params["c_real"] self.rad_mod = self.linspace(self.params["radius"], 0.08) self.params["radius"] = self.rad_mod[self.scene_pos] self.params["c_imag"] += 4e-5 * self.low self.params["c_real"] = self.base_real + 2e-4 * self.hgh self.params["grad_freq"] += 3e-3 * self.mid if __name__ == "__main__": run_main(Demo())
34.605839
75
0.607467
670
4,741
4.153731
0.274627
0.136543
0.071146
0.060367
0.440532
0.398491
0.385196
0.355372
0.341718
0.306504
0
0.08228
0.248893
4,741
136
76
34.860294
0.699242
0.133938
0
0.163462
0
0
0.195748
0.005132
0
0
0
0
0
1
0.096154
false
0
0.028846
0
0.134615
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
695c9b1e7ed238ec8d68378d50cb9434b9b47feb
2,240
py
Python
design-pattern/factory_method.py
twotwo/tools-python
b9e7a97e58fb0a3f3fb5e8b674e64a997669c2c4
[ "MIT" ]
null
null
null
design-pattern/factory_method.py
twotwo/tools-python
b9e7a97e58fb0a3f3fb5e8b674e64a997669c2c4
[ "MIT" ]
null
null
null
design-pattern/factory_method.py
twotwo/tools-python
b9e7a97e58fb0a3f3fb5e8b674e64a997669c2c4
[ "MIT" ]
1
2016-10-21T07:51:24.000Z
2016-10-21T07:51:24.000Z
from abc import ABC, abstractmethod class Pizza(ABC): @abstractmethod def prepare(self): pass def bake(self): print("baking pizza for 12min in 400 degrees..") def cut(self): print("cutting pizza in pieces") def box(self): print("putting pizza in box") class NYStyleCheesePizza(Pizza): def prepare(self): print("preparing a New York style cheese pizza..") class ChicagoStyleCheesePizza(Pizza): def prepare(self): print("preparing a Chicago style cheese pizza..") class NYStyleGreekPizza(Pizza): def prepare(self): print("preparing a New York style greek pizza..") class ChicagoStyleGreekPizza(Pizza): def prepare(self): print("preparing a Chicago style greek pizza..") # This time, PizzaStore is abstract class PizzaStore(ABC): # We brought createPizza back into the PizzaStore (instead of the SimpleFactory) # However, it is declared as abstract. This time, instead of having # a factory class, we have a factory method: @abstractmethod def _createPizza(self, pizzaType: str) -> Pizza: pass def orderPizza(self, pizzaType): pizza: Pizza pizza = self._createPizza(pizzaType) pizza.prepare() pizza.bake() pizza.cut() pizza.box() class NYPizzaStore(PizzaStore): def _createPizza(self, pizzaType: str) -> Pizza: pizza: Pizza = None if pizzaType == 'Greek': pizza = NYStyleGreekPizza() elif pizzaType == 'Cheese': pizza = NYStyleCheesePizza() else: print("No matching pizza found in the NY pizza store...") return pizza class ChicagoPizzaStore(PizzaStore): def _createPizza(self, pizzaType: str) -> Pizza: pizza: Pizza = None if pizzaType == 'Greek': pizza = ChicagoStyleGreekPizza() elif pizzaType == 'Cheese': pizza = ChicagoStyleCheesePizza() else: print("No matching pizza found in the Chicago pizza store...") return pizza nyPizzaStore = NYPizzaStore() chPizzaStore = ChicagoPizzaStore() nyPizzaStore.orderPizza('Greek') print("\n") chPizzaStore.orderPizza('Cheese')
23.092784
84
0.638839
240
2,240
5.945833
0.308333
0.044149
0.049054
0.053259
0.313245
0.313245
0.288718
0.288718
0.241065
0.176594
0
0.003036
0.264732
2,240
96
85
23.333333
0.863388
0.098661
0
0.372881
0
0
0.187686
0
0
0
0
0
0
1
0.20339
false
0.033898
0.016949
0
0.389831
0.169492
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
1
695cb03fad71e52d66b52655147eb22d30993c0d
366
py
Python
backup/server/__init__.py
TheSithPadawan/CSE222A-CourseProject
ded7232fa76a8c57e2355a6559573f71e6e63871
[ "MIT" ]
1
2019-02-17T06:41:59.000Z
2019-02-17T06:41:59.000Z
backup/server/__init__.py
TheSithPadawan/CSE222A-CourseProject
ded7232fa76a8c57e2355a6559573f71e6e63871
[ "MIT" ]
1
2019-02-21T05:19:31.000Z
2019-03-02T06:38:33.000Z
backup/server/__init__.py
TheSithPadawan/CSE222A-CourseProject
ded7232fa76a8c57e2355a6559573f71e6e63871
[ "MIT" ]
1
2022-02-12T05:18:49.000Z
2022-02-12T05:18:49.000Z
from flask import Flask from flask_sqlalchemy import SQLAlchemy db_url = 'postgresql://postgres:postgres@localhost:5432/postgres' db = SQLAlchemy() def create_app(): app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = db_url app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # initialize database db.init_app(app) return app
22.875
65
0.743169
46
366
5.630435
0.5
0.069498
0.146718
0
0
0
0
0
0
0
0
0.013029
0.161202
366
15
66
24.4
0.830619
0.051913
0
0
0
0
0.311047
0.311047
0
0
0
0
0
1
0.1
false
0
0.2
0
0.4
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
695d8b7488bd393e88af11f9dfa6cf05fcd29803
2,677
py
Python
ics2csv.py
wikier/apachecon-tac-scripts
8b58eb910990910ed113996c2662e2601bee0176
[ "Apache-2.0" ]
null
null
null
ics2csv.py
wikier/apachecon-tac-scripts
8b58eb910990910ed113996c2662e2601bee0176
[ "Apache-2.0" ]
null
null
null
ics2csv.py
wikier/apachecon-tac-scripts
8b58eb910990910ed113996c2662e2601bee0176
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # -*- coding: utf8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from clize import run from utils import download_file import re from os.path import basename, splitext from icalendar import Calendar import datetime import pytz import csv stopwords = [ "breakfast", "registration", "sponsor showcase", "coffee break", "lunch" "barcamp", "keynote", "morning run", "attendee reception" "BarCampApache" ] def ics2csv(ics, name=None): """ Transforms a ICS files to CSV ics: ics path or url name: conference name (optional) """ logging.basicConfig(level=logging.DEBUG, format="\033[1m%(name)s\033[0m %(message)s") logging.getLogger("requests").setLevel(logging.WARNING) log = logging.getLogger("tac") if name is None: name = splitext(basename(ics))[0] csv_path = "%s.csv" % name ics_path = "%s.ics" % name if ics.startswith("http") or ics.startswith("http"): ics_path = download_file(ics, ics_path) log.debug("Downloaded %s at %s", ics, ics_path) slots = [] with open(ics_path, 'r') as g: gcal = Calendar.from_ical(g.read()) for component in gcal.walk(): if component.name == "VEVENT": title = component.get('summary') start_time_utc = component.get('dtstart').dt local_tz = pytz.timezone('US/Eastern') # TODO: arg start_time_local = start_time_utc.astimezone(local_tz) start = start_time_local.strftime("%Y-%m-%d %H:%M") location = re.sub(', Miami, FL, United States$', '', component.get('location')) # TODO: arg if not any(stopword in title.lower() for stopword in stopwords): slots.append((title, location, start)) with open(csv_path, "w") as f: writer = csv.writer(f, quoting=csv.QUOTE_ALL) #writer.writerow(["talk", "room", "time", "volunteer", "backup"]) for slot in slots: writer.writerow(slot) log.info("Exported %d talks to %s", len(slots), csv_path) if __name__ == "__main__": run(ics2csv)
30.078652
109
0.637281
356
2,677
4.707865
0.505618
0.0358
0.0179
0.019093
0
0
0
0
0
0
0
0.007866
0.240194
2,677
88
110
30.420455
0.816126
0.27232
0
0
0
0
0.160293
0.011524
0
0
0
0.011364
0
1
0.019231
false
0
0.173077
0
0.192308
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
695e5925518853dabd7c44e5771ea4c0dcb5f954
1,925
py
Python
ctci/p3_1.py
camirmas/ctci
d90ab6c296a18cba5eb1204e0569aff2c6795422
[ "MIT" ]
null
null
null
ctci/p3_1.py
camirmas/ctci
d90ab6c296a18cba5eb1204e0569aff2c6795422
[ "MIT" ]
null
null
null
ctci/p3_1.py
camirmas/ctci
d90ab6c296a18cba5eb1204e0569aff2c6795422
[ "MIT" ]
null
null
null
"""Describe how you could use a single array to implement three stacks.""" class StackManager: def __init__(self): self.stacks = [] self.top = { 1: None, 2: None, 3: None, } self.length = { 1: 0, 2: 0, 3: 0, } def push(self, stack: int, data): assert stack in self.top if stack == 1: if self.top[1] is not None: self.top[1] += 1 if self.top[2] is not None: self.top[2] += 1 if self.top[3] is not None: self.top[3] += 1 else: self.top[1] = 0 elif stack == 2: if self.top[2] is not None: self.top[2] += 1 if self.top[3] is not None: self.top[3] += 1 else: if self.top[1] is not None: self.top[2] = self.top[1] + 1 else: self.top[2] = 0 else: if self.top[3] is not None: self.top[3] += 1 else: self.top[3] = len(self.stacks) self.stacks.insert(self.top[stack], data) self.length[stack] += 1 def pop(self, stack: int): assert stack in self.top if self.top[stack] is None: return None top = self.stacks.pop(self.top[stack]) self.top[stack] -= 1 self.length[stack] -= 1 if self.length[stack] == 0: self.top[stack] = None if stack == 1: if self.top[2] is not None: self.top[2] -= 1 if self.top[3] is not None: self.top[3] -= 1 elif stack == 2: if self.top[3] is not None: self.top[3] -= 1 return top
25
74
0.404156
245
1,925
3.159184
0.159184
0.289406
0.127907
0.167959
0.49354
0.49354
0.392765
0.392765
0.392765
0.325581
0
0.053213
0.482597
1,925
76
75
25.328947
0.723896
0.035325
0
0.474576
0
0
0
0
0
0
0
0
0.033898
1
0.050847
false
0
0
0
0.101695
0
0
0
0
null
1
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
695eb2e49aac8f15bf80012509cf307d5b4f61f7
5,434
py
Python
src/main/resources/basic.py
feng345fengcool/hellojava
efb1db4997d5e35572d69221b955e89f4ad84301
[ "Apache-2.0" ]
null
null
null
src/main/resources/basic.py
feng345fengcool/hellojava
efb1db4997d5e35572d69221b955e89f4ad84301
[ "Apache-2.0" ]
null
null
null
src/main/resources/basic.py
feng345fengcool/hellojava
efb1db4997d5e35572d69221b955e89f4ad84301
[ "Apache-2.0" ]
null
null
null
__author__ = 'chenshuai' cast = ["Cleese", "Plain", "Jones", "Idle"] print cast print len(cast) print cast[1] cast.append("Gilliam") print cast cast.pop() print cast cast.extend(["Gilliam", "Chapman"]) print cast cast.remove("Chapman") print cast cast.insert(0, "Chapman") print cast movies = ["The Holy Grail", "The Life of Brian", "The Meaning of Life"] movies.insert(1, 1975) movies.insert(3, 1979) movies.append(1983) fav_movies = ["The Holy Grail", "The Life of Brain"] for each_flick in fav_movies: print(each_flick) # movies = [[],[],[]] print movies[4][1][3] print isinstance(movies, list) # True print isinstance(len(movies), list) # False # nester.py # default value is not necessary def print_lol(the_list, indent=False, level=0, fh=sys.stdou): for each_item in the_list: if isinstance(each_item, list): print_lol(each_item, indent, level+1, fh) else: if indent: for tab_stop in range(level): print "\t" print each_item # print(each_item, end='', file=fh) python3 # python PyPI # perl CPAN """This is the standard way to include a multiple-line comment in your code.""" """import sys; print(sys.path); the location of python lib""" """pyc file === java class file""" # list() # range() # enumerate() # int() # id() # next() import os print os.chdir("../") print os.getcwd() data = open("sketch.txt") print data.readline() data.seek(0) # Man: Is this the right room for an argument? # Other Man: I've told you once. # Man: No you haven't! # Other Man: Yes I have. # Man: When? # Other Man: Just now. # Man: No you didn't if os.path.exists("readme.txt"): data = open("readme.txt") for each_line in data: if not each_line.find(":") == -1: try: # split: Immutable parameters (role, line_spoken) = each_line.split(":", 1) print role print line_spoken # focus your job's content except ValueError: pass data.close() else: print "The data file is missing !" # try/except/finally man = [] other = [] try: data = open("sketch.txt") for each_line in data: try: (role, line_spoken) = each_line.split(":", 1) line_spoken = line_spoken.strip() if role == "Man": man.append(line_spoken) elif role == 'Other Man': other.append(line_spoken) except ValueError as err: print "File error: " + str(err) pass # call locals() before call close() # locals() BIF finally: if 'data' in locals(): data.close() except IOError: print "The datafile is missing !" print man print other """with is equals try/except/finally, with use a kind of context management protocol python tech""" try: with open("its.txt", "w") as data: data.write("It's...") except IOError as err: print "File error: " + str(err) """||""" """||""" """||""" """with is equals try/except/finally, with use a kind of context management protocol python tech""" try: data = open("its.txt", "w") data.write("It's...") except IOError as err: print "File error: " + str(err) finally: if "data" in locals(): data.close() with open("man_data.txt", "w") as man_file, open("other_data.txt", "w") as other_file: # data in memory print man_file.readlines() # data in memory print other_file.readlines() # dump load; must use binary import pickle try: with open("mydata.pickle", "wb") as mysavedata: pickle.dump([1, 2, 'three'], mysavedata) with open("mydata.pickle", "rb") as myrestoredata: a_list = pickle.load(myrestoredata) print a_list except IOError as err: print "File error: " + str(err) except pickle.PickleError as pickle_err: print "Pickling error: " + str(pickle_perr) # In-place sorting print data.sort() # Copied sorting print sorted(data) def sanitize(time_string): if "-" in time_string: splitter = "-" elif ":" in time_string: splitter = ":" else: return time_string mins, secs = time_string.split(splitter) return mins + "." + secs # create convert iterate append clean_mikey = [sanitize(each_t) for each_t in mikey] print sorted(set([sanitize(each_t) for each_t in mikey]), reverse=True)[0:3] # pop def get_coach_data(filename): try: with open(filename) as f: data = f.readline() templ = data.strip().split(",") return { "name": templ.pop(0), "dob": templ.pop(0), "times": str(sorted(set(sanitize(t) for t in sarah_data["times"]))[0:3]) } except IOError as ioerr: print "File error: " + str(ioerr) return None # class class Athlete: def __init__(self, a_name, a_dob=None, a_times=[]): self.name = a_name self.dob = a_dob self.times = a_times def top3(self): return sorted(set([sanitize(t) for t in self.times]))[0:3] def add_time(self, time_value): self.times.append(time_value) def add_times(self, list_of_times): self.times.extend(list_of_times) sarah = Athlete("Sarah Sweeney", "2002-6-17", ["2:58", "2.58", "1.56"]) james = Athlete("James Jones") print str(sarah.top3()) print str(james.top3())
24.367713
99
0.602503
760
5,434
4.214474
0.290789
0.019669
0.021855
0.026538
0.198876
0.198876
0.186388
0.110521
0.093038
0.081174
0
0.013637
0.257821
5,434
222
100
24.477477
0.78056
0.110232
0
0.27972
0
0
0.113786
0
0
0
0
0
0
0
null
null
0.013986
0.013986
null
null
0.272727
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
695ec52440fba379a30f79fa614d663b2b26c725
110
py
Python
MiddleKit/Design/SQLitePythonGenerator.py
PeaceWorksTechnologySolutions/w4py
74f5a03a63f1a93563502b908474aefaae2abda2
[ "MIT" ]
18
2016-08-01T20:15:59.000Z
2019-12-24T16:00:03.000Z
MiddleKit/Design/SQLitePythonGenerator.py
WebwareForPython/w4py
bba08f5974d49f5da7e88abe3eeda1037d0824a3
[ "MIT" ]
6
2016-09-13T05:48:45.000Z
2020-01-09T18:29:12.000Z
MiddleKit/Design/SQLitePythonGenerator.py
WebwareForPython/w4py
bba08f5974d49f5da7e88abe3eeda1037d0824a3
[ "MIT" ]
6
2016-09-16T14:32:29.000Z
2020-01-03T18:52:16.000Z
from SQLPythonGenerator import SQLPythonGenerator class SQLitePythonGenerator(SQLPythonGenerator): pass
18.333333
49
0.854545
8
110
11.75
0.75
0
0
0
0
0
0
0
0
0
0
0
0.118182
110
5
50
22
0.969072
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0.333333
0.333333
0
0.666667
0
1
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
1
1
0
1
0
0
7
69606e8d600007b6ed1a1fe06f495e08cc77f964
994
py
Python
Spell Compendium/scr/Spell1108 - Dirge.py
Sagenlicht/ToEE_Mods
a4b07f300df6067f834e09fcbc4c788f1f4e417b
[ "MIT" ]
1
2021-04-26T08:03:56.000Z
2021-04-26T08:03:56.000Z
Spell Compendium/scr/Spell1108 - Dirge.py
Sagenlicht/ToEE_Mods
a4b07f300df6067f834e09fcbc4c788f1f4e417b
[ "MIT" ]
2
2021-06-11T05:55:01.000Z
2021-08-03T23:41:02.000Z
Spell Compendium/scr/Spell1108 - Dirge.py
Sagenlicht/ToEE_Mods
a4b07f300df6067f834e09fcbc4c788f1f4e417b
[ "MIT" ]
1
2021-05-17T15:37:58.000Z
2021-05-17T15:37:58.000Z
from toee import * def OnBeginSpellCast(spell): print "Dirge OnBeginSpellCast" print "spell.target_list=", spell.target_list print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level def OnSpellEffect(spell): print "Dirge OnSpellEffect" targetsToRemove = [] spell.duration = 1 * spell.caster_level # 1 round/cl #spellTarget = spell.target_list[0] for spellTarget in spell.target_list: targetsToRemove.append(spellTarget.obj) dirgeObject = game.obj_create(OBJECT_SPELL_GENERIC, spell.target_loc) casterInitiative = spell.caster.get_initiative() dirgeObject.d20_status_init() dirgeObject.set_initiative(casterInitiative) dirgeObject.condition_add_with_args('sp-Dirge', spell.id, spell.duration, spell.dc) spell.target_list.remove_list(targetsToRemove) #spell.spell_end(spell.id) def OnBeginRound(spell): print "Dirge OnBeginRound" def OnEndSpellCast(spell): print "Dirge OnEndSpellCast"
30.121212
87
0.740443
116
994
6.172414
0.413793
0.092179
0.104749
0
0
0
0
0
0
0
0
0.005995
0.160966
994
33
88
30.121212
0.852518
0.069417
0
0
0
0
0.144252
0
0
0
0
0
0
0
null
null
0
0.047619
null
null
0.285714
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
6961424e888d8e63d731e6c1e71ebfa8b2d27d7f
468
py
Python
OMIEData/Downloaders/marginal_price_downloader.py
acruzgarcia/OMIEData
e4f8d8b8d7b5a8351a65c32e86f1a798f968cc6c
[ "MIT" ]
9
2021-02-14T19:47:18.000Z
2022-03-25T14:03:04.000Z
OMIEData/Downloaders/marginal_price_downloader.py
acruzgarcia/OMIEData
e4f8d8b8d7b5a8351a65c32e86f1a798f968cc6c
[ "MIT" ]
2
2022-03-09T15:45:05.000Z
2022-03-25T11:02:46.000Z
OMIEData/Downloaders/marginal_price_downloader.py
acruzgarcia/OMIEData
e4f8d8b8d7b5a8351a65c32e86f1a798f968cc6c
[ "MIT" ]
null
null
null
from OMIEData.Downloaders.general_omie_downloader import GeneralOMIEDownloader class MarginalPriceDownloader(GeneralOMIEDownloader): url_year = 'AGNO_YYYY' url_month = '/MES_MM/TXT/' url_name = 'INT_PBC_EV_H_1_DD_MM_YYYY_DD_MM_YYYY.TXT' output_mask = 'PMD_YYYYMMDD.txt' def __init__(self): url1 = self.url_year + self.url_month + self.url_name GeneralOMIEDownloader.__init__(self, url_mask=url1, output_mask=self.output_mask)
29.25
89
0.762821
63
468
5.142857
0.52381
0.08642
0.049383
0
0
0
0
0
0
0
0
0.007576
0.153846
468
15
90
31.2
0.810606
0
0
0
0
0
0.164882
0.085653
0
0
0
0
0
1
0.111111
false
0
0.111111
0
0.777778
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
6962fbbf3e083926d0de2767052362c19acba0b1
5,556
py
Python
054-asong/code.py
Life4gal/adworld.xctf-REVERSE
5e552de6cf1f5fccdcba40d26ecf7060f5e782da
[ "MIT" ]
14
2020-09-01T03:43:48.000Z
2021-09-10T15:43:33.000Z
054-asong/code.py
Life4gal/adworld.xctf-REVERSE
5e552de6cf1f5fccdcba40d26ecf7060f5e782da
[ "MIT" ]
null
null
null
054-asong/code.py
Life4gal/adworld.xctf-REVERSE
5e552de6cf1f5fccdcba40d26ecf7060f5e782da
[ "MIT" ]
3
2021-03-04T12:22:46.000Z
2021-07-30T03:25:44.000Z
from struct import unpack from os.path import getsize # 第一步 读取 out 文件的 二进制 内容 def un_sub_400CC0() -> tuple: """ :return: 返回一个元祖,内容是从 out 文件中读取的内容 """ # 读取 out 文件 outFilePath = "./out" outLength = getsize(outFilePath) with open(outFilePath, 'rb') as outFile: # B = unsigned char return unpack(''.join(['B' * outLength]), outFile.read()) # 第二步 处理 out 的内容 def un_sub_400DB4(t: tuple) -> list: """ :param t: out 中读取的内容 :return: 返回一个列表,是 out 中内容对 sub_400DB4 函数的逆变换 """ # 按 byte 读取,所以 & 0xFF v3 = (t[-1] << 5 | t[0] >> 3) & 0xFF _list = [v3] for i in range(len(t) - 1): _list.append(((t[i] << 5) | t[i + 1] >> 3) & 0xFF) return _list # 第三步 读取 that_girl def un_sub_400AAA() -> dict: """ :return: 返回一个字典,内容为经过 sub_400936 函数变换后的 that_girl 的内容每个字符与其出现的次数 """ # sub_400936 对每个字符的处理 def sub_400936(char: str) -> int: """ :param char: 读取的字符 :return: 变换对应的整数 """ char = ord(char) result = char - 10 if char is 10: result = char + 35 # 10 -> 45 : '\n' -> '-' elif char is 32 or char is 33 or char is 34: # 其实只有 ' ' result = char + 10 # 32 33 34 -> 42 43 44 : ' ' or '!' or '"' -> '*' or '+' or ',' elif char is 39: result = char + 2 # 39 -> 41 : '\'' -> ')' # 经测试,下面这几个分支没用 # elif char is 44: # result = char - 4 # 44 -> 40 : ',' -> '(' # elif char is 46: # result = char - 7 # 46 -> 39 : '.' -> '\'' # elif char is 58 or char is 59: # 58 59 -> 37 38 : ':' or ';' -> '%' '&' # result = char - 21 # elif char is 63: # result = char - 27 # 63 -> 37 : '?' -> '%' elif char is 95: result = char - 49 # 95 -> 46 : '_' -> '.' else: if char <= 47 or char > 48: # not 48('0') if char <= 64 or char > 90: if 96 < char <= 122: result = char - 87 # a ~ z -> 10 ~ 35 else: result = char - 55 # [A ~ Z] -> 10 ~ 35 else: # 这个也是不存在的 result = char - 48 # '0' -> 0 return result songFilePath = "./that_girl" # 原来的操作是 ++*(_DWORD *)(4LL * v2 + ptr); 但其实它的指针类型是 __int64,而实际的数据类型为 byte,我们可以不需要乘这个4 # 经过测试命中区域处于 40 ~ 184 之间, (184 - 40) / 4 = 36 _list = [0] * 37 with open(songFilePath, "r") as song: for c in song.read(): v2 = sub_400936(c) _list[v2 - 10] += 1 """ 观察 sub_400936 函数我们不难发现其实就是一个映射关系 不分大小写 a~z(A~Z) 映射到 _list[0~25] 剩下的依次是 '\'' -> 31 ' ' -> 32 '\\n'' -> 35 '_' -> 36 其他的都是无效的 我们可以只返回有效的数据 """ ret = _list[:26] ret.append(_list[31]) ret.append(_list[32]) ret.append(_list[35]) ret.append(_list[36]) return dict(zip("abcdefghijklmnopqrstuvwxyz' \n_", ret)) # 第四步 获取flag def getFlag(_list: list, mapping: dict) -> str: """ :param _list: 这个列表带着处理后的 out 的内容 :param mapping: 这个字典带着 字符 与 出现次数 的映射 :return: """ def un_sub_400D33() -> None: """ 处理 getFlag 传进来的 _list """ # 直接用外面传进来的列表 nonlocal _list dword_6020A0 = [ 0x16, 0x00, 0x06, 0x02, 0x1e, 0x18, 0x09, 0x01, 0x15, 0x07, 0x12, 0x0a, 0x08, 0x0c, 0x11, 0x17, 0x0d, 0x04, 0x03, 0x0e, 0x13, 0x0b, 0x14, 0x10, 0x0f, 0x05, 0x19, 0x24, 0x1b, 0x1c, 0x1d, 0x25, 0x1f, 0x20, 0x21, 0x1a, 0x22, 0x23 ] """ dword_6020A0 = [ 22, 0, 6, 2, 30, 24, 9, 1, 21, 7, 18, 10, 8, 12, 17, 23, 13, 4, 3, 14, 19, 11, 20, 16, 15, 5, 25, 36, 27, 28, 29, 37, 31, 32, 33, 26, 34, 35 ] index -> dword_6020A0[index] 0 -> [22] = 20 20 -> [20] = 19 19 -> [19] = 14 14 -> [14] = 17 17 -> [17] = 4 4 -> [4] = 30 30 -> [30] = 29 29 -> [29] = 28 28 -> [28] = 27 27 -> [27] = 36 36 -> [36] = 34 34 -> [34] = 33 33 -> [33] = 32 32 -> [32] = 31 31 -> [31] = 37 37 -> [37] = 35 35 -> [35] = 26 26 -> [26] = 25 25 -> [25] = 5 5 -> [5] = 24 24 -> [24] = 15 15 -> [15] = 23 23 -> [23] = 16 16 -> [16] = 13 13 -> [13] = 12 12 -> [12] = 8 8 -> [8] = 21 21 -> [21] = 11 11 -> [11] = 10 10 -> [10] = 18 18 -> [18] = 3 3 -> [3] = 2 2 -> [2] = 6 6 -> [6] = 9 9 -> [9] = 7 7 -> [7] = 1 1 -> [1] = 0 没有重复,没有覆盖,可以还原 """ v2 = 37 while dword_6020A0.index(v2) is not 37: _list[v2] = _list[dword_6020A0.index(v2)] v2 = dword_6020A0.index(v2) un_sub_400D33() flag = [] mappingKey = list(mapping.keys()) mappingValue = list(mapping.values()) for i in _list: index = mappingValue.index(i) flag.append(mappingKey[index]) return f"QCTF{{{''.join(flag)}}}" print(getFlag(un_sub_400DB4(un_sub_400CC0()), un_sub_400AAA()))
28.639175
95
0.415767
670
5,556
3.365672
0.359701
0.053215
0.031042
0.023947
0.008869
0
0
0
0
0
0
0.203368
0.433585
5,556
193
96
28.787565
0.513187
0.194384
0
0.041096
0
0
0.027479
0.018567
0
0
0.059413
0
0
1
0.082192
false
0
0.027397
0
0.178082
0.013699
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
69652dfb803516a28321ac437986a8a9c6bc0aa9
1,345
py
Python
textblob.py
usmanhaider1995/TextBlob
d609fe58b1e581bc8055d61bbefc7d20ef5ce388
[ "BSD-3-Clause" ]
null
null
null
textblob.py
usmanhaider1995/TextBlob
d609fe58b1e581bc8055d61bbefc7d20ef5ce388
[ "BSD-3-Clause" ]
null
null
null
textblob.py
usmanhaider1995/TextBlob
d609fe58b1e581bc8055d61bbefc7d20ef5ce388
[ "BSD-3-Clause" ]
null
null
null
from textblob import TextBlob from textblob import Word import nltk nltk.download('punkt') nltk.download('wordnet') #getting correct sentences words = ['Machin','Learnin','corect'] corrected_words = [] for i in words: corrected_words.append(TextBlob(i)) print('worng words :', words) print('Corrected words :') for i in corrected_words: print(i.correct()) # Getting sentiment analysis test = TextBlob('Usman is a great machine learning developer and also have some cloud knowledge') print(test.sentiment) print('Polarity :',test.sentiment.polarity) # Add space before dot inorder to get in as a sentence token = TextBlob("Usman is a great machine learning. " "developer and also. " "have some cloud knowledge.") # printing seperate words and sentences print('Word :',token.words) print('Sentences', token.sentences) # Getting sentiments of those sentences print('Sentences sentiments ::') for i in token.sentences: print(i.sentiment) # Words singularization and pluralization sentence = TextBlob('we bought 5 tomatos from shop today') print(sentence.words[5].pluralize()) print(sentence.words[3].singularize()) #for i in sentence.words: # print(i) # correcting nouns word = Word('speling') print(word.correct()) zen =TextBlob('beautiful is better') print(zen.upper())
23.596491
97
0.719703
176
1,345
5.482955
0.409091
0.058031
0.02487
0.037306
0.194819
0.153368
0.153368
0.153368
0.153368
0.153368
0
0.002676
0.166543
1,345
56
98
24.017857
0.858162
0.203717
0
0
0
0
0.311848
0
0
0
0
0
0
1
0
false
0
0.096774
0
0.096774
0.419355
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
1
696b0fe7fb16a5ee74d9c65d62711192a825d49b
942
py
Python
loop_fix_sample_rate.py
Crystalwarrior/AO2-Scripts
acbabc64706374362bd93662d9ce1e2cf8eb35fb
[ "MIT" ]
1
2020-11-21T14:27:27.000Z
2020-11-21T14:27:27.000Z
loop_fix_sample_rate.py
Crystalwarrior/AO2-Scripts
acbabc64706374362bd93662d9ce1e2cf8eb35fb
[ "MIT" ]
null
null
null
loop_fix_sample_rate.py
Crystalwarrior/AO2-Scripts
acbabc64706374362bd93662d9ce1e2cf8eb35fb
[ "MIT" ]
1
2020-08-14T02:44:46.000Z
2020-08-14T02:44:46.000Z
import os from os import path old_sample_rate = float(input("What was the original sample rate? ")) new_sample_rate = float(input("What is the new sample rate? ")) for file in os.listdir(os.getcwd()): name = file.rsplit(".",1)[0] if file.rsplit(".",1)[-1] == "opus" and path.exists(name + ".opus.txt"): print('\n') print(name) f = open(name + ".opus.txt", "r") lines = f.readlines() f.close() new_lines = [] for line in lines: args = line.split('=') command = args[0].strip() samples = int(args[1].strip()) new_samples = int(samples * (new_sample_rate / old_sample_rate)) new_line = f'{command}={new_samples}' print(f'Converting {line.strip()} to {new_line.strip()}') new_lines.append(new_line) f = open(name + ".opus.txt", "w") f.write('\n'.join(new_lines)) f.close()
36.230769
76
0.549894
129
942
3.891473
0.387597
0.119522
0.077689
0.079681
0.159363
0
0
0
0
0
0
0.008837
0.279193
942
26
77
36.230769
0.730486
0
0
0.083333
0
0
0.184518
0.02439
0
0
0
0
0
1
0
false
0
0.083333
0
0.083333
0.125
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
696b8fef41b6b27dc44ddf7473367dc19aba29de
2,221
py
Python
reviewboard/extensions/templatetags/rb_extensions.py
Khan/reviewboard
51ec4261e67b8bf4e2cfa9a0894a97b16509ad33
[ "MIT" ]
1
2015-09-11T15:50:17.000Z
2015-09-11T15:50:17.000Z
reviewboard/extensions/templatetags/rb_extensions.py
Khan/reviewboard
51ec4261e67b8bf4e2cfa9a0894a97b16509ad33
[ "MIT" ]
null
null
null
reviewboard/extensions/templatetags/rb_extensions.py
Khan/reviewboard
51ec4261e67b8bf4e2cfa9a0894a97b16509ad33
[ "MIT" ]
null
null
null
from django import template from django.conf import settings from django.template.loader import render_to_string from djblets.util.decorators import basictag from reviewboard.extensions.hooks import DiffViewerActionHook, \ NavigationBarHook, \ ReviewRequestActionHook, \ ReviewRequestDropdownActionHook register = template.Library() def action_hooks(context, hookcls, action_key="action", template_name="extensions/action.html"): """Displays all registered action hooks from the specified ActionHook.""" s = "" for hook in hookcls.hooks: for actions in hook.get_actions(context): if actions: new_context = { action_key: actions } context.update(new_context) s += render_to_string(template_name, new_context) return s @register.tag @basictag(takes_context=True) def diffviewer_action_hooks(context): """Displays all registered action hooks for the diff viewer.""" return action_hooks(context, DiffViewerActionHook) @register.tag @basictag(takes_context=True) def review_request_action_hooks(context): """Displays all registered action hooks for review requests.""" return action_hooks(context, ReviewRequestActionHook) @register.tag @basictag(takes_context=True) def review_request_dropdown_action_hooks(context): """Displays all registered action hooks for review requests.""" return action_hooks(context, ReviewRequestDropdownActionHook, "actions", "extensions/action_dropdown.html") @register.tag @basictag(takes_context=True) def navigation_bar_hooks(context): """Displays all registered navigation bar entries.""" s = "" for hook in NavigationBarHook.hooks: for nav_info in hook.get_entries(context): if nav_info: context.push() context['entry'] = nav_info s += render_to_string("extensions/navbar_entry.html", context) context.pop() return s
30.847222
78
0.641603
225
2,221
6.16
0.288889
0.087302
0.090909
0.077922
0.344877
0.29798
0.29798
0.243146
0.243146
0.131313
0
0
0.281405
2,221
71
79
31.28169
0.868421
0.130122
0
0.25
0
0
0.051941
0.042497
0
0
0
0
0
1
0.104167
false
0
0.104167
0
0.3125
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
696c68c8ad6875cf4824c538720ffa0e9657eb27
8,671
py
Python
opengnn/models/model.py
CoderPat/OpenGNN
bc54328ad4aa034098073c72153eed361b4266ce
[ "MIT" ]
32
2019-01-28T13:38:21.000Z
2022-03-29T08:39:00.000Z
opengnn/models/model.py
CoderPat/OpenGNN
bc54328ad4aa034098073c72153eed361b4266ce
[ "MIT" ]
1
2020-01-16T03:09:18.000Z
2020-01-16T03:44:20.000Z
opengnn/models/model.py
CoderPat/OpenGNN
bc54328ad4aa034098073c72153eed361b4266ce
[ "MIT" ]
7
2019-03-07T14:13:15.000Z
2022-03-15T10:40:41.000Z
from abc import ABC, abstractmethod from typing import Dict, Any import tensorflow as tf import numpy as np from opengnn.utils.data import diverse_batch, batch_and_bucket_by_size from opengnn.utils.data import filter_examples_by_size, truncate_examples_by_size def optimize(loss: tf.Tensor, params: Dict[str, Any]): global_step = tf.train.get_or_create_global_step() optimizer = params.get('optimizer', 'Adam') if optimizer != 'Adam': optimizer_class = getattr(tf.train, optimizer, None) if optimizer_class is None: raise ValueError("Unsupported optimizer %s" % optimizer) optimizer_params = params.get("optimizer_params", {}) def optimizer(lr): return optimizer_class(lr, **optimizer_params) learning_rate = params['learning_rate'] if params.get('decay_rate') is not None: learning_rate = tf.train.exponential_decay( learning_rate, global_step, decay_steps=params.get('decay_steps', 1), decay_rate=params['decay_rate'], staircase=True) return tf.contrib.layers.optimize_loss( loss=loss, global_step=global_step, learning_rate=learning_rate, clip_gradients=params['clip_gradients'], summaries=[ "learning_rate", "global_gradient_norm", ], optimizer=optimizer, name="optimizer") class Model(ABC): def __init__(self, name: str, features_inputter=None, labels_inputter=None) -> None: self.name = name self.features_inputter = features_inputter self.labels_inputter = labels_inputter def model_fn(self): def _model_fn(features, labels, mode, params, config=None): if mode == tf.estimator.ModeKeys.TRAIN: with tf.variable_scope(self.name): # build models graph outputs, predictions = self.__call__( features, labels, mode, params, config) # compute loss, tb_loss and train_op loss, tb_loss = self.compute_loss( features, labels, outputs, params, mode) train_op = optimize(loss, params) return tf.estimator.EstimatorSpec( mode, loss=tb_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: with tf.variable_scope(self.name): # build models graph outputs, predictions = self.__call__( features, labels, mode, params, config) # compute loss, tb_loss and metric ops loss, tb_loss = self.compute_loss( features, labels, outputs, params, mode) metrics = self.compute_metrics( features, labels, predictions) # TODO: this assumes that the loss across validation can be # calculated as the average over the loss of the minibatch # which is not always the case (cross entropy averaged over time an batch) # but if minibatch a correctly shuffled, this is a good aproximation for now return tf.estimator.EstimatorSpec( mode, loss=tb_loss, eval_metric_ops=metrics) elif mode == tf.estimator.ModeKeys.PREDICT: with tf.variable_scope(self.name): # build models graph _, predictions = self.__call__( features, labels, mode, params, config) return tf.estimator.EstimatorSpec( mode, predictions=predictions) return _model_fn def input_fn(self, mode: tf.estimator.ModeKeys, batch_size: int, metadata, features_file, labels_file=None, sample_buffer_size=None, maximum_features_size=None, maximum_labels_size=None, features_bucket_width=None, labels_bucket_width=None, num_threads=None): assert not (mode != tf.estimator.ModeKeys.PREDICT and labels_file is None) # the function returned def _input_fn(): self.initialize(metadata) feat_dataset, feat_process_fn, feat_batch_fn, features_size_fn =\ self.get_features_builder(features_file, mode) if labels_file is not None: labels_dataset, labels_process_fn, \ labels_batch_fn, labels_size_fn = \ self.get_labels_builder(labels_file, mode) dataset = tf.data.Dataset.zip((feat_dataset, labels_dataset)) def process_fn(features, labels): return feat_process_fn(features), labels_process_fn(labels, features) def batch_fn(dataset, batch_size): return diverse_batch( dataset, batch_size, (feat_batch_fn, labels_batch_fn)) example_size_fns = [features_size_fn, labels_size_fn] bucket_widths = [features_bucket_width, labels_bucket_width] maximum_example_size = (maximum_features_size, maximum_labels_size) else: dataset = feat_dataset process_fn = feat_process_fn batch_fn = feat_batch_fn example_size_fns = features_size_fn bucket_widths = features_bucket_width maximum_example_size = maximum_features_size # shuffle, process batch and allow repetition # TODO: Fix derived seed (bug in tensorflow) seed = np.random.randint(np.iinfo(np.int64).max) if sample_buffer_size is not None: dataset = dataset.shuffle( sample_buffer_size, reshuffle_each_iteration=False, seed=seed) dataset = dataset.map(process_fn, num_parallel_calls=num_threads or 4) dataset = dataset.apply(filter_examples_by_size( example_size_fns=example_size_fns, maximum_example_sizes=maximum_example_size)) dataset = dataset.apply(batch_and_bucket_by_size( batch_size=batch_size, batch_fn=batch_fn, bucket_widths=bucket_widths, example_size_fns=example_size_fns)) if mode == tf.estimator.ModeKeys.TRAIN: dataset = dataset.repeat() return dataset.prefetch(None) return _input_fn def initialize(self, metadata): """ Runs model specific initialization (e.g. vocabularies loading). Args: metadata: A dictionary containing additional metadata set by the user. """ if self.features_inputter is not None: self.features_inputter.initialize(metadata) if self.labels_inputter is not None: self.labels_inputter.initialize(metadata) @abstractmethod def __call__(self, features, labels, mode, params, config=None): raise NotImplementedError() @abstractmethod def compute_loss(self, features, labels, outputs, params, mode): raise NotImplementedError() @abstractmethod def compute_metrics(self, features, labels, predictions): raise NotImplementedError() def get_features_builder(self, features_file, mode): if self.features_inputter is None: raise NotImplementedError() dataset = self.features_inputter.make_dataset(features_file, mode) process_fn = self.features_inputter.process batch_fn = self.features_inputter.batch size_fn = self.features_inputter.get_example_size return dataset, process_fn, batch_fn, size_fn def get_labels_builder(self, labels_file, mode): if self.labels_inputter is None: raise NotImplementedError() dataset = self.labels_inputter.make_dataset(labels_file, mode) process_fn = self.labels_inputter.process batch_fn = self.labels_inputter.batch size_fn = self.labels_inputter.get_example_size return dataset, process_fn, batch_fn, size_fn
39.958525
93
0.587937
913
8,671
5.297919
0.20701
0.018813
0.033078
0.02853
0.357039
0.237544
0.199504
0.167459
0.104817
0.095927
0
0.000705
0.345404
8,671
216
94
40.143519
0.85148
0.075539
0
0.170886
0
0
0.020282
0
0
0
0
0.00463
0.006329
1
0.094937
false
0
0.037975
0.018987
0.208861
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
696cdcbe00ab21ab20807832ccc7573329262037
894
py
Python
pyopendds/dev/itl2py/Output.py
jwillemsen/pyopendds
fd025416a02433dd42eeaf1ae449b6c1e19d177e
[ "MIT" ]
19
2020-03-10T22:23:00.000Z
2022-03-30T01:18:56.000Z
pyopendds/dev/itl2py/Output.py
jwillemsen/pyopendds
fd025416a02433dd42eeaf1ae449b6c1e19d177e
[ "MIT" ]
28
2020-02-15T18:07:08.000Z
2022-03-31T18:38:57.000Z
pyopendds/dev/itl2py/Output.py
jwillemsen/pyopendds
fd025416a02433dd42eeaf1ae449b6c1e19d177e
[ "MIT" ]
6
2021-04-29T07:39:11.000Z
2022-01-21T13:38:13.000Z
from pathlib import Path from .ast import NodeVisitor class Output(NodeVisitor): def __init__(self, context: dict, path: Path, templates: dict): self.context = context self.path = path self.templates = {} for filename, template in templates.items(): self.templates[path / filename] = context['jinja'].get_template(template) def write(self): if self.context['dry_run']: print('######################################## Create Dir', self.path) else: self.path.mkdir(exist_ok=True) for path, template in self.templates.items(): content = template.render(self.context) if self.context['dry_run']: print('======================================== Write file', path) print(content) else: path.write_text(content)
33.111111
85
0.530201
91
894
5.10989
0.406593
0.11828
0.055914
0.068817
0.103226
0.103226
0
0
0
0
0
0
0.282998
894
26
86
34.384615
0.725429
0
0
0.190476
0
0
0.135347
0.089485
0
0
0
0
0
1
0.095238
false
0
0.095238
0
0.238095
0.142857
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
696d1b5afd422299951b5f3ee0a8a3483cf6d75d
2,449
py
Python
ansible/plugins/connection/multi_passwd_ssh.py
shubav/sonic-mgmt
0ff71b907a55489bb4ed7d17b1682380fd459bf2
[ "Apache-2.0" ]
132
2016-10-19T12:34:44.000Z
2022-03-16T09:00:39.000Z
ansible/plugins/connection/multi_passwd_ssh.py
shubav/sonic-mgmt
0ff71b907a55489bb4ed7d17b1682380fd459bf2
[ "Apache-2.0" ]
3,152
2016-09-21T23:05:58.000Z
2022-03-31T23:29:08.000Z
ansible/plugins/connection/multi_passwd_ssh.py
shubav/sonic-mgmt
0ff71b907a55489bb4ed7d17b1682380fd459bf2
[ "Apache-2.0" ]
563
2016-09-20T01:00:15.000Z
2022-03-31T22:43:54.000Z
import imp import os from functools import wraps from ansible.errors import AnsibleAuthenticationFailure from ansible.plugins import connection # HACK: workaround to import the SSH connection plugin _ssh_mod = os.path.join(os.path.dirname(connection.__file__), "ssh.py") _ssh = imp.load_source("_ssh", _ssh_mod) # Use same options as the builtin Ansible SSH plugin DOCUMENTATION = _ssh.DOCUMENTATION # Add an option `ansible_ssh_altpassword` to represent an alternative password # to try if `ansible_ssh_password` is invalid DOCUMENTATION += """ altpassword: description: Alternative authentication password for the C(remote_user). Can be supplied as CLI option. vars: - name: ansible_altpassword - name: ansible_ssh_altpass - name: ansible_ssh_altpassword """.lstrip("\n") def _password_retry(func): """ Decorator to retry ssh/scp/sftp in the case of invalid password Will retry for password in (ansible_password, ansible_altpassword): """ @wraps(func) def wrapped(self, *args, **kwargs): password = self.get_option("password") or self._play_context.password conn_passwords = [password] altpassword = self.get_option("altpassword") if altpassword: conn_passwords.append(altpassword) while conn_passwords: conn_password = conn_passwords.pop(0) # temporarily replace `password` for this trial self.set_option("password", conn_password) self._play_context.password = conn_password try: return func(self, *args, **kwargs) except AnsibleAuthenticationFailure: # if there is no more altpassword to try, raise if not conn_passwords: raise finally: # reset `password` to its original state self.set_option("password", password) self._play_context.password = password # retry here, need create a new pipe for sshpass self.sshpass_pipe = os.pipe() return wrapped class Connection(_ssh.Connection): @_password_retry def _run(self, *args, **kwargs): return super(Connection, self)._run(*args, **kwargs) @_password_retry def _file_transport_command(self, *args, **kwargs): return super(Connection, self)._file_transport_command(*args, **kwargs)
34.985714
113
0.660269
281
2,449
5.548043
0.391459
0.038486
0.03592
0.044259
0.109686
0.050032
0.050032
0
0
0
0
0.000551
0.258473
2,449
69
114
35.492754
0.85793
0.218865
0
0.044444
0
0
0.173383
0.012195
0
0
0
0
0
1
0.088889
false
0.466667
0.111111
0.044444
0.311111
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
696db1e4a92f0d0e222cee7bcee91e0fd0798929
218
py
Python
tests/helpers.py
shanedabes/sputils
396fda1932e2a1ae4a602e9d2bc8238f0f6fecd9
[ "Apache-2.0" ]
1
2019-05-29T23:49:38.000Z
2019-05-29T23:49:38.000Z
tests/helpers.py
shanedabes/sputils
396fda1932e2a1ae4a602e9d2bc8238f0f6fecd9
[ "Apache-2.0" ]
33
2019-06-04T15:14:10.000Z
2021-11-15T17:48:40.000Z
tests/helpers.py
shanedabes/sputils
396fda1932e2a1ae4a602e9d2bc8238f0f6fecd9
[ "Apache-2.0" ]
null
null
null
import os import json def rel_fn(fn): dir_name = os.path.dirname(os.path.realpath(__file__)) return os.path.join(dir_name, fn) def mock_json(fn): with open(rel_fn(fn)) as f: return json.load(f)
16.769231
58
0.669725
39
218
3.512821
0.512821
0.131387
0.10219
0
0
0
0
0
0
0
0
0
0.201835
218
12
59
18.166667
0.787356
0
0
0
0
0
0
0
0
0
0
0
0
1
0.25
false
0
0.25
0
0.75
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
696f6073b8eafcb697b67113138ad0cec4dabea2
3,423
py
Python
Lab7/Q3.py
fancent/PHY407
38ce8badb9537060becc255ec64e6de2968ca73c
[ "MIT" ]
1
2020-12-20T17:30:06.000Z
2020-12-20T17:30:06.000Z
Lab7/Q3.py
fancent/PHY407
38ce8badb9537060becc255ec64e6de2968ca73c
[ "MIT" ]
null
null
null
Lab7/Q3.py
fancent/PHY407
38ce8badb9537060becc255ec64e6de2968ca73c
[ "MIT" ]
1
2021-06-12T14:21:13.000Z
2021-06-12T14:21:13.000Z
""" This file aims to simulate the Belousov–Zhabotinsky reaction, is a chemical mixture which, when heated, undergoes a series of reactions that cause the chemical concentrations in the mixture to oscillate between two extremes (x, y). """ import numpy as np import matplotlib.pyplot as plt ## Constants a = 1 b = 3 x0 = 0 # x concentration level (M) y0 = 0 # y concentration level (M) targetAcc = 10 ** -10 # target accuracy for BS method start = 0 # start time (s) end = 20 # end time (s) def f(r): """ This function calculates the equations for the BZ reaction """ x = r[0] y = r[1] dxdt = 1 - ((b + 1) * x) + (a * (x ** 2) * y) dydt = (b * x) - (a * (x ** 2) * y) return np.array([dxdt, dydt], float) def midpoint(r, n, H): """ This function calculates the modified mid-point method given in the textbook """ r2 = np.copy(r) h = H / n r1 = r + 0.5 * h * f(r) r2 += h * f(r1) for _ in range(n - 1): r1 += h * f(r2) r2 += h * f(r1) return 0.5 * (r1 + r2 + 0.5 * h * f(r2)) def BZ_reaction(): """ This function simulates the entire Belousov–Zhabotinsky reaction from start time to end time with the given constants at the beginning of the file using the Bulirsch–Stoer method with recursion instead of a while loop. """ r = np.array([x0, y0], float) tpoints = [start] xpoints = [r[0]] ypoints = [r[1]] def BS(r, t, H): """ This function is just a shell for the following recursive function if n, the number of recursive calls, exceeds 8. Then we will redo the calculation with a smaller H. """ def BS_row(R1, n): """ This function calculates the row of extrapolation estimates. Then it calculates the error and check if it falls under our desired accuracy. If not, it will recurse on itself with a larger n. If yes, then it will update the list of variables. """ if n > 8: r1 = BS(r, t, H / 2) return BS(r1, t + H / 2, H / 2) else: R2 = [midpoint(r, n, H)] for m in range(1, n): R2.append(R2[m - 1] + (R2[m - 1] - R1[m - 1]) / ((n / (n - 1)) ** (2 * (m)) - 1)) R2 = np.array(R2, float) error_vector = (R2[n - 2] - R1[n - 2]) / ((n / (n - 1)) ** (2 * (n - 1)) - 1) error = np.sqrt(error_vector[0] ** 2 + error_vector[1] ** 2) target_accuracy = H * targetAcc if error < target_accuracy: tpoints.append(t + H) xpoints.append(R2[n - 1][0]) ypoints.append(R2[n - 1][1]) return R2[n - 1] else: return BS_row(R2, n + 1) return BS_row(np.array([midpoint(r, 1, H)], float), 2) BS(r, start, end - start) return tpoints, xpoints, ypoints #plotting our results t, x, y = BZ_reaction() fig, graph = plt.subplots() graph.plot(t, x, 'r', label="x") graph.plot(t, y, 'b', label="y") graph.plot(t, x, 'r.') graph.plot(t, y, 'b.') graph.set(xlabel='time (s)', ylabel='concentration level (M)', title='Belousov–Zhabotinsky concentration level over time') graph.grid() graph.legend() fig.savefig("q3.png") plt.show()
31.990654
101
0.532282
512
3,423
3.544922
0.3125
0.008815
0.008815
0.041322
0.031956
0
0
0
0
0
0
0.038698
0.33567
3,423
107
102
31.990654
0.757696
0.334502
0
0.0625
0
0
0.045564
0
0
0
0
0
0
1
0.078125
false
0
0.03125
0
0.21875
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
69708664ff337e44ffae2d3817c35e032d51bec6
2,747
py
Python
tests/solr_tests/tests/management_commands.py
kmgroup/django-haystack-1.2.x-for-d1.8
b9368f169eec06e78131e81d6968cc6580d6ddee
[ "BSD-3-Clause" ]
1
2016-02-24T19:40:05.000Z
2016-02-24T19:40:05.000Z
tests/solr_tests/tests/management_commands.py
kmgroup/django-haystack-1.2.x-for-d1.8
b9368f169eec06e78131e81d6968cc6580d6ddee
[ "BSD-3-Clause" ]
null
null
null
tests/solr_tests/tests/management_commands.py
kmgroup/django-haystack-1.2.x-for-d1.8
b9368f169eec06e78131e81d6968cc6580d6ddee
[ "BSD-3-Clause" ]
null
null
null
import pysolr from django.conf import settings from django.core.management import call_command from django.test import TestCase from haystack import indexes from haystack.sites import SearchSite from core.models import MockModel class SolrMockSearchIndex(indexes.SearchIndex): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr='author', faceted=True) pub_date = indexes.DateField(model_attr='pub_date') class ManagementCommandTestCase(TestCase): fixtures = ['bulk_data.json'] def setUp(self): super(ManagementCommandTestCase, self).setUp() self.solr = pysolr.Solr(settings.HAYSTACK_SOLR_URL) self.site = SearchSite() self.site.register(MockModel, SolrMockSearchIndex) # Stow. import haystack self.old_site = haystack.site haystack.site = self.site def tearDown(self): import haystack haystack.site = self.old_site super(ManagementCommandTestCase, self).tearDown() def test_basic_commands(self): call_command('clear_index', interactive=False, verbosity=0) self.assertEqual(self.solr.search('*:*').hits, 0) call_command('update_index', verbosity=0) self.assertEqual(self.solr.search('*:*').hits, 23) call_command('clear_index', interactive=False, verbosity=0) self.assertEqual(self.solr.search('*:*').hits, 0) call_command('rebuild_index', interactive=False, verbosity=0) self.assertEqual(self.solr.search('*:*').hits, 23) def test_remove(self): call_command('clear_index', interactive=False, verbosity=0) self.assertEqual(self.solr.search('*:*').hits, 0) call_command('update_index', verbosity=0) self.assertEqual(self.solr.search('*:*').hits, 23) # Remove a model instance. MockModel.objects.get(pk=1).delete() self.assertEqual(self.solr.search('*:*').hits, 23) # Plain ``update_index`` doesn't fix it. call_command('update_index', verbosity=0) self.assertEqual(self.solr.search('*:*').hits, 23) # With the remove flag, it's gone. call_command('update_index', remove=True, verbosity=0) self.assertEqual(self.solr.search('*:*').hits, 22) def test_multiprocessing(self): call_command('clear_index', interactive=False, verbosity=0) self.assertEqual(self.solr.search('*:*').hits, 0) # Watch the output, make sure there are multiple pids. call_command('update_index', verbosity=2, workers=2, batchsize=5) self.assertEqual(self.solr.search('*:*').hits, 23)
36.626667
73
0.650528
316
2,747
5.541139
0.306962
0.054826
0.11936
0.144489
0.432895
0.415191
0.415191
0.375214
0.350657
0.349515
0
0.014513
0.222424
2,747
74
74
37.121622
0.805243
0.056425
0
0.38
0
0
0.068832
0
0
0
0
0
0.22
1
0.1
false
0
0.18
0
0.4
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
6971294bf9fe140162bcbb44e819402a23fefea8
15,633
py
Python
cons3rt/models/user.py
cons3rt/cons3rt-python-sdk
f0bcb295735ac55bbe47448fcbd95d2c7beb3ec0
[ "RSA-MD" ]
null
null
null
cons3rt/models/user.py
cons3rt/cons3rt-python-sdk
f0bcb295735ac55bbe47448fcbd95d2c7beb3ec0
[ "RSA-MD" ]
null
null
null
cons3rt/models/user.py
cons3rt/cons3rt-python-sdk
f0bcb295735ac55bbe47448fcbd95d2c7beb3ec0
[ "RSA-MD" ]
null
null
null
""" Copyright 2020 Jackpine Technologies Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # coding: utf-8 """ cons3rt - Copyright Jackpine Technologies Corp. NOTE: This file is auto-generated. Do not edit the file manually. """ import pprint import re # noqa: F401 import six from cons3rt.configuration import Configuration __author__ = 'Jackpine Technologies Corporation' __copyright__ = 'Copyright 2020, Jackpine Technologies Corporation' __license__ = 'Apache 2.0', __version__ = '1.0.0' __maintainer__ = 'API Support' __email__ = 'support@cons3rt.com' class User(object): """NOTE: This class is auto-generated. Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'created_at': 'int', 'updated_at': 'int', 'administered_clouds': 'list[Cloud]', 'administered_virt_realms': 'list[VirtualizationRealm]', 'certificates': 'list[Certificate]', 'comment': 'str', 'default_project': 'Project', 'email': 'str', 'firstname': 'str', 'id': 'int', 'lastname': 'str', 'log_entries': 'list[LogEntry]', 'organization': 'str', 'project_count': 'int', 'state': 'str', 'terms_of_service_accepted': 'bool', 'username': 'str' } attribute_map = { 'created_at': 'createdAt', 'updated_at': 'updatedAt', 'administered_clouds': 'administeredClouds', 'administered_virt_realms': 'administeredVirtRealms', 'certificates': 'certificates', 'comment': 'comment', 'default_project': 'defaultProject', 'email': 'email', 'firstname': 'firstname', 'id': 'id', 'lastname': 'lastname', 'log_entries': 'logEntries', 'organization': 'organization', 'project_count': 'projectCount', 'state': 'state', 'terms_of_service_accepted': 'termsOfServiceAccepted', 'username': 'username' } def __init__(self, created_at=None, updated_at=None, administered_clouds=None, administered_virt_realms=None, certificates=None, comment=None, default_project=None, email=None, firstname=None, id=None, lastname=None, log_entries=None, organization=None, project_count=None, state=None, terms_of_service_accepted=None, username=None, local_vars_configuration=None): # noqa: E501 """User - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._created_at = None self._updated_at = None self._administered_clouds = None self._administered_virt_realms = None self._certificates = None self._comment = None self._default_project = None self._email = None self._firstname = None self._id = None self._lastname = None self._log_entries = None self._organization = None self._project_count = None self._state = None self._terms_of_service_accepted = None self._username = None self.discriminator = None if created_at is not None: self.created_at = created_at if updated_at is not None: self.updated_at = updated_at if administered_clouds is not None: self.administered_clouds = administered_clouds if administered_virt_realms is not None: self.administered_virt_realms = administered_virt_realms if certificates is not None: self.certificates = certificates if comment is not None: self.comment = comment if default_project is not None: self.default_project = default_project if email is not None: self.email = email if firstname is not None: self.firstname = firstname if id is not None: self.id = id if lastname is not None: self.lastname = lastname if log_entries is not None: self.log_entries = log_entries if organization is not None: self.organization = organization if project_count is not None: self.project_count = project_count if state is not None: self.state = state if terms_of_service_accepted is not None: self.terms_of_service_accepted = terms_of_service_accepted if username is not None: self.username = username @property def created_at(self): """Gets the created_at of this User. # noqa: E501 :return: The created_at of this User. # noqa: E501 :rtype: int """ return self._created_at @created_at.setter def created_at(self, created_at): """Sets the created_at of this User. :param created_at: The created_at of this User. # noqa: E501 :type: int """ self._created_at = created_at @property def updated_at(self): """Gets the updated_at of this User. # noqa: E501 :return: The updated_at of this User. # noqa: E501 :rtype: int """ return self._updated_at @updated_at.setter def updated_at(self, updated_at): """Sets the updated_at of this User. :param updated_at: The updated_at of this User. # noqa: E501 :type: int """ self._updated_at = updated_at @property def administered_clouds(self): """Gets the administered_clouds of this User. # noqa: E501 :return: The administered_clouds of this User. # noqa: E501 :rtype: list[Cloud] """ return self._administered_clouds @administered_clouds.setter def administered_clouds(self, administered_clouds): """Sets the administered_clouds of this User. :param administered_clouds: The administered_clouds of this User. # noqa: E501 :type: list[Cloud] """ self._administered_clouds = administered_clouds @property def administered_virt_realms(self): """Gets the administered_virt_realms of this User. # noqa: E501 :return: The administered_virt_realms of this User. # noqa: E501 :rtype: list[VirtualizationRealm] """ return self._administered_virt_realms @administered_virt_realms.setter def administered_virt_realms(self, administered_virt_realms): """Sets the administered_virt_realms of this User. :param administered_virt_realms: The administered_virt_realms of this User. # noqa: E501 :type: list[VirtualizationRealm] """ self._administered_virt_realms = administered_virt_realms @property def certificates(self): """Gets the certificates of this User. # noqa: E501 :return: The certificates of this User. # noqa: E501 :rtype: list[Certificate] """ return self._certificates @certificates.setter def certificates(self, certificates): """Sets the certificates of this User. :param certificates: The certificates of this User. # noqa: E501 :type: list[Certificate] """ self._certificates = certificates @property def comment(self): """Gets the comment of this User. # noqa: E501 :return: The comment of this User. # noqa: E501 :rtype: str """ return self._comment @comment.setter def comment(self, comment): """Sets the comment of this User. :param comment: The comment of this User. # noqa: E501 :type: str """ self._comment = comment @property def default_project(self): """Gets the default_project of this User. # noqa: E501 :return: The default_project of this User. # noqa: E501 :rtype: Project """ return self._default_project @default_project.setter def default_project(self, default_project): """Sets the default_project of this User. :param default_project: The default_project of this User. # noqa: E501 :type: Project """ self._default_project = default_project @property def email(self): """Gets the email of this User. # noqa: E501 :return: The email of this User. # noqa: E501 :rtype: str """ return self._email @email.setter def email(self, email): """Sets the email of this User. :param email: The email of this User. # noqa: E501 :type: str """ self._email = email @property def firstname(self): """Gets the firstname of this User. # noqa: E501 :return: The firstname of this User. # noqa: E501 :rtype: str """ return self._firstname @firstname.setter def firstname(self, firstname): """Sets the firstname of this User. :param firstname: The firstname of this User. # noqa: E501 :type: str """ self._firstname = firstname @property def id(self): """Gets the id of this User. # noqa: E501 :return: The id of this User. # noqa: E501 :rtype: int """ return self._id @id.setter def id(self, id): """Sets the id of this User. :param id: The id of this User. # noqa: E501 :type: int """ self._id = id @property def lastname(self): """Gets the lastname of this User. # noqa: E501 :return: The lastname of this User. # noqa: E501 :rtype: str """ return self._lastname @lastname.setter def lastname(self, lastname): """Sets the lastname of this User. :param lastname: The lastname of this User. # noqa: E501 :type: str """ self._lastname = lastname @property def log_entries(self): """Gets the log_entries of this User. # noqa: E501 :return: The log_entries of this User. # noqa: E501 :rtype: list[LogEntry] """ return self._log_entries @log_entries.setter def log_entries(self, log_entries): """Sets the log_entries of this User. :param log_entries: The log_entries of this User. # noqa: E501 :type: list[LogEntry] """ self._log_entries = log_entries @property def organization(self): """Gets the organization of this User. # noqa: E501 :return: The organization of this User. # noqa: E501 :rtype: str """ return self._organization @organization.setter def organization(self, organization): """Sets the organization of this User. :param organization: The organization of this User. # noqa: E501 :type: str """ self._organization = organization @property def project_count(self): """Gets the project_count of this User. # noqa: E501 :return: The project_count of this User. # noqa: E501 :rtype: int """ return self._project_count @project_count.setter def project_count(self, project_count): """Sets the project_count of this User. :param project_count: The project_count of this User. # noqa: E501 :type: int """ self._project_count = project_count @property def state(self): """Gets the state of this User. # noqa: E501 :return: The state of this User. # noqa: E501 :rtype: str """ return self._state @state.setter def state(self, state): """Sets the state of this User. :param state: The state of this User. # noqa: E501 :type: str """ allowed_values = ["REQUESTED", "ACTIVE", "INACTIVE"] # noqa: E501 if self.local_vars_configuration.client_side_validation and state not in allowed_values: # noqa: E501 raise ValueError( "Invalid value for `state` ({0}), must be one of {1}" # noqa: E501 .format(state, allowed_values) ) self._state = state @property def terms_of_service_accepted(self): """Gets the terms_of_service_accepted of this User. # noqa: E501 :return: The terms_of_service_accepted of this User. # noqa: E501 :rtype: bool """ return self._terms_of_service_accepted @terms_of_service_accepted.setter def terms_of_service_accepted(self, terms_of_service_accepted): """Sets the terms_of_service_accepted of this User. :param terms_of_service_accepted: The terms_of_service_accepted of this User. # noqa: E501 :type: bool """ self._terms_of_service_accepted = terms_of_service_accepted @property def username(self): """Gets the username of this User. # noqa: E501 :return: The username of this User. # noqa: E501 :rtype: str """ return self._username @username.setter def username(self, username): """Sets the username of this User. :param username: The username of this User. # noqa: E501 :type: str """ self._username = username def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, User): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, User): return True return self.to_dict() != other.to_dict()
27.966011
382
0.602827
1,820
15,633
4.992857
0.112088
0.044899
0.074832
0.078574
0.443381
0.335864
0.307252
0.195994
0.103444
0.030923
0
0.018182
0.306915
15,633
558
383
28.016129
0.820489
0.319197
0
0.085714
0
0
0.09905
0.018237
0
0
0
0
0
1
0.163265
false
0
0.016327
0
0.289796
0.008163
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
69716928cf6a5af476069ffd69aec9842674f683
1,703
py
Python
Topics/6_Compute/files/lambda_keepsecret.py
nsvijay04b1/AWS_Certified_Solutions_Architect_Professional
f141b9a64b652ffa9496ff47d527e7eaf4df006d
[ "Apache-2.0" ]
1
2022-03-10T18:38:54.000Z
2022-03-10T18:38:54.000Z
Topics/6_Compute/files/lambda_keepsecret.py
nsvijay04b1/AWS_Certified_Solutions_Architect_Professional
f141b9a64b652ffa9496ff47d527e7eaf4df006d
[ "Apache-2.0" ]
null
null
null
Topics/6_Compute/files/lambda_keepsecret.py
nsvijay04b1/AWS_Certified_Solutions_Architect_Professional
f141b9a64b652ffa9496ff47d527e7eaf4df006d
[ "Apache-2.0" ]
1
2022-03-10T18:38:56.000Z
2022-03-10T18:38:56.000Z
from __future__ import print_function import json import boto3 print('Loading function') s3 = boto3.client('s3') bucket_of_interest = "secretcatpics" # For a PutObjectAcl API Event, gets the bucket and key name from the event # If the object is not private, then it makes the object private by making a # PutObjectAcl call. def lambda_handler(event, context): # Get bucket name from the event bucket = event['Records'][0]['s3']['bucket']['name'] if (bucket != bucket_of_interest): print("Doing nothing for bucket = " + bucket) return # Get key name from the event key = event['Records'][0]['s3']['object']['key'] # If object is not private then make it private if not (is_private(bucket, key)): print("Object with key=" + key + " in bucket=" + bucket + " is not private!") make_private(bucket, key) else: print("Object with key=" + key + " in bucket=" + bucket + " is already private.") # Checks an object with given bucket and key is private def is_private(bucket, key): # Get the object ACL from S3 acl = s3.get_object_acl(Bucket=bucket, Key=key) # Private object should have only one grant which is the owner of the object if (len(acl['Grants']) > 1): return False # If canonical owner and grantee ids do no match, then conclude that the object # is not private owner_id = acl['Owner']['ID'] grantee_id = acl['Grants'][0]['Grantee']['ID'] if (owner_id != grantee_id): return False return True # Makes an object with given bucket and key private by calling the PutObjectAcl API. def make_private(bucket, key): s3.put_object_acl(Bucket=bucket, Key=key, ACL="private") print("Object with key=" + key + " in bucket=" + bucket + " is marked as private.")
32.132075
84
0.704052
266
1,703
4.424812
0.296992
0.071368
0.040782
0.040782
0.279524
0.189465
0.143585
0.094308
0.094308
0
0
0.009279
0.177334
1,703
52
85
32.75
0.830835
0.354668
0
0.068966
0
0
0.247698
0
0
0
0
0
0
1
0.103448
false
0
0.103448
0
0.344828
0.206897
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15c48e2d345be8eb45daabb4d97935eaab12b990
17,156
py
Python
tests/commons/big_query/copy_job_async/copy_job/test_copy_job_service.py
Morgenz/bbq
f0fd3f626841c610aee80ad08a61123b7cccb775
[ "Apache-2.0" ]
41
2018-05-08T11:54:37.000Z
2022-02-09T21:19:17.000Z
tests/commons/big_query/copy_job_async/copy_job/test_copy_job_service.py
Morgenz/bbq
f0fd3f626841c610aee80ad08a61123b7cccb775
[ "Apache-2.0" ]
139
2018-06-07T13:45:21.000Z
2021-04-30T20:44:06.000Z
tests/commons/big_query/copy_job_async/copy_job/test_copy_job_service.py
Morgenz/bbq
f0fd3f626841c610aee80ad08a61123b7cccb775
[ "Apache-2.0" ]
5
2019-09-11T12:28:24.000Z
2022-02-04T21:38:29.000Z
import unittest from apiclient.errors import HttpError from google.appengine.ext import testbed, ndb from mock import patch, Mock from src.commons.big_query.copy_job_async.copy_job.copy_job_request \ import CopyJobRequest from src.commons.big_query.copy_job_async.copy_job.copy_job_service \ import CopyJobService from src.commons.big_query.copy_job_async.post_copy_action_request import \ PostCopyActionRequest from src.commons.big_query.copy_job_async.result_check.result_check_request \ import ResultCheckRequest from src.commons.big_query.copy_job_async.task_creator import TaskCreator from src.commons.big_query.big_query import BigQuery from src.commons.big_query.big_query_job_reference import BigQueryJobReference from src.commons.big_query.big_query_table import BigQueryTable class TestCopyJobService(unittest.TestCase): def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() ndb.get_context().clear_cache() patch('googleapiclient.discovery.build').start() patch( 'oauth2client.client.GoogleCredentials.get_application_default') \ .start() self._create_http = patch.object(BigQuery, '_create_http').start() self.example_source_bq_table = BigQueryTable('source_project_id_1', 'source_dataset_id_1', 'source_table_id_1') self.example_target_bq_table = BigQueryTable('target_project_id_1', 'target_dataset_id_1', 'target_table_id_1') def tearDown(self): patch.stopall() self.testbed.deactivate() @patch.object(BigQuery, 'insert_job', return_value=BigQueryJobReference( project_id='test_project', job_id='job123', location='EU')) @patch.object(TaskCreator, 'create_copy_job_result_check') def test_that_post_copy_action_request_is_passed( self, create_copy_job_result_check, _): # given post_copy_action_request = \ PostCopyActionRequest(url='/my/url', data={'key1': 'value1'}) # when CopyJobService().run_copy_job_request( CopyJobRequest( task_name_suffix='task_name_suffix', copy_job_type_id='test-process', source_big_query_table=self.example_source_bq_table, target_big_query_table=self.example_target_bq_table, create_disposition="CREATE_IF_NEEDED", write_disposition="WRITE_EMPTY", retry_count=0, post_copy_action_request=post_copy_action_request ) ) # then create_copy_job_result_check.assert_called_once_with( ResultCheckRequest( task_name_suffix='task_name_suffix', copy_job_type_id='test-process', job_reference=BigQueryJobReference( project_id='test_project', job_id='job123', location='EU'), retry_count=0, post_copy_action_request=post_copy_action_request ) ) @patch.object(BigQuery, 'insert_job', return_value=BigQueryJobReference( project_id='test_project', job_id='job123', location='EU')) @patch.object(TaskCreator, 'create_copy_job_result_check') def test_that_create_and_write_disposition_are_passed_to_result_check( self, create_copy_job_result_check, _): # given create_disposition = "SOME_CREATE_DISPOSITION" write_disposition = "SOME_WRITE_DISPOSITION" # when CopyJobService().run_copy_job_request( CopyJobRequest( task_name_suffix='task_name_suffix', copy_job_type_id='test-process', source_big_query_table=self.example_source_bq_table, target_big_query_table=self.example_target_bq_table, create_disposition=create_disposition, write_disposition=write_disposition, retry_count=0, post_copy_action_request=None ) ) # then create_copy_job_result_check.assert_called_once_with( ResultCheckRequest( task_name_suffix='task_name_suffix', copy_job_type_id='test-process', job_reference=BigQueryJobReference( project_id='test_project', job_id='job123', location='EU'), retry_count=0, post_copy_action_request=None ) ) @patch.object(BigQuery, 'insert_job') @patch('time.sleep', side_effect=lambda _: None) def test_that_copy_table_should_throw_error_after_exception_not_being_http_error_thrown_on_copy_job_creation( self, _, insert_job): # given error_message = 'test exception' insert_job.side_effect = Exception(error_message) request = CopyJobRequest( task_name_suffix=None, copy_job_type_id=None, source_big_query_table=self.example_source_bq_table, target_big_query_table=self.example_target_bq_table, create_disposition="CREATE_IF_NEEDED", write_disposition="WRITE_EMPTY" ) # when with self.assertRaises(Exception) as context: CopyJobService().run_copy_job_request(request) # then self.assertTrue(error_message in context.exception) @patch.object(BigQuery, 'insert_job') @patch('time.sleep', side_effect=lambda _: None) def test_that_copy_table_should_throw_unhandled_errors(self, _, insert_job): # given exception = HttpError(Mock(status=500), 'internal error') exception._get_reason = Mock(return_value='internal error') insert_job.side_effect = exception request = CopyJobRequest( task_name_suffix=None, copy_job_type_id=None, source_big_query_table=self.example_source_bq_table, target_big_query_table=self.example_target_bq_table, create_disposition="CREATE_IF_NEEDED", write_disposition="WRITE_EMPTY" ) # when with self.assertRaises(HttpError) as context: CopyJobService().run_copy_job_request(request) # then self.assertEqual(context.exception, exception) @patch.object(BigQuery, 'insert_job') @patch.object(TaskCreator, 'create_post_copy_action') def test_that_copy_table_should_create_correct_post_copy_action_if_404_http_error_thrown_on_copy_job_creation( self, create_post_copy_action, insert_job): # given error = HttpError(Mock(status=404), 'not found') error._get_reason = Mock(return_value='not found') insert_job.side_effect = error post_copy_action_request = PostCopyActionRequest(url='/my/url', data={'key1': 'value1'}) request = CopyJobRequest( task_name_suffix='task_name_suffix', copy_job_type_id='test-process', source_big_query_table=self.example_source_bq_table, target_big_query_table=self.example_target_bq_table, create_disposition="CREATE_IF_NEEDED", write_disposition="WRITE_EMPTY", retry_count=0, post_copy_action_request=post_copy_action_request ) # when CopyJobService().run_copy_job_request(request) # then create_post_copy_action.assert_called_once_with( copy_job_type_id='test-process', post_copy_action_request=post_copy_action_request, job_json={ 'status': { 'state': 'DONE', 'errors': [ { 'reason': 'Invalid', 'message': ( "404 while creating Copy Job from {} to {}".format( self.example_source_bq_table, self.example_target_bq_table)) } ] }, 'configuration': { 'copy': { 'sourceTable': { 'projectId': self.example_source_bq_table.get_project_id(), 'tableId': self.example_source_bq_table.get_table_id(), 'datasetId': self.example_source_bq_table.get_dataset_id() }, 'destinationTable': { 'projectId': self.example_target_bq_table.get_project_id(), 'tableId': self.example_target_bq_table.get_table_id(), 'datasetId': self.example_target_bq_table.get_dataset_id() } } } } ) @patch.object(BigQuery, 'insert_job') @patch.object(TaskCreator, 'create_post_copy_action') def test_that_copy_table_should_create_correct_post_copy_action_if_access_denied_http_error_thrown_on_copy_job_creation( self, create_post_copy_action, insert_job): # given http_error_content = "{\"error\": " \ " {\"errors\": [" \ " {\"reason\": \"Access Denied\"," \ " \"message\": \"Access Denied\"," \ " \"location\": \"US\"" \ " }]," \ " \"code\": 403," \ " \"message\": \"Access Denied\"}}" insert_job.side_effect = HttpError(Mock(status=403), http_error_content) post_copy_action_request = PostCopyActionRequest(url='/my/url', data={ 'key1': 'value1'}) request = CopyJobRequest( task_name_suffix='task_name_suffix', copy_job_type_id='test-process', source_big_query_table=self.example_source_bq_table, target_big_query_table=self.example_target_bq_table, create_disposition="CREATE_IF_NEEDED", write_disposition="WRITE_EMPTY", retry_count=0, post_copy_action_request=post_copy_action_request ) # when CopyJobService().run_copy_job_request(request) # then create_post_copy_action.assert_called_once_with( copy_job_type_id='test-process', post_copy_action_request=post_copy_action_request, job_json={ 'status': { 'state': 'DONE', 'errors': [ { 'reason': 'Invalid', 'message': ( "Access Denied while creating Copy Job from {} to {}".format( self.example_source_bq_table, self.example_target_bq_table)) } ] }, 'configuration': { 'copy': { 'sourceTable': { 'projectId': self.example_source_bq_table.get_project_id(), 'tableId': self.example_source_bq_table.get_table_id(), 'datasetId': self.example_source_bq_table.get_dataset_id() }, 'destinationTable': { 'projectId': self.example_target_bq_table.get_project_id(), 'tableId': self.example_target_bq_table.get_table_id(), 'datasetId': self.example_target_bq_table.get_dataset_id() } } } } ) @patch.object(BigQuery, 'get_job') @patch.object(BigQuery, 'insert_job') @patch.object(TaskCreator, 'create_copy_job_result_check') def test_that_copy_table_will_try_to_wait_if_deadline_exceeded( self, create_copy_job_result_check, insert_job, get_job): # given http_error_content = "{\"error\": " \ " {\"errors\": [" \ " {\"reason\": \"Deadline exceeded\"," \ " \"message\": \"Deadline exceeded\"," \ " \"location\": \"US\"" \ " }]," \ " \"code\": 500," \ " \"message\": \"Deadline exceeded\"}}" successful_job_json = { 'status': { 'state': 'DONE' }, 'jobReference': { 'projectId': self.example_target_bq_table.get_project_id(), 'location': 'EU', 'jobId': 'job123', }, 'configuration': { 'copy': { 'sourceTable': { 'projectId': self.example_source_bq_table.get_project_id(), 'tableId': self.example_source_bq_table.get_table_id(), 'datasetId': self.example_source_bq_table.get_dataset_id() }, 'destinationTable': { 'projectId': self.example_target_bq_table.get_project_id(), 'tableId': self.example_target_bq_table.get_table_id(), 'datasetId': self.example_target_bq_table.get_dataset_id() } } } } insert_job.side_effect = HttpError(Mock(status=500), http_error_content) get_job.return_value = successful_job_json request = CopyJobRequest( task_name_suffix='task_name_suffix', copy_job_type_id='test-process', source_big_query_table=self.example_source_bq_table, target_big_query_table=self.example_target_bq_table, create_disposition="CREATE_IF_NEEDED", write_disposition="WRITE_EMPTY", retry_count=0, post_copy_action_request=None ) # when CopyJobService().run_copy_job_request(request) # then create_copy_job_result_check.assert_called_once_with( ResultCheckRequest( task_name_suffix='task_name_suffix', copy_job_type_id='test-process', job_reference=BigQueryJobReference( project_id=self.example_target_bq_table.get_project_id(), job_id='job123', location='EU' ), retry_count=0, post_copy_action_request=None ) ) @patch('src.commons.big_query.big_query_table_metadata.BigQueryTableMetadata') @patch.object(TaskCreator, 'create_copy_job_result_check') @patch.object(CopyJobService, '_create_random_job_id', return_value='random_job_123') @patch.object(BigQuery, 'insert_job', side_effect=[HttpError(Mock(status=503), 'internal error'), HttpError(Mock(status=409), 'job exists')]) @patch('time.sleep', side_effect=lambda _: None) def test_bug_regression_job_already_exists_after_internal_error( self, _, insert_job, _create_random_job_id, create_copy_job_result_check, table_metadata ): # given post_copy_action_request = \ PostCopyActionRequest(url='/my/url', data={'key1': 'value1'}) table_metadata._BigQueryTableMetadata__get_table_or_partition.return_value.get_location.return_value='EU' # when CopyJobService().run_copy_job_request( CopyJobRequest( task_name_suffix='task_name_suffix', copy_job_type_id='test-process', source_big_query_table=self.example_source_bq_table, target_big_query_table=self.example_target_bq_table, create_disposition="CREATE_IF_NEEDED", write_disposition="WRITE_EMPTY", retry_count=0, post_copy_action_request=post_copy_action_request ) ) # then self.assertEqual(insert_job.call_count, 2) create_copy_job_result_check.assert_called_once_with( ResultCheckRequest( task_name_suffix='task_name_suffix', copy_job_type_id='test-process', job_reference=BigQueryJobReference( project_id='target_project_id_1', job_id='random_job_123', location='EU'), retry_count=0, post_copy_action_request=post_copy_action_request ) )
42.152334
124
0.570354
1,684
17,156
5.328385
0.108076
0.037446
0.053048
0.060849
0.772206
0.747019
0.743898
0.708347
0.671124
0.654519
0
0.007199
0.344136
17,156
406
125
42.256158
0.79026
0.007403
0
0.585014
0
0
0.120214
0.022584
0
0
0
0
0.0317
1
0.028818
false
0.005764
0.034582
0
0.066282
0
0
0
0
null
0
0
0
0
1
1
1
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
15c53f273bb229773a9dd501a2ed7fb628ef13eb
399
py
Python
solutions/dog_muffin.py
attawesome/Computer-Vision-with-OpenCV
1198bfee8683f6b5c415e07e085fa528e00ecd0a
[ "MIT" ]
6
2020-04-30T21:46:13.000Z
2021-02-15T21:32:50.000Z
solutions/dog_muffin.py
attawesome/Computer-Vision-with-OpenCV
1198bfee8683f6b5c415e07e085fa528e00ecd0a
[ "MIT" ]
null
null
null
solutions/dog_muffin.py
attawesome/Computer-Vision-with-OpenCV
1198bfee8683f6b5c415e07e085fa528e00ecd0a
[ "MIT" ]
6
2020-04-27T17:59:50.000Z
2020-12-13T16:10:09.000Z
import cv2 import numpy as np import matplotlib.pyplot as plt image = np.flip(cv2.imread('../img/dog_muffin.jpg'), axis=2) mask = np.zeros(image.shape[:2], dtype="uint8") cv2.rectangle(mask, (90, 120), (160, 190), 255, -1) masked = cv2.bitwise_and(image, image, mask=mask) plt.figure(figsize=(20, 10)) plt.imshow(np.flip(masked, axis =2)) plt.title('Masked Image'), plt.xticks([]), plt.yticks([])
30.692308
60
0.691729
67
399
4.089552
0.597015
0.043796
0
0
0
0
0
0
0
0
0
0.075419
0.102757
399
12
61
33.25
0.689944
0
0
0
0
0
0.095238
0.052632
0
0
0
0
0
1
0
false
0
0.3
0
0.3
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15c8d860e73304bf40bd4b99e9d98b1c9921b456
2,676
py
Python
jetavator/schema_registry/VaultObject.py
jetavator/jetavator
6edc7b57532809f9903735c333544658631252b5
[ "Apache-2.0" ]
null
null
null
jetavator/schema_registry/VaultObject.py
jetavator/jetavator
6edc7b57532809f9903735c333544658631252b5
[ "Apache-2.0" ]
86
2020-04-11T18:03:32.000Z
2021-06-15T14:48:45.000Z
jetavator/schema_registry/VaultObject.py
jetavator/jetavator
6edc7b57532809f9903735c333544658631252b5
[ "Apache-2.0" ]
null
null
null
from __future__ import annotations from typing import Any, Dict, List from abc import ABC, abstractmethod from datetime import datetime from collections import namedtuple from lazy_property import LazyProperty from .sqlalchemy_tables import ObjectDefinition import wysdom from jetavator.services import ComputeServiceABC from .ProjectABC import ProjectABC VaultObjectKey = namedtuple('VaultObjectKey', ['type', 'name']) HubKeyColumn = namedtuple('HubKeyColumn', ['name', 'source']) class VaultObject(wysdom.UserObject, wysdom.RegistersSubclasses, ABC): name: str = wysdom.UserProperty(str) type: str = wysdom.UserProperty(str) optional_yaml_properties = [] def __init__( self, project: ProjectABC, sqlalchemy_object: ObjectDefinition ) -> None: self.project = project self._sqlalchemy_object = sqlalchemy_object super().__init__(self.definition) def __repr__(self) -> str: class_name = type(self).__name__ return f'{class_name}({self.name})' @classmethod def subclass_instance( cls, project: ProjectABC, definition: ObjectDefinition ) -> VaultObject: return cls.registered_subclass_instance( definition.type, project, definition ) @LazyProperty def key(self) -> VaultObjectKey: return VaultObjectKey(self.type, self.name) @property def definition(self) -> Dict[str, Any]: return self._sqlalchemy_object.definition def export_sqlalchemy_object(self) -> ObjectDefinition: if self._sqlalchemy_object.version != str(self.project.version): raise ValueError( "ObjectDefinition version must match project version " "and cannot be updated." ) self._sqlalchemy_object.deploy_dt = str(datetime.now()) return self._sqlalchemy_object @abstractmethod def validate(self) -> None: pass @property def compute_service(self) -> ComputeServiceABC: return self.project.compute_service @property def full_name(self) -> str: return f'{self.type}_{self.name}' @property def checksum(self) -> str: return str(self._sqlalchemy_object.checksum) @property def dependent_satellites(self) -> List[VaultObject]: return [ satellite for satellite in self.project.satellites.values() if any( dependency.type == self.type and dependency.name == self.name for dependency in satellite.pipeline.dependencies ) ]
26.49505
72
0.65284
264
2,676
6.424242
0.318182
0.084906
0.070755
0.028302
0.03184
0.03184
0
0
0
0
0
0
0.2642
2,676
100
73
26.76
0.861351
0
0
0.093333
0
0
0.062079
0.017951
0
0
0
0
0
1
0.146667
false
0.013333
0.133333
0.093333
0.453333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15caae15c5cee5107dd04fd63976ca50c1febedb
79
py
Python
braandket/kernel/__init__.py
ZhengKeli/BraAndKet
f47cdbdb4c5040dd071815378138ac376c205f14
[ "MIT" ]
1
2022-01-13T13:18:41.000Z
2022-01-13T13:18:41.000Z
braandket/kernel/__init__.py
ZhengKeli/BraAndKet
f47cdbdb4c5040dd071815378138ac376c205f14
[ "MIT" ]
null
null
null
braandket/kernel/__init__.py
ZhengKeli/BraAndKet
f47cdbdb4c5040dd071815378138ac376c205f14
[ "MIT" ]
2
2020-11-06T20:16:13.000Z
2020-12-01T12:56:03.000Z
from .abstract import Kernel from .auto import AutoKernel from .numpy import *
19.75
28
0.797468
11
79
5.727273
0.636364
0
0
0
0
0
0
0
0
0
0
0
0.151899
79
3
29
26.333333
0.940299
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
15cdcd4087b753790bc8fb71c6e5d7a167674399
1,500
py
Python
CourseOnline/MainProject/forms.py
smygt/DjangoSchoolSystem.
6ddbef118ed7a2bb77192f96fc888a36ad4831ed
[ "MIT" ]
null
null
null
CourseOnline/MainProject/forms.py
smygt/DjangoSchoolSystem.
6ddbef118ed7a2bb77192f96fc888a36ad4831ed
[ "MIT" ]
null
null
null
CourseOnline/MainProject/forms.py
smygt/DjangoSchoolSystem.
6ddbef118ed7a2bb77192f96fc888a36ad4831ed
[ "MIT" ]
null
null
null
from django import forms from .models import Announcement # from .models import Role from .models import Assignment from .models import CourseMaterial from .models import Grade from .models import StudentUploadFile from .models import Syllabus from .models import Assistant from django.forms import ClearableFileInput # from .models import Instructor # from .models import Student # from .models import Assistant class LoginForm (forms.Form): username = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput, label="Password") class AnnouncementForm (forms.ModelForm): class Meta: model = Announcement fields = ('title', 'content') class AssignmentForm(forms.ModelForm): class Meta: model = Assignment fields = ('title', 'content', 'doc_file', 'due_date') class CourseMaterialForm(forms.ModelForm): print("CourseMaterialForm") class Meta: model = CourseMaterial fields = ('title', 'doc_file') class GradeForm(forms.ModelForm): print("GradeForm") class Meta: model = Grade fields = ('title', 'doc_file') class StudentUploadFileForm(forms.ModelForm): class Meta: model = StudentUploadFile fields = ('doc_file', ) class SyllabusForm(forms.ModelForm): class Meta: model = Syllabus fields = ('doc_file', ) # class AssistantForm(forms.ModelForm): # class Meta: # model = Assistant # fields = ('assistant_id', )
22.38806
76
0.685333
155
1,500
6.587097
0.290323
0.107738
0.17238
0.112635
0.182174
0
0
0
0
0
0
0
0.218667
1,500
67
77
22.38806
0.87116
0.152667
0
0.263158
0
0
0.092637
0
0
0
0
0
0
1
0
false
0.026316
0.236842
0
0.631579
0.052632
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
15ced209f13f0b2a1de3e15ddd92542a87b54d79
29,172
py
Python
ginga/canvas/types/plots.py
kyraikeda/ginga
e0ce979de4a87e12ba7a90eec0517a0be05d14bc
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2015-01-05T14:46:14.000Z
2022-03-23T04:10:54.000Z
ginga/canvas/types/plots.py
kyraikeda/ginga
e0ce979de4a87e12ba7a90eec0517a0be05d14bc
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
858
2015-01-17T01:55:12.000Z
2022-03-08T20:20:31.000Z
ginga/canvas/types/plots.py
kyraikeda/ginga
e0ce979de4a87e12ba7a90eec0517a0be05d14bc
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
60
2015-01-14T21:59:07.000Z
2022-02-13T03:38:49.000Z
# # plots.py -- classes for plots added to Ginga canvases. # # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # import sys import numpy as np from ginga.canvas.CanvasObject import (CanvasObjectBase, _color, register_canvas_types, colors_plus_none) from ginga.misc import Bunch from ginga.canvas.types.layer import CompoundObject from .basic import Path from ginga.misc.ParamSet import Param class XYPlot(CanvasObjectBase): """ Plotable object that defines a single path representing an X/Y line plot. Like a Path, but has some optimization to reduce the actual numbers of points in the path, depending on the scale and pan of the viewer. """ @classmethod def get_params_metadata(cls): return [ Param(name='linewidth', type=int, default=2, min=0, max=20, widget='spinbutton', incr=1, description="Width of outline"), Param(name='linestyle', type=str, default='solid', valid=['solid', 'dash'], description="Style of outline (default: solid)"), Param(name='color', valid=colors_plus_none, type=_color, default='black', description="Color of text"), Param(name='alpha', type=float, default=1.0, min=0.0, max=1.0, widget='spinfloat', incr=0.05, description="Opacity of outline"), ] def __init__(self, name=None, color='black', linewidth=1, linestyle='solid', alpha=1.0, x_acc=None, y_acc=None, **kwargs): super(XYPlot, self).__init__(color=color, linewidth=linewidth, linestyle=linestyle, alpha=alpha, **kwargs) self.name = name self.kind = 'xyplot' self.x_func = None nul_arr = np.array([]) if x_acc is not None: self.x_func = lambda arr: nul_arr if arr.size == 0 else x_acc(arr) if y_acc is None: y_acc = np.mean self.y_func = lambda arr: nul_arr if arr.size == 0 else y_acc(arr) self.points = np.copy(nul_arr) self.limits = np.array([(0.0, 0.0), (0.0, 0.0)]) self.plot_xlim = (None, None) self.path = Path([], color=color, linewidth=linewidth, linestyle=linestyle, alpha=alpha, coord='data') self.path.get_cpoints = self.get_cpoints def plot_xy(self, xpts, ypts): """Convenience function for plotting X and Y points that are in separate arrays. """ self.plot(np.asarray((xpts, ypts)).T) def plot(self, points, limits=None): """Plot `points`, a list, tuple or array of (x, y) points. Parameter --------- points : array-like list, tuple or array of (x, y) points limits : array-like, optional array of (xmin, ymin), (xmax, ymax) Limits will be calculated if not passed in. """ self.points = np.asarray(points) self.plot_xlim = (None, None) # set or calculate limits if limits is not None: # passing limits saves costly min/max calculation self.limits = np.asarray(limits) else: self._calc_limits(self.points) def _calc_limits(self, points): """Internal routine to calculate the limits of `points`. """ # TODO: what should limits be if there are no points? if len(points) == 0: self.limits = np.array([[0.0, 0.0], [0.0, 0.0]]) else: x_vals, y_vals = points.T self.limits = np.array([(x_vals.min(), y_vals.min()), (x_vals.max(), y_vals.max())]) def calc_points(self, viewer, start_x, stop_x): """Called when recalculating our path's points. """ # in case X axis is flipped start_x, stop_x = min(start_x, stop_x), max(start_x, stop_x) new_xlim = (start_x, stop_x) if new_xlim == self.plot_xlim: # X limits are the same, no need to recalculate points return self.plot_xlim = new_xlim points = self.get_data_points(points=self.points) if len(points) == 0: self.path.points = points return x_data, y_data = points.T # if we can determine the visible region shown on the plot # limit the points to those within the region if np.all(np.isfinite([start_x, stop_x])): idx = np.logical_and(x_data >= start_x, x_data <= stop_x) points = points[idx] if self.x_func is not None: # now find all points position in canvas X coord cpoints = self.get_cpoints(viewer, points=points) cx, cy = cpoints.T # Reduce each group of Y points that map to a unique X via a # function that reduces to a single value. The desirable function # will depend on the function of the plot, but mean() would be a # sensible default _, i = np.unique(cx, return_index=True) gr_pts = np.split(points, i) x_data = np.array([self.x_func(a.T[0]) for a in gr_pts if len(a) > 0]) y_data = np.array([self.y_func(a.T[1]) for a in gr_pts if len(a) > 0]) assert len(x_data) == len(y_data) points = np.array((x_data, y_data)).T self.path.points = points def recalc(self, viewer): """Called when recalculating our path's points. """ # select only points within range of the current pan/zoom bbox = viewer.get_pan_rect() if bbox is None: self.path.points = [] return start_x, stop_x = bbox[0][0], bbox[2][0] self.calc_points(viewer, start_x, stop_x) def get_cpoints(self, viewer, points=None, no_rotate=False): """Mostly internal routine used to calculate the native positions to draw the plot. """ # If points are passed, they are assumed to be in data space if points is None: points = self.path.get_points() return viewer.tform['data_to_plot'].to_(points) def update_resize(self, viewer, dims): """Called when the viewer is resized.""" self.recalc(viewer) def get_latest(self): """Get the latest (last) point on the plot. Returns None if there are no points. """ if len(self.points) == 0: return None return self.points[-1] def get_limits(self, lim_type): """Get the limits of the data or the visible part of the plot. If `lim_type` == 'data' returns the limits of all the data points. Otherwise returns the limits of the visibly plotted area. Limits are returned in the form ((xmin, ymin), (xmax, ymax)), as an array. """ if lim_type == 'data': # data limits return np.asarray(self.limits) # plot limits self.path.crdmap = self.crdmap if len(self.path.points) > 0: llur = self.path.get_llur() llur = [llur[0:2], llur[2:4]] else: llur = [(0.0, 0.0), (0.0, 0.0)] return np.asarray(llur) def draw(self, viewer): """Draw the plot. Normally not called by the user, but by the viewer as needed. """ self.path.crdmap = self.crdmap self.recalc(viewer) if len(self.path.points) > 0: self.path.draw(viewer) class Axis(CompoundObject): """ Base class for axis plotables. """ def __init__(self, title=None, num_labels=4, font='sans', fontsize=10.0): super(Axis, self).__init__() self.aide = None self.num_labels = num_labels self.title = title self.font = font self.fontsize = fontsize self.grid_alpha = 1.0 self.format_value = self._format_value def register_decor(self, aide): self.aide = aide def _format_value(self, v): """Default formatter for XAxis labels. """ return "%.4g" % v def set_grid_alpha(self, alpha): """Set the transparency (alpha) of the XAxis grid lines. `alpha` should be between 0.0 and 1.0 """ for i in range(self.num_labels): grid = self.grid[i] grid.alpha = alpha def get_data_xy(self, viewer, pt): arr_pts = np.asarray(pt) x, y = viewer.tform['data_to_plot'].from_(arr_pts).T[:2] flips = viewer.get_transforms() if flips[2]: x, y = y, x return (x, y) def get_title(self): titles_d = self.aide.get_axes_titles() return titles_d[self.kind] def add_plot(self, viewer, plot_src): # Axis objects typically do not need to do anything when a # plot is added--they recalculate labels in update_elements() pass def delete_plot(self, viewer, plot_src): # Axis objects typically do not need to do anything when a # plot is deleted--they recalculate labels in update_elements() pass class XAxis(Axis): """ Plotable object that defines X axis labels and grid lines. """ def __init__(self, title=None, num_labels=4, font='sans', fontsize=10.0): super(XAxis, self).__init__(title=title, num_labels=num_labels, font=font, fontsize=fontsize) self.kind = 'axis_x' self.txt_ht = 0 self.title_wd = 0 self.pad_px = 5 def register_decor(self, aide): self.aide = aide # add X grid self.grid = Bunch.Bunch() for i in range(self.num_labels): self.grid[i] = aide.dc.Line(0, 0, 0, 0, color=aide.grid_fg, linestyle='dash', linewidth=1, alpha=self.grid_alpha, coord='window') self.objects.append(self.grid[i]) self.axis_bg = aide.dc.Rectangle(0, 0, 100, 100, color=aide.norm_bg, fill=True, fillcolor=aide.axis_bg, coord='window') self.objects.append(self.axis_bg) self.lbls = Bunch.Bunch() for i in range(self.num_labels): self.lbls[i] = aide.dc.Text(0, 0, text='', color='black', font=self.font, fontsize=self.fontsize, coord='window') self.objects.append(self.lbls[i]) self._title = aide.dc.Text(0, 0, text='', color='black', font=self.font, fontsize=self.fontsize, alpha=0.0, coord='window') self.objects.append(self._title) def update_elements(self, viewer): """This method is called if the plot is set with new points, or is scaled or panned with existing points. Update the XAxis labels to reflect the new values and/or pan/scale. """ for i in range(self.num_labels): lbl = self.lbls[i] # get data coord equivalents x, y = self.get_data_xy(viewer, (lbl.x, lbl.y)) # format according to user's preference lbl.text = self.format_value(x) def update_bbox(self, viewer, dims): """This method is called if the viewer's window is resized. Update all the XAxis elements to reflect the new dimensions. """ title = self.get_title() self._title.text = title if title is not None else '555.55' self.title_wd, self.txt_ht = viewer.renderer.get_dimensions(self._title) wd, ht = dims[:2] y_hi = ht if title is not None: # remove Y space for X axis title y_hi -= self.txt_ht + 4 # remove Y space for X axis labels y_hi -= self.txt_ht + self.pad_px self.aide.update_plot_bbox(y_hi=y_hi) def update_resize(self, viewer, dims, xy_lim): """This method is called if the viewer's window is resized. Update all the XAxis elements to reflect the new dimensions. """ x_lo, y_lo, x_hi, y_hi = xy_lim wd, ht = dims[:2] # position axis title title = self.get_title() cx, cy = wd // 2 - self.title_wd // 2, ht - 4 if title is not None: self._title.x = cx self._title.y = cy self._title.alpha = 1.0 cy = cy - self.txt_ht else: self._title.alpha = 0.0 # set X labels/grid as needed # calculate evenly spaced interval on X axis in window coords a = (x_hi - x_lo) // (self.num_labels - 1) cx = x_lo for i in range(self.num_labels): lbl = self.lbls[i] lbl.x, lbl.y = cx, cy # get data coord equivalents x, y = self.get_data_xy(viewer, (cx, cy)) # convert to formatted label lbl.text = self.format_value(x) grid = self.grid[i] grid.x1 = grid.x2 = cx grid.y1, grid.y2 = y_lo, y_hi cx += a self.axis_bg.x1, self.axis_bg.x2 = 0, wd self.axis_bg.y1, self.axis_bg.y2 = y_hi, ht class YAxis(Axis): """ Plotable object that defines Y axis labels and grid lines. """ def __init__(self, title=None, num_labels=4, font='sans', fontsize=10.0): super(YAxis, self).__init__(title=title, num_labels=num_labels, font=font, fontsize=fontsize) self.kind = 'axis_y' self.title_wd = 0 self.txt_wd = 0 self.txt_ht = 0 self.pad_px = 4 def register_decor(self, aide): self.aide = aide # add Y grid self.grid = Bunch.Bunch() for i in range(self.num_labels): self.grid[i] = aide.dc.Line(0, 0, 0, 0, color=aide.grid_fg, linestyle='dash', linewidth=1, alpha=self.grid_alpha, coord='window') self.objects.append(self.grid[i]) # bg for RHS Y axis labels self.axis_bg = aide.dc.Rectangle(0, 0, 100, 100, color=aide.norm_bg, fill=True, fillcolor=aide.axis_bg, coord='window') self.objects.append(self.axis_bg) # bg for LHS Y axis title self.axis_bg2 = aide.dc.Rectangle(0, 0, 100, 100, color=aide.norm_bg, fill=True, fillcolor=aide.axis_bg, coord='window') self.objects.append(self.axis_bg2) # Y grid (tick) labels self.lbls = Bunch.Bunch() for i in range(self.num_labels): self.lbls[i] = aide.dc.Text(0, 0, text='', color='black', font=self.font, fontsize=self.fontsize, coord='window') self.objects.append(self.lbls[i]) # Y title self._title = aide.dc.Text(0, 0, text=self.title, color='black', font=self.font, fontsize=self.fontsize, alpha=0.0, rot_deg=90.0, coord='window') self.objects.append(self._title) def update_elements(self, viewer): """This method is called if the plot is set with new points, or is scaled or panned with existing points. Update the YAxis labels to reflect the new values and/or pan/scale. """ # set Y labels/grid as needed for i in range(self.num_labels): lbl = self.lbls[i] # get data coord equivalents x, y = self.get_data_xy(viewer, (lbl.x, lbl.y)) lbl.text = self.format_value(y) def update_bbox(self, viewer, dims): """This method is called if the viewer's window is resized. Update all the YAxis elements to reflect the new dimensions. """ title = self.get_title() self._title.text = title if title is not None else '555.55' wd, ht = dims[:2] self.title_wd, self.txt_ht = viewer.renderer.get_dimensions(self._title) # TODO: not sure this will give us the maximum length of number text = self.format_value(sys.float_info.max) t = self.aide.dc.Text(0, 0, text=text, fontsize=self.fontsize, font=self.font) self.txt_wd, _ = viewer.renderer.get_dimensions(t) if title is not None: x_lo = self.txt_ht + 2 + self.pad_px else: x_lo = 0 x_hi = wd - (self.txt_wd + 4) - self.pad_px self.aide.update_plot_bbox(x_lo=x_lo, x_hi=x_hi) def update_resize(self, viewer, dims, xy_lim): """This method is called if the viewer's window is resized. Update all the YAxis elements to reflect the new dimensions. """ x_lo, y_lo, x_hi, y_hi = xy_lim wd, ht = dims[:2] # position axis title title = self.get_title() cx = self.txt_ht + 2 cy = ht // 2 + self.title_wd // 2 if title is not None: self._title.x = cx self._title.y = cy self._title.alpha = 1.0 else: self._title.alpha = 0.0 cx = x_hi + self.pad_px cy = y_hi # set Y labels/grid as needed a = (y_hi - y_lo) // (self.num_labels - 1) for i in range(self.num_labels): lbl = self.lbls[i] # calculate evenly spaced interval on Y axis in window coords lbl.x, lbl.y = cx, cy # get data coord equivalents x, y = self.get_data_xy(viewer, (cx, cy)) lbl.text = self.format_value(y) grid = self.grid[i] grid.x1, grid.x2 = x_lo, x_hi grid.y1 = grid.y2 = cy cy -= a self.axis_bg.x1, self.axis_bg.x2 = x_hi, wd self.axis_bg.y1, self.axis_bg.y2 = y_lo, y_hi self.axis_bg2.x1, self.axis_bg2.x2 = 0, x_lo self.axis_bg2.y1, self.axis_bg2.y2 = y_lo, y_hi class PlotBG(CompoundObject): """ Plotable object that defines the plot background. Can include a warning line and an alert line. If the last Y value plotted exceeds the warning line then the background changes color. For example, you might be plotting detector values and want to set a warning if a certain threshold is crossed and an alert if the detector has saturated (alerts are higher than warnings). """ def __init__(self, warn_y=None, alert_y=None, linewidth=1): super(PlotBG, self).__init__() self.y_lbl_info = [warn_y, alert_y] self.warn_y = warn_y self.alert_y = alert_y self.linewidth = linewidth # default warning check self.check_warning = self._check_warning self.norm_bg = 'white' self.warn_bg = 'lightyellow' self.alert_bg = 'mistyrose2' self.kind = 'plot_bg' self.pickable = True self.opaque = True def register_decor(self, aide): self.aide = aide # add a backdrop that we can change color for visual warnings self.bg = aide.dc.Rectangle(0, 0, 100, 100, color=aide.norm_bg, fill=True, fillcolor=aide.norm_bg, fillalpha=1.0, coord='window') self.objects.append(self.bg) # add warning and alert lines self.ln_warn = aide.dc.Line(0, self.warn_y, 1, self.warn_y, color='gold3', linewidth=self.linewidth, alpha=0.0, coord='window') self.objects.append(self.ln_warn) self.ln_alert = aide.dc.Line(0, self.alert_y, 1, self.alert_y, color='red', linewidth=self.linewidth, alpha=0.0, coord='window') self.objects.append(self.ln_alert) def warning(self): self.bg.fillcolor = self.warn_bg def alert(self): self.bg.fillcolor = self.alert_bg def normal(self): self.bg.fillcolor = self.norm_bg def _check_warning(self): max_y = None for i, plot_src in enumerate(self.aide.plots.values()): limits = plot_src.get_limits('data') y = limits[1][1] max_y = y if max_y is None else max(max_y, y) if max_y is not None: if self.alert_y is not None and max_y > self.alert_y: self.alert() elif self.warn_y is not None and max_y > self.warn_y: self.warning() else: self.normal() def update_elements(self, viewer): """This method is called if the plot is set with new points, or is scaled or panned with existing points. Update the XAxis labels to reflect the new values and/or pan/scale. """ y_lo, y_hi = self.aide.bbox.T[1].min(), self.aide.bbox.T[1].max() # adjust warning/alert lines if self.warn_y is not None: x, y = self.get_canvas_xy(viewer, (0, self.warn_y)) if y_lo <= y <= y_hi: self.ln_warn.alpha = 1.0 else: # y out of range of plot area, so make it invisible self.ln_warn.alpha = 0.0 self.ln_warn.y1 = self.ln_warn.y2 = y if self.alert_y is not None: x, y = self.get_canvas_xy(viewer, (0, self.alert_y)) if y_lo <= y <= y_hi: self.ln_alert.alpha = 1.0 else: # y out of range of plot area, so make it invisible self.ln_alert.alpha = 0.0 self.ln_alert.y1 = self.ln_alert.y2 = y self.check_warning() def update_bbox(self, viewer, dims): # this object does not adjust the plot bbox at all pass def update_resize(self, viewer, dims, xy_lim): """This method is called if the viewer's window is resized. Update all the PlotBG elements to reflect the new dimensions. """ # adjust bg to window size, in case it changed x_lo, y_lo, x_hi, y_hi = xy_lim wd, ht = dims[:2] self.bg.x1, self.bg.y1 = x_lo, y_lo self.bg.x2, self.bg.y2 = x_hi, y_hi # adjust warning/alert lines if self.warn_y is not None: x, y = self.get_canvas_xy(viewer, (0, self.warn_y)) self.ln_warn.x1, self.ln_warn.x2 = x_lo, x_hi self.ln_warn.y1 = self.ln_warn.y2 = y if self.alert_y is not None: x, y = self.get_canvas_xy(viewer, (0, self.alert_y)) self.ln_alert.x1, self.ln_alert.x2 = x_lo, x_hi self.ln_alert.y1 = self.ln_alert.y2 = y def add_plot(self, viewer, plot_src): pass def delete_plot(self, viewer, plot_src): pass def get_canvas_xy(self, viewer, pt): arr_pts = np.asarray(pt) return viewer.tform['data_to_plot'].to_(arr_pts).T[:2] class PlotTitle(CompoundObject): """ Plotable object that defines the plot title and keys. """ def __init__(self, title='', font='sans', fontsize=12.0): super(PlotTitle, self).__init__() self.font = font self.fontsize = fontsize self.title = title self.txt_ht = 0 self.kind = 'plot_title' self.format_label = self._format_label self.pad_px = 5 def register_decor(self, aide): self.aide = aide self.title_bg = aide.dc.Rectangle(0, 0, 100, 100, color=aide.norm_bg, fill=True, fillcolor=aide.axis_bg, coord='window') self.objects.append(self.title_bg) self.lbls = dict() self.lbls[0] = aide.dc.Text(0, 0, text=self.title, color='black', font=self.font, fontsize=self.fontsize, coord='window') self.objects.append(self.lbls[0]) def _format_label(self, lbl, plot_src): """Default formatter for PlotTitle labels. """ lbl.text = "{0:}".format(plot_src.name) def update_elements(self, viewer): """This method is called if the plot is set with new points, or is scaled or panned with existing points. Update the PlotTitle labels to reflect the new values. """ for i, plot_src in enumerate(self.aide.plots.values()): lbl = self.lbls[plot_src] self.format_label(lbl, plot_src) def update_bbox(self, viewer, dims): """This method is called if the viewer's window is resized. Update all the PlotTitle elements to reflect the new dimensions. """ wd, ht = dims[:2] if self.txt_ht == 0: _, self.txt_ht = viewer.renderer.get_dimensions(self.lbls[0]) y_lo = self.txt_ht + self.pad_px self.aide.update_plot_bbox(y_lo=y_lo) def update_resize(self, viewer, dims, xy_lim): """This method is called if the viewer's window is resized. Update all the PlotTitle elements to reflect the new dimensions. """ x_lo, y_lo, x_hi, y_hi = xy_lim wd, ht = dims[:2] nplots = len(list(self.aide.plots.keys())) + 1 # set title labels as needed a = wd // (nplots + 1) cx, cy = 4, self.txt_ht lbl = self.lbls[0] lbl.x, lbl.y = cx, cy for i, plot_src in enumerate(self.aide.plots.values()): cx += a lbl = self.lbls[plot_src] lbl.x, lbl.y = cx, cy self.format_label(lbl, plot_src) self.title_bg.x1, self.title_bg.x2 = 0, wd self.title_bg.y1, self.title_bg.y2 = 0, y_lo def add_plot(self, viewer, plot_src): text = plot_src.name color = plot_src.color lbl = self.aide.dc.Text(0, 0, text=text, color=color, font=self.font, fontsize=self.fontsize, coord='window') self.lbls[plot_src] = lbl self.objects.append(lbl) lbl.crdmap = self.lbls[0].crdmap self.format_label(lbl, plot_src) # reorder and place labels dims = viewer.get_window_size() self.update_resize(viewer, dims, self.aide.llur) def delete_plot(self, viewer, plot_src): lbl = self.lbls[plot_src] del self.lbls[plot_src] self.objects.remove(lbl) # reorder and place labels dims = viewer.get_window_size() self.update_resize(viewer, dims, self.aide.llur) class CalcPlot(XYPlot): def __init__(self, name=None, x_fn=None, y_fn=None, color='black', linewidth=1, linestyle='solid', alpha=1.0, **kwdargs): super(CalcPlot, self).__init__(name=name, color=color, linewidth=linewidth, linestyle=linestyle, alpha=alpha, **kwdargs) self.kind = 'calcplot' if x_fn is None: x_fn = lambda x: x # noqa self.x_fn = x_fn if y_fn is None: y_fn = lambda y: y # noqa self.y_fn = y_fn def plot(self, y_fn, x_fn=None): if x_fn is not None: self.x_fn = x_fn self.y_fn = y_fn self.plot_xlim = (None, None) def calc_points(self, viewer, start_x, stop_x): # in case X axis is flipped start_x, stop_x = min(start_x, stop_x), max(start_x, stop_x) new_xlim = (start_x, stop_x) if new_xlim == self.plot_xlim: # X limits are the same, no need to recalculate points return self.plot_xlim = new_xlim wd, ht = self.viewer.get_window_size() x_pts = self.x_fn(np.linspace(start_x, stop_x, wd, dtype=np.float)) y_pts = self.y_fn(x_pts) points = np.array((x_pts, y_pts)).T self.path.points = points def get_limits(self, lim_type): try: llur = self.path.get_llur() limits = [llur[0:2], llur[2:4]] return np.array(limits) except Exception: return np.array(((0.0, 0.0), (0.0, 0.0))) # register our types register_canvas_types(dict(xyplot=XYPlot, calcplot=CalcPlot))
35.189385
80
0.547614
4,021
29,172
3.828152
0.106441
0.007406
0.005457
0.005717
0.583902
0.526148
0.487429
0.444358
0.409277
0.381472
0
0.016214
0.350953
29,172
828
81
35.231884
0.796768
0.199095
0
0.479371
0
0
0.01986
0
0
0
0
0.002415
0.001965
1
0.10609
false
0.009823
0.013752
0.001965
0.165029
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15d0460d3097f204a84b42c16fe07a92ea6eb177
8,305
py
Python
process_disqualified_directors_data.py
Global-Witness/uk-companies-house-parsers-public
e33a3a7791d6565638e2f3c0fd1233a909d983f2
[ "MIT" ]
2
2019-08-03T16:58:43.000Z
2022-01-23T16:57:52.000Z
process_disqualified_directors_data.py
Global-Witness/uk-companies-house-parsers-public
e33a3a7791d6565638e2f3c0fd1233a909d983f2
[ "MIT" ]
1
2019-06-18T10:10:20.000Z
2019-06-18T10:10:20.000Z
process_disqualified_directors_data.py
Global-Witness/uk-companies-house-parsers-public
e33a3a7791d6565638e2f3c0fd1233a909d983f2
[ "MIT" ]
1
2020-11-01T10:21:03.000Z
2020-11-01T10:21:03.000Z
import csv import os import sys from collections import defaultdict PERSONS_OUTPUT_FILENAME_TEMPLATE = "persons_data_%s.csv" DISQUALIFICATIONS_FILENAME_TEMPLATE = "disqualifications_data_%s.csv" EXEMPTIONS_FILENAME_TEMPLATE = 'exemptions_data_%s.csv' SNAPSHOT_HEADER_IDENTIFIER = "DISQUALS" TRAILER_RECORD_IDENTIFIER = "DISQUALS" PERSON_RECORD_TYPE = '1' DISQUALIFICATION_RECORD_TYPE = '2' EXEMPTION_RECORD_TYPE = '3' def process_header_row(row): header_identifier = row[0:8] print(header_identifier) run_number = row[8:12] production_date = row[12:20] if header_identifier != SNAPSHOT_HEADER_IDENTIFIER: print( "Unsuported file type from header: '%s'. Expecting a snapshot header: '%s'" % (header_identifier, SNAPSHOT_HEADER_IDENTIFIER)) sys.exit(1) print("Processing snapshot file with run number %s from date %s" % (run_number, production_date)) def process_person_row(row, output_writer): record_type = row[0] person_number = str(row[1:13]) person_dob = row[13:21] person_postcode = row[21:29] person_variable_ind = int(row[29:33]) person_details = row[33:33 + person_variable_ind] person_details = person_details.split('<') title = person_details[0] forenames = person_details[1] surname = person_details[2] honours = person_details[3] address_line_1 = person_details[4] address_line_2 = person_details[5] posttown = person_details[6] county = person_details[7] country = person_details[8] nationality = person_details[9] corporate_number = person_details[10] country_registration = person_details[11] output_writer.writerow([ record_type, person_number, person_dob, person_postcode, person_details, title, forenames, surname, honours, address_line_1, address_line_2, posttown, county, country, nationality, corporate_number, country_registration ]) def process_disqualification_row(row, output_writer): record_type = row[0] person_number = str(row[1:13]) disqual_start_date = row[13:21] disqual_end_date = row[21:29] section_of_act = row[29:49] disqual_type = row[49:79] disqual_order_date = row[79:87] case_number = row[87:117] company_name = row[117:277] court_name_variable_ind = int(row[277:281]) court_name = row[281:281 + court_name_variable_ind] output_writer.writerow([ record_type, person_number, disqual_start_date, disqual_end_date, section_of_act, disqual_type, disqual_order_date, case_number, company_name, court_name ]) def process_exemption_row(row, output_writer): record_type = row[0] person_number = str(row[1:9]) exemption_start_date = row[13:21] exemption_end_date = row[21:29] exemption_purpose = int(row[29:39]) exemption_purpose_dict = defaultdict( lambda: '', { 1: 'Promotion', 2: 'Formation', 3: 'Directorships or other participation in management of a company', 4: 'Designated member/member or other participation in management of an LLP', 5: 'Receivership in relation to a company or LLP' }) exemption_purpose = exemption_purpose_dict[exemption_purpose] exemption_company_name_ind = int(row[39:43]) exemption_company_name = row[43:43 + exemption_company_name_ind] output_writer.writerow([ record_type, person_number, exemption_start_date, exemption_end_date, exemption_purpose, exemption_company_name ]) def init_person_output_file(filename): output_persons_file = open(filename, 'w') persons_writer = csv.writer(output_persons_file, delimiter=",") persons_writer.writerow([ "record_type", "person_number", "person_dob", "person_postcode", "person_details", 'title', 'forenames', 'surname', 'honours', 'address_line_1', 'address_line_2', 'posttown', 'county', 'country', 'nationality', 'corporate_number', 'country_registration' ]) return output_persons_file, persons_writer def init_disquals_output_file(filename): output_disquals_file = open(filename, 'w') disqauls_writer = csv.writer(output_disquals_file, delimiter=",") disqauls_writer.writerow([ "record_type", "person_number", "disqual_start_date", "disqual_end_date", "section_of_act", "disqual_type", "disqual_order_date", "case_number", "company_name", "court_name" ]) return output_disquals_file, disqauls_writer def init_exemptions_output_file(filename): output_exemptions_file = open(filename, 'w') exemptions_writer = csv.writer(output_exemptions_file, delimiter=",") exemptions_writer.writerow([ "record_type", "person_number", "exemption_start_date", "exemption_end_date", "exemption_purpose", "exemption_company_name" ]) return output_exemptions_file, exemptions_writer def init_input_files(output_folder, base_input_name): persons_output_filename = os.path.join( output_folder, PERSONS_OUTPUT_FILENAME_TEMPLATE % (base_input_name)) disquals_output_filename = os.path.join( output_folder, DISQUALIFICATIONS_FILENAME_TEMPLATE % (base_input_name)) exemptions_output_filename = os.path.join( output_folder, EXEMPTIONS_FILENAME_TEMPLATE % (base_input_name)) print("Saving companies data to %s" % persons_output_filename) print("Saving persons data to %s" % disquals_output_filename) print("Saving persons data to %s" % exemptions_output_filename) output_persons_file, output_persons_writer = init_person_output_file( persons_output_filename) output_disquals_file, output_disquals_writer = init_disquals_output_file( disquals_output_filename) output_exemptions_file, output_exemptions_writer = init_exemptions_output_file( exemptions_output_filename) return output_persons_file, output_persons_writer, output_disquals_file, output_disquals_writer, output_exemptions_file, output_exemptions_writer def process_company_appointments_data(input_file, output_folder, base_input_name): persons_processed = 0 disquals_processed = 0 exemptions_processed = 0 output_persons_file, output_persons_writer, output_disquals_file, output_disquals_writer, output_exemptions_file, output_exemptions_writer = init_input_files( output_folder, base_input_name) for row_num, row in enumerate(input_file): if row_num == 0: process_header_row(row) elif row[0:8] == TRAILER_RECORD_IDENTIFIER: # End of file record_count = int(row[45:53]) print( "Reached end of file. Processed %s == %s records: %s persons, %s disquals, %s exemptions." % (record_count, persons_processed + disquals_processed + exemptions_processed, persons_processed, disquals_processed, exemptions_processed)) output_persons_file.close() output_disquals_file.close() output_exemptions_file.close() sys.exit(0) elif row[0] == PERSON_RECORD_TYPE: process_person_row(row, output_persons_writer) persons_processed += 1 elif row[0] == DISQUALIFICATION_RECORD_TYPE: process_disqualification_row(row, output_disquals_writer) disquals_processed += 1 elif row[0] == EXEMPTION_RECORD_TYPE: process_exemption_row(row, output_exemptions_writer) exemptions_processed += 1 if __name__ == '__main__': if len(sys.argv) < 3: print( 'Usage: python process_disqualified_directors_data.py input_file output_folder\n', 'E.g. python process_disqualified_directors_data.py Prod195_1111_ni_sample.dat ./output/' ) sys.exit(1) input_filename = sys.argv[1] output_folder = sys.argv[2] input_file = open(input_filename, 'r') base_input_name = os.path.basename(input_filename) # Do not include the extension in the base input name base_input_name = os.path.splitext(base_input_name)[0] process_company_appointments_data(input_file, output_folder, base_input_name)
41.318408
162
0.706562
1,021
8,305
5.354554
0.164545
0.040424
0.026157
0.02634
0.462777
0.375526
0.313335
0.284068
0.252241
0.252241
0
0.02382
0.206382
8,305
201
163
41.318408
0.805644
0.007586
0
0.106742
0
0.005618
0.143811
0.021238
0
0
0
0
0
1
0.050562
false
0
0.022472
0
0.095506
0.044944
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15d05a5b381b6c77c32c1817ba56017e005be78f
2,875
py
Python
myPackage/tools.py
marcgonzmont/ML_Challenge
ed9767689064a941c2db7642fc499828d0ad1326
[ "CC0-1.0" ]
null
null
null
myPackage/tools.py
marcgonzmont/ML_Challenge
ed9767689064a941c2db7642fc499828d0ad1326
[ "CC0-1.0" ]
null
null
null
myPackage/tools.py
marcgonzmont/ML_Challenge
ed9767689064a941c2db7642fc499828d0ad1326
[ "CC0-1.0" ]
null
null
null
from os import makedirs, errno from os.path import exists, join import numpy as np from matplotlib import pyplot as plt import itertools from sklearn import preprocessing def makeDir(path): ''' To create output path if doesn't exist see: https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist :param path: path to be created :return: none ''' try: if not exists(path): makedirs(path) print("\nCreated '{}' folder\n".format(path)) except OSError as e: if e.errno != errno.EEXIST: raise def split_train_test(data, test_ratio): shuffled_indices = np.random.permutation(len(data)) test_set_size = int(len(data) * test_ratio) test_indices = shuffled_indices[:test_set_size] train_indices = shuffled_indices[test_set_size:] train_set = [data[i] for i in train_indices] test_set = [data[i] for i in test_indices] return np.asarray(train_set), np.asarray(test_set) def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Greens): ''' This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. :param cm: confusion matrix :param classes: array of classes' names :param normalize: boolean :param title: plot title :param cmap: colour of matrix background :return: plot confusion matrix ''' # plt_name = altsep.join((plot_path,"".join((title,".png")))) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) print('\nSum of main diagonal') print(np.trace(cm)) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label', labelpad=0) # plt.savefig(plt_name) plt.show() def normalize(data): ''' Normalize input data [0, 1] :param data: input data :return: normalized data ''' scaler = preprocessing.MinMaxScaler() data_min_max = scaler.fit_transform(data) return data_min_max
31.593407
102
0.619826
371
2,875
4.708895
0.425876
0.060103
0.01889
0.029765
0.059531
0.059531
0.043503
0
0
0
0
0.007583
0.266087
2,875
90
103
31.944444
0.820379
0.224
0
0
0
0
0.089932
0
0
0
0
0
0
1
0.074074
false
0
0.111111
0
0.222222
0.111111
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15d0b4957b2e9a69a93ba4e15d527f629984be60
9,802
py
Python
maskrcnn_benchmark/data/datasets/kitti.py
pwllr/IDA-3D
f5c8acbcf90a7c351499249a24754ad311da375e
[ "MIT" ]
78
2020-03-02T12:00:57.000Z
2022-02-21T09:48:08.000Z
maskrcnn_benchmark/data/datasets/kitti.py
pwllr/IDA-3D
f5c8acbcf90a7c351499249a24754ad311da375e
[ "MIT" ]
19
2020-03-02T12:07:18.000Z
2022-03-30T08:04:06.000Z
maskrcnn_benchmark/data/datasets/kitti.py
pwllr/IDA-3D
f5c8acbcf90a7c351499249a24754ad311da375e
[ "MIT" ]
14
2020-06-14T03:29:47.000Z
2021-07-21T06:30:08.000Z
import os import torch import torch.utils.data from PIL import Image import sys import numpy as np if sys.version_info[0] == 2: import xml.etree.cElementTree as ET else: import xml.etree.ElementTree as ET from maskrcnn_benchmark.structures.bounding_box import BoxList from maskrcnn_benchmark.structures.bounding_box import ObjectList def read_calib(calib_file_path): data = {} with open(calib_file_path, 'r') as f: for line in f.readlines(): line = line.rstrip() if len(line)==0: continue key, value = line.split(':', 1) data[key] = np.array([float(x) for x in value.split()]) return data class KittiDataset(torch.utils.data.Dataset): CLASSES = ( "__background__ ", "car", ) def __init__(self, data_dir, split, use_difficult=False, transforms=None): self.root = data_dir self.image_set = split self.keep_difficult = use_difficult self.transforms = transforms self._annopath = os.path.join(self.root, "label_3d", "%s.xml") self._image_left_path = os.path.join(self.root, "image_2", "%s.png") self._image_right_path = os.path.join(self.root, "image_3", "%s.png") self._calib_path = os.path.join(self.root, "calib", "%s.txt") self._imgsetpath = os.path.join(self.root, "splits", "%s.txt") with open(self._imgsetpath % self.image_set) as f: self.ids = f.readlines() self.ids = [x.strip("\n") for x in self.ids] self.id_to_img_map = {k: v for k, v in enumerate(self.ids)} cls = KittiDataset.CLASSES self.class_to_ind = dict(zip(cls, range(len(cls)))) self.categories = dict(zip(range(len(cls)), cls)) def __getitem__(self, index): img_id = self.ids[index] img_left = Image.open(self._image_left_path % img_id).convert("RGB") img_right = Image.open(self._image_right_path % img_id).convert("RGB") target = self.get_groundtruth(index) target_object = self.get_groundtruth(index) target_left = target_object.get_field("left_box") target_right = target_object.get_field("right_box") target_left = target_left.clip_to_image(remove_empty=True) target_right = target_right.clip_to_image(remove_empty=True) if self.transforms is not None: img_left, target_left = self.transforms(img_left, target_left) img_right, target_right = self.transforms(img_right, target_right) target_object.add_field("left_box", target_left) target_object.add_field("right_box", target_right) calib = self.preprocess_calib(index) return img_left, img_right, target, calib, index def __len__(self): return len(self.ids) def get_groundtruth(self, index): img_id = self.ids[index] anno = ET.parse(self._annopath % img_id).getroot() anno = self._preprocess_annotation(anno) height, width = anno["im_info"] left_target = BoxList(anno["left_boxes"], (width, height), mode="xyxy") left_target.add_field("labels", anno["labels"]) left_target.add_field("difficult", anno["difficult"]) right_target = BoxList(anno["right_boxes"], (width, height), mode="xyxy") right_target.add_field("labels", anno["labels"]) right_target.add_field("difficult", anno["difficult"]) object_target = ObjectList() object_target.add_field("left_box", left_target) object_target.add_field("right_box", right_target) object_target.add_field("labels", anno["labels"]) object_target.add_field("left_centers", anno["left_centers"]) object_target.add_field("right_centers", anno["right_centers"]) object_target.add_field("positions_xy", anno["positions_xy"]) object_target.add_field("positions_z", anno["positions_z"]) object_target.add_field("dimensions", anno["dimensions"]) object_target.add_field("alpha", anno["alpha"]) object_target.add_field("beta", anno["beta"]) object_target.add_field("corners", anno["corners"]) assert object_target.is_equal() return object_target def preprocess_calib(self, index): img_id = self.ids[index] calib_path = self._calib_path % img_id calib = read_calib(calib_path) P2 = np.reshape(calib['P2'], [3,4]) P3 = np.reshape(calib['P3'], [3,4]) c_u = P2[0,2] c_v = P2[1,2] f_u = P2[0,0] f_v = P2[1,1] b_x_2 = P2[0,3]/(f_u) # relative b_y_2 = P2[1,3]/(f_v) b_x_3 = P3[0,3]/(f_u) # relative b_y_3 = P3[1,3]/(f_v) b = abs(b_x_3 - b_x_2) return { "cu": c_u, "cv": c_v, "fu": f_u, "fv": f_v, "b": b, "bx2":b_x_2, } def _preprocess_annotation(self, target): left_boxes = [] right_boxes = [] gt_classes = [] difficult_boxes = [] TO_REMOVE = 0 #3d parameters left_centers = [] right_centers = [] dimensions = [] positions_xy = [] positions_z = [] rotations = [] alphas = [] pconers = [] #occluded = [] #truncted = [] for obj in target.iter("object"): difficult = int(obj.find("difficult").text) == 1 if not self.keep_difficult and difficult: continue name = obj.find("name").text.lower().strip() left_bb = obj.find("left_bndbox") left_box = [ left_bb.find("xmin").text, left_bb.find("ymin").text, left_bb.find("xmax").text, left_bb.find("ymax").text, ] left_bndbox = tuple( map(lambda x: x - TO_REMOVE, list(map(float, left_box))) ) left_boxes.append(left_bndbox) left_center = [ left_bb.find("center").find("x").text, left_bb.find("center").find("y").text, ] left_center = list(map(float, left_center)) left_centers.append(left_center) right_bb = obj.find("right_bndbox") right_box = [ right_bb.find("xmin").text, right_bb.find("ymin").text, right_bb.find("xmax").text, right_bb.find("ymax").text, ] right_bndbox = tuple( map(lambda x: x - TO_REMOVE, list(map(float, right_box))) ) right_boxes.append(right_bndbox) right_center = [ right_bb.find("center").find("x").text, right_bb.find("center").find("y").text, ] right_center = list(map(float, right_center)) right_centers.append(right_center) gt_classes.append(self.class_to_ind[name]) difficult_boxes.append(difficult) position_xy = [ obj.find("position").find("x").text, obj.find("position").find("y").text, ] position_xy = list(map(float, position_xy)) positions_xy.append(position_xy) position_z = [ obj.find("position").find("z").find("depth").text, obj.find("position").find("z").find("disp").text, ] position_z = list(map(float, position_z)) positions_z.append(position_z) dimension = [ obj.find("dimensions").find("h").text, obj.find("dimensions").find("w").text, obj.find("dimensions").find("l").text, ] dimension = list(map(float, dimension)) dimensions.append(dimension) alp = float(obj.find("alpha").text) alphas.append(alp) rot = float(obj.find("rotation").text) rotations.append(rot) pc = [] corners = obj.find("corners") for i in range(8): pc_str = corners.find("pc%d"%i).text pc_i = [float(pc_s) for pc_s in pc_str.split(',')] pc.append(pc_i) pconers.append(pc) size = target.find("size") im_info = tuple(map(int, (size.find("height").text, size.find("width").text))) res = { "left_boxes": torch.tensor(left_boxes, dtype=torch.float32).view(-1,4), "right_boxes": torch.tensor(right_boxes, dtype=torch.float32).view(-1,4), "labels": torch.tensor(gt_classes), "difficult": torch.tensor(difficult_boxes), "left_centers": torch.tensor(left_centers, dtype=torch.float32).view(-1,2), "right_centers": torch.tensor(right_centers, dtype=torch.float32).view(-1,2), "positions_xy": torch.tensor(positions_xy, dtype=torch.float32).view(-1,2), "positions_z": torch.tensor(positions_z, dtype=torch.float32).view(-1,2), "dimensions": torch.tensor(dimensions, dtype=torch.float32).view(-1,3), "alpha": torch.tensor(alphas, dtype=torch.float32), "beta": torch.tensor(rotations, dtype=torch.float32), "corners": torch.tensor(pconers, dtype=torch.float32).view(-1,8,7), "im_info": im_info, } return res def get_img_info(self, index): img_id = self.ids[index] anno = ET.parse(self._annopath % img_id).getroot() size = anno.find("size") im_info = tuple(map(int, (size.find("height").text, size.find("width").text))) return {"height": im_info[0], "width": im_info[1]} def map_class_id_to_class_name(self, class_id): return KittiDataset.CLASSES[class_id]
36.169742
89
0.576515
1,245
9,802
4.301205
0.160643
0.025397
0.039216
0.041083
0.302708
0.206162
0.133147
0.060878
0.060878
0.060878
0
0.012839
0.28484
9,802
270
90
36.303704
0.75107
0.005917
0
0.03653
0
0
0.079791
0
0
0
0
0
0.004566
1
0.041096
false
0
0.045662
0.009132
0.13242
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15d22cd4619c04c4fa2d8d4c420166060bc9ee2a
25,744
py
Python
escriptcore/py_src/faultsystems.py
markendr/esys-escript.github.io
0023eab09cd71f830ab098cb3a468e6139191e8d
[ "Apache-2.0" ]
null
null
null
escriptcore/py_src/faultsystems.py
markendr/esys-escript.github.io
0023eab09cd71f830ab098cb3a468e6139191e8d
[ "Apache-2.0" ]
null
null
null
escriptcore/py_src/faultsystems.py
markendr/esys-escript.github.io
0023eab09cd71f830ab098cb3a468e6139191e8d
[ "Apache-2.0" ]
null
null
null
############################################################################## # # Copyright (c) 2003-2020 by The University of Queensland # http://www.uq.edu.au # # Primary Business: Queensland, Australia # Licensed under the Apache License, version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # # Development until 2012 by Earth Systems Science Computational Center (ESSCC) # Development 2012-2013 by School of Earth Sciences # Development from 2014 by Centre for Geoscience Computing (GeoComp) # Development from 2019 by School of Earth and Environmental Sciences # ############################################################################## from __future__ import print_function, division __copyright__="""Copyright (c) 2003-2020 by The University of Queensland http://www.uq.edu.au Primary Business: Queensland, Australia""" __license__="""Licensed under the Apache License, version 2.0 http://www.apache.org/licenses/LICENSE-2.0""" __url__="https://launchpad.net/escript-finley" #from esys.escript import sqrt, EPSILON, cos, sin, Lsup, atan, length, matrixmult, wherePositive, matrix_mult, inner, Scalar, whereNonNegative, whereNonPositive, maximum, minimum, sign, whereNegative, whereZero import esys.escriptcore.pdetools as pdt #from .util import * from . import util as es import numpy import math __all__= ['FaultSystem'] class FaultSystem(object): """ The FaultSystem class defines a system of faults in the Earth's crust. A fault system is defined by set of faults index by a tag. Each fault is defined by a starting point V0 and a list of strikes ``strikes`` and length ``l``. The strikes and the length is used to define a polyline with points ``V[i]`` such that - ``V[0]=V0`` - ``V[i]=V[i]+ls[i]*array(cos(strikes[i]),sin(strikes[i]),0)`` So ``strikes`` defines the angle between the direction of the fault segment and the x0 axis. ls[i]==0 is allowed. In case of a 3D model a fault plane is defined through a dip and depth. The class provides a mechanism to parametrise each fault with the domain [0,w0_max] x [0, w1_max] (to [0,w0_max] in the 2D case). """ NOTAG="__NOTAG__" MIN_DEPTH_ANGLE=0.1 def __init__(self,dim=3): """ Sets up the fault system :param dim: spatial dimension :type dim: ``int`` of value 2 or 3 """ if not (dim == 2 or dim == 3): raise ValueError("only dimension2 2 and 3 are supported.") self.__dim=dim self.__top={} self.__ls={} self.__strikes={} self.__strike_vectors={} self.__medDepth={} self.__total_length={} if dim ==2: self.__depths=None self.__depth_vectors=None self.__dips=None self.__bottom=None self.__normals=None else: self.__depths={} self.__depth_vectors={} self.__dips={} self.__bottom={} self.__normals={} self.__offsets={} self.__w1_max={} self.__w0_max={} self.__center=None self.__orientation = None def getStart(self,tag=None): """ returns the starting point of fault ``tag`` :rtype: ``numpy.array``. """ return self.getTopPolyline(tag)[0] def getTags(self): """ returns a list of the tags used by the fault system :rtype: ``list`` """ return list(self.__top.keys()) def getDim(self): """ returns the spatial dimension :rtype: ``int`` """ return self.__dim def getTopPolyline(self, tag=None): """ returns the polyline used to describe fault tagged by ``tag`` :param tag: the tag of the fault :type tag: ``float`` or ``str`` :return: the list of vertices defining the top of the fault. The coordinates are ``numpy.array``. """ if tag is None: tag=self.NOTAG return self.__top[tag] def getStrikes(self, tag=None): """ :return: the strike of the segements in fault ``tag`` :rtype: ``list`` of ``float`` """ if tag is None: tag=self.NOTAG return self.__strikes[tag] def getStrikeVectors(self, tag=None): """ :return: the strike vectors of fault ``tag`` :rtype: ``list`` of ``numpy.array``. """ if tag is None: tag=self.NOTAG return self.__strike_vectors[tag] def getLengths(self, tag=None): """ :return: the lengths of segments in fault ``tag`` :rtype: ``list`` of ``float`` """ if tag is None: tag=self.NOTAG return self.__ls[tag] def getTotalLength(self, tag=None): """ :return: the total unrolled length of fault ``tag`` :rtype: ``float`` """ if tag is None: tag=self.NOTAG return self.__total_length[tag] def getMediumDepth(self,tag=None): """ returns the medium depth of fault ``tag`` :rtype: ``float`` """ if tag is None: tag=self.NOTAG return self.__medDepth[tag] def getDips(self, tag=None): """ returns the list of the dips of the segements in fault ``tag`` :param tag: the tag of the fault :type tag: ``float`` or ``str`` :return: the list of segment dips. In the 2D case None is returned. """ if tag is None: tag=self.NOTAG if self.getDim()==3: return self.__dips[tag] else: return None def getBottomPolyline(self, tag=None): """ returns the list of the vertices defining the bottom of the fault ``tag`` :param tag: the tag of the fault :type tag: ``float`` or ``str`` :return: the list of vertices. In the 2D case None is returned. """ if tag is None: tag=self.NOTAG if self.getDim()==3: return self.__bottom[tag] else: return None def getSegmentNormals(self, tag=None): """ returns the list of the normals of the segments in fault ``tag`` :param tag: the tag of the fault :type tag: ``float`` or ``str`` :return: the list of vectors normal to the segments. In the 2D case None is returned. """ if tag is None: tag=self.NOTAG if self.getDim()==3: return self.__normals[tag] else: return None def getDepthVectors(self, tag=None): """ returns the list of the depth vector at top vertices in fault ``tag``. :param tag: the tag of the fault :type tag: ``float`` or ``str`` :return: the list of segment depths. In the 2D case None is returned. """ if tag is None: tag=self.NOTAG if self.getDim()==3: return self.__depth_vectors[tag] else: return None def getDepths(self, tag=None): """ returns the list of the depths of the segements in fault ``tag``. :param tag: the tag of the fault :type tag: ``float`` or ``str`` :return: the list of segment depths. In the 2D case None is returned. """ if tag is None: tag=self.NOTAG if self.getDim()==3: return self.__depths[tag] else: return None def getW0Range(self,tag=None): """ returns the range of the parameterization in ``w0`` :rtype: two ``float`` """ return self.getW0Offsets(tag)[0], self.getW0Offsets(tag)[-1] def getW1Range(self,tag=None): """ returns the range of the parameterization in ``w1`` :rtype: two ``float`` """ if tag is None: tag=self.NOTAG return -self.__w1_max[tag],0 def getW0Offsets(self, tag=None): """ returns the offsets for the parametrization of fault ``tag``. :return: the offsets in the parametrization :rtype: ``list`` of ``float`` """ if tag is None: tag=self.NOTAG return self.__offsets[tag] def getCenterOnSurface(self): """ returns the center point of the fault system at the surface :rtype: ``numpy.array`` """ if self.__center is None: self.__center=numpy.zeros((3,),numpy.float) counter=0 for t in self.getTags(): for s in self.getTopPolyline(t): self.__center[:2]+=s[:2] counter+=1 self.__center/=counter return self.__center[:self.getDim()] def getOrientationOnSurface(self): """ returns the orientation of the fault system in RAD on the surface around the fault system center :rtype: ``float`` """ if self.__orientation is None: center=self.getCenterOnSurface() covariant=numpy.zeros((2,2)) for t in self.getTags(): for s in self.getTopPolyline(t): covariant[0,0]+=(center[0]-s[0])**2 covariant[0,1]+=(center[1]-s[1])*(center[0]-s[0]) covariant[1,1]+=(center[1]-s[1])**2 covariant[1,0]+=(center[1]-s[1])*(center[0]-s[0]) e, V=numpy.linalg.eigh(covariant) if e[0]>e[1]: d=V[:,0] else: d=V[:,1] if abs(d[0])>0.: self.__orientation=es.atan(d[1]/d[0]) else: self.__orientation=math.pi/2 return self.__orientation def transform(self, rot=0, shift=numpy.zeros((3,))): """ applies a shift and a consecutive rotation in the x0x1 plane. :param rot: rotation angle in RAD :type rot: ``float`` :param shift: shift vector to be applied before rotation :type shift: ``numpy.array`` of size 2 or 3 """ if self.getDim() == 2: mat=numpy.array([[es.cos(rot), -es.sin(rot)], [es.sin(rot), es.cos(rot)] ]) else: mat=numpy.array([[es.cos(rot), -es.sin(rot),0.], [es.sin(rot), es.cos(rot),0.], [0.,0.,1.] ]) for t in self.getTags(): strikes=[ s+ rot for s in self.getStrikes(t) ] V0=self.getStart(t) self.addFault(strikes = [ s+ rot for s in self.getStrikes(t) ], \ ls = self.getLengths(t), \ V0=numpy.dot(mat,self.getStart(t)+shift), \ tag =t, \ dips=self.getDips(t),\ depths=self.getDepths(t), \ w0_offsets=self.getW0Offsets(t), \ w1_max=-self.getW1Range(t)[0]) def addFault(self, strikes, ls, V0=[0.,0.,0.],tag=None, dips=None, depths= None, w0_offsets=None, w1_max=None): """ adds a new fault to the fault system. The fault is named by ``tag``. The fault is defined by a starting point V0 and a list of ``strikes`` and length ``ls``. The strikes and the length is used to define a polyline with points ``V[i]`` such that - ``V[0]=V0`` - ``V[i]=V[i]+ls[i]*array(cos(strikes[i]),sin(strikes[i]),0)`` So ``strikes`` defines the angle between the direction of the fault segment and the x0 axis. In 3D ``ls[i]`` ==0 is allowed. In case of a 3D model a fault plane is defined through a dip ``dips`` and depth ``depths``. From the dip and the depth the polyline ``bottom`` of the bottom of the fault is computed. Each segment in the fault is decribed by the for vertices ``v0=top[i]``, ``v1==top[i+1]``, ``v2=bottom[i]`` and ``v3=bottom[i+1]`` The segment is parametrized by ``w0`` and ``w1`` with ``w0_offsets[i]<=w0<=w0_offsets[i+1]`` and ``-w1_max<=w1<=0``. Moreover - ``(w0,w1)=(w0_offsets[i] , 0)->v0`` - ``(w0,w1)=(w0_offsets[i+1], 0)->v1`` - ``(w0,w1)=(w0_offsets[i] , -w1_max)->v2`` - ``(w0,w1)=(w0_offsets[i+1], -w1_max)->v3`` If no ``w0_offsets`` is given, - ``w0_offsets[0]=0`` - ``w0_offsets[i]=w0_offsets[i-1]+L[i]`` where ``L[i]`` is the length of the segments on the top in 2D and in the middle of the segment in 3D. If no ``w1_max`` is given, the average fault depth is used. :param strikes: list of strikes. This is the angle of the fault segment direction with x0 axis. Right hand rule applies. :type strikes: ``list`` of ``float`` :param ls: list of fault lengths. In the case of a 3D fault a segment may have length 0. :type ls: ``list`` of ``float`` :param V0: start point of the fault :type V0: ``list`` or ``numpy.array`` with 2 or 3 components. ``V0[2]`` must be zero. :param tag: the tag of the fault. If fault ``tag`` already exists it is overwritten. :type tag: ``float`` or ``str`` :param dips: list of dip angles. Right hand rule around strike direction applies. :type dips: ``list`` of ``float`` :param depths: list of segment depth. Value mut be positive in the 3D case. :type depths: ``list`` of ``float`` :param w0_offsets: ``w0_offsets[i]`` defines the offset of the segment ``i`` in the fault to be used in the parametrization of the fault. If not present the cumulative length of the fault segments is used. :type w0_offsets: ``list`` of ``float`` or ``None`` :param w1_max: the maximum value used for parametrization of the fault in the depth direction. If not present the mean depth of the fault segments is used. :type w1_max: ``float`` :note: In the three dimensional case the lists ``dip`` and ``top`` must have the same length. """ if tag is None: tag=self.NOTAG else: if self.NOTAG in self.getTags(): raise ValueError('Attempt to add a fault with no tag to a set of existing faults') if not isinstance(strikes, list): strikes=[strikes, ] n_segs=len(strikes) if not isinstance(ls, list): ls=[ ls for i in range(n_segs) ] if not n_segs==len(ls): raise ValueError("number of strike direction and length must match.") if len(V0)>2: if abs(V0[2])>0: raise Value("start point needs to be surface (3rd component ==0)") if self.getDim()==2 and not (dips is None and depths is None) : raise ValueError('Spatial dimension two does not support dip and depth for faults.') if not dips is None: if not isinstance(dips, list): dips=[dips for i in range(n_segs) ] if n_segs != len(dips): raise ValueError('length of dips must be one less than the length of top.') if not depths is None: if not isinstance(depths, list): depths=[depths for i in range(n_segs+1) ] if n_segs+1 != len(depths): raise ValueError('length of depths must be one less than the length of top.') if w0_offsets != None: if len(w0_offsets) != n_segs+1: raise ValueError('expected length of w0_offsets is %s'%(n_segs)) self.__center=None self.__orientation = None # # in the 2D case we don't allow zero length: # if self.getDim() == 2: for l in ls: if l<=0: raise ValueError("length must be positive") else: for l in ls: if l<0: raise ValueError("length must be non-negative") for i in range(n_segs+1): if depths[i]<0: raise ValueError("negative depth.") # # translate start point to numarray # V0= numpy.array(V0[:self.getDim()],numpy.double) # # set strike vectors: # strike_vectors=[] top_polyline=[V0] total_length=0 for i in range(n_segs): v=numpy.zeros((self.getDim(),)) v[0]=es.cos(strikes[i]) v[1]=es.sin(strikes[i]) strike_vectors.append(v) top_polyline.append(top_polyline[-1]+ls[i]*v) total_length+=ls[i] # # normal and depth direction # if self.getDim()==3: normals=[] for i in range(n_segs): normals.append(numpy.array([es.sin(dips[i])*strike_vectors[i][1],-es.sin(dips[i])*strike_vectors[i][0], es.cos(dips[i])]) ) d=numpy.cross(strike_vectors[0],normals[0]) if d[2]>0: f=-1 else: f=1 depth_vectors=[f*depths[0]*d/numpy.linalg.norm(d) ] for i in range(1,n_segs): d=-numpy.cross(normals[i-1],normals[i]) d_l=numpy.linalg.norm(d) if d_l<=0: d=numpy.cross(strike_vectors[i],normals[i]) d_l=numpy.linalg.norm(d) else: for L in [ strike_vectors[i], strike_vectors[i-1]]: if numpy.linalg.norm(numpy.cross(L,d)) <= self.MIN_DEPTH_ANGLE * numpy.linalg.norm(L) * d_l: raise ValueError("%s-th depth vector %s too flat."%(i, d)) if d[2]>0: f=-1 else: f=1 depth_vectors.append(f*d*depths[i]/d_l) d=numpy.cross(strike_vectors[n_segs-1],normals[n_segs-1]) if d[2]>0: f=-1 else: f=1 depth_vectors.append(f*depths[n_segs]*d/numpy.linalg.norm(d)) bottom_polyline=[ top_polyline[i]+depth_vectors[i] for i in range(n_segs+1) ] # # calculate offsets if required: # if w0_offsets is None: w0_offsets=[0.] for i in range(n_segs): if self.getDim()==3: w0_offsets.append(w0_offsets[-1]+(float(numpy.linalg.norm(bottom_polyline[i+1]-bottom_polyline[i]))+ls[i])/2.) else: w0_offsets.append(w0_offsets[-1]+ls[i]) w0_max=max(w0_offsets) if self.getDim()==3: self.__normals[tag]=normals self.__depth_vectors[tag]=depth_vectors self.__depths[tag]=depths self.__dips[tag]=dips self.__bottom[tag]=bottom_polyline self.__ls[tag]=ls self.__strikes[tag]=strikes self.__strike_vectors[tag]=strike_vectors self.__top[tag]=top_polyline self.__total_length[tag]=total_length self.__offsets[tag]=w0_offsets if self.getDim()==2: self.__medDepth[tag]=0. else: self.__medDepth[tag]=sum([ numpy.linalg.norm(v) for v in depth_vectors])/len(depth_vectors) if w1_max is None or self.getDim()==2: w1_max=self.__medDepth[tag] self.__w0_max[tag]=w0_max self.__w1_max[tag]=w1_max def getMaxValue(self,f, tol=es.sqrt(es.EPSILON)): """ returns the tag of the fault of where ``f`` takes the maximum value and a `Locator` object which can be used to collect values from `Data` class objects at the location where the minimum is taken. :param f: a distribution of values :type f: `escript.Data` :param tol: relative tolerance used to decide if point is on fault :type tol: ``tol`` :return: the fault tag the maximum is taken, and a `Locator` object to collect the value at location of maximum value. """ ref=-es.Lsup(f)*2 f_max=ref t_max=None loc_max=None x=f.getFunctionSpace().getX() for t in self.getTags(): p,m=self.getParametrization(x,tag=t, tol=tol) loc=((m*f)+(1.-m)*ref).internal_maxGlobalDataPoint() f_t=f.getTupleForGlobalDataPoint(*loc)[0] if f_t>f_max: f_max=f_t t_max=t loc_max=loc if loc_max is None: return None, None else: return t_max, pdt.Locator(x.getFunctionSpace(),x.getTupleForGlobalDataPoint(*loc_max)) def getMinValue(self,f, tol=es.sqrt(es.EPSILON)): """ returns the tag of the fault of where ``f`` takes the minimum value and a `Locator` object which can be used to collect values from `Data` class objects at the location where the minimum is taken. :param f: a distribution of values :type f: `escript.Data` :param tol: relative tolerance used to decide if point is on fault :type tol: ``tol`` :return: the fault tag the minimum is taken, and a `Locator` object to collect the value at location of minimum value. """ ref=es.Lsup(f)*2 f_min=ref t_min=None loc_min=None x=f.getFunctionSpace().getX() for t in self.getTags(): p,m=self.getParametrization(x,tag=t, tol=tol) loc=((m*f)+(1.-m)*ref).internal_minGlobalDataPoint() f_t=f.getTupleForGlobalDataPoint(*loc)[0] if f_t<f_min: f_min=f_t t_min=t loc_min=loc if loc_min is None: return None, None else: return t_min, pdt.Locator(x.getFunctionSpace(),x.getTupleForGlobalDataPoint(*loc_min)) def getParametrization(self,x,tag=None, tol=es.sqrt(es.EPSILON), outsider=None): """ returns the parametrization of the fault ``tag`` in the fault system. In fact the values of the parametrization for at given coordinates ``x`` is returned. In addition to the value of the parametrization a mask is returned indicating if the given location is on the fault with given tolerance ``tol``. Typical usage of the this method is dom=Domain(..) x=dom.getX() fs=FaultSystem() fs.addFault(tag=3,...) p, m=fs.getParametrization(x, outsider=0,tag=3) saveDataCSV('x.csv',p=p, x=x, mask=m) to create a file with the coordinates of the points in ``x`` which are on the fault (as ``mask=m``) together with their location ``p`` in the fault coordinate system. :param x: location(s) :type x: `escript.Data` object or ``numpy.array`` :param tag: the tag of the fault :param tol: relative tolerance to check if location is on fault. :type tol: ``float`` :param outsider: value used for parametrization values outside the fault. If not present an appropriate value is choosen. :type outsider: ``float`` :return: the coordinates ``x`` in the coordinate system of the fault and a mask indicating coordinates in the fault by 1 (0 elsewhere) :rtype: `escript.Data` object or ``numpy.array`` """ offsets=self.getW0Offsets(tag) w1_range=self.getW1Range(tag) w0_range=self.getW0Range(tag)[1]-self.getW0Range(tag)[0] if outsider is None: outsider=min(self.getW0Range(tag)[0],self.getW0Range(tag)[1])-abs(w0_range)/es.sqrt(es.EPSILON) if isinstance(x,list): x=numpy.array(x, numpy.double) updated=x[0]*0 if self.getDim()==2: # # p=x[0]*0 + outsider top=self.getTopPolyline(tag) for i in range(1,len(top)): d=top[i]-top[i-1] h=x-top[i-1] h_l=es.length(h) d_l=es.length(d) s=es.inner(h,d)/d_l**2 s=s*es.whereNonPositive(s-1.-tol)*es.whereNonNegative(s+tol) m=es.whereNonPositive(es.length(h-s*d)-tol*es.maximum(h_l,d_l))*(1.-updated) p=(1.-m)*p+m*(offsets[i-1]+(offsets[i]-offsets[i-1])*s) updated=es.wherePositive(updated+m) else: p=x[:2]*0 + outsider top=self.getTopPolyline(tag) bottom=self.getBottomPolyline(tag) n=self.getSegmentNormals(tag) for i in range(len(top)-1): h=x-top[i] R=top[i+1]-top[i] r=bottom[i+1]-bottom[i] D0=bottom[i]-top[i] D1=bottom[i+1]-top[i+1] s_upper=es.matrix_mult(numpy.linalg.pinv(numpy.vstack((R,D1)).T),h) s_lower=es.matrix_mult(numpy.linalg.pinv(numpy.vstack((r,D0)).T),h) m_ul=es.wherePositive(s_upper[0]-s_upper[1]) s=s_upper*m_ul+s_lower*(1-m_ul) s0=s[0] s1=s[1] m=es.whereNonNegative(s0+tol)*es.whereNonPositive(s0-1.-tol)*es.whereNonNegative(s1+tol)*es.whereNonPositive(s1-1.-tol) s0=s0*m s1=s1*m atol=tol*es.maximum(es.length(h),es.length(top[i]-bottom[i+1])) m=es.whereNonPositive(es.length(h-s0*R-s1*D1)*m_ul+(1-m_ul)*es.length(h-s0*r-s1*D0)-atol) p[0]=(1.-m)*p[0]+m*(offsets[i]+(offsets[i+1]-offsets[i])*s0) p[1]=(1.-m)*p[1]+m*(w1_range[1]+(w1_range[0]-w1_range[1])*s1) updated=es.wherePositive(updated+m) return p, updated def getSideAndDistance(self,x,tag=None): """ returns the side and the distance at ``x`` from the fault ``tag``. :param x: location(s) :type x: `escript.Data` object or ``numpy.array`` :param tag: the tag of the fault :return: the side of ``x`` (positive means to the right of the fault, negative to the left) and the distance to the fault. Note that a value zero for the side means that that the side is undefined. """ d=None side=None if self.getDim()==2: mat=numpy.array([[0., 1.], [-1., 0.] ]) s=self.getTopPolyline(tag) for i in range(1,len(s)): q=(s[i]-s[i-1]) h=x-s[i-1] q_l=es.length(q) qt=es.matrixmult(mat,q) # orthogonal direction t=es.inner(q,h)/q_l**2 t=es.maximum(es.minimum(t,1,),0.) p=h-t*q dist=es.length(p) lside=es.sign(es.inner(p,qt)) if d is None: d=dist side=lside else: m=es.whereNegative(d-dist) m2=es.wherePositive(es.whereZero(abs(lside))+m) d=dist*(1-m)+d*m side=lside*(1-m2)+side*m2 else: ns=self.getSegmentNormals(tag) top=self.getTopPolyline(tag) bottom=self.getBottomPolyline(tag) for i in range(len(top)-1): h=x-top[i] R=top[i+1]-top[i] r=bottom[i+1]-bottom[i] D0=bottom[i]-top[i] D1=bottom[i+1]-top[i+1] s_upper=es.matrix_mult(numpy.linalg.pinv(numpy.vstack((R,D1)).T),h) s_lower=es.matrix_mult(numpy.linalg.pinv(numpy.vstack((r,D0)).T),h) m_ul=es.wherePositive(s_upper[0]-s_upper[1]) s=s_upper*m_ul+s_lower*(1-m_ul) s=es.maximum(es.minimum(s,1.),0) p=h-(m_ul*R+(1-m_ul)*r)*s[0]-(m_ul*D1+(1-m_ul)*D0)*s[1] dist=es.length(p) lside=es.sign(es.inner(p,ns[i])) if d is None: d=dist side=lside else: m=es.whereNegative(d-dist) m2=es.wherePositive(es.whereZero(abs(lside))+m) d=dist*(1-m)+d*m side=lside*(1-m2)+side*m2 return side, d
37.803231
305
0.595284
3,880
25,744
3.862113
0.106186
0.015682
0.018018
0.010277
0.445245
0.389456
0.363764
0.335269
0.305706
0.292759
0
0.022846
0.26379
25,744
680
306
37.858824
0.767794
0.361793
0
0.338462
0
0
0.050321
0
0
0
0
0
0
1
0.066667
false
0
0.012821
0
0.164103
0.002564
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15d2546aeaf271239203d19ad3ebcd6e67edaf83
9,680
py
Python
acs/acs/Core/FileParsingManager.py
wangji1/test-framework-and-suites-for-android
59564f826f205fe7fab64f45b88b1a6dde6900af
[ "Apache-2.0" ]
null
null
null
acs/acs/Core/FileParsingManager.py
wangji1/test-framework-and-suites-for-android
59564f826f205fe7fab64f45b88b1a6dde6900af
[ "Apache-2.0" ]
null
null
null
acs/acs/Core/FileParsingManager.py
wangji1/test-framework-and-suites-for-android
59564f826f205fe7fab64f45b88b1a6dde6900af
[ "Apache-2.0" ]
null
null
null
""" :copyright: (c)Copyright 2013, Intel Corporation All Rights Reserved. The source code contained or described here in and all documents related to the source code ("Material") are owned by Intel Corporation or its suppliers or licensors. Title to the Material remains with Intel Corporation or its suppliers and licensors. The Material contains trade secrets and proprietary and confidential information of Intel or its suppliers and licensors. The Material is protected by worldwide copyright and trade secret laws and treaty provisions. No part of the Material may be used, copied, reproduced, modified, published, uploaded, posted, transmitted, distributed, or disclosed in any way without Intel's prior express written permission. No license under any patent, copyright, trade secret or other intellectual property right is granted to or conferred upon you by disclosure or delivery of the Materials, either expressly, by implication, inducement, estoppel or otherwise. Any license under such intellectual property rights must be express and approved by Intel in writing. :organization: INTEL MCG PSI :summary: Implements file parsing manager :since: 05/03/2013 :author: vdechefd """ import os import lxml.etree as et from acs.ErrorHandling.AcsConfigException import AcsConfigException from acs.Core.Report.ACSLogging import LOGGER_FWK from acs.Core.PathManager import Paths import acs.UtilitiesFWK.Utilities as Utils class FileParsingManager: """ FileParsingManager This class implements the File Parsing Manager. This manager takes XML files as inputs and parses them into dictionaries. It will parse: - use case catalog - bench config - equipment catalog - campaign """ def __init__(self, bench_config_name, equipment_catalog, global_config): self._file_extention = ".xml" self._execution_config_path = Paths.EXECUTION_CONFIG self._equipment_catalog_path = Paths.EQUIPMENT_CATALOG self._bench_config_name = (bench_config_name if os.path.isfile(bench_config_name) else os.path.join(self._execution_config_path, bench_config_name + self._file_extention)) self._equipment_catalog_name = equipment_catalog + self._file_extention self._global_config = global_config self._ucase_catalogs = None self._logger = LOGGER_FWK def parse_bench_config(self): """ This function parses the bench config XML file into a dictionary. """ def __parse_node(node): """ This private function parse a node from bench_config parsing. :rtype: dict :return: Data stocked into a dictionnary. """ dico = {} name = node.get('name', "") if name: # store all keys (except 'name')/value in a dict for key in [x for x in node.attrib if x != "name"]: dico[key] = node.attrib[key] node_list = node.xpath('./*') if node_list: for node_item in node_list: name = node_item.get('name', "") if name: dico[name] = __parse_node(node_item) return dico def __parse_bench_config(document): """ Last version of function parsing bench_config adapted for Multiphone. :type document: object :param document: xml document parsed by etree :rtype: dict :return: Data stocked into a dictionary. """ # parse bench_config (dom method) bench_config = {} node_list = document.xpath('/BenchConfig/*/*') for node in node_list: name = node.get('name', "") if name: bench_config[name] = __parse_node(node) return bench_config # body of the parse_bench_config() function. if not os.path.isfile(self._bench_config_name): error_msg = "Bench config file : %s does not exist" % self._bench_config_name raise AcsConfigException(AcsConfigException.FILE_NOT_FOUND, error_msg) try: document = et.parse(self._bench_config_name) except et.XMLSyntaxError: _, error_msg, _ = Utils.get_exception_info() error_msg = "{}; {}".format(self._bench_config_name, error_msg) raise AcsConfigException(AcsConfigException.XML_PARSING_ERROR, error_msg) result = __parse_bench_config(document) bench_config_parameters = Utils.BenchConfigParameters(dictionnary=result, bench_config_file=self._bench_config_name) return bench_config_parameters def parse_equipment_catalog(self): """ This function parses the equipment catalog XML file into a dictionary. """ # Instantiate empty dictionaries eqt_type_dic = {} # Get the xml doc equipment_catalog_path = os.path.join(self._equipment_catalog_path, self._equipment_catalog_name) if not os.path.isfile(equipment_catalog_path): error_msg = "Equipment catalog file : %s does not exist" % equipment_catalog_path raise AcsConfigException(AcsConfigException.FILE_NOT_FOUND, error_msg) try: equipment_catalog_doc = et.parse(equipment_catalog_path) except et.XMLSyntaxError: _, error_msg, _ = Utils.get_exception_info() error_msg = "{}; {}".format(equipment_catalog_path, error_msg) raise AcsConfigException(AcsConfigException.XML_PARSING_ERROR, error_msg) root_node = equipment_catalog_doc.xpath('/Equipment_Catalog') if not root_node: raise AcsConfigException(AcsConfigException.FILE_NOT_FOUND, "Wrong XML: could not find expected document root node: " "'Equipment_Catalog'") # Parse EquipmentTypes list_eq_types = root_node[0].xpath('./EquipmentType') for eq_type in list_eq_types: eqt_type_dic.update(self._load_equipment_type(eq_type)) self._global_config.equipmentCatalog = eqt_type_dic.copy() def _load_equipment_type(self, node): """ This function parses an "EquipmentType" XML Tag into a dictionary :type node: Etree node :param node: the "EquipmentType" node :rtype dic: dict :return: a dictionary of equipment """ dic = {} eqt_type_name = node.get("name", "") if eqt_type_name: dic[eqt_type_name] = self._load_equipments(node) return dic def _load_equipments(self, node): """ This function parses "Equipment" XML Tags into a dictionary :type node: Etree node :param node: the node containing "Equipment" nodes """ # Get common equipment type parameters dic = {} dic.update(self._get_parameters(node)) eqt_nodes = node.xpath('./Equipment') for sub_node in eqt_nodes: eqt_model = sub_node.get("name", "") if eqt_model: dic[eqt_model] = self._get_parameters(sub_node) dic[eqt_model].update(self._load_transport(sub_node)) dic[eqt_model].update(self._load_features(sub_node)) dic[eqt_model].update(self._load_controllers(sub_node)) return dic def _load_transport(self, node): """ This function parses a "Transport" XML Tags from a node into a dictionary :type node: DOM node :param node: the node from which to get all parameters value :rtype dic: dict :return: a dictionary of transports """ dic = {} transport_node = node.xpath('./Transports') if transport_node: dic["Transports"] = self._get_parameters(transport_node[0]) return dic def _load_controllers(self, node): """ This function parses a "Controllers" XML Tags from a node into a dictionary :type node: DOM node :param node: the node from which to get all parameters value :rtype dic: dict :return: the dictionary of controllers """ dic = {} transport_node = node.xpath('./Controllers') if transport_node: dic["Controllers"] = self._get_parameters(transport_node[0]) return dic def _load_features(self, node): """ This function parses a "Features" XML Tags from a node into a dictionary :type node: Element node :param node: the node from which to get all parameters value :rtype dic: dict :return: a dictionary of features """ dic = {} transport_node = node.xpath('./Features') if transport_node: dic["Features"] = self._get_parameters(transport_node[0]) return dic def _get_parameters(self, node): """ This function parses all "Parameter" XML Tags from a node into a dictionary :type node: Element node :param node: the node from which to get all parameters value :rtype dic: dict :return: a dictionary of parameters """ dic = {} parameters = node.xpath('./Parameter') for parameter in parameters: name = parameter.get("name", "") value = parameter.get("value", "") if name: dic[name] = value return dic
36.946565
119
0.630785
1,135
9,680
5.171806
0.21674
0.048722
0.028109
0.022658
0.36184
0.273765
0.235945
0.207496
0.191141
0.16201
0
0.002343
0.294421
9,680
261
120
37.088123
0.857101
0.335537
0
0.262712
0
0
0.05807
0
0
0
0
0
0
1
0.09322
false
0
0.050847
0
0.228814
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15d53e64696bdcd31c356310ca351fd13adec82e
2,256
py
Python
Chapter 16/excel_to_csv.py
ostin-r/automate-boring-stuff-solutions
78f0a2981e6520ff2907285e666168a0f35eba02
[ "FTL" ]
4
2021-06-14T10:37:58.000Z
2021-12-30T17:49:17.000Z
Chapter 16/excel_to_csv.py
ostin-r/automate-boring-stuff-solutions
78f0a2981e6520ff2907285e666168a0f35eba02
[ "FTL" ]
null
null
null
Chapter 16/excel_to_csv.py
ostin-r/automate-boring-stuff-solutions
78f0a2981e6520ff2907285e666168a0f35eba02
[ "FTL" ]
1
2021-07-29T15:26:54.000Z
2021-07-29T15:26:54.000Z
''' Austin Richards 4/14/21 excel_to_csv.py automates the conversion of many xlsx files into csv files. This program names the csv file in the format <filename>_<sheetname>.csv ''' import logging import os, csv, openpyxl from pathlib import Path from openpyxl.utils import get_column_letter logging.basicConfig(level=logging.DEBUG, format='%(asctime)s: %(message)s') def get_all_paths(directory): ''' returns all paths in a directory (and it's sub-directories) in a list type ''' file_paths = [] for path, dirs, files in os.walk(directory): for filename in files: filepath = os.path.join(path, filename) file_paths.append(filepath) return file_paths def excel_to_csv(directory): # get the absolute path, make a folder within it to save converted files, get files to convert directory = os.path.abspath(directory) new_dir = os.path.join(directory, 'converted_csv_files') os.makedirs(new_dir, exist_ok=True) all_paths = [path for path in get_all_paths(directory) if path.endswith('.xlsx')] for excel_file in all_paths: workbook = openpyxl.load_workbook(excel_file) excel_filename = Path(excel_file).stem print(f'copying {excel_filename}...') for sheet_name in workbook.sheetnames: print(f' copying {sheet_name}...') # create a csv filename with the excel filename and sheetname, put in new folder csv_filename = f'{excel_filename}_{sheet_name}.csv' csv_filepath = os.path.join(new_dir, csv_filename) new_file = open(csv_filepath, 'w', newline='') csv_writer = csv.writer(new_file) # get data from the xlsx file and write it to the new csv sheet = workbook[sheet_name] for row_num in range(1, sheet.max_row + 1): row_data = [] for col_num in range(1, sheet.max_column + 1): col_letter = get_column_letter(col_num) row_data.append(sheet[col_letter + str(row_num)].value) # write data to the new csv csv_writer.writerow(row_data) new_file.close() print('files copied.') excel_to_csv('Chapter 16')
35.25
98
0.649379
318
2,256
4.424528
0.339623
0.028429
0.021322
0.028429
0.027008
0.027008
0
0
0
0
0
0.006579
0.258865
2,256
64
99
35.25
0.834928
0.223404
0
0
0
0
0.092281
0.019153
0
0
0
0
0
1
0.054054
false
0
0.108108
0
0.189189
0.081081
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15d571532daed68e7ee3f7aca094467594fa8bdd
2,041
py
Python
kg/diff/templates/real_abs_rel_template.py
kevinsogo/compgen
c765fdb3008d41f409836a45ad5a506db6a99e74
[ "MIT" ]
6
2019-11-30T17:03:13.000Z
2021-09-30T05:08:31.000Z
kg/diff/templates/real_abs_rel_template.py
kevinsogo/compgen
c765fdb3008d41f409836a45ad5a506db6a99e74
[ "MIT" ]
1
2020-01-20T12:13:03.000Z
2020-01-20T12:13:03.000Z
kg/diff/templates/real_abs_rel_template.py
kevinsogo/compgen
c765fdb3008d41f409836a45ad5a506db6a99e74
[ "MIT" ]
null
null
null
# Checks for an XXX error ### @replace "XXX", ('absolute/relative' if has_rel else 'absolute') # with an error of at most 1e-XXX ### @replace "XXX", prec # Don't edit this file. Edit real_abs_rel_template.py instead, and then run _real_check_gen.py # Oh, actually, you're editing the correct file. Go on. ### @if False raise Exception("You're not supposed to run this!!!") ### @if False from itertools import zip_longest from decimal import Decimal, InvalidOperation from kg.checkers import * ### @keep @import EPS = 0 ### @replace 0, f"Decimal('1e-{prec}')" EPS *= 1+Decimal('1e-5') # add some leniency @set_checker() @default_score def checker(input_file, output_file, judge_file, **kwargs): worst = 0 for line1, line2 in zip_longest(output_file, judge_file): if (line1 is None) != (line2 is None): raise WA("Unequal number of lines") p1 = line1.rstrip().split(" ") p2 = line2.rstrip().split(" ") if len(p1) != len(p2): raise WA("Incorrect number of values in line") for v1, v2 in zip(p1, p2): if v1 != v2: # they're different as tokens. try considering them as numbers try: err = error(Decimal(v1), Decimal(v2)) ### @replace "error", "abs_rel_error" if has_rel else "abs_error" except InvalidOperation: raise WA(f"Unequal tokens that are not numbers: {v1!r} != {v2!r}") worst = max(worst, err) if err > EPS: print('Found an error of', worst) ### @keep @if format not in ('hr', 'cms') raise WA("Bad precision.") print('Worst error:', worst) ### @keep @if format not in ('pg', 'hr', 'cms') help_ = ('Compare if two sequences of real numbers are "close enough" (by XXX). ' ### @replace 'XXX', '1e-' + str(prec) "Uses XXX error.") ### @replace 'XXX', 'absolute/relative' if has_rel else 'absolute' if __name__ == '__main__': chk(help=help_)
52.333333
123
0.588437
283
2,041
4.134276
0.45583
0.034188
0.020513
0.030769
0.129915
0.129915
0.092308
0.092308
0.092308
0.092308
0
0.019555
0.273395
2,041
38
124
53.710526
0.769386
0.353748
0
0
0
0
0.223612
0
0
0
0
0
0
1
0.034483
false
0
0.103448
0
0.137931
0.068966
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15d5daf61123ba5cf4f2cb454d6eaf622ef68705
1,099
py
Python
osspeak/recognition/actions/library/process.py
OSSpeak/OSSpeak
327c38a37684165f87bf8d76ab2ca135b43b8ab7
[ "MIT" ]
1
2020-03-17T10:24:41.000Z
2020-03-17T10:24:41.000Z
osspeak/recognition/actions/library/process.py
OSSpeak/OSSpeak
327c38a37684165f87bf8d76ab2ca135b43b8ab7
[ "MIT" ]
12
2016-09-28T05:16:00.000Z
2020-11-27T22:32:40.000Z
osspeak/recognition/actions/library/process.py
OSSpeak/OSSpeak
327c38a37684165f87bf8d76ab2ca135b43b8ab7
[ "MIT" ]
null
null
null
import time import os import subprocess import threading class ProcessHandler: def __init__(self, *args, on_output=None): self.process = subprocess.Popen(args, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True) self.on_output = on_output self.start_stdout_listening() def send_message(self, msg): if not isinstance(msg, bytes): msg = msg.encode('utf8') if not msg.endswith(b'\n'): msg += b'\n' self.process.stdin.write(msg) try: self.process.stdin.flush() except OSError: print(f'Process {self} already closed') def dispatch_process_output(self): for line in self.process.stdout: line = line.decode('utf8') self.on_output(line) def start_stdout_listening(self): t = threading.Thread(target=self.dispatch_process_output, daemon=True) t.start() def run(s): proc = ProcessHandler(s) return proc def run_sync(s): return subprocess.run(s, shell=True).stdout
28.179487
78
0.626934
138
1,099
4.862319
0.427536
0.04769
0.035768
0
0
0
0
0
0
0
0
0.002481
0.266606
1,099
39
79
28.179487
0.830025
0
0
0
0
0
0.037273
0
0
0
0
0
0
1
0.1875
false
0
0.125
0.03125
0.40625
0.03125
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15d6695d5c93e5916f4ed45db19a2876ea82e9ee
977
py
Python
setup.py
haaspt/whatsnew
0524ad2b6132593282946073f2d647ea0ce960e8
[ "MIT" ]
2
2015-09-02T21:14:26.000Z
2015-09-02T22:23:04.000Z
setup.py
haaspt/whatsnew
0524ad2b6132593282946073f2d647ea0ce960e8
[ "MIT" ]
2
2018-01-02T00:54:49.000Z
2018-01-02T00:56:01.000Z
setup.py
haaspt/whatsnew
0524ad2b6132593282946073f2d647ea0ce960e8
[ "MIT" ]
null
null
null
import os from setuptools import setup readme = open('README.md').read() requirements = ['click', 'feedparser', 'beautifulsoup4'] setup( name = "whatsnew", version = "0.13", author = "Patrick Tyler Haas", author_email = "patrick.tyler.haas@gmail.com", description = ("A lightweight, convenient tool to get an overview of the day's headlines right from your command line."), license = "MIT", keywords = "", url = "https://github.com/haaspt/whatsnew", scripts=['main.py', 'newsfeeds.py', 'config.py'], install_requires=requirements, long_description=readme, entry_points = { 'console_scripts': [ 'whatsnew = main:main' ], }, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 3.6', ], )
29.606061
125
0.602866
102
977
5.72549
0.784314
0.041096
0.054795
0
0
0
0
0
0
0
0
0.009615
0.254862
977
32
126
30.53125
0.792582
0
0
0.068966
0
0.034483
0.47697
0.028659
0
0
0
0
0
1
0
false
0
0.068966
0
0.068966
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15da0373b1191b0c411cc06fa6774cfb3700fb3a
2,880
py
Python
Flask-Server/timeswitch/server.py
weichweich/pi-timeswitch
c4428783fbf8b2294f7a6f55c312beeabae94d6f
[ "MIT" ]
4
2015-10-12T19:13:22.000Z
2018-07-18T17:55:48.000Z
Flask-Server/timeswitch/server.py
weichweich/pi-timeswitch
c4428783fbf8b2294f7a6f55c312beeabae94d6f
[ "MIT" ]
null
null
null
Flask-Server/timeswitch/server.py
weichweich/pi-timeswitch
c4428783fbf8b2294f7a6f55c312beeabae94d6f
[ "MIT" ]
2
2017-04-25T16:19:09.000Z
2022-01-24T08:15:12.000Z
import argparse import logging import sys from timeswitch.switch.manager import SwitchManager from timeswitch.app import setup_app from timeswitch.api import setup_api from timeswitch.model import setup_model # ###################################### # # parsing commandline args # ###################################### def parse_arguments(): PARSER = argparse.ArgumentParser(description='Timeswitch for the\ GPIOs of an Raspberry Pi with a webinterface.') PARSER.add_argument('-f', '--file', dest='schedule_file', metavar='file', type=str, required=True, help='A JSON-file containing the schedule.') PARSER.add_argument('--debug', action='store_true', help='A JSON-file containing the schedule.') PARSER.add_argument('--create', dest='create', action='store_true', help='Creates a new database. DELETES ALL DATA!!') PARSER.add_argument('--manager', dest='manager', action='store_true', help='Start the manager which switches the GPIOs at specified times.') PARSER.add_argument('--static', dest='static_dir', metavar='file', type=str, help='Folder with static files to serve') return PARSER.parse_args() # ###################################### # # Logging: # ###################################### def setup_logger(debug=True): # set up logging to file - see previous section for more details logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-20s \ %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename='piSwitch.log', filemode='a') # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() if debug: console.setLevel(logging.DEBUG) else: console.setLevel(logging.INFO) # set a format which is simpler for console use formatter = logging.Formatter('%(levelname)-8s:%(name)-8s:%(message)s') # tell the handler to use this format console.setFormatter(formatter) # add the handler to the root logger logging.getLogger('').addHandler(console) def start(cmd_args, app, switch_model): switch_manager = None if cmd_args.manager: switch_manager = SwitchManager(switch_model) switch_manager.start() try: app.run(debug=cmd_args.debug) finally: if cmd_args.manager: switch_manager.stop() def main(): cmd_args = parse_arguments() setup_logger(cmd_args.debug) app = setup_app(static_folder=cmd_args.static_dir, static_url_path='') model = setup_model(app) _ = setup_api(app, model) start(cmd_args, app, model) if __name__ == '__main__': main()
32
94
0.601389
329
2,880
5.118541
0.386018
0.033254
0.050475
0.033848
0.099762
0.099762
0.065321
0.065321
0.065321
0.065321
0
0.002291
0.242361
2,880
89
95
32.359551
0.769478
0.100347
0
0.071429
0
0
0.162196
0.015683
0
0
0
0
0
1
0.071429
false
0
0.125
0
0.214286
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15db2920ca4b3d1d42695dca0b6816fa94b0f30d
12,055
py
Python
utils/videoloader.py
mie-lab/traffic4cast
aea6f90e8884c01689c84255c99e96d2b58dc470
[ "Apache-2.0" ]
8
2020-07-26T20:54:58.000Z
2022-03-01T14:36:13.000Z
utils/videoloader.py
mie-lab/traffic4cast
aea6f90e8884c01689c84255c99e96d2b58dc470
[ "Apache-2.0" ]
null
null
null
utils/videoloader.py
mie-lab/traffic4cast
aea6f90e8884c01689c84255c99e96d2b58dc470
[ "Apache-2.0" ]
5
2019-11-05T09:46:01.000Z
2021-01-24T04:42:53.000Z
import sys, os, time from pathlib import Path import pickle import datetime as dt import glob import h5py import numpy as np from matplotlib import pyplot as plt from multiprocessing import Pool from functools import partial import torch from torchvision import datasets, transforms def subsample(x, n=0, m=200): return x[..., n:m, n:m] def _get_tstamp_string(tstamp_ix): """Calculates the timestamp in hh:mm based on the file index Args: tstamp_ix (int): Index of the single frame Returns: Str: hh:mm """ total_minutes = tstamp_ix*5 hours = total_minutes // 60 minutes = total_minutes % 60 return hours, minutes class trafic4cast_dataset(torch.utils.data.Dataset): """Dataloader for trafic4cast data Attributes: compression (TYPE): Description do_precomp_path (TYPE): Description num_frames (TYPE): Description reduce (TYPE): Description source_root (TYPE): Description split_type (TYPE): Description target_file_paths (TYPE): Description target_root (TYPE): Description transform (TYPE): Description valid_test_clips (TYPE): Description """ def __init__(self, source_root, target_root="precomuted_data", split_type='train', cities=['Berlin', 'Istanbul', 'Moscow'], transform=None, reduce=False, compression=None, num_frames=15, do_subsample=None, filter_test_times=False, return_features=False, return_city=False): """Dataloader for the trafic4cast competition Usage Dataloader: The dataloader is situated in "videoloader.py", to use it, you have to download the competition data and set two paths. "source_root" and "target_root". source_root: Is the directory with the raw competition data. The expected file structure is shown below. target_root: This directory will be used to store the preprocessed data (about 200 GB) Expected folder structure for raw data: -source_root - Berlin -Berlin_test -Berlin_training -Berlin_validation -Istanbul -Instanbul_test -… -Moscow -… Args: source_root (str): Is the directory with the raw competition data. target_root (str, optional): This directory will be used to store the preprocessed data split_type (str, optional): Can be ['training', 'validation', 'test'] cities (list, optional): This can be used to limit the data loader to a subset of cities. Has to be a list! Default is ['Berlin', 'Moscow', 'Istanbul'] transform (None, optional): Transform applied to x before returning it. reduce (bool, optional): This option collapses the time dimension into the (color) channel dimension. compression (str, optional): The h5py compression method to store the preprocessed data. 'compression=None' is the fastest. num_frames (int, optional): do_subsample (tuple, optional): Tuple of two integers. Returns only a part of the image. Slices the image in the 'pixel' dimensions with x = x[n:m, n:m]. with m>n filter_test_times (bool, optional): Filters output data, such that only valid (city-dependend) test-times are returned. """ self.reduce = reduce self.source_root = source_root self.target_root = target_root self.transform = transform self.split_type = split_type self.compression = compression self.cities = cities self.num_frames = num_frames self.subsample = False self.filter_test_times = filter_test_times self.return_features = return_features self.return_city = return_city if self.filter_test_times: tt_dict2 = {} tt_dict = pickle.load(open(os.path.join('.', 'utils', 'test_timestamps.dict'), "rb")) for city, values in tt_dict.items(): values.sort() tt_dict2[city] = values self.valid_test_times = tt_dict2 if do_subsample is not None: self.subsample = True self.n = do_subsample[0] self.m = do_subsample[1] source_file_paths = [] for city in cities: source_file_paths = source_file_paths + glob.glob( os.path.join(self.source_root, city, '*_' + self.split_type, '*.h5')) do_precomp_path = [] missing_target_files = [] for raw_file_path in source_file_paths: target_file = raw_file_path.replace( self.source_root, self.target_root) if not os.path.exists(target_file): do_precomp_path.append(raw_file_path) missing_target_files.append(target_file) self.do_precomp_path = do_precomp_path target_dirs = list(set([str(Path(x).parent) for x in missing_target_files])) for target_dir in target_dirs: if not os.path.exists(target_dir): os.makedirs(target_dir) with Pool() as pool: pool.map(self.precompute_clip, self.do_precomp_path) pool.close() pool.join() target_file_paths = [] for city in cities: target_file_paths = target_file_paths + glob.glob( os.path.join(self.target_root, city, '*_' + self.split_type, '*.h5')) self.target_file_paths = target_file_paths if self.split_type == 'test': precomp_readt_test = partial(self.precompute_clip, mode='reading_test') with Pool() as pool: valid_test_clips = pool.map(precomp_readt_test, self.target_file_paths) pool.close() pool.join() valid_test_clips = [valid_tuple for sublist in valid_test_clips for valid_tuple in sublist] valid_test_clips.sort() self.valid_test_clips = valid_test_clips def precompute_clip(self, source_path, mode='writing'): """Summary Args: source_path (TYPE): Description mode (str, optional): Description Returns: TYPE: Description """ target_path = source_path.replace(self.source_root, self.target_root) f_source = h5py.File(source_path, 'r') data1 = f_source['array'] data1 = data1[:] if mode == 'writing': data1 = np.moveaxis(data1, 3, 1) f_target = h5py.File(target_path, 'w') dset = f_target.create_dataset('array', (288, 3, 495, 436), chunks=(1, 3, 495, 436), dtype='uint8', data=data1, compression=self.compression) f_target.close() if mode == 'reading_test': valid_test_clips = list = [] for tstamp_ix in range(288-15): clip = data1[tstamp_ix:tstamp_ix+self.num_frames, :, :, :] sum_first_train_frame = np.sum(clip[0, :, :, :]) sum_last_train_frame = np.sum(clip[11, :, :, :]) if (sum_first_train_frame != 0) and (sum_last_train_frame != 0): valid_test_clips.append((source_path, tstamp_ix)) f_source.close() if mode == 'reading_test': return valid_test_clips def __len__(self): if self.split_type == 'test': pass return len(self.valid_test_clips) elif self.filter_test_times: return len(self.target_file_paths) * 5 else: return len(self.target_file_paths) * 272 def __getitem__(self, idx): """Summary Args: idx (TYPE): Description Returns: TYPE: Description """ return_dict = {} if torch.is_tensor(idx): idx = idx.tolist() if self.split_type == 'test': target_file_path, tstamp_ix = self.valid_test_clips[idx] elif self.filter_test_times: file_ix = idx // 5 valid_tstamp_ix = idx % 5 target_file_path = self.target_file_paths[file_ix] city_name_path = Path(target_file_path.replace(self.target_root,'')) city_name = city_name_path.parts[1] tstamp_ix = self.valid_test_times[city_name][valid_tstamp_ix] else: file_ix = idx // 272 tstamp_ix = idx % 272 target_file_path = self.target_file_paths[file_ix] if self.return_features: # create feature vector date_string = Path(target_file_path).name.split('_')[0] date_datetime = dt.datetime.strptime(date_string, '%Y%m%d') hour, minute = _get_tstamp_string(tstamp_ix) # feature_vector = [] sin_hours = np.sin(2*np.pi/24 * hour) cos_hours = np.cos(2*np.pi/24 * hour) sin_mins = np.sin(2*np.pi/60 * minute) cos_mins = np.cos(2*np.pi/60 * minute) sin_month = np.sin(2*np.pi/12 * date_datetime.month) cos_month = np.cos(2*np.pi/12 * date_datetime.month) weekday_ix = date_datetime.weekday() / 6 week_number = date_datetime.isocalendar()[1] / 52 feature_vector = np.asarray([sin_hours, cos_hours, sin_mins, cos_mins, sin_month, cos_month, weekday_ix, week_number]).ravel() feature_vector = torch.from_numpy(feature_vector) feature_vector = feature_vector.to(dtype=torch.float) return_dict['feature_vector'] = feature_vector if self.return_city: city_name_path = Path(target_file_path.replace(self.target_root,'')) city_name = city_name_path.parts[1] return_dict['city_names'] = city_name # we want to predict the image at idx+1 based on the image with idx f = h5py.File(target_file_path, 'r') sample = f.get('array') x = sample[tstamp_ix:tstamp_ix+12, :, :, :] y = sample[tstamp_ix+12:tstamp_ix+15, :, :, :] if self.reduce: # stack all time dimensions into the channels. # all channels of the same timestamp are left togehter x = np.moveaxis(x, (0, 1), (2, 3)) x = np.reshape(x, (495, 436, 36)) x = torch.from_numpy(x) x = x.permute(2, 0, 1) # Dimensions: time/channels, h, w y = np.moveaxis(y, (0, 1), (2, 3)) y = np.reshape(y, (495, 436, 9)) y = torch.from_numpy(y) y = y.permute(2, 0, 1) y = y.to(dtype=torch.float) # is ByteTensor? x = x.to(dtype=torch.float) # is ByteTensor? else: x = torch.from_numpy(x) y = torch.from_numpy(y) y = y.to(dtype=torch.float) # is ByteTensor? x = x.to(dtype=torch.float) # is ByteTensor? f.close() if self.subsample: x = subsample(x,self.n,self.m) y = subsample(y,self.n,self.m) if self.transform is not None: x = self.transform(x) return x, y, return_dict
34.942029
132
0.555454
1,436
12,055
4.443593
0.194986
0.03291
0.026328
0.017866
0.226297
0.156872
0.118163
0.105313
0.071149
0.058925
0
0.018006
0.355039
12,055
345
133
34.942029
0.801929
0.233513
0
0.181818
0
0
0.022516
0
0
0
0
0
0
1
0.032086
false
0.005348
0.064171
0.005348
0.139037
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15dd1eeb2fac5589a59d8aeda6e5e6d37752563e
2,369
py
Python
foundation/correspondence/views/letter.py
pilnujemy/foundation-manager
1f1d6afcbb408c87a171bcbe3f9e58570eb478b6
[ "BSD-3-Clause" ]
1
2016-01-04T06:30:24.000Z
2016-01-04T06:30:24.000Z
foundation/correspondence/views/letter.py
pilnujemy/foundation-manager
1f1d6afcbb408c87a171bcbe3f9e58570eb478b6
[ "BSD-3-Clause" ]
36
2015-11-27T14:17:34.000Z
2016-07-14T10:23:52.000Z
foundation/correspondence/views/letter.py
pilnujemy/foundation-manager
1f1d6afcbb408c87a171bcbe3f9e58570eb478b6
[ "BSD-3-Clause" ]
1
2016-05-14T01:11:28.000Z
2016-05-14T01:11:28.000Z
from django.views.generic import DeleteView, DetailView, UpdateView, CreateView from django.forms.models import BaseInlineFormSet from django.forms.models import inlineformset_factory from braces.views import LoginRequiredMixin, UserFormKwargsMixin, SelectRelatedMixin from ..models import Letter, Attachment from ..forms import LetterForm from ..filters import LetterFilter from .mixins import (InitialFormMixin, CreateFormMessagesMixin, UpdateFormMessagesMixin, DeletedMessageMixin, CreateFormsetView, UpdateFormsetView) from ..forms import AttachmentForm from django_filters.views import FilterView from crispy_forms.helper import FormHelper from django.core.urlresolvers import reverse class FormsetHelper(FormHelper): form_tag = False form_method = 'post' class TableInlineHelper(FormsetHelper): template = 'bootstrap/table_inline_formset.html' def formset_attachment_factory(form_formset=None, *args, **kwargs): if form_formset is None: class BaseAttachmentFormSet(BaseInlineFormSet): helper = TableInlineHelper() form_formset = BaseAttachmentFormSet return inlineformset_factory(Letter, Attachment, form=AttachmentForm, formset=form_formset, *args, **kwargs) AttachmentFormSet = formset_attachment_factory() class LetterDetailView(SelectRelatedMixin, DetailView): model = Letter select_related = ["created_by", "modified_by", "contact"] class LetterListView(SelectRelatedMixin, FilterView): model = Letter filterset_class = LetterFilter select_related = ["created_by", "modified_by", "contact", ] class LetterCreateView(LoginRequiredMixin, CreateFormMessagesMixin, UserFormKwargsMixin, InitialFormMixin, CreateFormsetView, CreateView): model = Letter form_class = LetterForm formset_class = {'attachment_form': AttachmentFormSet} class LetterDeleteView(DeletedMessageMixin, DeleteView): model = Letter def get_success_message(self): return self.object def get_success_url(self): return reverse('correspondence:contact_list') class LetterUpdateView(LoginRequiredMixin, UpdateFormMessagesMixin, UserFormKwargsMixin, UpdateFormsetView, UpdateView): model = Letter form_class = LetterForm formset_class = {'attachment_form': AttachmentFormSet}
34.333333
95
0.765724
217
2,369
8.202765
0.37788
0.02809
0.016854
0.023596
0.161798
0.131461
0.131461
0.131461
0.082022
0.082022
0
0
0.165893
2,369
68
96
34.838235
0.90081
0
0
0.183673
0
0
0.064162
0.026171
0
0
0
0
0
1
0.061224
false
0
0.244898
0.040816
0.857143
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
15de738d2ebcbbe25e92a2d8f2d43e4cb6af3d82
1,760
py
Python
pychunkedgraph/ingest/ingestion_utils.py
perlman/PyChunkedGraph
2c582f46a8292010e8f9f54c94c63af0b172bdad
[ "MIT" ]
null
null
null
pychunkedgraph/ingest/ingestion_utils.py
perlman/PyChunkedGraph
2c582f46a8292010e8f9f54c94c63af0b172bdad
[ "MIT" ]
null
null
null
pychunkedgraph/ingest/ingestion_utils.py
perlman/PyChunkedGraph
2c582f46a8292010e8f9f54c94c63af0b172bdad
[ "MIT" ]
null
null
null
import numpy as np from pychunkedgraph.backend import chunkedgraph, chunkedgraph_utils import cloudvolume def initialize_chunkedgraph(cg_table_id, ws_cv_path, chunk_size, cg_mesh_dir, fan_out=2, instance_id=None, project_id=None): """ Initalizes a chunkedgraph on BigTable :param cg_table_id: str name of chunkedgraph :param ws_cv_path: str path to watershed segmentation on Google Cloud :param chunk_size: np.ndarray array of three ints :param cg_mesh_dir: str mesh folder name :param fan_out: int fan out of chunked graph (2 == Octree) :param instance_id: str Google instance id :param project_id: str Google project id :return: ChunkedGraph """ ws_cv = cloudvolume.CloudVolume(ws_cv_path) bbox = np.array(ws_cv.bounds.to_list()).reshape(2, 3) # assert np.all(bbox[0] == 0) # assert np.all((bbox[1] % chunk_size) == 0) n_chunks = ((bbox[1] - bbox[0]) / chunk_size).astype(np.int) n_layers = int(np.ceil(chunkedgraph_utils.log_n(np.max(n_chunks), fan_out))) + 2 dataset_info = ws_cv.info dataset_info["mesh"] = cg_mesh_dir dataset_info["data_dir"] = ws_cv_path dataset_info["graph"] = {"chunk_size": [int(s) for s in chunk_size]} kwargs = {"table_id": cg_table_id, "chunk_size": chunk_size, "fan_out": np.uint64(fan_out), "n_layers": np.uint64(n_layers), "dataset_info": dataset_info, "is_new": True} if instance_id is not None: kwargs["instance_id"] = instance_id if project_id is not None: kwargs["project_id"] = project_id cg = chunkedgraph.ChunkedGraph(**kwargs) return cg
30.877193
84
0.64375
251
1,760
4.25498
0.318725
0.067416
0.029963
0.02809
0.031835
0
0
0
0
0
0
0.011416
0.253409
1,760
56
85
31.428571
0.80137
0.289205
0
0
0
0
0.084041
0
0
0
0
0
0
1
0.04
false
0
0.12
0
0.2
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15dec2f55095e3b6ec802c41f0cedadb58146312
2,691
py
Python
brew_gui.py
mburgess00/brew_controller
913e3b37b9421759db5186e5f0e44cf8f4fd7f6a
[ "Apache-2.0" ]
null
null
null
brew_gui.py
mburgess00/brew_controller
913e3b37b9421759db5186e5f0e44cf8f4fd7f6a
[ "Apache-2.0" ]
null
null
null
brew_gui.py
mburgess00/brew_controller
913e3b37b9421759db5186e5f0e44cf8f4fd7f6a
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 from guizero import App, Text, Slider, Combo, PushButton, Box, Picture pause = True def readsensors(): return {"hlt" : 160, "rims" : 152, "bk" : 75} def handlepause(): global pause global pauseState print("Pause Button pressed") if pause: print("running") pause = not pause pauseState.value=("Running") hltFlame.visible=True rimsFlame.visible=True bkFlame.visible=True else: print("pausing") pause = not pause pauseState.value=("Paused") hltFlame.visible=False rimsFlame.visible=False bkFlame.visible=False return app = App(title="Brew GUI", width=1280, height=768, layout="grid") vertPad = Picture(app, image="blank_vert.gif", grid=[0,0]) hltBox = Box(app, layout="grid", grid=[1,0]) hltPad = Picture(hltBox, image="blank.gif", grid=[0,0]) hltTitle = Text(hltBox, text="HLT", grid=[0,1], align="top") hltText = Text(hltBox, text="180", grid=[0,2], align="top") hltSlider = Slider(hltBox, start=212, end=100, horizontal=False, grid=[0,3], align="top") hltSlider.tk.config(length=500, width=50) hltFlamePad = Picture(hltBox, image="blank_flame.gif", grid=[0,4]) hltFlame = Picture(hltBox, image="flame.gif", grid=[0,4]) rimsBox = Box(app, layout="grid", grid=[2,0]) rimsPad = Picture(rimsBox, image="blank.gif", grid=[0,0]) rimsTitle = Text(rimsBox, text="RIMS", grid=[0,1], align="top") rimsText = Text(rimsBox, text="180", grid=[0,2], align="top") rimsSlider = Slider(rimsBox, start=212, end=100, horizontal=False, grid=[0,3], align="top") rimsSlider.tk.config(length=500, width=50) rimsFlamePad = Picture(rimsBox, image="blank_flame.gif", grid=[0,4]) rimsFlame = Picture(rimsBox, image="flame.gif", grid=[0,4]) bkBox = Box(app, layout="grid", grid=[3,0]) bkPad = Picture(bkBox, image="blank.gif", grid=[0,0]) bkTitle = Text(bkBox, text="BK", grid=[0,1], align="top") bkText = Text(bkBox, text="75", grid=[0,2], align="top") bkSlider = Slider(bkBox, start=100, end=0, horizontal=False, grid=[0,3], align="top") bkSlider.tk.config(length=500, width=50) bkFlamePad = Picture(bkBox, image="blank_flame.gif", grid=[0,4]) bkFlame = Picture(bkBox, image="flame.gif", grid=[0,4]) modeBox = Box(app, layout="grid", grid=[4,0]) modePad = Picture(modeBox, image="blank.gif", grid=[0,0]) modeTitle = Text(modeBox, text="Mode", grid=[0,0], align="top") mode = Combo(modeBox, options=["HLT", "RIMS", "BK"], grid=[1,0]) pauseState = Text(modeBox, text="Paused", grid=[0,1]) pauseButton = PushButton(modeBox, icon="pause-play.gif", command=handlepause, grid=[1,1]) hltFlame.visible=False rimsFlame.visible=False bkFlame.visible=False app.display()
37.901408
91
0.670011
393
2,691
4.577608
0.264631
0.061145
0.048916
0.043357
0.414675
0.307949
0.193997
0.114508
0.114508
0.047804
0
0.047783
0.136752
2,691
70
92
38.442857
0.726647
0.007804
0
0.135593
0
0
0.107156
0
0
0
0
0
0
1
0.033898
false
0
0.016949
0.016949
0.084746
0.050847
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15e018d003308b6e32514ff4f0cb219f8f099c3b
2,498
py
Python
tests/integration/test_integration.py
nuvolos-cloud/resolos
0918066cab7b11ef04ae005f3e052b14a65ded68
[ "MIT" ]
1
2021-11-30T06:47:24.000Z
2021-11-30T06:47:24.000Z
tests/integration/test_integration.py
nuvolos-cloud/resolos
0918066cab7b11ef04ae005f3e052b14a65ded68
[ "MIT" ]
1
2021-04-08T12:56:39.000Z
2021-04-08T12:56:39.000Z
tests/integration/test_integration.py
nuvolos-cloud/resolos
0918066cab7b11ef04ae005f3e052b14a65ded68
[ "MIT" ]
null
null
null
from click.testing import CliRunner from resolos.interface import ( res_remote_add, res_remote_remove, res_init, res_sync, res ) from resolos.remote import read_remote_db, list_remote_ids, delete_remote from tests.common import verify_result import logging from pathlib import Path import os logger = logging.getLogger(__name__) USER = os.environ["TEST_USER"] PWD = os.environ["SSHPASS"] HOST = os.environ["TEST_HOST"] class TestIntegration: remote_id = "test_remote" def test_job(self, *args): runner = CliRunner() with runner.isolated_filesystem() as fs: # Initialize a new local project logger.info(f"Initializing new project in {fs}") verify_result(runner.invoke(res, ["-v", "DEBUG", "info"])) verify_result(runner.invoke(res_init, ["-y"])) # Add remote logger.info(f"### Adding remote in {fs}") verify_result( runner.invoke( res_remote_add, [self.remote_id, "-y", "-h", HOST, "-p", "3144", "-u", USER, "--remote-path", "/data/integration_test", "--conda-install-path", "/data", "--conda-load-command", "source /data/miniconda/bin/activate"] ) ) remotes_list = read_remote_db() assert self.remote_id in remotes_list remotes_settings = remotes_list[self.remote_id] assert remotes_settings["hostname"] == HOST assert remotes_settings["username"] == USER # Run job with (Path(fs) / "test_script.py").open("w") as py: py.write("""with open('test_output.txt', 'w') as txtf: txtf.write('Hello, world!')""") logger.info(f"### Syncing with remote {self.remote_id}") verify_result(runner.invoke(res_sync, ["-r", self.remote_id])) logger.info(f"### Running test job on {self.remote_id}") verify_result(runner.invoke(res, ["-v", "DEBUG", "job", "-r", self.remote_id, "run", "-p", "normal", "python test_script.py"])) # Sync back job results logger.info(f"### Syncing results from remote {self.remote_id}") verify_result(runner.invoke(res_sync, ["-r", self.remote_id])) assert (Path(fs) / "test_output.txt").exists() # Remove remote logger.info(f"### Removing remote {self.remote_id}") verify_result(runner.invoke(res_remote_remove, [self.remote_id]))
43.068966
219
0.601281
308
2,498
4.681818
0.331169
0.066574
0.09154
0.116505
0.222607
0.203884
0.195562
0.144244
0.117198
0.085992
0
0.002158
0.257806
2,498
58
220
43.068966
0.77562
0.034027
0
0.081633
0
0
0.234635
0.030316
0
0
0
0
0.081633
1
0.020408
false
0.020408
0.142857
0
0.204082
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15e034a0325db7cea2ebf82178c6ea8ad80d5cda
946
py
Python
test/test_add_group.py
romanovaes/python_training
5df3a9b716e7659fb8f61e0b55e5217cc6a1a89e
[ "Apache-2.0" ]
null
null
null
test/test_add_group.py
romanovaes/python_training
5df3a9b716e7659fb8f61e0b55e5217cc6a1a89e
[ "Apache-2.0" ]
null
null
null
test/test_add_group.py
romanovaes/python_training
5df3a9b716e7659fb8f61e0b55e5217cc6a1a89e
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- from builtins import * from model.group import Group import pytest import allure #@pytest.mark.parametrize("group", testdata, ids=[repr(x) for x in testdata]) @allure.step('test_add_group') def test_add_group(app, db, json_groups, check_ui): group=json_groups #with pytest.allure.step('Given a group list'): old_group=db.get_group_list() #with pytest.allure.step('When I add a group % to the list' % group): app.group.create(group) #with pytest.allure.step('Then the group list is equal to the old list with the added group'): new_group=db.get_group_list() old_group.append(group) assert sorted(old_group, key=Group.id_or_max)==sorted(new_group, key=Group.id_or_max) if check_ui: assert sorted(map(app.group.clean_gap_from_group, new_group), key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max)
35.037037
153
0.689218
151
946
4.112583
0.364238
0.072464
0.064412
0.077295
0.21095
0.125604
0.125604
0
0
0
0
0.001305
0.190275
946
26
154
36.384615
0.809399
0.32241
0
0
0
0
0.022187
0
0
0
0
0
0.142857
1
0.071429
false
0
0.285714
0
0.357143
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15e04aa4840a7e7977d248d10cc55f54658702cd
753
py
Python
examples/Genius/Python/GeniusCancel/GeniusCancel/GeniusCancel.py
sfmwright/developer-docs
160c7c9d8b1f75964ed2615373516361564cac82
[ "Apache-2.0" ]
4
2019-08-20T03:06:43.000Z
2021-11-09T18:18:31.000Z
examples/Genius/Python/GeniusCancel/GeniusCancel/GeniusCancel.py
sfmwright/developer-docs
160c7c9d8b1f75964ed2615373516361564cac82
[ "Apache-2.0" ]
1
2020-01-28T11:26:32.000Z
2020-03-09T11:06:26.000Z
examples/Genius/Python/GeniusCancel/GeniusCancel/GeniusCancel.py
sfmwright/developer-docs
160c7c9d8b1f75964ed2615373516361564cac82
[ "Apache-2.0" ]
8
2019-04-20T00:16:26.000Z
2020-12-29T20:48:14.000Z
import urllib3 import lxml.etree as etree import lxml.objectify as objectify # Declare IP Address ip_address = "192.168.0.123" # Generate XML and XSD Validation genius_schema = etree.XMLSchema(file='Genius.xsd') xml_parser = objectify.makeparser(schema=genius_schema) # Send Status Request genius_comm = urllib3.PoolManager() genius_request_url = "http://%s:8080/v2/pos?Action=Cancel&Format=XML" % ip_address genius_response = genius_comm.request("GET", genius_request_url).data # Validate the response with the Genius XSD genius_response_data = objectify.fromstring(genius_response, xml_parser) print("Cancel Result: %s" % genius_response_data.Status) print("Response Message: %s" % genius_response_data.ResponseMessage) input("Press Enter to close")
39.631579
82
0.802125
108
753
5.407407
0.5
0.119863
0.092466
0.065068
0
0
0
0
0
0
0
0.024963
0.095618
753
19
83
39.631579
0.832599
0.148738
0
0
1
0
0.202512
0
0
0
0
0
0
1
0
false
0
0.230769
0
0.230769
0.153846
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
15e0c5cedcaca764ffdaedc7f69b8b05a55711fa
6,270
py
Python
editNames.py
harmsm/phylo_tools
470873a6decd8c9ca6f66308eeb53f7f6627115b
[ "Unlicense" ]
null
null
null
editNames.py
harmsm/phylo_tools
470873a6decd8c9ca6f66308eeb53f7f6627115b
[ "Unlicense" ]
1
2015-07-22T15:53:11.000Z
2015-07-22T16:49:54.000Z
editNames.py
harmsm/phylo_tools
470873a6decd8c9ca6f66308eeb53f7f6627115b
[ "Unlicense" ]
3
2015-07-01T22:39:55.000Z
2019-08-13T21:23:20.000Z
#!/usr/bin/env python __description__ =\ """ editNames.py Goes through a file looking for a set of strings, replacing each one with a specific counterpart. The strings are defined in a delimited text file with columns naemd "key" and "value". """ __author__ = "Michael J. Harms" __date__ = "091205" __usage__ = "editTreeNames.py file_to_modify master_file key_col value_col" import os, sys, re class EditNamesError(Exception): """ General error class for this module. """ pass class NameObject: """ """ def __init__(self,line,column_names,column_delimiter): """ Hold all column values for this sequence, keyed to column_name. """ column_values = [c.strip() for c in line.split(column_delimiter)] if len(column_values) > len(column_names): warning = "There are more data columns than data names for this\n" warning += "line. This usually occurs if you added a '%s' within\n" \ % column_delimiter warning += "one of the column entries. This may lead to wonkiness.\n" warning += "The offending line is: \n\n" warning += "%s\n" % line warning += "which, when split, yields:\n\n" warning += "\n".join(["%s: %s" % (column_names[i],column_values[i]) for i in range(len(column_names))]) warning += "\n\n" sys.stderr.write(warning) try: self.columns = dict([(column_names[i],column_values[i]) for i in range(len(column_names))]) except IndexError: err = "There is an error in the following line:\n\n" err += line err += "\n\nIncorrect number of columns?\n" raise EditNamesError(err) # make it so all column values can be accessed by a simple # s.internal_name nomenclature self.__dict__.update(self.columns) def checkUniqueness(some_list): """ Verifies that every entry in a list is unique. If it is not, it returns non-unique values. """ unique_list = dict([(x,[]) for x in some_list]).keys() repeated_entries = [u for u in unique_list if len([s for s in some_list if s == u]) > 1] return repeated_entries def readMasterFile(name_file,column_delimiter="\t"): """ Read a delimited (usually comma-delimited) file that has a set of sequence attributes under a unique internal_name. """ f = open(name_file,'r') lines = f.readlines() f.close() # Parse the file lines = [l for l in lines if l[0] != "#" and l.strip() != ""] # Create a dictionary that keys column names to column numbers column_names = [c.strip() for c in lines[0].split(column_delimiter)] column_dict = dict([(c,i) for i, c in enumerate(column_names)]) # Make sure file will be useful... if "internal_name" not in column_names: err = "\nYou must have an 'internal_name' column in this file!\n\n" raise EditNamesError(err) # Make sure column names are not repeated more than once for k in column_dict.keys(): num_col_in_file = len([c for c in column_names if c == k]) if num_col_in_file > 1: err = "column '%s' occurs more than once in the file!\n" % k raise EditNamesError(err) # Load all names names = [] for l in lines[1:]: names.append(NameObject(l,column_names,column_delimiter)) # make sure all internal_names are unique internal_names = [n.internal_name for n in names] repeated_names = checkUniqueness(internal_names) if len(repeated_names) != 0: err = "internal_name column must have unique entry for every line!\n" err += "The following entries are repeated:\n\n" err += "\n".join(repeated_names) err += "\n\n" raise EditNamesError(err) return names def modifyFile(file_to_modify,names,key_column,value_column): """ Read a file and replace all instances of the key_column with value_column where key_column and value_column are defined uniquely for each sequence in names. """ f = open(file_to_modify) contents = f.read() f.close() # Grab keys and values from every sequence keys = [] values = [] for n in names: try: keys.append(n.columns[key_column]) values.append(n.columns[value_column]) except KeyError: err = "Sequences '%s' does not have '%s' or '%s'!\n\n" % \ (n.internal_name,key_column,value_column) raise EditNamesError(err) # Check keys and values to make sure they are unique repeated_keys = checkUniqueness(keys) if len(repeated_keys) != 0: err = "Column '%s' has non-unique entries!\n" % key_column err += "The following entries are repeated:\n\n" err += "\n".join(repeated_keys) err += "\n\n" repeated_values = checkUniqueness(values) if len(repeated_values) != 0: err = "Column '%s' has non-unique entries!\n" % value_column err += "The following entries are repeated:\n\n" err += "\n".join(repeated_values) err += "\n\n" # Use regular experessions to replace all instances of key with value in the # file. name_dictionary = dict(zip(keys,values)) for key in name_dictionary.keys(): k = re.compile(key) num_counts = len(k.findall(contents)) contents = k.sub("%s" % name_dictionary[key],contents,count=num_counts) return contents def main(argv=None): """ Read the command line and master file, then alter contents of file_to_modify and print. """ if argv == None: argv = sys.argv[1:] try: file_to_modify = argv[0] master_file = argv[1] key_column = argv[2] value_column = argv[3] except IndexError: err = "Incorrect number of arguments!\n\nUsage:\n\n%s\n\n" % __usage__ raise EditNamesError(err) names = readMasterFile(master_file) out = modifyFile(file_to_modify,names,key_column,value_column) print out if __name__ == "__main__": main()
32.319588
82
0.612919
859
6,270
4.32014
0.240978
0.008084
0.019402
0.018593
0.141202
0.113447
0.113447
0.113447
0.113447
0.071409
0
0.004217
0.28134
6,270
193
83
32.487047
0.819352
0.080064
0
0.189189
0
0
0.185071
0.006169
0
0
0
0
0
0
null
null
0.009009
0.009009
null
null
0.009009
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
15e3d38045eea34ae5ee1b0e2ce54a0a8b72223a
3,988
py
Python
test/test_docx_context.py
ieric2/docx2python
4a1266811f9bd71f5eea5e0d458a391fd9eb4f73
[ "MIT" ]
52
2019-07-08T19:37:45.000Z
2022-03-30T11:36:08.000Z
test/test_docx_context.py
ieric2/docx2python
4a1266811f9bd71f5eea5e0d458a391fd9eb4f73
[ "MIT" ]
29
2019-08-29T09:48:24.000Z
2022-03-13T13:58:58.000Z
test/test_docx_context.py
ieric2/docx2python
4a1266811f9bd71f5eea5e0d458a391fd9eb4f73
[ "MIT" ]
23
2019-08-29T11:33:13.000Z
2022-03-03T17:22:35.000Z
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ """Test docx2python.docx_context.py author: Shay Hill created: 6/26/2019 """ import os import shutil import zipfile from collections import defaultdict from typing import Any, Dict import pytest from docx2python.docx_context import ( collect_docProps, collect_numFmts, get_context, pull_image_files, ) class TestCollectNumFmts: """Test strip_text.collect_numFmts """ # noinspection PyPep8Naming def test_gets_formats(self) -> None: """Retrieves formats from example.docx This isn't a great test. There are numbered lists I've added then removed as I've edited my test docx. These still appear in the docx file. I could compare directly with the extracted numbering xml file, but even then I'd be comparing to something I don't know to be accurate. This just tests that all numbering formats are represented. """ zipf = zipfile.ZipFile("resources/example.docx") numId2numFmts = collect_numFmts(zipf.read("word/numbering.xml")) formats = {x for y in numId2numFmts.values() for x in y} assert formats == { "lowerLetter", "upperLetter", "lowerRoman", "upperRoman", "bullet", "decimal", } class TestCollectDocProps: """Test strip_text.collect_docProps """ def test_gets_properties(self) -> None: """Retrieves properties from docProps""" zipf = zipfile.ZipFile("resources/example.docx") props = collect_docProps(zipf.read("docProps/core.xml")) assert props["creator"] == "Shay Hill" assert props["lastModifiedBy"] == "Shay Hill" @pytest.fixture def docx_context() -> Dict[str, Any]: """result of running strip_text.get_context""" zipf = zipfile.ZipFile("resources/example.docx") return get_context(zipf) # noinspection PyPep8Naming class TestGetContext: """Text strip_text.get_context """ def test_docProp2text(self, docx_context) -> None: """All targets mapped""" zipf = zipfile.ZipFile("resources/example.docx") props = collect_docProps(zipf.read("docProps/core.xml")) assert docx_context["docProp2text"] == props def test_numId2numFmts(self, docx_context) -> None: """All targets mapped""" zipf = zipfile.ZipFile("resources/example.docx") numId2numFmts = collect_numFmts(zipf.read("word/numbering.xml")) assert docx_context["numId2numFmts"] == numId2numFmts def test_numId2count(self, docx_context) -> None: """All numIds mapped to a default dict defaulting to 0""" for numId in docx_context["numId2numFmts"]: assert isinstance(docx_context["numId2count"][numId], defaultdict) assert docx_context["numId2count"][numId][0] == 0 def test_lists(self) -> None: """Pass silently when no numbered or bulleted lists.""" zipf = zipfile.ZipFile("resources/basic.docx") context = get_context(zipf) assert "numId2numFmts" not in context assert "numId2count" not in context class TestPullImageFiles: """Test strip_text.pull_image_files """ def test_pull_image_files(self) -> None: """Copy image files to output path.""" zipf = zipfile.ZipFile("resources/example.docx") context = get_context(zipf) pull_image_files(zipf, context, "delete_this/path/to/images") assert os.listdir("delete_this/path/to/images") == ["image1.png", "image2.jpg"] # clean up shutil.rmtree("delete_this") def test_no_image_files(self) -> None: """Pass silently when no image files.""" zipf = zipfile.ZipFile("resources/basic.docx") context = get_context(zipf) pull_image_files(zipf, context, "delete_this/path/to/images") assert os.listdir("delete_this/path/to/images") == [] # clean up shutil.rmtree("delete_this")
33.79661
87
0.658977
476
3,988
5.388655
0.327731
0.060039
0.05614
0.084211
0.363743
0.355166
0.284211
0.284211
0.284211
0.284211
0
0.010407
0.228937
3,988
117
88
34.08547
0.82374
0.243731
0
0.287879
0
0
0.195848
0.081661
0
0
0
0
0.166667
1
0.136364
false
0
0.106061
0
0.318182
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15e42de122c93447226408dd404b3ccbe892d9e6
1,022
py
Python
src/transporters/approximator/transporter.py
mucharafal/optics_generator_python
c14d4e5f19f921f4dc0a98129bca9d31754b72ad
[ "MIT" ]
null
null
null
src/transporters/approximator/transporter.py
mucharafal/optics_generator_python
c14d4e5f19f921f4dc0a98129bca9d31754b72ad
[ "MIT" ]
null
null
null
src/transporters/approximator/transporter.py
mucharafal/optics_generator_python
c14d4e5f19f921f4dc0a98129bca9d31754b72ad
[ "MIT" ]
null
null
null
import transporters.approximator.runner as ra from data.parameters_names import ParametersNames as Parameters def transport(approximator, particles): """matrix in format returned by data.particles_generator functions""" segments = dict() segments["start"] = particles matrix_for_transporter = particles.get_default_coordinates_of(Parameters.X, Parameters.THETA_X, Parameters.Y, Parameters.THETA_Y, Parameters.PT) transported_particles = ra.transport(approximator, matrix_for_transporter) segments["end"] = particles.__class__(transported_particles, get_mapping()) return segments def get_mapping(): mapping = { Parameters.X: 0, Parameters.THETA_X: 1, Parameters.Y: 2, Parameters.THETA_Y: 3, Parameters.PT: 4 } return mapping def get_transporter(approximator): def transporter(particles): return transport(approximator, particles) return transporter
28.388889
113
0.683953
106
1,022
6.386792
0.415094
0.088626
0.088626
0
0
0
0
0
0
0
0
0.006418
0.237769
1,022
35
114
29.2
0.862644
0.061644
0
0
0
0
0.008395
0
0
0
0
0
0
1
0.173913
false
0
0.086957
0.043478
0.434783
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15e6039e8fc572eeaac3ad290d2bd1f836aa300b
183
py
Python
vega/modules/tensformers/__init__.py
jie311/vega
1bba6100ead802697e691403b951e6652a99ccae
[ "MIT" ]
724
2020-06-22T12:05:30.000Z
2022-03-31T07:10:54.000Z
vega/modules/tensformers/__init__.py
jie311/vega
1bba6100ead802697e691403b951e6652a99ccae
[ "MIT" ]
147
2020-06-30T13:34:46.000Z
2022-03-29T11:30:17.000Z
vega/modules/tensformers/__init__.py
jie311/vega
1bba6100ead802697e691403b951e6652a99ccae
[ "MIT" ]
160
2020-06-29T18:27:58.000Z
2022-03-23T08:42:21.000Z
from .embeddings import BertEmbeddings from .encoder import BertEncoder from .pooler import Pooler from .pertrained_hooks import pretrained_bert_hook, pretrained_bert_classifier_hook
36.6
83
0.879781
23
183
6.73913
0.565217
0.180645
0
0
0
0
0
0
0
0
0
0
0.092896
183
4
84
45.75
0.933735
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
5
15e6149aa17b64d559de3c4f55ed8ff3fa679352
666
py
Python
postgresqleu/confsponsor/migrations/0008_class_params_json.py
bradfordboyle/pgeu-system
bbe70e7a94092c10f11a0f74fda23079532bb018
[ "MIT" ]
11
2020-08-20T11:16:02.000Z
2022-03-12T23:25:04.000Z
postgresqleu/confsponsor/migrations/0008_class_params_json.py
bradfordboyle/pgeu-system
bbe70e7a94092c10f11a0f74fda23079532bb018
[ "MIT" ]
71
2019-11-18T10:11:22.000Z
2022-03-27T16:12:57.000Z
postgresqleu/confsponsor/migrations/0008_class_params_json.py
bradfordboyle/pgeu-system
bbe70e7a94092c10f11a0f74fda23079532bb018
[ "MIT" ]
18
2019-11-18T09:56:31.000Z
2022-01-08T03:16:43.000Z
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-06-26 20:22 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('confsponsor', '0007_contract_per_conference'), ] operations = [ migrations.RunSQL("UPDATE confsponsor_sponsorshipbenefit SET class_parameters='{}' WHERE class_parameters=''"), migrations.AlterField( model_name='sponsorshipbenefit', name='class_parameters', field=django.contrib.postgres.fields.jsonb.JSONField(blank=True), ), ]
28.956522
119
0.686186
70
666
6.342857
0.685714
0.101351
0.094595
0.121622
0.144144
0
0
0
0
0
0
0.041431
0.202703
666
22
120
30.272727
0.794727
0.103604
0
0
1
0
0.272727
0.132997
0
0
0
0
0
1
0
false
0
0.2
0
0.4
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
15e6a04a8da0e44c61254eaa10ce768020d0ae51
186
py
Python
example_problem/dialogue/dialogue_functions.py
seakers/daphne-brain
1d703d468cd503a21395f986dd72e67b6e556451
[ "MIT" ]
null
null
null
example_problem/dialogue/dialogue_functions.py
seakers/daphne-brain
1d703d468cd503a21395f986dd72e67b6e556451
[ "MIT" ]
null
null
null
example_problem/dialogue/dialogue_functions.py
seakers/daphne-brain
1d703d468cd503a21395f986dd72e67b6e556451
[ "MIT" ]
null
null
null
import example_problem.analyst.dialogue_functions as analyst import example_problem.engineer.dialogue_functions as engineer import example_problem.critic.dialogue_functions as critic
26.571429
62
0.887097
24
186
6.625
0.375
0.245283
0.377358
0
0
0
0
0
0
0
0
0
0.080645
186
6
63
31
0.929825
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
7
15e96ef0984aad80cae6e556037214dc416821d1
9,077
py
Python
hack/make-rules/generate-notice.py
dingfeng/galaxykube
f5ea5cf40c957358e2bc5b14eabc9dea2ec93ad2
[ "Apache-2.0" ]
29
2021-10-16T06:01:53.000Z
2022-03-31T02:37:30.000Z
hack/make-rules/generate-notice.py
dingfeng/galaxykube
f5ea5cf40c957358e2bc5b14eabc9dea2ec93ad2
[ "Apache-2.0" ]
null
null
null
hack/make-rules/generate-notice.py
dingfeng/galaxykube
f5ea5cf40c957358e2bc5b14eabc9dea2ec93ad2
[ "Apache-2.0" ]
11
2021-10-18T02:26:32.000Z
2022-01-11T12:06:03.000Z
#!/usr/bin/env python3 # Copyright 2021 Alibaba Group Holding Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import difflib import os.path import sys from typing import List, Tuple from lib import * NOTICE_HEADER = '''PolarDB-X operator contains and relies on various third-party components under other open source licenses. The following sections summaries those components and their licenses. ## Third-party + [hsperfdata](https://github.com/xin053/hsperfdata), [MIT license](./third-party/hsperfdata/LICENSE). ## Vendors ''' def generate_markdown_list(vendor_licenses: List[Tuple[str, str, str]], vendor_license_root: str) -> List[str]: vendor_license_markdown_item = [] for vendor_name, guessed_license, license_file_relative_path in vendor_licenses: if len(guessed_license) > 0: vendor_license_markdown_item.append( '+ %s, [%s license](%s/%s).' % ( vendor_name, guessed_license, vendor_license_root, license_file_relative_path)) else: vendor_license_markdown_item.append( '+ %s, [license](%s/%s).' % ( vendor_name, vendor_license_root, license_file_relative_path)) return vendor_license_markdown_item def normalize_license_content(s: str): # remove all white spaces and concat with one blank. return ' '.join(s.split()).lower() MIT_LICENSE = normalize_license_content('''Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.''') BSD2_LICENSE = normalize_license_content(''' Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''') BSD3_LICENSE = normalize_license_content('''Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of AUTHOR nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''') BSD3_NEW_CLAUSE = normalize_license_content('''endorse or promote products derived from this software without specific prior written permission''') ISC_LICENSE = normalize_license_content('''Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.''') def guess_license(license_file: str) -> str: with open(license_file, 'r') as f: content = f.read() content = normalize_license_content(content) if 'mit license' in content: return 'MIT' elif 'apache license' in content: if 'version 2.0' in content: return 'Apache 2.0' else: return 'Apache' elif 'isc license' in content: return 'ISC' elif 'Mozilla Public License'.lower() in content: if 'version 2.0' in content: return 'MPL 2.0' else: return '' else: closest_matches = difflib.get_close_matches(content, [MIT_LICENSE, BSD2_LICENSE, BSD3_LICENSE, ISC_LICENSE], n=1, cutoff=0.3) if len(closest_matches) == 0: return '' else: m = closest_matches[0] if m == MIT_LICENSE: return 'MIT' elif m == BSD3_LICENSE or m == BSD2_LICENSE: if BSD3_NEW_CLAUSE in content: # The new clause return '3-Clause BSD' else: return '2-Clause BSD' elif m == ISC_LICENSE: return 'ISC' else: raise RuntimeError('never here') def walk_through_vendor_licenses(licenses_dir: str) -> List[Tuple[str, str, str]]: vendor_licenses = [] for root, dirs, files in os.walk(licenses_dir): if 'LICENSE' in files: relative_path = os.path.relpath(root, licenses_dir) license_file_relative_path = os.path.join(relative_path, 'LICENSE') vendor_licenses.append( (relative_path, guess_license(os.path.join(root, 'LICENSE')), license_file_relative_path)) return vendor_licenses def generate_notice_file(build_env: BuildEnv): # Generate vendor licenses. vendor_licenses_dir = os.path.join(build_env.root_dir, 'LICENSES/vendor') vendor_licenses = walk_through_vendor_licenses(vendor_licenses_dir) vendor_notice_list = generate_markdown_list(vendor_licenses, './LICENSES/vendor') # Write to notice file. notice_file = os.path.join(build_env.root_dir, 'NOTICE.md') notice_content = NOTICE_HEADER + '\n\n'.join(vendor_notice_list) + '\n' with open(notice_file, 'w+') as f: f.write(notice_content) def main(): generate_notice_file(BASIC_BUILD_ENV) return 0 if __name__ == '__main__': sys.exit(main())
46.311224
755
0.736036
1,273
9,077
5.142969
0.235664
0.025661
0.024591
0.021078
0.502826
0.455629
0.395296
0.367497
0.353444
0.342752
0
0.005091
0.199295
9,077
195
756
46.548718
0.895707
0.077449
0
0.138686
0
0.036496
0.606989
0.005146
0
0
0
0
0
1
0.043796
false
0
0.036496
0.007299
0.189781
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
15f0c68253b44fcf807be3d2c13c0296e0b8bc18
47
py
Python
python/graph/__init__.py
advaithm582/algorithms
9a5261b69ea7bc84afb9f8561c1d497a799733f9
[ "MIT" ]
2
2021-11-17T07:48:34.000Z
2021-12-10T03:09:00.000Z
python/graph/__init__.py
advaithm582/algorithms
9a5261b69ea7bc84afb9f8561c1d497a799733f9
[ "MIT" ]
null
null
null
python/graph/__init__.py
advaithm582/algorithms
9a5261b69ea7bc84afb9f8561c1d497a799733f9
[ "MIT" ]
null
null
null
import graph.bfs as bfs import graph.dfs as dfs
23.5
23
0.808511
10
47
3.8
0.5
0.578947
0
0
0
0
0
0
0
0
0
0
0.148936
47
2
24
23.5
0.95
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
1
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
7
15f328ce83cf7262e3a2711b251f951f5f5aef7e
1,542
py
Python
src/hydratk/core/eventhandler.py
hydratk/hydratk
54f64df2a68f49ba4ce564bf102824cc33dbe6c8
[ "BSD-3-Clause" ]
null
null
null
src/hydratk/core/eventhandler.py
hydratk/hydratk
54f64df2a68f49ba4ce564bf102824cc33dbe6c8
[ "BSD-3-Clause" ]
null
null
null
src/hydratk/core/eventhandler.py
hydratk/hydratk
54f64df2a68f49ba4ce564bf102824cc33dbe6c8
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """HydraTK core event handling implementation class .. module:: core.eventhandler :platform: Unix :synopsis: HydraTK core event handling implementation class .. moduleauthor:: Petr Czaderna <pc@hydratk.org> """ from hydratk.core import hsignal class EventHandler(object): """Class EventHandler """ def _ec_check_co_privmsg(self, oevent): self._check_co_privmsg() def _ec_check_cw_privmsg(self, oevent): self._check_cw_privmsg() def _ec_stop_app(self, oevent, *args): self._stop_app(*args) def _eh_htk_on_got_cmd_options(self, oevent): self.apply_command_options() def _eh_htk_on_debug_info(self, oevent, *args): self.dout(*args) def _eh_htk_on_warning(self, oevent, *args): if int(self.cfg['System']['Warnings']['enabled']) == 1: self.wout(*args) def _eh_htk_on_extension_warning(self, oevent, *args): self.wout(*args) def _eh_htk_on_error(self, oevent, *args): self.errout(*args) def _eh_htk_on_exception(self, oevent, *args): self.exout(*args) def _eh_htk_on_extension_error(self, oevent, *args): self.errout(*args) def _eh_htk_on_cprint(self, oevent, *args): self.spout(*args) def _ec_sig_handler(self, oevent, signum): signal = hsignal.sigint2string[ signum] if signum in hsignal.sigint2string else signum self.demsg('htk_on_debug_info', self._trn.msg( 'htk_sig_recv', signal), self.fromhere())
27.052632
66
0.662776
204
1,542
4.681373
0.357843
0.125654
0.117277
0.08377
0.381152
0.259686
0.136126
0.090052
0.090052
0.090052
0
0.003306
0.215305
1,542
56
67
27.535714
0.78595
0.166667
0
0.133333
0
0
0.039308
0
0
0
0
0
0
1
0.4
false
0
0.033333
0
0.466667
0.033333
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
1
15f34bffaf876f6f6a2e7f2b53d0bff13ac885d0
13,660
py
Python
charon/saver.py
Galithil/charon
7b11780b8275d775c467e7ebd4a99a9d6bb77ee4
[ "MIT" ]
3
2015-11-18T06:20:56.000Z
2017-09-20T14:44:45.000Z
charon/saver.py
Galithil/charon
7b11780b8275d775c467e7ebd4a99a9d6bb77ee4
[ "MIT" ]
25
2015-02-20T15:13:27.000Z
2018-11-06T14:17:17.000Z
charon/saver.py
Galithil/charon
7b11780b8275d775c467e7ebd4a99a9d6bb77ee4
[ "MIT" ]
8
2015-05-22T14:16:05.000Z
2022-03-22T07:55:25.000Z
" Charon: Context handler for saving an entity. " import logging import couchdb from . import constants from . import utils class Field(object): "Specification of a data field for an entity." type ='text' def __init__(self, key, title=None, description=None, mandatory=False, editable=True, default=None): assert key self.key = key self.title = title or key.capitalize().replace('_', ' ') self.description = description or self.__doc__ self.mandatory = mandatory # A non-None value is requried. self.editable = editable # Changeable once set? self.default=default self.none_value=u'None' def store(self, saver, data=None, check_only=False): """Check, convert and store the field value. If 'data' is None, then obtain the value from HTML form parameter. If 'check_only' is True, then just do validity checking, no update. """ if not saver.is_new() and not self.editable: return logging.debug("Field.store(%s)", data) value = self.get(saver, data=data) try: value = self.process(saver, value) except ValueError, msg: raise ValueError("field '{0}': {1}".format(self.key, msg)) if check_only: return if self.default is not None and value is None: value = self.default if value == saver.doc.get(self.key): logging.debug("Field.store: '%s' value equal", self.key) return saver.doc[self.key] = value saver.changed[self.key] = value def get(self, saver, data=None): "Obtain the value from data, if given, else from HTML form parameter." if data is None: value = saver.rqh.get_argument(self.key, default=None) if value == self.none_value: return None else: return value else: try: return data[self.key] except KeyError: return saver.get(self.key) def process(self, saver, value): """Check validity and return converted to the appropriate type. Raise ValueError if there is a problem.""" self.check_mandatory(saver, value) self.check_valid(saver, value) return value or None def check_mandatory(self, saver, value): "Check that a value is provided when required." if self.mandatory and value is None: raise ValueError('a defined value is mandatory') def check_valid(self, saver, value): "Check that the value, if provided, is valid." pass def html_display(self, entity): "Return the field value as valid HTML." return str(entity.get(self.key) or '-') def html_create(self): "Return an appropriate HTML input field for a create form." return '<input type="text" name="{0}">'.format(self.key) def html_edit(self, entity): "Return an appropriate HTML input field for an edit form." if self.editable: return '<input type="text" name="{0}" value="{1}">'.\ format(self.key, entity.get(self.key) or '') else: return entity.get(self.key) or '-' class ListField(Field): type = "list" def __init__(self, key, title=None, description=None, default=[]): super(ListField, self).__init__(key, title=title, description=description, mandatory=False, editable=True, default=default) self.none_value = [] def process(self, saver, value): self.check_mandatory(saver, value) old_value = saver.doc.get(self.key) if old_value is None: old_value=[] if value not in [None, '']: if isinstance(value, list): old_value = value elif value.startswith('[') and value.endswith(']'): old_value=[] #assume it's a serialized list values=value[1:-1].split(",") for val in values: if val.strip().startswith("u'") and val.endswith("'"): old_value.append(val[2:-1]) else: old_value.append(val) else: old_value = [value] return old_value class IdField(Field): "The identifier for the entity." type ='identifier' def __init__(self, key, title=None, description=None): super(IdField, self).__init__(key, title=title, description=description, mandatory=True, editable=False) def check_valid(self, saver, value): "Only allow a subset of ordinary ASCII characters." logging.debug('IdField.check_valid') if not constants.ALLOWED_ID_CHARS.match(value): raise ValueError('invalid identifier value (disallowed characters)') class SelectField(Field): "Select one of a set of values." none_value = u'None' def __init__(self, key, title=None, description=None, mandatory=False, editable=True, options=[]): super(SelectField, self).__init__(key, title=title, description=description, mandatory=mandatory, editable=editable) self.options = options def get(self, saver, data=None): "Obtain the value from data, if given, else from HTML form parameter." if data is None : value = saver.rqh.get_argument(self.key, default=None) if value == self.none_value: return None else: return value else: try: return data[self.key] except KeyError: return saver.get(self.key) def check_valid(self, saver, value): "Check that the value, if provided, is valid." if value is None or value == self.none_value: return if value not in self.options: logging.debug("invalid select value: %s", value) raise ValueError("invalid value '{0}; not among options for select". format(value)) def html_create(self): "Return the field HTML input field for a create form." options = ["<option>{0}</option>".format(o) for o in self.options] if not self.mandatory: options.insert(0, "<option>{0}</option>".format(self.none_value)) return '<select name="{0}">{1}</select>'.format(self.key, options) def html_edit(self, entity): "Return the field HTML input field for an edit form." value = entity.get(self.key) if self.editable: options = [] if not self.mandatory: if value is None: options.append("<option selected>{0}</option>".format( self.none_value)) else: options.append("<option>{0}</option>".format( self.none_value)) for option in self.options: if value == option: options.append("<option selected>{0}</option>".format(option)) else: options.append("<option>{0}</option>".format(option)) return '<select name="{0}">{1}</select>'.format(self.key, options) else: return value or '-' class NameField(Field): "The name for the entity, unique if non-null." def __init__(self, key, title=None, description=None): super(NameField, self).__init__(key, title=title, description=description, mandatory=False) class FloatField(Field): "A floating point value field." type ='float' def __init__(self, key, title=None, description=None, mandatory=False, editable=True, default=None): super(FloatField, self).__init__(key, title=title, description=description, mandatory=mandatory, editable=editable, default=default) def process(self, saver, value): self.check_mandatory(saver, value) if value is None: return None if value == '': return None return float(value) def html_display(self, entity): "Return the field value as valid HTML." value = entity.get(self.key) if value is None: value = '-' else: value = str(value) return '<span class="number">{0}</span>'.format(value) def html_edit(self, entity): "Return the field HTML input field for an edit form." value = entity.get(self.key) if value is None: if self.editable: return '<input type="text" name="{0}">'.format(self.key) else: return '-' else: if self.editable: return '<input type="text" name="{0}" value="{1}">'.\ format(self.key, value) else: return str(value) class RangeFloatField(FloatField): "A floating point value field, with an allowed range." def __init__(self, key, minimum=None, maximum=None, title=None, description=None, mandatory=False, editable=True): super(RangeFloatField, self).__init__(key, title=title, description=description, mandatory=mandatory, editable=editable) self.minimum = minimum self.maximum = maximum def process(self, saver, value): value = super(RangeFloatField, self).process(saver, value) if value is None: return None if self.minimum is not None: if value < self.minimum: raise ValueError('value too low') if self.maximum is not None: if value > self.maximum: raise ValueError('value too high') return value class Saver(object): "Context handler defining the fields of the entity and saving the data." doctype = None fields = [] field_keys = [] def __init__(self, doc=None, rqh=None, db=None): self.fields_lookup = dict([(f.key, f) for f in self.fields]) assert self.doctype if rqh is not None: self.rqh = rqh self.db = rqh.db self.current_user = rqh.current_user elif db is not None: self.db = db self.current_user = dict() else: raise AttributeError('neither db nor rqh given') self.doc = doc or dict() self.changed = dict() if '_id' in self.doc: assert self.doctype == self.doc[constants.DB_DOCTYPE] else: self.doc['_id'] = utils.get_iuid() self.doc[constants.DB_DOCTYPE] = self.doctype self.initialize() def __enter__(self): return self def __exit__(self, type, value, tb): if type is not None: return False # No exceptions handled here self.finalize() try: self.db.save(self.doc) except couchdb.http.ResourceConflict: raise IOError('document revision update conflict') if self.changed: utils.log(self.db, self.doc, changed=self.changed, current_user=self.current_user) def __setitem__(self, key, value): "Update the key/value pair." try: field = self.fields_lookup[key] except KeyError: try: checker = getattr(self, "check_{0}".format(key)) except AttributeError: pass else: checker(value) try: converter = getattr(self, "convert_{0}".format(key)) except AttributeError: pass else: value = converter(value) try: if self.doc[key] == value: return except KeyError: pass self.doc[key] = value self.changed[key] = value else: field.store(self, value) def __getitem__(self, key): return self.doc[key] def initialize(self): "Perform actions when creating the entity." self.doc['created'] = utils.timestamp() def is_new(self): "Is the entity new, i.e. not previously saved in the database?" return '_rev' not in self.doc def store(self, data=None, check_only=False): """Given the fields, store the data items. If data is None, then obtain the value from HTML form parameter. If 'check_only' is True, then just do validity checking, no update. """ for field in self.fields: field.store(self, data=data, check_only=check_only) def finalize(self): "Perform any final modifications before saving the entity." self.doc['modified'] = utils.timestamp() def get(self, key, default=None): try: return self[key] except KeyError: return default
35.572917
82
0.544583
1,546
13,660
4.721216
0.140362
0.034525
0.015071
0.013427
0.477463
0.400603
0.380463
0.324565
0.305384
0.251541
0
0.003072
0.356662
13,660
383
83
35.665796
0.827492
0.00776
0
0.401929
0
0
0.150864
0.008676
0
0
0
0
0.009646
0
null
null
0.012862
0.012862
null
null
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
15f39d0f421f2c653443422d6ac14afb93981bf5
5,264
py
Python
app/projects/tests/test_portfolio_api.py
nestor-san/cooperation-fit
1a922233345698970c7e18e6213ad0320de70cce
[ "MIT" ]
null
null
null
app/projects/tests/test_portfolio_api.py
nestor-san/cooperation-fit
1a922233345698970c7e18e6213ad0320de70cce
[ "MIT" ]
null
null
null
app/projects/tests/test_portfolio_api.py
nestor-san/cooperation-fit
1a922233345698970c7e18e6213ad0320de70cce
[ "MIT" ]
null
null
null
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import PortfolioItem from projects.serializers import PortfolioItemSerializer PORTFOLIO_URL = reverse('projects:portfolioitem-list') def detail_url(portfolio_id): """Return the detail URL of a portfolio item""" return reverse('projects:portfolioitem-detail', args=[portfolio_id]) class PublicPortfolioApiTests(TestCase): """Test the publicly available projects API""" def setUp(self): self.client = APIClient() def test_login_not_required(self): """Test that login is not required to access the endpoint""" res = self.client.get(PORTFOLIO_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_retrieve_portfolio_list(self): """Test retrieving a list of portfolio items""" sample_user = get_user_model().objects.create_user( 'test@xemob.com', 'testpass' ) PortfolioItem.objects.create(user=sample_user, name='Portfolio Item 1') PortfolioItem.objects.create(user=sample_user, name='Portfolio Item 2') res = self.client.get(PORTFOLIO_URL) portfolio_items = PortfolioItem.objects.all().order_by('-name') serializer = PortfolioItemSerializer(portfolio_items, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data) class PrivatePortfolioApiTests(TestCase): """Test the private portfolio API""" def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( 'test@xemob.com', 'testpass' ) self.client.force_authenticate(self.user) def test_create_portfolio_item_successfully(self): """Test creating a new portfolio item""" payload = {'name': 'New portfolio item', 'user': self.user.id} self.client.post(PORTFOLIO_URL, payload) exists = PortfolioItem.objects.filter( user=self.user, name=payload['name'] ).exists() self.assertTrue(exists) def test_create_portfolio_item_invalid(self): """Test creating a portfolio item with invalid payload""" payload = {'name': '', 'user': self.user.id} res = self.client.post(PORTFOLIO_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_partial_portfolio_update_successfully(self): """Test partial updating a project by owner is successful""" portfolio_item = PortfolioItem.objects.create(user=self.user, name='Portfolio Item 1') payload = {'name': 'Alt portfolio item'} url = detail_url(portfolio_item.id) res = self.client.patch(url, payload) portfolio_item.refresh_from_db() self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(portfolio_item.name, payload['name']) def test_partial_portfolio_update_invalid(self): """Test updating a portfolio item by not owner is invalid""" self.user2 = get_user_model().objects.create_user( 'other@xemob.com', 'testpass' ) portfolio_item = PortfolioItem.objects.create(user=self.user2, name='Portfolio Item 1') payload = {'name': 'Alt portfolio item'} url = detail_url(portfolio_item.id) res = self.client.patch(url, payload) portfolio_item.refresh_from_db() self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN) self.assertNotEqual(portfolio_item.name, payload['name']) def test_full_portfolio_update_successful(self): """Test updating a portfolio item by owner is successful with PUT""" portfolio_item = PortfolioItem.objects.create(user=self.user, name='Portfolio Item 1') payload = {'user': self.user.id, 'name': 'Alt portfolio item'} url = detail_url(portfolio_item.id) res = self.client.put(url, payload) portfolio_item.refresh_from_db() self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(portfolio_item.name, payload['name']) def test_full_portfolio_update_invalid(self): """Test updateing a portfolio item by not owner is invalid with PUT""" self.user2 = get_user_model().objects.create_user( 'other@xemob.com', 'testpass' ) portfolio_item = PortfolioItem.objects.create(user=self.user2, name='Portfolio Item 1') payload = {'user': self.user.id, 'name': 'Alt portfolio item'} url = detail_url(portfolio_item.id) res = self.client.put(url, payload) portfolio_item.refresh_from_db() self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN) self.assertNotEqual(portfolio_item.name, payload['name'])
38.992593
78
0.644187
606
5,264
5.412541
0.181518
0.13872
0.051829
0.05122
0.629268
0.590854
0.553659
0.506707
0.486585
0.43872
0
0.007912
0.255699
5,264
134
79
39.283582
0.82925
0.101634
0
0.56383
0
0
0.084956
0.011984
0
0
0
0
0.138298
1
0.117021
false
0.042553
0.074468
0
0.223404
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15f3b785cb9961fa87557827d4473398f7509cf4
3,662
py
Python
msc_CollectData.py
waldu/AdPExT
99238119d170ead8cfc0fe5a5ff163d1fc0e9dbb
[ "MIT" ]
null
null
null
msc_CollectData.py
waldu/AdPExT
99238119d170ead8cfc0fe5a5ff163d1fc0e9dbb
[ "MIT" ]
null
null
null
msc_CollectData.py
waldu/AdPExT
99238119d170ead8cfc0fe5a5ff163d1fc0e9dbb
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on: Sun May 21 05:09:40 2017 Author: Waldu Woensdregt Description: Code uses OpenWPM package to extract HTTPS responses from selected set of URLs (defined in GetListOfSiteURLsToExtract) and then splits the resulting data into individual URL parameters to allow it to be sorted and classified for use in a thesis masters assignment """ import msc_UseOpenWPM from msc_ParamCleansing import open_db_conn from msc_ParamCleansing import setup_db_tables from msc_ParamCleansing import extract_parameters def get_site_urls_to_extract(): url_list = [] # url_list.append('http://www.smallestwebsitetotheworld.com/') # for testing # url_list.append('https://www.reddit.com/') # for testing url_list.append('https://www.youtube.com/watch?v=JGwWNGJdvx8') url_list.append('https://www.reddit.com/') url_list.append('https://www.amazon.co.uk/') url_list.append('http://www.ebay.co.uk/itm/232254122171') url_list.append('http://www.ladbible.com/') url_list.append('https://www.yahoo.com/') url_list.append('https://www.theguardian.com/uk') url_list.append('http://diply.com/') url_list.append('http://imgur.com/gallery/nxrNk') url_list.append('http://www.dailymail.co.uk/home/index.html') url_list.append('https://www.twitch.tv/') url_list.append('http://www.imdb.com/') url_list.append('http://www.rightmove.co.uk/property-for-sale/property-66961808.html') url_list.append('http://www.telegraph.co.uk/') url_list.append('http://fandom.wikia.com/articles/pitch-perfect-3-teaser-trailer-drops') url_list.append('http://www.sportbible.com/football/transfers-barcelonas-plan-b-is-just-as-good-as-marco-verratti' '-20170625') url_list.append('http://www.independent.co.uk/') url_list.append('https://www.gumtree.com/p/plumbing-central-heating/gas-fired-log-fired-central-heating-system' '-cheap-/1250349004') url_list.append('https://wordpress.com/') url_list.append('http://www.msn.com/en-gb/lifestyle/family-relationships/meghan-markle-responds-to-marriage' '-rumours/ar-BBCxAHD') return url_list # -------------------------------------------------------------------------- # # - MAIN START - # # ------------------------------------------------------------------------- -# # init variables myprefix = 'msc_' # table prefix to easily keep them separate from OpenWPM # enable/disable certain parts during testing runDataCollection = 1 # 1 = enabled do_extractParameters = 1 # 1 = enabled # open database connection conn = open_db_conn() # connect to DB and get max crawl (to later know which crawls are new) max_crawl_id = conn.execute('SELECT MAX(crawl_id) FROM crawl').fetchone()[0] print 'Max CrawlID before new crawl = ' + str(max_crawl_id) setup_db_tables(conn, myprefix) # create msc tables if they do not exist # Run data collection new_crawl_id = 0 if runDataCollection == 1: sites = get_site_urls_to_extract() msc_UseOpenWPM.extract_via_openwpm(sites) print 'Data collection completed for:' for site in sites: print ' - ' + site new_crawl_id = conn.execute('SELECT MAX(crawl_id) FROM crawl').fetchone()[0] print 'All data extraction completed for new crawl: {}'.format(new_crawl_id) # extract parameters into parameter table if do_extractParameters == 1 and new_crawl_id > 0: extract_parameters(conn, new_crawl_id, myprefix) # close database connection conn.close() print '-done-'
43.082353
118
0.66521
488
3,662
4.852459
0.42623
0.070946
0.120777
0.093328
0.271537
0.158361
0.092061
0.076858
0.048142
0.048142
0
0.020799
0.172856
3,662
84
119
43.595238
0.760977
0.201529
0
0
0
0.1
0.42886
0
0
0
0
0
0
0
null
null
0
0.08
null
null
0.1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
15f3e6d11f8953cc11ced404d841621499083f56
2,545
py
Python
utils/generateLocation.py
mie-lab/change-detection
53f44d1e39405ab56be4e24da9e40cca31af8908
[ "MIT" ]
null
null
null
utils/generateLocation.py
mie-lab/change-detection
53f44d1e39405ab56be4e24da9e40cca31af8908
[ "MIT" ]
null
null
null
utils/generateLocation.py
mie-lab/change-detection
53f44d1e39405ab56be4e24da9e40cca31af8908
[ "MIT" ]
null
null
null
import pandas as pd import datetime import geopandas as gpd import os from tqdm import tqdm from shapely import wkt from config import config import trackintel as ti def generate_Location(df, epsilon, user): """Cluster staypoints to locations, with different parameters and distinguish 'user' and 'dataset'""" # select only activity staypoints df = df.loc[df["activity"] == True].copy() # change to trackintel format df.set_index("id", inplace=True) tqdm.pandas(desc="Load Geometry") df["geom"] = df["geom"].progress_apply(wkt.loads) gdf = gpd.GeoDataFrame(df, crs="EPSG:4326", geometry="geom") # cluster the staypoints into locations (DBSCAN) if user: agg_level = "user" else: agg_level = "dataset" stps, locs = gdf.as_staypoints.generate_locations( epsilon=epsilon, num_samples=1, distance_metric="haversine", agg_level=agg_level, n_jobs=-1 ) print("cluster complete") # rename to avoid conflict stps.rename( columns={"user_id": "userid", "started_at": "startt", "finished_at": "endt", "location_id": "locid"}, inplace=True, ) locs.rename(columns={"user_id": "userid"}, inplace=True) stps["startt"] = pd.to_datetime(stps["startt"]).dt.tz_localize(None) stps["endt"] = pd.to_datetime(stps["endt"]).dt.tz_localize(None) stps.sort_index(inplace=True) locs.sort_index(inplace=True) stps.to_csv(os.path.join(config["proc"], f"stps_act_{agg_level}_{epsilon}.csv"), index=True) locs.to_csv(os.path.join(config["proc"], f"locs_{agg_level}_{epsilon}.csv"), index=True) if __name__ == "__main__": # SBB # df = pd.read_csv(os.path.join(config["raw"], "stps.csv")) # df.rename(columns={"userid": "user_id", "startt": "started_at", "endt": "finished_at"}, inplace=True) # df["started_at"], df["finished_at"] = pd.to_datetime(df["started_at"]), pd.to_datetime(df["finished_at"]) # # end period cut # end_period = datetime.datetime(2017, 12, 25) # df = df.loc[df["finished_at"] < end_period].copy() # df["started_at"] = df["started_at"].dt.tz_localize(tz="utc") # df["finished_at"] = df["finished_at"].dt.tz_localize(tz="utc") # Geolife df = pd.read_csv(os.path.join(config["proc"], "stps.csv")) df.rename(columns={"userid": "user_id", "startt": "started_at", "endt": "finished_at"}, inplace=True) df["started_at"], df["finished_at"] = pd.to_datetime(df["started_at"]), pd.to_datetime(df["finished_at"]) generate_Location(df, epsilon=50, user=True)
35.84507
111
0.667191
362
2,545
4.497238
0.303867
0.061425
0.051597
0.031941
0.374693
0.300983
0.242015
0.242015
0.176904
0.176904
0
0.007501
0.161886
2,545
70
112
36.357143
0.755743
0.291552
0
0
1
0
0.196859
0.035895
0
0
0
0
0
1
0.026316
false
0
0.210526
0
0.236842
0.026316
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
15f6ebf3d219ce6b1cd4eb680d9639aa61bcb259
369
py
Python
test.py
liyao001/EVBUS
8730ce6b062bc31df27506a06723dee3b5ab511a
[ "Apache-2.0" ]
null
null
null
test.py
liyao001/EVBUS
8730ce6b062bc31df27506a06723dee3b5ab511a
[ "Apache-2.0" ]
null
null
null
test.py
liyao001/EVBUS
8730ce6b062bc31df27506a06723dee3b5ab511a
[ "Apache-2.0" ]
null
null
null
from EVBUS import EVBUS from sklearn.datasets import load_boston import sklearn.model_selection as xval boston = load_boston() Y = boston.data[:, 12] X = boston.data[:, 0:12] bos_X_train, bos_X_test, bos_y_train, bos_y_test = xval.train_test_split(X, Y, test_size=0.3) evbus = EVBUS.varU(bos_X_train, bos_y_train, bos_X_test) v = evbus.calculate_variance() print(v)
26.357143
93
0.772358
68
369
3.882353
0.397059
0.060606
0.068182
0.090909
0
0
0
0
0
0
0
0.021472
0.116531
369
13
94
28.384615
0.788344
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.3
0
0.3
0.1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15f8928949b14c3be24585b15f6516fd3a9db474
7,226
py
Python
tests/listings/test_views.py
meghabhoj/NEWBAZAAR
cb1405dcb2c8b4812ddf724d5a3c07b2f77c1b34
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
tests/listings/test_views.py
meghabhoj/NEWBAZAAR
cb1405dcb2c8b4812ddf724d5a3c07b2f77c1b34
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
tests/listings/test_views.py
meghabhoj/NEWBAZAAR
cb1405dcb2c8b4812ddf724d5a3c07b2f77c1b34
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
from __future__ import absolute_import from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse from django.test import TestCase from django.utils.translation import ugettext as _ from bazaar.listings.models import Listing from rest_framework import status from tests import factories as f from tests.factories import PublishingFactory, ListingFactory class TestBase(TestCase): def setUp(self): self.user = get_user_model().objects.create_user(username='test', email='test@test.it', password='test') class TestListingsListView(TestBase): def test_list_view(self): """ Test that list view works fine """ # By default this operation will create a bound listing x1 of that product self.product = f.ProductFactory(name='product1', price=2, description='the best you can have!') self.listing = self.product.listings.first() self.client.login(username=self.user.username, password='test') response = self.client.get(reverse('bazaar:listing-list')) self.assertEqual(response.status_code, status.HTTP_200_OK) listings = response.context_data['listing_list'] self.assertEqual(listings.count(), 1) self.assertEqual(listings[0].sku, self.listing.sku) def test_list_view_not_working_without_login(self): """ Test that trying to call the list view without being logged redirects to the login page """ response = self.client.get(reverse('bazaar:listing-list')) self.assertRedirects(response, '/accounts/login/?next=/listings/') def test_list_view_no_products(self): """ Test that a void list view displays "no products" """ self.client.login(username=self.user.username, password='test') response = self.client.get(reverse('bazaar:listing-list')) self.assertEqual(response.status_code, status.HTTP_200_OK) listings = response.context_data['listing_list'] self.assertEqual(listings.count(), 0) self.assertIn(_('There are 0 listings').encode(encoding='UTF-8'), response.content) class TestListingUpdateView(TestBase): def test_update_view_not_working_without_login(self): """ Test that the update view redirects to the login page if the user is not logged """ response = self.client.get(reverse('bazaar:listing-update', kwargs={'pk': 1})) self.assertRedirects(response, '/accounts/login/?next=%s' % reverse('bazaar:listing-update', kwargs={'pk': 1})) def test_update_listing_does_not_change_sku(self): self.client.login(username=self.user.username, password='test') product = f.ProductFactory() listing = product.listings.first() self.client.login(username=self.user.username, password='test') data = {'product': product.pk} response = self.client.post(reverse('bazaar:listing-update', kwargs={'pk': listing.pk}), data=data) self.assertEqual(response.status_code, status.HTTP_302_FOUND) modified_listing = Listing.objects.get(pk=listing.pk) self.assertEqual(listing.sku, modified_listing.sku) def test_new_simple_view_has_back_button(self): """ Test that the new view has back and save button """ self.client.login(username=self.user.username, password='test') response = self.client.get(reverse('bazaar:listing-create')) content = response.content.decode('utf-8') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIn('href="/listings/"', content) self.assertIn('id="submit-id-save"', content) class TestListingCreateView(TestBase): def test_create_simple_listing_view(self): """ Test that the create view works fine """ # By default this operation will create a bound listing x1 of that product self.product = f.ProductFactory(name='product1', price=2, description='the best you can have!') self.listing = self.product.listings.first() self.client.login(username=self.user.username, password='test') data = {'product': self.product.id} response = self.client.post(reverse('bazaar:listing-create'), data=data) new_listing = Listing.objects.exclude(sku=self.listing.sku).first() self.assertRedirects(response, '/listings/%s/' % new_listing.pk) def test_create_view_not_working_without_login(self): """ Test that the create view redirects to the login page if the user is not logged """ # By default this operation will create a bound listing x1 of that product self.product = f.ProductFactory(name='product1', price=2, description='the best you can have!') self.listing = self.product.listings.first() data = {'product': self.product.id} response = self.client.post(reverse('bazaar:listing-create'), data=data) self.assertRedirects(response, '/accounts/login/?next=/listings/new/') class TestDeleteView(TestBase): def test_delete_view_not_working_without_login(self): """ Test that the delete view redirects to the login page if the user is not logged """ response = self.client.get(reverse('bazaar:listing-delete', kwargs={'pk': 1})) self.assertRedirects(response, '/accounts/login/?next=/listings/delete/%s/' % 1) def test_delete_view(self): """ Test that the delete view works fine """ # By default this operation will create a bound listing x1 of that product self.product = f.ProductFactory(name='product1', price=2, description='the best you can have!') self.listing = self.product.listings.first() self.client.login(username=self.user.username, password='test') response = self.client.post(reverse('bazaar:listing-delete', kwargs={'pk': self.listing.pk})) self.assertEqual(response.status_code, status.HTTP_302_FOUND) listing_exists = Listing.objects.filter(pk=self.listing.pk).exists() self.assertEqual(listing_exists, False) def test_delete_view_let_delete_a_listing_only_if_it_has_not_publishing_associated(self): """ Test that the product has associated publishings """ # By default this operation will create a bound listing x1 of that product self.product = f.ProductFactory(name='product1', price=2, description='the best you can have!') self.listing = self.product.listings.first() publishing = PublishingFactory(listing=self.listing) self.client.login(username=self.user.username, password='test') response = self.client.post(reverse('bazaar:listing-delete', kwargs={'pk': self.listing.pk})) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) publishing.delete() response = self.client.post(reverse('bazaar:listing-delete', kwargs={'pk': self.listing.pk})) self.assertEqual(response.status_code, status.HTTP_302_FOUND) listing_exists = Listing.objects.filter(pk=self.listing.pk).exists() self.assertEqual(listing_exists, False)
44.604938
119
0.691392
914
7,226
5.343545
0.16302
0.04095
0.053235
0.037674
0.674038
0.66769
0.652539
0.613432
0.605651
0.518018
0
0.00789
0.193191
7,226
161
120
44.881988
0.829846
0.130778
0
0.430108
0
0
0.12256
0.056897
0
0
0
0
0.225806
1
0.129032
false
0.096774
0.107527
0
0.290323
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
15f98430ae44305a9e31a13aeb782706e3a1fd29
2,141
py
Python
aws/olympic-api/olympic/app.py
kevinle-1/olympic-api
c341328eb9c4ce26fcd08199abf1fb996deebbbf
[ "MIT" ]
4
2021-07-29T06:29:33.000Z
2021-08-31T22:38:21.000Z
aws/olympic-api/olympic/app.py
kevinle-1/olympic-api
c341328eb9c4ce26fcd08199abf1fb996deebbbf
[ "MIT" ]
null
null
null
aws/olympic-api/olympic/app.py
kevinle-1/olympic-api
c341328eb9c4ce26fcd08199abf1fb996deebbbf
[ "MIT" ]
2
2021-07-25T08:51:52.000Z
2021-07-25T18:06:24.000Z
import json import requests from bs4 import BeautifulSoup PAGE_URL = 'https://olympics.com/tokyo-2020/olympic-games/en/results/all-sports/medal-standings.htm' def get_table(html=None): if not html: html = requests.get(PAGE_URL).content site = BeautifulSoup(html, 'html.parser') table = site.find('table', { 'id': 'medal-standing-table' }) return table.findAll('tr')[1:] # Remove header def get_num(value): try: return int(value.find('a').getText()) except: return 0 def get_counts(entry): values = entry.findAll('td', { 'class': 'text-center'}) return int(values[0].find('strong').getText()), { # 4 total, 3 bronze, 2 silver, 1 gold, 0 rank 'gold': get_num(values[1]), 'silver': get_num(values[2]), 'bronze': get_num(values[3]), 'total': get_num(values[4]), } def get_rankings(): rankings = [] for country in get_table(): rank, medals = get_counts(country) rankings.append({ 'country': country.find('a', { 'class': 'country'}).getText(), 'country_alpha3': country.find('div', { 'class': 'playerTag'})['country'], 'rank': rank, 'medals': medals }) return rankings def lambda_handler(event, context): try: country = event['queryStringParameters']['country'] except: country = None print(f'Request -> Country: {country}') rankings = get_rankings() if country: if len(country) == 3: for country_ranking in rankings: if country == country_ranking['country_alpha3']: rankings = country_ranking return { "statusCode": 200, "headers": { "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,X-Amz-Security-Token,Authorization,X-Api-Key,X-Requested-With,Accept,Access-Control-Allow-Methods,Access-Control-Allow-Origin,Access-Control-Allow-Headers", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET" }, "body": json.dumps(rankings), "isBase64Encoded": False }
30.15493
225
0.601588
250
2,141
5.076
0.432
0.061466
0.085106
0.039401
0.066194
0.066194
0.066194
0
0
0
0
0.015442
0.243811
2,141
70
226
30.585714
0.768376
0.026623
0
0.072727
0
0.036364
0.294712
0.135577
0
0
0
0
0
1
0.090909
false
0
0.054545
0
0.254545
0.018182
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15fb00a29a6af7f533e2efe7c7832130560820ef
5,348
py
Python
crawlers/core/thread_types.py
nonemaw/YeTi
92a3ba89f5b7fd8b2d5d3f5929ade0bf0b9e5cbe
[ "MIT" ]
1
2017-10-04T12:21:20.000Z
2017-10-04T12:21:20.000Z
crawlers/core/thread_types.py
nonemaw/YeTi
92a3ba89f5b7fd8b2d5d3f5929ade0bf0b9e5cbe
[ "MIT" ]
null
null
null
crawlers/core/thread_types.py
nonemaw/YeTi
92a3ba89f5b7fd8b2d5d3f5929ade0bf0b9e5cbe
[ "MIT" ]
null
null
null
import queue import json import logging import threading from crawlers.core.flags import FLAGS class BaseThread(threading.Thread): def __init__(self, name: str, worker, pool): threading.Thread.__init__(self, name=name) self._worker = worker # can be a Fetcher/Parser/Saver instance self._thread_pool = pool # ThreadPool def running(self): return def run(self): logging.warning(f'{self.__class__.__name__}[{self.getName()}] started...') while True: try: # keep running self.working() and checking result # break (terminate) thread when self.working() failed # break (terminate) thread when queue is empty, and all jobs # are done if not self.running(): break except queue.Empty: if self._thread_pool.all_done(): break except Exception as e: import sys, os exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] logging.warning(f'{self.__class__.__name__} end: error={str(e)}, file={str(fname)}, line={str(exc_tb.tb_lineno)}') break logging.warning(f'{self.__class__.__name__}[{self.getName()}] ended...') class FetcherThread(BaseThread): def __init__(self, name: str, worker, pool, session=None): super().__init__(name, worker, pool) self.session = session def running(self): """ invoke Fetcher's working() content: (status_code, url, html_text) """ priority, url, data, deep, repeat = self._thread_pool.get_task(FLAGS.FETCH) try: data = json.loads(data) except: data = {} fetch_result, data, content = self._worker.working(url, data, repeat, self.session) # fetch success, update FETCH counter, add task to task_queue_p, for # parser's further process if isinstance(data, dict): data = json.dumps(data) if fetch_result == 1: self._thread_pool.update_flag(FLAGS.FETCH, 1) self._thread_pool.put_task(FLAGS.PARSE, (priority, url, data, deep, content)) # fetch failed, put back to task_queue_f and repeat later elif fetch_result == 0: self._thread_pool.put_task(FLAGS.FETCH, (priority + 1, url, data, deep, repeat + 1)) # current round of fetcher is done, notify task_queue_f with # task_done() to stop block self._thread_pool.finish_task(FLAGS.FETCH) return False if fetch_result == -1 else True class ParserThread(BaseThread): def __init__(self, name: str, worker, pool): super().__init__(name, worker, pool) def running(self): """ invoke Parser's working() get all required urls from target html text content: (status_code, url, html_text) """ priority, url, data, deep, content = self._thread_pool.get_task(FLAGS.PARSE) try: data = json.loads(data) except: data = {} parse_result = 1 urls = [] stamp = () # if data is negative or data has a negative 'save' value, parse the # html, otherwise skip if not data or not data.get('save'): parse_result, urls, stamp = self._worker.working(priority, url, data, deep, content) if parse_result > 0: self._thread_pool.update_flag(FLAGS.PARSE, 1) # add each url in urls list into task_queue_f, waiting for # fetcher's further process for _url, _data, _priority in urls: if isinstance(_data, dict): _data = json.dumps(_data) self._thread_pool.put_task(FLAGS.FETCH, (_priority, _url, _data, deep + 1, 0)) # add current url (already fetched/parsed) into task_queue_s, # waiting for saver's further process # # if data in task_queue_p has a positive 'save' value, or no data but with an url if (data and data.get('save')) or (not data and url): try: # when saving to task_queue_s, delete 'save' key del data['save'] del data['type'] data = json.dumps(data) except: pass self._thread_pool.put_task(FLAGS.SAVE, (url, data, stamp)) # current round of parser is done, notify task_queue_p with # task_done() to stop block self._thread_pool.finish_task(FLAGS.PARSE) return True class SaverThread(BaseThread): def __init__(self, name: str, worker, pool): super().__init__(name, worker, pool) def running(self): """ invoke Saver's working() """ url, data, stamp = self._thread_pool.get_task(FLAGS.SAVE) save_result = self._worker.working(url, data, stamp) if save_result: self._thread_pool.update_flag(FLAGS.SAVE, 1) # current round of saver is done, notify task_queue_s with # task_done() to stop block self._thread_pool.finish_task(FLAGS.SAVE) return True
35.184211
130
0.583209
665
5,348
4.454135
0.237594
0.050641
0.070898
0.032073
0.411884
0.341999
0.259284
0.229575
0.139095
0.139095
0
0.003572
0.319559
5,348
151
131
35.417219
0.810387
0.227188
0
0.318182
0
0.011364
0.053785
0.034612
0
0
0
0
0
1
0.102273
false
0.011364
0.068182
0.011364
0.261364
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15fb43831ed30c20a10a9d980a0fdb47897df9ba
30
py
Python
SampleAIs/Sample_Sophie/__init__.py
YSabarad/monopyly
0460f2452c83846b6b9e3b234be411e12a86d69c
[ "MIT" ]
4
2015-11-04T21:18:40.000Z
2020-12-26T21:15:23.000Z
SampleAIs/Sample_Sophie/__init__.py
YSabarad/monopyly
0460f2452c83846b6b9e3b234be411e12a86d69c
[ "MIT" ]
2
2021-08-09T18:19:58.000Z
2021-08-10T14:44:54.000Z
SampleAIs/Sample_Sophie/__init__.py
YSabarad/monopyly
0460f2452c83846b6b9e3b234be411e12a86d69c
[ "MIT" ]
6
2015-08-01T17:54:17.000Z
2022-02-28T00:00:21.000Z
from .sophie import SophieAI
10
28
0.8
4
30
6
1
0
0
0
0
0
0
0
0
0
0
0
0.166667
30
2
29
15
0.96
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
6
15fb6a076074eb470434200bde6610f2e5b3ecae
1,848
py
Python
develop/tools/import-prep.py
Gautamverma66/pycon
1ca95727619dbbe82483227e0964402b433131ee
[ "BSD-3-Clause" ]
null
null
null
develop/tools/import-prep.py
Gautamverma66/pycon
1ca95727619dbbe82483227e0964402b433131ee
[ "BSD-3-Clause" ]
null
null
null
develop/tools/import-prep.py
Gautamverma66/pycon
1ca95727619dbbe82483227e0964402b433131ee
[ "BSD-3-Clause" ]
1
2020-09-30T18:09:16.000Z
2020-09-30T18:09:16.000Z
#!/usr/bin/env python2.7 # # Take various CSV inputs and produce a read-to-import conference schedule. import pandas as pd from datetime import date def main(): dfs = [] t = pd.read_csv('talks.csv') t['kind_slug'] = 'talk' t['proposal_id'] = t.pop('proposal') t['day'] = date(2016, 5, 30) + pd.to_timedelta(t['day'], 'd') t['room'] = 'Session ' + t['room'] t = t[['kind_slug', 'proposal_id', 'day', 'time', 'duration', 'room']] dfs.append(t) t = pd.read_csv('~/Downloads/PyCon 2016 Tutorial Counts - Sheet1.csv') rooms = {str(title).strip().lower(): room_name for title, room_name in t[['Title', 'Room Name']].values} t = pd.read_csv('tutorials.csv') t['kind_slug'] = 'tutorial' t['proposal_id'] = t.pop('ID') t['day'] = pd.to_datetime(t['Day Slot']) t['time'] = t['Time Slot'].str.extract('([^ ]*)') t['duration'] = 200 t['room'] = t['Title'].str.strip().str.lower().map(rooms) t = t[['kind_slug', 'proposal_id', 'day', 'time', 'duration', 'room']] dfs.append(t) t = pd.read_csv('sponsor-tutorials-edited.csv') t = t[t['ID'].notnull()].copy() t['kind_slug'] = 'sponsor-tutorial' #t['kind_slug'] = 'tutorial' t['proposal_id'] = t.pop('ID').astype(int) t['day'] = pd.to_datetime(t['Day Slot']) t['time'] = t['Time Slot'].str.extract('([^ ]*)') t['room'] = t['Room'] # t = t.sort_values(['Title']) # t['room'] = t.groupby(['day', 'time'])['room'].cumsum() # t['room'] = t['room'].apply(lambda n: 'Sponsor Room {}'.format(n)) t = t[['kind_slug', 'proposal_id', 'day', 'time', 'duration', 'room']] dfs.append(t) #t.to_csv('schedule.csv', index=False) c = pd.concat(dfs).rename(columns={'time': 'start'}) c.to_csv('schedule.csv', index=False) if __name__ == '__main__': main()
28.875
75
0.566017
272
1,848
3.724265
0.3125
0.017769
0.062192
0.039487
0.395854
0.381046
0.329714
0.329714
0.329714
0.329714
0
0.011371
0.191017
1,848
63
76
29.333333
0.666221
0.169372
0
0.277778
0
0
0.309758
0.018337
0
0
0
0
0
1
0.027778
false
0
0.055556
0
0.083333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15fc22916a07202affa161b6e886fa7702bd9a42
2,468
py
Python
2020/05/05.py
nhtsai/advent-of-code
d79ec16eb9014acc766805e9d922168aaa2809de
[ "MIT" ]
null
null
null
2020/05/05.py
nhtsai/advent-of-code
d79ec16eb9014acc766805e9d922168aaa2809de
[ "MIT" ]
null
null
null
2020/05/05.py
nhtsai/advent-of-code
d79ec16eb9014acc766805e9d922168aaa2809de
[ "MIT" ]
null
null
null
NUM_ROWS = 128 NUM_COLS = 8 """ Cool solution: https://github.com/tymofij/advent-of-code-2020/blob/master/05/seats.py Cool solution using str.translate: def seat_id(s, t=str.maketrans("FBLR", "0101")): return int(s.translate(t), 2) def max_seat_id(boarding_passes): return max(map(seat_id, boarding_passes)) def missing_seat(boarding_passes, t=str.maketrans("FBLR", "0101")): return max(set(range(920)) - set(int(s.translate(t), 2) for s in boarding_passes)) """ def part1(l): highest_id = -1 for p in l: row = -1 col = -1 r_lo = c_lo = 0 r_hi = NUM_ROWS - 1 c_hi = NUM_COLS - 1 for s in p: r_mid = r_lo + (r_hi - r_lo) // 2 c_mid = c_lo + (c_hi - c_lo) // 2 if s == 'F': r_hi = r_mid elif s == 'B': r_lo = r_mid + 1 elif s == 'R': c_lo = c_mid + 1 elif s == 'L': c_hi = c_mid else: return -1 assert r_hi == r_lo assert c_hi == c_lo row, col = r_hi, c_hi seat_id = row * 8 + col if seat_id > highest_id: highest_id = seat_id return highest_id def part2(l): seats = [] for p in l: row = -1 col = -1 r_lo = c_lo = 0 r_hi = NUM_ROWS - 1 c_hi = NUM_COLS - 1 for s in p: r_mid = r_lo + (r_hi - r_lo) // 2 c_mid = c_lo + (c_hi - c_lo) // 2 if s == 'F': r_hi = r_mid elif s == 'B': r_lo = r_mid + 1 elif s == 'R': c_lo = c_mid + 1 elif s == 'L': c_hi = c_mid else: return -1 assert r_hi == r_lo assert c_hi == c_lo row, col = r_hi, c_hi seat_id = row * 8 + col seats.append(seat_id) # all_seats = [r * 8 + c for r in range(NUM_ROWS) for c in range(NUM_COLS)] # missing = [x for x in all_seats if x not in seats] # my_seat = [x for x in missing if x - 1 not in missing and x + 1 not in missing][0] my_seat = [s for s in range(min(seats), max(seats) + 1) if s not in seats][0] return my_seat if __name__ == '__main__': with open('input.txt', 'r') as f: l = [x.strip().upper() for x in f] print("Part 1:", part1(l)) print("Part 2:", part2(l))
25.443299
90
0.47812
402
2,468
2.708955
0.20398
0.027548
0.022039
0.022039
0.453627
0.400367
0.350781
0.350781
0.350781
0.350781
0
0.039216
0.400729
2,468
96
91
25.708333
0.697093
0.083874
0
0.730159
0
0
0.022472
0
0
0
0
0
0.063492
1
0.031746
false
0
0
0
0.095238
0.031746
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
15fdf4924a3b098bc325a7b35edf84b4ae175290
997
py
Python
utilities/resize_images.py
bmhopkinson/Marsh_Ann
7d1baaa444392622967dd1ed12f9c7a23c5fb018
[ "MIT" ]
null
null
null
utilities/resize_images.py
bmhopkinson/Marsh_Ann
7d1baaa444392622967dd1ed12f9c7a23c5fb018
[ "MIT" ]
null
null
null
utilities/resize_images.py
bmhopkinson/Marsh_Ann
7d1baaa444392622967dd1ed12f9c7a23c5fb018
[ "MIT" ]
null
null
null
import os import cv2 import numpy as np import re path_regex = re.compile('^.+?/(.*)') def resize_image(im, factor): row, col, chan = im.shape col_re = np.rint(col*factor).astype(int) row_re = np.rint(row*factor).astype(int) im = cv2.resize(im, (col_re, row_re)) #resize patch return im imdir = '../Marsh_Images_BH/Row1_1_2748to2797' outdir = './image_resize_BH' for (dirpath, dirname, files) in os.walk(imdir, topdown='True'): for name in files: fullpath = os.path.join(dirpath,name) print(name) m = path_regex.findall(dirpath) dirpath_sub = m[0] new_dirpath = os.path.join(outdir,dirpath_sub) if not os.path.isdir(new_dirpath): os.makedirs(new_dirpath) file_base = os.path.splitext(name)[0] im = cv2.imread(fullpath) im_alt = resize_image(im, 0.2) outfile = file_base + '_small.jpg' outpath = os.path.join(new_dirpath, outfile) cv2.imwrite(outpath,im_alt)
27.694444
64
0.636911
148
997
4.121622
0.432432
0.04918
0.04918
0
0
0
0
0
0
0
0
0.023438
0.229689
997
35
65
28.485714
0.770833
0.012036
0
0
0
0
0.077236
0.036585
0
0
0
0
0
1
0.035714
false
0
0.142857
0
0.214286
0.035714
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15fe23beb9c7568305a1094a355c8b8ff59b537e
294
py
Python
arc/setupc.py
m-schleier/ARC-Alkali-Rydberg-Calculator
eabba3bc9ac2e37ba3a8dbba18d39771dcbbb9fd
[ "BSD-3-Clause" ]
53
2016-12-13T11:57:07.000Z
2022-03-23T20:25:36.000Z
arc/setupc.py
m-schleier/ARC-Alkali-Rydberg-Calculator
eabba3bc9ac2e37ba3a8dbba18d39771dcbbb9fd
[ "BSD-3-Clause" ]
78
2016-12-21T11:56:03.000Z
2022-03-15T21:01:30.000Z
arc/setupc.py
m-schleier/ARC-Alkali-Rydberg-Calculator
eabba3bc9ac2e37ba3a8dbba18d39771dcbbb9fd
[ "BSD-3-Clause" ]
39
2016-12-20T07:17:50.000Z
2022-03-02T17:27:44.000Z
from distutils.core import setup, Extension from numpy.distutils.misc_util import get_numpy_include_dirs setup(ext_modules=[Extension("arc_c_extensions", ["arc_c_extensions.c"], extra_compile_args = ['-Wall', '-O3'], include_dirs=get_numpy_include_dirs())])
42
72
0.707483
38
294
5.078947
0.578947
0.170984
0.15544
0.196891
0
0
0
0
0
0
0
0.004132
0.176871
294
6
73
49
0.793388
0
0
0
0
0
0.142857
0
0
0
0
0
0
1
0
true
0
0.4
0
0.4
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
15fe4d22550f5d656a8766cbb160d9cad971c027
5,133
py
Python
load.py
OdysseyScorpio/FactionGist
a3af4b52557890cb9c2cad20a740545917db7ec4
[ "MIT" ]
3
2019-10-17T08:28:55.000Z
2020-06-02T15:43:32.000Z
load.py
OdysseyScorpio/FactionGist
a3af4b52557890cb9c2cad20a740545917db7ec4
[ "MIT" ]
11
2019-10-17T08:32:09.000Z
2019-10-21T07:14:13.000Z
load.py
OdysseyScorpio/FactionGist
a3af4b52557890cb9c2cad20a740545917db7ec4
[ "MIT" ]
3
2019-10-17T08:33:51.000Z
2021-07-05T18:05:38.000Z
import sys import os import ttk import Tkinter as tk import tkMessageBox from ttkHyperlinkLabel import HyperlinkLabel from config import applongname, appversion import myNotebook as nb import json import requests import zlib import re import webbrowser this = sys.modules[__name__] this.apiURL = "http://factiongist.herokuapp.com" FG_VERSION = "0.0.3" availableFactions = tk.StringVar() try: this_fullpath = os.path.realpath(__file__) this_filepath, this_extension = os.path.splitext(this_fullpath) config_file = this_filepath + "config.json" with open(config_file) as f: data = json.load(f) availableFactions.set(data) except: availableFactions.set("everyone") if(availableFactions.get() == "everyone"): msginfo = ['Please update your Reporting Faction.', '\nYou can report to one or many factions,' 'simply separate each faction with a comma.\n' '\nFile > Settings > FactionGist'] tkMessageBox.showinfo("Reporting Factions", "\n".join(msginfo)) def plugin_app(parent): this.parent = parent this.frame = tk.Frame(parent) filter_update() return this.frame def filter_update(): this.parent.after(300000, filter_update) response = requests.get(this.apiURL + "/listeningFor") if(response.status_code == 200): this.listening = response.content def plugin_start(plugin_dir): awake = requests.get(this.apiURL) check_version() return 'FactionGist' def plugin_prefs(parent): PADX = 10 # formatting frame = nb.Frame(parent) frame.columnconfigure(5, weight=1) HyperlinkLabel(frame, text='FactionGist GitHub', background=nb.Label().cget('background'), url='https://github.com/OdysseyScorpio/FactionGist', underline=True).grid(columnspan=2, padx=PADX, sticky=tk.W) nb.Label(frame, text="FactionGist - crazy-things-might-happen-pre-pre-alpha release Version {VER}".format( VER=FG_VERSION)).grid(columnspan=2, padx=PADX, sticky=tk.W) nb.Label(frame).grid() # spacer nb.Button(frame, text="UPGRADE", command=upgrade_callback).grid(row=10, column=0, columnspan=2, padx=PADX, sticky=tk.W) nb.lblReportingFactions = tk.Label(frame) nb.lblReportingFactions.grid( row=3, column=0, columnspan=2, padx=PADX, sticky=tk.W) nb.lblReportingFactions.config(text='Factions I am supporting') nb.Entry1 = tk.Entry(frame, textvariable=availableFactions) nb.Entry1.grid(row=4, column=0, columnspan=2, padx=PADX, sticky=tk.W+tk.E) return frame def check_version(): response = requests.get(this.apiURL + "/version") version = response.content if version != FG_VERSION: upgrade_callback() def upgrade_callback(): this_fullpath = os.path.realpath(__file__) this_filepath, this_extension = os.path.splitext(this_fullpath) corrected_fullpath = this_filepath + ".py" try: response = requests.get(this.apiURL + "/download") if (response.status_code == 200): with open(corrected_fullpath, "wb") as f: f.seek(0) f.write(response.content) f.truncate() f.flush() os.fsync(f.fileno()) this.upgrade_applied = True # Latch on upgrade successful msginfo = ['Upgrade has completed sucessfully.', 'Please close and restart EDMC'] tkMessageBox.showinfo("Upgrade status", "\n".join(msginfo)) sys.stderr.write("Finished plugin upgrade!\n") else: msginfo = ['Upgrade failed. Bad server response', 'Please try again'] tkMessageBox.showinfo("Upgrade status", "\n".join(msginfo)) except: sys.stderr.writelines( "Upgrade problem when fetching the remote data: {E}\n".format(E=sys.exc_info()[0])) msginfo = ['Upgrade encountered a problem.', 'Please try again, and restart if problems persist'] tkMessageBox.showinfo("Upgrade status", "\n".join(msginfo)) def dashboard_entry(cmdr, is_beta, entry): this.cmdr = cmdr def journal_entry(cmdr, is_beta, system, station, entry, state): if entry['event'] in this.listening: entry['commanderName'] = cmdr entry['pluginVersion'] = FG_VERSION entry['currentSystem'] = system entry['currentStation'] = station entry['reportingFactions'] = [availableFactions.get()] transmit_json = json.dumps(entry) url_jump = this.apiURL + '/events' headers = {'content-type': 'application/json'} response = requests.post( url_jump, data=transmit_json, headers=headers, timeout=7) def plugin_stop(): sys.stderr.writelines("\nGood bye commander\n") config = availableFactions.get() this_fullpath = os.path.realpath(__file__) this_filepath, this_extension = os.path.splitext(this_fullpath) config_file = this_filepath + "config.json" with open(config_file, 'w') as f: json.dump(config, f)
36.147887
130
0.653029
607
5,133
5.413509
0.352554
0.018259
0.024346
0.028911
0.258065
0.21759
0.21759
0.176506
0.176506
0.165855
0
0.0091
0.229301
5,133
141
131
36.404255
0.821537
0.008767
0
0.142857
0
0
0.181943
0.007671
0
0
0
0
0
1
0.07563
false
0
0.109244
0
0.210084
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15ff229d57bd444a73d08386dd948e890ca375a0
12,542
py
Python
hexa/plugins/connector_s3/models.py
qgerome/openhexa-app
8c9377b2ad972121d8e9575f5d52420212b52ed4
[ "MIT" ]
4
2021-07-19T12:53:21.000Z
2022-01-26T17:45:02.000Z
hexa/plugins/connector_s3/models.py
qgerome/openhexa-app
8c9377b2ad972121d8e9575f5d52420212b52ed4
[ "MIT" ]
20
2021-05-17T12:27:06.000Z
2022-03-30T11:35:26.000Z
hexa/plugins/connector_s3/models.py
qgerome/openhexa-app
8c9377b2ad972121d8e9575f5d52420212b52ed4
[ "MIT" ]
2
2021-09-07T04:19:59.000Z
2022-02-08T15:33:29.000Z
import os from logging import getLogger from django.core.exceptions import ValidationError from django.db import models, transaction from django.template.defaultfilters import filesizeformat, pluralize from django.urls import reverse from django.utils import timezone from django.utils.translation import gettext_lazy as _ from hexa.catalog.models import CatalogQuerySet, Datasource, Entry from hexa.catalog.sync import DatasourceSyncResult from hexa.core.models import Base, Permission from hexa.core.models.cryptography import EncryptedTextField from hexa.plugins.connector_s3.api import ( S3ApiError, get_object_metadata, head_bucket, list_objects_metadata, ) from hexa.plugins.connector_s3.region import AWSRegion logger = getLogger(__name__) class Credentials(Base): """We actually only need one set of credentials. These "principal" credentials will be then used to generate short-lived credentials with a tailored policy giving access only to the buckets that the user team can access""" class Meta: verbose_name = "S3 Credentials" verbose_name_plural = "S3 Credentials" ordering = ("username",) username = models.CharField(max_length=200) access_key_id = EncryptedTextField() secret_access_key = EncryptedTextField() default_region = models.CharField( max_length=50, default=AWSRegion.EU_CENTRAL_1, choices=AWSRegion.choices ) user_arn = models.CharField(max_length=200) app_role_arn = models.CharField(max_length=200) @property def display_name(self): return self.username class BucketPermissionMode(models.IntegerChoices): READ_ONLY = 1, "Read Only" READ_WRITE = 2, "Read Write" class BucketQuerySet(CatalogQuerySet): def filter_by_mode(self, user, mode: BucketPermissionMode = None): if user.is_active and user.is_superuser: # if SU -> all buckets are RW; so if mode is provided and mode == RO -> no buckets available if mode == BucketPermissionMode.READ_ONLY: return self.none() else: return self if mode is None: # return all buckets modes = [BucketPermissionMode.READ_ONLY, BucketPermissionMode.READ_WRITE] else: modes = [mode] return self.filter( bucketpermission__team__in=[t.pk for t in user.team_set.all()], bucketpermission__mode__in=modes, ).distinct() def filter_for_user(self, user): if user.is_active and user.is_superuser: return self return self.filter( bucketpermission__team__in=[t.pk for t in user.team_set.all()], ).distinct() class Bucket(Datasource): def get_permission_set(self): return self.bucketpermission_set.all() class Meta: verbose_name = "S3 Bucket" ordering = ("name",) name = models.CharField(max_length=200) region = models.CharField( max_length=50, default=AWSRegion.EU_CENTRAL_1, choices=AWSRegion.choices ) objects = BucketQuerySet.as_manager() searchable = True # TODO: remove (see comment in datasource_index command) @property def principal_credentials(self): try: return Credentials.objects.get() except (Credentials.DoesNotExist, Credentials.MultipleObjectsReturned): raise ValidationError( "The S3 connector plugin should be configured with a single Credentials entry" ) def refresh(self, path): metadata = get_object_metadata( principal_credentials=self.principal_credentials, bucket=self, object_key=path, ) try: s3_object = Object.objects.get(bucket=self, key=path) except Object.DoesNotExist: Object.create_from_metadata(self, metadata) except Object.MultipleObjectsReturned: logger.warning( "Bucket.refresh(): incoherent object list for bucket %s", self.id ) else: s3_object.update_from_metadata(metadata) s3_object.save() def clean(self): try: head_bucket(principal_credentials=self.principal_credentials, bucket=self) except S3ApiError as e: raise ValidationError(e) def sync(self): """Sync the bucket by querying the S3 API""" s3_objects = list_objects_metadata( principal_credentials=self.principal_credentials, bucket=self, ) # Lock the bucket with transaction.atomic(): Bucket.objects.select_for_update().get(pk=self.pk) # Sync data elements with transaction.atomic(): created_count = 0 updated_count = 0 identical_count = 0 deleted_count = 0 remote = set() local = {str(x.key): x for x in self.object_set.all()} for s3_object in s3_objects: key = s3_object["Key"] remote.add(key) if key in local: if ( s3_object.get("ETag") == local[key].etag and s3_object["Type"] == local[key].type ): # If it has the same key bot not the same ETag: the file was updated on S3 # (Sometime, the ETag contains double quotes -> strip them) identical_count += 1 else: updated_count += 1 local[key].update_from_metadata(s3_object) local[key].save() else: Object.create_from_metadata(self, s3_object) created_count += 1 # cleanup unmatched objects for key, obj in local.items(): if key not in remote: deleted_count += 1 obj.delete() # Flag the datasource as synced self.last_synced_at = timezone.now() self.save() return DatasourceSyncResult( datasource=self, created=created_count, updated=updated_count, identical=identical_count, deleted=deleted_count, ) @property def content_summary(self): count = self.object_set.count() return ( "" if count == 0 else _("%(count)d object%(suffix)s") % {"count": count, "suffix": pluralize(count)} ) def populate_index(self, index): index.last_synced_at = self.last_synced_at index.content = self.content_summary index.path = [self.pk.hex] index.external_id = self.name index.external_name = self.name index.external_type = "bucket" index.search = f"{self.name}" index.datasource_name = self.name index.datasource_id = self.id @property def display_name(self): return self.name def __str__(self): return self.display_name def writable_by(self, user): if not user.is_active: return False elif user.is_superuser: return True elif ( BucketPermission.objects.filter( bucket=self, team_id__in=user.team_set.all().values("id"), mode=BucketPermissionMode.READ_WRITE, ).count() > 0 ): return True else: return False def get_absolute_url(self): return reverse( "connector_s3:datasource_detail", kwargs={"datasource_id": self.id} ) class BucketPermission(Permission): bucket = models.ForeignKey("Bucket", on_delete=models.CASCADE) mode = models.IntegerField( choices=BucketPermissionMode.choices, default=BucketPermissionMode.READ_WRITE ) class Meta: unique_together = [("bucket", "team")] def index_object(self): self.bucket.build_index() def __str__(self): return f"Permission for team '{self.team}' on bucket '{self.bucket}'" class ObjectQuerySet(CatalogQuerySet): def filter_for_user(self, user): if user.is_active and user.is_superuser: return self return self.filter(bucket__in=Bucket.objects.filter_for_user(user)) class Object(Entry): def get_permission_set(self): return self.bucket.bucketpermission_set.all() class Meta: verbose_name = "S3 Object" ordering = ("key",) unique_together = [("bucket", "key")] bucket = models.ForeignKey("Bucket", on_delete=models.CASCADE) key = models.TextField() parent_key = models.TextField() size = models.PositiveBigIntegerField() storage_class = models.CharField(max_length=200) # TODO: choices type = models.CharField(max_length=200) # TODO: choices last_modified = models.DateTimeField(null=True, blank=True) etag = models.CharField(max_length=200, null=True, blank=True) objects = ObjectQuerySet.as_manager() searchable = True # TODO: remove (see comment in datasource_index command) def save(self, *args, **kwargs): if self.parent_key is None: self.parent_key = self.compute_parent_key(self.key) super().save(*args, **kwargs) def populate_index(self, index): index.last_synced_at = self.bucket.last_synced_at index.external_name = self.filename index.path = [self.bucket.pk.hex, self.pk.hex] index.context = self.parent_key index.external_id = self.key index.external_type = self.type index.external_subtype = self.extension index.search = f"{self.filename} {self.key}" index.datasource_name = self.bucket.name index.datasource_id = self.bucket.id def __repr__(self): return f"<Object s3://{self.bucket.name}/{self.key}>" @property def display_name(self): return self.filename @property def filename(self): if self.key.endswith("/"): return os.path.basename(self.key[:-1]) return os.path.basename(self.key) @property def extension(self): return os.path.splitext(self.key)[1].lstrip(".") def full_path(self): return f"s3://{self.bucket.name}/{self.key}" @classmethod def compute_parent_key(cls, key): if key.endswith("/"): # This is a directory return os.path.dirname(os.path.dirname(key)) + "/" else: # This is a file return os.path.dirname(key) + "/" @property def file_size_display(self): return filesizeformat(self.size) if self.size > 0 else "-" @property def type_display(self): if self.type == "directory": return _("Directory") else: if verbose_file_type := self.verbose_file_type: return verbose_file_type else: return _("File") @property def verbose_file_type(self): file_type = { "xlsx": "Excel file", "md": "Markdown document", "ipynb": "Jupyter Notebook", "csv": "CSV file", }.get(self.extension) if file_type: return _(file_type) else: return None def update_from_metadata(self, metadata): self.key = metadata["Key"] self.parent_key = self.compute_parent_key(metadata["Key"]) self.size = metadata["Size"] self.storage_class = metadata["StorageClass"] self.type = metadata["Type"] self.last_modified = metadata["LastModified"] self.etag = metadata["ETag"] @classmethod def create_from_metadata(cls, bucket, metadata): return cls.objects.create( bucket=bucket, key=metadata["Key"], parent_key=cls.compute_parent_key(metadata["Key"]), storage_class=metadata["StorageClass"], last_modified=metadata["LastModified"], etag=metadata["ETag"], type=metadata["Type"], size=metadata["Size"], ) def get_absolute_url(self): return reverse( "connector_s3:object_detail", kwargs={"bucket_id": self.bucket.id, "path": self.key}, )
32.492228
112
0.603253
1,391
12,542
5.265996
0.196262
0.020478
0.022116
0.029488
0.264164
0.22116
0.199317
0.148805
0.102116
0.089829
0
0.007787
0.303779
12,542
385
113
32.576623
0.831081
0.060676
0
0.2443
0
0
0.062048
0.010639
0
0
0
0.002597
0
1
0.104235
false
0
0.045603
0.045603
0.384365
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
15ff677f5997837a0bb374dc2d35fd4c8a6040d2
301
py
Python
Curso de Python Completo e Proficional/Aulas/Aula 28 - Operadores de identidade Python.py
MauriSdL/Programs-in-Python
79e35bc9488fdd377f161b0faf573b2df765fdb3
[ "MIT" ]
null
null
null
Curso de Python Completo e Proficional/Aulas/Aula 28 - Operadores de identidade Python.py
MauriSdL/Programs-in-Python
79e35bc9488fdd377f161b0faf573b2df765fdb3
[ "MIT" ]
null
null
null
Curso de Python Completo e Proficional/Aulas/Aula 28 - Operadores de identidade Python.py
MauriSdL/Programs-in-Python
79e35bc9488fdd377f161b0faf573b2df765fdb3
[ "MIT" ]
null
null
null
# Operadores de identidade # serve para compara objetos não somente se eles sao iguais , mas sim se estao no mesmo local de memoria(na mesma variavel) x = ["apple", "banana"] y = ["apple", "banana"] z = x print(x is z) print(x is y) print(x == y) print(x is not z) print(x is not y) print(x != y)
20.066667
123
0.667774
57
301
3.526316
0.54386
0.179104
0.159204
0.089552
0
0
0
0
0
0
0
0
0.20598
301
15
124
20.066667
0.841004
0.48505
0
0
0
0
0.144737
0
0
0
0
0
0
1
0
false
0
0
0
0
0.666667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
1
c600a7c769c43dfaa68adc940ed5418cbaa4e03b
121
py
Python
treasureisland/Parameters.py
idoerg/GenomicIslandPrediction
c50edd0c280efca3fac90674a9695cb763c27e31
[ "MIT" ]
null
null
null
treasureisland/Parameters.py
idoerg/GenomicIslandPrediction
c50edd0c280efca3fac90674a9695cb763c27e31
[ "MIT" ]
null
null
null
treasureisland/Parameters.py
idoerg/GenomicIslandPrediction
c50edd0c280efca3fac90674a9695cb763c27e31
[ "MIT" ]
null
null
null
WINDOW_SIZE = 8000 KMER_SIZE = 6 UPPER_THRESHOLD = 0.75 LOWER_THRESHOLD = 0.5 TUNE_METRIC = 1000 MINIMUM_GI_SIZE = 10000
17.285714
23
0.785124
21
121
4.190476
0.809524
0.227273
0
0
0
0
0
0
0
0
0
0.184466
0.14876
121
6
24
20.166667
0.669903
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
c6013d78d67df4cefccabade66230bcf85da9cde
343
py
Python
ex109/teste.py
almmessias/CursoPython
4cec6946f32002cbd5d3b802df11ea1ba74169f5
[ "MIT" ]
null
null
null
ex109/teste.py
almmessias/CursoPython
4cec6946f32002cbd5d3b802df11ea1ba74169f5
[ "MIT" ]
null
null
null
ex109/teste.py
almmessias/CursoPython
4cec6946f32002cbd5d3b802df11ea1ba74169f5
[ "MIT" ]
null
null
null
import moeda n = float(input('Digite o preço: R$')) print (f'O dobro de {moeda.moeda(n)} é {moeda.dobro(n, True)}') print (f'A metade de {moeda.moeda(n)} é {moeda.metade(n, True)}') print (f'O aumento de 10% de {moeda.moeda(n)} é {moeda.aumento(n, 10, True)}') print (f'O desconto de 13% de {moeda.moeda(n)} é {moeda.desconto(n, 13, True)}')
42.875
80
0.650146
67
343
3.328358
0.313433
0.134529
0.215247
0.233184
0.340807
0.340807
0
0
0
0
0
0.027027
0.137026
343
7
81
49
0.726351
0
0
0
0
0.333333
0.758017
0
0
0
0
0
0
1
0
false
0
0.166667
0
0.166667
0.666667
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
6
c60143a70f259a4e959098d87fdd7674fa7e33dc
1,618
py
Python
vi/vi/csp/backtrack_search.py
pveierland/permve-ntnu-it3105
6a7e4751de47b091c1c9c59560c19a8452698d81
[ "CC0-1.0" ]
null
null
null
vi/vi/csp/backtrack_search.py
pveierland/permve-ntnu-it3105
6a7e4751de47b091c1c9c59560c19a8452698d81
[ "CC0-1.0" ]
null
null
null
vi/vi/csp/backtrack_search.py
pveierland/permve-ntnu-it3105
6a7e4751de47b091c1c9c59560c19a8452698d81
[ "CC0-1.0" ]
null
null
null
import vi.csp import collections import operator BacktrackStatistics = collections.namedtuple( 'BacktrackStatistics', ['calls', 'failures']) def backtrack_search(network): statistics = BacktrackStatistics(calls=0, failures=0) # Ensure arc consistency before making any assumptions: return backtrack(vi.csp.general_arc_consistency(network), statistics) def backtrack(network, statistics): def select_unassigned_variable(): # Use Minimum-Remaining-Values heuristic: return min(((variable, domain) for variable, domain in network.domains.items() if len(domain) > 1), key=operator.itemgetter(1))[0] def order_domain_variables(): return network.domains[variable] statistics = BacktrackStatistics(statistics.calls + 1, statistics.failures) if all(len(domain) == 1 for domain in network.domains.values()): return network, statistics variable = select_unassigned_variable() for value in order_domain_variables(): successor = network.copy() successor.domains[variable] = [value] successor = vi.csp.general_arc_consistency_rerun(successor, variable) if all(len(domain) >= 1 for domain in successor.domains.values()): result, statistics = backtrack(successor, statistics) if result: return result, statistics statistics = BacktrackStatistics(statistics.calls, statistics.failures + 1) return None, statistics
32.36
77
0.644623
158
1,618
6.512658
0.329114
0.066084
0.029155
0.029155
0.101069
0.050535
0.050535
0.050535
0
0
0
0.007614
0.269468
1,618
49
78
33.020408
0.862944
0.057478
0
0
0
0
0.021025
0
0
0
0
0
0
1
0.121212
false
0
0.090909
0.060606
0.393939
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c601aedeadeb98d2c741f809b0374722d418f823
1,377
py
Python
k_means.py
lgq9220/easy12306
e31abd1c7675e2acb37f4653ab88cae49d2317cc
[ "Artistic-2.0" ]
null
null
null
k_means.py
lgq9220/easy12306
e31abd1c7675e2acb37f4653ab88cae49d2317cc
[ "Artistic-2.0" ]
null
null
null
k_means.py
lgq9220/easy12306
e31abd1c7675e2acb37f4653ab88cae49d2317cc
[ "Artistic-2.0" ]
null
null
null
#! env python # coding: utf-8 # 功能:对文字部分使用k-means算法进行聚类 import os import time import sys import cv2 from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn.externals import joblib def get_img_as_vector(fn): im = cv2.imread(fn) im = im[:, :, 0] retval, dst = cv2.threshold(im, 128, 1, cv2.THRESH_BINARY_INV) return dst.reshape(dst.size) def main(): # 读取训练用数据 print('Start: read data', time.process_time()) fns = os.listdir('ocr') X = [get_img_as_vector(os.path.join('ocr', fn)) for fn in fns] print('Samples', len(X), 'Feature', len(X[0])) # PCA print('Start: PCA', time.process_time()) pca = PCA(n_components=0.99) pca.fit(X) X = pca.transform(X) print('Samples', len(X), 'Feature', len(X[0])) sys.stdout.flush() # 训练 print('Start: train', time.process_time()) n_clusters = 2000 # 聚类中心个数 estimator = KMeans(n_clusters, n_init=1, max_iter=20, verbose=True) estimator.fit(X) print('Clusters', estimator.n_clusters, 'Iter', estimator.n_iter_) print('Start: classify', time.process_time()) fp = open('result11.txt', 'w') for fn, c in zip(fns, estimator.labels_): print(fn, c, file=fp) fp.close() print('Start: save model', time.process_time()) joblib.dump(estimator, 'k-means11.pkl') if __name__ == '__main__': main()
27.54
71
0.647785
205
1,377
4.204878
0.473171
0.058005
0.087007
0.032483
0.064965
0.064965
0.064965
0.064965
0
0
0
0.023466
0.195352
1,377
49
72
28.102041
0.754513
0.052288
0
0.054054
0
0
0.115562
0
0
0
0
0
0
1
0.054054
false
0
0.189189
0
0.27027
0.243243
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c60244641d848895dbb47d903f04c522a8e5355d
14,735
py
Python
datasets/blender_efficient_sm.py
ktiwary2/nerf_pl
99d40cba3a2d9a11d6988cb1a74cf29035a1ab5e
[ "MIT" ]
null
null
null
datasets/blender_efficient_sm.py
ktiwary2/nerf_pl
99d40cba3a2d9a11d6988cb1a74cf29035a1ab5e
[ "MIT" ]
null
null
null
datasets/blender_efficient_sm.py
ktiwary2/nerf_pl
99d40cba3a2d9a11d6988cb1a74cf29035a1ab5e
[ "MIT" ]
null
null
null
import torch from torch.utils.data import Dataset import json import numpy as np import os from PIL import Image, ImageFilter from torchvision import transforms as T from models.camera import Camera from tqdm import tqdm from .ray_utils import * class BlenderEfficientShadows(Dataset): def __init__(self, root_dir, split='train', img_wh=(800, 800), hparams=None): self.root_dir = root_dir self.split = split assert img_wh[0] == img_wh[1], 'image width must equal image height!' self.img_wh = img_wh print("Training Image size:", img_wh) self.define_transforms() self.white_back = True # self.white_back = False # Setting it to False (!) self.hparams = hparams self.black_and_white = False if self.hparams is not None and self.hparams.black_and_white_test: self.black_and_white = True self.read_meta() self.hparams.coords_trans = False print("------------") print("NOTE: self.hparams.coords_trans is set to {} ".format(self.hparams.coords_trans)) print("------------") def read_meta(self): # self.split = 'train' with open(os.path.join(self.root_dir, # f"transforms_train.json"), 'r') as f: f"transforms_{self.split}.json"), 'r') as f: self.meta = json.load(f) w, h = self.img_wh print("Root Directory: ".format(self.root_dir)) # if 'bunny' or 'box' or 'vase' in self.root_dir: # res = 200 # these imgs have original size of 200 # else: # res = 800 res = 800 if 'resolution' in self.meta.keys(): res = self.meta['resolution'] print("-------------------------------") print("RESOLUTION OF THE ORIGINAL IMAGE IS SET TO {}".format(res)) print("-------------------------------") self.focal = 0.5*res/np.tan(0.5*self.meta['camera_angle_x']) # original focal length # when W=res self.focal *= self.img_wh[0]/res # modify focal length to match size self.img_wh ################ self.light_camera_focal = 0.5*res/np.tan(0.5*self.meta['light_camera_angle_x']) # original focal length ################ # if 'bunny' or 'box' or 'vase' in self.root_dir: # self.light_camera_focal = 0.5*res/np.tan(0.5*self.meta['light_angle_x']) # original focal length # else: # self.light_camera_focal = 0.5*res/np.tan(0.5*self.meta['light_camera_angle_x']) # original focal length # when W=res self.light_camera_focal *= self.img_wh[0]/res # modify focal length to match size self.img_wh # bounds, common for all scenes self.near = 1.0 self.far = 200.0 # probably need to change this self.light_near = 1.0 self.light_far = 200.0 self.bounds = np.array([self.near, self.far]) # ray directions for all pixels, same for all images (same H, W, focal) self.directions = \ get_ray_directions(h, w, self.focal) # (h, w, 3) ### Light Camera Matrix ################ pose = np.array(self.meta['light_camera_transform_matrix'])[:3, :4] ################ # if 'bunny' or 'box' or 'vase' in self.root_dir: # self.meta['light_angle_x'] = 0.5 * self.meta['light_angle_x'] # print("Changing the HFOV of Light") # pose = np.array(self.meta['frames'][0]['light_transform'])[:3, :4] # else: # pose = np.array(self.meta['light_camera_transform_matrix'])[:3, :4] self.l2w = torch.FloatTensor(pose) pixels_u = torch.arange(0, w, 1) pixels_v = torch.arange(0, h, 1) i, j = np.meshgrid(pixels_v.numpy(), pixels_u.numpy(), indexing='xy') i = torch.tensor(i) + 0.5 #.unsqueeze(2) j = torch.tensor(j)+ 0.5 #.unsqueeze(2) self.light_pixels = torch.stack([i,j, torch.ones_like(i)], axis=-1).view(-1, 3) # (H*W,3) light_directions = get_ray_directions(h, w, self.light_camera_focal) # (h, w, 3) rays_o, rays_d = get_rays(light_directions, self.l2w) # both (h*w, 3) self.light_rays = torch.cat([rays_o, rays_d, self.light_near*torch.ones_like(rays_o[:, :1]), self.light_far*torch.ones_like(rays_o[:, :1])], 1) # (h*w, 8) ################ hfov = self.meta['light_camera_angle_x'] * 180./np.pi ################ # if 'bunny' or 'box' or 'vase' in self.root_dir: # hfov = self.meta['light_angle_x'] * 180./np.pi # else: # hfov = self.meta['light_camera_angle_x'] * 180./np.pi self.light_ppc = Camera(hfov, (h, w)) self.light_ppc.set_pose_using_blender_matrix(self.l2w, self.hparams.coords_trans) print("LIGHT: c2w: {}\n, camera:{}\n, eye:{}\n".format(self.l2w, self.light_ppc.camera, self.light_ppc.eye_pos)) ### Light Camera Matrix # new_frames = [] # # only do on a single image # for frame in self.meta['frames']: # if 'r_137' in frame['file_path']: # a = [frame] # new_frames.extend(a * 10) # break # self.meta['frames'] = new_frames if self.split == 'val': new_frames = [] for frame in self.meta['frames']: ###### load the RGB+SM Image file_path = frame['file_path'].split('/') sm_file_path = 'sm_'+ file_path[-1] sm_path = os.path.join(self.root_dir, f"{sm_file_path}.png") ## Continue if not os.path.exists(shadows) if not os.path.exists(sm_path): continue else: new_frames.append(frame) self.meta['frames'] = new_frames if self.split == 'train': # create buffer of all rays and rgb data self.image_paths = [] self.poses = [] self.all_rays = [] self.all_rgbs = [] self.all_ppc = [] self.all_pixels = [] for frame in tqdm(self.meta['frames']): #### change it to load the shadow map file_path = frame['file_path'].split('/') file_path = 'sm_'+ file_path[-1] ################ image_path = os.path.join(self.root_dir, f"{file_path}.png") self.image_paths += [image_path] ## Continue if not os.path.exists(shadows) if not os.path.exists(image_path): continue print("Processing Frame {}".format(image_path)) ##### # real processing begins pose = np.array(frame['transform_matrix'])[:3, :4] self.poses += [pose] c2w = torch.FloatTensor(pose) hfov = self.meta['camera_angle_x'] * 180./np.pi ppc = Camera(hfov, (h, w)) ppc.set_pose_using_blender_matrix(c2w, self.hparams.coords_trans) self.all_ppc.extend([ppc]*h*w) img = Image.open(image_path) img = img.resize(self.img_wh, Image.LANCZOS) if not self.hparams.blur == -1: img = img.filter(ImageFilter.GaussianBlur(self.hparams.blur)) img = self.transform(img) # (4, h, w) img = img.view(3, -1).permute(1, 0) # (h*w, 4) RGBA # Figure out where the rays originated from pixels_u = torch.arange(0, w, 1) pixels_v = torch.arange(0, h, 1) i, j = np.meshgrid(pixels_v.numpy(), pixels_u.numpy(), indexing='xy') i = torch.tensor(i) + 0.5 #.unsqueeze(2) j = torch.tensor(j)+ 0.5 #.unsqueeze(2) pixels = torch.stack([i,j, torch.ones_like(i)], axis=-1).view(-1, 3) # (H*W,3) rays_o, rays_d = get_rays(self.directions, c2w) rays = torch.cat([rays_o, rays_d, self.near*torch.ones_like(rays_o[:, :1]), self.far*torch.ones_like(rays_o[:, :1])], 1) # (H*W, 8) print("-------------------------------") print("frame: {}\n, c2w: {}\n, camera:{}\n, eye:{}\n".format(file_path, c2w, ppc.camera, ppc.eye_pos)) print("-------------------------------") self.all_rgbs += [img] self.all_rays += [rays] self.all_pixels += [pixels] self.all_rays = torch.cat(self.all_rays, 0) # (len(self.meta['frames])*h*w, 3) self.all_pixels = torch.cat(self.all_pixels, 0) # (len(self.meta['frames])*h*w, 3) self.all_rgbs = torch.cat(self.all_rgbs, 0) # (len(self.meta['frames])*h*w, 3) print("self.all_rgbs.shape, self.all_rays.shape, self.all_pixels.shape, all_ppc.shape", self.all_rgbs.shape, self.all_rays.shape, self.all_pixels.shape, len(self.all_ppc)) if not (float(self.hparams.white_pix) == -1): print("-------------------------- rgb max {}, min {}".format(self.all_rgbs.max(), self.all_rgbs.min())) print("only Training on pixels with shadow map values > 0.") all_bw = (self.all_rgbs[:,0] + self.all_rgbs[:,1] + self.all_rgbs[:,2])/3. idx = torch.where(all_bw > float(self.hparams.white_pix)) self.all_rgbs = self.all_rgbs[idx] self.all_pixels = self.all_pixels[idx] self.all_rays = self.all_rays[idx] new_ppc = [] for i in idx[0]: new_ppc.append(self.all_ppc[i]) self.all_ppc = new_ppc print("self.all_rgbs.shape, self.all_rays.shape, self.all_pixels.shape, all_ppc.shape", self.all_rgbs.shape, self.all_rays.shape, self.all_pixels.shape, len(self.all_ppc)) def define_transforms(self): self.transform = T.ToTensor() def __len__(self): if self.split == 'train': return len(self.all_rays) elif self.split == 'val': return 8 # only validate 8 images (to support <=8 gpus) else: return len(self.meta['frames']) def __getitem__(self, idx): """ Processes and return rays, rgbs PER image instead of on a ray by ray basis. Albeit slower, Implementation of shadow mapping is easier this way. """ if self.split == 'train': # use data in the buffers # pose = self.poses[idx] # c2w = torch.FloatTensor(pose) sample = {'rays': self.all_rays[idx], # (8) Ray originating from pixel (i,j) 'pixels': self.all_pixels[idx], # pixel where the ray originated from 'rgbs': self.all_rgbs[idx], # (h*w,3) # 'ppc': [self.all_ppc[idx].eye_pos, self.all_ppc[idx].camera], # 'light_ppc': [self.light_ppc.eye_pos, self.light_ppc.camera], 'ppc': { 'eye_pos': self.all_ppc[idx].eye_pos, 'camera': self.all_ppc[idx].camera, }, 'light_ppc': { 'eye_pos': self.light_ppc.eye_pos, 'camera': self.light_ppc.camera, }, # 'c2w': pose, # (3,4) # pixel where the light ray originated from 'light_pixels': self.light_pixels, #(h*w, 3) # light rays 'light_rays': self.light_rays, #(h*w,8) } else: # create data for each image separately frame = self.meta['frames'][idx] file_path = frame['file_path'].split('/') file_path = 'sm_'+ file_path[-1] c2w = torch.FloatTensor(frame['transform_matrix'])[:3, :4] ########### w, h = self.img_wh hfov = self.meta['camera_angle_x'] * 180./np.pi ppc = Camera(hfov, (h, w)) ppc.set_pose_using_blender_matrix(c2w, self.hparams.coords_trans) eye_poses = [ppc.eye_pos]*h*w cameras = [ppc.camera]*h*w ########### img = Image.open(os.path.join(self.root_dir, f"{file_path}.png")) img = img.resize(self.img_wh, Image.LANCZOS) if not self.hparams.blur == -1: img = img.filter(ImageFilter.GaussianBlur(self.hparams.blur)) img = self.transform(img) # (3, H, W) img = img.view(3, -1).permute(1, 0) # (H*W, 3) RGBA # img = img[:, :3]*img[:, -1:] + (1-img[:, -1:]) # blend A to RGB pixels_u = torch.arange(0, w, 1) pixels_v = torch.arange(0, h, 1) i, j = np.meshgrid(pixels_v.numpy(), pixels_u.numpy(), indexing='xy') i = torch.tensor(i) + 0.5 #.unsqueeze(2) j = torch.tensor(j)+ 0.5 #.unsqueeze(2) pixels = torch.stack([i,j, torch.ones_like(i)], axis=-1).view(-1, 3) # (H*W,3) rays_o, rays_d = get_rays(self.directions, c2w) rays = torch.cat([rays_o, rays_d, self.near*torch.ones_like(rays_o[:, :1]), self.far*torch.ones_like(rays_o[:, :1])], 1) # (H*W, 8) # print("rays.shape", rays.shape) # valid_mask = (img[-1]>0).flatten() # (H*W) valid color area sample = {'rays': rays, 'pixels': pixels, # pixel where rays originated from 'rgbs': img, 'ppc': { 'eye_pos': eye_poses, 'camera': cameras, }, 'light_ppc': { 'eye_pos': self.light_ppc.eye_pos, 'camera': self.light_ppc.camera, }, # pixel where the light ray originated from 'light_pixels': self.light_pixels, #(h*w, 3) # light rays 'light_rays': self.light_rays, #(h*w,8) } return sample
44.651515
120
0.498812
1,852
14,735
3.805076
0.13067
0.048673
0.024975
0.018731
0.561799
0.490563
0.467149
0.438059
0.409394
0.406556
0
0.021092
0.350051
14,735
330
121
44.651515
0.714733
0.19905
0
0.382075
0
0.009434
0.100252
0.023977
0
0
0
0
0.004717
1
0.023585
false
0
0.04717
0
0.09434
0.080189
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c60337a0cc834ad033d09738b410868a1fcb6ef6
625
py
Python
python_submission/5.longest-palindromic-substring.197920566.notac.py
stavanmehta/leetcode
1224e43ce29430c840e65daae3b343182e24709c
[ "Apache-2.0" ]
null
null
null
python_submission/5.longest-palindromic-substring.197920566.notac.py
stavanmehta/leetcode
1224e43ce29430c840e65daae3b343182e24709c
[ "Apache-2.0" ]
null
null
null
python_submission/5.longest-palindromic-substring.197920566.notac.py
stavanmehta/leetcode
1224e43ce29430c840e65daae3b343182e24709c
[ "Apache-2.0" ]
null
null
null
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ if len(s) == 1: return s start = 0 end = len(s) maxlength = 0 longest = "" while(start < len(s)): substring = s[start:end] if substring == substring[::-1] and len(substring) > maxlength: maxlength = len(substring) longest = substring else: end -=1 if start == end: start += 1 end = len(s) return longest
26.041667
75
0.4192
60
625
4.366667
0.383333
0.061069
0.053435
0
0
0
0
0
0
0
0
0.018293
0.4752
625
23
76
27.173913
0.780488
0.0384
0
0.105263
0
0
0
0
0
0
0
0
0
1
0.052632
false
0
0
0
0.210526
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c604f6057b5dbbc4327c8b89a1889d99d12111c1
10,410
py
Python
pysnmp/RBN-ICR-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
11
2021-02-02T16:27:16.000Z
2021-08-31T06:22:49.000Z
pysnmp/RBN-ICR-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
75
2021-02-24T17:30:31.000Z
2021-12-08T00:01:18.000Z
pysnmp/RBN-ICR-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # PySNMP MIB module RBN-ICR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-ICR-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:44:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint") InetPortNumber, InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetPortNumber", "InetAddressType", "InetAddress") rbnMgmt, = mibBuilder.importSymbols("RBN-SMI", "rbnMgmt") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") NotificationType, ObjectIdentity, ModuleIdentity, IpAddress, Unsigned32, Counter32, Counter64, iso, Bits, TimeTicks, MibIdentifier, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "ObjectIdentity", "ModuleIdentity", "IpAddress", "Unsigned32", "Counter32", "Counter64", "iso", "Bits", "TimeTicks", "MibIdentifier", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32") DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus") rbnIcrMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 2352, 2, 101)) rbnIcrMIB.setRevisions(('2011-01-10 00:00',)) if mibBuilder.loadTexts: rbnIcrMIB.setLastUpdated('201101100000Z') if mibBuilder.loadTexts: rbnIcrMIB.setOrganization('Ericsson AB.') rbnIcrNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 2, 101, 0)) rbnIcrMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1)) rbnIcrMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 2, 101, 2)) rbnIcrTable = MibTable((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1), ) if mibBuilder.loadTexts: rbnIcrTable.setStatus('current') rbnIcrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1), ).setIndexNames((0, "RBN-ICR-MIB", "rbnIcrId")) if mibBuilder.loadTexts: rbnIcrEntry.setStatus('current') rbnIcrId = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: rbnIcrId.setStatus('current') rbnIcrLocalAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 2), InetAddressType().clone('unknown')).setMaxAccess("readcreate") if mibBuilder.loadTexts: rbnIcrLocalAddressType.setStatus('current') rbnIcrLocalAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 3), InetAddress().clone(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: rbnIcrLocalAddress.setStatus('current') rbnIcrLocalPort = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 4), InetPortNumber()).setMaxAccess("readcreate") if mibBuilder.loadTexts: rbnIcrLocalPort.setStatus('current') rbnIcrPeerAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 5), InetAddressType().clone('unknown')).setMaxAccess("readcreate") if mibBuilder.loadTexts: rbnIcrPeerAddressType.setStatus('current') rbnIcrPeerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 6), InetAddress().clone(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: rbnIcrPeerAddress.setStatus('current') rbnIcrPeerPort = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 7), InetPortNumber()).setMaxAccess("readcreate") if mibBuilder.loadTexts: rbnIcrPeerPort.setStatus('current') rbnIcrPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("low", 1), ("high", 2))).clone('low')).setMaxAccess("readcreate") if mibBuilder.loadTexts: rbnIcrPriority.setStatus('current') rbnIcrKeepAliveInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 9), Integer32().clone(1)).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: rbnIcrKeepAliveInterval.setStatus('current') rbnIcrHoldTime = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 10), Integer32().clone(10)).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: rbnIcrHoldTime.setStatus('current') rbnIcrState = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("initialize", 1), ("active", 2), ("standby", 3), ("pendingStandby", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: rbnIcrState.setStatus('current') rbnIcrAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2))).clone('down')).setMaxAccess("readcreate") if mibBuilder.loadTexts: rbnIcrAdminStatus.setStatus('current') rbnIcrRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 1, 1, 13), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: rbnIcrRowStatus.setStatus('current') rbnIcrInconsistencyError = MibScalar((1, 3, 6, 1, 4, 1, 2352, 2, 101, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("peerLoss", 1)))).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: rbnIcrInconsistencyError.setStatus('current') rbnIcrNewActive = NotificationType((1, 3, 6, 1, 4, 1, 2352, 2, 101, 0, 1)).setObjects(("RBN-ICR-MIB", "rbnIcrLocalAddressType"), ("RBN-ICR-MIB", "rbnIcrLocalAddress"), ("RBN-ICR-MIB", "rbnIcrLocalPort"), ("RBN-ICR-MIB", "rbnIcrState")) if mibBuilder.loadTexts: rbnIcrNewActive.setStatus('current') rbnIcrNewStandby = NotificationType((1, 3, 6, 1, 4, 1, 2352, 2, 101, 0, 2)).setObjects(("RBN-ICR-MIB", "rbnIcrLocalAddressType"), ("RBN-ICR-MIB", "rbnIcrLocalAddress"), ("RBN-ICR-MIB", "rbnIcrLocalPort"), ("RBN-ICR-MIB", "rbnIcrPeerAddressType"), ("RBN-ICR-MIB", "rbnIcrPeerAddress"), ("RBN-ICR-MIB", "rbnIcrPeerPort"), ("RBN-ICR-MIB", "rbnIcrState")) if mibBuilder.loadTexts: rbnIcrNewStandby.setStatus('current') rbnIcrNewPendingStandby = NotificationType((1, 3, 6, 1, 4, 1, 2352, 2, 101, 0, 3)).setObjects(("RBN-ICR-MIB", "rbnIcrLocalAddressType"), ("RBN-ICR-MIB", "rbnIcrLocalAddress"), ("RBN-ICR-MIB", "rbnIcrLocalPort"), ("RBN-ICR-MIB", "rbnIcrPeerAddressType"), ("RBN-ICR-MIB", "rbnIcrPeerAddress"), ("RBN-ICR-MIB", "rbnIcrPeerPort"), ("RBN-ICR-MIB", "rbnIcrState")) if mibBuilder.loadTexts: rbnIcrNewPendingStandby.setStatus('current') rbnIcrInconsistency = NotificationType((1, 3, 6, 1, 4, 1, 2352, 2, 101, 0, 4)).setObjects(("RBN-ICR-MIB", "rbnIcrLocalAddressType"), ("RBN-ICR-MIB", "rbnIcrLocalAddress"), ("RBN-ICR-MIB", "rbnIcrLocalPort"), ("RBN-ICR-MIB", "rbnIcrPeerAddressType"), ("RBN-ICR-MIB", "rbnIcrPeerAddress"), ("RBN-ICR-MIB", "rbnIcrPeerPort"), ("RBN-ICR-MIB", "rbnIcrInconsistencyError")) if mibBuilder.loadTexts: rbnIcrInconsistency.setStatus('current') rbnIcrMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 2, 101, 2, 1)) rbnIcrMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 2352, 2, 101, 2, 2)) rbnIcrMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 2352, 2, 101, 2, 1, 1)).setObjects(("RBN-ICR-MIB", "rbnIcrGroup"), ("RBN-ICR-MIB", "rbnIcrNotificationObjectGroup"), ("RBN-ICR-MIB", "rbnIcrNotificationGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): rbnIcrMIBCompliance = rbnIcrMIBCompliance.setStatus('current') rbnIcrGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2352, 2, 101, 2, 2, 1)).setObjects(("RBN-ICR-MIB", "rbnIcrLocalAddressType"), ("RBN-ICR-MIB", "rbnIcrLocalAddress"), ("RBN-ICR-MIB", "rbnIcrLocalPort"), ("RBN-ICR-MIB", "rbnIcrPeerAddressType"), ("RBN-ICR-MIB", "rbnIcrPeerAddress"), ("RBN-ICR-MIB", "rbnIcrPeerPort"), ("RBN-ICR-MIB", "rbnIcrPriority"), ("RBN-ICR-MIB", "rbnIcrKeepAliveInterval"), ("RBN-ICR-MIB", "rbnIcrHoldTime"), ("RBN-ICR-MIB", "rbnIcrState"), ("RBN-ICR-MIB", "rbnIcrAdminStatus"), ("RBN-ICR-MIB", "rbnIcrRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): rbnIcrGroup = rbnIcrGroup.setStatus('current') rbnIcrNotificationObjectGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2352, 2, 101, 2, 2, 2)).setObjects(("RBN-ICR-MIB", "rbnIcrInconsistencyError")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): rbnIcrNotificationObjectGroup = rbnIcrNotificationObjectGroup.setStatus('current') rbnIcrNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 2352, 2, 101, 2, 2, 3)).setObjects(("RBN-ICR-MIB", "rbnIcrNewActive"), ("RBN-ICR-MIB", "rbnIcrNewStandby"), ("RBN-ICR-MIB", "rbnIcrNewPendingStandby"), ("RBN-ICR-MIB", "rbnIcrInconsistency")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): rbnIcrNotificationGroup = rbnIcrNotificationGroup.setStatus('current') mibBuilder.exportSymbols("RBN-ICR-MIB", rbnIcrGroup=rbnIcrGroup, rbnIcrPeerAddress=rbnIcrPeerAddress, rbnIcrPeerAddressType=rbnIcrPeerAddressType, rbnIcrNotifications=rbnIcrNotifications, rbnIcrNewActive=rbnIcrNewActive, rbnIcrMIBCompliance=rbnIcrMIBCompliance, rbnIcrNotificationObjectGroup=rbnIcrNotificationObjectGroup, rbnIcrMIB=rbnIcrMIB, PYSNMP_MODULE_ID=rbnIcrMIB, rbnIcrTable=rbnIcrTable, rbnIcrMIBConformance=rbnIcrMIBConformance, rbnIcrLocalAddressType=rbnIcrLocalAddressType, rbnIcrPriority=rbnIcrPriority, rbnIcrEntry=rbnIcrEntry, rbnIcrState=rbnIcrState, rbnIcrKeepAliveInterval=rbnIcrKeepAliveInterval, rbnIcrAdminStatus=rbnIcrAdminStatus, rbnIcrLocalPort=rbnIcrLocalPort, rbnIcrHoldTime=rbnIcrHoldTime, rbnIcrRowStatus=rbnIcrRowStatus, rbnIcrNotificationGroup=rbnIcrNotificationGroup, rbnIcrPeerPort=rbnIcrPeerPort, rbnIcrMIBObjects=rbnIcrMIBObjects, rbnIcrNewPendingStandby=rbnIcrNewPendingStandby, rbnIcrLocalAddress=rbnIcrLocalAddress, rbnIcrNewStandby=rbnIcrNewStandby, rbnIcrMIBGroups=rbnIcrMIBGroups, rbnIcrId=rbnIcrId, rbnIcrInconsistency=rbnIcrInconsistency, rbnIcrMIBCompliances=rbnIcrMIBCompliances, rbnIcrInconsistencyError=rbnIcrInconsistencyError)
131.772152
1,175
0.747166
1,164
10,410
6.680412
0.150344
0.037809
0.056713
0.015432
0.444959
0.388503
0.365484
0.337963
0.302726
0.300926
0
0.070414
0.0805
10,410
78
1,176
133.461538
0.741956
0.030355
0
0.057143
0
0
0.229648
0.038076
0
0
0
0
0
1
0
false
0
0.114286
0
0.114286
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
c6074a650ad47398b9b59002465392e2c249c2e3
14,325
py
Python
data-preprocess/ice-vision-data-merger-pipeline.py
jingwoo4710/mmdetection-icevision
da82741b29fdd1eb77b4e7483ff2a515d43d1760
[ "Apache-2.0" ]
4
2020-03-13T00:12:44.000Z
2021-06-25T07:54:17.000Z
data-preprocess/ice-vision-data-merger-pipeline.py
jingwoo4710/mmdetection-icevision
da82741b29fdd1eb77b4e7483ff2a515d43d1760
[ "Apache-2.0" ]
4
2020-03-13T00:24:15.000Z
2022-03-12T00:19:03.000Z
data-preprocess/ice-vision-data-merger-pipeline.py
jingwoo4710/mmdetection-icevision
da82741b29fdd1eb77b4e7483ff2a515d43d1760
[ "Apache-2.0" ]
1
2021-03-07T06:24:08.000Z
2021-03-07T06:24:08.000Z
#!/usr/bin/env python # coding: utf-8 # In[93]: import os from shutil import copyfile import json print("cwd = ", os.getcwd()) current_folder = os.getcwd() #extracted_train_data = os.path.join(current_folder, "extracted_train_data") extracted_train_data = "/dataset/training/" #annotations_dir = '/data/annotations' copied_train_data = "/data/dataset/training/" # In[100]: data_location = "/dataset/training/" files_list = [] neural_net_list = [] linear_mappings = [] for subdir, dirs, files in os.walk(data_location): for file in set(files): if file.endswith('.pnm'): current_file = os.path.join(subdir, file) files_list.append(current_file) print(len(files_list)) prev_file_number = 0 prev_file_dir_name = "" prev_neural_net = "" counter = 0 linear_list = [] ########################################## EDIT ##################################################################### for file in sorted(files_list): file_name_split = file.split('/') file_number = int(file_name_split[-1].split(".pnm")[0]) dir_name = file_name_split[-3] + file_name_split[-2] counter += file_number - prev_file_number if(prev_file_dir_name != dir_name): counter = 0 neural_net_list.append(file) prev_neural_net = file linear_list = [] else: if(counter >= 5): neural_net_list.append(file) linear_mappings.append({ "linear_list": linear_list, "predecessor": prev_neural_net, "successor": file }) counter = 0 prev_neural_net = file linear_list = [] else: #linear_mappings[file] = "linear" linear_list.append(file) # print("making linear", file) prev_file_number = file_number prev_file_dir_name = dir_name with open('linear_mappings.json', 'w') as outfile: json.dump(linear_mappings, outfile) # for file in file_body: # if (file_body[file] == "neuralnet"): # print(file) # for file in file_body: # if (file_body[file] == "linear"): # print(file) # In[97]: #neural_net_list[] - list of images to be sent to neural network import os import glob from mmdet.apis import init_detector, inference_detector, show_result, write_result import time import datetime config_file = '/root/ws/mmdetection-icevision/configs/dcn/cascade_rcnn_dconv_c3-c5_r50_fpn_1x_all_classes.py' #model = init_detector(config_file, checkpoint_file, device='cuda:0') #epch_count = 1 #for epochs in glob.glob(os.path.join('/data_tmp/icevisionmodels/cascade_rcnn_dconv_c3-c5_r50_fpn_1x_all_classes/', '*.pth')): checkpoint_file = '/data/trained_models/cascade_rcnn_dconv_c3-c5_r50_fpn_1x_135_classes/epoch_15.pth' #checkpoint_file = epochs # build the model from a config file and a checkpoint file model = init_detector(config_file, checkpoint_file, device='cuda:0') TEST_RESULT_PATH = "/data/test_results/" img_count = 0 #print(img_count) FINAL_ONLINE_TEST_PATH = "/data/train_subset/" #FINAL_ONLINE_TEST_PATH = '/data/test_results/2018-02-13_1418/left/' #for TEST_SET_PATH in (FINAL_ONLINE_TEST_PATH + "2018-02-16_1515_left/", FINAL_ONLINE_TEST_PATH + "2018-03-16_1424_left/", FINAL_ONLINE_TEST_PATH + "2018-03-23_1352_right/"): #print(TEST_SET_PATH) #imgs = glob.glob('/dataset/training/**/*.pnm', recursive=True) for img in neural_net_list: ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') print ("time =", st) #imgs = ['test.jpg', '000000.jpg'] #print(img) # /dataset/training/2018-02-13_1418/left/020963.pnm --> required format 2018-02-13_1418_left/000033 name = img.split("/") # ['', 'home', 'luminosity', 'ws', 'icevision', 'data', 'final', '2018-02-16_1515_left', '001887.jpg'] #print(name) base = name[-1].split(".")[0] # ['001887', 'jpg'] #print(base) name = name[-3] + "_" + name[-2] tmp = name name = name + "/" + base #print(name) ######## Remove #name_tmp = base.split("_") #name = name_tmp[0] + "_" + name_tmp[1] + "_" + name_tmp[2] + "/" + name_tmp[-1] #name = "annotation_train_subset/" + base #base_list = base.split("_") #name = base_list[0] + "_" + base_list[1] + "_" + base_list[2] + "/" + base_list[3] ##########Remove result = inference_detector(model, img) #write_result(name, result, model.CLASSES, out_file=os.path.join(TEST_RESULT_PATH, 'my_test_multi_scale_epch_{}.tsv'.format(epch_count))) # use name instead name1 for hackthon submission #show_result(img, result, model.CLASSES, out_file= TEST_RESULT_PATH + 'bboxs/' + tmp + ".pnm") write_result(name, result, model.CLASSES, out_file=os.path.join(TEST_RESULT_PATH, 'my_test_epch_15_interpolation.tsv')) # use name instead name1 for hackthon submission img_count+=1 #print(img_count) print("num = %d name = %s" %(img_count,name)) # In[103]: import os import glob import csv from shutil import copyfile def linear_interpolation(pred, succ, lin_images, input_tsv, step, out_tsv): lin_images.sort() succ_base_name = os.path.basename(succ).split(".")[0] pred_base_name = os.path.basename(pred).split(".")[0] #copyfile(input_tsv, out_tsv) tsv_file = csv.reader(open(input_tsv, "r"), delimiter="\t") prd_classes = [] suc_classes = [] prd_keys = set() suc_keys = set() for row in tsv_file: # print("row = ", row) # print('ped_keys = ', prd_keys) # print('suc_keys = ', suc_keys) # frame xtl ytl xbr ybr class temporary data # 2018-02-13_1418_left/020963 679 866 754 941 3.27 prd_record = {} #defaultdict(list) suc_record = {} #defaultdict(list) #print("row[0] = ", row[0]) x = os.path.join(os.path.basename(os.path.dirname(pred)),os.path.basename(pred)) y = os.path.basename(os.path.dirname(os.path.dirname(pred))) dict_key = y + "_" + x x2 = os.path.join(os.path.basename(os.path.dirname(succ)),os.path.basename(succ)) y2 = os.path.basename(os.path.dirname(os.path.dirname(succ))) dict_key2 = y2 + "_" + x2 # print('y = ', y) # print("x = ", x) # print("dict_key = ", dict_key.split('.')[0]) if row[0] == dict_key.split('.')[0]: if row[5] not in prd_keys: print("pred check cleared") prd_record["class"] = row[5] prd_record["xtl"] = row[1] prd_record["ytl"] = row[2] prd_record["xbr"] = row[3] prd_record["ybr"] = row[4] print("prd_record['ybr'] = ", prd_record["ybr"]) prd_keys.add(row[5]) # #prd_record[row[5]].append(row[1]) #xtl # prd_record[row[5]].append(row[2]) #ytl # prd_record[row[5]].append(row[3]) #xbr # prd_record[row[5]].append(row[4]) #ybr prd_classes.append(prd_record) else: for prd_class in prd_classes: if prd_class["class"] == row[5]: del prd_class print("del prd_class") elif row[0] == dict_key2.split('.')[0]: print("Succ check cleared") if row[5] not in suc_keys: suc_record["class"] = row[5] suc_record["xtl"] = row[1] suc_record["ytl"] = row[2] suc_record["xbr"] = row[3] suc_record["ybr"] = row[4] suc_keys.add(row[5]) # suc_record[row[5]].append(row[1]) # suc_record[row[5]].append(row[2]) # suc_record[row[5]].append(row[3]) # suc_record[row[5]].append(row[4]) suc_classes.append(suc_record) else: for suc_class in suc_classes: if suc_class["class"] == row[5]: del suc_class print("del prd_class") #print("prd_keys = ", prd_keys) common_classes = prd_keys.intersection(suc_keys) print(common_classes) for common_class in common_classes: for prd_class in prd_classes: if prd_class["class"] == common_class: for suc_class in suc_classes: if suc_class["class"] == common_class: xtl_gr = (int(prd_class["xtl"]) - int(suc_class["xtl"])) / step ytl_gr = (int(prd_class["ytl"]) - int(suc_class["ytl"])) / step xbr_gr = (int(prd_class["xbr"]) - int(suc_class["xbr"])) / step ybr_gr = (int(prd_class["ybr"]) - int(suc_class["ybr"])) / step print(xtl_gr, ytl_gr, xbr_gr, ybr_gr) for f in lin_images: curr_base = os.path.basename(f).split(".")[0] # print("curr_base = ", curr_base) # print("pred_base_name = ", pred_base_name) # print("f = ", f) factor = int(curr_base) - int(pred_base_name) curr_xtl = int(prd_class["xtl"]) + (factor * xtl_gr) curr_ytl = int(prd_class["ytl"]) + (factor * ytl_gr) curr_xbr = int(prd_class["xbr"]) + (factor * xbr_gr) curr_ybr = int(prd_class["ybr"]) + (factor * ybr_gr) temp = '' with open(out_tsv, mode = 'a') as result_file: result_file_writer = csv.writer(result_file, delimiter = '\t') result_file_writer.writerow([f, str(curr_xtl), str(curr_ytl), str(curr_xbr), str(curr_ybr), prd_class["class"], temp, temp]) # In[105]: #load the linear mappings.json import csv linear_mappings = "/root/ws/mmdetection-icevision/data-preprocess/linear_mappings.json" input_tsv = os.path.join(TEST_RESULT_PATH, 'my_test_epch_15_interpolation_copy.tsv') out_tsv = os.path.join(TEST_RESULT_PATH, 'my_test_epch_15_interpolation_copy.tsv') interpolation_mappings = [] with open(linear_mappings, 'r') as f: interpolation_mappings = json.load(f) for i in interpolation_mappings: pred = i["predecessor"] succ = i['successor'] interpol_list = i['linear_list'] step = 5 linear_interpolation(pred, succ, interpol_list, input_tsv, step, out_tsv) # if i["predecessor"] == neural_net_list[100]: # break # In[70]: # trial code # extracted_train_data = "/home/sgj/temp/test_data/2018-03-16_1324" # for subdir, dirs, files in os.walk(extracted_train_data): # print("subdir = ", subdir) # for file in files: # if file.endswith('.jpg'): # current_file = os.path.join(subdir, file) # #folder_name = os.path.basename(os.path.dirname(current_file)) # #expected_name = folder_name + '_' + os.path.basename(current_file) # y = file.split("_") # expected_name = y[0] + "_" + y[1] + "_left_jpgs_" + y[2] # absolute_expected_name = os.path.join(os.path.dirname(current_file),expected_name) # os.rename(current_file, absolute_expected_name) # In[37]: extracted_train_data = "/home/sgj/temp/train_data/2018-02-13_1418_left_jpgs" for subdir, dirs, files in os.walk(extracted_train_data): print("subdir = ", subdir) for file in files: if file.endswith('.jpg'): current_file = os.path.join(subdir, file) folder_name = os.path.basename(os.path.dirname(current_file)) expected_name = folder_name + '_' + os.path.basename(current_file) absolute_expected_name = os.path.join(os.path.dirname(current_file),expected_name) os.rename(current_file, absolute_expected_name) # In[25]: # move out un-annotated images - # ARGS - # Annotations data tsv # Extracted images folder # Destination folder for annotated_data import os annotation_data_tsv_folder = "/home/sgj/nvme/ice-vision/annotations/test/all_validation_annotations" extracted_images_folder = "/home/sgj/temp/test_data/all_validation_images" #dest_annotated_imgs = "/home/sgj/nvme/ice-vision/annotated_data/val" dest_annotated_imgs = "/home/sgj/temp/ice-vision/annotated_data/val" os.makedirs(dest_annotated_imgs) img_count = 0 for root, dirs, files in os.walk(annotation_data_tsv_folder): for name in files: if name.endswith('.tsv'): prefix = name.split(".")[0] image_name = prefix + ".jpg" expected_img_path = os.path.join(extracted_images_folder, image_name) new_image_path = os.path.join(dest_annotated_imgs, image_name) if os.path.exists(expected_img_path): img_count = img_count + 1 os.rename(expected_img_path, new_image_path) else: print("image missing-----------------------") print("total images = ", img_count) # In[18]: temp = "2018-02-13_1418_left_jpgs_014810.tsv" temp.split(".")[0] # In[3]: for subdir, dirs, files in os.walk(copied_train_data): print("subdir = ", subdir) for file in files: if file.endswith('.pnm'): current_file = os.path.join(subdir, file) print('current file = ', current_file) cam_dir = current_file.split('/')[-2] #print("cam dir = ", cam_dir) date_dir = current_file.split('/')[-3] #print("date_dir = ", date_dir) expected_folder = '/data/train_subset/' expected_file_name = date_dir + "_" + cam_dir + "_" + os.path.basename(current_file) expected_file_path = os.path.join(expected_folder, expected_file_name) #copyfile(current_file, dst_file_path) os.rename(current_file, expected_file_path) print("expected_file_path = ", expected_file_path) # In[4]: # In[ ]:
35.02445
194
0.585829
1,859
14,325
4.243141
0.152232
0.031947
0.021552
0.016227
0.36676
0.29285
0.240365
0.208418
0.204868
0.177485
0
0.031364
0.269948
14,325
408
195
35.110294
0.722892
0.281396
0
0.207921
0
0
0.117788
0.064564
0
0
0
0
0
1
0.004951
false
0
0.069307
0
0.074257
0.084158
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c6093977665e22ed8590c36fa4cf3dd81037f912
4,721
py
Python
second_childwin.py
liwy27/similation_experiment_qt
20c0b7e9f2777fb828bf5b596985121ef517823a
[ "MIT" ]
null
null
null
second_childwin.py
liwy27/similation_experiment_qt
20c0b7e9f2777fb828bf5b596985121ef517823a
[ "MIT" ]
null
null
null
second_childwin.py
liwy27/similation_experiment_qt
20c0b7e9f2777fb828bf5b596985121ef517823a
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'second_childwin.ui' # # Created by: PyQt5 UI code generator 5.15.0 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form_2(object): def setupUi(self, Form_2): Form_2.setObjectName("Form_2") Form_2.resize(982, 618) self.graphicsView = QtWidgets.QGraphicsView(Form_2) self.graphicsView.setGeometry(QtCore.QRect(420, 10, 560, 606)) self.graphicsView.setObjectName("graphicsView") self.pushButton = QtWidgets.QPushButton(Form_2) self.pushButton.setGeometry(QtCore.QRect(20, 60, 301, 40)) font = QtGui.QFont() font.setPointSize(20) self.pushButton.setFont(font) self.pushButton.setObjectName("pushButton") self.lineEdit = QtWidgets.QLineEdit(Form_2) self.lineEdit.setGeometry(QtCore.QRect(20, 110, 391, 41)) font = QtGui.QFont() font.setPointSize(16) self.lineEdit.setFont(font) self.lineEdit.setObjectName("lineEdit") self.pushButton_2 = QtWidgets.QPushButton(Form_2) self.pushButton_2.setGeometry(QtCore.QRect(20, 160, 91, 41)) font = QtGui.QFont() font.setPointSize(20) self.pushButton_2.setFont(font) self.pushButton_2.setObjectName("pushButton_2") self.label = QtWidgets.QLabel(Form_2) self.label.setGeometry(QtCore.QRect(30, 220, 101, 41)) font = QtGui.QFont() font.setPointSize(20) self.label.setFont(font) self.label.setObjectName("label") self.lineEdit_2 = QtWidgets.QLineEdit(Form_2) self.lineEdit_2.setGeometry(QtCore.QRect(80, 280, 130, 40)) font = QtGui.QFont() font.setPointSize(16) self.lineEdit_2.setFont(font) self.lineEdit_2.setText("") self.lineEdit_2.setReadOnly(True) self.lineEdit_2.setObjectName("lineEdit_2") self.lineEdit_4 = QtWidgets.QLineEdit(Form_2) self.lineEdit_4.setGeometry(QtCore.QRect(80, 400, 130, 40)) font = QtGui.QFont() font.setPointSize(16) self.lineEdit_4.setFont(font) self.lineEdit_4.setReadOnly(True) self.lineEdit_4.setObjectName("lineEdit_4") self.label_2 = QtWidgets.QLabel(Form_2) self.label_2.setGeometry(QtCore.QRect(40, 280, 40, 30)) font = QtGui.QFont() font.setFamily("Times New Roman") font.setPointSize(20) self.label_2.setFont(font) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(Form_2) self.label_3.setGeometry(QtCore.QRect(40, 400, 40, 30)) font = QtGui.QFont() font.setFamily("Times New Roman") font.setPointSize(20) self.label_3.setFont(font) self.label_3.setObjectName("label_3") self.label_4 = QtWidgets.QLabel(Form_2) self.label_4.setGeometry(QtCore.QRect(40, 340, 40, 30)) font = QtGui.QFont() font.setFamily("Times New Roman") font.setPointSize(20) self.label_4.setFont(font) self.label_4.setObjectName("label_4") self.pushButton_3 = QtWidgets.QPushButton(Form_2) self.pushButton_3.setGeometry(QtCore.QRect(30, 520, 91, 41)) font = QtGui.QFont() font.setPointSize(20) self.pushButton_3.setFont(font) self.pushButton_3.setObjectName("pushButton_3") self.lineEdit_3 = QtWidgets.QLineEdit(Form_2) self.lineEdit_3.setGeometry(QtCore.QRect(80, 340, 130, 40)) font = QtGui.QFont() font.setPointSize(16) self.lineEdit_3.setFont(font) self.lineEdit_3.setText("") self.lineEdit_3.setReadOnly(True) self.lineEdit_3.setObjectName("lineEdit_3") self.retranslateUi(Form_2) self.pushButton_3.clicked.connect(Form_2.close) QtCore.QMetaObject.connectSlotsByName(Form_2) def retranslateUi(self, Form_2): _translate = QtCore.QCoreApplication.translate Form_2.setWindowTitle(_translate("Form_2", "色度测量仿真")) self.pushButton.setText(_translate("Form_2", "选择透射谱/反射谱文件")) self.pushButton_2.setText(_translate("Form_2", "运行")) self.label.setText(_translate("Form_2", "色坐标:")) self.label_2.setText(_translate("Form_2", "x:")) self.label_3.setText(_translate("Form_2", "z:")) self.label_4.setText(_translate("Form_2", "y:")) self.pushButton_3.setText(_translate("Form_2", "返回"))
42.918182
76
0.644779
580
4,721
5.089655
0.210345
0.050813
0.039634
0.067073
0.365515
0.326897
0.199187
0.199187
0.155827
0.155827
0
0.064266
0.235332
4,721
109
77
43.311927
0.753463
0.059309
0
0.263158
1
0
0.055504
0
0
0
0
0
0
1
0.021053
false
0
0.010526
0
0.042105
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
c609dcc818d4247b3e931541707e6e65fd9fc433
1,683
py
Python
osu/graph_metadata.py
brandondong/osu-beatmap-generator
7ca14793ef6a48a65cfd1a564f3b24d940a6051a
[ "MIT" ]
null
null
null
osu/graph_metadata.py
brandondong/osu-beatmap-generator
7ca14793ef6a48a65cfd1a564f3b24d940a6051a
[ "MIT" ]
1
2021-06-01T23:50:59.000Z
2021-06-01T23:50:59.000Z
osu/graph_metadata.py
brandondong/osu-beatmap-generator
7ca14793ef6a48a65cfd1a564f3b24d940a6051a
[ "MIT" ]
null
null
null
import os import matplotlib.pyplot as plt import numpy as np from models import models_util DIFFICULTY_LABEL = "Star Difficulty" BPM_LABEL = "BPM" LENGTH_LABEL = "Length" CS_LABEL = "Circle Size" DRAIN_LABEL = "HP Drain" ACCURACY_LABEL = "Accuracy" AR_LABEL = "Approach Rate" SAVE_FOLDER = "visualization/" def print_property_values(labels, values): for idx, value in enumerate(values): print(f"{labels[idx]}: {value}") print() # Data rows are in the format of [difficulty_rating],[bpm],[total_length],[cs],[drain],[accuracy],[ar]. labels = [DIFFICULTY_LABEL, BPM_LABEL, LENGTH_LABEL, CS_LABEL, DRAIN_LABEL, ACCURACY_LABEL, AR_LABEL] filename_labels = [] for label in labels: filename_labels.append(label.lower().replace(" ", "_")) # Keep track of each property in separate rows. points = np.transpose(models_util.load_metadata_dataset()) mins = points.min(axis=-1) maxes = points.max(axis=-1) means = np.mean(points, axis=-1) print("Minimum values:") print_property_values(labels, mins) print("Maximum values:") print_property_values(labels, maxes) print("Mean values:") print_property_values(labels, means) # Plot graphs for each input output feature pair. for i in range(3): for j in range(3, 7): plt.hexbin(points[i], points[j], gridsize=50, cmap="inferno") plt.axis([mins[i], maxes[i], mins[j], maxes[j]]) x_label = labels[i] y_label = labels[j] plt.title(f"{y_label} vs {x_label}") plt.xlabel(x_label) plt.ylabel(y_label) x_file_label = filename_labels[i] y_file_label = filename_labels[j] image_name = os.path.join(SAVE_FOLDER, f"{y_file_label}_vs_{x_file_label}.png") print(f"Saving graph to {image_name}.") plt.savefig(image_name)
28.525424
103
0.734403
263
1,683
4.494297
0.387833
0.043993
0.064298
0.084602
0.07868
0
0
0
0
0
0
0.005431
0.124777
1,683
59
104
28.525424
0.797013
0.115865
0
0
0
0
0.160269
0.024242
0
0
0
0
0
1
0.022727
false
0
0.090909
0
0.113636
0.227273
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c60b950c7ec0457cb6e2c5b50e37bb91e2cf7ca7
2,327
py
Python
tests/test_zad02.py
TestowanieAutomatyczneUG/laboratorium-12-SzymonWilczewski
18f0a6c8f5f4c304ef1497907edeb53a470dcf58
[ "MIT" ]
null
null
null
tests/test_zad02.py
TestowanieAutomatyczneUG/laboratorium-12-SzymonWilczewski
18f0a6c8f5f4c304ef1497907edeb53a470dcf58
[ "MIT" ]
null
null
null
tests/test_zad02.py
TestowanieAutomatyczneUG/laboratorium-12-SzymonWilczewski
18f0a6c8f5f4c304ef1497907edeb53a470dcf58
[ "MIT" ]
null
null
null
import unittest from unittest.mock import * from src.zad02.main import Subscriber class SubscriberTest(unittest.TestCase): def setUp(self): self.subscriber = Subscriber() def test_add_client(self): self.subscriber.add_client = MagicMock(return_value=["Andrzej"]) self.assertEqual(["Andrzej"], self.subscriber.add_client("Andrzej")) def test_remove_client(self): self.subscriber.remove_client = MagicMock(return_value=[]) self.assertEqual([], self.subscriber.remove_client("Andrzej")) def test_send_message_to_client(self): self.subscriber.clients = ["Andrzej"] self.subscriber.send_message = MagicMock(side_effect=lambda client, message: message) self.assertEqual("Hello Andrzej!", self.subscriber.send_message_to_client("Andrzej", "Hello Andrzej!")) def test_add_client_type_error(self): self.subscriber.add_client = MagicMock(side_effect=TypeError("Client is not a string!")) with self.assertRaisesRegex(TypeError, "Client is not a string!"): self.subscriber.add_client(1) def test_add_client_value_error(self): self.subscriber.add_client = MagicMock(side_effect=ValueError("Client already exists!")) with self.assertRaisesRegex(ValueError, "Client already exists!"): self.subscriber.add_client("Andrzej") def test_remove_client_type_error(self): self.subscriber.remove_client = MagicMock(side_effect=TypeError("Client is not a string!")) with self.assertRaisesRegex(TypeError, "Client is not a string!"): self.subscriber.remove_client(1) def test_send_message_to_client_type_error(self): self.subscriber.send_message_to_client = MagicMock(side_effect=TypeError("Client or message is not a string!")) with self.assertRaisesRegex(TypeError, "Client or message is not a string!"): self.subscriber.send_message_to_client("Andrzej", []) def test_send_message_to_client_value_error(self): self.subscriber.send_message_to_client = MagicMock(side_effect=ValueError("Client doesn't exist!")) with self.assertRaisesRegex(ValueError, "Client doesn't exist!"): self.subscriber.send_message_to_client("Andrzej", "Hello Andrzej!") def tearDown(self): self.subscriber = None
45.627451
119
0.72067
285
2,327
5.652632
0.175439
0.165115
0.111732
0.094351
0.734947
0.646183
0.524519
0.507759
0.431409
0.290503
0
0.002076
0.171895
2,327
50
120
46.54
0.833939
0
0
0.052632
0
0
0.150838
0
0
0
0
0
0.210526
1
0.263158
false
0
0.078947
0
0.368421
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
1
c60bdc534000a18e4fc655a5cff50a94af3d4302
2,077
py
Python
ADE/train.py
BinahHu/ADE-Longtail
4aabf1cbf50746e610b91362c40cbcb7884dd170
[ "Apache-2.0" ]
null
null
null
ADE/train.py
BinahHu/ADE-Longtail
4aabf1cbf50746e610b91362c40cbcb7884dd170
[ "Apache-2.0" ]
null
null
null
ADE/train.py
BinahHu/ADE-Longtail
4aabf1cbf50746e610b91362c40cbcb7884dd170
[ "Apache-2.0" ]
null
null
null
# import some common libraries # import some common detectron2 utilities from detectron2.config import get_cfg from detectron2.data import ( build_detection_test_loader, build_detection_train_loader, ) from detectron2.engine import default_argument_parser, default_setup, launch, DefaultTrainer # import ADE related package from dataset.ade import register_all_ade from dataset.my_mapper import MyDatasetMapper from transforms.my_resize import MyResize from modeling.backbone.my_build import register_my_backbone from modeling.roi_heads.roi_cls import register_roi_cls from additional_cfg import set_additional_cfg class Trainer(DefaultTrainer): @classmethod def build_train_loader(cls, cfg): """ Returns: iterable It now calls :func:`detectron2.data.build_detection_train_loader`. Overwrite it if you'd like a different data loader. """ return build_detection_train_loader(cfg, mapper=MyDatasetMapper(cfg, is_train=True, augmentations=[ MyResize(cfg.INPUT.RESIZE_SHORT, cfg.INPUT.RESIZE_LONG)])) def setup(args): """ Create configs and perform basic setups. """ cfg = get_cfg() cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) cfg = set_additional_cfg(cfg) cfg.freeze() default_setup( cfg, args ) # if you don't like any of the default setup, write your own setup code return cfg def register_all(cfg): register_all_ade(cfg.DATASETS.ADE_ROOT) register_my_backbone() register_roi_cls() def main(args): cfg = setup(args) register_all(cfg) trainer = Trainer(cfg) trainer.resume_or_load(resume=args.resume) return trainer.train() if __name__ == "__main__": args = default_argument_parser().parse_args() print("Command Line Args:", args) launch( main, args.num_gpus, num_machines=args.num_machines, machine_rank=args.machine_rank, dist_url=args.dist_url, args=(args,), )
26.628205
107
0.703418
269
2,077
5.159851
0.390335
0.040346
0.041066
0.054035
0
0
0
0
0
0
0
0.003081
0.218585
2,077
77
108
26.974026
0.852126
0.168031
0
0
0
0
0.01603
0
0
0
0
0
0
1
0.083333
false
0
0.1875
0
0.354167
0.020833
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c60d16dc84b1f51d0fe6d4f73e98b08bb5beed06
146
py
Python
VacationPy/api_keys.py
jagfinancial/python-api-challenge
3b15bdd8389dd208efc2fecce6a681ccde54ef6d
[ "ADSL" ]
null
null
null
VacationPy/api_keys.py
jagfinancial/python-api-challenge
3b15bdd8389dd208efc2fecce6a681ccde54ef6d
[ "ADSL" ]
null
null
null
VacationPy/api_keys.py
jagfinancial/python-api-challenge
3b15bdd8389dd208efc2fecce6a681ccde54ef6d
[ "ADSL" ]
null
null
null
# OpenWeatherMap API Key weather_api_key = "3796d9507516315ec2ebdc39473cc6ea" # Google API Key g_key = "AIzaSyDQ3DTH86ntlGML7QCVhKWSocZX8Cb4yBA"
24.333333
52
0.842466
13
146
9.230769
0.615385
0.15
0
0
0
0
0
0
0
0
0
0.206107
0.10274
146
5
53
29.2
0.709924
0.253425
0
0
0
0
0.669811
0.669811
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
0
0
0
0
1
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
5
c60dde17e3e2f4dd2320cb3a7f244103bed46b66
2,411
py
Python
src/messages.py
Colk-tech/gcpdiscord
b2a43dca8db5a17e6e72f36c7e895db19b836067
[ "MIT" ]
4
2020-12-31T09:41:09.000Z
2022-02-20T14:13:41.000Z
src/messages.py
Colk-tech/gcpdiscord
b2a43dca8db5a17e6e72f36c7e895db19b836067
[ "MIT" ]
3
2020-12-28T18:19:44.000Z
2021-01-03T14:51:59.000Z
src/messages.py
Colk-tech/gcpdiscord
b2a43dca8db5a17e6e72f36c7e895db19b836067
[ "MIT" ]
2
2020-12-31T05:42:57.000Z
2022-03-24T07:54:25.000Z
PERMISSION_DENIED_MESSAGE: str = "***PERMISSION DENIED!*** \n" \ "You are not permitted to use this command. \n" \ "Please contact to your server master. \n." ERROR_OCCURRED_MESSAGE: str = "***ERROR OCCURRED!*** \n" \ "Error has occurred while executing gcp request command. \n" \ "Please contact to your server master or the software developer. \n" \ "Error: {} \n" OPERATION_COMPLETED_MESSAGE: str = "***Operation Completed! ***\n" \ "Operation: {} has successfully completed. \n" \ "This may take more 2~3 minutes that the Minecraft Server starts (stops)." INSTANCE_IS_ALREADY_IN_REQUESTED_STATUS: str = "***Already in status of {}.*** \n" \ "The instance is already in the status. \n" \ "No operation has done." PRE_STOP_OPERATION_PROCESSING: str = "Processing pre-stop operation... \n" \ "Trying to shutdown Minecraft server from the console channel. \n" \ "Whichever the operation is completed or not, " \ "the server will shutdown in 5 minutes forcibly." REQUEST_RECEIVED: str = "Operation: {} has requested. \n" \ "Please wait until the operation is done. \n" START_REQUEST_RECEIVED_MESSAGE = "Trying to start the gcp server. \n" \ "It takes 3 sec at least to complete the operation. \n" \ "The minecraft server will start as soon as gcp server started. \n" \ "PLEASE WAIT UNTIL YOU RECEIVE MESSAGE 'SERVER HAS STARTED!' " \ "BEFORE YOU JOIN THE MINECRAFT SERVER." STOP_REQUEST_RECEIVED_MESSAGE = "Trying to stop the gcp server. \n" \ "It takes 5 minutes at least to complete the operation. \n" \ "We will issue `stop` command in console channel. \n" \ "And then, we will wait for 5 minutes for the Minecraft server stops." \ "After all the process is done, we will shutdown GCP instance finally."
70.911765
109
0.517628
256
2,411
4.792969
0.34375
0.061125
0.05868
0.03423
0.193969
0.145069
0.112469
0.06357
0
0
0
0.004172
0.403567
2,411
33
110
73.060606
0.849096
0
0
0
0
0
0.542099
0
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c60e59d24506527b02637849c4f5442ee5efa5c7
4,035
py
Python
util/SR2SC.py
lorteddie/dcmqi
4f668745f4f8b2a67e6dcfdee187ac7793e07116
[ "BSD-3-Clause" ]
null
null
null
util/SR2SC.py
lorteddie/dcmqi
4f668745f4f8b2a67e6dcfdee187ac7793e07116
[ "BSD-3-Clause" ]
null
null
null
util/SR2SC.py
lorteddie/dcmqi
4f668745f4f8b2a67e6dcfdee187ac7793e07116
[ "BSD-3-Clause" ]
null
null
null
from pydicom.sr import _snomed_dict import os import re import pydicom.sr._snomed_dict folder = "E:\\work\\QIICR\\dcmqi" Out_Folder = "E:\\work\\QIICR\\renamed_dcmqi" def recursive_file_find(address, regexp): filelist = os.listdir(address) approvedlist=[] for filename in filelist: fullpath = os.path.join(address, filename) if os.path.isdir(fullpath): approvedlist.extend(recursive_file_find(fullpath, regexp)) elif re.match(regexp, fullpath) is not None: approvedlist.append(fullpath) return approvedlist def GetFileString(filename): File_object = open(filename, "r") try: Content = File_object.read() except: print("Couldn't read the file") Content = "" File_object.close() return Content def WriteTextInFile(filename, txt): folder = os.path.dirname(filename) if not os.path.exists(folder): os.makedirs(folder) File_object = open(filename, "w") File_object.write(txt) File_object.close() def FindRegex(regexp, text, extend=[0, 0], printout=False): found_iters = re.finditer(regexp, text) founds = list(found_iters) ii = [] for mmatch in founds: yy = text[mmatch.start() - extend[0]:mmatch.end() + extend[1]] counter = "[%04d ]" % len(ii) if (printout): print(counter + yy) ii.append(yy) return ii def ReplaceQuotedText(find_text, rep_text, text): pattern = "(\"\s*" + find_text + "\s*\")|('\s*" + find_text + "\s*')" replacement = "\"" + rep_text + "\""; new_text = re.sub(pattern, replacement, text) View = ShowReplaceMent(pattern, replacement, text) return [new_text, View] def FindAndReplace(find_text, rep_text, text): newtext = re.sub(find_text, rep_text, text) x = ShowReplaceMent(find_text, rep_text, text) return [newtext, x] def ShowReplaceMent(find_text, rep_text, text): output = [] text_seq = FindRegex("\\n.*(" + find_text + ").*\\n", text, [-1, -1]) for line_txt in text_seq: found_iters = re.finditer(find_text, line_txt) founds = list(found_iters) if len(founds) > 0: mmatch = founds[0] yy = line_txt[:mmatch.start()] + \ "{ [" + line_txt[mmatch.start():mmatch.end()] + "]-->[" + rep_text + "] }" + \ line_txt[mmatch.end():] output.append(yy) return output dict = _snomed_dict.mapping["SCT"] details = [] # recursive_file_find(folder, all_files, "(.*\\.cpp$)|(.*\\.h$)|(.*\\.json$)") all_files = recursive_file_find(folder, "(?!.*\.git.*)") for f, jj in zip(all_files, range(1, len(all_files))): f_content = (GetFileString(f)) if len(f_content) == 0: continue [f_content, x] = ReplaceQuotedText("SCT", "SCT", f_content) details = x [f_content, x] = FindAndReplace(",\s*SRT\s*,", ",SCT,", f_content) details.extend(x) [f_content, x] = FindAndReplace("SCT", " SCT ", f_content) details.extend(x) [f_content, x] = FindAndReplace("_SCT_", "_SCT_", f_content) details.extend(x) [f_content, x] = FindAndReplace("sct.h", "sct.h", f_content) details.extend(x) for srt_code, sct_code in dict.items(): # f_content = ReplaceQuotedText(srt_code, sct_code, f_content) [f_content, x] = FindAndReplace(srt_code, sct_code, f_content) details.extend(x) if len(details) == 0: continue edited_file_name = f.replace(folder, Out_Folder) edited_file_log = f.replace(folder, os.path.join(Out_Folder, '..\\log')) + ".txt" WriteTextInFile(edited_file_name, f_content) print("------------------------------------------------------------------------") f_number = "(file %03d ) " % jj print(f_number + f) logg = "" for m, c in zip(details, range(0, len(details))): indent = "\t\t\t%04d" % c logg += (indent + m + "\n") if len(logg) != 0: WriteTextInFile(edited_file_log, logg) print("the find/replace process finished ...")
32.28
95
0.603965
512
4,035
4.576172
0.242188
0.058045
0.023047
0.03201
0.172002
0.113103
0.065301
0.065301
0.065301
0.065301
0
0.006061
0.223048
4,035
124
96
32.540323
0.741308
0.033953
0
0.108911
0
0
0.092683
0.031836
0
0
0
0
0
1
0.069307
false
0
0.039604
0
0.168317
0.069307
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c60ef77ba35cbe6b2d5368873bee63645c0514b7
9,417
py
Python
disentanglement_lib/visualize/visualize_util.py
erow/disentanglement_lib
c875207fdeadc44880277542447544941bc0bd0a
[ "Apache-2.0" ]
null
null
null
disentanglement_lib/visualize/visualize_util.py
erow/disentanglement_lib
c875207fdeadc44880277542447544941bc0bd0a
[ "Apache-2.0" ]
null
null
null
disentanglement_lib/visualize/visualize_util.py
erow/disentanglement_lib
c875207fdeadc44880277542447544941bc0bd0a
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # Copyright 2018 The DisentanglementLib Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility functions for the visualization code.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from disentanglement_lib.utils import resources import numpy as np from PIL import Image import scipy from six.moves import range import torch import imageio import matplotlib.pyplot as plt import matplotlib.animation as animation def array_animation(data, fps=20): fig, ax = plt.subplots(figsize=(3, 3)) plt.tight_layout() ax.set_axis_off() if len(data.shape) == 4: data = data.transpose([0, 2, 3, 1]) im = ax.imshow(data[0], vmin=0, vmax=1) def init(): im.set_data(data[0]) return (im,) # animation function. This is called sequentially def animate(i): data_slice = data[i] im.set_data(data_slice) return (im,) # call the animator. blit=True means only re-draw the parts that have changed. anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(data), interval=1000 / fps, blit=True) return anim def traversal_latents(base_latent, traversal_vector, dim): l = len(traversal_vector) traversals = base_latent.repeat(l, 1) traversals[:, dim] = traversal_vector return traversals def plot_bar(axes, images, label=None): for ax, img in zip(axes, images): if img.shape[2] == 3: ax.imshow(img) elif img.shape[2] == 1: ax.imshow(img.squeeze(2), cmap='gray') ax.axis('off') if label: axes[-1].get_yaxis().set_label_position("right") axes[-1].set_ylabel(label) def sigmoid(x): return 1 / (1 + np.exp(-np.clip(x, -20, 20))) def plt_sample_traversal(mu, decode, traversal_len=5, dim_list=range(4), r=3): """ :param mu: Tensor: [1,dim] :param decode: :param traversal_len: :param dim_list: :param r: :return: """ dim_len = len(dim_list) if len(mu.shape) == 1: mu = mu.unsqueeze(0) with torch.no_grad(): fig, axes = plt.subplots(dim_len, traversal_len, squeeze=False, figsize=(traversal_len, dim_len,)) plt.tight_layout(pad=0.1) plt.subplots_adjust(wspace=0.01, hspace=0.05) for i, dim in enumerate(dim_list): base_latents = mu.clone() linear_traversal = torch.linspace(-r, r, traversal_len) traversals = traversal_latents(base_latents, linear_traversal, dim) recon_batch = decode(traversals) plot_bar(axes[i, :], recon_batch) return fig def save_image(image, image_path): """Saves an image in the [0,1]-valued Numpy array to image_path. Args: image: Numpy array of shape (height, width, {1,3}) with values in [0, 1]. image_path: String with path to output image. """ # Copy the single channel if we are provided a grayscale image. if image.shape[2] == 1: image = np.repeat(image, 3, axis=2) image = np.ascontiguousarray(image) image *= 255. image = image.astype(np.uint8) # disable the converting warning with open(image_path, "wb") as path: img = Image.fromarray(image, mode="RGB") img.save(path) def grid_save_images(images, image_path): """Saves images in list of [0,1]-valued np.arrays on a grid. Args: images: List of Numpy arrays of shape (height, width, {1,3}) with values in [0, 1]. image_path: String with path to output image. """ side_length = int(math.floor(math.sqrt(len(images)))) image_rows = [ np.concatenate( images[side_length * i:side_length * i + side_length], axis=0) for i in range(side_length) ] tiled_image = np.concatenate(image_rows, axis=1) print(image_path) save_image(tiled_image, image_path) def padded_grid(images, num_rows=None, padding_px=10, value=None): """Creates a grid with padding in between images.""" num_images = len(images) if num_rows is None: num_rows = best_num_rows(num_images) # Computes how many empty images we need to add. num_cols = int(np.ceil(float(num_images) / num_rows)) num_missing = num_rows * num_cols - num_images # Add the empty images at the end. all_images = images + [np.ones_like(images[0])] * num_missing # Create the final grid. rows = [padded_stack(all_images[i * num_cols:(i + 1) * num_cols], padding_px, 1, value=value) for i in range(num_rows)] return padded_stack(rows, padding_px, axis=0, value=value) def padded_stack(images, padding_px=10, axis=0, value=None): """Stacks images along axis with padding in between images.""" padding_arr = padding_array(images[0], padding_px, axis, value=value) new_images = [images[0]] for image in images[1:]: new_images.append(padding_arr) new_images.append(image) return np.concatenate(new_images, axis=axis) def padding_array(image, padding_px, axis, value=None): """Creates padding image of proper shape to pad image along the axis.""" shape = list(image.shape) shape[axis] = padding_px if value is None: return np.ones(shape, dtype=image.dtype) else: assert len(value) == shape[-1] shape[-1] = 1 return np.tile(value, shape) def best_num_rows(num_elements, max_ratio=4): """Automatically selects a smart number of rows.""" best_remainder = num_elements best_i = None i = int(np.sqrt(num_elements)) while True: if num_elements > max_ratio * i * i: return best_i remainder = (i - num_elements % i) % i if remainder == 0: return i if remainder < best_remainder: best_remainder = remainder best_i = i i -= 1 def pad_around(image, padding_px=10, axis=None, value=None): """Adds a padding around each image.""" # If axis is None, pad both the first and the second axis. if axis is None: image = pad_around(image, padding_px, axis=0, value=value) axis = 1 padding_arr = padding_array(image, padding_px, axis, value=value) return np.concatenate([padding_arr, image, padding_arr], axis=axis) def add_below(image, padding_px=10, value=None): """Adds a footer below.""" if len(image.shape) == 2: image = np.expand_dims(image, -1) if image.shape[2] == 1: image = np.repeat(image, 3, 2) if image.shape[2] != 3: raise ValueError("Could not convert image to have three channels.") with open(resources.get_file("disentanglement_lib.png"), "rb") as f: footer = np.array(Image.open(f).convert("RGB")) * 1.0 / 255. missing_px = image.shape[1] - footer.shape[1] if missing_px < 0: return image if missing_px > 0: padding_arr = padding_array(footer, missing_px, axis=1, value=value) footer = np.concatenate([padding_arr, footer], axis=1) return padded_stack([image, footer], padding_px, axis=0, value=value) def save_animation(list_of_animated_images, image_path, fps): full_size_images = [] for single_images in zip(*list_of_animated_images): full_size_images.append( pad_around(add_below(padded_grid(list(single_images))))) imageio.mimwrite(image_path, full_size_images, fps=fps) def cycle_factor(starting_index, num_indices, num_frames): """Cycles through the state space in a single cycle.""" grid = np.linspace(starting_index, starting_index + 2 * num_indices, num=num_frames, endpoint=False) grid = np.array(np.ceil(grid), dtype=np.int64) grid -= np.maximum(0, 2 * grid - 2 * num_indices + 1) grid += np.maximum(0, -2 * grid - 1) return grid def cycle_gaussian(starting_value, num_frames, loc=0., scale=1.): """Cycles through the quantiles of a Gaussian in a single cycle.""" starting_prob = scipy.stats.norm.cdf(starting_value, loc=loc, scale=scale) grid = np.linspace(starting_prob, starting_prob + 2., num=num_frames, endpoint=False) grid -= np.maximum(0, 2 * grid - 2) grid += np.maximum(0, -2 * grid) grid = np.minimum(grid, 0.999) grid = np.maximum(grid, 0.001) return np.array([scipy.stats.norm.ppf(i, loc=loc, scale=scale) for i in grid]) def cycle_interval(starting_value, num_frames, min_val, max_val): """Cycles through the state space in a single cycle.""" starting_in_01 = (starting_value - min_val) / (max_val - min_val) grid = np.linspace(starting_in_01, starting_in_01 + 2., num=num_frames, endpoint=False) grid -= np.maximum(0, 2 * grid - 2) grid += np.maximum(0, -2 * grid) return grid * (max_val - min_val) + min_val
34.119565
84
0.653818
1,387
9,417
4.284066
0.240808
0.018176
0.015315
0.014137
0.143554
0.106698
0.099461
0.07001
0.07001
0.056547
0
0.021859
0.232452
9,417
275
85
34.243636
0.800221
0.207922
0
0.063584
0
0
0.012598
0.003149
0
0
0
0
0.00578
1
0.109827
false
0
0.075145
0.00578
0.289017
0.011561
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c60efc48bff6adf1e39c4b9e35874cde0aa11abd
6,515
py
Python
Lab/Lab5/lab5_group12_server.py
Zhuoyue-Xing/IOT---INTELLIG-CONNECTED-SYS
09111380e5ad36663e90de5bcd22691619c9a2f1
[ "Apache-2.0" ]
1
2020-03-04T21:51:42.000Z
2020-03-04T21:51:42.000Z
Lab/Lab5/lab5_group12_server.py
Zhuoyue-Xing/IOT---INTELLIG-CONNECTED-SYS
09111380e5ad36663e90de5bcd22691619c9a2f1
[ "Apache-2.0" ]
null
null
null
Lab/Lab5/lab5_group12_server.py
Zhuoyue-Xing/IOT---INTELLIG-CONNECTED-SYS
09111380e5ad36663e90de5bcd22691619c9a2f1
[ "Apache-2.0" ]
null
null
null
# Created by Chenye Yang, Haokai Zhao, Zhuoyue Xing on 2019/10/13. # Copyright © 2019 Chenye Yang, Haokai Zhao, Zhuoyue Xing . All rights reserved. from machine import Pin, I2C, RTC, Timer import socket import ssd1306 import time import network import urequests import json # ESP8266 connects to a router def ConnectWIFI(essid, key): import network sta_if = network.WLAN(network.STA_IF) # config a station object if not sta_if.isconnected(): # if the connection is not established print('connecting to network...') sta_if.active(True) # activate the station interface sta_if.connect(essid, key) # connect to WiFi network while not sta_if.isconnected(): print('connecting') pass print('network config:', sta_if.ifconfig()) # check the IP address # ap_if.active(False) # disable the access-point interface else: print('network config:', sta_if.ifconfig()) # IP address, subnet mask, gateway and DNS server # Get Current Time and Set ESP8266 Time to current time def SetCurtTime(): # World Clock API url = "http://worldclockapi.com/api/json/est/now" webTime = json.loads(urequests.get(url).text) # returns a json string, convert it to json webTime = webTime['currentDateTime'].split('T') # currentDataTime string as 2019-10-13T15:05-04:00 date = list(map(int, webTime[0].split('-'))) # extract time numbers time = list(map(int, webTime[1].split('-')[0].split(':'))) timeTuple = (date[0], date[1], date[2], 0, time[0], time[1], 0, 0) # (year, month, day, weekday, hours, minutes, seconds, mseconds) rtc.datetime(timeTuple) # set a specific date and time # print(rtc.datetime()) # Show current time on OLED def OLEDShowTime(): weekday = {0:'Monday', 1:'Tuesday', 2:'Wednesday', 3:'Thursday', 4:'Friday', 5:'Saturday', 6:'Sunday'} # Storeage the current date and time to <int> list timeList = list(map(int, rtc.datetime())) # Covert <int> list to <str> dateStr = "{:0>4d}".format(timeList[0])+'-'+"{:0>2d}".format(timeList[1])+'-'+"{:0>2d}".format(timeList[2]) # weekStr = weekday[timeList[3]] timeStr = "{:0>2d}".format(timeList[4])+':'+"{:0>2d}".format(timeList[5])+':'+"{:0>2d}".format(timeList[6]) # Put string to OLED oled.text(dateStr, 0, 0) # (message, x, y, color) # oled.text(weekStr, 0, 11) oled.text(timeStr, 0, 22) # OLED show whether ESP8266 received commands def OLEDRecvComd(received): if received: oled.text('RCVD', 80, 22) # Received the correct command else: oled.text('MISS', 80, 22) # Received a command ,but NOT a correct one # Judge the Command received def WhatCommand(cmd): # cmd is Command in string, like: "turn on display" global FLAG_True_Comd # Flag about whether it is a right command global FLAG_Display_On # Flag about whetehr OLED can display things global FLAG_Show_Time # Flag about whether the current time is shown on OLED if cmd == 'turn on display': FLAG_True_Comd = 1 FLAG_Display_On = 1 elif cmd == 'turn off display': FLAG_True_Comd = 1 FLAG_Display_On = 0 elif cmd == 'show current time': FLAG_True_Comd = 1 FLAG_Show_Time = 1 elif cmd == 'close current time': FLAG_True_Comd = 1 FLAG_Show_Time = 0 else: FLAG_True_Comd = 0 # not a right command # Judge what to display on OLED, and display OLED with Timer def WhatShowOLED(p): global FLAG_True_Comd # Flag about whether it is a right command global FLAG_Display_On # Flag about whetehr OLED can display things global FLAG_Show_Time # Flag about whether the current time is shown on OLED global showComd if FLAG_Display_On: # able to display OLED oled.text(showComd,0,11) OLEDRecvComd(FLAG_True_Comd) # whether it's a right command, show on OLED if FLAG_Show_Time: # show time on OLED if be able to OLEDShowTime() oled.show() # display text else: oled.fill(0) # fill OLED with black oled.show() # display all black oled.fill(0) # refresh, remove residue # ESP8266 as a server to listen and response def ListenResponse(): # a response ahout receiving a right JSON POST request goodHTML = """<!DOCTYPE html> <html> <head> <title>Good Command</title> </head> <body> <h1>The command from you is received by ESP8266</h1></body> </html> """ # a response ahout NOT receiving a JSON POST request badHTML = """<!DOCTYPE html> <html> <head> <title>Bad Command</title> </head> <body> <h1>The command from you is NOT a JSON format</h1></body> </html> """ addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] # Set web server port number to 80 s = socket.socket() s.bind(addr) # Bind the socket to address s.listen(1) # Enable a server to accept connections print('listening on', addr) global FLAG_True_Comd # Flag about whether it is a right command global FLAG_Display_On # Flag about whetehr OLED can display things global FLAG_Show_Time # Flag about whether the current time is shown on OLED FLAG_True_Comd = 0 FLAG_Display_On = 0 FLAG_Show_Time = 0 while True: print("FLAG_True_Comd", FLAG_True_Comd) print("FLAG_Display_On", FLAG_Display_On) print("FLAG_Show_Time", FLAG_Show_Time) # accept the connect to 80 port cl, addr = s.accept() print('client connected from', addr) # ESP8266 listen from the port # The client terminal instruction should be like: # curl -H "Content-Type:application/json" -X POST -d '{"Command":"turn on display"}' http://192.168.50.100:80 cl_receive = cl.recv(500).decode("utf-8").split("\r\n")[-1] # get the whole request and try to split it try: # if the request is in a JSON POST format cl_receive = json.loads(cl_receive) # convert the json string to json print(cl_receive['Command']) global showComd showComd = cl_receive['Command'] except ValueError: # if not, give the response ahout not receiving a JSON POST response = "HTTP/1.1 501 Implemented\r\n\r\nBad" else: # if can be trasformed to JSON, give good response response = "HTTP/1.1 200 OK\r\n\r\nGood" WhatCommand(cl_receive['Command']) # judge what's the command received # write to the port, i.e., give response cl.send(response) cl.close() if __name__ == '__main__': i2c = I2C(-1, scl=Pin(5), sda=Pin(4)) # initialize access to the I2C bus i2c.scan() oled = ssd1306.SSD1306_I2C(128, 32, i2c) # the width=128 and height=32 rtc = RTC() tim = Timer(-1) tim.init(period=100, mode=Timer.PERIODIC, callback=WhatShowOLED) ConnectWIFI('Columbia University','') # connect esp8266 to a router SetCurtTime() ListenResponse() # Show ESP8266 Pins to test server
35.601093
132
0.701765
1,024
6,515
4.383789
0.282227
0.021386
0.032078
0.018935
0.214079
0.203386
0.175763
0.160615
0.145912
0.129873
0
0.039351
0.176976
6,515
183
133
35.601093
0.79765
0.407982
0
0.31746
0
0
0.208344
0.005809
0.015873
0
0
0
0
1
0.055556
false
0.007937
0.063492
0
0.119048
0.079365
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c60efea748edd359a502e1515888c7b36fe55c0f
1,397
py
Python
Util/Validation.py
SkyfallenHQ/CoProvider-Daemon
57cc2eb44f21c053db39313840c23c754a0143be
[ "MIT" ]
1
2021-03-01T07:43:32.000Z
2021-03-01T07:43:32.000Z
Util/Validation.py
SkyfallenHQ/CoProvider-Daemon
57cc2eb44f21c053db39313840c23c754a0143be
[ "MIT" ]
null
null
null
Util/Validation.py
SkyfallenHQ/CoProvider-Daemon
57cc2eb44f21c053db39313840c23c754a0143be
[ "MIT" ]
null
null
null
# ____ _ __ _ _ # # / ___|| | ___ _ / _| __ _| | | ___ _ __ # # \___ \| |/ / | | | |_ / _` | | |/ _ \ '_ \ # # ___) | <| |_| | _| (_| | | | __/ | | |# # |____/|_|\_\\__, |_| \__,_|_|_|\___|_| |_|# # |___/ ######### # ____ ____ _ _ # # / ___|___ | _ \ _ __ _____ _(_) __| | ___ _ __ # # | | / _ \| |_) | '__/ _ \ \ / / |/ _` |/ _ \ '__|# # | |__| (_) | __/| | | (_) \ V /| | (_| | __/ | # # \____\___/|_| |_| \___/ \_/ |_|\__,_|\___|_| # # # ########################################################################### # (C) 2021 - Skyfallen Developers # # Skyfallen CoProvider Beta # # Manage your containerized servers with ease. # # ----DAEMON CODE---- # # This file helps validate requests # ########################################################################### class ArgumentValidator: def validateGetParams(requestArgs, paramsToValidate): for x in paramsToValidate: y = requestArgs.get(x) if(y == "" or y == None): return False return True
45.064516
76
0.286328
44
1,397
5.977273
0.840909
0
0
0
0
0
0
0
0
0
0
0.005263
0.455977
1,397
31
77
45.064516
0.340789
0.656407
0
0
0
0
0
0
0
0
0
0
0
1
0.142857
false
0
0
0
0.571429
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
c60fff305331c5af7ece82691a51268226e5c661
453
py
Python
cord19/scripts/metadata/prefixes.py
udel-cbcb/covid19kg_rdf
3cd8dd6c4654333777db6127f2a3f2e01b92b0ac
[ "CC-BY-4.0" ]
null
null
null
cord19/scripts/metadata/prefixes.py
udel-cbcb/covid19kg_rdf
3cd8dd6c4654333777db6127f2a3f2e01b92b0ac
[ "CC-BY-4.0" ]
null
null
null
cord19/scripts/metadata/prefixes.py
udel-cbcb/covid19kg_rdf
3cd8dd6c4654333777db6127f2a3f2e01b92b0ac
[ "CC-BY-4.0" ]
null
null
null
from rdflib import Namespace, XSD from rdflib.namespace import DC, DCTERMS FHIRCAT_CORD = Namespace("http://fhircat.org/cord-19/") SSO = Namespace("http://semanticscholar.org/cv-research/") DOI = Namespace("https://doi.org/") PUBMED = Namespace("https://www.ncbi.nlm.nih.gov/pubmed/") PMC = Namespace("https://www.ncbi.nlm.nih.gov/pmc/articles/") MS_ACADEMIC = Namespace("https://academic.microsoft.com/paper/") FHIR = Namespace("http://hl7.org/fhir/")
45.3
64
0.735099
64
453
5.171875
0.515625
0.169184
0.102719
0.126888
0.181269
0.181269
0.181269
0
0
0
0
0.007109
0.068433
453
10
65
45.3
0.777251
0
0
0
0
0
0.477974
0
0
0
0
0
0
1
0
false
0
0.222222
0
0.222222
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c6111b7e68c98d9dc89d8452745da9d3fb412b2a
6,568
py
Python
pbutils/argparsers.py
phonybone/phonybone_utils
d95f226ddfc62a1d69b5ff6f53de86188fe0c8f9
[ "MIT" ]
null
null
null
pbutils/argparsers.py
phonybone/phonybone_utils
d95f226ddfc62a1d69b5ff6f53de86188fe0c8f9
[ "MIT" ]
null
null
null
pbutils/argparsers.py
phonybone/phonybone_utils
d95f226ddfc62a1d69b5ff6f53de86188fe0c8f9
[ "MIT" ]
null
null
null
import sys import os import argparse from types import MethodType from importlib import import_module from argparse import RawTextHelpFormatter # Note: this applies to all options, might not always be what we want... from pbutils.configs import get_config, get_config_from_data, to_dict, inject_opts, CP from .strings import qw, ppjson from .streams import warn def parser_stub(docstr): parser = argparse.ArgumentParser(description=docstr, formatter_class=RawTextHelpFormatter) parser.add_argument('--config', default=_get_default_config_fn()) parser.add_argument('-v', '--verbose', action='store_true', help='verbose') parser.add_argument('-q', '--silent', action='store_true', help='silent mode') parser.add_argument('-d', '--debug', action='store_true', help='debugging flag') # leave comments here as templates # parser.add_argument('required_arg') # parser.add_argument('--something', default='', help='') # parser.add_argument('args', nargs=argparse.REMAINDER) return parser def _get_default_config_fn(): # warning: pyenv breaks this with its shims fn = sys.argv[0].replace('.py', '.ini') if not fn.endswith('.ini'): fn += '.ini' return fn def _assemble_config(opts, default_section_name='default'): ''' This builds a config by the following steps: 1. read config file (as specified in opts, otherwise empty) 2. inject environment vars as specified by config 3. inject opts returns a ConfigParserRaw object. ''' if opts.config: try: config = get_config(opts.config, config_type='Raw') except OSError as e: if e.errno == 2 and e.filename != _get_default_config_fn(): raise else: config = get_config_from_data(f'[{default_section_name}]') if opts.debug: warn(f'skipping non-existent config file {opts.config}') inject_opts(config, opts) # add a convenience method to get opts, which are stored in the default section: def opt(self, opt, default=None): try: return self.get(default_section_name, opt) except CP.NoOptionError: if default is not None: return default else: raise config.opt = MethodType(opt, config) return config def wrap_main(main, parser, args=sys.argv[1:]): ''' create config from config file and cmd-line args; set os.environ['DEBUG'] if -d; Call main(config); trap exceptions; if they occur, print an error message (with optional stack trace) and set exit value appropriately. ''' opts = parser.parse_args(args) config = _assemble_config(opts) if opts.debug: os.environ['DEBUG'] = 'True' warn(opts) if opts.silent and opts.verbose: warn('WARNING: both --silent and --verbose are set. Your output may be weird') try: rc = main(config) or 0 sys.exit(rc) except Exception as e: if 'DEBUG' in os.environ: import traceback traceback.print_exc() else: print('error: {} {}'.format(type(e), e)) sys.exit(1) def parser_config(parser, config): ''' Use sections/values from the config file to initialize an argparser. One cmd-line arg per config section; that is, each section contains all the args needed for a call to parser.add_argument() Example: names = ['-x', '--some-option'] section = {'type': int, 'action': 'store_true', etc} (Note: conflict) ''' for section in config.sections(): section_dict = to_dict(config, section) names = ['--'+section] if 'short_name' in section_dict: names.append('-'+section_dict.pop('short_name')) if 'type' in section_dict: actual_type = eval(section_dict['type']) section_dict['type'] = actual_type if 'default' in section_dict: section_dict['default'] = actual_type(section_dict['default']) if 'action' in section_dict: action = section_dict['action'] if action not in qw('store store_const store_true store_false append append_const count help version'): # action must be fully qualified name (module and class) of a class derived from argparse.Action modname, clsname = action.rsplit('.', 1) mod = import_module(modname) cls = getattr(mod, clsname) section_dict['action'] = cls parser.add_argument(*names, **section_dict) class FloatIntStrParserAction(argparse.Action): ''' Convert a string value to float, int, or str as possible. To be used as value to 'action' kwarg of argparse.parser.add_argument, eg: parser.add_argument('--some-value', action=FloatIntStrParserAction, ...) This is called one time for each value on command line. NOTE: use of this class as an Action precludes the use of the 'type' kwarg in add_argument! ''' def __init__(self, **kwargs): super(FloatIntStrParserAction, self).__init__(**kwargs) def __call__(self, parser, namespace, values, option_string): if self.type is not None: # coerce to that type setattr(namespace, self.dest, self.type(values)) return for t in [int, float, str]: # order important try: setattr(namespace, self.dest, t(values)) break except ValueError as e: pass else: parser.error("Error processing negc_var '{}'".format(values)) # should never get here if __name__ == '__main__': def getopts(opts_ini=None): import argparse parser = argparse.ArgumentParser() if opts_ini: opts_config = get_config(opts_ini) parser.add_argument('-v', action='store_true', help='verbose mode') parser.add_argument('-q', action='store_true', help='silent mode') parser.add_argument('-d', action='store_true', help='debugging flag') opts = parser.parse_args() if opts.debug: os.environ['DEBUG'] = 'True' print(ppjson(vars(opts))) return opts # ----------------------------------------------------------------------- opts_ini = os.path.abspath(os.path.join(os.path.dirname(__file__), 'opts.ini')) if not os.path.exists(opts_ini): warn('{}: no such file') opts_ini = None opts = getopts(opts_ini)
34.568421
115
0.622259
828
6,568
4.786232
0.300725
0.041635
0.060056
0.028766
0.079233
0.054504
0.038355
0.023719
0.023719
0.023719
0
0.00185
0.25944
6,568
189
116
34.751323
0.812911
0.25609
0
0.149123
0
0
0.124526
0.005057
0
0
0
0
0
1
0.078947
false
0.008772
0.105263
0
0.254386
0.026316
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c612683f9e5f1b8a554762571a5c3752edd3f4c6
513
py
Python
api/management/commands/user_stats.py
kopf/zzzz
eeaebc24c7c2c290e167dcf1a74c18586a3a75a7
[ "BSD-3-Clause" ]
10
2019-04-16T18:08:55.000Z
2022-03-17T21:30:47.000Z
api/management/commands/user_stats.py
kopf/zzzz
eeaebc24c7c2c290e167dcf1a74c18586a3a75a7
[ "BSD-3-Clause" ]
3
2019-04-16T18:26:41.000Z
2021-06-10T21:22:13.000Z
api/management/commands/user_stats.py
kopf/zzzz
eeaebc24c7c2c290e167dcf1a74c18586a3a75a7
[ "BSD-3-Clause" ]
1
2021-05-23T07:10:04.000Z
2021-05-23T07:10:04.000Z
#!/usr/bin/env python3 import json from django.core.management.base import BaseCommand from api.models import User class Command(BaseCommand): help = 'Print a dict of user status (number of users signed up per day) to stdout' def handle(self, *args, **options): stats = {} for user in User.objects.all(): date_str = user.date_joined.strftime('%Y-%m-%d') stats.setdefault(date_str, 0) stats[date_str] += 1 print(json.dumps(stats, indent=4))
27
86
0.639376
73
513
4.438356
0.739726
0.064815
0
0
0
0
0
0
0
0
0
0.010309
0.243665
513
18
87
28.5
0.824742
0.040936
0
0
0
0
0.164969
0
0
0
0
0
0
1
0.083333
false
0
0.25
0
0.5
0.083333
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c614a1664f6bdf152a7894bbff6e36ef78258fe0
1,234
py
Python
tests/test_asdf_schema.py
WilliamJamieson/asdf-standard
d0934b2abd95507e5d5f79ed69782d5b6b24eadd
[ "BSD-3-Clause" ]
47
2015-04-21T10:03:44.000Z
2020-06-16T12:02:35.000Z
tests/test_asdf_schema.py
WilliamJamieson/asdf-standard
d0934b2abd95507e5d5f79ed69782d5b6b24eadd
[ "BSD-3-Clause" ]
120
2015-01-12T23:45:17.000Z
2020-06-06T17:20:28.000Z
tests/test_asdf_schema.py
WilliamJamieson/asdf-standard
d0934b2abd95507e5d5f79ed69782d5b6b24eadd
[ "BSD-3-Clause" ]
22
2015-04-21T10:14:44.000Z
2020-06-16T08:55:17.000Z
import pytest from common import SCHEMAS_PATH, assert_yaml_header_and_footer, load_yaml from jsonschema import ValidationError @pytest.mark.parametrize("path", SCHEMAS_PATH.glob("asdf-schema-*.yaml")) def test_asdf_schema(path): assert_yaml_header_and_footer(path) # Asserting no exceptions here load_yaml(path) @pytest.mark.parametrize("path", SCHEMAS_PATH.glob("asdf-schema-*.yaml")) def test_nested_object_validation(path, create_validator): """ Test that the validations are applied to nested objects. """ metaschema = load_yaml(path) validator = create_validator(metaschema) schema = {"$schema": metaschema["id"], "type": "object", "properties": {"foo": {"datatype": "float32"}}} # No error here validator.validate(schema) schema = {"$schema": metaschema["id"], "type": "object", "properties": {"foo": {"datatype": "banana"}}} with pytest.raises(ValidationError, match="'banana' is not valid"): validator.validate(schema) schema = { "$schema": metaschema["id"], "type": "array", "items": {"type": "object", "properties": {"foo": {"ndim": "twelve"}}}, } with pytest.raises(ValidationError): validator.validate(schema)
33.351351
108
0.67342
139
1,234
5.827338
0.410072
0.074074
0.081481
0.088889
0.449383
0.449383
0.377778
0.377778
0.28642
0.150617
0
0.001947
0.167747
1,234
36
109
34.277778
0.786758
0.081037
0
0.217391
0
0
0.191585
0
0
0
0
0
0.086957
1
0.086957
false
0
0.130435
0
0.217391
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c61593afa95fc30a19ca5363d13b5db09015e8fd
5,552
py
Python
retinanet/dataloader/label_encoder.py
lchen-wyze/retinanet-tensorflow2.x
86404a2da6ec636d4b1aef768ac52f018c127798
[ "Apache-2.0" ]
36
2020-09-23T13:32:47.000Z
2022-03-29T18:53:58.000Z
retinanet/dataloader/label_encoder.py
lchen-wyze/retinanet-tensorflow2.x
86404a2da6ec636d4b1aef768ac52f018c127798
[ "Apache-2.0" ]
12
2020-10-25T09:07:58.000Z
2021-11-17T12:53:50.000Z
retinanet/dataloader/label_encoder.py
lchen-wyze/retinanet-tensorflow2.x
86404a2da6ec636d4b1aef768ac52f018c127798
[ "Apache-2.0" ]
9
2020-11-12T20:03:06.000Z
2022-01-03T12:40:48.000Z
import tensorflow as tf from retinanet.dataloader.anchor_generator import AnchorBoxGenerator from retinanet.dataloader.preprocessing_pipeline import PreprocessingPipeline from retinanet.dataloader.utils import compute_iou class LabelEncoder: def __init__(self, params): self.input_shape = params.input.input_shape self.encoder_params = params.encoder_params self.anchors = AnchorBoxGenerator( *self.input_shape, params.architecture.feature_fusion.min_level, params.architecture.feature_fusion.max_level, params.anchor_params) self.preprocessing_pipeline = PreprocessingPipeline( self.input_shape, params.dataloader_params) self._all_unmatched = -1 * tf.ones( [self.anchors.boxes.get_shape().as_list()[0]], dtype=tf.int32) self._min_level = params.architecture.feature_fusion.min_level self._max_level = params.architecture.feature_fusion.max_level self._params = params def _match_anchor_boxes(self, anchor_boxes, gt_boxes): if tf.shape(gt_boxes)[0] == 0: return self._all_unmatched iou_matrix = compute_iou(gt_boxes, anchor_boxes, pair_wise=True) max_ious = tf.reduce_max(iou_matrix, axis=0) matched_gt_idx = tf.argmax(iou_matrix, axis=0, output_type=tf.int32) matches = tf.where(tf.greater(max_ious, self.encoder_params.match_iou), matched_gt_idx, -1) matches = tf.where( tf.logical_and( tf.greater_equal(max_ious, self.encoder_params.ignore_iou), tf.greater(self.encoder_params.match_iou, max_ious)), -2, matches) best_matched_anchors = tf.argmax(iou_matrix, axis=-1, output_type=tf.int32) best_matched_anchors_one_hot = tf.one_hot( best_matched_anchors, depth=tf.shape(iou_matrix)[-1]) matched_anchors = tf.reduce_max(best_matched_anchors_one_hot, axis=0) matched_anchors_gt_idx = tf.argmax(best_matched_anchors_one_hot, axis=0, output_type=tf.int32) matches = tf.where(tf.cast(matched_anchors, dtype=tf.bool), matched_anchors_gt_idx, matches) return matches def _compute_box_target(self, matched_gt_boxes, matches, eps=1e-8): matched_gt_boxes = tf.maximum(matched_gt_boxes, eps) box_target = tf.concat( [ (matched_gt_boxes[:, :2] - self.anchors.boxes[:, :2]) / self.anchors.boxes[:, 2:], tf.math.log( matched_gt_boxes[:, 2:] / self.anchors.boxes[:, 2:]), ], axis=-1, ) positive_mask = tf.expand_dims(tf.greater_equal(matches, 0), axis=-1) positive_mask = tf.broadcast_to(positive_mask, tf.shape(box_target)) box_target = tf.where(positive_mask, box_target, 0.0) if self.encoder_params.scale_box_targets: box_target = box_target / tf.convert_to_tensor( self.encoder_params.box_variance, dtype=tf.float32) return box_target @staticmethod def _pad_labels(gt_boxes, cls_ids): gt_boxes = tf.concat([tf.stack([tf.zeros(4), tf.zeros(4)]), gt_boxes], axis=0) cls_ids = tf.concat([ tf.squeeze(tf.stack([-2 * tf.ones(1), -1 * tf.ones(1)])), cls_ids ], axis=0) return gt_boxes, cls_ids def encode_sample(self, sample): image, gt_boxes, cls_ids = self.preprocessing_pipeline(sample) matches = self._match_anchor_boxes(self.anchors.boxes, gt_boxes) cls_ids = tf.cast(cls_ids, dtype=tf.float32) gt_boxes, cls_ids = LabelEncoder._pad_labels(gt_boxes, cls_ids) gt_boxes = tf.gather(gt_boxes, matches + 2) cls_target = tf.gather(cls_ids, matches + 2) box_target = self._compute_box_target(gt_boxes, matches) iou_target = compute_iou(self.anchors.boxes, gt_boxes, pair_wise=False) iou_target = tf.where(tf.greater(matches, -1), iou_target, -1.0) boundaries = self.anchors.anchor_boundaries targets = {'class-targets': {}, 'box-targets': {}} if self._params.architecture.auxillary_head.use_auxillary_head: targets['iou-targets'] = {} # TODO(srihari): use pyramid levels for indexing for level in range(self._min_level, self._max_level + 1): i = level - 3 fh = tf.math.ceil(self.input_shape[0] / (2**(i + 3))) fw = tf.math.ceil(self.input_shape[1] / (2**(i + 3))) targets['class-targets'][str(i + 3)] = tf.reshape( cls_target[boundaries[i]:boundaries[i + 1]], shape=[fh, fw, self.anchors._num_anchors]) targets['box-targets'][str(i + 3)] = tf.reshape( box_target[boundaries[i]:boundaries[i + 1]], shape=[fh, fw, 4 * self.anchors._num_anchors]) if 'iou-targets' in targets: targets['iou-targets'][str(i + 3)] = tf.reshape( iou_target[boundaries[i]:boundaries[i + 1]], shape=[fh, fw, self.anchors._num_anchors]) num_positives = tf.reduce_sum( tf.cast(tf.greater(matches, -1), dtype=tf.float32)) targets['num-positives'] = num_positives return image, targets
44.063492
79
0.608249
695
5,552
4.579856
0.185612
0.043984
0.032045
0.024505
0.314797
0.222432
0.15677
0.112473
0.092366
0.060949
0
0.016779
0.2808
5,552
125
80
44.416
0.780366
0.008285
0
0.096154
0
0
0.017078
0
0
0
0
0.008
0
1
0.048077
false
0
0.038462
0
0.144231
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0