hexsha
stringlengths
40
40
size
int64
1
1.03M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
239
max_stars_repo_name
stringlengths
5
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
239
max_issues_repo_name
stringlengths
5
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
239
max_forks_repo_name
stringlengths
5
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.03M
avg_line_length
float64
1
958k
max_line_length
int64
1
1.03M
alphanum_fraction
float64
0
1
ace86adcf8fdda3535ec166fdd65047c17e41f21
142
py
Python
degiroapi/order_type.py
Jorricks/python-degiro
ee155ce952ff6b6d04daf3b2f1fe94c85e757b5d
[ "MIT" ]
7
2021-09-12T21:08:22.000Z
2022-01-24T21:16:25.000Z
degiroapi/order_type.py
Jorricks/python-degiro
ee155ce952ff6b6d04daf3b2f1fe94c85e757b5d
[ "MIT" ]
null
null
null
degiroapi/order_type.py
Jorricks/python-degiro
ee155ce952ff6b6d04daf3b2f1fe94c85e757b5d
[ "MIT" ]
1
2021-09-12T21:08:25.000Z
2021-09-12T21:08:25.000Z
class OrderType: """The type of order we want to perform on DeGiro.""" LIMIT = 0 STOP_LIMIT = 1 MARKET = 2 STOP_LOSS = 3
17.75
57
0.598592
ace86b0705665210f597f1f0d52eae705b811c20
2,278
py
Python
utils/console_fonts.py
TheVinhLuong102/ev3dev-lang-python
f84152ca9b952a7a47a3f477542f878f3b69b824
[ "MIT" ]
306
2017-10-19T08:58:44.000Z
2022-03-25T09:02:09.000Z
utils/console_fonts.py
TheVinhLuong102/ev3dev-lang-python
f84152ca9b952a7a47a3f477542f878f3b69b824
[ "MIT" ]
357
2017-10-15T07:33:04.000Z
2022-02-28T16:56:16.000Z
utils/console_fonts.py
TheVinhLuong102/ev3dev-lang-python
f84152ca9b952a7a47a3f477542f878f3b69b824
[ "MIT" ]
116
2017-10-29T11:53:57.000Z
2022-03-31T19:23:17.000Z
#!/usr/bin/env micropython from time import sleep from sys import stderr from os import listdir from ev3dev2.console import Console """ Used to iterate over the system console fonts (in /usr/share/consolefonts) and show the max row/col. Font names consist of three parameters - codeset, font face and font size. The codeset specifies what characters will be supported by the font. The font face determines the general look of the font. Each font face is available in certain possible sizes. For Codeset clarity, see https://www.systutorials.com/docs/linux/man/5-console-setup/#lbAP """ def show_fonts(): """ Iterate through all the Latin "1 & 5" fonts, and see how many rows/columns the EV3 LCD console can accommodate for each font. Note: ``Terminus`` fonts are "thinner"; ``TerminusBold`` and ``VGA`` offer more contrast on the LCD console and are thus more readable; the ``TomThumb`` font is waaaaay too small to read! """ console = Console() files = [f for f in listdir("/usr/share/consolefonts/") if f.startswith("Lat15") and f.endswith(".psf.gz")] files.sort() fonts = [] for font in files: console.set_font(font, True) console.text_at(font, 1, 1, False, True) console.clear_to_eol() console.text_at("{}, {}".format(console.columns, console.rows), column=2, row=4, reset_console=False, inverse=False) print("{}, {}, \"{}\"".format(console.columns, console.rows, font), file=stderr) fonts.append((console.columns, console.rows, font)) fonts.sort(key=lambda f: (f[0], f[1], f[2])) # Paint the screen full of numbers that represent the column number, reversing the even rows for cols, rows, font in fonts: print(cols, rows, font, file=stderr) console.set_font(font, True) for row in range(1, rows + 1): for col in range(1, cols + 1): console.text_at("{}".format(col % 10), col, row, False, (row % 2 == 0)) console.text_at(font.split(".")[0], 1, 1, False, True) console.clear_to_eol() # Show the fonts; you may want to adjust the ``startswith`` filter to show other codesets. show_fonts() sleep(5)
39.275862
111
0.64223
ace86bac35bef6685cd70f7dac83a6701350f273
1,753
py
Python
icgauge/utils_similarity.py
ptoman/icgauge
3e7c12c0365de717ad20521aca4adc24aaa8d1db
[ "MIT" ]
10
2016-05-16T05:14:34.000Z
2021-05-07T11:41:01.000Z
icgauge/utils_similarity.py
ptoman/icgauge
3e7c12c0365de717ad20521aca4adc24aaa8d1db
[ "MIT" ]
null
null
null
icgauge/utils_similarity.py
ptoman/icgauge
3e7c12c0365de717ad20521aca4adc24aaa8d1db
[ "MIT" ]
3
2016-05-22T20:54:28.000Z
2021-01-07T13:57:39.000Z
# -*- coding: utf-8 -*- #!/usr/bin/python import numpy as np from nltk.tokenize import word_tokenize, sent_tokenize from nltk.corpus import wordnet as wn def get_synset(tuple_word_pos): """ Returns the most common synset for the word/pos pair `tuple_word_pos`, or `None` if the word is unknown to WordNet """ word, pos = tuple_word_pos synset = wn.synsets(word, pos) if len(synset) == 0: return None else: return synset[0] def similarity_li(tuple1, tuple2, alpha=0.2, beta=0.6): """ Follows Li et al. 2003 as represented in Kannan Ambili 2014 thesis, page 41 """ # Return 0 similarity if Noun+Verb pair (situation not specified in thesis) if tuple1[1] != tuple2[1]: return 0 # Get synsets (approach not specified in thesis) synset1 = get_synset(tuple1) synset2 = get_synset(tuple2) # Return 0 similarity if word is not in wordnet (situation not specified in thesis) if synset1 is None or synset2 is None: return 0 # Calculate path length, path depth path_length = 1 if synset1 == synset2 else synset1.shortest_path_distance(synset2) # If they aren't reachable from each other, no similarity btw words (not specified in thesis) if path_length is None: path_length = np.inf subsumers = synset1.lowest_common_hypernyms(synset2, simulate_root=True, use_min_depth=True) # If nothing subsumes, there is no similarity between words (not specified) if len(subsumers) == 0: return 0 subsumer = subsumers[0] path_depth = subsumer.max_depth() + 1 # Calculate similarity similarity = np.exp(-alpha * path_length) * \ (np.exp(beta*path_depth) - np.exp(-beta*path_depth)) / \ (np.exp(beta*path_depth) + np.exp(-beta*path_depth)) return similarity
36.520833
95
0.707359
ace86c2fd6fcd1666a3b92f109aa2f8dcd4cd6c2
16,684
py
Python
yt_dlp/extractor/mediasite.py
mrBliss/yt-dlp
aecd021656b672dbb617e5bae54a8986f9c4ebaf
[ "Unlicense" ]
80
2021-05-25T11:33:49.000Z
2022-03-29T20:36:53.000Z
yt_dlp/extractor/mediasite.py
mrBliss/yt-dlp
aecd021656b672dbb617e5bae54a8986f9c4ebaf
[ "Unlicense" ]
53
2017-04-12T19:53:18.000Z
2022-02-22T10:33:13.000Z
yt_dlp/extractor/mediasite.py
mrBliss/yt-dlp
aecd021656b672dbb617e5bae54a8986f9c4ebaf
[ "Unlicense" ]
22
2021-05-07T05:01:27.000Z
2022-03-26T19:10:54.000Z
# coding: utf-8 from __future__ import unicode_literals import re import json from .common import InfoExtractor from ..compat import ( compat_str, compat_urlparse, ) from ..utils import ( ExtractorError, float_or_none, mimetype2ext, str_or_none, try_get, unescapeHTML, unsmuggle_url, url_or_none, urljoin, ) _ID_RE = r'(?:[0-9a-f]{32,34}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12,14})' class MediasiteIE(InfoExtractor): _VALID_URL = r'(?xi)https?://[^/]+/Mediasite/(?:Play|Showcase/[^/#?]+/Presentation)/(?P<id>%s)(?P<query>\?[^#]+|)' % _ID_RE _TESTS = [ { 'url': 'https://hitsmediaweb.h-its.org/mediasite/Play/2db6c271681e4f199af3c60d1f82869b1d', 'info_dict': { 'id': '2db6c271681e4f199af3c60d1f82869b1d', 'ext': 'mp4', 'title': 'Lecture: Tuesday, September 20, 2016 - Sir Andrew Wiles', 'description': 'Sir Andrew Wiles: “Equations in arithmetic”\\n\\nI will describe some of the interactions between modern number theory and the problem of solving equations in rational numbers or integers\\u0027.', 'timestamp': 1474268400.0, 'upload_date': '20160919', }, }, { 'url': 'http://mediasite.uib.no/Mediasite/Play/90bb363295d945d6b548c867d01181361d?catalog=a452b7df-9ae1-46b7-a3ba-aceeb285f3eb', 'info_dict': { 'id': '90bb363295d945d6b548c867d01181361d', 'ext': 'mp4', 'upload_date': '20150429', 'title': '5) IT-forum 2015-Dag 1 - Dungbeetle - How and why Rain created a tiny bug tracker for Unity', 'timestamp': 1430311380.0, }, }, { 'url': 'https://collegerama.tudelft.nl/Mediasite/Play/585a43626e544bdd97aeb71a0ec907a01d', 'md5': '481fda1c11f67588c0d9d8fbdced4e39', 'info_dict': { 'id': '585a43626e544bdd97aeb71a0ec907a01d', 'ext': 'mp4', 'title': 'Een nieuwe wereld: waarden, bewustzijn en techniek van de mensheid 2.0.', 'description': '', 'thumbnail': r're:^https?://.*\.jpg(?:\?.*)?$', 'duration': 7713.088, 'timestamp': 1413309600, 'upload_date': '20141014', }, }, { 'url': 'https://collegerama.tudelft.nl/Mediasite/Play/86a9ea9f53e149079fbdb4202b521ed21d?catalog=fd32fd35-6c99-466c-89d4-cd3c431bc8a4', 'md5': 'ef1fdded95bdf19b12c5999949419c92', 'info_dict': { 'id': '86a9ea9f53e149079fbdb4202b521ed21d', 'ext': 'wmv', 'title': '64ste Vakantiecursus: Afvalwater', 'description': 'md5:7fd774865cc69d972f542b157c328305', 'thumbnail': r're:^https?://.*\.jpg(?:\?.*?)?$', 'duration': 10853, 'timestamp': 1326446400, 'upload_date': '20120113', }, }, { 'url': 'http://digitalops.sandia.gov/Mediasite/Play/24aace4429fc450fb5b38cdbf424a66e1d', 'md5': '9422edc9b9a60151727e4b6d8bef393d', 'info_dict': { 'id': '24aace4429fc450fb5b38cdbf424a66e1d', 'ext': 'mp4', 'title': 'Xyce Software Training - Section 1', 'description': r're:(?s)SAND Number: SAND 2013-7800.{200,}', 'upload_date': '20120409', 'timestamp': 1333983600, 'duration': 7794, } }, { 'url': 'https://collegerama.tudelft.nl/Mediasite/Showcase/livebroadcast/Presentation/ada7020854f743c49fbb45c9ec7dbb351d', 'only_matching': True, }, { 'url': 'https://mediasite.ntnu.no/Mediasite/Showcase/default/Presentation/7d8b913259334b688986e970fae6fcb31d', 'only_matching': True, }, { # dashed id 'url': 'https://hitsmediaweb.h-its.org/mediasite/Play/2db6c271-681e-4f19-9af3-c60d1f82869b1d', 'only_matching': True, } ] # look in Mediasite.Core.js (Mediasite.ContentStreamType[*]) _STREAM_TYPES = { 0: 'video1', # the main video 2: 'slide', 3: 'presentation', 4: 'video2', # screencast? 5: 'video3', } @staticmethod def _extract_urls(webpage): return [ unescapeHTML(mobj.group('url')) for mobj in re.finditer( r'(?xi)<iframe\b[^>]+\bsrc=(["\'])(?P<url>(?:(?:https?:)?//[^/]+)?/Mediasite/Play/%s(?:\?.*?)?)\1' % _ID_RE, webpage)] def __extract_slides(self, *, stream_id, snum, Stream, duration, images): slide_base_url = Stream['SlideBaseUrl'] fname_template = Stream['SlideImageFileNameTemplate'] if fname_template != 'slide_{0:D4}.jpg': self.report_warning('Unusual slide file name template; report a bug if slide downloading fails') fname_template = re.sub(r'\{0:D([0-9]+)\}', r'{0:0\1}', fname_template) fragments = [] for i, slide in enumerate(Stream['Slides']): if i == 0: if slide['Time'] > 0: default_slide = images.get('DefaultSlide') if default_slide is None: default_slide = images.get('DefaultStreamImage') if default_slide is not None: default_slide = default_slide['ImageFilename'] if default_slide is not None: fragments.append({ 'path': default_slide, 'duration': slide['Time'] / 1000, }) next_time = try_get(None, [ lambda _: Stream['Slides'][i + 1]['Time'], lambda _: duration, lambda _: slide['Time'], ], expected_type=(int, float)) fragments.append({ 'path': fname_template.format(slide.get('Number', i + 1)), 'duration': (next_time - slide['Time']) / 1000 }) return { 'format_id': '%s-%u.slides' % (stream_id, snum), 'ext': 'mhtml', 'url': slide_base_url, 'protocol': 'mhtml', 'acodec': 'none', 'vcodec': 'none', 'format_note': 'Slides', 'fragments': fragments, 'fragment_base_url': slide_base_url, } def _real_extract(self, url): url, data = unsmuggle_url(url, {}) mobj = self._match_valid_url(url) resource_id = mobj.group('id') query = mobj.group('query') webpage, urlh = self._download_webpage_handle(url, resource_id) # XXX: add UrlReferrer? redirect_url = urlh.geturl() # XXX: might have also extracted UrlReferrer and QueryString from the html service_path = compat_urlparse.urljoin(redirect_url, self._html_search_regex( r'<div[^>]+\bid=["\']ServicePath[^>]+>(.+?)</div>', webpage, resource_id, default='/Mediasite/PlayerService/PlayerService.svc/json')) player_options = self._download_json( '%s/GetPlayerOptions' % service_path, resource_id, headers={ 'Content-type': 'application/json; charset=utf-8', 'X-Requested-With': 'XMLHttpRequest', }, data=json.dumps({ 'getPlayerOptionsRequest': { 'ResourceId': resource_id, 'QueryString': query, 'UrlReferrer': data.get('UrlReferrer', ''), 'UseScreenReader': False, } }).encode('utf-8'))['d'] presentation = player_options['Presentation'] title = presentation['Title'] if presentation is None: raise ExtractorError( 'Mediasite says: %s' % player_options['PlayerPresentationStatusMessage'], expected=True) thumbnails = [] formats = [] for snum, Stream in enumerate(presentation['Streams']): stream_type = Stream.get('StreamType') if stream_type is None: continue video_urls = Stream.get('VideoUrls') if not isinstance(video_urls, list): video_urls = [] stream_id = self._STREAM_TYPES.get( stream_type, 'type%u' % stream_type) stream_formats = [] for unum, VideoUrl in enumerate(video_urls): video_url = url_or_none(VideoUrl.get('Location')) if not video_url: continue # XXX: if Stream.get('CanChangeScheme', False), switch scheme to HTTP/HTTPS media_type = VideoUrl.get('MediaType') if media_type == 'SS': stream_formats.extend(self._extract_ism_formats( video_url, resource_id, ism_id='%s-%u.%u' % (stream_id, snum, unum), fatal=False)) elif media_type == 'Dash': stream_formats.extend(self._extract_mpd_formats( video_url, resource_id, mpd_id='%s-%u.%u' % (stream_id, snum, unum), fatal=False)) else: stream_formats.append({ 'format_id': '%s-%u.%u' % (stream_id, snum, unum), 'url': video_url, 'ext': mimetype2ext(VideoUrl.get('MimeType')), }) if Stream.get('HasSlideContent', False): images = player_options['PlayerLayoutOptions']['Images'] stream_formats.append(self.__extract_slides( stream_id=stream_id, snum=snum, Stream=Stream, duration=presentation.get('Duration'), images=images, )) # disprefer 'secondary' streams if stream_type != 0: for fmt in stream_formats: fmt['quality'] = -10 thumbnail_url = Stream.get('ThumbnailUrl') if thumbnail_url: thumbnails.append({ 'id': '%s-%u' % (stream_id, snum), 'url': urljoin(redirect_url, thumbnail_url), 'preference': -1 if stream_type != 0 else 0, }) formats.extend(stream_formats) self._sort_formats(formats) # XXX: Presentation['Presenters'] # XXX: Presentation['Transcript'] return { 'id': resource_id, 'title': title, 'description': presentation.get('Description'), 'duration': float_or_none(presentation.get('Duration'), 1000), 'timestamp': float_or_none(presentation.get('UnixTime'), 1000), 'formats': formats, 'thumbnails': thumbnails, } class MediasiteCatalogIE(InfoExtractor): _VALID_URL = r'''(?xi) (?P<url>https?://[^/]+/Mediasite) /Catalog/Full/ (?P<catalog_id>{0}) (?: /(?P<current_folder_id>{0}) /(?P<root_dynamic_folder_id>{0}) )? '''.format(_ID_RE) _TESTS = [{ 'url': 'http://events7.mediasite.com/Mediasite/Catalog/Full/631f9e48530d454381549f955d08c75e21', 'info_dict': { 'id': '631f9e48530d454381549f955d08c75e21', 'title': 'WCET Summit: Adaptive Learning in Higher Ed: Improving Outcomes Dynamically', }, 'playlist_count': 6, 'expected_warnings': ['is not a supported codec'], }, { # with CurrentFolderId and RootDynamicFolderId 'url': 'https://medaudio.medicine.iu.edu/Mediasite/Catalog/Full/9518c4a6c5cf4993b21cbd53e828a92521/97a9db45f7ab47428c77cd2ed74bb98f14/9518c4a6c5cf4993b21cbd53e828a92521', 'info_dict': { 'id': '9518c4a6c5cf4993b21cbd53e828a92521', 'title': 'IUSM Family and Friends Sessions', }, 'playlist_count': 2, }, { 'url': 'http://uipsyc.mediasite.com/mediasite/Catalog/Full/d5d79287c75243c58c50fef50174ec1b21', 'only_matching': True, }, { # no AntiForgeryToken 'url': 'https://live.libraries.psu.edu/Mediasite/Catalog/Full/8376d4b24dd1457ea3bfe4cf9163feda21', 'only_matching': True, }, { 'url': 'https://medaudio.medicine.iu.edu/Mediasite/Catalog/Full/9518c4a6c5cf4993b21cbd53e828a92521/97a9db45f7ab47428c77cd2ed74bb98f14/9518c4a6c5cf4993b21cbd53e828a92521', 'only_matching': True, }, { # dashed id 'url': 'http://events7.mediasite.com/Mediasite/Catalog/Full/631f9e48-530d-4543-8154-9f955d08c75e', 'only_matching': True, }] def _real_extract(self, url): mobj = self._match_valid_url(url) mediasite_url = mobj.group('url') catalog_id = mobj.group('catalog_id') current_folder_id = mobj.group('current_folder_id') or catalog_id root_dynamic_folder_id = mobj.group('root_dynamic_folder_id') webpage = self._download_webpage(url, catalog_id) # AntiForgeryToken is optional (e.g. [1]) # 1. https://live.libraries.psu.edu/Mediasite/Catalog/Full/8376d4b24dd1457ea3bfe4cf9163feda21 anti_forgery_token = self._search_regex( r'AntiForgeryToken\s*:\s*(["\'])(?P<value>(?:(?!\1).)+)\1', webpage, 'anti forgery token', default=None, group='value') if anti_forgery_token: anti_forgery_header = self._search_regex( r'AntiForgeryHeaderName\s*:\s*(["\'])(?P<value>(?:(?!\1).)+)\1', webpage, 'anti forgery header name', default='X-SOFO-AntiForgeryHeader', group='value') data = { 'IsViewPage': True, 'IsNewFolder': True, 'AuthTicket': None, 'CatalogId': catalog_id, 'CurrentFolderId': current_folder_id, 'RootDynamicFolderId': root_dynamic_folder_id, 'ItemsPerPage': 1000, 'PageIndex': 0, 'PermissionMask': 'Execute', 'CatalogSearchType': 'SearchInFolder', 'SortBy': 'Date', 'SortDirection': 'Descending', 'StartDate': None, 'EndDate': None, 'StatusFilterList': None, 'PreviewKey': None, 'Tags': [], } headers = { 'Content-Type': 'application/json; charset=UTF-8', 'Referer': url, 'X-Requested-With': 'XMLHttpRequest', } if anti_forgery_token: headers[anti_forgery_header] = anti_forgery_token catalog = self._download_json( '%s/Catalog/Data/GetPresentationsForFolder' % mediasite_url, catalog_id, data=json.dumps(data).encode(), headers=headers) entries = [] for video in catalog['PresentationDetailsList']: if not isinstance(video, dict): continue video_id = str_or_none(video.get('Id')) if not video_id: continue entries.append(self.url_result( '%s/Play/%s' % (mediasite_url, video_id), ie=MediasiteIE.ie_key(), video_id=video_id)) title = try_get( catalog, lambda x: x['CurrentFolder']['Name'], compat_str) return self.playlist_result(entries, catalog_id, title,) class MediasiteNamedCatalogIE(InfoExtractor): _VALID_URL = r'(?xi)(?P<url>https?://[^/]+/Mediasite)/Catalog/catalogs/(?P<catalog_name>[^/?#&]+)' _TESTS = [{ 'url': 'https://msite.misis.ru/Mediasite/Catalog/catalogs/2016-industrial-management-skriabin-o-o', 'only_matching': True, }] def _real_extract(self, url): mobj = self._match_valid_url(url) mediasite_url = mobj.group('url') catalog_name = mobj.group('catalog_name') webpage = self._download_webpage(url, catalog_name) catalog_id = self._search_regex( r'CatalogId\s*:\s*["\'](%s)' % _ID_RE, webpage, 'catalog id') return self.url_result( '%s/Catalog/Full/%s' % (mediasite_url, catalog_id), ie=MediasiteCatalogIE.ie_key(), video_id=catalog_id)
39.913876
229
0.542136
ace86c5cf4cab35c1e3c9a4859daf1e10e027a1f
1,003
py
Python
test/adjust.py
shawcx/pysdl2
a2222e549dc47a02ebf52aa8331ee5bf1911f739
[ "MIT" ]
null
null
null
test/adjust.py
shawcx/pysdl2
a2222e549dc47a02ebf52aa8331ee5bf1911f739
[ "MIT" ]
null
null
null
test/adjust.py
shawcx/pysdl2
a2222e549dc47a02ebf52aa8331ee5bf1911f739
[ "MIT" ]
null
null
null
#!/usr/bin/python3 # For LCD monitors using a VGA connection run this program then "auto-adjust" the monitor import SDL2 # Initialize SDL2 SDL2.Init(SDL2.INIT_VIDEO) numberOfDisplays = SDL2.GetNumVideoDisplays() windows = [] for i in range(numberOfDisplays): x,y,w,h = SDL2.GetDisplayBounds(i) window = SDL2.Window("Adjust", size=(w,h), position=(x,y), flags=SDL2.WINDOW_FULLSCREEN) windows.append((window, w, h)) # Hide the cursor SDL2.ShowCursor(SDL2.DISABLE) white = b'\xff\xff\xff\x00' black = b'\x00\x00\x00\x00' for window,w,h in windows: surface = window.GetWindowSurface() surface.LockSurface() surface.pixels = ((white + black) * int(w/2) + (black + white) * int(w/2)) * int(h/2) surface.UnlockSurface() window.UpdateWindowSurface() while True: event = SDL2.WaitEvent() if event: if SDL2.QUIT == event[0]: break if SDL2.KEYUP == event[0]: break # Show the cursor SDL2.ShowCursor(SDL2.ENABLE) SDL2.Quit()
23.880952
92
0.666999
ace86ce27a00ae0acadf24ba315253076a3b4b50
18
py
Python
projects/sacremoses/test.py
fleimgruber/python
2e735762c73651cffc027ca850b2a58d87d54b49
[ "Unlicense" ]
25
2021-10-30T19:54:59.000Z
2022-03-29T06:11:02.000Z
projects/sacremoses/test.py
fleimgruber/python
2e735762c73651cffc027ca850b2a58d87d54b49
[ "Unlicense" ]
21
2021-10-19T01:09:38.000Z
2022-03-24T16:08:53.000Z
projects/sacremoses/test.py
fleimgruber/python
2e735762c73651cffc027ca850b2a58d87d54b49
[ "Unlicense" ]
3
2022-01-25T20:25:13.000Z
2022-03-08T02:58:50.000Z
import sacremoses
9
17
0.888889
ace86d594c0fdbb6df71a55036186435b6600344
641
py
Python
anillo/http/request.py
niwinz/anillo
50d125be369ac16b37a892ac8b95f98aa1500ea0
[ "BSD-2-Clause" ]
14
2015-03-02T17:49:45.000Z
2021-05-04T16:11:48.000Z
anillo/http/request.py
niwinz/anillo
50d125be369ac16b37a892ac8b95f98aa1500ea0
[ "BSD-2-Clause" ]
14
2015-03-03T09:52:17.000Z
2017-02-15T08:55:58.000Z
anillo/http/request.py
niwinz/anillo
50d125be369ac16b37a892ac8b95f98aa1500ea0
[ "BSD-2-Clause" ]
8
2015-03-03T09:02:51.000Z
2019-02-03T04:19:02.000Z
class Request(dict): def __init__(self, server_port=None, server_name=None, remote_addr=None, uri=None, query_string=None, script_name=None, scheme=None, method=None, headers={}, body=None): super().__init__({ "server_port": server_port, "server_name": server_name, "remote_addr": remote_addr, "uri": uri, "script_name": script_name, "query_string": query_string, "scheme": scheme, "method": method, "headers": headers, "body": body, }) self.__dict__ = self
33.736842
76
0.533541
ace86ea508e1b1309d6427c0ba6935536681c0d0
675
py
Python
venv/bin/rst2s5.py
brendanbowidas/python-slackbot
a285130f081f37f590bb878509604a694f8e4077
[ "MIT" ]
null
null
null
venv/bin/rst2s5.py
brendanbowidas/python-slackbot
a285130f081f37f590bb878509604a694f8e4077
[ "MIT" ]
null
null
null
venv/bin/rst2s5.py
brendanbowidas/python-slackbot
a285130f081f37f590bb878509604a694f8e4077
[ "MIT" ]
null
null
null
#!/Users/brendan/Desktop/python-slackbot/venv/bin/python # $Id: rst2s5.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: Chris Liechti <cliechti@gmx.net> # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing HTML slides using the S5 template system. """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates S5 (X)HTML slideshow documents from standalone ' 'reStructuredText sources. ' + default_description) publish_cmdline(writer_name='s5', description=description)
27
74
0.745185
ace86f4ba3b2401c9d445096a7efd326b9080d1d
3,951
py
Python
timesofindia-crawler/scrap_links.py
project-anuvaad/anuvaad-corpus-tools
7624b48bc32eda6cf2efe126e28ad41a9763fe10
[ "MIT" ]
6
2021-03-17T10:25:44.000Z
2022-03-10T11:28:51.000Z
timesofindia-crawler/scrap_links.py
project-anuvaad/anuvaad-corpus-tools
7624b48bc32eda6cf2efe126e28ad41a9763fe10
[ "MIT" ]
null
null
null
timesofindia-crawler/scrap_links.py
project-anuvaad/anuvaad-corpus-tools
7624b48bc32eda6cf2efe126e28ad41a9763fe10
[ "MIT" ]
7
2020-12-17T07:23:29.000Z
2021-12-01T14:35:28.000Z
import requests import time import sys import os import pandas as pd from bs4 import BeautifulSoup import bs4 import copy from argparse import ArgumentParser def tags(lang): if lang == "en": return ["ga-headlines","Normal","_23498","_1Y-96","_3p5Tz img_cptn","_2ZigF id-r-highlights","_3YYSt clearfix"] else: return ["headline","articleBody","caption text_ellipsis","section tpstory_title","description","section tpstory_title"] def scraper(month,year,lang_code,inp_dir,save_dir,count,log,stopcount): list_c=list() articles_data = pd.read_csv(str(inp_dir),encoding='utf-16-le') if stopcount!=None : print("total no of links to be scraped - "+str(stopcount-count)+" from-"+str(count)+" to-"+str(stopcount)) else : print("total no of links to be scraped - "+str(int(articles_data.shape[0])-count)+" from-"+str(count)+" to-"+str(int(articles_data.shape[0])-1)) start_time = time.time() for link in articles_data['Link'][count:stopcount]: #print(link) try: markup_string = requests.get(link, stream=True).content soup = BeautifulSoup(markup_string, "html.parser") head=[] try: head.extend(soup.findAll(['arttitle'])) #Headline except: pass for i in tags(lang_code): try: if i == "headline" or i == "articleBody" or i == "description" : head.extend(soup.findAll(attrs={"itemprop":i})) head.extend(soup.findAll(class_=i)) except: pass head=list(filter(None,head)) if not os.path.exists(str(save_dir)): os.makedirs(str(save_dir)) with open(os.path.join(str(save_dir), f"TOI-{lang_code}-{month[:3]}-{year}-{count}.txt"), mode="w", encoding="utf-16") as file_w: for text in range(len(head)): try: try: if " ".join(head[text]['class']) == "_2ZigF id-r-highlights": try: file_w.write(head[text].get_text("\n",strip=True) + "\r\n") except: print("->",file_w.write(head[text].text.strip() + "\r\n")) else: file_w.write(head[text].text.strip() + "\r\n") except: file_w.write(head[text].text.strip() + "\r\n") except: if log : print('---error-while-encoding-occured---') if log : print(f"TOI-{lang_code}-{month[:3]}-{year}-{count}.txt") count+=1 except: print(count,"----------",link) list_c.append(count) count+=1 print("Total error :",len(list_c)) if len(list_c)>0 : print("error counts are :",list_c) time_taken=time.time() - start_time print("Time Take - ",time_taken//60," minutes ",time_taken%60," seconds") return def main(): parser = ArgumentParser() parser.add_argument("--lang-code", help="Language Code - bn,hi,en", type=str, required=True) parser.add_argument("--year", help="Year in YYYY format", type=str, required=True) parser.add_argument("--month", help="Month ", type=str, required=True) parser.add_argument("--start-count", help="count to start from", type=int, default=0) parser.add_argument("--stop-count", help="count to start from", type=int, default=None) parser.add_argument("--log", help="will print log",action="store_true") parser.add_argument("--input-csv",help="csv file to be scraped",type=str ,default="") parser.add_argument("--output-dir", help="output directory", type=str, default="") lang_full = {'en':'english','gu':'gujarati','hi':'hindi','mr':'marathi','kn':'kannada','bn':'bengali','gu':'gujarati','ml':'malayalam','te':'telugu','ta':'tamil'} args = parser.parse_args() lang_code=args.lang_code year=args.year month=args.month count=args.start_count stopcount=args.stop_count inp_dir=args.input_csv save_dir=args.output_dir if len(inp_dir)==0 : inp_dir="article_list/"+str(year)+"/"+str(month)+" "+str(year)+"/"+f"TOI_{lang_full[lang_code]}_{month.lower()}_{year}.csv" if len(save_dir)==0 : save_dir="scraped_files/"+str(year)+"/"+str(month)+" "+str(year)+"/"+lang_full[lang_code] log=args.log scraper(month,year,lang_code,inp_dir,save_dir,count,log,stopcount) if __name__ == "__main__": main()
41.589474
163
0.672994
ace871680b4e005841b43a987256f0fea2d81117
405
py
Python
examples/audio.py
brentru/METROX-CircuitPython-1
66b5ebec2ca3d0e1cc2b3a382671d07239253f30
[ "MIT" ]
null
null
null
examples/audio.py
brentru/METROX-CircuitPython-1
66b5ebec2ca3d0e1cc2b3a382671d07239253f30
[ "MIT" ]
3
2018-03-21T15:15:57.000Z
2021-02-01T03:15:15.000Z
examples/audio.py
brentru/METROX-CircuitPython-1
66b5ebec2ca3d0e1cc2b3a382671d07239253f30
[ "MIT" ]
2
2020-12-07T13:42:14.000Z
2021-01-29T14:13:19.000Z
""" 'audio.py'. ================================================= alarm circuit with a FSR and a speaker requires: - CircuitPython_CharLCD Module """ import audioio import analogio import board f = open('siren.wav', 'rb') a = audioio.AudioOut(board.A0, f) fsr = analogio.AnalogIn(board.A2) threshold = 200 while True: if fsr.value < threshold: a.play(loop=True) else: a.pause()
17.608696
49
0.590123
ace872c35b11c6f39f570699ce6695cd3e5c645d
1,163
py
Python
setup.py
cilame/ii
ea364a8fab96066be7065749783be1224d1222e3
[ "MIT" ]
null
null
null
setup.py
cilame/ii
ea364a8fab96066be7065749783be1224d1222e3
[ "MIT" ]
null
null
null
setup.py
cilame/ii
ea364a8fab96066be7065749783be1224d1222e3
[ "MIT" ]
null
null
null
from setuptools import setup import ii setup( name = "ii", version = ii.__version__, keywords = "ii", author = "cilame", author_email = "opaquisrm@hotmail.com", license = "MIT", description = "my tools", classifiers = [ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Intended Audience :: Developers', ], packages = [ "ii", ], package_data ={ "ii":[ 'adb-tools.zip', 'Notepad++.zip', 'procexp32.zip', 'procexp64.zip', 'ollydbg.zip', 'tcc-0.9.27-win32-bin.zip', 'tcc-0.9.27-win64-bin.zip', 'upx-3.95-32.zip', 'upx-3.95-64.zip', 'winapi-full-for-0.9.27.zip', 'nasm-2.14.02-win32.zip', 'nasm-2.14.02-win64.zip', 'ProcessMonitor.zip', ] }, python_requires=">=3.5", entry_points={ 'console_scripts': [ 'ii = ii.main:execute', ], 'gui_scripts': [ 'igui = ii.main:gui', 'inote = ii.main:notepad', ] }, )
24.744681
49
0.467756
ace872f34619d2180694d42b5126f1a0dea0ae3f
286
py
Python
app/user/urls.py
shubhamksm/Recipe-App-API
7cd7d4db52ded95a27237d331487849e66d06f8c
[ "MIT" ]
null
null
null
app/user/urls.py
shubhamksm/Recipe-App-API
7cd7d4db52ded95a27237d331487849e66d06f8c
[ "MIT" ]
null
null
null
app/user/urls.py
shubhamksm/Recipe-App-API
7cd7d4db52ded95a27237d331487849e66d06f8c
[ "MIT" ]
null
null
null
from django.urls import path from user import views app_name = 'user' urlpatterns = [ path('create/', views.CreateUserView.as_view(), name='create'), path('token/', views.CreatTokenView.as_view(), name='token'), path('me/', views.ManageUserView.as_view(), name='me'), ]
22
67
0.678322
ace8730d0cc944a75595a12ec37d5ea04a501316
8,091
py
Python
visualizer(2020)/plot.py
farzan-dehbashi/RFID_touch
49716bad2bd2b94dc47fe4e70bb44baf5ce051cb
[ "MIT" ]
null
null
null
visualizer(2020)/plot.py
farzan-dehbashi/RFID_touch
49716bad2bd2b94dc47fe4e70bb44baf5ce051cb
[ "MIT" ]
null
null
null
visualizer(2020)/plot.py
farzan-dehbashi/RFID_touch
49716bad2bd2b94dc47fe4e70bb44baf5ce051cb
[ "MIT" ]
null
null
null
import matplotlib import pandas as pd pd.options.mode.chained_assignment = None # default='warn' import dominate from dominate.tags import * import sys import os import matplotlib.pyplot as plt from datetime import datetime from matplotlib.font_manager import FontProperties import cv2 import pathlib class Tag: # contains color and other necesities of the tag to be plotted def __init__(self, color, epc): self.color = color self.epc = epc def get_color(self): return self.color def get_epc(self): return self.epc def read_gestures(directory): # read all log files of the experiments gesture_sheets = [] with os.scandir(str(directory)) as gesture_directories: for gesture_directory in gesture_directories: if os.path.isdir(gesture_directory): sheet_name = str(directory)+"/"+str(gesture_directory.name)+"/"+str(gesture_directory.name)+".csv" column_names = ["EPCValue", "TimeStamp", "RunNum", "RSSI", "Reader", "Frequency", "Power", "Antenna"] #sets the names of columns sheet = pd.read_csv(sheet_name, names = column_names) sheet.name = str(gesture_directory.name) gesture_sheets.append(sheet) return gesture_sheets def read_tags(tags_file_name): #this method reads all tags in the instruction file and return a list of tags tags_instruction = pd.read_csv(str(tags_file_name)) #reads the instruction file tags = [] for index, row in tags_instruction.iterrows(): #adds tags to the tag list tag = Tag(row['COLOR'], row['EPCValue']) tags.append(tag) return tags #tags contains a list of all tags whose instructions was provided in the instructions.csv file def clear(log_file, valid_epcs): log_file = log_file.iloc[5:] #removes first 4 lines of each log file which contains reader machine's data ##################################### for i, row in log_file.iterrows(): if row['EPCValue'] not in valid_epcs: #removes the row if the tag is not present in the instructions.csv file log_file.drop(index = i, inplace = True) ##################################### drop unnecessary columns ##################################### return log_file def plot(log, valid_epcs, name, tags): # plots all the files in a single log file print(name) font = FontProperties() font.set_family('serif') font.set_name('Times') plt.yticks(fontname="Times", fontsize="15") plt.xticks(fontname="Times", fontsize="15") plt.legend(prop={'family': 'Times'}) for epc in valid_epcs: this_epc_traces = log.loc[log['EPCValue'] == str(epc)] #returns the specific epc that is required to plot if this_epc_traces.empty == False: times = this_epc_traces['TimeStamp'].tolist() RSSIs = this_epc_traces['RSSI'].tolist() start_time = datetime.fromtimestamp(float(times[0])) for i in range(0, len(times)): #converts lists of time stamps and rssis to int and float times[i] = float(times[i]) time_stamp = datetime.fromtimestamp(times[i]) times[i]= time_stamp - start_time # indicates each sample time to be sample timestamp - start time times[i] = float(times [i].total_seconds()) #convert the result to seconds RSSIs[i] = int(RSSIs[i]) ########problematic color color = "" for tag in tags: if tag.get_epc() == epc: color = tag.get_color() ##############problematic color #(color) plt.scatter(times, RSSIs, label= epc, marker='o', color= color ) #plot the graph plt.axis([-0.1, 10.1, -55, -41]) # should be removed plt.grid(b=True, which='major', color='#666666', linestyle=':') plt.ylabel('RSS (dBm)', fontfamily="Times", fontsize="18") plt.xlabel('Time (S)', fontfamily="Times", fontsize="18") plt.legend() plt.savefig('./rfid_logs/'+str(name)+"/"+str(name)+".png", dpi = 500) #saves the file into the directories of the log files plt.clf() def plot_graph(log_name, tags, unit, x_offset, y_offset): # this part of the code plots a dot on the raw graph provided #find the location [x, y] = log_name.split('_') x = int(x) * unit y = int(y) * unit ################################### img = cv2.imread('figure.png') red = [233, 66, 245] cv2.circle(img, (x_offset + x, y_offset + y), (10), red, thickness=19, lineType=8, shift=0) cv2.imwrite('./rfid_logs/'+str(log_name)+"/figure.png", img) def make_html(directory, index): page_title = index doc = dominate.document(title=page_title) with doc.head: link(rel='stylesheet', href='style.css') doc.add(h1("Experiment name: "+str(page_title))) logs_list = [] #all of the logs are stored here with os.scandir(str(directory)) as gesture_directories: for gesture_directory in gesture_directories: if os.path.isdir(gesture_directory): logs_list.append(gesture_directory) #contains not sorted list of log file directories log_names = os.listdir(str(directory)) #sorts the list of the names of the contents of the log file directory ########## remove this later on sudu_names = [] for item in log_names: item = item.split("_") sudu_names.append(int(item[0])) sudu_names.sort() i = 0 while i <len(sudu_names) : sudu_names[i] = str(sudu_names[i])+"_0" i = i +1 #log_names.sort() log_names = sudu_names ########## remove this later on sorted_logs = [] #contains sorted order of all log files for log_name in log_names: #filter outs type of file which is not directory in the directory of log files if not ('.' in log_name): #if it is a direcotry for log in logs_list: if log.name == log_name: sorted_logs.append(log) break for log in sorted_logs: log_name = str(log.name) [x, y] = log_name.split('_') # to distinguish the location of touch point based on the naming of the file trial = div(cls='plot') #this is a trial div in the html page which represent an individual trial of experiment trial.add(h3("location of touch is at: x=" + str(x) + " y=" + str(y))) # headline of the experiment is added setup_graph = img(src="rfid_logs/" + str(log_name) + "/figure.png", figcaption="setup") # experiment setup is plotted trial.add(setup_graph) log_graph = img(src="rfid_logs/" + str(log_name) + "/" + str(log_name) + ".png", figcaption="RSS of the tags") # log file is plotted trial.add(log_graph) doc.add(trial) #print(str(doc)) f = open(str(page_title) + ".html", "w") f.write(str(doc)) f.close() if __name__ == "__main__": tags = read_tags (sys.argv[2]) log_files = [] log_files = read_gestures(sys.argv[1]) # read sheets from directories ########################################finds all valid epcs valid_epcs = [] for tag in tags: valid_epcs.append(tag.get_epc()) ######################################## for log_file in log_files: log_name = log_file.name #there is a bug that log file names mess up after clearing them log_file = clear(log_file, valid_epcs)#clear tags and just keep needed ones based on instructions.csv plot(log_file, valid_epcs, log_name, tags)#plots the log files unit = 55 # unit of pixels to change location of touch point based on the name of the files and this unit plot_graph(log_name, tags, unit, 160,265) #two last variables are the offset location of the finger ######################################## make_html(sys.argv[1], sys.argv[3]) # arg1= log files directory and arg 3 is the name of the file
37.632558
144
0.608825
ace87354f03a4cd6cd2bcb535a8f0bf45f0a80cc
10,098
py
Python
test/sagemaker_tests/tensorflow/tensorflow1_training/integration/sagemaker/test_mnist.py
leezu/deep-learning-containers
52591228240ad88d1eb39f419ade93d3ca5ec695
[ "Apache-2.0" ]
null
null
null
test/sagemaker_tests/tensorflow/tensorflow1_training/integration/sagemaker/test_mnist.py
leezu/deep-learning-containers
52591228240ad88d1eb39f419ade93d3ca5ec695
[ "Apache-2.0" ]
null
null
null
test/sagemaker_tests/tensorflow/tensorflow1_training/integration/sagemaker/test_mnist.py
leezu/deep-learning-containers
52591228240ad88d1eb39f419ade93d3ca5ec695
[ "Apache-2.0" ]
null
null
null
# Copyright 2017-2020 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. from __future__ import absolute_import import os import boto3 import pytest from sagemaker.tensorflow import TensorFlow from sagemaker.tuner import HyperparameterTuner, IntegerParameter from six.moves.urllib.parse import urlparse from test.test_utils import is_pr_context, SKIP_PR_REASON from ...integration.utils import processor, py_version, unique_name_from_base # noqa: F401 from .timeout import timeout @pytest.mark.skipif(is_pr_context(), reason=SKIP_PR_REASON) @pytest.mark.model("mnist") @pytest.mark.deploy_test def test_mnist(sagemaker_session, ecr_image, instance_type, framework_version): resource_path = os.path.join(os.path.dirname(__file__), '..', '..', 'resources') script = os.path.join(resource_path, 'mnist', 'mnist.py') estimator = TensorFlow(entry_point=script, role='SageMakerRole', train_instance_type=instance_type, train_instance_count=1, sagemaker_session=sagemaker_session, image_name=ecr_image, framework_version=framework_version, script_mode=True) inputs = estimator.sagemaker_session.upload_data( path=os.path.join(resource_path, 'mnist', 'data'), key_prefix='scriptmode/mnist') estimator.fit(inputs, job_name=unique_name_from_base('test-sagemaker-mnist')) _assert_s3_file_exists(sagemaker_session.boto_region_name, estimator.model_data) @pytest.mark.skipif(is_pr_context(), reason=SKIP_PR_REASON) @pytest.mark.model("mnist") @pytest.mark.multinode("multinode(2)") @pytest.mark.integration("no parameter server") def test_distributed_mnist_no_ps(sagemaker_session, ecr_image, instance_type, framework_version): resource_path = os.path.join(os.path.dirname(__file__), '..', '..', 'resources') script = os.path.join(resource_path, 'mnist', 'mnist.py') estimator = TensorFlow(entry_point=script, role='SageMakerRole', train_instance_count=2, train_instance_type=instance_type, sagemaker_session=sagemaker_session, image_name=ecr_image, framework_version=framework_version, script_mode=True) inputs = estimator.sagemaker_session.upload_data( path=os.path.join(resource_path, 'mnist', 'data'), key_prefix='scriptmode/mnist') estimator.fit(inputs, job_name=unique_name_from_base('test-tf-sm-distributed-mnist')) _assert_s3_file_exists(sagemaker_session.boto_region_name, estimator.model_data) @pytest.mark.model("mnist") @pytest.mark.multinode("multinode(2)") @pytest.mark.integration("parameter server") def test_distributed_mnist_ps(sagemaker_session, ecr_image, instance_type, framework_version): resource_path = os.path.join(os.path.dirname(__file__), '..', '..', 'resources') script = os.path.join(resource_path, 'mnist', 'mnist_estimator.py') estimator = TensorFlow(entry_point=script, role='SageMakerRole', hyperparameters={'sagemaker_parameter_server_enabled': True}, train_instance_count=2, train_instance_type=instance_type, sagemaker_session=sagemaker_session, image_name=ecr_image, framework_version=framework_version, script_mode=True) inputs = estimator.sagemaker_session.upload_data( path=os.path.join(resource_path, 'mnist', 'data-distributed'), key_prefix='scriptmode/mnist-distributed') estimator.fit(inputs, job_name=unique_name_from_base('test-tf-sm-distributed-mnist')) _assert_checkpoint_exists(sagemaker_session.boto_region_name, estimator.model_dir, 0) _assert_s3_file_exists(sagemaker_session.boto_region_name, estimator.model_data) @pytest.mark.skipif(is_pr_context(), reason=SKIP_PR_REASON) @pytest.mark.model("mnist") @pytest.mark.integration("s3 plugin") def test_s3_plugin(sagemaker_session, ecr_image, instance_type, region, framework_version): resource_path = os.path.join(os.path.dirname(__file__), '..', '..', 'resources') script = os.path.join(resource_path, 'mnist', 'mnist_estimator.py') estimator = TensorFlow(entry_point=script, role='SageMakerRole', hyperparameters={ # Saving a checkpoint after every 5 steps to hammer the S3 plugin 'save-checkpoint-steps': 10, # Disable throttling for checkpoint and model saving 'throttle-secs': 0, # Without the patch training jobs would fail around 100th to # 150th step 'max-steps': 200, # Large batch size would result in a larger checkpoint file 'batch-size': 1024, # This makes the training job exporting model during training. # Stale model garbage collection will also be performed. 'export-model-during-training': True }, train_instance_count=1, train_instance_type=instance_type, sagemaker_session=sagemaker_session, image_name=ecr_image, framework_version=framework_version, script_mode=True) estimator.fit('s3://sagemaker-sample-data-{}/tensorflow/mnist'.format(region), job_name=unique_name_from_base('test-tf-sm-s3-mnist')) _assert_s3_file_exists(region, estimator.model_data) _assert_checkpoint_exists(region, estimator.model_dir, 200) @pytest.mark.skipif(is_pr_context(), reason=SKIP_PR_REASON) @pytest.mark.model("mnist") @pytest.mark.integration("hpo") def test_tuning(sagemaker_session, ecr_image, instance_type, framework_version): resource_path = os.path.join(os.path.dirname(__file__), '..', '..', 'resources') script = os.path.join(resource_path, 'mnist', 'mnist.py') estimator = TensorFlow(entry_point=script, role='SageMakerRole', train_instance_type=instance_type, train_instance_count=1, sagemaker_session=sagemaker_session, image_name=ecr_image, framework_version=framework_version, script_mode=True) hyperparameter_ranges = {'epochs': IntegerParameter(1, 2)} objective_metric_name = 'accuracy' metric_definitions = [{'Name': objective_metric_name, 'Regex': 'accuracy = ([0-9\\.]+)'}] tuner = HyperparameterTuner(estimator, objective_metric_name, hyperparameter_ranges, metric_definitions, max_jobs=2, max_parallel_jobs=2) with timeout(minutes=20): inputs = estimator.sagemaker_session.upload_data( path=os.path.join(resource_path, 'mnist', 'data'), key_prefix='scriptmode/mnist') tuning_job_name = unique_name_from_base('test-tf-sm-tuning', max_length=32) tuner.fit(inputs, job_name=tuning_job_name) tuner.wait() @pytest.mark.model("mnist") @pytest.mark.integration("smdebug") @pytest.mark.skip_py2_containers def test_tf1x_smdebug(sagemaker_session, ecr_image, instance_type, framework_version): resource_path = os.path.join(os.path.dirname(__file__), '..', '..', 'resources') script = os.path.join(resource_path, 'mnist', 'tf1x_mnist_smdebug.py') hyperparameters = {'smdebug_path': '/tmp/ml/output/tensors'} estimator = TensorFlow(entry_point=script, role='SageMakerRole', train_instance_type=instance_type, train_instance_count=1, sagemaker_session=sagemaker_session, image_name=ecr_image, framework_version=framework_version, script_mode=True, hyperparameters=hyperparameters) inputs = estimator.sagemaker_session.upload_data( path=os.path.join(resource_path, 'mnist', 'data'), key_prefix='scriptmode/mnist_smdebug') estimator.fit(inputs, job_name=unique_name_from_base('test-sagemaker-mnist-smdebug')) _assert_s3_file_exists(sagemaker_session.boto_region_name, estimator.model_data) def _assert_checkpoint_exists(region, model_dir, checkpoint_number): _assert_s3_file_exists(region, os.path.join(model_dir, 'graph.pbtxt')) _assert_s3_file_exists(region, os.path.join(model_dir, 'model.ckpt-{}.index'.format(checkpoint_number))) _assert_s3_file_exists(region, os.path.join(model_dir, 'model.ckpt-{}.meta'.format(checkpoint_number))) def _assert_s3_file_exists(region, s3_url): parsed_url = urlparse(s3_url) s3 = boto3.resource('s3', region_name=region) s3.Object(parsed_url.netloc, parsed_url.path.lstrip('/')).load()
50.49
100
0.63468
ace873f78a0e2d017a8a954b5f630d34b773d691
2,605
py
Python
phpBuilds/phpSupport.py
skylarkgit/sql2phpclass
a79e7f3cfda8cb41ba00e8cbba0de33e9be759d6
[ "MIT" ]
null
null
null
phpBuilds/phpSupport.py
skylarkgit/sql2phpclass
a79e7f3cfda8cb41ba00e8cbba0de33e9be759d6
[ "MIT" ]
null
null
null
phpBuilds/phpSupport.py
skylarkgit/sql2phpclass
a79e7f3cfda8cb41ba00e8cbba0de33e9be759d6
[ "MIT" ]
null
null
null
import sys sys.path.append("..") from phpBuilds.phpTemplates import * from phpBuilds.phpTools import * from dtfParser import * from sql.sqlTemplates import * def getValidate(var): return VALIDATE(THIS(var.alias),var.validType) def getSanitize(var): return SANITIZE(THIS(var.alias),var.validType) def getValidations(varlist): str="" for d in varlist.values(): cond=ISEQUAL(getValidate(d),"false") if (d.lenConstraint==True): cond+=" || "+ISEQUAL(lenCheck(d),"false") str+=IF(cond,INVALID(d.alias)) str+=THIS(d.alias)+"="+getSanitize(d) return str def lenCheck(var): return LENCHECK(THIS(var.alias),var.minLen,var.maxLen) def getArgsToLocal(varList): str="" for d in varList.values(): str+=(THIS(d.alias)+"="+VAR(d.alias)+";") return str+"\n" def localizeAliases(varList): str="" for d in varList.values(): str+=("if (isset($_POST['"+d.alias+"'])) $this->"+d.alias+"=$_POST['"+d.alias+"'];") str+=("else $this->"+d.alias+"=NULL;\n") return str def getBindings(paramList): bindings=""; for p in paramList.values(): bindings+=BIND(p.alias,"this->"+p.alias) return bindings def getDeclarations(tableSurface): varList=tableSurface.getVars(); return "".join("public "+VAR(x.alias)+";" for x in varList.values())+"\n"; def getArgs(varList): return ",".join(VAR(x.alias) for x in varList.values()) def getNulledArgs(varList): return ",".join(VAR(x.alias)+"=NULL" for x in varList.values()) def writePHP(fname,code): phpStr =PHP(code) phpFile =open(fname, "w") phpFile.write(phpStr) phpFile.close() finalPhp=beautify(fname) phpFile =open(fname, "w") phpFile.write(finalPhp) phpFile.close() def getVarDependency(varName,elsecase): return IF(ISSET(POST(varName)),VAR(varName)+"="+POST(varName)+";\n")+ELSE(elsecase) def getVarDependenciesToLocal(varList): code="" for v in varList.values(): code+=IF(ISSET(POST(v.alias)),THIS(v.alias)+"="+POST(v.alias)+";\n")+ELSE(INVALIDRESPONSE(VAR('res'),v.alias)+ECHO(GETRESPONSE(VAR('res')))+DIE()) return code def APICALLS(type,tableSurface): tableName=tableSurface.alias keys=tableSurface.getKeys() return apiCallsTemplates[type].format(tableName=tableName,vars=getArgs(keys)) def getAPIcase(type,tableSurface): tableName=tableSurface.alias return CASE(tableName,APICALLS(type,tableSurface)) def getTransactionBody(db,var,code): finalcode=VAR(db)+"="+CALL('createConnection','') finalcode+=BEGINTRANSACTION(VAR(db)) finalcode+=code finalcode+=IF(ISEQUAL(MEMBER(VAR(var),'status'),'"OK"'),COMMIT(VAR(db))) finalcode+=ELSE(ROLLBACK(VAR(db))) finalcode+=ECHO(GETRESPONSE(VAR(var))) return finalcode
28.315217
148
0.711708
ace874b16b4332e58fe68083ab9cc88c58cd18b7
2,123
py
Python
viking/domain/seedwork/abstract_repository.py
JohnnyIrvin/hungry-task
92094c5f974bc369f1cf32faa5c06b244b19ca70
[ "MIT" ]
null
null
null
viking/domain/seedwork/abstract_repository.py
JohnnyIrvin/hungry-task
92094c5f974bc369f1cf32faa5c06b244b19ca70
[ "MIT" ]
null
null
null
viking/domain/seedwork/abstract_repository.py
JohnnyIrvin/hungry-task
92094c5f974bc369f1cf32faa5c06b244b19ca70
[ "MIT" ]
null
null
null
# Copyright (c) 2021 Johnathan P. Irvin # # 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. from abc import ABC, abstractmethod from typing import List from viking.domain.seedwork.entity import Entity class AbstractRepository(ABC): @abstractmethod def add(self, entity: Entity): """ Add an entity to the repository. Args: entity (Entity): The entity to add. """ @abstractmethod def get(self, reference) -> Entity: """ Get an entity from the repository. Args: reference: The reference of the entity to get. Returns: Entity: The entity. """ @abstractmethod def remove(self, entity: Entity) -> Entity: """ Remove an entity from the repository. Args: entity (Entity): The entity to remove. Returns: Entity: The entity. """ @abstractmethod def list(self) -> List[Entity]: """ List all entities in the repository. Returns: list: The list of entities. """
30.768116
72
0.668394
ace874b8b4123d1d691409bbc83ab13c950be950
1,199
py
Python
app/dashboard/views/recovery_code.py
fareszr/app
1f3bc693eccb307234e53653f6fa2cb25ddc0647
[ "MIT" ]
null
null
null
app/dashboard/views/recovery_code.py
fareszr/app
1f3bc693eccb307234e53653f6fa2cb25ddc0647
[ "MIT" ]
null
null
null
app/dashboard/views/recovery_code.py
fareszr/app
1f3bc693eccb307234e53653f6fa2cb25ddc0647
[ "MIT" ]
null
null
null
from flask import render_template, flash, redirect, url_for, request from flask_login import login_required, current_user from app.dashboard.base import dashboard_bp from app.log import LOG from app.models import RecoveryCode @dashboard_bp.route("/recovery_code", methods=["GET", "POST"]) @login_required def recovery_code_route(): if not current_user.two_factor_authentication_enabled(): flash("you need to enable either TOTP or WebAuthn", "warning") return redirect(url_for("dashboard.index")) recovery_codes = RecoveryCode.filter_by(user_id=current_user.id).all() if request.method == "GET" and not recovery_codes: # user arrives at this page for the first time LOG.d("%s has no recovery keys, generate", current_user) RecoveryCode.generate(current_user) recovery_codes = RecoveryCode.filter_by(user_id=current_user.id).all() if request.method == "POST": RecoveryCode.generate(current_user) flash("New recovery codes generated", "success") return redirect(url_for("dashboard.recovery_code_route")) return render_template( "dashboard/recovery_code.html", recovery_codes=recovery_codes )
38.677419
78
0.735613
ace8752195482b22a6879e7a2957d4d8d1a57177
1,387
py
Python
flask-app/starterkit/tests/test_hashedassets.py
carrete/docker-flask-starterkit-mirror
0ec866cc32b6ccc5d8efd5b02de7dc5e911df103
[ "Unlicense" ]
null
null
null
flask-app/starterkit/tests/test_hashedassets.py
carrete/docker-flask-starterkit-mirror
0ec866cc32b6ccc5d8efd5b02de7dc5e911df103
[ "Unlicense" ]
2
2018-04-06T12:01:12.000Z
2019-12-21T23:34:06.000Z
flask-app/starterkit/tests/test_hashedassets.py
carrete/docker-flask-starterkit-mirror
0ec866cc32b6ccc5d8efd5b02de7dc5e911df103
[ "Unlicense" ]
null
null
null
# -*- coding: utf-8 -*- import os.path from tempfile import NamedTemporaryFile from flask import render_template from flask_script import Manager import pytest from starterkit.hashedassets import HashAssetsCommand, HashedAssetNotFoundError, HashedAssets from .helpers import with_tst_request_context def mktempfile(): with NamedTemporaryFile() as fd: name = fd.name return name @with_tst_request_context def test_hashed_assets(*args, **kwargs): test_app = kwargs["test_app"] HashedAssets(test_app) assert render_template("tests/starterkit/hashedassets/hashedassets.html") @pytest.mark.xfail(raises=HashedAssetNotFoundError) @with_tst_request_context def test_hashed_asset_not_found_error(*args, **kwargs): test_app = kwargs["test_app"] test_app.config["HASHEDASSETS_CATALOG"] = "" HashedAssets(test_app) assert render_template("tests/starterkit/hashedassets/hashedassets.html") @with_tst_request_context def test_hash_assets_command(*args, **kwargs): test_app = kwargs["test_app"] catalog_name = mktempfile() assert os.path.exists(catalog_name) is False test_app.config["HASHEDASSETS_CATALOG"] = catalog_name manager = Manager(test_app) manager.add_command("hashassets", HashAssetsCommand()) manager.handle("what-the-hell-is-this?", ["hashassets"]) assert os.path.exists(catalog_name) is True
26.169811
93
0.76496
ace8774745b60814bee095da7321dcbb758fe4d5
3,594
py
Python
image_processing.py
vulnguard/mp_gui
f15ecb9da17f828115947a8f37a022c8e2093622
[ "MIT" ]
null
null
null
image_processing.py
vulnguard/mp_gui
f15ecb9da17f828115947a8f37a022c8e2093622
[ "MIT" ]
null
null
null
image_processing.py
vulnguard/mp_gui
f15ecb9da17f828115947a8f37a022c8e2093622
[ "MIT" ]
null
null
null
import numpy as np import cv2 import os import sys import matplotlib.pyplot as plt # ================ Loading / Saving images ================ # Each of these should return the resepctive kernel def perwit_kx_kernal(): pass def perwit_ky_kernal(): pass def sobel_kx_kernal(): pass def sobel_ky_kernal(): pass def laplacian_kernal(): pass def gaussian_kernal(): pass # ================ Loading / Saving images ================ def load_image(image_path): # imports image path # returns what cv2.imread returns return np.zeros([100, 100, 3], dtype=np.uint8) def save_image(image, file_path): # imports an image (as defined by opencv) and a path which to save it to # returns nothing pass # ================ Accessors ================ def get_image_dimentions(image): # imports an image # returns rows, cols return 100, 100 # ================ Mutators - linear filtering ================ def apply_convolution(image, kernel): # Returns the comvoluted image pass def general_gaussian_filter(image, sigma_x = 5, sigma_y = None, size_x = 5, size_y = 5): # Returns the blurred image pass def apply_median_filter(image, kernel_size = 5): # Returns the blurred image pass # ================ Mutators - Transforms ================ def crop_image(image, x, y, width, height): # Returns the cropped image pass def rotate_image(image, angle_deg): # Returns the rotated image pass def resize_image(image, x_scale_factor, y_scale_factor): # Returns the resized image pass def apply_affine_transformation(image, starting_point, ending_point): # Returns the transformed image pass def apply_affine_pixel_transform(image, alpha, beta): # Returns the pixel - transformed image (ignore the weird name) # (this is y =ax + b) pass def normalize_histogram_bnw(image): # Returns the noramlized image pass def normalize_histogram_bgr(image): # Returns the noramlized image pass # ================ Mutators - Other ================ # Start pos, and end_pos and col are all tuples. (x, y) (r, g, b) def draw_rect_on_image(image, start_pos, end_pos, thickness = 3, colour = (0, 0, 0)): # Returns a COPY of the image with the rect drawn on it pass def inverse_bw(image): # Returns inversed image pass # ================ Mutators - Morphological opperations ================ def morph_dilate(image, structuring_element = None, size = 5): # Returns dilated image pass def morph_erode(image, structuring_element = None, size = 5): # Returns modified image pass def morph_open(image, structuring_element = None, size= 5): # Returns modified image pass def morph_close(image, structuring_element = None, size = 5): # Returns modified image pass def morph_gradiant(image, structuring_element = None, size = 5): # Returns modified image pass def morph_blackhat(image, structuring_element = None, size = 5): # Returns modified image pass # ================ Format Converters ================ def rgb_to_bgr(image): # Returns modified image pass def bgr_to_rgb(image): # Returns modified image pass # @Note the following functions expect input image to be in bgr format. def to_grayscale(image): # Returns modified image pass def to_hsv(image): # Returns modified image pass def to_luv(image): # Returns modified image pass def to_lab(image): # Returns modified image pass def to_yuv(image): # Returns modified image pass
22.322981
88
0.65025
ace87927d5aeff73115aa010072400f596319705
45,094
py
Python
guided_diffusion/gaussian_diffusion.py
xvdp/guided-diffusion
dd5122b00ab42f4d93b0c749d101415fccbb5bda
[ "MIT" ]
null
null
null
guided_diffusion/gaussian_diffusion.py
xvdp/guided-diffusion
dd5122b00ab42f4d93b0c749d101415fccbb5bda
[ "MIT" ]
null
null
null
guided_diffusion/gaussian_diffusion.py
xvdp/guided-diffusion
dd5122b00ab42f4d93b0c749d101415fccbb5bda
[ "MIT" ]
null
null
null
""" This code started out as a PyTorch port of Ho et al's diffusion models: https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py Docstrings have been added, as well as DDIM sampling and a new collection of beta schedules. """ import enum import math import numpy as np import torch as th from .nn import mean_flat from .losses import normal_kl, discretized_gaussian_log_likelihood from .debug_utils import logkwargs, logtensor, print_cond, save_image, _DEBUG # pylint: disable=no-member def get_named_beta_schedule(schedule_name, num_diffusion_timesteps): """ Get a pre-defined beta schedule for the given name. The beta schedule library consists of beta schedules which remain similar in the limit of num_diffusion_timesteps. Beta schedules may be added, but should not be removed or changed once they are committed to maintain backwards compatibility. """ if schedule_name == "linear": # Linear schedule from Ho et al, extended to work for any number of # diffusion steps. scale = 1000 / num_diffusion_timesteps beta_start = scale * 0.0001 beta_end = scale * 0.02 return np.linspace( beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64 ) elif schedule_name == "cosine": return betas_for_alpha_bar( num_diffusion_timesteps, lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2, ) else: raise NotImplementedError(f"unknown beta schedule: {schedule_name}") def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): """ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of (1-beta) over time from t = [0,1]. :param num_diffusion_timesteps: the number of betas to produce. :param alpha_bar: a lambda that takes an argument t from 0 to 1 and produces the cumulative product of (1-beta) up to that part of the diffusion process. :param max_beta: the maximum beta to use; use values lower than 1 to prevent singularities. """ betas = [] for i in range(num_diffusion_timesteps): t1 = i / num_diffusion_timesteps t2 = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta)) return np.array(betas) class ModelMeanType(enum.Enum): """ Which type of output the model predicts. """ PREVIOUS_X = enum.auto() # the model predicts x_{t-1} START_X = enum.auto() # the model predicts x_0 EPSILON = enum.auto() # the model predicts epsilon class ModelVarType(enum.Enum): """ What is used as the model's output variance. The LEARNED_RANGE option has been added to allow the model to predict values between FIXED_SMALL and FIXED_LARGE, making its job easier. """ LEARNED = enum.auto() FIXED_SMALL = enum.auto() FIXED_LARGE = enum.auto() LEARNED_RANGE = enum.auto() class LossType(enum.Enum): MSE = enum.auto() # use raw MSE loss (and KL when learning variances) RESCALED_MSE = ( enum.auto() ) # use raw MSE loss (with RESCALED_KL when learning variances) KL = enum.auto() # use the variational lower-bound RESCALED_KL = enum.auto() # like KL, but rescale to estimate the full VLB def is_vb(self): return self == LossType.KL or self == LossType.RESCALED_KL class GaussianDiffusion: """ Utilities for training and sampling diffusion models. Ported directly from here, and then adapted over time to further experimentation. https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py#L42 :param betas: a 1-D numpy array of betas for each diffusion timestep, starting at T and going to 1. :param model_mean_type: a ModelMeanType determining what the model outputs. :param model_var_type: a ModelVarType determining how variance is output. :param loss_type: a LossType determining the loss function to use. :param rescale_timesteps: if True, pass floating point timesteps into the model so that they are always scaled like in the original paper (0 to 1000). """ def __init__( self, *, betas, model_mean_type, model_var_type, loss_type, rescale_timesteps=False, ): self.model_mean_type = model_mean_type self.model_var_type = model_var_type self.loss_type = loss_type self.rescale_timesteps = rescale_timesteps # Use float64 for accuracy. betas = np.array(betas, dtype=np.float64) self.betas = betas assert len(betas.shape) == 1, "betas must be 1-D" assert (betas > 0).all() and (betas <= 1).all() self.num_timesteps = int(betas.shape[0]) alphas = 1.0 - betas self.alphas_cumprod = np.cumprod(alphas, axis=0) self.alphas_cumprod_prev = np.append(1.0, self.alphas_cumprod[:-1]) self.alphas_cumprod_next = np.append(self.alphas_cumprod[1:], 0.0) assert self.alphas_cumprod_prev.shape == (self.num_timesteps,) # calculations for diffusion q(x_t | x_{t-1}) and others self.sqrt_alphas_cumprod = np.sqrt(self.alphas_cumprod) self.sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - self.alphas_cumprod) self.log_one_minus_alphas_cumprod = np.log(1.0 - self.alphas_cumprod) self.sqrt_recip_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod) self.sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod - 1) # calculations for posterior q(x_{t-1} | x_t, x_0) self.posterior_variance = ( betas * (1.0 - self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod) ) # log calculation clipped because the posterior variance is 0 at the # beginning of the diffusion chain. self.posterior_log_variance_clipped = np.log( np.append(self.posterior_variance[1], self.posterior_variance[1:]) ) self.posterior_mean_coef1 = ( betas * np.sqrt(self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod) ) self.posterior_mean_coef2 = ( (1.0 - self.alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - self.alphas_cumprod) ) self.logonce = [] print_cond(f"GaussianDiffusion.__init__()") print_cond(f" model_mean_type {self.model_mean_type}") print_cond(f" model_var_type {self.model_var_type}") print_cond(f" loss_type {self.loss_type}") print_cond(f" rescale_timesteps {self.rescale_timesteps}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = ( _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start ) variance = _extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = _extract_into_tensor( self.log_one_minus_alphas_cumprod, t, x_start.shape ) print_cond(f" GaussianDiffusion.q_mean_variance(mean: {mean.shape}, variance: {variance.shape}, log_variance: {log_variance.shape})", cond=_DEBUG and "q_mean_variance" not in self.logonce) if "q_mean_variance" not in self.logonce: self.logonce.append('q_mean_variance') return mean, variance, log_variance def q_sample(self, x_start, t, noise=None): """ Diffuse the data for a given number of diffusion steps. In other words, sample from q(x_t | x_0). :param x_start: the initial data batch. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :param noise: if specified, the split-out normal noise. :return: A noisy version of x_start. """ if noise is None: noise = th.randn_like(x_start) assert noise.shape == x_start.shape print_cond(f" GaussianDiffusion.q_sample(noise: {noise.shape}, x_start: {x_start.shape}", cond=_DEBUG and "q_sample" not in self.logonce) if "q_sample" not in self.logonce: self.logonce.append('q_sample') return ( _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise ) def q_posterior_mean_variance(self, x_start, x_t, t): """ Compute the mean and variance of the diffusion posterior: q(x_{t-1} | x_t, x_0) Args x_t original noise x_start output of ModelMeanType.EPSILON: _predict_xstart_from_eps (x/√Πα_t - model(x)/√(Πα_t - 1)) # where x is last gaussian output ModelMeanType.START_X: model(x) μ = coef1 * x_start _ coef2 + noise var = β_t*Πα_t1/Πα_t """ assert x_start.shape == x_t.shape posterior_mean = ( _extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + _extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = _extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = _extract_into_tensor( self.posterior_log_variance_clipped, t, x_t.shape ) assert ( posterior_mean.shape[0] == posterior_variance.shape[0] == posterior_log_variance_clipped.shape[0] == x_start.shape[0] ) print_cond(f" GaussianDiffusion.q_posterior_mean_variance( posterior_mean:{logtensor(posterior_mean)}, posterior_variance: {logtensor(posterior_variance)}, posterior_log_variance_clipped: {logtensor(posterior_log_variance_clipped)}", cond=_DEBUG and "q_posterior_mean_variance" not in self.logonce) if"q_posterior_mean_variance" not in self.logonce: self.logonce.append('q_posterior_mean_variance') return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance( self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None ): """ Apply the model to get p(x_{t-1} | x_t), as well as a prediction of the initial x, x_0. :param model: the model, which takes a signal and a batch of timesteps as input. :param x: the [N x C x ...] tensor at time t. :param t: a 1-D Tensor of timesteps. :param clip_denoised: if True, clip the denoised signal into [-1, 1]. :param denoised_fn: if not None, a function which applies to the x_start prediction before it is used to sample. Applies before clip_denoised. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :return: a dict with the following keys: - 'mean': the model mean output. - 'variance': the model variance output. - 'log_variance': the log of 'variance'. - 'pred_xstart': the prediction for x_0. """ if model_kwargs is None: model_kwargs = {} B, C = x.shape[:2] assert t.shape == (B,) _cond = _DEBUG and ("p_mean_variance" not in self.logonce or t.sum().item() == 0 or t.sum().item() == B or t.sum().item() == B*100) print_cond("\n",t.sum().item(), _cond, "p_mean_variance" in self.logonce, self.logonce, cond=_cond) print_cond(f"PRE.GaussianDiffusion.p_mean_variance(x: {logtensor(x)}, kwargs:{logkwargs(model_kwargs)}", cond=_cond) model_output = model(x, self._scale_timesteps(t), **model_kwargs) print_cond(f"POST.GaussianDiffusion.p_mean_variance(model_output: {logtensor(model_output)}, model {model.__class__.__name__})", cond=_cond) img = [] names = [] if self.model_var_type in [ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE]: assert model_output.shape == (B, C * 2, *x.shape[2:]) model_output, model_var_values = th.split(model_output, C, dim=1) if self.model_var_type == ModelVarType.LEARNED: model_log_variance = model_var_values model_variance = th.exp(model_log_variance) else: min_log = _extract_into_tensor( self.posterior_log_variance_clipped, t, x.shape ) max_log = _extract_into_tensor(np.log(self.betas), t, x.shape) # The model_var_values is [-1, 1] for [min_var, max_var]. frac = (model_var_values + 1) / 2 model_log_variance = frac * max_log + (1 - frac) * min_log model_variance = th.exp(model_log_variance) if _cond: img.append(model_output.cpu().clone().detach()) names.append(f"model_output: {img[-1].mean().item():.3f} std {img[-1].mean().item():.3f}") # img.append(model_var_values.cpu().clone().detach()) # names.append(f"model_var: {img[-1].mean().item():.3f} std {img[-1].mean().item():.3f}") # img.append(model_log_variance.cpu().clone().detach()) # names.append(f"log_var: {img[-1].mean().item():.3f} std {img[-1].mean().item():.3f}") img.append(model_variance.cpu().clone().detach()) names.append(f"var: {img[-1].mean().item():.3f} std {img[-1].mean().item():.3f}") else: model_variance, model_log_variance = { # for fixedlarge, we set the initial (log-)variance like so # to get a better decoder log likelihood. ModelVarType.FIXED_LARGE: ( np.append(self.posterior_variance[1], self.betas[1:]), np.log(np.append(self.posterior_variance[1], self.betas[1:])), ), ModelVarType.FIXED_SMALL: ( self.posterior_variance, self.posterior_log_variance_clipped, ), }[self.model_var_type] model_variance = _extract_into_tensor(model_variance, t, x.shape) model_log_variance = _extract_into_tensor(model_log_variance, t, x.shape) print_cond(f":VAR.GaussianDiffusion.p_mean_variance(model_var_type: {self.model_var_type},\n\tmodel_output {logtensor(model_output)} var {logtensor(model_variance)}, logvar {logtensor(model_log_variance)}", cond=_cond) def process_xstart(x): if denoised_fn is not None: print_cond(f"PRE.GaussianDiffusion.p_mean_variance.process_xstart(x: {logtensor(x)}", cond=_cond) x = denoised_fn(x) print_cond(f"POST.GaussianDiffusion.p_mean_variance.process_xstart(x: {logtensor(x)}", cond=_cond) if clip_denoised: return x.clamp(-1, 1) return x if self.model_mean_type == ModelMeanType.PREVIOUS_X: print_cond(f" MODELMEAN: {self.model_mean_type}", cond=_DEBUG and "p_mean_variance_previousX" not in self.logonce) pred_xstart = process_xstart( self._predict_xstart_from_xprev(x_t=x, t=t, xprev=model_output) ) model_mean = model_output print_cond(f" MODELMEAN:{self.model_mean_type}, mean: {logtensor(model_mean)}", cond=_DEBUG and ("p_mean_variance_previousX" not in self.logonce or t.sum().item() == 0)) if"p_mean_variance_previousX" not in self.logonce: self.logonce.append("p_mean_variance_previousX") elif self.model_mean_type in [ModelMeanType.START_X, ModelMeanType.EPSILON]: print_cond(f" MODELMEAN: {self.model_mean_type}", cond=_DEBUG and ("p_mean_variance_startX" not in self.logonce or t.sum().item() == 0)) if self.model_mean_type == ModelMeanType.START_X: pred_xstart = process_xstart(model_output) else: pred_xstart = process_xstart( self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output) ) model_mean, _, _ = self.q_posterior_mean_variance( x_start=pred_xstart, x_t=x, t=t ) if _cond: img.append(pred_xstart.cpu().clone().detach()) names.append(f"pred_xstart=noise_ish-model_ish: {img[-1].mean().item():.3f} std {img[-1].mean().item():.3f}") img.append(model_mean.cpu().clone().detach()) names.append(f"mmean=pred_xstart+var_noise_ish: {img[-1].mean().item():.3f} std {img[-1].mean().item():.3f}") print_cond(f" MODELMEAN:{self.model_mean_type}, mean: {logtensor(model_mean)}", cond=_DEBUG and ("p_mean_variance_startX" not in self.logonce or t.sum().item() == 0)) if"p_mean_variance_startX" not in self.logonce: self.logonce.append("p_mean_variance_startX") else: raise NotImplementedError(self.model_mean_type) assert ( model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape ) print_cond(f" OUT; GaussianDiffusion.p_mean_variance(mean, var, logvar, pred_xstart: {logtensor(pred_xstart)}", cond=_cond) if"p_mean_variance" not in self.logonce: self.logonce.append('p_mean_variance') if _cond: save_image(*img, name="gaussian_fwd", i= int(t.sum().item()//B), names=names) return { "mean": model_mean, "variance": model_variance, "log_variance": model_log_variance, "pred_xstart": pred_xstart, } def _predict_xstart_from_eps(self, x_t, t, eps): """ Args x_t noise_0 eps new_x: eps = model(x_previous) out = x_t/√Πα_t - eps/√(Πα_t - 1) """ assert x_t.shape == eps.shape print_cond(f" GaussianDiffusion._predict_xstart_from_eps(x_t: {logtensor(x_t)}, eps: {logtensor(eps)}", cond=_DEBUG and ("_predict_xstart_from_eps" not in self.logonce or t.sum().item() == 0)) if"_predict_xstart_from_eps" not in self.logonce: self.logonce.append('_predict_xstart_from_eps') return ( _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps ) def _predict_xstart_from_xprev(self, x_t, t, xprev): """ Args x_t: original noise_0 xprev: model() out = (model(x)- noise_0 * coef2)/coef1 """ assert x_t.shape == xprev.shape print_cond(f" GaussianDiffusion._predict_xstart_from_xprev(x_t: {logtensor(x_t)}, xprev: {logtensor(xprev)}", cond=_DEBUG and ("_predict_xstart_from_xprev" not in self.logonce or t.sum().item() == 0)) if"_predict_xstart_from_xprev" not in self.logonce: self.logonce.append('_predict_xstart_from_xprev') return ( # (xprev - coef2*x_t) / coef1 _extract_into_tensor(1.0 / self.posterior_mean_coef1, t, x_t.shape) * xprev - _extract_into_tensor( self.posterior_mean_coef2 / self.posterior_mean_coef1, t, x_t.shape ) * x_t ) def _predict_eps_from_xstart(self, x_t, t, pred_xstart): print_cond(f" GaussianDiffusion._predict_eps_from_xstart(x_t: {logtensor(x_t)}, pred_xstart: {logtensor(pred_xstart)}", cond=_DEBUG and ("_predict_eps_from_xstart" not in self.logonce or t.sum().item() == 0)) if"_predict_eps_from_xstart" not in self.logonce: self.logonce.append('_predict_eps_from_xstart') return ( _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) def _scale_timesteps(self, t): if self.rescale_timesteps: return t.float() * (1000.0 / self.num_timesteps) return t def condition_mean(self, cond_fn, p_mean_var, x, t, model_kwargs=None): """ Compute the mean for the previous step, given a function cond_fn that computes the gradient of a conditional log probability with respect to x. In particular, cond_fn computes grad(log(p(y|x))), and we want to condition on y. This uses the conditioning strategy from Sohl-Dickstein et al. (2015). """ print_cond(f" GaussianDiffusion.condition_mean(x: {logtensor(x)}, cond_fn: {cond_fn}, t: {t} model_kwargs: {logkwargs(model_kwargs)}", cond=_DEBUG and ("condition_mean" not in self.logonce or t.sum().item() == 0)) gradient = cond_fn(x, self._scale_timesteps(t), **model_kwargs) new_mean = ( p_mean_var["mean"].float() + p_mean_var["variance"] * gradient.float() ) print_cond(f" 2.GaussianDiffusion.condition_mean(new_mean: {logtensor(new_mean)}", cond=_DEBUG and ("condition_mean" not in self.logonce or t.sum().item() == 0)) if"condition_mean" not in self.logonce: self.logonce.append('condition_mean') return new_mean def condition_score(self, cond_fn, p_mean_var, x, t, model_kwargs=None): """ Compute what the p_mean_variance output would have been, should the model's score function be conditioned by cond_fn. See condition_mean() for details on cond_fn. Unlike condition_mean(), this instead uses the conditioning strategy from Song et al (2020). """ alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape) eps = self._predict_eps_from_xstart(x, t, p_mean_var["pred_xstart"]) eps = eps - (1 - alpha_bar).sqrt() * cond_fn( x, self._scale_timesteps(t), **model_kwargs ) out = p_mean_var.copy() out["pred_xstart"] = self._predict_xstart_from_eps(x, t, eps) out["mean"], _, _ = self.q_posterior_mean_variance( x_start=out["pred_xstart"], x_t=x, t=t ) print_cond(f" GaussianDiffusion.condition_score(x: {logtensor(x)}, cond_fn: {cond_fn}, p_mean_var: {logtensor(p_mean_var)} out: {logtensor(out)}", cond=_DEBUG and ("condition_score" not in self.logonce or t.sum().item() == 0)) if"condition_score" not in self.logonce: self.logonce.append('condition_score') return out def p_sample( self, model, x, t, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, ): """ Sample x_{t-1} from the model at the given timestep. :param model: the model to sample from. :param x: the current tensor at x_{t-1}. :param t: the value of t, starting at 0 for the first diffusion step. :param clip_denoised: if True, clip the x_start prediction to [-1, 1]. :param denoised_fn: if not None, a function which applies to the x_start prediction before it is used to sample. :param cond_fn: if not None, this is a gradient function that acts similarly to the model. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :return: a dict containing the following keys: - 'sample': a random sample from the model. - 'pred_xstart': a prediction of x_0. """ print_cond(f"PRE.GaussianDiffusion.p_sample(x: {logtensor(x)}, cond_fn: {cond_fn}, t: {t}, model: {model.__class__.__name__} model_kwargs: {logkwargs(model_kwargs)}", cond=_DEBUG and "p_sample" not in self.logonce) out = self.p_mean_variance( model, x, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, model_kwargs=model_kwargs, ) noise = th.randn_like(x) nonzero_mask = ( (t != 0).float().view(-1, *([1] * (len(x.shape) - 1))) ) # no noise when t == 0 if cond_fn is not None: out["mean"] = self.condition_mean( cond_fn, out, x, t, model_kwargs=model_kwargs ) sample = out["mean"] + nonzero_mask * th.exp(0.5 * out["log_variance"]) * noise print_cond(f"POST.GaussianDiffusion.p_sample(x: {logtensor(x)}, cond_fn: {cond_fn}, sample: {logtensor(sample)} pred_xstart: {logtensor(out['pred_xstart'])}", cond=_DEBUG and "p_sample" not in self.logonce) if"p_sample" not in self.logonce: self.logonce.append('p_sample') return {"sample": sample, "pred_xstart": out["pred_xstart"]} def p_sample_loop( self, model, shape, noise=None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, device=None, progress=False, ): """ Generate samples from the model. :param model: the model module. :param shape: the shape of the samples, (N, C, H, W). :param noise: if specified, the noise from the encoder to sample. Should be of the same shape as `shape`. :param clip_denoised: if True, clip x_start predictions to [-1, 1]. :param denoised_fn: if not None, a function which applies to the x_start prediction before it is used to sample. :param cond_fn: if not None, this is a gradient function that acts similarly to the model. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :param device: if specified, the device to create the samples on. If not specified, use a model parameter's device. :param progress: if True, show a tqdm progress bar. :return: a non-differentiable batch of samples. """ final = None for sample in self.p_sample_loop_progressive( model, shape, noise=noise, clip_denoised=clip_denoised, denoised_fn=denoised_fn, cond_fn=cond_fn, model_kwargs=model_kwargs, device=device, progress=progress, ): final = sample print_cond(f" GaussianDiffusion.p_sample_loop( final['sample']: {final['sample'].shape}", cond=_DEBUG and "p_sample_loop" not in self.logonce) if"p_sample_loop" not in self.logonce: self.logonce.append('p_sample_loop') return final["sample"] def p_sample_loop_progressive( self, model, shape, noise=None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, device=None, progress=False, ): """ Generate samples from the model and yield intermediate samples from each timestep of diffusion. Arguments are the same as p_sample_loop(). Returns a generator over dicts, where each dict is the return value of p_sample(). """ if device is None: device = next(model.parameters()).device assert isinstance(shape, (tuple, list)) if noise is not None: img = noise else: img = th.randn(*shape, device=device) indices = list(range(self.num_timesteps))[::-1] print_cond(f" GaussianDiffusion.p_sample_loop_progressive(indices: {len(indices)}", cond=_DEBUG and "p_sample_loop_progressive" not in self.logonce) if"p_sample_loop" not in self.logonce: self.logonce.append('p_sample_loop') if progress: # Lazy import so that we don't depend on tqdm. from tqdm.auto import tqdm indices = tqdm(indices) for i in indices: t = th.tensor([i] * shape[0], device=device) with th.no_grad(): out = self.p_sample( model, img, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, cond_fn=cond_fn, model_kwargs=model_kwargs, ) yield out img = out["sample"] def ddim_sample( self, model, x, t, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, eta=0.0, ): """ Sample x_{t-1} from the model using DDIM. Same usage as p_sample(). """ out = self.p_mean_variance( model, x, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, model_kwargs=model_kwargs, ) if cond_fn is not None: out = self.condition_score(cond_fn, out, x, t, model_kwargs=model_kwargs) # Usually our model outputs epsilon, but we re-derive it # in case we used x_start or x_prev prediction. eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"]) alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape) alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape) sigma = ( eta * th.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar)) * th.sqrt(1 - alpha_bar / alpha_bar_prev) ) # Equation 12. noise = th.randn_like(x) mean_pred = ( out["pred_xstart"] * th.sqrt(alpha_bar_prev) + th.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps ) nonzero_mask = ( (t != 0).float().view(-1, *([1] * (len(x.shape) - 1))) ) # no noise when t == 0 sample = mean_pred + nonzero_mask * sigma * noise print_cond(f" GaussianDiffusion.ddim_sample(sample: {sample.shape}, out['pred_xstart']:{out['pred_xstart'].shape}", cond=_DEBUG and "ddim_sample" not in self.logonce) if "ddim_sample" not in self.logonce: self.logonce.append('ddim_sample') return {"sample": sample, "pred_xstart": out["pred_xstart"]} def ddim_reverse_sample( self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None, eta=0.0, ): """ Sample x_{t+1} from the model using DDIM reverse ODE. """ assert eta == 0.0, "Reverse ODE only for deterministic path" out = self.p_mean_variance( model, x, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, model_kwargs=model_kwargs, ) # Usually our model outputs epsilon, but we re-derive it # in case we used x_start or x_prev prediction. eps = ( _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x.shape) * x - out["pred_xstart"] ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x.shape) alpha_bar_next = _extract_into_tensor(self.alphas_cumprod_next, t, x.shape) # Equation 12. reversed mean_pred = ( out["pred_xstart"] * th.sqrt(alpha_bar_next) + th.sqrt(1 - alpha_bar_next) * eps ) print_cond(f" GaussianDiffusion.ddim_reverse_sample(sample: {mean_pred.shape}, out['pred_xstart']:{out['pred_xstart'].shape}", cond=_DEBUG and "ddim_reverse_sample" not in self.logonce) if "ddim_reverse_sample" not in self.logonce: self.logonce.append('ddim_reverse_sample') return {"sample": mean_pred, "pred_xstart": out["pred_xstart"]} def ddim_sample_loop( self, model, shape, noise=None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, device=None, progress=False, eta=0.0, ): """ Generate samples from the model using DDIM. Same usage as p_sample_loop(). """ final = None for sample in self.ddim_sample_loop_progressive( model, shape, noise=noise, clip_denoised=clip_denoised, denoised_fn=denoised_fn, cond_fn=cond_fn, model_kwargs=model_kwargs, device=device, progress=progress, eta=eta, ): final = sample print_cond(f" GaussianDiffusion.ddim_sample_loop(final['sample']:{final['sample']}", cond=_DEBUG and "ddim_sample_loop" not in self.logonce) if "ddim_reverse_sample" not in self.logonce: self.logonce.append('ddim_reverse_sample') return final["sample"] def ddim_sample_loop_progressive( self, model, shape, noise=None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, device=None, progress=False, eta=0.0, ): """ Use DDIM to sample from the model and yield intermediate samples from each timestep of DDIM. Same usage as p_sample_loop_progressive(). """ if device is None: device = next(model.parameters()).device assert isinstance(shape, (tuple, list)) if noise is not None: img = noise else: img = th.randn(*shape, device=device) indices = list(range(self.num_timesteps))[::-1] print_cond(f" GaussianDiffusion.ddim_sample_loop_progressive(indices:{indices}", cond=_DEBUG and "ddim_sample_loop_progressive" not in self.logonce) if "ddim_sample_loop_progressive" not in self.logonce: self.logonce.append('ddim_sample_loop_progressive') if progress: # Lazy import so that we don't depend on tqdm. from tqdm.auto import tqdm indices = tqdm(indices) for i in indices: t = th.tensor([i] * shape[0], device=device) with th.no_grad(): out = self.ddim_sample( model, img, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, cond_fn=cond_fn, model_kwargs=model_kwargs, eta=eta, ) yield out img = out["sample"] def _vb_terms_bpd( self, model, x_start, x_t, t, clip_denoised=True, model_kwargs=None ): """ Get a term for the variational lower-bound. The resulting units are bits (rather than nats, as one might expect). This allows for comparison to other papers. :return: a dict with the following keys: - 'output': a shape [N] tensor of NLLs or KLs. - 'pred_xstart': the x_0 predictions. """ true_mean, _, true_log_variance_clipped = self.q_posterior_mean_variance( x_start=x_start, x_t=x_t, t=t ) out = self.p_mean_variance( model, x_t, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs ) kl = normal_kl( true_mean, true_log_variance_clipped, out["mean"], out["log_variance"] ) kl = mean_flat(kl) / np.log(2.0) decoder_nll = -discretized_gaussian_log_likelihood( x_start, means=out["mean"], log_scales=0.5 * out["log_variance"] ) assert decoder_nll.shape == x_start.shape decoder_nll = mean_flat(decoder_nll) / np.log(2.0) # At the first timestep return the decoder NLL, # otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t)) output = th.where((t == 0), decoder_nll, kl) print_cond(f" GaussianDiffusion._vb_terms_bpd(output:{output.shape}, pred_xstart: {out['pred_xstart'].shape}", cond=_DEBUG and "_vb_terms_bpd" not in self.logonce) if "_vb_terms_bpd" not in self.logonce: self.logonce.append('_vb_terms_bpd') return {"output": output, "pred_xstart": out["pred_xstart"]} def training_losses(self, model, x_start, t, model_kwargs=None, noise=None): """ Compute training losses for a single timestep. :param model: the model to evaluate loss on. :param x_start: the [N x C x ...] tensor of inputs. :param t: a batch of timestep indices. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :param noise: if specified, the specific Gaussian noise to try to remove. :return: a dict with the key "loss" containing a tensor of shape [N]. Some mean or variance settings may also have other keys. """ if model_kwargs is None: model_kwargs = {} if noise is None: noise = th.randn_like(x_start) x_t = self.q_sample(x_start, t, noise=noise) terms = {} if self.loss_type == LossType.KL or self.loss_type == LossType.RESCALED_KL: terms["loss"] = self._vb_terms_bpd( model=model, x_start=x_start, x_t=x_t, t=t, clip_denoised=False, model_kwargs=model_kwargs, )["output"] if self.loss_type == LossType.RESCALED_KL: terms["loss"] *= self.num_timesteps elif self.loss_type == LossType.MSE or self.loss_type == LossType.RESCALED_MSE: model_output = model(x_t, self._scale_timesteps(t), **model_kwargs) print_cond(f" GaussianDiffusion.training_losses(model_output:{logtensor(model_output)}, loss_type {self.loss_type}", cond=_DEBUG and "training_losses" not in self.logonce) if self.model_var_type in [ ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE, ]: B, C = x_t.shape[:2] assert model_output.shape == (B, C * 2, *x_t.shape[2:]) model_output, model_var_values = th.split(model_output, C, dim=1) # Learn the variance using the variational bound, but don't let # it affect our mean prediction. frozen_out = th.cat([model_output.detach(), model_var_values], dim=1) terms["vb"] = self._vb_terms_bpd( model=lambda *args, r=frozen_out: r, x_start=x_start, x_t=x_t, t=t, clip_denoised=False, )["output"] if self.loss_type == LossType.RESCALED_MSE: # Divide by 1000 for equivalence with initial implementation. # Without a factor of 1/1000, the VB term hurts the MSE term. terms["vb"] *= self.num_timesteps / 1000.0 target = { ModelMeanType.PREVIOUS_X: self.q_posterior_mean_variance( x_start=x_start, x_t=x_t, t=t )[0], ModelMeanType.START_X: x_start, ModelMeanType.EPSILON: noise, }[self.model_mean_type] print_cond(f" GaussianDiffusion.training_losses(model_output:{logtensor(model_output)}, target:{logtensor(target)}, x_start:{logtensor(x_start)}", cond=_DEBUG and "training_losses" not in self.logonce) assert model_output.shape == target.shape == x_start.shape terms["mse"] = mean_flat((target - model_output) ** 2) if "vb" in terms: terms["loss"] = terms["mse"] + terms["vb"] else: terms["loss"] = terms["mse"] else: raise NotImplementedError(self.loss_type) if "training_losses" not in self.logonce: self.logonce.append('training_losses') return terms def _prior_bpd(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element. """ batch_size = x_start.shape[0] t = th.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t) kl_prior = normal_kl( mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0 ) print_cond(f" GaussianDiffusion._prior_bpd(kl_prior:{kl_prior.shape}", cond=_DEBUG and "_prior_bpd" not in self.logonce) if "_prior_bpd" not in self.logonce: self.logonce.append('_prior_bpd') return mean_flat(kl_prior) / np.log(2.0) def calc_bpd_loop(self, model, x_start, clip_denoised=True, model_kwargs=None): """ Compute the entire variational lower-bound, measured in bits-per-dim, as well as other related quantities. :param model: the model to evaluate loss on. :param x_start: the [N x C x ...] tensor of inputs. :param clip_denoised: if True, clip denoised samples. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :return: a dict containing the following keys: - total_bpd: the total variational lower-bound, per batch element. - prior_bpd: the prior term in the lower-bound. - vb: an [N x T] tensor of terms in the lower-bound. - xstart_mse: an [N x T] tensor of x_0 MSEs for each timestep. - mse: an [N x T] tensor of epsilon MSEs for each timestep. """ device = x_start.device batch_size = x_start.shape[0] vb = [] xstart_mse = [] mse = [] for t in list(range(self.num_timesteps))[::-1]: t_batch = th.tensor([t] * batch_size, device=device) noise = th.randn_like(x_start) x_t = self.q_sample(x_start=x_start, t=t_batch, noise=noise) # Calculate VLB term at the current timestep with th.no_grad(): out = self._vb_terms_bpd( model, x_start=x_start, x_t=x_t, t=t_batch, clip_denoised=clip_denoised, model_kwargs=model_kwargs, ) vb.append(out["output"]) xstart_mse.append(mean_flat((out["pred_xstart"] - x_start) ** 2)) eps = self._predict_eps_from_xstart(x_t, t_batch, out["pred_xstart"]) mse.append(mean_flat((eps - noise) ** 2)) vb = th.stack(vb, dim=1) xstart_mse = th.stack(xstart_mse, dim=1) mse = th.stack(mse, dim=1) prior_bpd = self._prior_bpd(x_start) total_bpd = vb.sum(dim=1) + prior_bpd print_cond(f" GaussianDiffusion.calc_bpd_loop(vb:{vb.shape}, prior_bpd:{prior_bpd.shape}, total_bpd:{total_bpd.shape}", cond=_DEBUG and "calc_bpd_loop" not in self.logonce) if "_prior_bpd" not in self.logonce: self.logonce.append('_prior_bpd') return { "total_bpd": total_bpd, "prior_bpd": prior_bpd, "vb": vb, "xstart_mse": xstart_mse, "mse": mse, } def _extract_into_tensor(arr, timesteps, broadcast_shape): """ Extract values from a 1-D numpy array for a batch of indices. :param arr: the 1-D numpy array. :param timesteps: a tensor of indices into the array to extract. :param broadcast_shape: a larger shape of K dimensions with the batch dimension equal to the length of timesteps. :return: a tensor of shape [batch_size, 1, ...] where the shape has K dims. """ res = th.from_numpy(arr).to(device=timesteps.device)[timesteps].float() while len(res.shape) < len(broadcast_shape): res = res[..., None] return res.expand(broadcast_shape)
41.870009
306
0.604537
ace879c918bcda026b508a94ff85564bf2d3680e
1,337
py
Python
lab05/markdown.py
Abneyus/CSCI2963-01-Spring2017
f667afeafaeb9d4626bc34380978f0610351310d
[ "MIT" ]
null
null
null
lab05/markdown.py
Abneyus/CSCI2963-01-Spring2017
f667afeafaeb9d4626bc34380978f0610351310d
[ "MIT" ]
null
null
null
lab05/markdown.py
Abneyus/CSCI2963-01-Spring2017
f667afeafaeb9d4626bc34380978f0610351310d
[ "MIT" ]
null
null
null
""" Markdown.py 0. just print whatever is passed in to stdin 0. if filename passed in as a command line parameter, then print file instead of stdin 1. wrap input in paragraph tags 2. convert single asterisk or underscore pairs to em tags 3. convert double asterisk or underscore pairs to strong tags """ import fileinput import re def convertStrong(line): line = re.sub(r'\*\*(.*)\*\*', r'<strong>\1</strong>', line) line = re.sub(r'__(.*)__', r'<strong>\1</strong>', line) return line def convertEm(line): line = re.sub(r'\*(.*)\*', r'<em>\1</em>', line) line = re.sub(r'_(.*)_', r'<em>\1</em>', line) return line def convertHead1(line): line = re.sub(r'#(.*)#', r'<h1>\1</h1>', line) return line def convertHead2(line): line = re.sub(r'##(.*)##', r'<h2>\1</h2>', line) return line def convertHead3(line): line = re.sub(r'###(.*)###', r'<h3>\1</h3>', line) return line def convertBlockquote(line): line = re.sub(r'>(.*\n.*)', r'<blockquote>\1</blockquote>', line) return line for line in fileinput.input(): line = line.rstrip() line = convertStrong(line) line = convertEm(line) line = convertHead3(line) line = convertHead2(line) line = convertHead1(line) line = convertBlockquote(line) print '<p>' + line + '</p>',
26.215686
68
0.60359
ace879d19dcea6b870b711e9cbbf312f35b55f8d
16,794
py
Python
framework/basehandlers.py
Fmichi50/chromium-dashboard
e77396a8cc5a5f10f46ff9b9456f6aa0b2dc94d8
[ "Apache-2.0" ]
null
null
null
framework/basehandlers.py
Fmichi50/chromium-dashboard
e77396a8cc5a5f10f46ff9b9456f6aa0b2dc94d8
[ "Apache-2.0" ]
2
2022-03-03T23:30:19.000Z
2022-03-08T23:38:42.000Z
framework/basehandlers.py
Fmichi50/chromium-dashboard
e77396a8cc5a5f10f46ff9b9456f6aa0b2dc94d8
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2021 Google Inc. # # 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 json import logging import os import re import flask import flask.views import werkzeug.exceptions from google.cloud import ndb import settings from framework import csp from framework import permissions from framework import ramcache from framework import secrets from framework import utils from framework import xsrf from internals import models from django.template.loader import render_to_string import django from google.oauth2 import id_token from google.auth.transport import requests from flask import session import sys from framework import users # Initialize django so that it'll function when run as a standalone script. # https://django.readthedocs.io/en/latest/releases/1.7.html#standalone-scripts django.setup() # Our API responses are prefixed with this ro prevent attacks that # exploit <script src="...">. See go/xssi. XSSI_PREFIX = ')]}\'\n'; class BaseHandler(flask.views.MethodView): @property def request(self): return flask.request def abort(self, status, msg=None, **kwargs): """Support webapp2-style, e.g., self.abort(400).""" if msg: if status == 500: logging.error('ISE: %s' % msg) else: logging.info('Abort %r: %s' % (status, msg)) flask.abort(status, description=msg, **kwargs) else: flask.abort(status, **kwargs) def redirect(self, url): """Support webapp2-style, e.g., return self.redirect(url).""" return flask.redirect(url) def get_current_user(self, required=False): # TODO(jrobbins): oauth support current_user = users.get_current_user() if required and not current_user: self.abort(403, msg='User must be signed in') return current_user def get_param( self, name, default=None, required=True, validator=None, allowed=None): """Get the specified JSON parameter.""" json_body = self.request.get_json(force=True, silent=True) or {} val = json_body.get(name, default) if required and not val: self.abort(400, msg='Missing parameter %r' % name) if val and validator and not validator(val): self.abort(400, msg='Invalid value for parameter %r' % name) if val and allowed and val not in allowed: self.abort(400, msg='Unexpected value for parameter %r' % name) return val def get_int_param( self, name, default=None, required=True, validator=None, allowed=None): """Get the specified integer JSON parameter.""" val = self.get_param( name, default=default, required=required, validator=validator, allowed=allowed) if val and type(val) != int: self.abort(400, msg='Parameter %r was not an int' % name) return val def get_bool_param(self, name, default=False, required=False): """Get the specified boolean JSON parameter.""" val = self.get_param(name, default=default, required=required) if type(val) != bool: self.abort(400, msg='Parameter %r was not a bool' % name) return val def get_specified_feature(self, feature_id=None, required=True): """Get the feature specified in the featureId parameter.""" feature_id = (feature_id or self.get_int_param('featureId', required=required)) if not required and not feature_id: return None feature = models.Feature.get_by_id(feature_id) if required and not feature: self.abort(404, msg='Feature not found') user = self.get_current_user() if not permissions.can_view_feature(user, feature): self.abort(403, msg='Cannot view that feature') return feature class APIHandler(BaseHandler): def get_headers(self): """Add CORS and Chrome Frame to all responses.""" headers = { 'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload', 'Access-Control-Allow-Origin': '*', 'X-UA-Compatible': 'IE=Edge,chrome=1', } return headers def defensive_jsonify(self, handler_data): """Return a Flask Response object with a JSON string prefixed with junk.""" body = json.dumps(handler_data) return flask.current_app.response_class( XSSI_PREFIX + body, mimetype=flask.current_app.config['JSONIFY_MIMETYPE']) def get(self, *args, **kwargs): """Handle an incoming HTTP GET request.""" headers = self.get_headers() ramcache.check_for_distributed_invalidation() handler_data = self.do_get(*args, **kwargs) return self.defensive_jsonify(handler_data), headers def post(self, *args, **kwargs): """Handle an incoming HTTP POST request.""" json_body = self.request.get_json(force=True, silent=True) or {} logging.info('POST data is %r', json_body) is_login_request = str(self.request.url_rule) == '/api/v0/login' if not is_login_request: self.require_signed_in_and_xsrf_token() headers = self.get_headers() ramcache.check_for_distributed_invalidation() handler_data = self.do_post(*args, **kwargs) return self.defensive_jsonify(handler_data), headers def patch(self, *args, **kwargs): """Handle an incoming HTTP PATCH request.""" self.require_signed_in_and_xsrf_token() headers = self.get_headers() ramcache.check_for_distributed_invalidation() handler_data = self.do_patch(*args, **kwargs) return self.defensive_jsonify(handler_data), headers def delete(self, *args, **kwargs): """Handle an incoming HTTP DELETE request.""" self.require_signed_in_and_xsrf_token() headers = self.get_headers() ramcache.check_for_distributed_invalidation() handler_data = self.do_delete(*args, **kwargs) return self.defensive_jsonify(handler_data), headers def _get_valid_methods(self): """For 405 responses, list methods the concrete handler implements.""" valid_methods = ['GET'] if self.do_post.__code__ is not APIHandler.do_post.__code__: valid_methods.append('POST') if self.do_patch.__code__ is not APIHandler.do_patch.__code__: valid_methods.append('PATCH') if self.do_delete.__code__ is not APIHandler.do_delete.__code__: valid_methods.append('DELETE') return valid_methods def do_get(self, **kwargs): """Subclasses should implement this method to handle a GET request.""" # Every API handler must handle GET. raise NotImplementedError() def do_post(self, **kwargs): """Subclasses should implement this method to handle a POST request.""" self.abort(405, valid_methods=self._get_valid_methods()) def do_patch(self, **kwargs): """Subclasses should implement this method to handle a PATCH request.""" self.abort(405, valid_methods=self._get_valid_methods()) def do_delete(self, **kwargs): """Subclasses should implement this method to handle a DELETE request.""" self.abort(405, valid_methods=self._get_valid_methods()) def validate_token(self, token, email): """If the token is not valid, raise an exception.""" # This is a separate method so that the refresh handler can override it. xsrf.validate_token(token, email) def require_signed_in_and_xsrf_token(self): """Every API POST, PUT, or DELETE must be signed in with an XSRF token.""" user = self.get_current_user(required=True) if not user: self.abort(403, msg='Sign in required') token = self.request.headers.get('X-Xsrf-Token') if not token: try: token = self.get_param('token', required=False) except werkzeug.exceptions.BadRequest: pass # Raised when the request has no body. if not token: self.abort(400, msg='Missing XSRF token') try: self.validate_token(token, user.email()) except xsrf.TokenIncorrect: self.abort(400, msg='Invalid XSRF token') class FlaskHandler(BaseHandler): TEMPLATE_PATH = None # Subclasses should define this. HTTP_CACHE_TYPE = None # Subclasses can use 'public' or 'private' JSONIFY = False # Set to True for JSON feeds. IS_INTERNAL_HANDLER = False # Subclasses can skip XSRF check. def get_cache_headers(self): """Add cache control headers if HTTP_CACHE_TYPE is set.""" if self.HTTP_CACHE_TYPE: directive = '%s, max-age=%s' % ( self.HTTP_CACHE_TYPE, settings.DEFAULT_CACHE_TIME) return {'Cache-Control': directive} return {} def get_headers(self): """Add CORS and Chrome Frame to all responses.""" headers = { 'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload', 'Access-Control-Allow-Origin': '*', 'X-UA-Compatible': 'IE=Edge,chrome=1', } headers.update(self.get_cache_headers()) return headers def get_template_data(self): """Subclasses should implement this method to handle a GET request.""" raise NotImplementedError() def get_template_path(self, template_data): """Subclasses can override their class constant via template_data.""" if 'template_path' in template_data: return template_data['template_path'] if self.TEMPLATE_PATH: return self.TEMPLATE_PATH raise ValueError( 'No TEMPLATE_PATH was defined in %r or returned in template_data.' % self.__class__.__name__) def process_post_data(self): """Subclasses should implement this method to handle a POST request.""" self.abort(405, msg='Unexpected HTTP method', valid_methods=['GET']) def get_common_data(self, path=None): """Return template data used on all pages, e.g., sign-in info.""" current_path = path or flask.request.full_path common_data = { 'prod': settings.PROD, 'APP_TITLE': settings.APP_TITLE, 'google_sign_in_client_id': settings.GOOGLE_SIGN_IN_CLIENT_ID, 'current_path': current_path, 'TEMPLATE_CACHE_TIME': settings.TEMPLATE_CACHE_TIME, 'banner_message': settings.BANNER_MESSAGE, 'banner_time': utils.get_banner_time(settings.BANNER_TIME), } user = self.get_current_user() if user: user_pref = models.UserPref.get_signed_in_user_pref() common_data['user'] = { 'can_create_feature': permissions.can_create_feature(user), 'can_edit': permissions.can_edit_any_feature(user), 'is_admin': permissions.can_admin_site(user), 'email': user.email(), 'dismissed_cues': json.dumps(user_pref.dismissed_cues), } common_data['xsrf_token'] = xsrf.generate_token(user.email()) common_data['xsrf_token_expires'] = xsrf.token_expires_sec() else: common_data['user'] = None common_data['xsrf_token'] = xsrf.generate_token(None) common_data['xsrf_token_expires'] = 0 return common_data def render(self, template_data, template_path): return render_to_string(template_path, template_data) def get(self, *args, **kwargs): """GET handlers can render templates, return JSON, or do redirects.""" ramcache.check_for_distributed_invalidation() handler_data = self.get_template_data(*args, **kwargs) if self.JSONIFY and type(handler_data) in (dict, list): headers = self.get_headers() return flask.jsonify(handler_data), headers elif type(handler_data) == dict: status = handler_data.get('status', 200) handler_data.update(self.get_common_data()) nonce = csp.get_nonce() handler_data['nonce'] = nonce template_path = self.get_template_path(handler_data) template_text = self.render(handler_data, os.path.join(template_path)) headers = self.get_headers() headers.update(csp.get_headers(nonce)) return template_text, status, headers else: # handler_data is a string or redirect response object. return handler_data def post(self, *args, **kwargs): """POST handlers return a string, JSON, or a redirect.""" ramcache.check_for_distributed_invalidation() self.require_xsrf_token() handler_data = self.process_post_data(*args, **kwargs) headers = self.get_headers() if self.JSONIFY and type(handler_data) in (dict, list): return flask.jsonify(handler_data), headers else: # handler_data is a string or redirect response object. return handler_data, headers @property def form(self): """Property for POST values dict.""" return flask.request.form def require_xsrf_token(self): """Every UI form submission must have a XSRF token.""" if settings.UNIT_TEST_MODE or self.IS_INTERNAL_HANDLER: return token = self.request.headers.get('X-Xsrf-Token') if not token: token = self.form.get('token') if not token: self.abort(400, msg='Missing XSRF token') user = self.get_current_user(required=True) try: xsrf.validate_token(token, user.email()) except xsrf.TokenIncorrect: self.abort(400, msg='Invalid XSRF token') def require_task_header(self): """Abort if this is not a Google Cloud Tasks request.""" if settings.UNIT_TEST_MODE: return if 'X-AppEngine-QueueName' not in self.request.headers: self.abort(403, msg='Lacking X-AppEngine-QueueName header') def split_input(self, field_name, delim='\\r?\\n'): """Split the input lines, strip whitespace, and skip blank lines.""" input_text = flask.request.form.get(field_name) or '' return [x.strip() for x in re.split(delim, input_text) if x] def split_emails(self, param_name): """Split one input field and construct objects for ndb.StringProperty().""" addr_strs = self.split_input(param_name, delim=',') emails = [str(addr) for addr in addr_strs] return emails def parse_link(self, param_name): link = flask.request.form.get(param_name) or None if link: if not link.startswith('http'): link = str('http://' + link) else: link = str(link) return link def parse_int(self, param_name): param = flask.request.form.get(param_name) or None if param: param = int(param) return param class Redirector(FlaskHandler): """Reusable handler that always redirects. Specify the location in the third part of a routing rule using: {'location': '/path/to/page'}.""" def get_template_data(self, location='/'): return flask.redirect(location), self.get_headers() class ConstHandler(FlaskHandler): """Reusable handler for templates that require no page-specific logic. Specify the location in the third part of a routing rule using: {'template_path': 'path/to/template.html'}.""" def get_template_data(self, **defaults): """Render a template, or return a JSON constant.""" if 'template_path' in defaults: template_path = defaults['template_path'] if '.html' not in template_path: self.abort( 500, msg='template_path %r does not end with .html' % template_path) return defaults return flask.jsonify(defaults) def ndb_wsgi_middleware(wsgi_app): """Create a new runtime context for cloud ndb for every request""" client = ndb.Client() def middleware(environ, start_response): with client.context(): return wsgi_app(environ, start_response) return middleware def FlaskApplication(routes, pattern_base='', debug=False): """Make a Flask app and add routes and handlers that work like webapp2.""" app = flask.Flask(__name__) app.wsgi_app = ndb_wsgi_middleware(app.wsgi_app) # For Cloud NDB Context client = ndb.Client() with client.context(): app.secret_key = secrets.get_session_secret() # For flask.session for i, rule in enumerate(routes): pattern = rule[0] handler_class = rule[1] defaults = rule[2] if len(rule) > 2 else None classname = handler_class.__name__ app.add_url_rule( pattern_base + pattern, endpoint=classname + str(i), # We don't use it, but it must be unique. view_func=handler_class.as_view(classname), defaults=defaults) # The following causes flask to print a stack trace and return 500 # when we are running locally and a handler raises a BadRequest exception. # In production, it will return a status 400. app.config["TRAP_BAD_REQUEST_ERRORS"] = settings.DEV_MODE # Flask apps also have a debug setting that can be used to auto-reload # template source code, but we use django for that. return app
35.355789
80
0.698285
ace879e331c8bd377d3df5e377c450df8173647f
3,115
py
Python
src/mem/slicc/util.py
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
765
2015-01-14T16:17:04.000Z
2022-03-28T07:46:28.000Z
src/mem/slicc/util.py
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
148
2018-07-20T00:58:36.000Z
2021-11-16T01:52:33.000Z
src/mem/slicc/util.py
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
807
2015-01-06T09:55:38.000Z
2022-03-30T10:23:36.000Z
# Copyright (c) 2009 The Hewlett-Packard Development Company # All rights reserved. # # 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 the copyright holders 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. import os import sys class PairContainer(object): def __init__(self, pairs=None): self.pairs = {} if pairs: self.pairs.update(pairs) def __contains__(self, item): return item in self.pairs def __getitem__(self, item): return self.pairs[item] def __setitem__(self, item, value): self.pairs[item] = value def get(self, item, failobj=None): return self.pairs.get(item, failobj) class Location(object): def __init__(self, filename, lineno, no_warning=False): if not isinstance(filename, str): raise AttributeError( "filename must be a string, found {}".format(type(filename))) if not isinstance(lineno, int): raise AttributeError( "filename must be an integer, found {}".format(type(lineno))) self.filename = filename self.lineno = lineno self.no_warning = no_warning def __str__(self): return '%s:%d' % (os.path.basename(self.filename), self.lineno) def warning(self, message, *args): if self.no_warning: return if args: message = message % args #raise Exception, "%s: Warning: %s" % (self, message) print("%s: Warning: %s" % (self, message), file=sys.stderr) def error(self, message, *args): if args: message = message % args raise Exception("{}: Error: {}".format(self, message)) sys.exit("\n%s: Error: %s" % (self, message)) __all__ = [ 'PairContainer', 'Location' ]
39.935897
77
0.691814
ace87a94e84ab4ede2a2b616d92533c415466a8f
3,301
py
Python
projectq/setups/decompositions/sqrtswap2cnot_test.py
kevin-teddy/ProjectQ
22828daca975cebed92f946ba2625f295cfa70e9
[ "Apache-2.0" ]
3
2021-11-08T11:46:42.000Z
2021-12-27T10:13:38.000Z
projectq/setups/decompositions/sqrtswap2cnot_test.py
kevin-teddy/ProjectQ
22828daca975cebed92f946ba2625f295cfa70e9
[ "Apache-2.0" ]
2
2021-11-09T14:57:09.000Z
2022-01-12T12:35:58.000Z
projectq/setups/decompositions/sqrtswap2cnot_test.py
kevin-teddy/ProjectQ
22828daca975cebed92f946ba2625f295cfa70e9
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2018 ProjectQ-Framework (www.projectq.ch) # # 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. """Tests for projectq.setups.decompositions.sqrtswap2cnot.""" import pytest from projectq import MainEngine from projectq.backends import Simulator from projectq.cengines import ( AutoReplacer, DecompositionRuleSet, DummyEngine, InstructionFilter, ) from projectq.ops import All, Measure, SqrtSwap, Command from projectq.types import WeakQubitRef import projectq.setups.decompositions.sqrtswap2cnot as sqrtswap2cnot def _decomp_gates(eng, cmd): if isinstance(cmd.gate, SqrtSwap.__class__): return False return True def test_sqrtswap_invalid(): qb0 = WeakQubitRef(engine=None, idx=0) qb1 = WeakQubitRef(engine=None, idx=1) qb2 = WeakQubitRef(engine=None, idx=2) with pytest.raises(ValueError): sqrtswap2cnot._decompose_sqrtswap(Command(None, SqrtSwap, ([qb0], [qb1], [qb2]))) with pytest.raises(ValueError): sqrtswap2cnot._decompose_sqrtswap(Command(None, SqrtSwap, ([qb0], [qb1, qb2]))) def test_sqrtswap(): for basis_state in ([1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]): correct_dummy_eng = DummyEngine(save_commands=True) correct_eng = MainEngine(backend=Simulator(), engine_list=[correct_dummy_eng]) rule_set = DecompositionRuleSet(modules=[sqrtswap2cnot]) test_dummy_eng = DummyEngine(save_commands=True) test_eng = MainEngine( backend=Simulator(), engine_list=[ AutoReplacer(rule_set), InstructionFilter(_decomp_gates), test_dummy_eng, ], ) test_sim = test_eng.backend correct_sim = correct_eng.backend correct_qureg = correct_eng.allocate_qureg(2) correct_eng.flush() test_qureg = test_eng.allocate_qureg(2) test_eng.flush() correct_sim.set_wavefunction(basis_state, correct_qureg) test_sim.set_wavefunction(basis_state, test_qureg) SqrtSwap | (test_qureg[0], test_qureg[1]) test_eng.flush() SqrtSwap | (correct_qureg[0], correct_qureg[1]) correct_eng.flush() assert len(test_dummy_eng.received_commands) != len(correct_dummy_eng.received_commands) for fstate in range(4): binary_state = format(fstate, '02b') test = test_sim.get_amplitude(binary_state, test_qureg) correct = correct_sim.get_amplitude(binary_state, correct_qureg) assert correct == pytest.approx(test, rel=1e-10, abs=1e-10) All(Measure) | test_qureg All(Measure) | correct_qureg test_eng.flush(deallocate_qubits=True) correct_eng.flush(deallocate_qubits=True)
36.274725
96
0.686459
ace87b4fbb392029bb61cb1641f27630d8f12e38
274
py
Python
problem10.py
charlesfranciscodev/project-euler
a66772853a636130fa37d83a3129ca3a66db7fd2
[ "MIT" ]
null
null
null
problem10.py
charlesfranciscodev/project-euler
a66772853a636130fa37d83a3129ca3a66db7fd2
[ "MIT" ]
null
null
null
problem10.py
charlesfranciscodev/project-euler
a66772853a636130fa37d83a3129ca3a66db7fd2
[ "MIT" ]
null
null
null
# Summation of primes # Answer: 142913828922 from problem3 import is_prime def sum_of_primes(limit): total = 0 for i in range(2, limit): if is_prime(i): total += i return total limit = 2000000 print(sum_of_primes(limit))
16.117647
30
0.613139
ace87b669e4bfa48f8a75751edb0364d76e6a51a
2,940
py
Python
tests/conftest.py
maheshsamudrala241/workday
2f3ec5a1027e48a255fbe73affc02876cdfe649b
[ "ISC" ]
35
2018-07-31T08:13:39.000Z
2022-01-14T01:40:32.000Z
tests/conftest.py
maheshsamudrala241/workday
2f3ec5a1027e48a255fbe73affc02876cdfe649b
[ "ISC" ]
7
2018-07-21T00:05:32.000Z
2020-05-08T10:39:14.000Z
tests/conftest.py
maheshsamudrala241/workday
2f3ec5a1027e48a255fbe73affc02876cdfe649b
[ "ISC" ]
16
2018-08-14T13:14:00.000Z
2021-08-23T08:15:58.000Z
# -*- coding: utf-8 -*- # Licensed to Anthony Shaw (anthonyshaw@apache.org) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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 os import pytest from lxml import etree import workday.auth import requests.sessions from requests_staticmock import ClassAdapter from requests_staticmock.abstractions import BaseMockClass from requests_staticmock.responses import StaticResponseFactory @pytest.fixture() def test_wsdl(): return {"test": "https://workday.com/api/v30"} @pytest.fixture() def test_authentication(): return workday.auth.AnonymousAuthentication() @pytest.fixture() def test_response_dict(): return { "Response_Results": { "Page": 1, "Total_Pages": 2, "Total_Results": 200, "Page_Results": 100, }, "Response_Data": {"TestData": [{"TestRecord": 1}]}, } @pytest.fixture() def workday_client(test_authentication, test_wsdl, mocker): class MockSoapClass(BaseMockClass): base_path = "tests/fixtures/v30_1" def _response(self, request, path): with open(os.path.join(self.base_path, path), "rb") as fo: body = fo.read() return StaticResponseFactory.GoodResponse(body, request) def _wsdl(self, request): return self._response(request, "test_wsdl") def _api_v30(self, request, url, method, params, headers): if "?wsdl" in url: return self._wsdl(request) return self._response(request, method) def _api_test(self, request, url, method, params, headers): root = etree.XML(request.body) soap_request = root.getchildren()[0].getchildren()[0] assert soap_request.tag == "{urn:examples:helloservice}sayHello" kwargs = {} for arg in soap_request.getchildren(): kwargs[arg.tag] = arg.text assert kwargs == {"firstName": "xavier"} return self._response(request, "test_soap_response") adapter = ClassAdapter(MockSoapClass) client = workday.WorkdayClient(wsdls=test_wsdl, authentication=test_authentication) client._session.adapters = {} client._session.mount("https://workday.com/", adapter) return client
33.793103
87
0.679252
ace87b8bf8de4067f97087d2aa7619cafcf5e079
1,031
py
Python
python/test/test_portfolio_plan_name_updated_event.py
dlens/dlxapi
189a6519240ce625d7a9cdb89e305a335d2aa045
[ "MIT" ]
null
null
null
python/test/test_portfolio_plan_name_updated_event.py
dlens/dlxapi
189a6519240ce625d7a9cdb89e305a335d2aa045
[ "MIT" ]
1
2020-08-20T17:31:43.000Z
2020-08-20T17:31:43.000Z
python/test/test_portfolio_plan_name_updated_event.py
dlens/dlxapi
189a6519240ce625d7a9cdb89e305a335d2aa045
[ "MIT" ]
null
null
null
# coding: utf-8 """ Decision Lens API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 1.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import dlxapi from dlxapi.models.portfolio_plan_name_updated_event import PortfolioPlanNameUpdatedEvent # noqa: E501 from dlxapi.rest import ApiException class TestPortfolioPlanNameUpdatedEvent(unittest.TestCase): """PortfolioPlanNameUpdatedEvent unit test stubs""" def setUp(self): pass def tearDown(self): pass def testPortfolioPlanNameUpdatedEvent(self): """Test PortfolioPlanNameUpdatedEvent""" # FIXME: construct object with mandatory attributes with example values # model = dlxapi.models.portfolio_plan_name_updated_event.PortfolioPlanNameUpdatedEvent() # noqa: E501 pass if __name__ == '__main__': unittest.main()
25.146341
119
0.736178
ace87be3a8c3409ceb38407700169c0f4725cc2a
10,023
py
Python
Spacing/Metrics Key Manager.py
justanotherfoundry/Glyphs-Scripts
f28aeab0224ae19ace4a86cf363e7990985199b7
[ "Apache-2.0" ]
283
2015-01-07T12:35:35.000Z
2022-03-29T06:10:44.000Z
Spacing/Metrics Key Manager.py
justanotherfoundry/Glyphs-Scripts
f28aeab0224ae19ace4a86cf363e7990985199b7
[ "Apache-2.0" ]
203
2015-01-26T18:43:08.000Z
2022-03-04T01:47:58.000Z
Spacing/Metrics Key Manager.py
justanotherfoundry/Glyphs-Scripts
f28aeab0224ae19ace4a86cf363e7990985199b7
[ "Apache-2.0" ]
96
2015-01-19T20:58:03.000Z
2022-03-29T06:10:56.000Z
#MenuTitle: Metrics Key Manager # -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals __doc__=""" Batch apply metrics keys to the current font. """ import vanilla from AppKit import NSFont LeftKeys=""" =H: B D E F I K L N P R Thorn Germandbls M =O: C G Q =o: c d e q eth =h: b k l thorn =n: idotless m p r =|n: u """ RightKeys=""" =|: A H I M N O T U V W X Y =O: D =U: J =o: b p thorn =n: h m =|n: idotless u """ class MetricsKeyManager( object ): def __init__( self ): # Window 'self.w': windowWidth = 350 windowHeight = 240 windowWidthResize = 1000 # user can resize width by this value windowHeightResize = 1000 # user can resize height by this value self.w = vanilla.FloatingWindow( ( windowWidth, windowHeight ), # default window size "Metrics Key Manager", # window title minSize = ( windowWidth, windowHeight-100 ), # minimum size (for resizing) maxSize = ( windowWidth + windowWidthResize, windowHeight + windowHeightResize ), # maximum size (for resizing) autosaveName = "com.mekkablue.MetricsKeyManager.mainwindow" # stores last window position and size ) # UI elements: linePos, inset, lineHeight, boxHeight = self.getMeasurements() self.w.LeftMetricsKeysText = vanilla.TextBox( (inset, linePos+2, 70, 14), u"Left Keys:", sizeStyle='small', selectable=True ) self.w.LeftMetricsKeys = vanilla.TextEditor( (inset+70, linePos, -inset, boxHeight), "", callback=self.SavePreferences) #, sizeStyle='small' ) linePos += boxHeight + 10 self.w.RightMetricsKeysText = vanilla.TextBox( (inset, linePos+2, 70, 14), u"Right Keys:", sizeStyle='small', selectable=True ) self.w.RightMetricsKeys = vanilla.TextEditor( (inset+70, linePos, -inset, boxHeight), "", callback=self.SavePreferences) #, sizeStyle='small' ) editFont = NSFont.legibileFontOfSize_(NSFont.smallSystemFontSize()) for editField in (self.w.LeftMetricsKeys, self.w.RightMetricsKeys): editField.getNSTextView().setToolTip_(u"Enter a metrics key like '=H', followed by a colon (:), followed by glyph names, spearated by space, comma, or any other separator that cannot be part of a glyph name. (Glyph names can contain A-Z, a-z, 0-9, period, underscore and hyphen.)\nExample: ‘=H: B D E F’.") editField.getNSTextView().setFont_(editFont) editField.getNSScrollView().setHasVerticalScroller_(1) editField.getNSScrollView().setRulersVisible_(1) # Buttons: self.w.resetButton = vanilla.Button( (-280-inset, -20-inset, -inset-190, -inset), u"⟲ Reset", sizeStyle='regular', callback=self.SetDefaults ) self.w.resetButton.getNSButton().setToolTip_(u"Resets the contents of the L+R Keys to their (currently only Latin) defaults.") self.w.scanButton = vanilla.Button( (-180-inset, -20-inset, -inset-90, -inset), u"↑ Extract", sizeStyle='regular', callback=self.ScanFontForKeys ) self.w.scanButton.getNSButton().setToolTip_(u"Scans the current font for all metrics keys and lists them here. Normalizes the preceding equals sign (=). No matter whether you typed them with or without an equals sign, they will show up here with one.") self.w.runButton = vanilla.Button( (-80-inset, -20-inset, -inset, -inset), u"↓ Apply", sizeStyle='regular', callback=self.MetricsKeyManagerMain ) self.w.runButton.getNSButton().setToolTip_(u"Parses the current content of the window and will attempt to set the metrics keys of the respective glyphs in the frontmost font.") self.w.setDefaultButton( self.w.runButton ) # Load Settings: if not self.LoadPreferences(): print("Note: 'Metrics Key Manager' could not load preferences. Will resort to defaults") # Bind resizing method: self.w.bind("resize", self.windowResize) # Open window and focus on it: self.w.open() self.w.makeKey() def getMeasurements(self, sender=None): lineHeight = 22 currentWindowHeight = self.w.getPosSize()[3] boxHeight = currentWindowHeight//2 - lineHeight*1.5 return 12, 15, lineHeight, boxHeight def windowResize(self, sender=None): linePos, inset, lineHeight, boxHeight = self.getMeasurements() self.w.LeftMetricsKeysText.setPosSize( (inset, linePos+2, 70, 14) ) self.w.LeftMetricsKeys.setPosSize( (inset+70, linePos, -inset, boxHeight) ) linePos += boxHeight + 10 self.w.RightMetricsKeysText.setPosSize( (inset, linePos+2, 70, 14) ) self.w.RightMetricsKeys.setPosSize( (inset+70, linePos, -inset, boxHeight) ) def SavePreferences( self, sender=None ): try: Glyphs.defaults["com.mekkablue.MetricsKeyManager.LeftMetricsKeys"] = self.w.LeftMetricsKeys.get() Glyphs.defaults["com.mekkablue.MetricsKeyManager.RightMetricsKeys"] = self.w.RightMetricsKeys.get() except: return False return True def LoadPreferences( self ): try: Glyphs.registerDefault("com.mekkablue.MetricsKeyManager.LeftMetricsKeys", LeftKeys) Glyphs.registerDefault("com.mekkablue.MetricsKeyManager.RightMetricsKeys", RightKeys) self.w.LeftMetricsKeys.set( Glyphs.defaults["com.mekkablue.MetricsKeyManager.LeftMetricsKeys"] ) self.w.RightMetricsKeys.set( Glyphs.defaults["com.mekkablue.MetricsKeyManager.RightMetricsKeys"] ) except: return False return True def SetDefaults(self, sender=None): self.w.RightMetricsKeys.set( RightKeys.strip() ) self.w.LeftMetricsKeys.set( LeftKeys.strip() ) # update settings to the latest user input: if not self.SavePreferences( self ): print("Note: 'Metrics Key Manager' could not write preferences.") def parseGlyphNames(self, glyphNameText): possibleChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-_" glyphNames = [] currName = "" for currChar in glyphNameText.strip()+" ": if currChar in possibleChars: currName += currChar else: if currName: glyphNames.append(currName) currName = "" return tuple(glyphNames) def font2dicts(self, font): leftDict, rightDict = {}, {} for glyph in font.glyphs: leftKey = glyph.leftMetricsKey if leftKey: # normalize equals sign: if not leftKey[0] == "=": leftKey = "=%s" % leftKey # create list or append to list: if leftKey not in leftDict: leftDict[leftKey] = [glyph.name,] else: leftDict[leftKey].append(glyph.name) rightKey = glyph.rightMetricsKey if rightKey: # normalize equals sign: if not rightKey[0] == "=": rightKey = "=%s" % rightKey # create list or append to list: if rightKey not in rightDict: rightDict[rightKey] = [glyph.name,] else: rightDict[rightKey].append(glyph.name) return leftDict, rightDict def ScanFontForKeys(self, sender=None, font=None): if not font: font = Glyphs.font if font: leftDict, rightDict = self.font2dicts(font) leftText = self.dict2text(leftDict) rightText = self.dict2text(rightDict) self.w.LeftMetricsKeys.set(leftText) self.w.RightMetricsKeys.set(rightText) self.SavePreferences() def dict2text(self, keyDict): keyText="" for key in sorted(keyDict.keys()): if key: glyphNames = " ".join(keyDict[key]) keyText += "%s: %s\n" % (key, glyphNames) return keyText.strip() def text2dict(self, keyText): parseDict = {} keyText = keyText.strip() for line in keyText.splitlines(): line = line.strip() if line and ":" in line: key, glyphNameText = line.split(":")[:2] parseDict[key] = self.parseGlyphNames( glyphNameText ) return parseDict def MetricsKeyManagerMain( self, sender ): try: # clears macro window log: Glyphs.clearLog() # update settings to the latest user input: if not self.SavePreferences( self ): print("Note: 'Metrics Key Manager' could not write preferences.") thisFont = Glyphs.font # frontmost font if not thisFont: Message(title="Metrics Key Manager Error", message="No font open. Metrics keys can only be applied to the frontmost font.", OKButton=None) else: print("Metrics Key Manager Report for %s" % thisFont.familyName) print(thisFont.filepath) # to be turned into selectable options: # delete all existing keys, respect existing keys, overwrite existing keys respectExistingKeys = False deleteExistingKeys = False includeNonexportingGlyphs = True shouldOpenTabWithAffectedGlyphs = False LeftKeysText = Glyphs.defaults["com.mekkablue.MetricsKeyManager.LeftMetricsKeys"] leftDict = self.text2dict(LeftKeysText) RightKeysText = Glyphs.defaults["com.mekkablue.MetricsKeyManager.RightMetricsKeys"] rightDict = self.text2dict(RightKeysText) dictDict = { "Left": leftDict, "Right": rightDict, } emojis = { "Left": "⬅️", "Right": "➡️", } affectedGlyphs = [] for LorR in dictDict.keys(): print() thisDict = dictDict[LorR] if not LorR in ("Left", "Right"): print("\n😬 Expected key 'Left' or 'Right', but got '%s' instead." % LorR) break else: for key in thisDict.keys(): print("%s Setting %s key %s" % (emojis[LorR], LorR.lower(), key)) glyphNames = thisDict[key] reportGlyphs = [] for glyphName in glyphNames: glyph = thisFont.glyphs[glyphName] if glyph: if LorR=="Left": glyph.leftMetricsKey = key elif LorR=="Right": glyph.rightMetricsKey = key affectedGlyphs.append(glyphName) reportGlyphs.append(glyphName) else: print(" ⚠️ Glyph '%s' not in font. Skipped." % glyphName) if reportGlyphs: print(" ✅ %s" % ", ".join(reportGlyphs)) else: print(" 🤷🏻‍♀️ No glyphs changed.") if affectedGlyphs and shouldOpenTabWithAffectedGlyphs: affectedGlyphs = set(affectedGlyphs) thisFont.newTab( "/"+"/".join(affectedGlyphs) ) except Exception as e: # brings macro window to front and reports error: Glyphs.showMacroWindow() print("Metrics Key Manager Error: %s" % e) import traceback print(traceback.format_exc()) MetricsKeyManager()
35.796429
309
0.693704
ace87c7f0dd2406cbbe68ba346d34f131d1895db
2,581
py
Python
data/p4VQE/R4/benchmark/startQiskit_noisy401.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/p4VQE/R4/benchmark/startQiskit_noisy401.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/p4VQE/R4/benchmark/startQiskit_noisy401.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
# qubit number=3 # total number=14 import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ import networkx as nx from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from qiskit.test.mock import FakeVigo, FakeYorktown kernel = 'circuit/bernstein' def make_circuit(n:int) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") prog = QuantumCircuit(input_qubit) prog.h(input_qubit[0]) # number=1 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.h(input_qubit[3]) # number=4 prog.y(input_qubit[3]) # number=5 for edge in E: k = edge[0] l = edge[1] prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1]) prog.p(gamma, k) prog.p(gamma, l) prog.rx(2 * beta, range(len(V))) prog.swap(input_qubit[1],input_qubit[0]) # number=6 prog.swap(input_qubit[1],input_qubit[0]) # number=7 prog.cx(input_qubit[1],input_qubit[0]) # number=8 prog.h(input_qubit[0]) # number=11 prog.cz(input_qubit[1],input_qubit[0]) # number=12 prog.h(input_qubit[0]) # number=13 prog.h(input_qubit[3]) # number=10 # circuit end return prog if __name__ == '__main__': n = 4 V = np.arange(0, n, 1) E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)] G = nx.Graph() G.add_nodes_from(V) G.add_weighted_edges_from(E) step_size = 0.1 a_gamma = np.arange(0, np.pi, step_size) a_beta = np.arange(0, np.pi, step_size) a_gamma, a_beta = np.meshgrid(a_gamma, a_beta) F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * ( 1 + np.cos(4 * a_gamma) ** 2) result = np.where(F1 == np.amax(F1)) a = list(zip(result[0], result[1]))[0] gamma = a[0] * step_size beta = a[1] * step_size prog = make_circuit(4) sample_shot =5600 writefile = open("../data/startQiskit_noisy401.csv", "w") # prog.draw('mpl', filename=(kernel + '.png')) backend = FakeYorktown() circuit1 = transpile(prog, FakeYorktown()) circuit1.measure_all() prog = circuit1 info = execute(prog,backend=backend, shots=sample_shot).result().get_counts() print(info, file=writefile) print("results end", file=writefile) print(circuit1.depth(), file=writefile) print(circuit1, file=writefile) writefile.close()
27.752688
118
0.634638
ace87d526361443b7c0e278d85daa7737b5c2387
769
py
Python
matplotlib/10.py
lcl1026504480/mfpython
c1b1689a42488129299e31152764c535eb8e66e0
[ "MIT" ]
null
null
null
matplotlib/10.py
lcl1026504480/mfpython
c1b1689a42488129299e31152764c535eb8e66e0
[ "MIT" ]
null
null
null
matplotlib/10.py
lcl1026504480/mfpython
c1b1689a42488129299e31152764c535eb8e66e0
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Fri Oct 9 14:52:47 2020 @author: lenovouser """ import matplotlib.pyplot as plt fig = plt.figure() x = [1, 2, 3, 4, 5, 6, 7] y = [1, 3, 4, 2, 5, 8, 6] # below are all percentage left, bottom, width, height = 0.1, 0.1, 0.8, 0.8 ax1 = fig.add_axes([left, bottom, width, height]) # main axes ax1.plot(x, y, 'r') ax1.set_xlabel('x') ax1.set_ylabel('y') ax1.set_title('title') ax2 = fig.add_axes([0.2, 0.6, 0.25, 0.25]) # inside axes ax2.plot(y, x, 'b') ax2.set_xlabel('x') ax2.set_ylabel('y') ax2.set_title('title inside 1') # different method to add axes #################################### plt.axes([0.6, 0.2, 0.25, 0.25]) plt.plot(y[::-1], x, 'g') plt.xlabel('x') plt.ylabel('y') plt.title('title inside 2') plt.show()
20.236842
62
0.585176
ace87d9a3a640e6f3b5aef07be0b0f836db685f8
9,588
py
Python
main.py
Joker6688/-
ae2a35e584be3eb8176b69c4a7c6fc0b6c9e1109
[ "MIT" ]
null
null
null
main.py
Joker6688/-
ae2a35e584be3eb8176b69c4a7c6fc0b6c9e1109
[ "MIT" ]
null
null
null
main.py
Joker6688/-
ae2a35e584be3eb8176b69c4a7c6fc0b6c9e1109
[ "MIT" ]
null
null
null
import traceback import StellarPlayer import importlib import requests import threading import json import time import inspect import os import sys from bs4 import BeautifulSoup as bs from .sites import match plugin_dir = os.path.dirname(__file__) sys.path.append(plugin_dir) # for js2py class MyPlugin(StellarPlayer.IStellarPlayerPlugin): def __init__(self,player:StellarPlayer.IStellarPlayer): super().__init__(player) self.q = '' self.result = [ ] self.favs = [ ] self.stop_flag = False self.load_favs() self.check_thread = None self.danmu = None self.page_url = '' self.real_url = '' self.danmuShow = True def handleRequest(self, method, args): if method == 'onPlay': print('---------------onPlay') url, = args if self.real_url == url: if self.danmu: self.danmu.stop() self.danmu = None self.danmu = self.create_damnu_client(self.page_url) if self.danmu: self.danmu.start(self.page_url, self.on_danmu) self.danmu.run() elif method == 'onStopPlay': print('---------------onStop') if self.danmu: print('self.danmu.stop') self.danmu.stop() self.danmu = None self.player.clearDanmu() else: print(f'handleRequest {method=} {args=}') def show(self): result_layout = [ [ { 'group': [ {'type':'label','name':'name'}, {'type':'label','name':'url'}, ], 'dir':'vertical', }, {'type':'link','name':'收藏','width':50, '@click': 'on_add_fav_click'}, ] ] favs_layout = [ [ { 'group': [ {'type':'label','name':'name'}, {'type':'label','name':'url'}, ], 'dir':'vertical', }, {'type':'label', 'name':'online', 'width':100}, {'type':'link','name':'播放','width':50, '@click': 'on_play_fav_click'}, {'type':'link','name':'删除','width':50, '@click': 'on_del_fav_click'}, ] ] controls = [ {'type':'space','height':20}, { 'group': [ {'type':'space'}, {'type':'edit','name':'search','height':30, 'width':0.6, 'label': ' ', '@input': 'on_search_input', ':value': 'q'}, {'type':'button','name':'播放', 'height':30, 'width':0.1, '@click': 'on_play_click'}, {'type':'check', 'name':'显示弹幕', '@click': 'on_toggle_danmu_click', ':value': 'danmuShow'}, {'type':'space'}, ], 'height':30 }, {'type':'space', 'height':20}, { 'group': [ {'type':'space'}, { 'group': [ {'type':'list','name':'result', 'height': 48, 'itemheight':48, 'itemlayout': result_layout, ':value': 'result','marginSize':5}, {'type':'space', 'height':10 }, {'type':'label','name': '收藏列表', 'height':30}, {'type':'list','name':'favs', 'itemheight':48, 'itemlayout': favs_layout, ':value': 'favs','marginSize':5, 'separator': True}, ], 'dir':'vertical', 'width': 0.9, }, {'type':'space'} ], 'width': 1.0 } ] if self.check_thread is None: print("create checking thread") self.check_thread = threading.Thread(target=self.check_thread_func, daemon=True) self.check_thread.start() self.player.showDanmu(self.danmuShow) self.doModal('main', 800, 600, '看各种直播门户', controls) def start(self): super().start() def stop(self): self.stop_flag = True super().stop() def check_thread_func(self): last = 0 while not self.stop_flag: time.sleep(0.1) if time.time() - last > 60.0 * 5: # check every 5 minitue last = time.time() print("thread loop") for fav in self.favs: if self.stop_flag: break time.sleep(0.1) print(f"check {fav['url']}") real_url, site = self.get_real_url(fav['url']) print(f"check ret {real_url}") fav['online'] = '在线' if real_url else '离线' self.favs = self.favs def danmu_thread_func(self, url): pass def create_damnu_client(self, url): ret, site = match(url) print(f'create_damnu_client {ret=} {site=}') if ret: danmu = site.get('danmu') if danmu: print(danmu) module_name, attr_name = danmu.rsplit('.', 1) module = importlib.import_module(f'..dmclient.{module_name}', package=__name__) Cls = getattr(module, attr_name) return Cls() return None def get_real_url(self, url): def call_get_real_url(module, ret): if hasattr(module, 'get_real_url'): return module.get_real_url(ret) for name, obj in inspect.getmembers(module): if inspect.isclass(obj): inst = obj(ret) if hasattr(inst, 'get_real_url'): return inst.get_real_url() return False ret, site = match(url) if ret: module_name = site['realurl'] module = importlib.import_module(f'..real-url.{module_name}', package=__name__) try: real_url = call_get_real_url(module, ret) return real_url, site except Exception as e: import traceback traceback.print_exc() return None, None def play(self, url, show_result=False): try: real_url, site = self.get_real_url(url) if not real_url: self.player and self.player.toast('main', '直播不存在或者未开播') return if 'key' in site: if callable(site['key']): real_url = site['key'](real_url) else: print(real_url) real_url = real_url[site['key']] self.player and self.player.toast('main', '在播放器中打开') hasattr(self.player, "clearDanmu") and self.player.clearDanmu() self.player.play(real_url) self.real_url = real_url self.page_url = url if show_result: headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'} r = requests.get(url, headers = headers) if r.status_code == 200: soup = bs(r.content, 'html.parser') title = soup.find('title') self.result = [{ 'name': title.string, 'url': url, 'online': '在线' }] except Exception as e: import traceback traceback.print_exc() def on_danmu(self, message): self.player.addDanmu(message) def on_play_click(self, *args): self.result = [] url = self.q self.play(url, True) def on_play_fav_click(self, page, listControl, item, itemControl): url = self.favs[item]['url'] print(url) self.play(url, False) def on_add_fav_click(self, page, listControl, item, itemControl): if self.result[0] not in self.favs: self.favs = self.favs + self.result self.result = [] self.save_favs() def on_del_fav_click(self, page, listControl, item, itemControl): self.favs.pop(item) self.favs = self.favs self.save_favs() def on_toggle_danmu_click(self, *a): self.player.showDanmu(self.danmuShow) print(f'{a=}, {self.danmuShow=}') def save_favs(self): f = open("favs.json", "w") favs = [] for fav in self.favs: favs.append({ 'name': fav['name'], 'url': fav['url'] }) f.write(json.dumps(favs, indent=4)) f.close() def load_favs(self): try: with open("favs.json") as f: favs = json.loads(f.read()) for fav in favs: fav['online'] = '正在检测' self.favs = favs except FileNotFoundError: pass def newPlugin(player:StellarPlayer.IStellarPlayer,*arg): plugin = MyPlugin(player) return plugin def destroyPlugin(plugin:StellarPlayer.IStellarPlayerPlugin): plugin.stop()
34.120996
184
0.464852
ace87ede8e8d85685f51bc2ae26dda1c6fcc0402
15,227
py
Python
.history/src/Simulador_20200712165348.py
eduardodut/Trabalho_final_estatistica_cd
fbedbbea6bdd7a79e1d62030cde0fab4e93fc338
[ "MIT" ]
null
null
null
.history/src/Simulador_20200712165348.py
eduardodut/Trabalho_final_estatistica_cd
fbedbbea6bdd7a79e1d62030cde0fab4e93fc338
[ "MIT" ]
null
null
null
.history/src/Simulador_20200712165348.py
eduardodut/Trabalho_final_estatistica_cd
fbedbbea6bdd7a79e1d62030cde0fab4e93fc338
[ "MIT" ]
null
null
null
import pandas as pd import numpy as np from Matriz_esferica import Matriz_esferica from Individuo import Individuo, Fabrica_individuo import random from itertools import permutations import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from scipy.sparse import csr_matrix, lil_matrix class Simulador(): SADIO = 0 INFECTADO_TIPO_1 = 1 #assintomáticos e o infectado inicial INFECTADO_TIPO_2 = 2 #sintomático CURADO = 3 MORTO = 4 def __init__( self, tamanho_matriz, #numero de linhas e colunas da matriz esférica percentual_inicial_tipo1, #percentual inicial da população que será infectada tipo 1 percentual_inicial_tipo2, #percentual inicial da população que será infectada tipo 2 chance_infeccao, #chance que um infectado tipo 2 tem de infectar um indivíduo saudável chance_infeccao_tipo2, #chance de um indivíduo infectado se tornar contagioso chance_morte, #chance de um indivíduo tipo 2 morrer ao fim de uma atualização atualizacoes_cura): #número de atualizações necessárias para a cura de um indivíduo tipo 1 ou 2 self.num_atualizacoes = 0 self.lista_infectados_tipo_2 = [] self.lista_infectados_tipo_1 = [] self.num_curados = 0 self.num_mortos = 0 self.chance_infeccao = chance_infeccao self.chance_infeccao_tipo2 = chance_infeccao_tipo2 self.chance_morte = chance_morte self.atualizacoes_cura = atualizacoes_cura self.populacao_inicial = int(tamanho_matriz**2) self.num_inicial_tipo2 = int(self.populacao_inicial * percentual_inicial_tipo2) self.num_inicial_tipo1 = 1 + int(self.populacao_inicial * percentual_inicial_tipo1) self.num_inicial_sadios = self.populacao_inicial - (self.num_inicial_tipo2 + self.num_inicial_tipo1) self.matriz_status =lil_matrix((tamanho_matriz, tamanho_matriz),dtype= np.uint8) # np.zeros((tamanho_matriz, tamanho_matriz),dtype= np.uint8)# self.matriz_atualizacoes_cura = lil_matrix((tamanho_matriz, tamanho_matriz),dtype= np.uint8)#np.zeros((tamanho_matriz, tamanho_matriz),dtype= np.uint8)# #self.matriz_status = self.df_individuos.to_numpy() self.popular(tamanho_matriz) self.lista_matrizes_status = [] #objeto que é responsável por validar a movimentação no grid n x n self.matriz_esferica = Matriz_esferica(tamanho_matriz) dict = { 'num_sadios':self.num_inicial_sadios, 'num_infect_t1':self.num_inicial_tipo1, 'num_infect_t2':self.num_inicial_tipo2, 'num_curados':0, 'num_mortos':0} #dataframe que guardará os resultados de cada atualização self.dataframe = pd.DataFrame(dict,index = [0]) self.salvar_posicionamento() def criar_individuo(self, status, posicao): self.matriz_status[posicao[0], posicao[1]] = status if status == self.INFECTADO_TIPO_1 or status == self.INFECTADO_TIPO_2: self.matriz_atualizacoes_cura[posicao[0], posicao[1]] = self.atualizacoes_cura else: self.matriz_atualizacoes_cura[posicao[0], posicao[1]] = 0 def salvar_posicionamento(self): self.lista_matrizes_status.append(self.matriz_status) def verificar_infeccao(self, lista_infectantes): lista_novos_infectados_tipo1 = [] lista_novos_infectados_tipo2 = [] #itera sobre sobre a lista de individuos que infectam e cada um realiza a tividade de infectar for indice_infectante in lista_infectantes: #busca os vizinhos do infectante atual lista_vizinhos = self.matriz_esferica.get_vizinhos(indice_infectante) #Para cada vizinho, se ele for sadio, é gerado um número aleatório para verificar se foi infectado for indice_vizinho in lista_vizinhos: #verificação de SADIO if self.verifica_status(indice_vizinho) == self.SADIO: #verificação do novo status novo_status = self.infectar(chance_infeccao, chance_infeccao_tipo2) #se for um infectado tipo 1 if novo_status == Individuo.INFECTADO_TIPO_1: #adiciona na lista de novos tipo 1 lista_novos_infectados_tipo1.append(indice_vizinho) if novo_status == Individuo.INFECTADO_TIPO_2: #adiciona na lista de novos tipo 2 lista_novos_infectados_tipo2.append(indice_vizinho) return lista_novos_infectados_tipo1, lista_novos_infectados_tipo2 def checagem_morte_individual(self, chance_morte): rng_morte = random.random() if rng_morte <= chance_morte: return self.MORTO else: return self.INFECTADO_TIPO_2 def checar_cura_individual(self, indice): self.matriz_atualizacoes_cura[indice[0], indice[1]] = self.matriz_atualizacoes_cura[indice[0], indice[1]] - 1 if self.matriz_atualizacoes_cura[indice[0], indice[1]] == 0: return self.CURADO else: return self.matriz_status[indice[0], indice[1]] def checagem_morte_lista(self, lista_infectantes): lista_mortos = [] for indice_infectante in lista_infectantes: novo_status = self.checagem_morte_individual(self.chance_morte) if novo_status == Individuo.MORTO: lista_mortos.append(indice_infectante) return lista_mortos def checagem_cura_lista(self, lista_infectantes): lista_curados = [] for indice_infectante in lista_infectantes: novo_status = self.checar_cura_individual(indice_infectante) if novo_status == Individuo.CURADO: lista_curados.append(indice_infectante) return lista_curados def iterar(self): #Verifica os novos infectados por infectantes do tipo 1 e 2 #print(self.lista_infectados_tipo_1+self.lista_infectados_tipo_2) lista_novos_infectados_tipo1, lista_novos_infectados_tipo2 = self.verificar_infeccao(self.lista_infectados_tipo_1+self.lista_infectados_tipo_2) for indice in lista_novos_infectados_tipo1: self.criar_individuo(self.INFECTADO_TIPO_1, indice) for indice in lista_novos_infectados_tipo2: self.criar_individuo(self.INFECTADO_TIPO_2, indice) #Verifica morte dos infectados tipo 2 lista_mortos = self.checagem_morte_lista(self.lista_infectados_tipo_2) #retira os indices dos individuos mortos da lista de infectados self.lista_infectados_tipo_2 = [indice for indice in self.lista_infectados_tipo_2 if indice not in lista_mortos] #Instancia individuos mortos na matriz for indice in lista_mortos: self.criar_individuo(self.MORTO, indice) #atualiza o número de mortos na matriz self.num_mortos = self.num_mortos + len(lista_mortos) #Verifica cura dos infectados tipo 1 lista_curados_t1 = self.checagem_cura_lista(self.lista_infectados_tipo_1) #Verifica cura dos infectados tipo 2 lista_curados_t2 = self.checagem_cura_lista(self.lista_infectados_tipo_2 ) #Instancia individuos mortos na matriz for indice in lista_curados_t1+lista_curados_t2: self.criar_individuo(self.CURADO, indice) #atualiza o número de curados na matriz self.num_curados = self.num_curados + len(lista_curados_t1 + lista_curados_t2) #Atualiza a lista de infectados após a cura dos individuos self.lista_infectados_tipo_1 = [indice for indice in self.lista_infectados_tipo_1 if indice not in lista_curados_t1] self.lista_infectados_tipo_2 = [indice for indice in self.lista_infectados_tipo_2 if indice not in lista_curados_t2] #movimentação nova_lista_t1 = [] for indice in self.lista_infectados_tipo_1: nova_lista_t1.append(self.mover_infectante(indice)) self.lista_infectados_tipo_1 = nova_lista_t1 print(self.lista_infectados_tipo_1) nova_lista_t2 = [] for indice in self.lista_infectados_tipo_2: nova_lista_t2.append(self.mover_infectante(indice)) self.lista_infectados_tipo_2 = nova_lista_t2 print(self.lista_infectados_tipo_2) # matriz_infectantes = matriz_infectantes[matriz_infectantes < 3] indices_infectados = list(zip(*self.matriz_status.nonzero())) indices_infectados = [indice for indice in indices_infectados if indice not in self.lista_infectados_tipo_1 + self.lista_infectados_tipo_2 + lista_curados_t1 +lista_curados_t2 + lista_mortos] # self.num_curados = 0 #self.num_mortos = 0 # self.lista_infectados_tipo_1 = [] # self.lista_infectados_tipo_2 = [] novos_t1 = [] novos_t2 = [] for indice in indices_infectados: # if indice not in self.lista_infectados_tipo_1 and indice not in self.lista_infectados_tipo_2: print(indice) print(self.matriz_status.shape) status = self.matriz_status[indice[0], indice[1]] if status == self.INFECTADO_TIPO_1: #self.lista_infectados_tipo_1.append(indice) novos_t1.append(indice) if status == self.INFECTADO_TIPO_2: #self.lista_infectados_tipo_2.append(indice) novos_t2.append(indice) # if status == self.CURADO: # self.num_curados +=1 # if status == self.MORTO: # self.num_mortos +=1 self.lista_infectados_tipo_1 = self.lista_infectados_tipo_1 + novos_t1 self.lista_infectados_tipo_2 = self.lista_infectados_tipo_2 + novos_t2 dict = {'num_sadios': self.populacao_inicial - len(self.lista_infectados_tipo_1) -len(self.lista_infectados_tipo_2) -self.num_curados-self.num_mortos, 'num_infect_t1': len(self.lista_infectados_tipo_1), 'num_infect_t2': len(self.lista_infectados_tipo_2), 'num_curados': self.num_curados, 'num_mortos': self.num_mortos} self.dataframe = self.dataframe.append(dict, ignore_index=True) self.salvar_posicionamento() #adiciona 1 ao número de atualizações realizadas na matriz self.num_atualizacoes +=1 def infectar(self, chance_infeccao, chance_infeccao_tipo2): saida = Individuo.SADIO #número aleatório para chance de infectar o vizinho rng_infeccao = random.random() if rng_infeccao <= chance_infeccao: #número aleatório para chance de infecção tipo 1 ou 2 rng_infeccao_tipo2 = random.random() if rng_infeccao_tipo2 <= chance_infeccao_tipo2: saida = Individuo.INFECTADO_TIPO_2 else: saida = Individuo.INFECTADO_TIPO_1 return saida def popular(self, tamanho_matriz): #lista de possíveis combinações de índices da matriz de dados permutacoes = permutations(list(range(tamanho_matriz)),2) #conversão para lista de tuplas(x,y) lista_indices = list(permutacoes) #embaralhamento dos índices random.shuffle(lista_indices) #cria o primeiro tipo1: indice = lista_indices.pop() self.criar_individuo(Individuo.INFECTADO_TIPO_1, indice) self.lista_infectados_tipo_1.append(indice) #cria o restante dos tipos 1 for i in range(self.num_inicial_tipo1-1): indice = lista_indices.pop() self.criar_individuo(Individuo.INFECTADO_TIPO_1,indice) self.lista_infectados_tipo_1.append(indice) #cria o restante dos tipo 2: for indice in range(self.num_inicial_tipo2): indice = lista_indices.pop() self.criar_individuo(Individuo.INFECTADO_TIPO_2,indice) self.lista_infectados_tipo_2.append(indice) def trocar(self,matriz,ponto_ini,ponto_final): x_ini = ponto_ini[0] y_ini = ponto_ini[1] x_fin = ponto_final[0] y_fin = ponto_final[1] aux = matriz[x_fin,y_fin] matriz[x_fin,y_fin] = matriz[x_ini,y_ini] matriz[x_ini,y_ini] = aux def verifica_status(self, indice): return self.matriz_status[indice[0], indice[1]] def mover_infectante(self, posicao_inicial): pos_x, pos_y = posicao_inicial[0], posicao_inicial[1] rng_posicao = random.random() if rng_posicao <=0.25: #move pra cima pos_x -= 1 elif rng_posicao <=0.5: #move pra baixo pos_x += 1 elif rng_posicao <=0.75: #move para esquerda pos_y -= 1 else: #move para direita pos_y += 1 posicao_final= self.matriz_esferica.valida_ponto_matriz(pos_x, pos_y) self.trocar(self.matriz_status, posicao_inicial, posicao_final) self.trocar(self.matriz_atualizacoes_cura, posicao_inicial, posicao_final) return posicao_final proporcao_inicial_infectados = random.random() proporcao_t1 = random.random() chance_infeccao = 0.3 chance_infeccao_tipo2 = 0.2 chance_morte = 0.5 atualizacoes_cura = 10 percentual_inicial_tipo1 = 0#proporcao_t1*proporcao_inicial_infectados percentual_inicial_tipo2 = 0#(1-proporcao_t1)*proporcao_inicial_infectados #print("% inicial t1: ",percentual_inicial_tipo1) #print("% inicial t2: ",percentual_inicial_tipo2) sim = Simulador( 5, percentual_inicial_tipo1, percentual_inicial_tipo2, chance_infeccao, chance_infeccao_tipo2, chance_morte,atualizacoes_cura) #print(sim.lista_matrizes_posicionamento[0]) #print(sim.lista_infectados_tipo_2) #print(sim.lista_infectados_tipo_1) cmap = ListedColormap(['w', 'y', 'r', 'blue', 'black']) while (sim.dataframe.iloc[-1]['num_infect_t1']+sim.dataframe.iloc[-1]['num_infect_t2']) > 0: #plt.matshow(sim.matriz_status.toarray(), cmap = cmap, vmin= 0, vmax = 4) # print(sim.dataframe.iloc[-1]) sim.iterar() # print(sim.num_atualizacoes) #print("xxxxxxxxxxxxxxxxxTipo: ",type(sim.lista_matrizes_posicionamento[len(sim.lista_matrizes_posicionamento)-1].toarray())) #plt.matshow(sim.matriz_status.toarray(), cmap = cmap, vmin= 0, vmax = 4) print(sim.dataframe) plt.show() # for i in range(30): # #plt.matshow(sim.lista_matrizes_status[i].toarray(), cmap = cmap, vmin= 0, vmax = 4) # sim.iterar() # print(sim.dataframe) # plt.show()
40.713904
199
0.6564
ace87f98f303abb873200c8e485dea739772c6b4
291
py
Python
setup.py
dougollerenshaw/drive_profiler
29dd9c46c90a7319d08c898a1dfaba07519f3d76
[ "MIT" ]
null
null
null
setup.py
dougollerenshaw/drive_profiler
29dd9c46c90a7319d08c898a1dfaba07519f3d76
[ "MIT" ]
null
null
null
setup.py
dougollerenshaw/drive_profiler
29dd9c46c90a7319d08c898a1dfaba07519f3d76
[ "MIT" ]
null
null
null
import setuptools setuptools.setup( name="drive_profiler", version="0.1", author="Doug Ollerenshaw", author_email="dougo@alleninstitute.org or d.ollerenshaw@gmail.com", description="python drive profiler", install_requires=[ "pandas", "click" ] )
22.384615
71
0.659794
ace87fbf03884820854b0f2e52abf0e65fd0d70b
933
py
Python
light_scores/normalize.py
ffreemt/light-scores
1796ea59ce78790c9bcfd24eda7e07a862d3ce48
[ "MIT" ]
null
null
null
light_scores/normalize.py
ffreemt/light-scores
1796ea59ce78790c9bcfd24eda7e07a862d3ce48
[ "MIT" ]
null
null
null
light_scores/normalize.py
ffreemt/light-scores
1796ea59ce78790c9bcfd24eda7e07a862d3ce48
[ "MIT" ]
null
null
null
"""Lemmatize nltk pos tag to wodnet tag.""" from typing import List import nltk from nltk.stem import WordNetLemmatizer from nltk.corpus import wordnet lemmatizer = WordNetLemmatizer() def convert_tag(tag: str) -> str: """Convert nltk pos tag to wodnet tag.""" res = tag[0].lower() if res in ["j"]: res = "a" if res not in ["a", "v", "n", "r"]: res = "n" return res def normalize(text: str) -> List[str]: """Lemmatize text. [lemmatize(word, convert_tag(tag)) for word, tag in pos_tag(word_tokenize(text))] 20s/1000 lines shakespeare 3min 35s 210s/lines shakespeare >>> text = 'I am loving it' >>> normalize('I am loving it')[1] in ["be"] True """ words = nltk.word_tokenize(text) tagged = nltk.pos_tag(words) res = [] for word, tag in tagged: _ = convert_tag(tag) res.append(lemmatizer.lemmatize(word, _)) return res
21.697674
85
0.614148
ace880c68c8ef4b276bc9e200b6c801f3ac4c97d
5,407
py
Python
modelci/hub/profile_.py
univerone/ML-Model-CI
f77635e469477b640a5c2d9b7ad3fe13374ce59e
[ "Apache-2.0" ]
170
2020-06-08T18:30:52.000Z
2022-03-28T12:08:11.000Z
modelci/hub/profile_.py
crazyCoderLi/ML-Model-CI
f77635e469477b640a5c2d9b7ad3fe13374ce59e
[ "Apache-2.0" ]
146
2020-06-14T18:56:27.000Z
2022-02-27T21:15:59.000Z
modelci/hub/profile_.py
univerone/ML-Model-CI
f77635e469477b640a5c2d9b7ad3fe13374ce59e
[ "Apache-2.0" ]
36
2020-06-08T18:30:56.000Z
2022-03-07T18:10:19.000Z
import os import random import time from pathlib import Path import docker from modelci.hub.client import CVTFSClient, CVTorchClient, CVONNXClient, CVTRTClient from modelci.metrics.benchmark.metric import BaseModelInspector from modelci.persistence.exceptions import ServiceException from modelci.types.models.mlmodel import MLModel, Engine from modelci.types.models.profile_results import DynamicProfileResult, ProfileMemory, ProfileThroughput, ProfileLatency from modelci.utils import Logger from modelci.utils.misc import get_ip from modelci.hub.deployer.dispatcher import serve DEFAULT_BATCH_NUM = 100 random.seed(ord(os.urandom(1))) logger = Logger(__name__, welcome=False) class Profiler(object): """Profiler class, call this to test model performance. Args: model_info (MLModel): Information about the model, can get from `retrieve_model` method. inspector (BaseModelInspector): The client instance implemented from :class:`BaseModelInspector`. """ def __init__(self, model_info: MLModel, inspector: BaseModelInspector = None): """Init a profiler object.""" self.model = model_info self.docker_client = docker.from_env() if inspector is None: self.inspector = self.__auto_select_client() # TODO: To Improve else: if isinstance(inspector, BaseModelInspector): self.inspector = inspector else: raise TypeError("The inspector should be an instance of class BaseModelInspector!") def pre_deploy(self, device='cuda'): container_list = self.docker_client.containers.list( filters={'ancestor': f"mlmodelci/{str(self.model.framework).lower().split('.')[1]}-serving:latest"} ) if not container_list: container = serve(self.model.saved_path, device=device, name=f'{self.model.engine}-profiler') print(f"Container:{container.name} is now serving.") return container.name else: print(f"Container:{container_list[0].name} is already serving.") return container_list[0].name def diagnose(self, server_name: str, batch_size: int = None, device='cuda', timeout=30) -> DynamicProfileResult: """Start diagnosing and profiling model. Args: server_name (str): to assign a name for the container you are creating for model profile batch_size (int): Batch size. device (str): Device name. timeout (float): Waiting for docker container timeout in second. Default timeout period is 30s. """ # Check server status model_status = False retry_time = 0 # use binary exponential backoff algorithm tick = time.time() while time.time() - tick < timeout: if self.inspector.check_model_status(): model_status = True break retry_time += 1 # get backoff time in s backoff_time = random.randint(0, 2 ** retry_time - 1) * 1e-3 time.sleep(backoff_time) if not model_status: # raise an error as model is not served. raise ServiceException('Model not served!') if batch_size is not None: self.inspector.set_batch_size(batch_size) result = self.inspector.run_model(server_name=server_name, device=device) dpr = DynamicProfileResult( device_id=result['device_id'], device_name=result['device_name'], batch=result['batch_size'], memory=ProfileMemory( total_memory=result['total_gpu_memory'], memory_usage=result['gpu_memory_used'], utilization=result['gpu_utilization'], ), latency=ProfileLatency( inference_latency=result['latency'], ), throughput=ProfileThroughput(inference_throughput=result['total_throughput']), ip=get_ip(), create_time=result['completed_time'], ) return dpr def __auto_select_client(self): import cv2 import modelci.hub.client as client # according to the serving engine, select the right testing client. # TODO: replace the input None data in each client with self-generated data. serving_engine = self.model.engine if serving_engine == Engine.NONE: raise Exception( 'please choose a serving engine for the model') # TODO How can we deploy to all available platforms if we don't know the engine? img_dir = Path(client.__file__).parent / 'data/cat.jpg' img = cv2.imread(str(img_dir)) kwargs = {'repeat_data': img, 'model_info': self.model, 'batch_num': DEFAULT_BATCH_NUM} if serving_engine == Engine.TFS: return CVTFSClient(**kwargs) elif serving_engine == Engine.TORCHSCRIPT: return CVTorchClient(**kwargs) elif serving_engine == Engine.ONNX: return CVONNXClient(**kwargs) elif serving_engine == Engine.TRT: return CVTRTClient(**kwargs) elif serving_engine == Engine.TVM: raise NotImplementedError elif serving_engine == Engine.CUSTOMIZED: raise Exception('please pass a custom client to the Profiler.__init__.') else: return None
41.274809
119
0.648419
ace8822582677c2951d14ad24093c66b681f2cba
47,377
py
Python
rllib/agents/trainer.py
romilbhardwaj/ray
e261b4778e18e4d7360c9241f81ef034d5c3c548
[ "Apache-2.0" ]
null
null
null
rllib/agents/trainer.py
romilbhardwaj/ray
e261b4778e18e4d7360c9241f81ef034d5c3c548
[ "Apache-2.0" ]
2
2022-01-13T04:15:38.000Z
2022-03-12T01:03:35.000Z
rllib/agents/trainer.py
romilbhardwaj/ray
e261b4778e18e4d7360c9241f81ef034d5c3c548
[ "Apache-2.0" ]
null
null
null
from datetime import datetime import copy import logging import math import os import pickle import time import tempfile import ray from ray.exceptions import RayError from ray.rllib.agents.callbacks import DefaultCallbacks from ray.rllib.models import MODEL_DEFAULTS from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID from ray.rllib.evaluation.metrics import collect_metrics from ray.rllib.optimizers.policy_optimizer import PolicyOptimizer from ray.rllib.evaluation.worker_set import WorkerSet from ray.rllib.utils import FilterManager, deep_update, merge_dicts, \ try_import_tf from ray.rllib.utils.annotations import override, PublicAPI, DeveloperAPI from ray.rllib.utils.memory import ray_get_and_free from ray.tune.registry import ENV_CREATOR, register_env, _global_registry from ray.tune.trainable import Trainable from ray.tune.trial import ExportFormat from ray.tune.resources import Resources from ray.tune.logger import UnifiedLogger from ray.tune.result import DEFAULT_RESULTS_DIR from ray.rllib.env.normalize_actions import NormalizeActionWrapper from ray.rllib.utils.deprecation import DEPRECATED_VALUE, deprecation_warning tf = try_import_tf() logger = logging.getLogger(__name__) # Max number of times to retry a worker failure. We shouldn't try too many # times in a row since that would indicate a persistent cluster issue. MAX_WORKER_FAILURE_RETRIES = 3 # yapf: disable # __sphinx_doc_begin__ COMMON_CONFIG = { # === Settings for Rollout Worker processes === # Number of rollout worker actors to create for parallel sampling. Setting # this to 0 will force rollouts to be done in the trainer actor. "num_workers": 2, # Number of environments to evaluate vectorwise per worker. This enables # model inference batching, which can improve performance for inference # bottlenecked workloads. "num_envs_per_worker": 1, # Divide episodes into fragments of this many steps each during rollouts. # Sample batches of this size are collected from rollout workers and # combined into a larger batch of `train_batch_size` for learning. # # For example, given rollout_fragment_length=100 and train_batch_size=1000: # 1. RLlib collects 10 fragments of 100 steps each from rollout workers. # 2. These fragments are concatenated and we perform an epoch of SGD. # # When using multiple envs per worker, the fragment size is multiplied by # `num_envs_per_worker`. This is since we are collecting steps from # multiple envs in parallel. For example, if num_envs_per_worker=5, then # rollout workers will return experiences in chunks of 5*100 = 500 steps. # # The dataflow here can vary per algorithm. For example, PPO further # divides the train batch into minibatches for multi-epoch SGD. "rollout_fragment_length": 200, # Deprecated; renamed to `rollout_fragment_length` in 0.8.4. "sample_batch_size": DEPRECATED_VALUE, # Whether to rollout "complete_episodes" or "truncate_episodes" to # `rollout_fragment_length` length unrolls. Episode truncation guarantees # evenly sized batches, but increases variance as the reward-to-go will # need to be estimated at truncation boundaries. "batch_mode": "truncate_episodes", # === Settings for the Trainer process === # Number of GPUs to allocate to the trainer process. Note that not all # algorithms can take advantage of trainer GPUs. This can be fractional # (e.g., 0.3 GPUs). "num_gpus": 0, # Training batch size, if applicable. Should be >= rollout_fragment_length. # Samples batches will be concatenated together to a batch of this size, # which is then passed to SGD. "train_batch_size": 200, # Arguments to pass to the policy model. See models/catalog.py for a full # list of the available model options. "model": MODEL_DEFAULTS, # Arguments to pass to the policy optimizer. These vary by optimizer. "optimizer": {}, # === Environment Settings === # Discount factor of the MDP. "gamma": 0.99, # Number of steps after which the episode is forced to terminate. Defaults # to `env.spec.max_episode_steps` (if present) for Gym envs. "horizon": None, # Calculate rewards but don't reset the environment when the horizon is # hit. This allows value estimation and RNN state to span across logical # episodes denoted by horizon. This only has an effect if horizon != inf. "soft_horizon": False, # Don't set 'done' at the end of the episode. Note that you still need to # set this if soft_horizon=True, unless your env is actually running # forever without returning done=True. "no_done_at_end": False, # Arguments to pass to the env creator. "env_config": {}, # Environment name can also be passed via config. "env": None, # Unsquash actions to the upper and lower bounds of env's action space "normalize_actions": False, # Whether to clip rewards prior to experience postprocessing. Setting to # None means clip for Atari only. "clip_rewards": None, # Whether to np.clip() actions to the action space low/high range spec. "clip_actions": True, # Whether to use rllib or deepmind preprocessors by default "preprocessor_pref": "deepmind", # The default learning rate. "lr": 0.0001, # === Debug Settings === # Whether to write episode stats and videos to the agent log dir. This is # typically located in ~/ray_results. "monitor": False, # Set the ray.rllib.* log level for the agent process and its workers. # Should be one of DEBUG, INFO, WARN, or ERROR. The DEBUG level will also # periodically print out summaries of relevant internal dataflow (this is # also printed out once at startup at the INFO level). When using the # `rllib train` command, you can also use the `-v` and `-vv` flags as # shorthand for INFO and DEBUG. "log_level": "WARN", # Callbacks that will be run during various phases of training. See the # `DefaultCallbacks` class and `examples/custom_metrics_and_callbacks.py` # for more usage information. "callbacks": DefaultCallbacks, # Whether to attempt to continue training if a worker crashes. The number # of currently healthy workers is reported as the "num_healthy_workers" # metric. "ignore_worker_failures": False, # Log system resource metrics to results. This requires `psutil` to be # installed for sys stats, and `gputil` for GPU metrics. "log_sys_usage": True, # Use fake (infinite speed) sampler. For testing only. "fake_sampler": False, # === Framework Settings === # Use PyTorch (instead of tf). If using `rllib train`, this can also be # enabled with the `--torch` flag. # NOTE: Some agents may not support `torch` yet and throw an error. "use_pytorch": False, # Enable TF eager execution (TF policies only). If using `rllib train`, # this can also be enabled with the `--eager` flag. "eager": False, # Enable tracing in eager mode. This greatly improves performance, but # makes it slightly harder to debug since Python code won't be evaluated # after the initial eager pass. "eager_tracing": False, # Disable eager execution on workers (but allow it on the driver). This # only has an effect if eager is enabled. "no_eager_on_workers": False, # === Exploration Settings === # Default exploration behavior, iff `explore`=None is passed into # compute_action(s). # Set to False for no exploration behavior (e.g., for evaluation). "explore": True, # Provide a dict specifying the Exploration object's config. "exploration_config": { # The Exploration class to use. In the simplest case, this is the name # (str) of any class present in the `rllib.utils.exploration` package. # You can also provide the python class directly or the full location # of your class (e.g. "ray.rllib.utils.exploration.epsilon_greedy. # EpsilonGreedy"). "type": "StochasticSampling", # Add constructor kwargs here (if any). }, # === Evaluation Settings === # Evaluate with every `evaluation_interval` training iterations. # The evaluation stats will be reported under the "evaluation" metric key. # Note that evaluation is currently not parallelized, and that for Ape-X # metrics are already only reported for the lowest epsilon workers. "evaluation_interval": None, # Number of episodes to run per evaluation period. If using multiple # evaluation workers, we will run at least this many episodes total. "evaluation_num_episodes": 10, # Internal flag that is set to True for evaluation workers. "in_evaluation": False, # Typical usage is to pass extra args to evaluation env creator # and to disable exploration by computing deterministic actions. # IMPORTANT NOTE: Policy gradient algorithms are able to find the optimal # policy, even if this is a stochastic one. Setting "explore=False" here # will result in the evaluation workers not using this optimal policy! "evaluation_config": { # Example: overriding env_config, exploration, etc: # "env_config": {...}, # "explore": False }, # Number of parallel workers to use for evaluation. Note that this is set # to zero by default, which means evaluation will be run in the trainer # process. If you increase this, it will increase the Ray resource usage # of the trainer since evaluation workers are created separately from # rollout workers. "evaluation_num_workers": 0, # Customize the evaluation method. This must be a function of signature # (trainer: Trainer, eval_workers: WorkerSet) -> metrics: dict. See the # Trainer._evaluate() method to see the default implementation. The # trainer guarantees all eval workers have the latest policy state before # this function is called. "custom_eval_function": None, # EXPERIMENTAL: use the execution plan based API impl of the algo. Can also # be enabled by setting RLLIB_EXEC_API=1. "use_exec_api": True, # === Advanced Rollout Settings === # Use a background thread for sampling (slightly off-policy, usually not # advisable to turn on unless your env specifically requires it). "sample_async": False, # Element-wise observation filter, either "NoFilter" or "MeanStdFilter". "observation_filter": "NoFilter", # Whether to synchronize the statistics of remote filters. "synchronize_filters": True, # Configures TF for single-process operation by default. "tf_session_args": { # note: overriden by `local_tf_session_args` "intra_op_parallelism_threads": 2, "inter_op_parallelism_threads": 2, "gpu_options": { "allow_growth": True, }, "log_device_placement": False, "device_count": { "CPU": 1 }, "allow_soft_placement": True, # required by PPO multi-gpu }, # Override the following tf session args on the local worker "local_tf_session_args": { # Allow a higher level of parallelism by default, but not unlimited # since that can cause crashes with many concurrent drivers. "intra_op_parallelism_threads": 8, "inter_op_parallelism_threads": 8, }, # Whether to LZ4 compress individual observations "compress_observations": False, # Wait for metric batches for at most this many seconds. Those that # have not returned in time will be collected in the next train iteration. "collect_metrics_timeout": 180, # Smooth metrics over this many episodes. "metrics_smoothing_episodes": 100, # If using num_envs_per_worker > 1, whether to create those new envs in # remote processes instead of in the same worker. This adds overheads, but # can make sense if your envs can take much time to step / reset # (e.g., for StarCraft). Use this cautiously; overheads are significant. "remote_worker_envs": False, # Timeout that remote workers are waiting when polling environments. # 0 (continue when at least one env is ready) is a reasonable default, # but optimal value could be obtained by measuring your environment # step / reset and model inference perf. "remote_env_batch_wait_ms": 0, # Minimum time per train iteration (frequency of metrics reporting). "min_iter_time_s": 0, # Minimum env steps to optimize for per train call. This value does # not affect learning, only the length of train iterations. "timesteps_per_iteration": 0, # This argument, in conjunction with worker_index, sets the random seed of # each worker, so that identically configured trials will have identical # results. This makes experiments reproducible. "seed": None, # Any extra python env vars to set in the trainer process, e.g., # {"OMP_NUM_THREADS": "16"} "extra_python_environs_for_driver": {}, # The extra python environments need to set for worker processes. "extra_python_environs_for_worker": {}, # === Advanced Resource Settings === # Number of CPUs to allocate per worker. "num_cpus_per_worker": 1, # Number of GPUs to allocate per worker. This can be fractional. This is # usually needed only if your env itself requires a GPU (i.e., it is a # GPU-intensive video game), or model inference is unusually expensive. "num_gpus_per_worker": 0, # Any custom Ray resources to allocate per worker. "custom_resources_per_worker": {}, # Number of CPUs to allocate for the trainer. Note: this only takes effect # when running in Tune. Otherwise, the trainer runs in the main program. "num_cpus_for_driver": 1, # You can set these memory quotas to tell Ray to reserve memory for your # training run. This guarantees predictable execution, but the tradeoff is # if your workload exceeeds the memory quota it will fail. # Heap memory to reserve for the trainer process (0 for unlimited). This # can be large if your are using large train batches, replay buffers, etc. "memory": 0, # Object store memory to reserve for the trainer process. Being large # enough to fit a few copies of the model weights should be sufficient. # This is enabled by default since models are typically quite small. "object_store_memory": 0, # Heap memory to reserve for each worker. Should generally be small unless # your environment is very heavyweight. "memory_per_worker": 0, # Object store memory to reserve for each worker. This only needs to be # large enough to fit a few sample batches at a time. This is enabled # by default since it almost never needs to be larger than ~200MB. "object_store_memory_per_worker": 0, # === Offline Datasets === # Specify how to generate experiences: # - "sampler": generate experiences via online simulation (default) # - a local directory or file glob expression (e.g., "/tmp/*.json") # - a list of individual file paths/URIs (e.g., ["/tmp/1.json", # "s3://bucket/2.json"]) # - a dict with string keys and sampling probabilities as values (e.g., # {"sampler": 0.4, "/tmp/*.json": 0.4, "s3://bucket/expert.json": 0.2}). # - a function that returns a rllib.offline.InputReader "input": "sampler", # Specify how to evaluate the current policy. This only has an effect when # reading offline experiences. Available options: # - "wis": the weighted step-wise importance sampling estimator. # - "is": the step-wise importance sampling estimator. # - "simulation": run the environment in the background, but use # this data for evaluation only and not for learning. "input_evaluation": ["is", "wis"], # Whether to run postprocess_trajectory() on the trajectory fragments from # offline inputs. Note that postprocessing will be done using the *current* # policy, not the *behavior* policy, which is typically undesirable for # on-policy algorithms. "postprocess_inputs": False, # If positive, input batches will be shuffled via a sliding window buffer # of this number of batches. Use this if the input data is not in random # enough order. Input is delayed until the shuffle buffer is filled. "shuffle_buffer_size": 0, # Specify where experiences should be saved: # - None: don't save any experiences # - "logdir" to save to the agent log dir # - a path/URI to save to a custom output directory (e.g., "s3://bucket/") # - a function that returns a rllib.offline.OutputWriter "output": None, # What sample batch columns to LZ4 compress in the output data. "output_compress_columns": ["obs", "new_obs"], # Max output file size before rolling over to a new file. "output_max_file_size": 64 * 1024 * 1024, # === Settings for Multi-Agent Environments === "multiagent": { # Map from policy ids to tuples of (policy_cls, obs_space, # act_space, config). See rollout_worker.py for more info. "policies": {}, # Function mapping agent ids to policy ids. "policy_mapping_fn": None, # Optional whitelist of policies to train, or None for all policies. "policies_to_train": None, # Optional function that can be used to enhance the local agent # observations to include more state. # See rllib/evaluation/observation_function.py for more info. "observation_fn": None, }, } # __sphinx_doc_end__ # yapf: enable @DeveloperAPI def with_common_config(extra_config): """Returns the given config dict merged with common agent confs.""" return with_base_config(COMMON_CONFIG, extra_config) def with_base_config(base_config, extra_config): """Returns the given config dict merged with a base agent conf.""" config = copy.deepcopy(base_config) config.update(extra_config) return config @PublicAPI class Trainer(Trainable): """A trainer coordinates the optimization of one or more RL policies. All RLlib trainers extend this base class, e.g., the A3CTrainer implements the A3C algorithm for single and multi-agent training. Trainer objects retain internal model state between calls to train(), so you should create a new trainer instance for each training session. Attributes: env_creator (func): Function that creates a new training env. config (obj): Algorithm-specific configuration data. logdir (str): Directory in which training outputs should be placed. """ # Whether to allow unknown top-level config keys. _allow_unknown_configs = False # List of top-level keys with value=dict, for which new sub-keys are # allowed to be added to the value dict. _allow_unknown_subkeys = [ "tf_session_args", "local_tf_session_args", "env_config", "model", "optimizer", "multiagent", "custom_resources_per_worker", "evaluation_config", "exploration_config", "extra_python_environs_for_driver", "extra_python_environs_for_worker" ] # List of top level keys with value=dict, for which we always override the # entire value (dict), iff the "type" key in that value dict changes. _override_all_subkeys_if_type_changes = ["exploration_config"] @PublicAPI def __init__(self, config=None, env=None, logger_creator=None): """Initialize an RLLib trainer. Args: config (dict): Algorithm-specific configuration data. env (str): Name of the environment to use. Note that this can also be specified as the `env` key in config. logger_creator (func): Function that creates a ray.tune.Logger object. If unspecified, a default logger is created. """ config = config or {} if tf and config.get("eager"): if not tf.executing_eagerly(): tf.enable_eager_execution() logger.info("Executing eagerly, with eager_tracing={}".format( "True" if config.get("eager_tracing") else "False")) if tf and not tf.executing_eagerly() and not config.get("use_pytorch"): logger.info("Tip: set 'eager': true or the --eager flag to enable " "TensorFlow eager execution") # Vars to synchronize to workers on each train call self.global_vars = {"timestep": 0} # Trainers allow env ids to be passed directly to the constructor. self._env_id = self._register_if_needed(env or config.get("env")) # Create a default logger creator if no logger_creator is specified if logger_creator is None: timestr = datetime.today().strftime("%Y-%m-%d_%H-%M-%S") logdir_prefix = "{}_{}_{}".format(self._name, self._env_id, timestr) def default_logger_creator(config): """Creates a Unified logger with a default logdir prefix containing the agent name and the env id """ if not os.path.exists(DEFAULT_RESULTS_DIR): os.makedirs(DEFAULT_RESULTS_DIR) logdir = tempfile.mkdtemp( prefix=logdir_prefix, dir=DEFAULT_RESULTS_DIR) return UnifiedLogger(config, logdir, loggers=None) logger_creator = default_logger_creator super().__init__(config, logger_creator) @classmethod @override(Trainable) def default_resource_request(cls, config): cf = dict(cls._default_config, **config) Trainer._validate_config(cf) num_workers = cf["num_workers"] + cf["evaluation_num_workers"] # TODO(ekl): add custom resources here once tune supports them return Resources( cpu=cf["num_cpus_for_driver"], gpu=cf["num_gpus"], memory=cf["memory"], object_store_memory=cf["object_store_memory"], extra_cpu=cf["num_cpus_per_worker"] * num_workers, extra_gpu=cf["num_gpus_per_worker"] * num_workers, extra_memory=cf["memory_per_worker"] * num_workers, extra_object_store_memory=cf["object_store_memory_per_worker"] * num_workers) @override(Trainable) @PublicAPI def train(self): """Overrides super.train to synchronize global vars.""" if self._has_policy_optimizer(): self.global_vars["timestep"] = self.optimizer.num_steps_sampled self.optimizer.workers.local_worker().set_global_vars( self.global_vars) for w in self.optimizer.workers.remote_workers(): w.set_global_vars.remote(self.global_vars) logger.debug("updated global vars: {}".format(self.global_vars)) result = None for _ in range(1 + MAX_WORKER_FAILURE_RETRIES): try: result = Trainable.train(self) except RayError as e: if self.config["ignore_worker_failures"]: logger.exception( "Error in train call, attempting to recover") self._try_recover() else: logger.info( "Worker crashed during call to train(). To attempt to " "continue training without the failed worker, set " "`'ignore_worker_failures': True`.") raise e except Exception as e: time.sleep(0.5) # allow logs messages to propagate raise e else: break if result is None: raise RuntimeError("Failed to recover from worker crash") if hasattr(self, "workers") and isinstance(self.workers, WorkerSet): self._sync_filters_if_needed(self.workers) if self._has_policy_optimizer(): result["num_healthy_workers"] = len( self.optimizer.workers.remote_workers()) if self.config["evaluation_interval"] == 1 or ( self._iteration > 0 and self.config["evaluation_interval"] and self._iteration % self.config["evaluation_interval"] == 0): evaluation_metrics = self._evaluate() assert isinstance(evaluation_metrics, dict), \ "_evaluate() needs to return a dict." result.update(evaluation_metrics) return result def _sync_filters_if_needed(self, workers): if self.config.get("observation_filter", "NoFilter") != "NoFilter": FilterManager.synchronize( workers.local_worker().filters, workers.remote_workers(), update_remote=self.config["synchronize_filters"]) logger.debug("synchronized filters: {}".format( workers.local_worker().filters)) @override(Trainable) def _log_result(self, result): self.callbacks.on_train_result(trainer=self, result=result) # log after the callback is invoked, so that the user has a chance # to mutate the result Trainable._log_result(self, result) @override(Trainable) def _setup(self, config): env = self._env_id if env: config["env"] = env if _global_registry.contains(ENV_CREATOR, env): self.env_creator = _global_registry.get(ENV_CREATOR, env) else: import gym # soft dependency self.env_creator = lambda env_config: gym.make(env) else: self.env_creator = lambda env_config: None # Merge the supplied config with the class default, but store the # user-provided one. self.raw_user_config = config self.config = Trainer.merge_trainer_configs(self._default_config, config) if self.config["normalize_actions"]: inner = self.env_creator def normalize(env): import gym # soft dependency if not isinstance(env, gym.Env): raise ValueError( "Cannot apply NormalizeActionActionWrapper to env of " "type {}, which does not subclass gym.Env.", type(env)) return NormalizeActionWrapper(env) self.env_creator = lambda env_config: normalize(inner(env_config)) Trainer._validate_config(self.config) if not callable(self.config["callbacks"]): raise ValueError( "`callbacks` must be a callable method that " "returns a subclass of DefaultCallbacks, got {}".format( self.config["callbacks"])) self.callbacks = self.config["callbacks"]() log_level = self.config.get("log_level") if log_level in ["WARN", "ERROR"]: logger.info("Current log_level is {}. For more information, " "set 'log_level': 'INFO' / 'DEBUG' or use the -v and " "-vv flags.".format(log_level)) if self.config.get("log_level"): logging.getLogger("ray.rllib").setLevel(self.config["log_level"]) def get_scope(): if tf and not tf.executing_eagerly(): return tf.Graph().as_default() else: return open(os.devnull) # fake a no-op scope with get_scope(): self._init(self.config, self.env_creator) # Evaluation setup. if self.config.get("evaluation_interval"): # Update env_config with evaluation settings: extra_config = copy.deepcopy(self.config["evaluation_config"]) # Assert that user has not unset "in_evaluation". assert "in_evaluation" not in extra_config or \ extra_config["in_evaluation"] is True extra_config.update({ "batch_mode": "complete_episodes", "rollout_fragment_length": 1, "in_evaluation": True, }) logger.debug( "using evaluation_config: {}".format(extra_config)) self.evaluation_workers = self._make_workers( self.env_creator, self._policy, merge_dicts(self.config, extra_config), num_workers=self.config["evaluation_num_workers"]) self.evaluation_metrics = {} @override(Trainable) def _stop(self): if hasattr(self, "workers"): self.workers.stop() if hasattr(self, "optimizer") and self.optimizer: self.optimizer.stop() @override(Trainable) def _save(self, checkpoint_dir): checkpoint_path = os.path.join(checkpoint_dir, "checkpoint-{}".format(self.iteration)) pickle.dump(self.__getstate__(), open(checkpoint_path, "wb")) return checkpoint_path @override(Trainable) def _restore(self, checkpoint_path): extra_data = pickle.load(open(checkpoint_path, "rb")) self.__setstate__(extra_data) @DeveloperAPI def _make_workers(self, env_creator, policy, config, num_workers): """Default factory method for a WorkerSet running under this Trainer. Override this method by passing a custom `make_workers` into `build_trainer`. Args: env_creator (callable): A function that return and Env given an env config. policy (class): The Policy class to use for creating the policies of the workers. config (dict): The Trainer's config. num_workers (int): Number of remote rollout workers to create. 0 for local only. remote_config_updates (Optional[List[dict]]): A list of config dicts to update `config` with for each Worker (len must be same as `num_workers`). Returns: WorkerSet: The created WorkerSet. """ return WorkerSet( env_creator, policy, config, num_workers=num_workers, logdir=self.logdir) @DeveloperAPI def _init(self, config, env_creator): """Subclasses should override this for custom initialization.""" raise NotImplementedError @DeveloperAPI def _evaluate(self): """Evaluates current policy under `evaluation_config` settings. Note that this default implementation does not do anything beyond merging evaluation_config with the normal trainer config. """ self._before_evaluate() # Broadcast the new policy weights to all evaluation workers. logger.info("Synchronizing weights to evaluation workers.") weights = ray.put(self.workers.local_worker().save()) self.evaluation_workers.foreach_worker( lambda w: w.restore(ray.get(weights))) self._sync_filters_if_needed(self.evaluation_workers) if self.config["custom_eval_function"]: logger.info("Running custom eval function {}".format( self.config["custom_eval_function"])) metrics = self.config["custom_eval_function"]( self, self.evaluation_workers) if not metrics or not isinstance(metrics, dict): raise ValueError("Custom eval function must return " "dict of metrics, got {}.".format(metrics)) else: logger.info("Evaluating current policy for {} episodes.".format( self.config["evaluation_num_episodes"])) if self.config["evaluation_num_workers"] == 0: for _ in range(self.config["evaluation_num_episodes"]): self.evaluation_workers.local_worker().sample() else: num_rounds = int( math.ceil(self.config["evaluation_num_episodes"] / self.config["evaluation_num_workers"])) num_workers = len(self.evaluation_workers.remote_workers()) num_episodes = num_rounds * num_workers for i in range(num_rounds): logger.info("Running round {} of parallel evaluation " "({}/{} episodes)".format( i, (i + 1) * num_workers, num_episodes)) ray.get([ w.sample.remote() for w in self.evaluation_workers.remote_workers() ]) metrics = collect_metrics(self.evaluation_workers.local_worker(), self.evaluation_workers.remote_workers()) return {"evaluation": metrics} @DeveloperAPI def _before_evaluate(self): """Pre-evaluation callback.""" pass @PublicAPI def compute_action(self, observation, state=None, prev_action=None, prev_reward=None, info=None, policy_id=DEFAULT_POLICY_ID, full_fetch=False, explore=None): """Computes an action for the specified policy on the local Worker. Note that you can also access the policy object through self.get_policy(policy_id) and call compute_actions() on it directly. Arguments: observation (obj): observation from the environment. state (list): RNN hidden state, if any. If state is not None, then all of compute_single_action(...) is returned (computed action, rnn state(s), logits dictionary). Otherwise compute_single_action(...)[0] is returned (computed action). prev_action (obj): previous action value, if any prev_reward (int): previous reward, if any info (dict): info object, if any policy_id (str): Policy to query (only applies to multi-agent). full_fetch (bool): Whether to return extra action fetch results. This is always set to True if RNN state is specified. explore (bool): Whether to pick an exploitation or exploration action (default: None -> use self.config["explore"]). Returns: any: The computed action if full_fetch=False, or tuple: The full output of policy.compute_actions() if full_fetch=True or we have an RNN-based Policy. """ if state is None: state = [] preprocessed = self.workers.local_worker().preprocessors[ policy_id].transform(observation) filtered_obs = self.workers.local_worker().filters[policy_id]( preprocessed, update=False) # Figure out the current (sample) time step and pass it into Policy. self.global_vars["timestep"] += 1 result = self.get_policy(policy_id).compute_single_action( filtered_obs, state, prev_action, prev_reward, info, clip_actions=self.config["clip_actions"], explore=explore, timestep=self.global_vars["timestep"]) if state or full_fetch: return result else: return result[0] # backwards compatibility @property def _name(self): """Subclasses should override this to declare their name.""" raise NotImplementedError @property def _default_config(self): """Subclasses should override this to declare their default config.""" raise NotImplementedError @PublicAPI def get_policy(self, policy_id=DEFAULT_POLICY_ID): """Return policy for the specified id, or None. Arguments: policy_id (str): id of policy to return. """ return self.workers.local_worker().get_policy(policy_id) @PublicAPI def get_weights(self, policies=None): """Return a dictionary of policy ids to weights. Arguments: policies (list): Optional list of policies to return weights for, or None for all policies. """ return self.workers.local_worker().get_weights(policies) @PublicAPI def set_weights(self, weights): """Set policy weights by policy id. Arguments: weights (dict): Map of policy ids to weights to set. """ self.workers.local_worker().set_weights(weights) @DeveloperAPI def export_policy_model(self, export_dir, policy_id=DEFAULT_POLICY_ID): """Export policy model with given policy_id to local directory. Arguments: export_dir (string): Writable local directory. policy_id (string): Optional policy id to export. Example: >>> trainer = MyTrainer() >>> for _ in range(10): >>> trainer.train() >>> trainer.export_policy_model("/tmp/export_dir") """ self.workers.local_worker().export_policy_model(export_dir, policy_id) @DeveloperAPI def export_policy_checkpoint(self, export_dir, filename_prefix="model", policy_id=DEFAULT_POLICY_ID): """Export tensorflow policy model checkpoint to local directory. Arguments: export_dir (string): Writable local directory. filename_prefix (string): file name prefix of checkpoint files. policy_id (string): Optional policy id to export. Example: >>> trainer = MyTrainer() >>> for _ in range(10): >>> trainer.train() >>> trainer.export_policy_checkpoint("/tmp/export_dir") """ self.workers.local_worker().export_policy_checkpoint( export_dir, filename_prefix, policy_id) @DeveloperAPI def import_policy_model_from_h5(self, import_file, policy_id=DEFAULT_POLICY_ID): """Imports a policy's model with given policy_id from a local h5 file. Arguments: import_file (str): The h5 file to import from. policy_id (string): Optional policy id to import into. Example: >>> trainer = MyTrainer() >>> trainer.import_policy_model_from_h5("/tmp/weights.h5") >>> for _ in range(10): >>> trainer.train() """ self.workers.local_worker().import_policy_model_from_h5( import_file, policy_id) @DeveloperAPI def collect_metrics(self, selected_workers=None): """Collects metrics from the remote workers of this agent. This is the same data as returned by a call to train(). """ return self.optimizer.collect_metrics( self.config["collect_metrics_timeout"], min_history=self.config["metrics_smoothing_episodes"], selected_workers=selected_workers) @classmethod def resource_help(cls, config): return ("\n\nYou can adjust the resource requests of RLlib agents by " "setting `num_workers`, `num_gpus`, and other configs. See " "the DEFAULT_CONFIG defined by each agent for more info.\n\n" "The config of this agent is: {}".format(config)) @classmethod def merge_trainer_configs(cls, config1, config2): config1 = copy.deepcopy(config1) # Error if trainer default has deprecated value. if config1["sample_batch_size"] != DEPRECATED_VALUE: deprecation_warning( "sample_batch_size", new="rollout_fragment_length", error=True) # Warning if user override config has deprecated value. if ("sample_batch_size" in config2 and config2["sample_batch_size"] != DEPRECATED_VALUE): deprecation_warning( "sample_batch_size", new="rollout_fragment_length") config2["rollout_fragment_length"] = config2["sample_batch_size"] del config2["sample_batch_size"] if "callbacks" in config2 and type(config2["callbacks"]) is dict: legacy_callbacks_dict = config2["callbacks"] def make_callbacks(): # Deprecation warning will be logged by DefaultCallbacks. return DefaultCallbacks( legacy_callbacks_dict=legacy_callbacks_dict) config2["callbacks"] = make_callbacks return deep_update(config1, config2, cls._allow_unknown_configs, cls._allow_unknown_subkeys, cls._override_all_subkeys_if_type_changes) @staticmethod def _validate_config(config): if "policy_graphs" in config["multiagent"]: logger.warning( "The `policy_graphs` config has been renamed to `policies`.") # Backwards compatibility config["multiagent"]["policies"] = config["multiagent"][ "policy_graphs"] del config["multiagent"]["policy_graphs"] if "gpu" in config: raise ValueError( "The `gpu` config is deprecated, please use `num_gpus=0|1` " "instead.") if "gpu_fraction" in config: raise ValueError( "The `gpu_fraction` config is deprecated, please use " "`num_gpus=<fraction>` instead.") if "use_gpu_for_workers" in config: raise ValueError( "The `use_gpu_for_workers` config is deprecated, please use " "`num_gpus_per_worker=1` instead.") if type(config["input_evaluation"]) != list: raise ValueError( "`input_evaluation` must be a list of strings, got {}".format( config["input_evaluation"])) def _try_recover(self): """Try to identify and blacklist any unhealthy workers. This method is called after an unexpected remote error is encountered from a worker. It issues check requests to all current workers and blacklists any that respond with error. If no healthy workers remain, an error is raised. """ if (not self._has_policy_optimizer() and not hasattr(self, "execution_plan")): raise NotImplementedError( "Recovery is not supported for this algorithm") if self._has_policy_optimizer(): workers = self.optimizer.workers else: assert hasattr(self, "execution_plan") workers = self.workers logger.info("Health checking all workers...") checks = [] for ev in workers.remote_workers(): _, obj_id = ev.sample_with_count.remote() checks.append(obj_id) healthy_workers = [] for i, obj_id in enumerate(checks): w = workers.remote_workers()[i] try: ray_get_and_free(obj_id) healthy_workers.append(w) logger.info("Worker {} looks healthy".format(i + 1)) except RayError: logger.exception("Blacklisting worker {}".format(i + 1)) try: w.__ray_terminate__.remote() except Exception: logger.exception("Error terminating unhealthy worker") if len(healthy_workers) < 1: raise RuntimeError( "Not enough healthy workers remain to continue.") if self._has_policy_optimizer(): self.optimizer.reset(healthy_workers) else: assert hasattr(self, "execution_plan") logger.warning("Recreating execution plan after failure") workers.reset(healthy_workers) self.train_exec_impl = self.execution_plan(workers, self.config) def _has_policy_optimizer(self): """Whether this Trainer has a PolicyOptimizer as `optimizer` property. Returns: bool: True if this Trainer holds a PolicyOptimizer object in property `self.optimizer`. """ return hasattr(self, "optimizer") and isinstance( self.optimizer, PolicyOptimizer) @override(Trainable) def _export_model(self, export_formats, export_dir): ExportFormat.validate(export_formats) exported = {} if ExportFormat.CHECKPOINT in export_formats: path = os.path.join(export_dir, ExportFormat.CHECKPOINT) self.export_policy_checkpoint(path) exported[ExportFormat.CHECKPOINT] = path if ExportFormat.MODEL in export_formats: path = os.path.join(export_dir, ExportFormat.MODEL) self.export_policy_model(path) exported[ExportFormat.MODEL] = path return exported def import_model(self, import_file): """Imports a model from import_file. Note: Currently, only h5 files are supported. Args: import_file (str): The file to import the model from. Returns: A dict that maps ExportFormats to successfully exported models. """ # Check for existence. if not os.path.exists(import_file): raise FileNotFoundError( "`import_file` '{}' does not exist! Can't import Model.". format(import_file)) # Get the format of the given file. import_format = "h5" # TODO(sven): Support checkpoint loading. ExportFormat.validate([import_format]) if import_format != ExportFormat.H5: raise NotImplementedError else: return self.import_policy_model_from_h5(import_file) def __getstate__(self): state = {} if hasattr(self, "workers"): state["worker"] = self.workers.local_worker().save() if hasattr(self, "optimizer") and hasattr(self.optimizer, "save"): state["optimizer"] = self.optimizer.save() return state def __setstate__(self, state): if "worker" in state: self.workers.local_worker().restore(state["worker"]) remote_state = ray.put(state["worker"]) for r in self.workers.remote_workers(): r.restore.remote(remote_state) if "optimizer" in state: self.optimizer.restore(state["optimizer"]) def _register_if_needed(self, env_object): if isinstance(env_object, str): return env_object elif isinstance(env_object, type): name = env_object.__name__ register_env(name, lambda config: env_object(config)) return name raise ValueError( "{} is an invalid env specification. ".format(env_object) + "You can specify a custom env as either a class " "(e.g., YourEnvCls) or a registered env id (e.g., \"your_env\").")
43.746076
79
0.638052
ace88254614886956e7f59ebdbcc363d74ec35e9
14,164
py
Python
plgx-esp-ui/tests/test_email_endpoints.py
dhoomakethu/plgx-esp
b466b52a5e16a0d12a61e505e48add83bee5bad4
[ "MIT" ]
20
2019-12-09T13:55:13.000Z
2022-01-10T09:10:42.000Z
plgx-esp-ui/tests/test_email_endpoints.py
dhoomakethu/plgx-esp
b466b52a5e16a0d12a61e505e48add83bee5bad4
[ "MIT" ]
13
2019-12-03T13:27:27.000Z
2021-12-03T05:22:49.000Z
plgx-esp-ui/tests/test_email_endpoints.py
dhoomakethu/plgx-esp
b466b52a5e16a0d12a61e505e48add83bee5bad4
[ "MIT" ]
16
2019-11-15T11:45:06.000Z
2022-01-07T08:07:11.000Z
""" All Test-Case required client, url_prefix and token, and these all we need to just pass as parameters in the function, Note:- make sure about email and password is correct. """ import json, base64 from polylogyx.constants import PolyLogyxServerDefaults from polylogyx.dao import settings_dao from polylogyx.models import Settings from .base import TestUtils from .factories import SettingsFactory test_utils_obj = TestUtils() settings_data = { 'email': 'abcd@gmail.com', 'smtpPort': '12', 'smtpAddress': 'smtp.gmail.com', 'password': 'abcd', 'emailRecipients': 'foobar@gmail.com,test2@gmail.com' } class TestGetConfigureEmailRecipientAndSender: def test_get_configure_email_without_existing_settings_data(self, client, url_prefix, token): """ Test-case without payloads and without existing settings data, expected output:- status is success """ resp = client.get(url_prefix + '/email/configure', headers={'x-access-token': token}) assert resp.status_code == 200 response_dict = json.loads(resp.data) assert response_dict['status'] == 'success' def test_get_configure_email_with_invalid_method(self, client, url_prefix, token, settings): """ Test-case with invalid request method, expected output:- status code is 405 """ resp = client.put(url_prefix + '/email/configure', headers={'x-access-token': token}) assert resp.status_code == 405 def test_get_configure_email_without_default_settings_data(self, client, url_prefix, token, settings): """ Test-case without payloads and without existing settings data of plgx_config_all_settings, expected output:- status is success """ resp = client.get(url_prefix + '/email/configure', headers={'x-access-token': token}) assert resp.status_code == 200 response_dict = json.loads(resp.data) assert response_dict['status'] == 'success' def test_get_configure_email_with_default_settings_data(self, client, url_prefix, token, settings): """ Test-case with all payloads value and settings data of plgx_config_all_settings, expected output:- status is success, and resultant data of settings """ SettingsFactory(name=PolyLogyxServerDefaults.plgx_config_all_settings, setting=json.dumps(settings_data)) resp = client.get(url_prefix + '/email/configure', headers={'x-access-token': token}) assert resp.status_code == 200 response_dict = json.loads(resp.data) assert response_dict['status'] == 'success' data = get_settings_by_name() assert response_dict['data'] == data class TestUpdateConfigureEmailRecipientAndSender: """ to check Valid/invalid of test-case must be gmail login with less_Secure_app is turned on gmail account which used in this, and Test-case inside these blocks where these payloads are used, all values are compulsory values all are string type, so if we pass any none value or value type which is not matching with specified type it will return 400 i.e., bad request """ payload = { 'email': 'abcd@gmail.com', 'smtpPort': '12', 'smtpAddress': 'smtp.gmail.com', 'password': 'abcd', 'emailRecipients': 'foo@gmail.com,test2@gmail.com' } def test_get_configure_email_without_payload(self, client, url_prefix, token): """ Test-case without payloads but without existing settings data, expected output:- status_code is 400 """ resp = client.post(url_prefix + '/email/configure', headers={'x-access-token': token}) assert resp.status_code == 400 def test_get_configure_email_with_payload_empty_dict(self, client, url_prefix, token): """ Test-case with payload is empty dictionary but without existing settings data, expected output:- status_code is 400 """ resp = client.post(url_prefix + '/email/configure', headers={'x-access-token': token}, json={}) assert resp.status_code == 400 def test_get_configure_email_with_none_value_email(self, client, url_prefix, token): """ Test-case with invalid payloads but without existing settings data, expected output:- status_code is 400 """ self.payload['email'] = None self.payload['smtpPort'] = None self.payload['smtpAddress'] = None self.payload['password'] = None self.payload['emailRecipients'] = None resp = client.post(url_prefix + '/email/configure', headers={'x-access-token': token}, json=self.payload) assert resp.status_code == 400 def test_get_configure_email_with_all_valid_credentials(self, client, url_prefix, token): """ Test-case with valid payloads and valid credentials as well as existing data to update with payload, expected output:- status is success, and resultant data is same as payload value """ payload = { 'email': 'abcd@gmail.com', 'smtpPort': '12', 'smtpAddress': 'smtp.gmail.com', 'password': 'abcd', 'emailRecipients': 'foo@gmail.com,test2@gmail.com' } resp = client.post(url_prefix + '/email/configure', headers={'x-access-token': token}, json=payload) assert resp.status_code == 200 response_dict = json.loads(resp.data) assert response_dict['status'] == 'success' assert response_dict['data']['email'] == payload['email'] assert response_dict['data']['smtpPort'] == int(payload['smtpPort']) assert response_dict['data']['smtpAddress'] == payload['smtpAddress'] assert response_dict['data']['password'] == base64.b64encode( payload['password'].encode('ascii')).decode('ascii') + '\n' assert response_dict['data']['emailRecipients'] == payload['emailRecipients'].split(',') def test_get_configure_email_with_invalid_method(self, client, url_prefix, token, settings): """ Test-case with invalid request method, expected output:- status code is 405 """ resp = client.put(url_prefix + '/email/configure', headers={'x-access-token': token}, json=self.payload) assert resp.status_code == 405 def test_get_configure_emails_with_all_valid_credentials(self, client, url_prefix, token, settings): """ Test-case with valid payloads and valid credentials as well as existing data to update with payload, expected output:- status is success, and resultant data is same as payload value """ payload = { 'email': 'abcd@gmail.com', 'smtpPort': '12', 'smtpAddress': 'smtp.gmail.com', 'password': 'abcd', 'emailRecipients': 'foobar@gmail.com,test2@gmail.com' } resp = client.post(url_prefix + '/email/configure', headers={'x-access-token': token}, json=payload) assert resp.status_code == 200 response_dict = json.loads(resp.data) assert response_dict['status'] == 'success' assert response_dict['data']['email'] == payload['email'] assert response_dict['data']['smtpPort'] == int(payload['smtpPort']) assert response_dict['data']['smtpAddress'] == payload['smtpAddress'] assert response_dict['data']['password'] == base64.b64encode( payload['password'].encode('ascii')).decode('ascii') + '\n' assert response_dict['data']['emailRecipients'] == payload['emailRecipients'].split(',') class TestEmailRecipientAndSender: """ Test-case inside these blocks where these payloads are used, all values are compulsory values except smtpPort and only type of smtpPort is positive integer, remainings all are string type, so if we pass any none value or value type which is not matching with specified type it will return 400 i.e., bad request """ payload = { 'email': 'abcd@gmail.com', 'smtpPort': '12', 'smtpAddress': 'smtp.gmail.com', 'password': 'abcd', 'emailRecipients': 'foo@gmail.com,test2@gmail.com' } def test_email_receipient_and_sender_without_payload(self, client, url_prefix, token): """ Test-case without payloads but without existing settings data, expected output:- status_code is 400 """ resp = client.post(url_prefix + '/email/test', headers={'x-access-token': token}) assert resp.status_code == 400 def test_email_receipient_and_sender_with_empty_payload(self, client, url_prefix, token): """ Test-Case with empty dictionary payload and with existing Settings Data, expected output:- status_code is 400 """ resp = client.post(url_prefix + '/email/test', headers={'x-access-token': token}, json={}) assert resp.status_code == 400 def test_email_receipient_and_sender_with_all_payload(self, client, url_prefix, token): """ Test-Case with all payload value and with existing Settings Data, expected output:- status is success """ resp = client.post(url_prefix + '/email/test', headers={'x-access-token': token}, json=self.payload) assert resp.status_code == 200 response_dict = json.loads(resp.data) assert response_dict['status'] == 'success' def test_email_receipient_and_sender_with_all_payload_except_smtp_port(self, client, url_prefix, token): """ Test-Case with all payload value except smtp port and with existing Settings Data, expected output:- status is failure """ payload = { 'email': 'abcd@gmail.com', 'smtpPort': '12', 'smtpAddress': 'smtp.gmail.com', 'password': 'abcd', 'emailRecipients': 'foo@gmail.com,test2@gmail.com' } resp = client.post(url_prefix + '/email/test', headers={'x-access-token': token}, json=payload) assert resp.status_code == 200 response_dict = json.loads(resp.data) assert response_dict['status'] == 'success' def test_email_receipient_and_sender_with_payload_value_none(self, client, url_prefix, token): """ Test-Case with all payloads values are none and with existing Settings Data, expected output:- status_code is 400 """ self.payload['email'] = None self.payload['smtpPort'] = None self.payload['smtpAddress'] = None self.payload['password'] = None self.payload['emailRecipients'] = None resp = client.post(url_prefix + '/email/test', headers={'x-access-token': token}, json={}) assert resp.status_code == 400 def test_email_receipient_and_sender_with_invalid_method(self, client, url_prefix, token, settings): """ Test-case with invalid request method, expected output:- status code is 405 """ resp = client.get(url_prefix + '/email/test', headers={'x-access-token': token}, json=self.payload) assert resp.status_code == 405 def test_email_receipient_and_sender_with_invalid_credentials(self, client, url_prefix, token, settings): """ Test-Case with invalid data but with existing settings data, expected output:- status is failure """ self.payload['email'] = 'abcd@gmail.com' self.payload['smtpPort'] = '12' self.payload['smtpAddress'] = 'smtp.gmail.com' self.payload['password'] = 'abcd' self.payload['emailRecipients'] = 'foo@gmail.com,test2@gmail.com' resp = client.post(url_prefix + '/email/test', headers={'x-access-token': token}, json=self.payload) assert resp.status_code == 200 response_dict = json.loads(resp.data) assert response_dict['status'] == 'failure' def test_email_receipient_and_sender_with_data(self, client, url_prefix, token, settings): """ Test-Case with valid credentials along with existing settings data, expected output:- status is success """ self.payload['email'] = 'abcd@gmail.com' self.payload['smtpPort'] = None self.payload['smtpAddress'] = 'smtp.gmail.com' self.payload['password'] = 'abcd' self.payload['emailRecipients'] = 'polylogyx@gmail.com,test2@gmail.com' settings = Settings.create( setting=json.dumps( { "email": "test@gmail.com", "emailRecipients": ["foo@gmail.com", "test2@gmail.com"], "password": "VGVzdEAxMjM0", "smtpAddress": "smtp.googlemail.com", "smtpPort": 465 } ), name='plgx_config_all_settings' ) resp = client.post(url_prefix + '/email/test', headers={'x-access-token': token}, data=self.payload) assert resp.status_code == 200 response_dict = json.loads(resp.data) assert response_dict['status'] == 'success' def test_email_receipient_and_sender_with_existing_data(self, client, url_prefix, token, settings): """ Test-Case with valid credentials and with existing settings data, expected output:- status is success """ settings.update( setting=json.dumps( { "email": "abc@gmail.com", "emailRecipients": ["foo@gmail.com", "test2@gmail.com"], "password": "VGVzdEAxMjM0", "smtpAddress": "smtp.googlemail.com", "smtpPort": 465 } ) ) resp = client.post(url_prefix + '/email/test', headers={'x-access-token': token}, data=self.payload) assert resp.status_code == 200 response_dict = json.loads(resp.data) assert response_dict['status'] == 'success' def get_settings_by_name(): existing_setting = settings_dao.get_settings_by_name(PolyLogyxServerDefaults.plgx_config_all_settings) setting = '' if existing_setting: setting = json.loads(existing_setting.setting) setting['password'] = base64.b64encode(setting['password'].encode('ascii')).decode('ascii') return setting
45.987013
113
0.651228
ace88258df6e9dedb061b2112488056b7a9f3a36
543
py
Python
rocketgram/api/delete_message.py
rocketgram/rocketgram
b94d8f83e577c0618a650c113d688ef8689ac3f5
[ "MIT" ]
35
2019-09-19T22:56:22.000Z
2022-03-12T10:49:47.000Z
rocketgram/api/delete_message.py
rocketgram/rocketgram
b94d8f83e577c0618a650c113d688ef8689ac3f5
[ "MIT" ]
2
2020-10-20T05:24:25.000Z
2021-03-27T18:21:23.000Z
rocketgram/api/delete_message.py
rocketgram/rocketgram
b94d8f83e577c0618a650c113d688ef8689ac3f5
[ "MIT" ]
4
2020-06-26T01:12:30.000Z
2022-01-16T13:55:47.000Z
# Copyright (C) 2015-2021 by Vd. # This file is part of Rocketgram, the modern Telegram bot framework. # Rocketgram is released under the MIT License (see LICENSE). from dataclasses import dataclass from typing import Union from .request import Request from .utils import BoolResultMixin @dataclass(frozen=True) class DeleteMessage(BoolResultMixin, Request): """\ Represents DeleteMessage request object: https://core.telegram.org/bots/api#deletemessage """ chat_id: Union[int, str] = None message_id: int = None
24.681818
69
0.744015
ace882c3895eb78686d4648e51f86c214dd06fa5
356
py
Python
bill/urls.py
reysmerwvr/checkout-api
73e59e7e1aa1dbed007c794269054d98e02e6112
[ "MIT" ]
null
null
null
bill/urls.py
reysmerwvr/checkout-api
73e59e7e1aa1dbed007c794269054d98e02e6112
[ "MIT" ]
null
null
null
bill/urls.py
reysmerwvr/checkout-api
73e59e7e1aa1dbed007c794269054d98e02e6112
[ "MIT" ]
null
null
null
from bill.views import InvoiceList, InvoiceDetail from rest_framework.urlpatterns import format_suffix_patterns from django.urls import path urlpatterns = [ path('invoices', InvoiceList.as_view(), name='invoice-list'), path('invoices/<int:pk>', InvoiceDetail.as_view(), name='invoice-detail'), ] urlpatterns = format_suffix_patterns(urlpatterns)
32.363636
78
0.780899
ace882d38e1e855031d339f20c974cdd35271963
3,134
py
Python
mockdata/scatter.py
mcoughlin/gw-mock-data
bbdf6b0c121ef5abbc4fa9450763e253b129631e
[ "MIT" ]
null
null
null
mockdata/scatter.py
mcoughlin/gw-mock-data
bbdf6b0c121ef5abbc4fa9450763e253b129631e
[ "MIT" ]
null
null
null
mockdata/scatter.py
mcoughlin/gw-mock-data
bbdf6b0c121ef5abbc4fa9450763e253b129631e
[ "MIT" ]
null
null
null
from __future__ import division import numpy as np import scipy.signal as sig # Function defaults sec_d = 16 fs_d = 2048 __all__ = ['coupling_func', 'witness'] # this is the laser wavelength. We need it so that the calibrated witness # channels make sense; the scattering fringing cares about the ratio of the # size motion to the wavelength lambduh = 1064e-9 def coupling_func(y1, y2, scale=3e-18, phi=0): return scale*np.sin(2*2*np.pi/lambduh*(y1 + y2) + phi) def witness(n_relevant, n_irrelevant, sec=sec_d, fs=fs_d, seed=None, rand_phase=False, filt_seismic=False): ''' Deterministically generate mock witness channel data for use in testing subtraction algorithms. ''' if isinstance(seed, np.random.RandomState): state = seed else: state = np.random.RandomState(seed) nyq = fs / 2.0 times = np.linspace(0, sec, fs*sec, endpoint=False) # Let's make this the 'seismic' channel with the low frequency stuff y1 = state.randn(sec*fs) b1, a1 = sig.butter(2, [0.1 / nyq, 5 / nyq], btype='bandpass') y1 = sig.lfilter(b1, a1, y1) y1 *= 5e-7 # this puts it into units of meters y1_imit = 5e-7*sig.lfilter(b1, a1, state.randn(sec*fs)) if(filt_seismic): b_lp, a_lp = sig.butter(1, 1.1/nyq, btype='lowpass') y1_given = sig.lfilter(b_lp, a_lp, y1) y1_irr = sig.lfilter(b_lp, a_lp, y1_imit) else: y1_given = y1 y1_irr = y1_imit # make several witnesses as requested rel_1 = (n_relevant+1)//2 irrel_1 = (n_irrelevant+1)//2 rel_1_wits = np.tile(y1_given, (rel_1, 1)) irrel_1_wits = np.tile(y1_irr, (irrel_1, 1)) wits_1 = np.concatenate((rel_1_wits, irrel_1_wits),0) # add different random noise to witnesses noise_add1 = 0.0*5e-11*state.randn(rel_1+irrel_1, sec*fs) noise_add1 *= state.uniform(low=0.1, high=1.0, size=(rel_1+irrel_1, 1)) wits_1 += noise_add1 # this is the acoustic channel so it has only high frequency noise f1 = 59.5 f2 = 119.7 phase1 = 0.8 phase2 = 0.32 y2 = 1 * np.sin(2*np.pi * (f1 * times + phase1)) # a couple of sine waves y2 += 0.3 * np.sin(2*np.pi * (f2 * times + phase2)) y2 *= 1e-7 # this puts it into units of meters rel_2 = n_relevant//2 irrel_2 = n_irrelevant//2 if(rand_phase): phase1_wit = 2*np.pi*state.uniform(size=(rel_2, 1)) phase2_wit = 2*np.pi*state.uniform(size=(rel_2, 1)) else: phase1_wit = np.zeros((rel_2, 1)) phase2_wit = np.zeros((rel_2, 1)) rel_2_wits = 1e-7*np.sin(2*np.pi*f1*times + phase1 + phase1_wit) + \ 3e-8*np.sin(2*np.pi*f2*times + phase2 + phase2_wit) f1_irr = 71.2 f2_irr = 143.0 phase1_irr = 2*np.pi*state.uniform(size=(irrel_2, 1)) phase2_irr = 2*np.pi*state.uniform(size=(irrel_2, 1)) irrel_2_wits = 1e-7*np.sin(2*np.pi*f1_irr*times + phase1_irr) + \ 3e-8*np.sin(2*np.pi*f2_irr*times + phase2_irr) wits_2 = np.concatenate((rel_2_wits, irrel_2_wits), 0) wits = np.concatenate((wits_1, wits_2), 0) return y1, y2, wits
34.43956
86
0.633376
ace882e1b4cd97c7212da90b06184ead37a09542
12,049
py
Python
Financal Project/Website/sa.py
KiranKhanna721/College-Projects
ea6fd00b7a4ebaa1e7df9bb0d198a2edcc9665f8
[ "MIT" ]
null
null
null
Financal Project/Website/sa.py
KiranKhanna721/College-Projects
ea6fd00b7a4ebaa1e7df9bb0d198a2edcc9665f8
[ "MIT" ]
null
null
null
Financal Project/Website/sa.py
KiranKhanna721/College-Projects
ea6fd00b7a4ebaa1e7df9bb0d198a2edcc9665f8
[ "MIT" ]
null
null
null
import pandas as pd import numpy as np import math from alpha_vantage.timeseries import TimeSeries from sklearn.metrics import mean_squared_error from bs4 import BeautifulSoup import streamlit as st import matplotlib.pyplot as plt from urllib.request import urlopen from urllib.request import Request from textblob import TextBlob from nltk.corpus import stopwords from sklearn.linear_model import LinearRegression from sklearn.preprocessing import StandardScaler from collections import Counter import warnings; warnings.simplefilter('ignore') import nltk import string from nltk import ngrams from nltk.tokenize import word_tokenize from nltk.stem import SnowballStemmer import datetime as dt import sklearn import yfinance as yf from datetime import datetime from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import LSTM def data(t): n = 1 ticker = t finviz_url = 'https://finviz.com/quote.ashx?t=' news_tables = {} url = finviz_url + ticker req = Request(url=url,headers={'user-agent': 'my-app/0.0.1'}) resp = urlopen(req) html = BeautifulSoup(resp, features="lxml") news_table = html.find(id='news-table') news_tables[ticker] = news_table try: df = news_tables[ticker] df_tr = df.findAll('tr') for i, table_row in enumerate(df_tr): a_text = table_row.a.text td_text = table_row.td.text td_text = td_text.strip() if i == n-1: break except KeyError: pass parsed_news = [] for file_name, news_table in news_tables.items(): for x in news_table.findAll('tr'): text = x.a.get_text() date_scrape = x.td.text.split() if len(date_scrape) == 1: time = date_scrape[0] else: date = date_scrape[0] time = date_scrape[1] ticker = file_name.split('_')[0] parsed_news.append([ticker, date, time, text]) columns = ['Ticker', 'Date', 'Time', 'Headline'] news = pd.DataFrame(parsed_news, columns=columns) return news def review_clean(review): # changing to lower case lower = review.str.lower() # Replacing the repeating pattern of &#039; pattern_remove = lower.str.replace("&#039;", "") # Removing all the special Characters special_remove = pattern_remove.str.replace(r'[^\w\d\s]',' ') # Removing all the non ASCII characters ascii_remove = special_remove.str.replace(r'[^\x00-\x7F]+',' ') # Removing the leading and trailing Whitespaces whitespace_remove = ascii_remove.str.replace(r'^\s+|\s+?$','') # Replacing multiple Spaces with Single Space multiw_remove = whitespace_remove.str.replace(r'\s+',' ') # Replacing Two or more dots with one dataframe = multiw_remove.str.replace(r'\.{2,}', ' ') return dataframe def sentiment(review): # Sentiment polarity of the reviews pol = [] for i in review: analysis = TextBlob(i) pol.append(analysis.sentiment.polarity) return pol def get_historical(quote): end = datetime.now() start = datetime(end.year-3,end.month,end.day) data = yf.download(quote, start=start, end=end) df = pd.DataFrame(data=data) if(df.empty): ts = TimeSeries(key='N6A6QT6IBFJOPJ70',output_format='pandas') data, meta_data = ts.get_daily_adjusted(symbol='NSE:'+quote, outputsize='full') data=data.head(503).iloc[::-1] data=data.reset_index() df=pd.DataFrame() df['Date']=data['date'] df['Open']=data['1. open'] df['High']=data['2. high'] df['Low']=data['3. low'] df['Close']=data['4. close'] df['Adj Close']=data['5. adjusted close'] df['Volume']=data['6. volume'] return df def LSTM_ALGO(df): dataset_train=df.iloc[0:int(0.8*len(df)),:] dataset_test=df.iloc[int(0.8*len(df)):,:] training_set=df.iloc[:,4:5].values sc=MinMaxScaler(feature_range=(0,1))#Scaled values btween 0,1 training_set_scaled=sc.fit_transform(training_set) X_train=[]#memory with 7 days from day i y_train=[]#day i for i in range(7,len(training_set_scaled)): X_train.append(training_set_scaled[i-7:i,0]) y_train.append(training_set_scaled[i,0]) X_train=np.array(X_train) y_train=np.array(y_train) X_forecast=np.array(X_train[-1,1:]) X_forecast=np.append(X_forecast,y_train[-1]) X_train=np.reshape(X_train, (X_train.shape[0],X_train.shape[1],1))#.shape 0=row,1=col X_forecast=np.reshape(X_forecast, (1,X_forecast.shape[0],1)) regressor=Sequential() regressor.add(LSTM(units=50,return_sequences=True,input_shape=(X_train.shape[1],1))) regressor.add(Dropout(0.1)) regressor.add(LSTM(units=50,return_sequences=True)) regressor.add(Dropout(0.1)) regressor.add(LSTM(units=50,return_sequences=True)) regressor.add(Dropout(0.1)) regressor.add(LSTM(units=50)) regressor.add(Dropout(0.1)) regressor.add(Dense(units=1)) regressor.compile(optimizer='adam',loss='mean_squared_error') regressor.fit(X_train,y_train,epochs=25,batch_size=32 ) real_stock_price=dataset_test.iloc[:,4:5].values dataset_total=pd.concat((dataset_train['Close'],dataset_test['Close']),axis=0) testing_set=dataset_total[ len(dataset_total) -len(dataset_test) -7: ].values testing_set=testing_set.reshape(-1,1) testing_set=sc.transform(testing_set) X_test=[] for i in range(7,len(testing_set)): X_test.append(testing_set[i-7:i,0]) X_test=np.array(X_test) X_test=np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1)) predicted_stock_price=regressor.predict(X_test) predicted_stock_price=sc.inverse_transform(predicted_stock_price) fig = plt.figure(figsize=(7.2,4.8),dpi=65) plt.plot(real_stock_price,label='Actual Price') plt.plot(predicted_stock_price,label='Predicted Price') plt.legend(loc=4) error_lstm = math.sqrt(mean_squared_error(real_stock_price, predicted_stock_price)) x_input=np.array(X_test.reshape(1,-1)) forecasted_stock_price=regressor.predict(X_forecast) forecasted_stock_price=sc.inverse_transform(forecasted_stock_price) lstm_pred=forecasted_stock_price[0,0] print() print("##############################################################################") print("Tomorrow's Closing Price Prediction by LSTM: ",lstm_pred) print("LSTM RMSE:",error_lstm) print("##############################################################################") return lstm_pred,error_lstm def LIN_REG_ALGO(df): forecast_out = int(7) df['Close after n days'] = df['Close'].shift(-forecast_out) df_new=df[['Close','Close after n days']] y =np.array(df_new.iloc[:-forecast_out,-1]) y=np.reshape(y, (-1,1)) X=np.array(df_new.iloc[:-forecast_out,0:-1]) X_to_be_forecasted=np.array(df_new.iloc[-forecast_out:,0:-1]) X_train=X[0:int(0.8*len(df)),:] X_test=X[int(0.8*len(df)):,:] y_train=y[0:int(0.8*len(df)),:] y_test=y[int(0.8*len(df)):,:] sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) X_to_be_forecasted=sc.transform(X_to_be_forecasted) clf = LinearRegression(n_jobs=-1) clf.fit(X_train, y_train) y_test_pred=clf.predict(X_test) y_test_pred=y_test_pred*(1.04) error_lr = math.sqrt(mean_squared_error(y_test, y_test_pred)) forecast_set = clf.predict(X_to_be_forecasted) forecast_set=forecast_set*(1.04) mean=forecast_set.mean() lr_pred=forecast_set[0,0] print() print("##############################################################################") print("Tomorrow's Closing Price Prediction by Linear Regression: ",lr_pred) print("Linear Regression RMSE:",error_lr) print("##############################################################################") return df, lr_pred, forecast_set, mean, error_lr def recommending(df, global_polarity,today_stock,mean): if today_stock.iloc[-1]['Close'] < mean: if global_polarity > 0: idea="RISE" decision="BUY" print() print("##############################################################################") print("According to the ML Predictions and Sentiment Analysis of Tweets, a",idea,"in stock is expected => ",decision) elif global_polarity <= 0: idea="FALL" decision="SELL" print() print("##############################################################################") print("According to the ML Predictions and Sentiment Analysis of Tweets, a",idea,"in stock is expected => ",decision) else: idea="FALL" decision="SELL" print() print("##############################################################################") print("According to the ML Predictions and Sentiment Analysis of Tweets, a",idea,"in stock is expected => ",decision) return idea, decision def app(): st.title("Combining Time Series and Sentiment Analysis for TCS Forecasting") ticker = st.text_input("Enter a Stock Name") if st.button("Submit"): news = data(t=ticker) news.to_csv('data2.csv') df = pd.read_csv('data2.csv') df['Text'] = review_clean(df['Headline']) stop_words = set(stopwords.words('english')) df['Text'] = df['Text'].apply(lambda x: ' '.join(word for word in x.split() if word not in stop_words)) Snow_ball = SnowballStemmer("english") df['Text'] = df['Text'].apply(lambda x: " ".join(Snow_ball.stem(word) for word in x.split())) df['sentiment_clean'] = sentiment(df['Text']) df.loc[(df['sentiment_clean'] >0), 'sentiment'] = 1 df.loc[(df['sentiment_clean'] < 0), 'sentiment'] = -1 df.loc[(df['sentiment_clean'] == 0) | (df['sentiment_clean']<0.05), 'sentiment'] = 0 df.to_csv('data.csv') st.write("The latest News of TCS") df1 = df.head(1) st.table(df1[["Date","Headline"]]) a = df1["sentiment"] if int(a) == 1: st.success("Postive News, Stock price might increases") elif int(a) == 0: st.success("Neutral News , Stock price might not change ") else: st.wrong("Negative News, Stock price might decrease") s = st.text_input("Enter a Stock Name for stock market prediction") if st.button("Predict"): stock = get_historical(s) stock.to_csv(''+s+'.csv') df2 = pd.read_csv(''+s+'.csv') today_stock=df2.iloc[-1:] df2 = df2.dropna() code_list=[] for i in range(0,len(df2)): code_list.append(s) df3=pd.DataFrame(code_list,columns=['Code']) df3 = pd.concat([df3, df2], axis=1) df2=df3 lstm_pred,error_lstm = LSTM_ALGO(df2) st.write("Tomorrow's Closing Price Prediction by LSTM: ",lstm_pred) st.write("LSTM RMSE:",error_lstm) df2, lr_pred, forecast_set,mean,error_lr=LIN_REG_ALGO(df2) st.write("Tomorrow's Closing Price Prediction by Linear regression: ",lr_pred) st.write("Linear Regression RMSE:",error_lstm) df4 = pd.read_csv('data.csv') df1 = df4.head(1) a = df1["sentiment"] a = int(a) idea, decision=recommending(df2,a,today_stock,mean) st.write("According to the ML Predictions and Sentiment Analysis of News") st.write("Stock will ",idea) st.write("So you can",decision)
40.982993
130
0.602623
ace882f3cff8b512f0d7aa6f050412274136dab9
3,671
py
Python
dtreeviz/utils.py
Ashafix/dtreeviz
2e472d9eb53b4585a64e29ba7896efd85f1e383b
[ "MIT" ]
1
2019-11-13T13:03:37.000Z
2019-11-13T13:03:37.000Z
dtreeviz/utils.py
arita37/dtreeviz
f9e0c1b54da9c1757e4799cac02a7047b0d77bdd
[ "MIT" ]
null
null
null
dtreeviz/utils.py
arita37/dtreeviz
f9e0c1b54da9c1757e4799cac02a7047b0d77bdd
[ "MIT" ]
null
null
null
import xml.etree.cElementTree as ET from numbers import Number from typing import Tuple def inline_svg_images(svg) -> str: """ Inline IMAGE tag refs in graphviz/dot -> SVG generated files. Convert all .svg image tag refs directly under g tags like: <g id="node1" class="node"> <image xlink:href="/tmp/node4.svg" width="45px" height="76px" preserveAspectRatio="xMinYMin meet" x="76" y="-80"/> </g> to <g id="node1" class="node"> <svg width="45px" height="76px" viewBox="0 0 49.008672 80.826687" preserveAspectRatio="xMinYMin meet" x="76" y="-80"> XYZ </svg> </g> where XYZ is taken from ref'd svg image file: <?xml version="1.0" encoding="utf-8" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <!-- Created with matplotlib (http://matplotlib.org/) --> <svg height="80.826687pt" version="1.1" viewBox="0 0 49.008672 80.826687" width="49.008672pt" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> XYZ </svg> Note that width/height must be taken image ref tag and put onto svg tag. We also need the viewBox or it gets clipped a bit. :param svg: SVG string with <image/> tags. :return: svg with <image/> tags replaced with content of referenced svg image files. """ ns = {"svg": "http://www.w3.org/2000/svg"} root = ET.fromstring(svg) tree = ET.ElementTree(root) parent_map = {c: p for p in tree.iter() for c in p} # Find all image tags in document (must use svg namespace) image_tags = tree.findall(".//svg:g/svg:image", ns) for img in image_tags: # load ref'd image and get svg root svgfilename = img.attrib["{http://www.w3.org/1999/xlink}href"] with open(svgfilename, encoding='UTF-8') as f: imgsvg = f.read() imgroot = ET.fromstring(imgsvg) for k,v in img.attrib.items(): # copy IMAGE tag attributes to svg from image file if k not in {"{http://www.w3.org/1999/xlink}href"}: imgroot.attrib[k] = v # replace IMAGE with SVG tag p = parent_map[img] # print("BEFORE " + ', '.join([str(c) for c in p])) p.append(imgroot) p.remove(img) # print("AFTER " + ', '.join([str(c) for c in p])) ET.register_namespace('', "http://www.w3.org/2000/svg") ET.register_namespace('xlink', "http://www.w3.org/1999/xlink") xml_str = ET.tostring(root).decode() return xml_str def get_SVG_shape(filename) -> Tuple[Number,Number]: """ Sample line from SVG file from which we can get w,h: <svg height="122.511795pt" version="1.1" viewBox="0 0 451.265312 122.511795" width="451.265312pt" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="..."> Hmm...Seems we don't need this anymore but I will leave it just in case """ with open(filename, mode="r", encoding='UTF-8') as f: for line in f.readlines(): if line.startswith("<svg "): args = line[len("<svg "):].split() d = {} for arg in args: a = arg.split('=') if len(a) == 2: d[a[0]] = a[1].strip('"').strip('pt') return float(d['width']), float(d['height']) def myround(v,ndigits=2): return format(v, '.' + str(ndigits) + 'f') if __name__ == '__main__': # test rig with open("/tmp/foo.svg") as f: svg = f.read() svg2 = inline_svg_images(svg) print(svg2) with open("/tmp/bar.svg", "w") as f: f.write(svg2)
35.298077
125
0.585399
ace88323e3d4dd703046a7c9d653c6c104dc4552
604
py
Python
resources/scripts/invalid-paths.py
giantmonkeyTC/adasim
5c22502d0f78cb57875e8bcb7c3180859678d374
[ "MIT" ]
null
null
null
resources/scripts/invalid-paths.py
giantmonkeyTC/adasim
5c22502d0f78cb57875e8bcb7c3180859678d374
[ "MIT" ]
null
null
null
resources/scripts/invalid-paths.py
giantmonkeyTC/adasim
5c22502d0f78cb57875e8bcb7c3180859678d374
[ "MIT" ]
null
null
null
#!/usr/bin/python # # Script: # Purpose: # Author: Jochen Wuttke, wuttkej@gmail.com # Date: import sys import re import math log = open(sys.argv[1]) line_num = 0 for line in log.readlines(): line_num = line_num +1 result = re.search( "Path: \[(.*)\]", line) if ( result ): # print result.group(1) nodes = result.group(1).split(", ") n = 0 while( n < len(nodes) -1 ): if ( n < len(nodes)-2 and math.fabs( int(nodes[n]) - int(nodes[n+1])) == 84 ): print ("INVALID PATH on line " + str(line_num) + ": " + result.group(1) + ": [" + nodes[n] + ", " + nodes[n+1] + "]") break n = n+1
23.230769
121
0.574503
ace883fec0b3bdf1f852bbdba11386b981ebd044
1,089
py
Python
views.py
Nixellion/MikrotikTrafficMonitor
9a6e4aa06c6e3440bc09ab91a00b8a46ba78da7a
[ "MIT" ]
17
2020-01-05T13:49:47.000Z
2021-07-27T06:23:00.000Z
views.py
Nixellion/MikrotikTrafficMonitor
9a6e4aa06c6e3440bc09ab91a00b8a46ba78da7a
[ "MIT" ]
4
2020-06-09T05:31:18.000Z
2021-05-11T17:22:53.000Z
views.py
Nixellion/MikrotikTrafficMonitor
9a6e4aa06c6e3440bc09ab91a00b8a46ba78da7a
[ "MIT" ]
5
2020-05-25T13:09:42.000Z
2021-02-25T10:29:43.000Z
''' HTML template views, actualy website frontend stuff Could use flask-restful, I personally did not find much benefit in using it, yet. ''' import os from flask import Blueprint, request, redirect, Response, jsonify, send_from_directory, render_template from debug import catch_errors_html from paths import APP_DIR from bro_utils import render_template_themed from configuration import read_config from dbo import MonthlyArchive config = read_config() app = Blueprint("views", __name__) @app.route("/") @catch_errors_html def index(): return render_template_themed("index.html") @app.route("/months") @catch_errors_html def months(): month = request.args.get("month", None) if month == None: query = MonthlyArchive.select() else: query = MonthlyArchive.select().where(MonthlyArchive.month == int(month)) return render_template_themed("months.html", query=query) # @app.route("/download/<var1>/<var2>") # @catch_errors_html # def dl(var1, var2): # return send_from_directory(os.path.join(APP_DIR, var1), os.path.join(APP_DIR, var1, var2))
27.923077
103
0.743802
ace88651d9377ef68a4f5cc98de6be8bd13a53d1
508
py
Python
tests/r/test_forbes.py
hajime9652/observations
2c8b1ac31025938cb17762e540f2f592e302d5de
[ "Apache-2.0" ]
199
2017-07-24T01:34:27.000Z
2022-01-29T00:50:55.000Z
tests/r/test_forbes.py
hajime9652/observations
2c8b1ac31025938cb17762e540f2f592e302d5de
[ "Apache-2.0" ]
46
2017-09-05T19:27:20.000Z
2019-01-07T09:47:26.000Z
tests/r/test_forbes.py
hajime9652/observations
2c8b1ac31025938cb17762e540f2f592e302d5de
[ "Apache-2.0" ]
45
2017-07-26T00:10:44.000Z
2022-03-16T20:44:59.000Z
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.forbes import forbes def test_forbes(): """Test module forbes.py by downloading forbes.csv and testing shape of extracted data has 17 rows and 2 columns """ test_path = tempfile.mkdtemp() x_train, metadata = forbes(test_path) try: assert x_train.shape == (17, 2) except: shutil.rmtree(test_path) raise()
21.166667
43
0.75
ace887f41768c66e913a809f32d4beb328b7c984
1,607
py
Python
src/streamlink/plugins/tvrby.py
hymer-up/streamlink
f09bf6e04cddc78eceb9ded655f716ef3ee4b84f
[ "BSD-2-Clause" ]
5
2019-07-26T17:03:26.000Z
2020-10-17T23:23:43.000Z
src/streamlink/plugins/tvrby.py
hymer-up/streamlink
f09bf6e04cddc78eceb9ded655f716ef3ee4b84f
[ "BSD-2-Clause" ]
9
2018-01-14T15:20:23.000Z
2021-03-08T20:29:51.000Z
src/streamlink/plugins/tvrby.py
bumplzz69/streamlink
34abc43875d7663ebafa241573dece272e93d88b
[ "BSD-2-Clause" ]
4
2018-01-14T13:27:25.000Z
2021-11-15T22:28:30.000Z
import re from streamlink.plugin import Plugin from streamlink.plugin.api import validate from streamlink.stream import HLSStream class TVRBy(Plugin): url_re = re.compile(r"""https?://(?:www\.)?tvr.by/televidenie/belarus""") file_re = re.compile(r"""(?P<url>https://stream\.hoster\.by[^"',]+\.m3u8[^"',]*)""") player_re = re.compile(r"""["'](?P<url>[^"']+tvr\.by/plugines/online-tv-main\.php[^"']+)["']""") stream_schema = validate.Schema( validate.all( validate.transform(file_re.finditer), validate.transform(list), [validate.get("url")], # remove duplicates validate.transform(set), validate.transform(list), ), ) def __init__(self, url): # ensure the URL ends with a / if not url.endswith("/"): url += "/" super(TVRBy, self).__init__(url) @classmethod def can_handle_url(cls, url): return cls.url_re.match(url) is not None def _get_streams(self): res = self.session.http.get(self.url) m = self.player_re.search(res.text) if not m: return player_url = m.group("url") res = self.session.http.get(player_url) stream_urls = self.stream_schema.validate(res.text) self.logger.debug("Found {0} stream URL{1}", len(stream_urls), "" if len(stream_urls) == 1 else "s") for stream_url in stream_urls: for s in HLSStream.parse_variant_playlist(self.session, stream_url).items(): yield s __plugin__ = TVRBy
30.903846
100
0.583074
ace8885c2eaf2b848854da21b6ffe5524cbb6693
769
py
Python
blog_contact/migrations/0001_initial.py
hossshakiba/Django-Personal-Website-Blog
6f75a7b7d8778e556305a883f23b04d526a8d5fd
[ "MIT" ]
2
2021-01-01T08:30:39.000Z
2021-01-01T08:35:39.000Z
blog_contact/migrations/0001_initial.py
hossshakiba/Django-Personal-Website-Blog
6f75a7b7d8778e556305a883f23b04d526a8d5fd
[ "MIT" ]
null
null
null
blog_contact/migrations/0001_initial.py
hossshakiba/Django-Personal-Website-Blog
6f75a7b7d8778e556305a883f23b04d526a8d5fd
[ "MIT" ]
null
null
null
# Generated by Django 3.1 on 2020-08-22 11:23 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Contact', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('fullname', models.CharField(max_length=20)), ('email', models.EmailField(max_length=254)), ('phone', models.IntegerField(default=0)), ('subject', models.CharField(max_length=50)), ('text', models.TextField()), ('is_read', models.BooleanField()), ], ), ]
28.481481
114
0.552666
ace888793979dd0c1ad22d61cc154d0463269304
17,668
py
Python
plugins/modules/panos_facts.py
itdependsnetworks/pan-os-ansible
ce8f01170a50d9da5fbf16418b67b03b775f336b
[ "Apache-2.0" ]
null
null
null
plugins/modules/panos_facts.py
itdependsnetworks/pan-os-ansible
ce8f01170a50d9da5fbf16418b67b03b775f336b
[ "Apache-2.0" ]
null
null
null
plugins/modules/panos_facts.py
itdependsnetworks/pan-os-ansible
ce8f01170a50d9da5fbf16418b67b03b775f336b
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Tomi Raittinen <tomi.raittinen@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: panos_facts short_description: Collects facts from Palo Alto Networks device description: - Collects fact information from Palo Alto Networks firewall running PanOS. author: - Tomi Raittinen (@traittinen) - Garfield Lee Freeman (@shinmog) notes: - Tested on PanOS 8.0.5 - Checkmode is not supported. - Panorama is not supported. requirements: - pan-python version_added: 2.8 extends_documentation_fragment: - paloaltonetworks.panos.fragments.transitional_provider options: host: description: - B(Removed) - Use I(provider) instead. gather_subset: description: - Scopes what information is gathered from the device. Possible values for this argument include all, system, session, interfaces, ha, routing, vr, vsys and config. You can specify a list of values to include a larger subset. Values can also be used with an initial ! to specify that a specific subset should not be collected. Certain subsets might be supported by Panorama. required: false default: ['!config'] ''' EXAMPLES = ''' # Gather facts - name: Get facts panos_facts: provider: '{{ provider }}' gather_subset: ['config'] ''' RETURN = ''' ansible_net_hostname: description: Hostname of the local node. returned: When C(system) is specified in C(gather_subset). type: str ansible_net_serial: description: Serial number of the local node. returned: When C(system) is specified in C(gather_subset). type: str ansible_net_model: description: Device model of the local node. returned: When C(system) is specified in C(gather_subset). type: str ansible_net_version: description: PanOS version of the local node. returned: When C(system) is specified in C(gather_subset). type: str ansible_net_uptime: description: Uptime of the local node. returned: When C(system) is specified in C(gather_subset). type: str sample: 469 days, 19:30:16 ansible_net_full_commit_required: description: Specifies whether full commit is required to apply changes. returned: When C(system) is specified in C(gather_subset). type: bool ansible_net_uncommitted_changes: description: Specifies if commit is required to apply changes. returned: When C(system) is specified in C(gather_subset). type: bool ansible_net_multivsys: description: Specifies whether multivsys mode is enabled on local node. returned: When C(system) is specified in C(gather_subset). type: str sample: on ansible_net_session_usage: description: Current number of active sessions on local node returned: When C(session) is specified in C(gather_subset). type: int ansible_net_session_max: description: Maximum number of sessions on local node. returned: When C(session) is specified in C(gather_subset). type: int ansible_net_pps: description: Current packets/s throughput. returned: When C(session) is specified in C(gather_subset). type: int ansible_net_kbps: description: Current kb/s throughput. returned: When C(session) is specified in C(gather_subset). type: int ansible_net_ha_enabled: description: Specifies whether HA is enabled or not. returned: When C(ha) is specified in C(gather_subset). type: bool ansible_net_ha_localmode: description: Specifies the HA mode on local node. returned: When C(ha) is specified in C(gather_subset). type: str sample: Active-Passive ansible_net_ha_localstate: description: Specifies the HA state on local node. returned: When C(ha) is specified in C(gather_subset). type: str sample: active ansible_net_config: description: Device confiration in XML format. returned: When C(config) is specified in C(gather_subset). type: str ansible_net_interfaces: description: Network interface information. returned: When C(interface) is specified in C(gather_subset). type: complex contains: name: description: Interface name. type: str sample: ae1.23 comment: description: Interface description/comment. type: str ip: description: List of interface IP addresses in CIDR format. type: list sample: 192.0.2.1/24 ipv6: description: List of interface IPv6 addresses in CIDR format. type: list sample: 2001:db8::0000:1/64 tag: description: VLAN tag for the subinterface. type: int sample: 23 ansible_net_virtual_routers: description: Virtual Router information. returned: When C(vr) is specified in C(gather_subset). type: complex contains: vr_name: description: Name of the virtual router. type: str vr_routerid: description: BGP router ID. type: str sample: 192.0.2.1 vr_asn: description: BGP autonomous system number. type: int sample: 65001 vr_iflist: description: List interfaces in the VR. type: list sample: - ae2.12 - ae2.14 ansible_net_virtual_systems: description: Virtual System information. returned: When C(vsys) is specified in C(gather_subset). type: complex contains: vsys_description: description: VSYS description/name. type: str vsys_id: description: VSYS ID. type: int vsys_name: description: VSYS name. type: int sample: vsys1 vsys_currentsessions: description: Number of active sessions on VSYS. type: int vsys_vsys_maxsessions: description: Number of configured maximum sessions on VSYS. 0 for unlimited. type: int vsys_vrlist: description: List of virtual routers attached to the VSYS. type: list vsys_iflist: description: List of interfaces attached to the VSYS. type: list vsys_zonelist: description: List of security zones attached to the VSYS. type: list ansible_net_routing_table: description: Routing Table information. returned: When C(routing) is specified in C(gather_subset). type: complex contains: age: description: Age of the route entry in the routing table. type: str destination: description: IP prefix of the destination. type: str flags: description: Flags for the route entry in the routing table. type: str interface: description: Egress interface the router will use to reach the next hop. type: str metric: description: Metric for the route. type: str nexthop: description: Address of the device at the next hop toward the destination network. type: str route_table: description: Unicast or multicast route table. type: str virtual_router: description: Virtual router the route belongs to. type: str ''' from ansible.module_utils.basic import AnsibleModule from ansible_collections.paloaltonetworks.panos.plugins.module_utils.panos import get_connection from ansible.module_utils.six import iteritems try: from pandevice.device import Vsys from pandevice.errors import PanDeviceError from pandevice.network import AggregateInterface from pandevice.network import EthernetInterface from pandevice.network import Layer3Subinterface from pandevice.network import Layer2Subinterface from pandevice.network import IPv6Address from pandevice.network import VlanInterface from pandevice.network import LoopbackInterface from pandevice.network import TunnelInterface from pandevice.network import VirtualRouter from pandevice.network import Bgp from pandevice.network import Zone except ImportError: pass class Factbase(object): def __init__(self, module, parent): self.module = module self.parent = parent self.facts = dict() class System(Factbase): def populate_facts(self): xapi = self.parent root = xapi.op('show system info').find('./result/system') self.facts.update({ 'hostname': root.findtext('hostname'), 'model': root.findtext('model'), 'serial': root.findtext('serial'), 'version': root.findtext('sw-version'), 'uptime': root.findtext('uptime'), 'multivsys': root.findtext('multi-vsys') }) # Check uncommitted changes result = xapi.op('check pending-changes').find('./result').text if result == "yes": uncommitted_changes = True else: uncommitted_changes = False # Check if full commit is required if uncommitted_changes: result = xapi.op('check full-commit-required').find('./result').text if result == "yes": full_commit_required = True else: full_commit_required = False else: full_commit_required = False self.facts.update({ 'uncommitted_changes': uncommitted_changes, 'full_commit_required': full_commit_required }) class Session(Factbase): def populate_facts(self): root = self.parent.op('show session info') self.facts.update({ 'session_usage': root.find('./result/num-active').text, 'session_max': root.find('./result/num-max').text, 'pps': root.find('./result/pps').text, 'kbps': root.find('./result/kbps').text }) class Routing(Factbase): def populate_facts(self): entries = self.parent.op('show routing route').findall('./result/entry') routing_table = [ {route.tag.replace('-', '_'): route.text for route in entry} for entry in entries ] self.facts.update({ 'routing_table': routing_table }) class Interfaces(Factbase): def populate_facts(self): interfaces = [] cls_types = (AggregateInterface, EthernetInterface, VlanInterface, LoopbackInterface, TunnelInterface) for cls_type in cls_types: listing = cls_type.refreshall(self.parent, add=False) for elm in listing: iface_info = { 'name': elm.name, 'comment': elm.comment, 'ip': getattr(elm, 'ip', []), 'ipv6': [], } for child in elm.children: if isinstance(child, IPv6Address): iface_info['ipv6'].append(child.uid) elif isinstance(child, Layer3Subinterface) or isinstance(child, Layer2Subinterface): child_info = { 'name': child.name, 'comment': child.comment, 'tag': child.tag, 'ip': getattr(child, 'ip', []), 'ipv6': [], } for sub_child in child.children: if isinstance(child, IPv6Address): child_info['ipv6'].append(sub_child.name) interfaces.append(child_info) interfaces.append(iface_info) newlist = sorted(interfaces, key=lambda k: k['name']) self.facts.update({ 'interfaces': newlist }) class Ha(Factbase): def populate_facts(self): root = self.parent.op('show high-availability all') if root.find('./result/enabled').text == 'yes': ha_enabled = True ha_localmode = root.find('./result/group/local-info/mode').text ha_localstate = root.find('./result/group/local-info/state').text else: ha_enabled = False ha_localmode = "standalone" ha_localstate = "active" self.facts.update({ 'ha_enabled': ha_enabled, 'ha_localmode': ha_localmode, 'ha_localstate': ha_localstate }) class Vr(Factbase): def populate_facts(self): listing = VirtualRouter.refreshall(self.parent, add=False) virtual_routers = [] for vr in listing: info = { 'vr_name': vr.name, 'vr_iflist': vr.interface or [], 'vr_asn': None, 'vr_routerid': None, } for child in vr.children: if isinstance(child, Bgp): info['vr_asn'] = child.local_as info['vr_routerid'] = child.router_id virtual_routers.append(info) self.facts.update({ 'virtual_routers': virtual_routers }) class VsysFacts(Factbase): def populate_facts(self): # Get session usage XML session_root = self.parent.op('show session meter') # Loop through all VSYS virtual_systems = [] vsys_list = Vsys.refreshall(self.parent, name_only=True) for vsys in vsys_list: for var in ('display_name', 'interface', 'virtual_routers'): vsys.refresh_variable(var) zones = [x.name for x in Zone.refreshall(vsys, name_only=True)] vsys_id = vsys.name[4:] vsys_sessions = session_root.find(".//entry/[vsys='" + vsys_id + "']") vsys_currentsessions = vsys_sessions.find('.//current').text vsys_maxsessions = vsys_sessions.find('.//maximum').text virtual_systems.append({ 'vsys_id': vsys_id, 'vsys_name': vsys.name, 'vsys_description': vsys.display_name, 'vsys_iflist': vsys.interface, 'vsys_vrlist': vsys.virtual_routers, 'vsys_zonelist': zones, 'vsys_maxsessions': vsys_maxsessions, 'vsys_currentsessions': vsys_currentsessions, }) self.facts.update({ 'virtual-systems': virtual_systems }) class Config(Factbase): def populate_facts(self): self.parent.xapi.show() config = self.parent.xapi.xml_result().encode('utf-8') self.facts.update({ 'config': config }) FACT_SUBSETS = dict( system=System, session=Session, interfaces=Interfaces, ha=Ha, vr=Vr, vsys=VsysFacts, config=Config, routing=Routing, ) VALID_SUBSETS = frozenset(FACT_SUBSETS.keys()) def main(): helper = get_connection( with_classic_provider_spec=True, panorama_error='This module is for firewall facts only', argument_spec=dict( gather_subset=dict(default=['!config'], type='list'), # TODO(gfreeman) - remove in a later version. host=dict(), ), ) module = AnsibleModule( argument_spec=helper.argument_spec, supports_check_mode=False, required_one_of=helper.required_one_of, ) # TODO(gfreeman) - remove in a later version. if module.params['host'] is not None: module.fail_json(msg='Param "host" is removed; use "provider" instead') parent = helper.get_pandevice_parent(module) gather_subset = module.params['gather_subset'] runable_subsets = set() exclude_subsets = set() for subset in gather_subset: if subset == 'all': runable_subsets.update(VALID_SUBSETS) continue if subset.startswith('!'): subset = subset[1:] if subset == 'all': exclude_subsets.update(VALID_SUBSETS) continue exclude = True else: exclude = False if subset not in VALID_SUBSETS: module.fail_json(msg='Subset must be one of [%s], got %s' % (', '.join(VALID_SUBSETS), subset)) if exclude: exclude_subsets.add(subset) else: runable_subsets.add(subset) if not runable_subsets: runable_subsets.update(VALID_SUBSETS) runable_subsets.difference_update(exclude_subsets) runable_subsets.add('system') facts = dict() facts['gather_subset'] = list(runable_subsets) # Create instance classes, e.g. System, Session etc. instances = list() for key in runable_subsets: instances.append(FACT_SUBSETS[key](module, parent)) # Populate facts for instances for inst in instances: inst.populate_facts() facts.update(inst.facts) ansible_facts = dict() for key, value in iteritems(facts): key = 'ansible_net_%s' % key ansible_facts[key] = value module.exit_json(ansible_facts=ansible_facts) if __name__ == '__main__': main()
32.065336
110
0.610029
ace88a683cd0e8640ec77bbe765b863683ed3a5e
6,253
py
Python
feats/feats_filtering.py
edwinv87/feats
b72de7f55cf757840cc0578008409dc420736372
[ "MIT" ]
1
2020-12-09T03:33:43.000Z
2020-12-09T03:33:43.000Z
feats/feats_filtering.py
edwinv87/feats
b72de7f55cf757840cc0578008409dc420736372
[ "MIT" ]
null
null
null
feats/feats_filtering.py
edwinv87/feats
b72de7f55cf757840cc0578008409dc420736372
[ "MIT" ]
null
null
null
import numpy as np def LogFilter(sc): """ Computes and stores the log-transformed gene expression data stored in SingleCell object. Here Log2 is performed after adding a pseudocount of 1. Parameters ---------- sc : SingleCell The SingleCell object containing gene expression data. Returns ------- sc : SingleCell The SingleCell object containing the log-transfprmed gene expression data. """ X = sc.getCounts() X = np.log2(X + 1) sc.setCounts(X) return sc def HVGFilter(sc, num_genes, name_by = 'gene_names'): """ Filters/Selects the Highly Variable Genes in the SingleCell object by computing the dispersion of each gene. Returns a sliced SingleCell object containing the top Highly Variable Genes. Stores additional information such as dispersion ('FEATS_dispersion), mean ('FEATS_mean') and variance ('FEATS_variance') in the genedata assay of SingleCell object. Parameters ---------- sc : SingleCell The SingleCell object containing gene expression data. num_genes : int The number of Highly Variable Genes to select. name_by : str The name of the column in SingleCell object that stores the gene names. This is used to print the top Highly Variable Genes. Returns ------- sc : SingleCell A sliced SingleCell object containing the top Highly Variable Genes. """ # compute dispersion and store it in sc object (genedata assay) X = sc.getCounts() var_bat = np.var(X, axis = 1) mu_bat = np.mean(X, axis = 1) dispersion = var_bat/mu_bat idx = np.argsort(dispersion) idx = idx[::-1] # Print if gene names are available if (sc.checkGeneData(name_by)): gene_names = sc.getGeneData(name_by) print("The top ", num_genes, " highly variable genes are: ") print(gene_names[idx[0:num_genes]]) hvg = np.zeros(dispersion.shape, dtype = bool) for i in range(num_genes): hvg[idx[i]] = True # Save the data sc.addGeneData(dispersion, "FEATS_dispersion") sc.addGeneData(var_bat, "FEATS_variance") sc.addGeneData(mu_bat, "FEATS_mean") sc.addGeneData(hvg, "FEATS_hvg") sc = sc[hvg, :] return sc def GeneFilter(sc, min_cells, max_cells, expr_thres = 0): """ Filters the lowly and/or highly expressed genes stored in the SingleCell object based on the expression counts. Returns the sliced SingleCell object with the genes selected through the filtering criteria. This functions skips filtering and warns the user if the filtering criteria filters out all the genes. Parameters ---------- sc : SingleCell The SingleCell object containing gene expression data. min_cells : int The minimum number of cells in which the gene must be expressed with the expression threshold. The value should be >= 0 and <= n, where n is the number of cells the the dataset. max_cells : int The maximum number of cells in which the gene must be expressed with the expression threshold. The value should be >= 0 and <= n, where n is the number of cells the the dataset. expr_thres : int, optional The expression threshold. Default 0. The gene is considered not expressed if the expression count is <= this threshold. Returns ------- sc : SingleCell A sliced SingleCell object containing the filtered genes. """ print("Applying Gene Filter . . .") X = sc.getCounts() expr_count = np.sum(X > expr_thres, axis = 1, keepdims = False) gene_filter = (expr_count <= max_cells) & (expr_count >= min_cells) print("Number of features remaining after gene filtering: ", np.sum(gene_filter)) # If gene filtering removes all features: if (np.sum(gene_filter) != 0): # Save the gene filter mask # sc_obj.addGeneDataColumn(col_data = gene_filter, col_name = "gene_filter") sc = sc[gene_filter, :] else: print ("Gene filtering removed all the features!") print ("Set different gene filter parameters.") print ("Skipping Gene Filtering step...") return sc def CellFilter(sc, min_genes, max_genes, expr_thres = 0): """ Filters the cells in which the genes are lowly and/or highly expressed. Returns the sliced SingleCell object with the cells selected through the filtering criteria. This functions skips filtering and warns the user if the filtering criteria filters out all the samples/cells. Parameters ---------- sc : SingleCell The SingleCell object containing gene expression data. min_genes : int The minimum number of genes in the cell in which the genes must be expressed with the expression threshold. The value should be >= 0 and <= d, where d is the number of genes the the dataset. max_genes : int The maximum number of genes in the cell in which the gene must be expressed with the expression threshold. The value should be >= 0 and <= d, where d is the number of genes the the dataset. expr_thres : int, optional The expression threshold. Default 0. The gene is considered not expressed if the expression count is <= this threshold. Returns ------- sc : SingleCell A sliced SingleCell object containing the filtered cells. """ print("Applying Cell Filter . . .") X = sc.getCounts() expr_count = np.sum(X , axis = 0, keepdims = False) cell_filter = (expr_count <= max_genes) & (expr_count >= min_genes) print("Number of samples remaining after cell filtering: ", np.sum(cell_filter)) # If cell filtering removes all samples: if (np.sum(cell_filter) != 0): # Save the cell filter mask # sc_obj.addCellDataColumn(col_data = cell_filter, col_name = "cell_filter") sc = sc[:, cell_filter] else: print ("Cell filtering removed all the samples!") print ("Set different cell filter parameters.") print ("Skipping Cell Filtering step...") return sc
30.502439
97
0.655206
ace88ac946ecaa12dfcc4105fdeaf20e9c2b6db7
1,832
py
Python
Lib/tkinter/scrolledtext.py
sireliah/polish-python
605df4944c2d3bc25f8bf6964b274c0a0d297cc3
[ "PSF-2.0" ]
1
2018-06-21T18:21:24.000Z
2018-06-21T18:21:24.000Z
Lib/tkinter/scrolledtext.py
sireliah/polish-python
605df4944c2d3bc25f8bf6964b274c0a0d297cc3
[ "PSF-2.0" ]
null
null
null
Lib/tkinter/scrolledtext.py
sireliah/polish-python
605df4944c2d3bc25f8bf6964b274c0a0d297cc3
[ "PSF-2.0" ]
null
null
null
"""A ScrolledText widget feels like a text widget but also has a vertical scroll bar on its right. (Later, options may be added to add a horizontal bar jako well, to make the bars disappear automatically when nie needed, to move them to the other side of the window, etc.) Configuration options are dalejed to the Text widget. A Frame widget jest inserted between the master oraz the text, to hold the Scrollbar widget. Most methods calls are inherited z the Text widget; Pack, Grid oraz Place methods are redirected to the Frame widget however. """ __all__ = ['ScrolledText'] z tkinter zaimportuj Frame, Text, Scrollbar, Pack, Grid, Place z tkinter.constants zaimportuj RIGHT, LEFT, Y, BOTH klasa ScrolledText(Text): def __init__(self, master=Nic, **kw): self.frame = Frame(master) self.vbar = Scrollbar(self.frame) self.vbar.pack(side=RIGHT, fill=Y) kw.update({'yscrollcommand': self.vbar.set}) Text.__init__(self, self.frame, **kw) self.pack(side=LEFT, fill=BOTH, expand=Prawda) self.vbar['command'] = self.yview # Copy geometry methods of self.frame without overriding Text # methods -- hack! text_meths = vars(Text).keys() methods = vars(Pack).keys() | vars(Grid).keys() | vars(Place).keys() methods = methods.difference(text_meths) dla m w methods: jeżeli m[0] != '_' oraz m != 'config' oraz m != 'configure': setattr(self, m, getattr(self.frame, m)) def __str__(self): zwróć str(self.frame) def example(): z tkinter.constants zaimportuj END stext = ScrolledText(bg='white', height=10) stext.insert(END, __doc__) stext.pack(fill=BOTH, side=LEFT, expand=Prawda) stext.focus_set() stext.mainloop() jeżeli __name__ == "__main__": example()
33.309091
76
0.674672
ace88b244c67cf333314acaad39c741268f7ccf9
4,282
py
Python
jiraticketing/views.py
GMedian/archerysec
9591fdb6b21ca56d77364d1433acbaff84437c7f
[ "BSD-3-Clause" ]
1
2018-11-10T22:34:27.000Z
2018-11-10T22:34:27.000Z
jiraticketing/views.py
GMedian/archerysec
9591fdb6b21ca56d77364d1433acbaff84437c7f
[ "BSD-3-Clause" ]
8
2020-02-12T00:43:21.000Z
2022-03-11T23:25:08.000Z
jiraticketing/views.py
GMedian/archerysec
9591fdb6b21ca56d77364d1433acbaff84437c7f
[ "BSD-3-Clause" ]
1
2018-08-12T17:29:35.000Z
2018-08-12T17:29:35.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, render_to_response, HttpResponseRedirect from jiraticketing.models import jirasetting from django.core import signing from jira import JIRA from webscanners.models import zap_scan_results_db, burp_scan_result_db, arachni_scan_result_db from networkscanners.models import ov_scan_result_db, nessus_report_db def jira_setting(request): if request.method == 'POST': jira_url = request.POST.get('jira_url') jira_username = request.POST.get('jira_username') jira_password = request.POST.get('jira_password') username = signing.dumps(jira_username) password = signing.dumps(jira_password) save_data = jirasetting(jira_server=jira_url, jira_username=username, jira_password=password) save_data.save() return render(request, 'jira_setting_form.html') def submit_jira_ticket(request): jira_setting = jirasetting.objects.all() for jira in jira_setting: jira_url = jira.jira_server username = jira.jira_username password = jira.jira_password jira_server = jira_url jira_username = signing.loads(username) jira_password = signing.loads(password) options = {'server': jira_server} jira_ser = JIRA(options, basic_auth=(jira_username, jira_password)) jira_projects = jira_ser.projects() if request.method == 'GET': summary = request.GET['summary'] description = request.GET['description'] scanner = request.GET['scanner'] vuln_id = request.GET['vuln_id'] scan_id = request.GET['scan_id'] return render(request, 'submit_jira_ticket.html', {'jira_projects': jira_projects, 'summary': summary, 'description': description, 'scanner': scanner, 'vuln_id': vuln_id, 'scan_id': scan_id }) if request.method == 'POST': summary = request.POST.get('summary') description = request.POST.get('description') project_id = request.POST.get('project_id') issue_type = request.POST.get('issue_type') vuln_id = request.POST.get('vuln_id') scanner = request.POST.get('scanner') scan_id = request.POST.get('scan_id') issue_dict = { 'project': {'id': project_id}, 'summary': summary, 'description': description, 'issuetype': {'name': issue_type}, } new_issue = jira_ser.create_issue(fields=issue_dict) print new_issue if scanner == 'zap': zap_scan_results_db.objects.filter(vuln_id=vuln_id).update(jira_ticket=new_issue) return HttpResponseRedirect('/webscanners/zap_vul_details/?scan_id=%s&scan_name=%s' % ( scan_id, summary ) ) elif scanner == 'burp': burp_scan_result_db.objects.filter(vuln_id=vuln_id).update(jira_ticket=new_issue) return HttpResponseRedirect('/webscanners/burp_vuln_out/?scan_id=%s&scan_name=%s' % ( scan_id, summary ) ) elif scanner == 'arachni': arachni_scan_result_db.objects.filter(vuln_id=vuln_id).update(jira_ticket=new_issue) return HttpResponseRedirect('/webscanners/arachni_vuln_out/?scan_id=%s&scan_name=%s' % (scan_id, summary)) elif scanner == 'open_vas': ov_scan_result_db.objects.filter(vul_id=vuln_id).update(jira_ticket=new_issue) return HttpResponseRedirect('/networkscanners/vul_details/?scan_id=%s' % scan_id) elif scanner == 'nessus': nessus_report_db.objects.filter(vul_id=vuln_id).update(jira_ticket=new_issue) return HttpResponseRedirect('/networkscanners/nessus_vuln_details/?scan_id=%s' % scan_id) # return render(request, 'submit_jira_ticket.html')
42.39604
118
0.605792
ace88da6efcb274d5005012b2bc033f84accf1ac
24,084
py
Python
temas/IV.optimizacion_convexa_y_machine_learning/algoritmos/Python/algorithms_for_cieco.py
Danahirmt/analisis-numerico-computo-cientifico
ec42457dc8f707ce8d481cb62441d29fc0a9ab52
[ "Apache-2.0" ]
null
null
null
temas/IV.optimizacion_convexa_y_machine_learning/algoritmos/Python/algorithms_for_cieco.py
Danahirmt/analisis-numerico-computo-cientifico
ec42457dc8f707ce8d481cb62441d29fc0a9ab52
[ "Apache-2.0" ]
null
null
null
temas/IV.optimizacion_convexa_y_machine_learning/algoritmos/Python/algorithms_for_cieco.py
Danahirmt/analisis-numerico-computo-cientifico
ec42457dc8f707ce8d481cb62441d29fc0a9ab52
[ "Apache-2.0" ]
null
null
null
import math import numpy as np from utils import compute_error, logarithmic_barrier, \ constraint_inequalities_funcs_eval, \ norm_residual from line_search import line_search_for_log_barrier_by_backtracking, \ line_search_for_residual_by_backtracking from numerical_differentiation import numerical_differentiation_of_logarithmic_barrier, \ gradient_approximation, Hessian_approximation def path_following_method_feasible_init_point(f, A, constraints_ineq, x_0, tol, tol_backtracking, x_ast=None, p_ast=None, maxiter=30, mu=None, gf_symbolic=None, Hf_symbolic=None, tol_outer_iter=1e-6,maxiter_path=30 ): m = len(constraints_ineq.keys()) if p_ast: t_0 = m/math.fabs(f(x_0)-p_ast) #other option: t_0 = mu*m/(f(x_0)-p_ast) else: print("p_ast must be defined") t = t_0 x = x_0 log_barrier_eval = logarithmic_barrier(f,x,t,constraints_ineq) stopping_criteria = m/t outer_iter = 1 const_ineq_funcs_eval = constraint_inequalities_funcs_eval(x,constraints_ineq) print("Outer iterations of path following method") print('{} {:0.2e}'.format("Mu value:", mu)) print('Outer iteration\tLogBarrier \tt_log_barrier\tStopping criteria') print('{}\t\t{:0.2e}\t{:0.2e}\t{:0.2e}'.format(outer_iter,log_barrier_eval, t,stopping_criteria )) print("----------------------------------------------------------------------------------------") iter_barrier = 0 while(stopping_criteria > tol_outer_iter and outer_iter < maxiter_path): [x,iteration,Err_plot,x_plot] = Newtons_method_log_barrier_feasible_init_point(f, A, constraints_ineq, t, x_0, tol, tol_backtracking, x_ast, p_ast, maxiter, gf_symbolic, Hf_symbolic) print("Inner iterations") print(x) const_ineq_funcs_eval = constraint_inequalities_funcs_eval(x,constraints_ineq) if(sum(const_ineq_funcs_eval > np.nextafter(0,1)) >=1): print("Some constraint inequalities evaluated in x were nonnegative, check approximations") t=mu*t log_barrier_eval = logarithmic_barrier(f,x,t,constraints_ineq) outer_iter+=1 stopping_criteria = m/t print("----------------------------------------------------------------------------------------") print("Outer iterations of path following method") print('{} {:0.2e}'.format("Mu value:", mu)) print('Outer iteration\tLogBarrier \tt_log_barrier\tStopping criteria') print('{}\t\t{:0.2e}\t{:0.2e}\t{:0.2e}'.format(outer_iter,log_barrier_eval, t,stopping_criteria )) print("----------------------------------------------------------------------------------------") iter_barrier+= iter_barrier + iteration return [x,iter_barrier,t] def Newtons_method_log_barrier_feasible_init_point(f, A, constraint_inequalities, t_path, x_0, tol, tol_backtracking, x_ast=None, p_ast=None, maxiter=30, gf_symbolic = None, Hf_symbolic = None): ''' Newton's method to numerically approximate solution of min f subject to Ax = b. IMPORTANT: this implementation requires that initial point x_0, satisfies: Ax_0 = b Args: f (fun): definition of function f as lambda expression or function definition. A (numpy ndarray): 2d numpy array of shape (m,n) defines system of constraints Ax=b. constraints_ineq t_path x_0 (numpy ndarray): initial point for Newton's method. Must satisfy: Ax_0 = b tol (float): tolerance that will halt method. Controls stopping criteria. tol_backtracking (float): tolerance that will halt method. Controls value of line search by backtracking. x_ast (numpy ndarray): solution of min f, now it's required that user knows the solution... p_ast (float): value of f(x_ast), now it's required that user knows the solution... maxiter (int): maximum number of iterations gf_symbolic (fun): definition of gradient of f. If given, no approximation is performed via finite differences. Hf_symbolic (fun): definition of Hessian of f. If given, no approximation is performed via finite differences. Returns: x (numpy ndarray): numpy array, approximation of x_ast. iteration (int): number of iterations. Err_plot (numpy ndarray): numpy array of absolute error between p_ast and f(x) with x approximation of x_ast. Useful for plotting. x_plot (numpy ndarray): numpy array that containts in columns vector of approximations. Last column contains x, approximation of solution. Useful for plotting. ''' iteration = 0 x = x_0 feval = f(x) if gf_symbolic and Hf_symbolic: gfeval = gf_symbolic(x) Hfeval = Hf_symbolic(x) else: grad_Hess_log_barrier_dict = numerical_differentiation_of_logarithmic_barrier(f,x,t_path, constraint_inequalities) gfeval = grad_Hess_log_barrier_dict['gradient'] Hfeval = grad_Hess_log_barrier_dict['Hessian'] normgf = np.linalg.norm(gfeval) condHf= np.linalg.cond(Hfeval) Err_plot_aux = np.zeros(maxiter) Err_plot_aux[iteration]=compute_error(p_ast,feval) Err = compute_error(x_ast,x) if (np.all(A < np.nextafter(0,1))): #A is zero matrix system_matrix = Hfeval rhs = -gfeval n = x.size p = 0 else: first_stack = np.column_stack((Hfeval, A.T)) if(A.ndim == 1): p = 1 n = x.size zero_matrix = np.zeros(p) second_stack = np.row_stack((A.reshape(1,n).T,zero_matrix)).reshape(1,n+1)[0] else: p,n = A.shape zero_matrix = np.zeros((p,p)) second_stack = np.column_stack((A,zero_matrix)) system_matrix = np.row_stack((first_stack,second_stack)) zero_vector = np.zeros(p) rhs = -np.row_stack((gfeval.reshape(n,1), zero_vector.reshape(p,1))).T[0] x_plot = np.zeros((n,maxiter)) x_plot[:,iteration] = x #Newton's direction and Newton's decrement dir_desc = np.linalg.solve(system_matrix, rhs) dir_Newton = dir_desc[0:n] dec_Newton = -gfeval.dot(dir_Newton) w_dual_variable_estimation = dir_desc[n:(n+p)] print('I\tNorm gfLogBarrier \tNewton Decrement\tError x_ast\tError p_ast\tline search\tCondHf') print('{}\t\t{:0.2e}\t\t{:0.2e}\t{:0.2e}\t{:0.2e}\t{}\t\t{:0.2e}'.format(iteration,normgf, dec_Newton,Err, Err_plot_aux[iteration],"---", condHf)) stopping_criteria = dec_Newton/2 iteration+=1 while(stopping_criteria>tol and iteration < maxiter): der_direct = -dec_Newton t = line_search_for_log_barrier_by_backtracking(f,dir_Newton,x,t_path, constraint_inequalities, der_direct) x = x + t*dir_Newton feval = f(x) if gf_symbolic and Hf_symbolic: gfeval = gf_symbolic(x) Hfeval = Hf_symbolic(x) else: grad_Hess_log_barrier_dict = numerical_differentiation_of_logarithmic_barrier(f,x,t_path, constraint_inequalities) gfeval = grad_Hess_log_barrier_dict['gradient'] Hfeval = grad_Hess_log_barrier_dict['Hessian'] if (np.all(A < np.nextafter(0,1))): #A is zero matrix system_matrix = Hfeval rhs = -gfeval n = x.size p = 0 else: first_stack = np.column_stack((Hfeval, A.T)) system_matrix = np.row_stack((first_stack,second_stack)) rhs = -np.row_stack((gfeval.reshape(n,1), zero_vector.reshape(p,1))).T[0] #Newton's direction and Newton's decrement dir_desc = np.linalg.solve(system_matrix, rhs) dir_Newton = dir_desc[0:n] dec_Newton = -gfeval.dot(dir_Newton) w_dual_variable_estimation = dir_desc[n:(n+p)] Err_plot_aux[iteration]=compute_error(p_ast,feval) x_plot[:,iteration] = x Err = compute_error(x_ast,x) print('{}\t\t{:0.2e}\t\t{:0.2e}\t{:0.2e}\t{:0.2e}\t{:0.2e}\t{:0.2e}'.format(iteration,normgf, dec_Newton,Err, Err_plot_aux[iteration],t, condHf)) stopping_criteria = dec_Newton/2 if t<tol_backtracking: #if t is less than tol_backtracking then we need to check the reason iter_salida=iteration iteration = maxiter - 1 iteration+=1 print('{} {:0.2e}'.format("Error of x with respect to x_ast:",Err)) print('{} {}'.format("Approximate solution:", x)) cond = Err_plot_aux > np.finfo(float).eps*10**(-2) Err_plot = Err_plot_aux[cond] if iteration == maxiter and t < tol_backtracking: print("Backtracking value less than tol_backtracking, check approximation") iteration=iter_salida else: if iteration == maxiter: print("Reached maximum of iterations, check approximation") x_plot = x_plot[:,:iteration] return [x,iteration,Err_plot,x_plot] def path_following_method_infeasible_init_point(f, A, b, constraints_ineq, x_0, nu_0,tol, tol_backtracking, x_ast=None, p_ast=None, maxiter=30, mu=None, gf_symbolic=None, Hf_symbolic=None, tol_outer_iter=1e-6,maxiter_path=30 ): m = len(constraints_ineq.keys()) if p_ast: t_0 = m/math.fabs(f(x_0)-p_ast) #other option: t_0 = mu*m/(f(x_0)-p_ast) else: print("p_ast must be defined") t = t_0 x = x_0 log_barrier_eval = logarithmic_barrier(f,x,t,constraints_ineq) stopping_criteria = m/t outer_iter = 1 const_ineq_funcs_eval = constraint_inequalities_funcs_eval(x,constraints_ineq) print("Outer iterations of path following method") print('{} {:0.2e}'.format("Mu value:", mu)) print('Outer iteration\tLogBarrier \tt_log_barrier\tStopping criteria') print('{}\t\t{:0.2e}\t{:0.2e}\t{:0.2e}'.format(outer_iter,log_barrier_eval, t,stopping_criteria )) print("----------------------------------------------------------------------------------------") iter_barrier = 0 while(stopping_criteria > tol_outer_iter and outer_iter < maxiter_path): [x,iteration,Err_plot,x_plot] = Newtons_method_log_barrier_infeasible_init_point(f, A, b, constraints_ineq, t, x_0, nu_0,tol, tol_backtracking, x_ast, p_ast, maxiter, gf_symbolic, Hf_symbolic) print("Inner iterations") print(x) const_ineq_funcs_eval = constraint_inequalities_funcs_eval(x,constraints_ineq) if(sum(const_ineq_funcs_eval > np.nextafter(0,1)) >=1): print("Some constraint inequalities evaluated in x were nonnegative, check approximations") t=mu*t log_barrier_eval = logarithmic_barrier(f,x,t,constraints_ineq) outer_iter+=1 stopping_criteria = m/t print("----------------------------------------------------------------------------------------") print("Outer iterations of path following method") print('{} {:0.2e}'.format("Mu value:", mu)) print('Outer iteration\tLogBarrier \tt_log_barrier\tStopping criteria') print('{}\t\t{:0.2e}\t{:0.2e}\t{:0.2e}'.format(outer_iter,log_barrier_eval, t,stopping_criteria )) print("----------------------------------------------------------------------------------------") iter_barrier+= iter_barrier + iteration return [x,iter_barrier,t] def Newtons_method_log_barrier_infeasible_init_point(f, A, b, constraint_inequalities, t_path, x_0, nu_0, tol, tol_backtracking, x_ast=None, p_ast=None, maxiter=30, gf_symbolic = None, Hf_symbolic = None): ''' Newton's method for infeasible initial point to numerically approximate solution of min f subject to Ax = b. Calls Newton's method for feasible initial point when reach primal feasibility given by tol. Args: f (fun): definition of function f as lambda expression or function definition. A (numpy ndarray): 2d numpy array of shape (m,n) defines system of constraints Ax=b. b (numpy ndarray or float): array that defines system of constraints Ax=b (can be a single number if just one restriction is defined) constraints_ineq t_path x_0 (numpy ndarray): initial point for Newton's method. nu_0 (numpy ndarray or float): initial point for Newton's method. tol (float): tolerance that will halt method. Controls stopping criteria. tol_backtracking (float): tolerance that will halt method. Controls value of line search by backtracking. x_ast (numpy ndarray): solution of min f, now it's required that user knows the solution... p_ast (float): value of f(x_ast), now it's required that user knows the solution... maxiter (int): maximum number of iterations gf_symbolic (fun): definition of gradient of f. If given, no approximation is performed via finite differences. Hf_symbolic (fun): definition of Hessian of f. If given, no approximation is performed via finite differences. Returns: x (numpy ndarray): numpy array, approximation of x_ast. iteration (int): number of iterations. Err_plot (numpy ndarray): numpy array of absolute error between p_ast and f(x) with x approximation of x_ast. Useful for plotting. x_plot (numpy ndarray): numpy array that containts in columns vector of approximations. Last column contains x, approximation of solution. Useful for plotting. ''' iteration = 0 x = x_0 nu = nu_0 feval = f(x) if gf_symbolic and Hf_symbolic: gfeval = gf_symbolic(x) Hfeval = Hf_symbolic(x) else: grad_Hess_log_barrier_dict = numerical_differentiation_of_logarithmic_barrier(f,x,t_path, constraint_inequalities) gfeval = grad_Hess_log_barrier_dict['gradient'] Hfeval = grad_Hess_log_barrier_dict['Hessian'] normgf = np.linalg.norm(gfeval) condHf= np.linalg.cond(Hfeval) Err_x_ast = compute_error(x_ast,x) Err_p_ast = compute_error(p_ast,feval) def residual_dual(nu_fun): if(A.ndim==1): return gfeval + A.T*nu_fun else: return gfeval + A.T@nu_fun feasibility_dual = residual_dual(nu) if (np.all(A < np.nextafter(0,1))): #A is zero matrix system_matrix = Hfeval rhs = -gfeval n = x.size p = 0 feasibility_primal = 0 else: first_stack = np.column_stack((Hfeval, A.T)) if(A.ndim == 1): p = 1 n = x.size zero_matrix = np.zeros(p) second_stack = np.row_stack((A.reshape(1,n).T,zero_matrix)).reshape(1,n+1)[0] else: p,n = A.shape zero_matrix = np.zeros((p,p)) second_stack = np.column_stack((A,zero_matrix)) system_matrix = np.row_stack((first_stack,second_stack)) residual_primal = lambda x_fun: A@x_fun-b feasibility_primal = residual_primal(x) rhs = -np.row_stack((feasibility_dual.reshape(n,1), feasibility_primal.reshape(p,1))).T[0] #Newton's direction and Newton's decrement dir_desc = np.linalg.solve(system_matrix, rhs) dir_Newton_primal = dir_desc[0:n] dec_Newton = -gfeval.dot(dir_Newton_primal) dir_Newton_dual = dir_desc[n:(n+p)] norm_residual_eval = norm_residual(feasibility_primal, feasibility_dual) norm_residual_primal = np.linalg.norm(feasibility_primal) norm_residual_dual = np.linalg.norm(feasibility_dual) print('I\t||res_primal||\t||res_dual|| \tNewton Decrement\tError x_ast\tError p_ast\tline search\tCondHf') print('{}\t{:0.2e}\t{:0.2e}\t{:0.2e}\t{:0.2e}\t{:0.2e}\t{}\t\t{:0.2e}'.format(iteration,norm_residual_primal, norm_residual_dual, dec_Newton,Err_x_ast, Err_p_ast,"---", condHf)) stopping_criteria = norm_residual_primal # or norm_residual_eval? iteration+=1 while(stopping_criteria>tol and iteration < maxiter): der_direct = -dec_Newton t = line_search_for_residual_by_backtracking(residual_primal, residual_dual, dir_Newton_primal, dir_Newton_dual, x, nu, norm_residual_eval ) x = x + t*dir_Newton_primal nu = nu + t*dir_Newton_dual feval = f(x) if gf_symbolic: gfeval = gf_symbolic(x) else: gfeval = gradient_approximation(f,x) if Hf_symbolic: Hfeval = Hf_symbolic(x) else: Hfeval = Hessian_approximation(f,x) first_stack = np.column_stack((Hfeval, A.T)) system_matrix = np.row_stack((first_stack,second_stack)) feasibility_primal = residual_primal(x) feasibility_dual = residual_dual(nu) rhs = -np.row_stack((feasibility_dual.reshape(n,1), feasibility_primal.reshape(p,1))).T[0] #Newton's direction and Newton's decrement dir_desc = np.linalg.solve(system_matrix, rhs) dir_Newton_primal = dir_desc[0:n] dec_Newton = -gfeval.dot(dir_Newton_primal) dir_Newton_dual = dir_desc[n:(n+p)] Err_x_ast = compute_error(x_ast,x) Err_p_ast = compute_error(p_ast,feval) norm_residual_eval = norm_residual(feasibility_primal, feasibility_dual) norm_residual_primal = np.linalg.norm(feasibility_primal) norm_residual_dual = np.linalg.norm(feasibility_dual) print('{}\t{:0.2e}\t{:0.2e}\t{:0.2e}\t{:0.2e}\t{:0.2e}\t{:0.2e}\t{:0.2e}'.format(iteration,norm_residual_primal, norm_residual_dual, dec_Newton,Err_x_ast, Err_p_ast,t, condHf)) stopping_criteria = norm_residual_primal # or norm_residual_eval? if t<tol_backtracking: #if t is less than tol_backtracking then we need to check the reason iteration = maxiter - 1 iteration+=1 if iteration == maxiter and t < tol_backtracking: print("Backtracking value less than tol_backtracking, try other initial point") return [None,None,None,None] else: if iteration == maxiter: print("------------------------------------------------------------") print("------------------------------------------------------------") print("------------------------------------------------------------") print("Reached maximum of iterations, check primal feasibility") print("Continuing with Newtons method for feasible initial point") return Newtons_method_log_barrier_feasible_init_point(f,A, constraint_inequalities, t_path, x,tol, tol_backtracking, x_ast, p_ast, maxiter,gf_symbolic,Hf_symbolic) else: print("------------------------------------------------------------") print("------------------------------------------------------------") print("------------------------------------------------------------") print("Beginning Newtons method for feasible initial point") return Newtons_method_log_barrier_feasible_init_point(f,A, constraint_inequalities, t_path, x,tol, tol_backtracking, x_ast, p_ast, maxiter,gf_symbolic,Hf_symbolic)
50.703158
120
0.502948
ace88e73223e9867c2cc5aafefca93d16a97ffea
1,186
py
Python
REDSI_1160929_1161573/boost_1_67_0/libs/mpi/test/python/all_reduce_test.py
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
198
2015-01-13T05:47:18.000Z
2022-03-09T04:46:46.000Z
libs/boost/libs/mpi/test/python/all_reduce_test.py
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
9
2015-01-28T16:33:19.000Z
2020-04-12T23:03:28.000Z
libs/boost/libs/mpi/test/python/all_reduce_test.py
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
139
2015-01-15T20:09:31.000Z
2022-01-31T15:21:16.000Z
# Copyright (C) 2006 Douglas Gregor <doug.gregor -at- gmail.com>. # Use, modification and distribution is subject to the Boost Software # License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # Test all_reduce() collective. import boost.parallel.mpi as mpi from generators import * def all_reduce_test(comm, generator, kind, op, op_kind): if comm.rank == 0: print ("Reducing to %s of %s..." % (op_kind, kind)), my_value = generator(comm.rank) result = mpi.all_reduce(comm, my_value, op) expected_result = generator(0); for p in range(1, comm.size): expected_result = op(expected_result, generator(p)) assert result == expected_result if comm.rank == 0: print "OK." return all_reduce_test(mpi.world, int_generator, "integers", lambda x,y:x + y, "sum") all_reduce_test(mpi.world, int_generator, "integers", lambda x,y:x * y, "product") all_reduce_test(mpi.world, string_generator, "strings", lambda x,y:x + y, "concatenation") all_reduce_test(mpi.world, string_list_generator, "list of strings", lambda x,y:x + y, "concatenation")
39.533333
104
0.682125
ace88ee8698de7c8d020a8e8e3dd8b310fccec7f
732
py
Python
Nombres/ETF.py
Krolov18/Languages
549952886f73f0b8e1b9e6393875f5473b591407
[ "Apache-2.0" ]
1
2019-12-11T14:56:09.000Z
2019-12-11T14:56:09.000Z
Nombres/ETF.py
Krolov18/Languages
549952886f73f0b8e1b9e6393875f5473b591407
[ "Apache-2.0" ]
null
null
null
Nombres/ETF.py
Krolov18/Languages
549952886f73f0b8e1b9e6393875f5473b591407
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 from abc import ABC, abstractmethod class ETF(ABC): """ Base class for any parsers needing to use additions and multiplications. """ @abstractmethod def p_e_1(self, p): """ E : E '+' T """ pass @abstractmethod def p_e_2(self, p): """ E : T """ pass @abstractmethod def p_t_1(self, p): """ T : T '*' F """ pass @abstractmethod def p_t_2(self, p): """ T : F """ pass @abstractmethod def p_f_1(self, p): """ F : '(' E ')' """ pass @abstractmethod def p_f_2(self, p): """ F : UNIT """ pass def main(): pass if __name__ == '__main__': main()
15.913043
80
0.47541
ace88f4227730b802bdb6ea72a2dfe7d15660c69
2,173
py
Python
tests/features/environment.py
haavardw/behave-webdriver
737637124716a6248cbd71c6d941e2e3780f53e2
[ "MIT" ]
null
null
null
tests/features/environment.py
haavardw/behave-webdriver
737637124716a6248cbd71c6d941e2e3780f53e2
[ "MIT" ]
null
null
null
tests/features/environment.py
haavardw/behave-webdriver
737637124716a6248cbd71c6d941e2e3780f53e2
[ "MIT" ]
null
null
null
import os import sys import shutil from os import getcwd from os.path import abspath, join from sys import version_info from behave_webdriver import before_all_factory, use_fixture_tag from behave_webdriver.driver import Chrome, ChromeOptions from functools import partial from behave_webdriver.fixtures import transformation_fixture, fixture_browser from behave_webdriver.transformers import FormatTransformer from behave.fixture import use_fixture import behave_webdriver def get_driver(**kwargs): args = [] kwargs.setdefault('default_wait', 5) Driver = behave_webdriver.utils._from_env(default_driver='Chrome') if Driver == behave_webdriver.Chrome: opts = ChromeOptions() opts.add_argument('--no-sandbox') # for travis build kwargs['chrome_options'] = opts pwd_driver_path = os.path.abspath(os.path.join(os.getcwd(), Driver._driver_name)) if sys.version_info[0] < 3: ex_path = pwd_driver_path else: ex_path = shutil.which(Driver._driver_name) or pwd_driver_path kwargs['executable_path'] = ex_path if os.environ.get('BEHAVE_WEBDRIVER_HEADLESS', None) and hasattr(Driver, 'headless'): Driver = Driver.headless return Driver, kwargs #context.behave_driver = context.BehaveDriver() def before_all(context): driver, kwargs = get_driver() context.BehaveDriver = partial(driver, **kwargs) use_fixture(fixture_browser, context, webdriver=driver, **kwargs) use_fixture(transformation_fixture, context, FormatTransformer, BASE_URL='http://localhost:8000', ALT_BASE_URL='http://127.0.0.1:8000') def before_tag(context, tag): use_fixture_tag(context, tag) def before_feature(context, feature): if "fresh_driver" in feature.tags: context.behave_driver.quit() context.behave_driver = context.BehaveDriver() context.behave_driver.default_wait = 5 def before_scenario(context, scenario): if "skip_firefox" in scenario.effective_tags and os.environ.get("BEHAVE_WEBDRIVER", '').lower() == 'firefox': scenario.skip("Skipping because @skip_firefox tag (usually this is because of a known-issue with firefox)") return
36.830508
139
0.745053
ace892b679f15fe173d57b7deee8c65bc02fbafb
10,277
py
Python
test/functional/listtransactions.py
CoinBitCore/coinbit
1b25e4221ecb6b61182d985d2b14175288813228
[ "MIT" ]
null
null
null
test/functional/listtransactions.py
CoinBitCore/coinbit
1b25e4221ecb6b61182d985d2b14175288813228
[ "MIT" ]
null
null
null
test/functional/listtransactions.py
CoinBitCore/coinbit
1b25e4221ecb6b61182d985d2b14175288813228
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Coinbit Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the listtransactions API.""" from test_framework.test_framework import CoinbitTestFramework from test_framework.util import * from test_framework.mininode import CTransaction, COIN from io import BytesIO def txFromHex(hexstring): tx = CTransaction() f = BytesIO(hex_str_to_bytes(hexstring)) tx.deserialize(f) return tx class ListTransactionsTest(CoinbitTestFramework): def set_test_params(self): self.num_nodes = 2 self.enable_mocktime() def run_test(self): # Simple send, 0 to 1: txid = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1) self.sync_all() assert_array_result(self.nodes[0].listtransactions(), {"txid":txid}, {"category":"send","account":"","amount":Decimal("-0.1"),"confirmations":0}) assert_array_result(self.nodes[1].listtransactions(), {"txid":txid}, {"category":"receive","account":"","amount":Decimal("0.1"),"confirmations":0}) # mine a block, confirmations should change: self.nodes[0].generate(1) self.sync_all() assert_array_result(self.nodes[0].listtransactions(), {"txid":txid}, {"category":"send","account":"","amount":Decimal("-0.1"),"confirmations":1}) assert_array_result(self.nodes[1].listtransactions(), {"txid":txid}, {"category":"receive","account":"","amount":Decimal("0.1"),"confirmations":1}) # send-to-self: txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 0.2) assert_array_result(self.nodes[0].listtransactions(), {"txid":txid, "category":"send"}, {"amount":Decimal("-0.2")}) assert_array_result(self.nodes[0].listtransactions(), {"txid":txid, "category":"receive"}, {"amount":Decimal("0.2")}) # sendmany from node1: twice to self, twice to node2: send_to = { self.nodes[0].getnewaddress() : 0.11, self.nodes[1].getnewaddress() : 0.22, self.nodes[0].getaccountaddress("from1") : 0.33, self.nodes[1].getaccountaddress("toself") : 0.44 } txid = self.nodes[1].sendmany("", send_to) self.sync_all() assert_array_result(self.nodes[1].listtransactions(), {"category":"send","amount":Decimal("-0.11")}, {"txid":txid} ) assert_array_result(self.nodes[0].listtransactions(), {"category":"receive","amount":Decimal("0.11")}, {"txid":txid} ) assert_array_result(self.nodes[1].listtransactions(), {"category":"send","amount":Decimal("-0.22")}, {"txid":txid} ) assert_array_result(self.nodes[1].listtransactions(), {"category":"receive","amount":Decimal("0.22")}, {"txid":txid} ) assert_array_result(self.nodes[1].listtransactions(), {"category":"send","amount":Decimal("-0.33")}, {"txid":txid} ) assert_array_result(self.nodes[0].listtransactions(), {"category":"receive","amount":Decimal("0.33")}, {"txid":txid, "account" : "from1"} ) assert_array_result(self.nodes[1].listtransactions(), {"category":"send","amount":Decimal("-0.44")}, {"txid":txid, "account" : ""} ) assert_array_result(self.nodes[1].listtransactions(), {"category":"receive","amount":Decimal("0.44")}, {"txid":txid, "account" : "toself"} ) multisig = self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) self.nodes[0].importaddress(multisig["redeemScript"], "watchonly", False, True) txid = self.nodes[1].sendtoaddress(multisig["address"], 0.1) self.nodes[1].generate(1) self.sync_all() assert(len(self.nodes[0].listtransactions("watchonly", 100, 0, False)) == 0) assert_array_result(self.nodes[0].listtransactions("watchonly", 100, 0, True), {"category":"receive","amount":Decimal("0.1")}, {"txid":txid, "account" : "watchonly"} ) self.run_rbf_opt_in_test() # Check that the opt-in-rbf flag works properly, for sent and received # transactions. def run_rbf_opt_in_test(self): # Check whether a transaction signals opt-in RBF itself def is_opt_in(node, txid): rawtx = node.getrawtransaction(txid, 1) for x in rawtx["vin"]: if x["sequence"] < 0xfffffffe: return True return False # Find an unconfirmed output matching a certain txid def get_unconfirmed_utxo_entry(node, txid_to_match): utxo = node.listunspent(0, 0) for i in utxo: if i["txid"] == txid_to_match: return i return None # 1. Chain a few transactions that don't opt-in. txid_1 = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 1) assert(not is_opt_in(self.nodes[0], txid_1)) assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_1}, {"bip125-replaceable":"no"}) sync_mempools(self.nodes) assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_1}, {"bip125-replaceable":"no"}) # Tx2 will build off txid_1, still not opting in to RBF. utxo_to_use = get_unconfirmed_utxo_entry(self.nodes[0], txid_1) assert_equal(utxo_to_use["safe"], True) utxo_to_use = get_unconfirmed_utxo_entry(self.nodes[1], txid_1) utxo_to_use = get_unconfirmed_utxo_entry(self.nodes[1], txid_1) assert_equal(utxo_to_use["safe"], False) # Create tx2 using createrawtransaction inputs = [{"txid":utxo_to_use["txid"], "vout":utxo_to_use["vout"]}] outputs = {self.nodes[0].getnewaddress(): 0.999} tx2 = self.nodes[1].createrawtransaction(inputs, outputs) tx2_signed = self.nodes[1].signrawtransaction(tx2)["hex"] txid_2 = self.nodes[1].sendrawtransaction(tx2_signed) # ...and check the result assert(not is_opt_in(self.nodes[1], txid_2)) assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_2}, {"bip125-replaceable":"no"}) sync_mempools(self.nodes) assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_2}, {"bip125-replaceable":"no"}) # Tx3 will opt-in to RBF utxo_to_use = get_unconfirmed_utxo_entry(self.nodes[0], txid_2) inputs = [{"txid": txid_2, "vout":utxo_to_use["vout"]}] outputs = {self.nodes[1].getnewaddress(): 0.998} tx3 = self.nodes[0].createrawtransaction(inputs, outputs) tx3_modified = txFromHex(tx3) tx3_modified.vin[0].nSequence = 0 tx3 = bytes_to_hex_str(tx3_modified.serialize()) tx3_signed = self.nodes[0].signrawtransaction(tx3)['hex'] txid_3 = self.nodes[0].sendrawtransaction(tx3_signed) assert(is_opt_in(self.nodes[0], txid_3)) assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_3}, {"bip125-replaceable":"yes"}) sync_mempools(self.nodes) assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_3}, {"bip125-replaceable":"yes"}) # Tx4 will chain off tx3. Doesn't signal itself, but depends on one # that does. utxo_to_use = get_unconfirmed_utxo_entry(self.nodes[1], txid_3) inputs = [{"txid": txid_3, "vout":utxo_to_use["vout"]}] outputs = {self.nodes[0].getnewaddress(): 0.997} tx4 = self.nodes[1].createrawtransaction(inputs, outputs) tx4_signed = self.nodes[1].signrawtransaction(tx4)["hex"] txid_4 = self.nodes[1].sendrawtransaction(tx4_signed) assert(not is_opt_in(self.nodes[1], txid_4)) assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_4}, {"bip125-replaceable":"yes"}) sync_mempools(self.nodes) assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_4}, {"bip125-replaceable":"yes"}) # Replace tx3, and check that tx4 becomes unknown tx3_b = tx3_modified tx3_b.vout[0].nValue -= int(Decimal("0.004") * COIN) # bump the fee tx3_b = bytes_to_hex_str(tx3_b.serialize()) tx3_b_signed = self.nodes[0].signrawtransaction(tx3_b)['hex'] txid_3b = self.nodes[0].sendrawtransaction(tx3_b_signed, True) assert(is_opt_in(self.nodes[0], txid_3b)) assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_4}, {"bip125-replaceable":"unknown"}) sync_mempools(self.nodes) assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_4}, {"bip125-replaceable":"unknown"}) # Check gettransaction as well: for n in self.nodes[0:2]: assert_equal(n.gettransaction(txid_1)["bip125-replaceable"], "no") assert_equal(n.gettransaction(txid_2)["bip125-replaceable"], "no") assert_equal(n.gettransaction(txid_3)["bip125-replaceable"], "yes") assert_equal(n.gettransaction(txid_3b)["bip125-replaceable"], "yes") assert_equal(n.gettransaction(txid_4)["bip125-replaceable"], "unknown") # After mining a transaction, it's no longer BIP125-replaceable self.nodes[0].generate(1) assert(txid_3b not in self.nodes[0].getrawmempool()) assert_equal(self.nodes[0].gettransaction(txid_3b)["bip125-replaceable"], "no") assert_equal(self.nodes[0].gettransaction(txid_4)["bip125-replaceable"], "unknown") if __name__ == '__main__': ListTransactionsTest().main()
50.876238
113
0.600078
ace8941f5a38d17213df3f0c37d08a22a261aa7d
873
py
Python
setup.py
benjcabalona1029/itaewon
1db68d39aeb4b5dfcb93e25235c6d60d2e081e2d
[ "MIT" ]
4
2020-07-24T06:30:45.000Z
2020-08-10T03:31:20.000Z
setup.py
benjcabalona1029/itaewon
1db68d39aeb4b5dfcb93e25235c6d60d2e081e2d
[ "MIT" ]
1
2020-07-24T06:30:06.000Z
2020-07-24T06:30:06.000Z
setup.py
benjcabalona1029/itaewon
1db68d39aeb4b5dfcb93e25235c6d60d2e081e2d
[ "MIT" ]
1
2020-08-07T04:42:56.000Z
2020-08-07T04:42:56.000Z
import pathlib from setuptools import setup, find_packages HERE = pathlib.Path(__file__).parent VERSION = '0.1.4' PACKAGE_NAME = 'itaewon' AUTHOR = 'Benjamin Cabalona Jr' AUTHOR_EMAIL = 'benjcabalonajr@gmail.com' URL = 'https://github.com/benjcabalona1029/itaewon' LICENSE = 'MIT License' DESCRIPTION = 'A personal python library to speed up my workflow' LONG_DESCRIPTION = (HERE / "README.md").read_text() LONG_DESC_TYPE = "text/markdown" INSTALL_REQUIRES = [ 'numpy', 'pandas', 'sklearn', 'rpy2' ] setup(name=PACKAGE_NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, long_description_content_type=LONG_DESC_TYPE, author=AUTHOR, license=LICENSE, author_email=AUTHOR_EMAIL, url=URL, install_requires=INSTALL_REQUIRES, packages=find_packages() )
24.25
65
0.707904
ace89487319ec16bb4951238ef201ff3f3a35f90
6,473
py
Python
python_module/Mangdang/minipupper/calibrate_servos.py
hdumcke/minipupper_base
930ee94384a17478391ac0f2a42175b57dbf44c8
[ "Apache-2.0" ]
null
null
null
python_module/Mangdang/minipupper/calibrate_servos.py
hdumcke/minipupper_base
930ee94384a17478391ac0f2a42175b57dbf44c8
[ "Apache-2.0" ]
null
null
null
python_module/Mangdang/minipupper/calibrate_servos.py
hdumcke/minipupper_base
930ee94384a17478391ac0f2a42175b57dbf44c8
[ "Apache-2.0" ]
null
null
null
from Mangdang.minipupper.HardwareInterface import HardwareInterface from Mangdang.minipupper.Config import PWMParams, ServoParams import numpy as np import re ServoCalibrationFilePath = '/sys/bus/nvmem/devices/3-00500/nvmem' def get_motor_name(i, j): motor_type = {0: "abduction", 1: "inner", 2: "outer"} # Top # Bottom leg_pos = {0: "front-right", 1: "front-left", 2: "back-right", 3: "back-left"} final_name = motor_type[i] + " " + leg_pos[j] return final_name def get_motor_setpoint(i, j): data = np.array([[0, 0, 0, 0], [90, 90, 90, 90], [-90, -90, -90, -90]]) return data[i, j] def degrees_to_radians(input_array): """Converts degrees to radians. Parameters ---------- input_array : Numpy array or float Degrees Returns ------- Numpy array or float Radians """ return input_array * np.pi / 180.0 def radians_to_degrees(input_array): """Converts degrees to radians. Parameters ---------- input_array : Numpy array or float Radians Returns ------- Numpy array or float Degrees """ return input_array * 180.0 / np.pi def step_until(hardware_interface, axis, leg, set_point): """Returns the angle offset needed to correct a given link by asking the user for input. Returns ------- Float Angle offset needed to correct the link. """ found_position = False set_names = ["vertical", "horizontal", "horizontal"] offset = 0 while not found_position: move_input = str( input("Enter 'a' or 'b' to move the link until it is **" + set_names[axis] + "**. Enter 'd' when done. Input: " ) ) if move_input == "a": offset += 1.0 hardware_interface.set_actuator_position( degrees_to_radians(set_point + offset), axis, leg, ) elif move_input == "b": offset -= 1.0 hardware_interface.set_actuator_position( degrees_to_radians(set_point + offset), axis, leg, ) elif move_input == "d": found_position = True print("Offset: ", offset) return offset def calibrate_angle_offset(hardware_interface): """Calibrate the angle offset for the twelve motors on the robot. Note that servo_params is modified in-place. Parameters ---------- servo_params : ServoParams Servo parameters. This variable is updated in-place. pi_board : Pi RaspberryPi object. pwm_params : PWMParams PWMParams object. """ # Found K value of (11.4) print("The scaling constant for your servo represents how much you have to increase\nthe pwm pulse width (in microseconds) to rotate the servo output 1 degree.") print("This value is currently set to: {:.3f}".format(degrees_to_radians(hardware_interface.servo_params.micros_per_rad))) print("For newer CLS6336 and CLS6327 servos the value should be 11.333.") ks = input("Press <Enter> to keep the current value, or enter a new value: ") if ks != '': k = float(ks) hardware_interface.servo_params.micros_per_rad = k * 180 / np.pi hardware_interface.servo_params.neutral_angle_degrees = np.zeros((3, 4)) for leg_index in range(4): for axis in range(3): # Loop until we're satisfied with the calibration completed = False while not completed: motor_name = get_motor_name(axis, leg_index) print("\n\nCalibrating the **" + motor_name + " motor **") set_point = get_motor_setpoint(axis, leg_index) # Zero out the neutral angle hardware_interface.servo_params.neutral_angle_degrees[axis, leg_index] = 0 # Move servo to set_point angle hardware_interface.set_actuator_position( degrees_to_radians(set_point), axis, leg_index, ) # Adjust the angle using keyboard input until it matches the reference angle offset = step_until( hardware_interface, axis, leg_index, set_point ) print("Final offset: ", offset) hardware_interface.servo_params.neutral_angle_degrees[axis, leg_index] = - offset print("Calibrated neutral angle: ", hardware_interface.servo_params.neutral_angle_degrees[axis, leg_index]) # Send the servo command using the new beta value and check that it's ok hardware_interface.set_actuator_position( degrees_to_radians([0, 45, -45][axis]), axis, leg_index, ) okay = "" prompt = "The leg should be at exactly **" + ["horizontal", "45 degrees", "45 degrees"][axis] + "**. Are you satisfied? Enter 'yes' or 'no': " while okay not in ["y", "n", "yes", "no"]: okay = str( input(prompt) ) completed = okay == "y" or okay == "yes" def overwrite_ServoCalibration_file(servo_params): buf_matrix = np.zeros((3, 4)) for i in range(3): for j in range(4): buf_matrix[i,j]= servo_params.neutral_angle_degrees[i,j] # Format array object string for np.array p1 = re.compile("([0-9]\.) ( *)") # pattern to replace the space that follows each number with a comma partially_formatted_matrix = p1.sub(r"\1,\2", str(buf_matrix)) p2 = re.compile("(\]\n)") # pattern to add a comma at the end of the first two lines formatted_matrix_with_required_commas = p2.sub("],\n", partially_formatted_matrix) with open(ServoCalibrationFilePath, "w") as nv_f: _tmp = str(buf_matrix) _tmp = _tmp.replace('.' , ',') _tmp = _tmp.replace('[' , '') _tmp = _tmp.replace(']' , '') print(_tmp, file = nv_f) def main(): """Main program """ hardware_interface = HardwareInterface() calibrate_angle_offset(hardware_interface) overwrite_ServoCalibration_file(hardware_interface.servo_params) print("\n\n CALIBRATION COMPLETE!\n") print("Calibrated neutral angles:") print(hardware_interface.servo_params.neutral_angle_degrees) main()
34.068421
165
0.596323
ace894c1a9acaf1a77eb9f7f647647ec4d39d38e
171
py
Python
app/api/__init__.py
netai/apidesk
f87ace7d08777ed3f1e587e904800e78d6401b7f
[ "MIT" ]
null
null
null
app/api/__init__.py
netai/apidesk
f87ace7d08777ed3f1e587e904800e78d6401b7f
[ "MIT" ]
null
null
null
app/api/__init__.py
netai/apidesk
f87ace7d08777ed3f1e587e904800e78d6401b7f
[ "MIT" ]
null
null
null
from flask import Flask from flask import Blueprint from .routes import api_routes api_blueprint = Blueprint('api', __name__, url_prefix='/api') api_routes(api_blueprint)
28.5
61
0.812865
ace895aaa8ec0f2c1ebbf0ec25b2b10bee0b0a65
1,436
py
Python
String/easy.py
MnkyC/Algorithms-Python
01d2c9099f185f549c07e6e3162b9b2d55ba6fd6
[ "MIT" ]
1
2020-01-03T06:30:41.000Z
2020-01-03T06:30:41.000Z
String/easy.py
MnkyC/Algorithms-Python
01d2c9099f185f549c07e6e3162b9b2d55ba6fd6
[ "MIT" ]
null
null
null
String/easy.py
MnkyC/Algorithms-Python
01d2c9099f185f549c07e6e3162b9b2d55ba6fd6
[ "MIT" ]
null
null
null
''' 13 Roman to Integer 罗马数字包含I,V,X,L,C,D,M,对应数值1,5,10,50,100,500,1000 罗马数字2写做II,12是XII,27是XXVII,通常小的数字在右边 4是IV,9是IX,小的在左边,这种特殊情况只适用于: I和V,X(4,9),X和L,C(40,90),C和D,M(400,900) 给定罗马数字转为整数,输入范围[1-3999] ''' def romanToInt(s): map = { 'I': 1, 'IV': 4, 'V': 5, 'IX': 9, 'X': 10, 'XL': 40, 'L': 50, 'XC': 90, 'C': 100, 'CD': 400, 'D': 500, 'CM': 900, 'M': 1000 } size = len(s) - 1 rlt = 0 for i in range(size): rlt = rlt - map.get(s[i]) if map.get(s[i]) < map.get(s[i+1]) else rlt + map.get(s[i]) return rlt + map.get(s[-1]) # 14 Longest Common Prefix # 查找字符串(只包含小写字母a-z)数组中的最长公共前缀,不存在返回"" def longestCommonPrefix(strs): size = len(strs) if size == 0: return '' s = strs[0] for i in range(1, size): while strs[i].find(s) < 0: s = s[:-1] return s ''' 20 Valid Parentheses 给定一个只包含(, ), {, }, [, ]的字符串,判断字符串是否有效 有效字符串必须满足 左括号用相同类型的右括号闭合 左括号以正确顺序闭合 空字符串是有效字符串 ''' def isValid(s): size = len(s) if size == 0: return True if size % 2 != 0: print(111) return False mapping = {'(': ')', '{': '}', '[': ']'} stack = ['#'] for c in s: if c in mapping: stack.append(c) else: if mapping[stack.pop()] != c: return False return len(stack) == 1
18.410256
93
0.478412
ace8961d074ccf4a420a3f7e33c0921e6375b489
32,600
py
Python
controllable_talknet.py
minermanb/ControllableTalkNet
6afb1703e207ab423d348e703e47a6c098076e56
[ "CC0-1.0" ]
null
null
null
controllable_talknet.py
minermanb/ControllableTalkNet
6afb1703e207ab423d348e703e47a6c098076e56
[ "CC0-1.0" ]
null
null
null
controllable_talknet.py
minermanb/ControllableTalkNet
6afb1703e207ab423d348e703e47a6c098076e56
[ "CC0-1.0" ]
null
null
null
import sys import os import base64 import dash from jupyter_dash import JupyterDash import dash_core_components as dcc import dash_html_components as html from dash.exceptions import PreventUpdate import torch import numpy as np import crepe import scipy from scipy.io import wavfile import psola import io import nemo from nemo.collections.asr.models import EncDecCTCModel from nemo.collections.tts.models import TalkNetSpectModel from nemo.collections.tts.models import TalkNetPitchModel from nemo.collections.tts.models import TalkNetDursModel from talknet_singer import TalkNetSingerModel import json from tqdm import tqdm import gdown import zipfile import resampy import traceback import ffmpeg import time import uuid sys.path.append("hifi-gan") from env import AttrDict from meldataset import mel_spectrogram, MAX_WAV_VALUE from models import Generator from denoiser import Denoiser app = JupyterDash(__name__) UPLOAD_DIRECTORY = "/content" torch.set_grad_enabled(False) app.layout = html.Div( children=[ html.H1( id="header", children="Controllable TalkNet", style={ "font-family": "Georgia", "color": "#000000", "font-size": "4em", "text-align": "center", "margin-top": "0em", "margin-bottom": "0em", }, ), html.Label("Character selection", htmlFor="model-dropdown"), dcc.Dropdown( id="model-dropdown", options=[ { "label": "Custom model", "value": "Custom", }, { "label": "--- ERROR LOADING MODEL LISTS ---", "value": "", "disabled": True, }, ], value=None, style={ "max-width": "90vw", "width": "35em", "margin-bottom": "0.7em", }, ), html.Div( children=[ dcc.Input( id="drive-id", type="text", placeholder="Drive ID for custom model", style={"width": "22em"}, ), ], id="custom-model", style={ "display": "none", }, ), html.Label( "Upload reference audio to " + UPLOAD_DIRECTORY, htmlFor="reference-dropdown", ), dcc.Store(id="current-f0s"), dcc.Store(id="current-f0s-nosilence"), dcc.Store(id="current-filename"), dcc.Loading( id="audio-loading", children=[ html.Div( [ html.Button( "Update file list", id="update-button", style={ "margin-right": "10px", }, ), dcc.Dropdown( id="reference-dropdown", options=[], value=None, style={ "max-width": "80vw", "width": "30em", }, disabled=False, ), dcc.Store(id="pitch-clicks"), html.Button( "Debug pitch", id="pitch-button", style={ "margin-left": "10px", }, disabled=False, ), ], style={ "width": "100%", "display": "flex", "align-items": "center", "justify-content": "center", "flex-direction": "row", "margin-left": "50px", "vertical-align": "middle", }, ), html.Audio( id="pitch-out", controls=True, style={"display": "none"}, ), html.Div( id="audio-loading-output", style={ "font-style": "italic", "margin-bottom": "0.7em", "text-align": "center", }, ), ], type="default", ), html.Div( [ dcc.Checklist( id="pitch-options", options=[ {"label": "Change input pitch", "value": "pf"}, {"label": "Auto-tune output", "value": "pc"}, {"label": "Disable reference audio", "value": "dra"}, ], value=[], ), html.Div( [ html.Label("Semitones", htmlFor="pitch-factor"), dcc.Input( id="pitch-factor", type="number", value="0", style={"width": "7em"}, min=-11, max=11, step=1, disabled=True, ), ], style={ "flex-direction": "column", "margin-left": "10px", "margin-bottom": "0.7em", }, ), ], style={ "width": "100%", "display": "flex", "align-items": "center", "justify-content": "center", "flex-direction": "row", "margin-left": "50px", "margin-bottom": "0.7em", }, ), html.Label("Transcript", htmlFor="transcript-input"), dcc.Textarea( id="transcript-input", value="", style={ "max-width": "90vw", "width": "50em", "height": "8em", "margin-bottom": "0.7em", }, ), dcc.Loading( html.Div( [ html.Button( "Generate", id="gen-button", ), html.Audio( id="audio-out", controls=True, style={ "display": "none", }, ), html.Div( id="generated-info", style={ "font-style": "italic", }, ), ], style={ "width": "100%", "display": "flex", "align-items": "center", "justify-content": "center", "flex-direction": "column", }, ) ), html.Footer( children=""" Presented by the Minerman Groupie Association. """, style={"margin-top": "2em", "font-size": "0.7em"}, ), ], style={ "width": "100%", "display": "flex", "align-items": "center", "justify-content": "center", "flex-direction": "column", "background-color": "#FFF", }, ) @app.callback( dash.dependencies.Output("model-dropdown", "options"), dash.dependencies.Input("header", "children"), ) def init_dropdown(value): dropdown = [ { "label": "Custom model", "value": "Custom|default", } ] prev_values = ["Custom|default"] def add_to_dropdown(entry): if entry["value"] in prev_values: return dropdown.append(entry) prev_values.append(entry["value"]) all_dict = {} for filename in os.listdir("model_lists"): if len(filename) < 5 or filename[-5:].lower() != ".json": continue with open(os.path.join("model_lists", filename)) as f: j = json.load(f) for s in j: for c in s["characters"]: c["source_file"] = filename[:-5] if s["source"] not in all_dict: all_dict[s["source"]] = s["characters"] else: all_dict[s["source"]].extend(s["characters"]) for k in sorted(all_dict): seen_chars = [] seen_ids = [] characters = {} characters_sing = {} has_singers = False for c in all_dict[k]: if c["drive_id"] in seen_ids: continue seen_ids.append(c["drive_id"]) # Handle duplicate names if c["name"] in seen_chars: if c["name"] in characters: rename = ( c["name"] + " [" + characters[c["name"]]["source_file"] + "]" ) characters[rename] = characters[c["name"]] del characters[c["name"]] c["name"] = c["name"] + " [" + c["source_file"] + "]" else: seen_chars.append(c["name"]) characters[c["name"]] = { "drive_id": c["drive_id"], "is_singing": c["is_singing"], "source_file": c["source_file"], } if c["is_singing"]: has_singers = True if has_singers: for ck in sorted(characters): if characters[ck]["is_singing"]: characters_sing[ck] = characters[ck] del characters[ck] separator = "--- " + k.strip().upper() + " MODELS (TALKING) ---" else: separator = "--- " + k.strip().upper() + " MODELS ---" if len(characters) > 0: add_to_dropdown( { "label": separator, "value": str(uuid.uuid4()) + "|default", "disabled": True, } ) for ck in sorted(characters): add_to_dropdown( { "label": ck, "value": characters[ck]["drive_id"] + "|default", } ) if has_singers: separator = "--- " + k.strip().upper() + " MODELS (SINGING) ---" add_to_dropdown( { "label": separator, "value": str(uuid.uuid4()) + "|default", "disabled": True, } ) for ck in sorted(characters_sing): add_to_dropdown( { "label": ck, "value": characters_sing[ck]["drive_id"] + "|singing", } ) if len(all_dict) == 0: add_to_dropdown( { "label": "--- NO MODEL LISTS FOUND ---", "value": str(uuid.uuid4()) + "|default", "disabled": True, } ) return dropdown def load_hifigan(model_name, conf_name): # Load HiFi-GAN conf = os.path.join("hifi-gan", conf_name + ".json") with open(conf) as f: json_config = json.loads(f.read()) h = AttrDict(json_config) torch.manual_seed(h.seed) hifigan = Generator(h).to(torch.device("cuda")) state_dict_g = torch.load(model_name, map_location=torch.device("cuda")) hifigan.load_state_dict(state_dict_g["generator"]) hifigan.eval() hifigan.remove_weight_norm() denoiser = Denoiser(hifigan, mode="normal") return hifigan, h, denoiser def generate_json(input, outpath): output = "" sample_rate = 22050 lpath = input.split("|")[0].strip() size = os.stat(lpath).st_size x = { "audio_filepath": lpath, "duration": size / (sample_rate * 2), "text": input.split("|")[1].strip(), } output += json.dumps(x) + "\n" with open(outpath, "w", encoding="utf8") as w: w.write(output) asr_model = ( EncDecCTCModel.from_pretrained(model_name="asr_talknet_aligner").cpu().eval() ) def forward_extractor(tokens, log_probs, blank): """Computes states f and p.""" n, m = len(tokens), log_probs.shape[0] # `f[s, t]` -- max sum of log probs for `s` first codes # with `t` first timesteps with ending in `tokens[s]`. f = np.empty((n + 1, m + 1), dtype=float) f.fill(-(10 ** 9)) p = np.empty((n + 1, m + 1), dtype=int) f[0, 0] = 0.0 # Start for s in range(1, n + 1): c = tokens[s - 1] for t in range((s + 1) // 2, m + 1): f[s, t] = log_probs[t - 1, c] # Option #1: prev char is equal to current one. if s == 1 or c == blank or c == tokens[s - 3]: options = f[s : (s - 2 if s > 1 else None) : -1, t - 1] else: # Is not equal to current one. options = f[s : (s - 3 if s > 2 else None) : -1, t - 1] f[s, t] += np.max(options) p[s, t] = np.argmax(options) return f, p def backward_extractor(f, p): """Computes durs from f and p.""" n, m = f.shape n -= 1 m -= 1 durs = np.zeros(n, dtype=int) if f[-1, -1] >= f[-2, -1]: s, t = n, m else: s, t = n - 1, m while s > 0: durs[s - 1] += 1 s -= p[s, t] t -= 1 assert durs.shape[0] == n assert np.sum(durs) == m assert np.all(durs[1::2] > 0) return durs def preprocess_tokens(tokens, blank): new_tokens = [blank] for c in tokens: new_tokens.extend([c, blank]) tokens = new_tokens return tokens def get_duration(wav_name, transcript): if not os.path.exists(os.path.join(UPLOAD_DIRECTORY, "output")): os.mkdir(os.path.join(UPLOAD_DIRECTORY, "output")) if "_" not in transcript: generate_json( os.path.join(UPLOAD_DIRECTORY, "output", wav_name + "_conv.wav") + "|" + transcript.strip(), os.path.join(UPLOAD_DIRECTORY, "output", wav_name + ".json"), ) else: generate_json( os.path.join(UPLOAD_DIRECTORY, "output", wav_name + "_conv.wav") + "|" + "dummy", os.path.join(UPLOAD_DIRECTORY, "output", wav_name + ".json"), ) data_config = { "manifest_filepath": os.path.join( UPLOAD_DIRECTORY, "output", wav_name + ".json" ), "sample_rate": 22050, "batch_size": 1, } parser = ( nemo.collections.asr.data.audio_to_text.AudioToCharWithDursF0Dataset.make_vocab( notation="phonemes", punct=True, spaces=True, stresses=False, add_blank_at="last", ) ) dataset = nemo.collections.asr.data.audio_to_text._AudioTextDataset( manifest_filepath=data_config["manifest_filepath"], sample_rate=data_config["sample_rate"], parser=parser, ) dl = torch.utils.data.DataLoader( dataset=dataset, batch_size=data_config["batch_size"], collate_fn=dataset.collate_fn, shuffle=False, ) blank_id = asr_model.decoder.num_classes_with_blank - 1 for sample_idx, test_sample in tqdm(enumerate(dl), total=len(dl)): log_probs, _, greedy_predictions = asr_model( input_signal=test_sample[0], input_signal_length=test_sample[1] ) log_probs = log_probs[0].cpu().detach().numpy() if "_" not in transcript: seq_ids = test_sample[2][0].cpu().detach().numpy() else: pass """arpa_input = ( transcript.replace("0", "") .replace("1", "") .replace("2", "") .replace("_", " _ ") .strip() .split(" ") ) seq_ids = [] for x in arpa_input: if x == "": continue if x.replace("_", " ") not in parser.labels: continue seq_ids.append(parser.labels.index(x.replace("_", " ")))""" seq_ids = test_sample[2][0].cpu().detach().numpy() target_tokens = preprocess_tokens(seq_ids, blank_id) f, p = forward_extractor(target_tokens, log_probs, blank_id) durs = backward_extractor(f, p) arpa = "" for s in seq_ids: if parser.labels[s] == " ": arpa += "_ " else: arpa += parser.labels[s] + " " del test_sample return durs, arpa.strip(), seq_ids return None, None, None def crepe_f0(wav_path, hop_length=256): # sr, audio = wavfile.read(io.BytesIO(wav_data)) sr, audio = wavfile.read(wav_path) audio_x = np.arange(0, len(audio)) / 22050.0 f0time, frequency, confidence, activation = crepe.predict(audio, sr, viterbi=True) x = np.arange(0, len(audio), hop_length) / 22050.0 freq_interp = np.interp(x, f0time, frequency) conf_interp = np.interp(x, f0time, confidence) audio_interp = np.interp(x, audio_x, np.absolute(audio)) / 32768.0 weights = [0.5, 0.25, 0.25] audio_smooth = np.convolve(audio_interp, np.array(weights)[::-1], "same") conf_threshold = 0.25 audio_threshold = 0.0005 for i in range(len(freq_interp)): if conf_interp[i] < conf_threshold: freq_interp[i] = 0.0 if audio_smooth[i] < audio_threshold: freq_interp[i] = 0.0 # Hack to make f0 and mel lengths equal if len(audio) % hop_length == 0: freq_interp = np.pad(freq_interp, pad_width=[0, 1]) return ( torch.from_numpy(freq_interp.astype(np.float32)), torch.from_numpy(frequency.astype(np.float32)), ) def f0_to_audio(f0s): volume = 0.2 sr = 22050 freq = 440.0 base_audio = ( np.sin(2 * np.pi * np.arange(256.0 * len(f0s)) * freq / sr) * volume ).astype(np.float32) shifted_audio = psola.vocode(base_audio, sr, target_pitch=f0s) for i in range(len(f0s)): if f0s[i] == 0.0: shifted_audio[i * 256 : (i + 1) * 256] = 0.0 print(type(shifted_audio[0])) buffer = io.BytesIO() wavfile.write(buffer, sr, shifted_audio.astype(np.float32)) b64 = base64.b64encode(buffer.getvalue()) sound = "data:audio/x-wav;base64," + b64.decode("ascii") return sound @app.callback( dash.dependencies.Output("custom-model", "style"), dash.dependencies.Input("model-dropdown", "value"), ) def update_model(model): if model is not None and model.split("|")[0] == "Custom": style = {"margin-bottom": "0.7em", "display": "block"} else: style = {"display": "none"} return style @app.callback( [ dash.dependencies.Output("pitch-factor", "disabled"), dash.dependencies.Output("reference-dropdown", "disabled"), dash.dependencies.Output("pitch-button", "disabled"), ], [ dash.dependencies.Input("pitch-options", "value"), ], ) def update_pitch_options(value): return ["pf" not in value, "dra" in value, "dra" in value] playback_style = { "margin-top": "0.3em", "margin-bottom": "0.3em", "display": "block", "width": "600px", "max-width": "90vw", } playback_hide = { "display": "none", } @app.callback( dash.dependencies.Output("reference-dropdown", "options"), [ dash.dependencies.Input("update-button", "n_clicks"), ], ) def update_filelist(n_clicks): filelist = [] supported_formats = [".wav", ".ogg", ".mp3", "flac", ".aac"] for x in sorted(os.listdir(UPLOAD_DIRECTORY)): if x[-4:].lower() in supported_formats: filelist.append({"label": x, "value": x}) return filelist @app.callback( [ dash.dependencies.Output("audio-loading-output", "children"), dash.dependencies.Output("current-f0s", "data"), dash.dependencies.Output("current-f0s-nosilence", "data"), dash.dependencies.Output("current-filename", "data"), ], [ dash.dependencies.Input("reference-dropdown", "value"), ], ) def select_file(dropdown_value): if dropdown_value is not None: if not os.path.exists(os.path.join(UPLOAD_DIRECTORY, "output")): os.mkdir(os.path.join(UPLOAD_DIRECTORY, "output")) ffmpeg.input(os.path.join(UPLOAD_DIRECTORY, dropdown_value)).output( os.path.join(UPLOAD_DIRECTORY, "output", dropdown_value + "_conv.wav"), ar="22050", ac="1", acodec="pcm_s16le", map_metadata="-1", fflags="+bitexact", ).overwrite_output().run(quiet=True) fo_with_silence, f0_wo_silence = crepe_f0( os.path.join(UPLOAD_DIRECTORY, "output", dropdown_value + "_conv.wav") ) return [ "Analyzed " + dropdown_value, fo_with_silence, f0_wo_silence, dropdown_value, ] else: return ["No audio analyzed", None, None] @app.callback( [ dash.dependencies.Output("pitch-out", "src"), dash.dependencies.Output("pitch-out", "style"), dash.dependencies.Output("pitch-clicks", "data"), ], [ dash.dependencies.Input("pitch-button", "n_clicks"), dash.dependencies.Input("pitch-clicks", "data"), dash.dependencies.Input("current-f0s", "data"), ], ) def debug_pitch(n_clicks, pitch_clicks, current_f0s): if not n_clicks or current_f0s is None or n_clicks <= pitch_clicks: if n_clicks is not None: pitch_clicks = n_clicks else: pitch_clicks = 0 return [ None, playback_hide, pitch_clicks, ] pitch_clicks = n_clicks return [f0_to_audio(current_f0s), playback_style, pitch_clicks] def download_model(model, custom_model): global hifigan_sr, h2, denoiser_sr d = "https://drive.google.com/uc?id=" if model == "Custom": drive_id = custom_model else: drive_id = model if not os.path.exists(os.path.join(UPLOAD_DIRECTORY, "models")): os.mkdir(os.path.join(UPLOAD_DIRECTORY, "models")) if not os.path.exists(os.path.join(UPLOAD_DIRECTORY, "models", drive_id)): os.mkdir(os.path.join(UPLOAD_DIRECTORY, "models", drive_id)) zip_path = os.path.join(UPLOAD_DIRECTORY, "models", drive_id, "model.zip") gdown.download( d + drive_id, zip_path, quiet=False, ) if not os.path.exists(zip_path): os.rmdir(os.path.join(UPLOAD_DIRECTORY, "models", drive_id)) return ("Model download failed", None, None) if os.stat(zip_path).st_size < 16: os.remove(zip_path) os.rmdir(os.path.join(UPLOAD_DIRECTORY, "models", drive_id)) return ("Model zip is empty", None, None) with zipfile.ZipFile(zip_path, "r") as zip_ref: zip_ref.extractall(os.path.join(UPLOAD_DIRECTORY, "models", drive_id)) os.remove(zip_path) # Download super-resolution HiFi-GAN sr_path = "hifi-gan/hifisr" if not os.path.exists(sr_path): gdown.download(d + "14fOprFAIlCQkVRxsfInhEPG0n-xN4QOa", sr_path, quiet=False) if not os.path.exists(sr_path): raise Exception("HiFI-GAN model failed to download!") hifigan_sr, h2, denoiser_sr = load_hifigan(sr_path, "config_32k") return ( None, os.path.join(UPLOAD_DIRECTORY, "models", drive_id, "TalkNetSpect.nemo"), os.path.join(UPLOAD_DIRECTORY, "models", drive_id, "hifiganmodel"), ) tnmodel, tnpath, tndurs, tnpitch = None, None, None, None hifigan, h, denoiser, hifipath = None, None, None, None @app.callback( [ dash.dependencies.Output("audio-out", "src"), dash.dependencies.Output("generated-info", "children"), dash.dependencies.Output("audio-out", "style"), dash.dependencies.Output("audio-out", "title"), ], [dash.dependencies.Input("gen-button", "n_clicks")], [ dash.dependencies.State("model-dropdown", "value"), dash.dependencies.State("drive-id", "value"), dash.dependencies.State("transcript-input", "value"), dash.dependencies.State("pitch-options", "value"), dash.dependencies.State("pitch-factor", "value"), dash.dependencies.State("current-filename", "data"), dash.dependencies.State("current-f0s", "data"), dash.dependencies.State("current-f0s-nosilence", "data"), ], ) def generate_audio( n_clicks, model, custom_model, transcript, pitch_options, pitch_factor, wav_name, f0s, f0s_wo_silence, ): global tnmodel, tnpath, tndurs, tnpitch, hifigan, h, denoiser, hifipath if n_clicks is None: raise PreventUpdate if model is None: return [None, "No character selected", playback_hide, None] if transcript is None or transcript.strip() == "": return [ None, "No transcript entered", playback_hide, None, ] if wav_name is None and "dra" not in pitch_options: return [ None, "No reference audio selected", playback_hide, None, ] load_error, talknet_path, hifigan_path = download_model( model.split("|")[0], custom_model ) if load_error is not None: return [ None, load_error, playback_hide, None, ] try: with torch.no_grad(): if tnpath != talknet_path: singer_path = os.path.join( os.path.dirname(talknet_path), "TalkNetSinger.nemo" ) if os.path.exists(singer_path): tnmodel = TalkNetSingerModel.restore_from(singer_path) else: tnmodel = TalkNetSpectModel.restore_from(talknet_path) durs_path = os.path.join( os.path.dirname(talknet_path), "TalkNetDurs.nemo" ) pitch_path = os.path.join( os.path.dirname(talknet_path), "TalkNetPitch.nemo" ) if os.path.exists(durs_path): tndurs = TalkNetDursModel.restore_from(durs_path) tnmodel.add_module("_durs_model", tndurs) tnpitch = TalkNetPitchModel.restore_from(pitch_path) tnmodel.add_module("_pitch_model", tnpitch) else: tndurs = None tnpitch = None tnmodel.eval() tokens = tnmodel.parse(text=transcript.strip()) arpa = "" if "dra" in pitch_options: if tndurs is None or tnpitch is None: return [ None, "Model doesn't support pitch prediction", playback_hide, None, ] spect = tnmodel.generate_spectrogram(tokens=tokens) else: durs, arpa, t = get_duration(wav_name, transcript) # Change pitch if "pf" in pitch_options: f0_factor = np.power(np.e, (0.0577623 * float(pitch_factor))) f0s = [x * f0_factor for x in f0s] f0s_wo_silence = [x * f0_factor for x in f0s_wo_silence] spect = tnmodel.force_spectrogram( tokens=tokens, durs=torch.from_numpy(durs).view(1, -1).to("cuda:0"), f0=torch.FloatTensor(f0s).view(1, -1).to("cuda:0"), ) if hifipath != hifigan_path: hifigan, h, denoiser = load_hifigan(hifigan_path, "config_v1") y_g_hat = hifigan(spect.float()) audio = y_g_hat.squeeze() audio = audio * MAX_WAV_VALUE audio_denoised = denoiser(audio.view(1, -1), strength=35)[:, 0] audio_np = ( audio_denoised.detach().cpu().numpy().reshape(-1).astype(np.int16) ) # Auto-tuning if "pc" in pitch_options and "dra" not in pitch_options: _, output_freq, _, _ = crepe.predict(audio_np, 22050, viterbi=True) output_pitch = torch.from_numpy(output_freq.astype(np.float32)) target_pitch = torch.FloatTensor(f0s_wo_silence) factor = torch.mean(output_pitch) / torch.mean(target_pitch) octaves = [0.125, 0.25, 0.5, 1.0, 2.0, 4.0, 8.0] nearest_octave = min(octaves, key=lambda x: abs(x - factor)) target_pitch *= nearest_octave if len(target_pitch) < len(output_pitch): target_pitch = torch.nn.functional.pad( target_pitch, (0, list(output_pitch.shape)[0] - list(target_pitch.shape)[0]), "constant", 0, ) if len(target_pitch) > len(output_pitch): target_pitch = target_pitch[0 : list(output_pitch.shape)[0]] audio_np = psola.vocode( audio_np, 22050, target_pitch=target_pitch ).astype(np.float32) normalize = (1.0 / np.max(np.abs(audio_np))) ** 0.9 audio_np = audio_np * normalize * MAX_WAV_VALUE audio_np = audio_np.astype(np.int16) # Resample to 32k wave = resampy.resample( audio_np, h.sampling_rate, h2.sampling_rate, filter="sinc_window", window=scipy.signal.windows.hann, num_zeros=8, ) wave_out = wave.astype(np.int16) # HiFi-GAN super-resolution wave = wave / MAX_WAV_VALUE wave = torch.FloatTensor(wave).to(torch.device("cuda")) new_mel = mel_spectrogram( wave.unsqueeze(0), h2.n_fft, h2.num_mels, h2.sampling_rate, h2.hop_size, h2.win_size, h2.fmin, h2.fmax, ) y_g_hat2 = hifigan_sr(new_mel) audio2 = y_g_hat2.squeeze() audio2 = audio2 * MAX_WAV_VALUE audio2_denoised = denoiser(audio2.view(1, -1), strength=35)[:, 0] # High-pass filter, mixing and denormalizing audio2_denoised = audio2_denoised.detach().cpu().numpy().reshape(-1) b = scipy.signal.firwin( 101, cutoff=10500, fs=h2.sampling_rate, pass_zero=False ) y = scipy.signal.lfilter(b, [1.0], audio2_denoised) y *= 4.0 # superres strength y_out = y.astype(np.int16) y_padded = np.zeros(wave_out.shape) y_padded[: y_out.shape[0]] = y_out sr_mix = wave_out + y_padded buffer = io.BytesIO() wavfile.write(buffer, 32000, sr_mix.astype(np.int16)) b64 = base64.b64encode(buffer.getvalue()) sound = "data:audio/x-wav;base64," + b64.decode("ascii") output_name = "TalkNet_" + str(int(time.time())) return [sound, arpa, playback_style, output_name] except Exception: return [ None, str(traceback.format_exc()), playback_hide, None, ] if __name__ == "__main__": app.run_server( mode="external", debug=True, dev_tools_ui=True, dev_tools_hot_reload=True, threaded=True, )
33.231397
88
0.492883
ace89652ec30f5a9b6f34183057c45a6ff9be8cc
33,020
py
Python
testplan/runners/pools/remote.py
YinjunZhu/testplan
8feeb92a15211454213c5ab279f1e4396a6d59a8
[ "Apache-2.0" ]
1
2021-07-21T08:28:41.000Z
2021-07-21T08:28:41.000Z
testplan/runners/pools/remote.py
YinjunZhu/testplan
8feeb92a15211454213c5ab279f1e4396a6d59a8
[ "Apache-2.0" ]
null
null
null
testplan/runners/pools/remote.py
YinjunZhu/testplan
8feeb92a15211454213c5ab279f1e4396a6d59a8
[ "Apache-2.0" ]
null
null
null
"""Remote worker pool module.""" import os import sys import signal import socket import getpass import platform import itertools from multiprocessing.pool import ThreadPool from schema import Or import testplan from testplan.common.utils.logger import TESTPLAN_LOGGER from testplan.common.config import ConfigOption from testplan.common.utils.path import ( module_abspath, pwd, makedirs, fix_home_prefix, workspace_root, ) from testplan.common.utils.strings import slugify from testplan.common.utils.remote import ( ssh_cmd, copy_cmd, link_cmd, remote_filepath_exists, ) from testplan.common.utils import path as pathutils from testplan.common.utils.process import execute_cmd from testplan.common.utils.timing import get_sleeper from testplan.runners.pools.base import Pool, PoolConfig from testplan.runners.pools.process import ProcessWorker, ProcessWorkerConfig from testplan.runners.pools.connection import ZMQServer from testplan.runners.pools.communication import Message class WorkerSetupMetadata(object): """ Metadata used on worker setup stage execution. Pushed dirs and files will be registered for deletion at exit. """ def __init__(self): self.push_dirs = None self.push_files = None self.push_dir = None self.setup_script = None self.env = None self.workspace_paths = None self.workspace_pushed = False class RemoteWorkerConfig(ProcessWorkerConfig): """ Configuration object for :py:class:`~testplan.runners.pools.remote.RemoteWorker` resource entity. """ @classmethod def get_options(cls): """ Schema for options validation and assignment of default values. """ return {"workers": int, "pool_type": str, "remote_host": str} class _LocationPaths(object): """Store local and remote equivalent paths.""" def __init__(self, local=None, remote=None): self.local = local self.remote = remote def __iter__(self): return iter((self.local, self.remote)) class RemoteWorker(ProcessWorker): """ Remote worker resource that pulls tasks from the transport provided, executes them in a local pool of workers and sends back task results. :param workers: Number of remote workers of remote pool of child worker. :type workers: ``int`` :param pool_type: Remote pool type that child worker will use. :type pool_type: ``str`` :param remote_host: Remote hostname to connect to. :type remote_host: ``str`` Also inherits all :py:class:`~testplan.runners.pools.process.ProcessWorkerConfig` options. """ CONFIG = RemoteWorkerConfig def __init__(self, **options): super(RemoteWorker, self).__init__(**options) self._remote_testplan_path = None self._user = getpass.getuser() self._workspace_paths = _LocationPaths() self._child_paths = _LocationPaths() self._working_dirs = _LocationPaths() self._should_transfer_workspace = True self._remote_testplan_runpath = None self.setup_metadata = WorkerSetupMetadata() self.remote_push_dir = None self.ssh_cfg = {"host": self.cfg.remote_host} self._testplan_import_path = _LocationPaths() def _execute_cmd_remote(self, cmd, label=None, check=True): """ Execute a command on the remote host. :param cmd: Remote command to execute - list of parameters. :param label: Optional label for debugging. :param check: Whether to check command return-code - defaults to True. See self._execute_cmd for more detail. """ execute_cmd( self.cfg.ssh_cmd(self.ssh_cfg, " ".join([str(a) for a in cmd])), label=label, check=check, logger=self.logger, ) def _mkdir_remote(self, remote_dir, label=None): """ Create a directory path on the remote host. :param remote_dir: Path to create. :param label: Optional debug label. """ if not label: label = "remote mkdir" cmd = self.cfg.remote_mkdir + [remote_dir] execute_cmd( self.cfg.ssh_cmd(self.ssh_cfg, " ".join([str(a) for a in cmd])), label=label, logger=self.logger, ) def _define_remote_dirs(self): """Define mandatory directories in remote host.""" runpath = os.path.join(self.parent.runpath) runpath_parts = runpath.split(os.sep) # We are not using os.path.join directly in case we are running # remote pool from Windows -> Linux hosts self._remote_testplan_path = "/".join( runpath_parts + ["remote_testplan_lib", slugify(self.cfg.parent.parent.name)] ) self._remote_testplan_runpath = "/".join( runpath_parts + ["remote_testplan_runpath", str(self.cfg.remote_host)] ) def _create_remote_dirs(self): """Create mandatory directories in remote host.""" cmd = self.cfg.remote_mkdir + [self._remote_testplan_path] execute_cmd( self.cfg.ssh_cmd(self.ssh_cfg, " ".join([str(a) for a in cmd])), label="create remote dirs", logger=self.logger, ) def _set_child_script(self): """Specify the remote worker executable file.""" self._child_paths.local = self._child_path() rel_path = os.path.relpath( self._child_paths.local, self._testplan_import_path.local ) self._child_paths.remote = os.path.join( self._testplan_import_path.remote, rel_path ) def _copy_dependencies_module(self): """Copy mandatory dependencies need to be imported before testplan.""" path = os.environ.get(testplan.TESTPLAN_DEPENDENCIES_PATH) if path is None: return local_path = "{}/dependencies.py".format(path) remote_path = "{}/dependencies.py".format(self._remote_testplan_path) self._transfer_data( source=local_path, target=remote_path, remote_target=True ) def _get_testplan_import_path(self): return os.path.dirname(os.path.dirname(module_abspath(testplan))) def _copy_testplan_package(self): """Make testplan package available on remote host""" self._testplan_import_path.local = self._get_testplan_import_path() if self.cfg.testplan_path: self._testplan_import_path.remote = self.cfg.testplan_path return # test if testplan package is available on remote host cmd = remote_filepath_exists( self.cfg.ssh_cmd, self.ssh_cfg, self._testplan_import_path.local ) if 0 == execute_cmd( cmd, label="testplan package availability check", check=False, logger=self.logger, ): # exists on remote self._testplan_import_path.remote = ( self._testplan_import_path.local ) else: # copy to remote self._testplan_import_path.remote = os.path.join( self._remote_testplan_path, "testplan_lib" ) # add trailing / to _testplan_import_path.local # this will copy everything under import path to to testplan_lib self._transfer_data( source=os.path.join(self._testplan_import_path.local, ""), target=self._testplan_import_path.remote, remote_target=True, deref_links=True, ) def _push_files(self): """Push files and directories to remote host.""" # Short-circuit if we've been given no files to push. if not self.cfg.push: if self.cfg.push_exclude or self.cfg.push_relative_dir: self.logger.warning( "Not been given any files to push - " "ignoring push configuration options." ) return # First enumerate the files and directories to be pushed, including # both their local source and remote destinations. push_files, push_dirs = self._build_push_lists() # Add the remote paths to the setup metadata. self.setup_metadata.push_files = [path.remote for path in push_files] self.setup_metadata.push_dirs = [path.remote for path in push_dirs] # Now actually push the files to the remote host. self._push_files_to_dst(push_files, push_dirs) def _build_push_lists(self): """ Create lists of the source and destination paths of files and directories to be pushed. Eliminate duplication of sub-directories. :return: Tuple containing lists of files and directories to be pushed. """ # Inspect types. Push config may either be a list of string paths, e.g: # ['/path/to/file1', '/path/to/file1'] # # Or it may be a list of tuples where the destination for each source # is specified also: # [('/local/path/to/file1', '/remote/path/to/file1'), # ('/local/path/to/file2', '/remote/path/to/file2')] if all(isinstance(cfg, str) for cfg in self.cfg.push): push_sources = self.cfg.push push_dsts = self._build_push_dests(push_sources) push_locations = zip(push_sources, push_dsts) else: if not all(len(pair) == 2 for pair in self.cfg.push): raise TypeError( "Expected either a list of 2-tuples or list of strings for " "push config." ) if self.cfg.push_relative_dir: self.logger.warning( "Ignoring push_relative_dir configuration " "as explicit destination paths have been provided." ) push_locations = self.cfg.push # Now seperate the push sources into lists of files and directories. push_files = [] push_dirs = [] for source, dest in push_locations: source = source.rstrip(os.sep) if os.path.isfile(source): push_files.append(_LocationPaths(source, dest)) elif os.path.isdir(source): push_dirs.append(_LocationPaths(source, dest)) else: self.logger.error('Item "{}" cannot be pushed!'.format(source)) # Eliminate push duplications if push_dirs and len(push_dirs) > 1: push_dirs.sort(key=lambda x: x.local) for idx in range(len(push_dirs) - 1): if push_dirs[idx + 1].local.startswith(push_dirs[idx].local): push_dirs[idx] = None push_dirs = [_dir for _dir in push_dirs if _dir is not None] return push_files, push_dirs def _build_push_dests(self, push_sources): """ When the destination paths have not been explicitly specified, build them automatically. By default we try to push to the same absolute path on the remote host, converted to POSIX format. However if a relative directory root has been configured we will build a remote destination based on that. """ if self.cfg.push_relative_dir: self.logger.debug( "local push dir = %s", self.cfg.push_relative_dir ) # Set up the remote push dir. self._remote_push_dir = "/".join( (self._remote_testplan_path, "push_files") ) self._mkdir_remote(self._remote_push_dir) self.setup_metadata.push_dir = self._remote_push_dir self.logger.debug( "Created remote push dir %s", self._remote_push_dir ) push_dsts = [ self._to_relative_push_dest(path) for path in push_sources ] else: push_dsts = [ pathutils.to_posix_path(path) for path in push_sources ] return push_dsts def _to_relative_push_dest(self, local_path): """ :param local_path: Full local path in local OS format. :return: Remote file and directory paths in POSIX format. """ relative_root = self.cfg.push_relative_dir if not pathutils.is_subdir(local_path, relative_root): raise RuntimeError( "Cannot push path {path} - is not within the " "specified local root {root}".format( path=local_path, root=relative_root ) ) local_rel_path = os.path.relpath(local_path, relative_root) return "/".join( (self._remote_push_dir, pathutils.to_posix_path(local_rel_path)) ) def _push_files_to_dst(self, push_files, push_dirs): """ Push files and directories to the remote host. Both the source and destination paths should be specified. :param push_files: Files to push. :param push_dirs: Directories to push. """ for source, dest in itertools.chain(push_files, push_dirs): remote_dir = dest.rpartition("/")[0] self.logger.debug("Create remote dir: %s", remote_dir) self._mkdir_remote(remote_dir) self._transfer_data( source=source, target=dest, remote_target=True, exclude=self.cfg.push_exclude, ) def _copy_workspace(self): """Make the local workspace available on remote host.""" self._workspace_paths.local = fix_home_prefix( os.path.abspath(self.cfg.workspace) ) self._workspace_paths.remote = "{}/{}".format( self._remote_testplan_path, self._workspace_paths.local.split(os.sep)[-1], ) if self.cfg.remote_workspace: # User defined the remote workspace to be used # Make a soft link and return execute_cmd( self.cfg.ssh_cmd( self.ssh_cfg, " ".join( self.cfg.link_cmd( path=fix_home_prefix(self.cfg.remote_workspace), link=self._workspace_paths.remote, ) ), ), label="linking to remote workspace (1).", logger=self.logger, ) return copy = True # flag to make a copy of workspace to remote if self.cfg.copy_workspace_check: cmd = self.cfg.copy_workspace_check( self.cfg.ssh_cmd, self.ssh_cfg, self._workspace_paths.local ) copy = ( execute_cmd( cmd, label="workspace availability check", check=False, logger=self.logger, ) != 0 ) if copy: # Workspace should be copied to remote. self._transfer_data( source=self._workspace_paths.local, target=self._remote_testplan_path, remote_target=True, exclude=self.cfg.workspace_exclude, ) # Mark that workspace pushed is safe to delete. Not some NFS. self.setup_metadata.workspace_pushed = True else: # Make a soft link instead of copying workspace. execute_cmd( self.cfg.ssh_cmd( self.ssh_cfg, " ".join( self.cfg.link_cmd( path=self._workspace_paths.local, link=self._workspace_paths.remote, ) ), ), label="linking to remote workspace (2).", logger=self.logger, ) def _remote_copy_path(self, path): """ Return a path on the remote host in the format user@host:path, suitable for use in a copy command such as `scp`. """ return "{user}@{host}:{path}".format( user=self._user, host=self.cfg.remote_host, path=path ) def _transfer_data( self, source, target, remote_source=False, remote_target=False, **copy_args ): if remote_source: source = self._remote_copy_path(source) if remote_target: target = self._remote_copy_path(target) self.logger.debug("Copying %(source)s to %(target)s", locals()) cmd = self.cfg.copy_cmd(source, target, **copy_args) with open(os.devnull, "w") as devnull: execute_cmd( cmd, "transfer data [..{}]".format(os.path.basename(target)), stdout=devnull, logger=self.logger, ) @property def _remote_working_dir(self): """Choose a working directory to use on the remote host.""" if not pathutils.is_subdir( self._working_dirs.local, self._workspace_paths.local ): raise RuntimeError( "Current working dir is not within the workspace.\n" "Workspace = {ws}\n" "Working dir = {cwd}".format( ws=self._workspace_paths.local, cwd=self._working_dirs.local, ) ) # Current working directory is within the workspace - use the same # path relative to the remote workspace. return pathutils.to_posix_path( os.path.join( self._workspace_paths.remote, os.path.relpath( self._working_dirs.local, self._workspace_paths.local ), ) ) def _prepare_remote(self): """Transfer local data to remote host.""" self._define_remote_dirs() self._create_remote_dirs() self._copy_workspace() self._copy_testplan_package() self._copy_dependencies_module() self._set_child_script() self._working_dirs.local = pwd() self._working_dirs.remote = self._remote_working_dir self.logger.debug( "Remote working path = %s", self._working_dirs.remote ) self._push_files() self.setup_metadata.setup_script = self.cfg.setup_script self.setup_metadata.env = self.cfg.env self.setup_metadata.workspace_paths = self._workspace_paths def _pull_files(self): """Push custom files to be available on remotes.""" for entry in [itm.rstrip("/") for itm in self.cfg.pull]: # Prepare target path for possible windows usage. dirname = os.sep.join(os.path.dirname(entry).split("/")) try: makedirs(dirname) except Exception as exc: self.logger.error( "Cound not create {} directory - {}".format(dirname, exc) ) else: self._transfer_data( source=entry, remote_source=True, target=dirname, exclude=self.cfg.pull_exclude, ) def _fetch_results(self): """Fetch back to local host the results generated remotely.""" self.logger.debug("Fetch results stage - %s", self.cfg.remote_host) try: self._transfer_data( source=self._remote_testplan_runpath, remote_source=True, target=os.path.dirname(self._remote_testplan_runpath), ) if self.cfg.pull: self._pull_files() except Exception as exc: self.logger.exception( "While fetching result from worker [%s]: %s", self, exc ) def _proc_cmd_impl(self): if platform.system() == "Windows": python_binary = os.environ["PYTHON3_REMOTE_BINARY"] else: python_binary = sys.executable cmd = [ python_binary, "-uB", self._child_paths.remote, "--index", str(self.cfg.index), "--address", self.transport.address, "--type", "remote_worker", "--log-level", str(TESTPLAN_LOGGER.getEffectiveLevel()), "--wd", self._working_dirs.remote, "--runpath", self._remote_testplan_runpath, "--remote-pool-type", self.cfg.pool_type, "--remote-pool-size", str(self.cfg.workers), "--testplan", self._testplan_import_path.remote, "--sys-path-file", self._write_syspath(), ] if os.environ.get(testplan.TESTPLAN_DEPENDENCIES_PATH): cmd.extend(["--testplan-deps", self._remote_testplan_path]) return cmd def _proc_cmd(self): """Command to start child process.""" cmd = self._proc_cmd_impl() return self.cfg.ssh_cmd(self.ssh_cfg, " ".join(cmd)) def _write_syspath(self): """ Write our current sys.path to a file and transfer it to the remote host. """ local_syspath_filepath = super(RemoteWorker, self)._write_syspath() remote_syspath_filepath = os.path.join( self._remote_testplan_path, os.path.basename(local_syspath_filepath), ) self._transfer_data( source=local_syspath_filepath, target=remote_syspath_filepath, remote_target=True, ) os.remove(local_syspath_filepath) self.logger.debug( "Transferred sys.path to remote host at: %s", remote_syspath_filepath, ) return remote_syspath_filepath def _get_syspath(self): """ adapt sys path to the remote side, replacing main script dir with proper remote path. If we could not figure out just return sys.path :return: list of remote valid sys paths """ sys_path = list(sys.path) main = sys.modules["__main__"] if main: main_path = os.path.dirname(os.path.abspath(main.__file__)) if pathutils.is_subdir(main_path, self._workspace_paths.local): try: rel_path = os.path.relpath( main_path, self._workspace_paths.local ) remote_path = os.path.join( self._workspace_paths.remote, rel_path ) sys_path.remove(main_path) sys_path.insert(0, remote_path) except Exception as e: self.logger.debug( "could not set the remote path as desired will use sys.path", exc_info=e, ) return sys_path def starting(self): """Start a child remote worker.""" self._prepare_remote() super(RemoteWorker, self).starting() def stopping(self): """Stop child process worker.""" self._fetch_results() super(RemoteWorker, self).stopping() def _wait_stopped(self, timeout=None): sleeper = get_sleeper(1, timeout) while next(sleeper): if self.status.tag != self.status.STOPPED: self.logger.info("Waiting for workers to stop") else: break else: raise RuntimeError( "Not able to stop worker {} after {}s".format(self, timeout) ) def aborting(self): """Abort child process worker.""" try: self._fetch_results() except Exception as exc: self.logger.error("Could not fetch results, {}".format(exc)) super(RemoteWorker, self).aborting() class RemotePoolConfig(PoolConfig): """ Configuration object for :py:class:`~testplan.runners.pools.remote.RemotePool` executor resource entity. """ default_hostname = socket.gethostbyname(socket.gethostname()) default_workspace_root = workspace_root() @classmethod def get_options(cls): """ Schema for options validation and assignment of default values. """ return { "hosts": dict, ConfigOption( "abort_signals", default=[signal.SIGINT, signal.SIGTERM] ): [int], ConfigOption("worker_type", default=RemoteWorker): object, ConfigOption("pool_type", default="thread"): str, ConfigOption("host", default=cls.default_hostname): str, ConfigOption("port", default=0): int, ConfigOption("copy_cmd", default=copy_cmd): lambda x: callable(x), ConfigOption("link_cmd", default=link_cmd): lambda x: callable(x), ConfigOption("ssh_cmd", default=ssh_cmd): lambda x: callable(x), ConfigOption("workspace", default=cls.default_workspace_root): str, ConfigOption("workspace_exclude", default=[]): Or(list, None), ConfigOption("remote_workspace", default=None): Or(str, None), ConfigOption( "copy_workspace_check", default=remote_filepath_exists ): Or(lambda x: callable(x), None), ConfigOption("env", default=None): Or(dict, None), ConfigOption("setup_script", default=None): Or(list, None), ConfigOption("push", default=[]): Or(list, None), ConfigOption("push_exclude", default=[]): Or(list, None), ConfigOption("push_relative_dir", default=None): Or(str, None), ConfigOption("delete_pushed", default=False): bool, ConfigOption("pull", default=[]): Or(list, None), ConfigOption("pull_exclude", default=[]): Or(list, None), ConfigOption("remote_mkdir", default=["/bin/mkdir", "-p"]): list, ConfigOption("testplan_path", default=None): Or(str, None), ConfigOption("worker_heartbeat", default=30): Or(int, float, None), } class RemotePool(Pool): """ Pool task executor object that initializes remote workers and dispatches tasks. :param name: Pool name. :type name: ``str`` :param hosts: Map of host(ip): number of their local workers. i.e {'hostname1': 2, '10.147.XX.XX': 4} :type hosts: ``dict`` of ``str``:``int`` :param size: Pool workers size. Default: 4 :type size: ``int`` :param abort_signals: Signals to trigger abort logic. Default: INT, TERM. :type abort_signals: ``list`` of ``int`` :param worker_type: Type of worker to be initialized. :type worker_type: :py:class:`~testplan.runners.pools.remote.RemoteWorker` :param pool_type: Local pool that will be initialized in remote workers. i.e ``thread``, ``process``. :type pool_type: ``str`` :param host: Host that pool binds and listens for requests. Defaults to local hostname. :type host: ``str`` :param port: Port that pool binds. Default: 0 (random) :type port: ``int`` :param copy_cmd: Creates the remote copy command. :type copy_cmd: ``callable`` :param link_cmd: Creates the solf link command. :type link_cmd: ``callable`` :param ssh_cmd: Creates the ssh command. :type ssh_cmd: ``callable`` :param workspace: Current project workspace to be transferred. :type workspace: ``str`` :param workspace_exclude: Patterns to exclude files when pushing workspace. :type workspace_exclude: ``list`` of ``str`` :param remote_workspace: Use a workspace that already exists in remote host. :type remote_workspace: ``str`` :param copy_workspace_check: Check to indicate whether to copy workspace. :type copy_workspace_check: ``callable`` or ``NoneType`` :param env: Environment variables to be propagated. :type env: ``dict`` :param setup_script: Script to be executed on remote as very first thing. :type setup_script: ``list`` of ``str`` :param push: Files and directories to push to the remote. :type push: ``list`` of ``str`` :param push_exclude: Patterns to exclude files on push stage. :type push_exclude: ``list`` of ``str`` :param delete_pushed: Deleted pushed files and workspace on remote at exit. :type delete_pushed: ``bool`` :param pull: Files and directories to be pulled from the remote at the end. :type pull: ``list`` of ``str`` :param pull_exclude: Patterns to exclude files on pull stage.. :type pull_exclude: ``list`` of ``str`` :param remote_mkdir: Command to make directories in remote worker. :type remote_mkdir: ``list`` of ``str`` :param testplan_path: Path to import testplan from on remote host. :type testplan_path: ``str`` :param worker_heartbeat: Worker heartbeat period. :type worker_heartbeat: ``int`` or ``float`` or ``NoneType`` Also inherits all :py:class:`~testplan.runners.pools.base.Pool` options. """ CONFIG = RemotePoolConfig CONN_MANAGER = ZMQServer def __init__( self, name, hosts, size=4, abort_signals=None, worker_type=RemoteWorker, pool_type="thread", host=CONFIG.default_hostname, port=0, copy_cmd=copy_cmd, link_cmd=link_cmd, ssh_cmd=ssh_cmd, workspace=CONFIG.default_workspace_root, workspace_exclude=None, remote_workspace=None, copy_workspace_check=remote_filepath_exists, env=None, setup_script=None, push=None, push_exclude=None, push_relative_dir=None, delete_pushed=False, pull=None, pull_exclude=None, remote_mkdir=None, testplan_path=None, worker_heartbeat=30, **options ): self.pool = None options.update(self.filter_locals(locals())) super(RemotePool, self).__init__(**options) self._request_handlers[ Message.MetadataPull ] = self._worker_setup_metadata self._instances = {} for host, number_of_workers in self.cfg.hosts.items(): self._instances[host] = { "host": host, "number_of_workers": number_of_workers, } @staticmethod def _worker_setup_metadata(worker, request, response): worker.respond( response.make(Message.Metadata, data=worker.setup_metadata) ) def _add_workers(self): """TODO.""" for instance in self._instances.values(): worker = self.cfg.worker_type( index=instance["host"], remote_host=instance["host"], workers=instance["number_of_workers"], pool_type=self.cfg.pool_type, restart_count=self.cfg.restart_count, ) self.logger.debug("Created {}".format(worker)) worker.parent = self worker.cfg.parent = self.cfg self._workers.add(worker, uid=instance["host"]) def _start_workers(self): """Start all workers of the pool""" for worker in self._workers: self._conn.register(worker) if self.pool: self._workers.start_in_pool(self.pool) else: self._workers.start() def _stop_workers(self): if self.pool: self._workers.stop_in_pool(self.pool) else: self._workers.stop() def _start_thread_pool(self): size = len(self._instances) try: if size > 2: self.pool = ThreadPool(5 if size > 5 else size) except Exception as exc: if isinstance(exc, AttributeError): self.logger.warning( "Please upgrade to the suggested python interpreter." ) def starting(self): self._start_thread_pool() super(RemotePool, self).starting() def stopping(self): for worker in self._workers: if worker.status.tag == worker.status.STARTING: try: worker.wait(worker.status.STARTED) except Exception: self.logger.error( "Timeout waiting for worker {} to quit starting " "while pool {} is stopping".format( worker, self.cfg.name ) ) super(RemotePool, self).stopping() if self.pool: self.pool.terminate() self.pool = None
35.697297
85
0.587068
ace896c49300d8245c4ba65d5a482bfd2e476222
3,133
py
Python
data/task_scripts/main/task01003.py
aallaire91/phyre
ee882194c12bae5561c25ec65f95a7c0944f8129
[ "Apache-2.0" ]
432
2019-08-15T15:45:43.000Z
2022-02-26T23:13:34.000Z
data/task_scripts/main/task01003.py
aallaire91/phyre
ee882194c12bae5561c25ec65f95a7c0944f8129
[ "Apache-2.0" ]
38
2019-09-06T15:39:03.000Z
2022-03-12T00:11:25.000Z
data/task_scripts/main/task01003.py
aallaire91/phyre
ee882194c12bae5561c25ec65f95a7c0944f8129
[ "Apache-2.0" ]
69
2019-08-16T02:08:41.000Z
2022-01-27T23:23:03.000Z
# Copyright (c) Facebook, Inc. and its affiliates. # # 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. """Falling""" """Template task in which you prevent something from falling so ball can roll into container.""" import numpy as np import phyre.creator as creator_lib import phyre.virtual_tools as vt @creator_lib.define_task_template( seed=range(1000), version="2", search_params=dict(required_flags=['BALL:GOOD_STABLE'], excluded_flags=['BALL:TRIVIAL'], diversify_tier='ball'), ) def build_task(C, seed): rng = np.random.RandomState(seed=seed) containerHeight = [50, 100] containerBottom = [50, 150] containerOverhangL = [10, 25] containerOverhangR = [10, 25] containerElevation = [10, 300] containerX = [30, (vt.VT_SCALE - 150 - 55)] ballRadius = [7, 15] flip_lr = rng.uniform(0, 1) < 0.5 cH = rng.uniform(containerHeight[0], containerHeight[1]) cB = rng.uniform(containerBottom[0], containerBottom[1]) cOL = rng.uniform(containerOverhangL[0], containerOverhangL[1]) cOR = rng.uniform(containerOverhangR[0], containerOverhangR[1]) cE = rng.uniform(containerElevation[0], containerElevation[1]) cX = rng.uniform(containerX[0], containerX[1]) bR = rng.uniform(ballRadius[0], ballRadius[1]) ## Get bottom left coordinate of container, coordinates of ball xBottom = cX yBottom = cE - cH / 2 xBall = cB / 2 + cX yBall = yBottom + 8 + bR if flip_lr: xBall = vt.flip_left_right(xBall) ## Make the world container, _ = vt.add_container( C, [[xBottom - cOL, yBottom + cH], [xBottom, yBottom], [xBottom + cB, yBottom], [xBottom + cB + cOR, yBottom + cH]], 7, True, False, flip_lr=flip_lr) floor = vt.add_box(C, [0., 0., vt.VT_SCALE, 7.], False, flip_lr=flip_lr) ball = C.add('dynamic ball', bR * 2. / vt.VT_SCALE, center_x=xBall * C.scene.width / vt.VT_SCALE, center_y=yBall * C.scene.height / vt.VT_SCALE) # Create assignment: C.update_task(body1=ball, body2=floor, relationships=[C.SpatialRelationship.TOUCHING]) C.set_meta(C.SolutionTier.VIRTUAL_TOOLS) ''' var pgw = new PGWorld(DIMS, GRAVITY) pgw.addContainer('Container', [[xBottom-cOL, yBottom+cH], [xBottom, yBottom], [xBottom+cB, yBottom], [xBottom+cB+cOR, yBottom+cH]], 7, null, 'blue') pgw.addBoxGoal('Floor', [0, 0, 600, 7], 'green') pgw.addBall('Ball', [xBall, yBall], bR, 'red') pgw.attachSpecificInGoal('Floor', 'Ball', 1) return pgw'''
38.207317
150
0.651133
ace899eb8bed2fcd9ff145913585cf73210102ee
1,389
py
Python
mytest/getDuoxiancheng.py
yejianfeng2014/tacotron
0dccf1f330c8f8f146347d4a4ca2d53a0780fb64
[ "Apache-2.0" ]
null
null
null
mytest/getDuoxiancheng.py
yejianfeng2014/tacotron
0dccf1f330c8f8f146347d4a4ca2d53a0780fb64
[ "Apache-2.0" ]
null
null
null
mytest/getDuoxiancheng.py
yejianfeng2014/tacotron
0dccf1f330c8f8f146347d4a4ca2d53a0780fb64
[ "Apache-2.0" ]
null
null
null
# -*-coding:utf-8-*- from time import ctime, sleep import threading import numpy as np import collections loops = ['广州', '北京'] t_list = ['01', '02', '03'] cldas_sum = collections.deque() class MyThread(threading.Thread): def __init__(self, func, args, name=''): threading.Thread.__init__(self) self.name = name self.func = func self.args = args self.result = self.func(*self.args) def get_result(self): try: return self.result except Exception: return None def loop(nloop): for j in t_list: cldas_values = [] for k in range(4): cldas_value = nloop + str(k) cldas_values.append(cldas_value) cldas_values.append(j) cldas_values.append(nloop) cldas_sum.append(cldas_values) print(id(cldas_values)) # print(cldas_sum) return cldas_sum def main(): print('start at', ctime()) threads = [] nloops = range(len(loops)) for i in nloops: t = MyThread(loop, (loops[i],), loop.__name__) threads.append(t) for i in nloops: # start threads 此处并不会执行线程,而是将任务分发到每个线程,同步线程。等同步完成后再开始执行start方法 threads[i].start() for i in nloops: # jion()方法等待线程完成 threads[i].join() print(threads[1].get_result()) print('DONE AT:', ctime()) if __name__ == '__main__': main()
23.15
84
0.597552
ace899efa788ded1617c208a3fab2c928a3bdacb
97
py
Python
pr0gramm/__init__.py
ricardoboss/python-pr0gramm-api
378bc6973e1899d027770522cb46d7e64ed9ea3c
[ "MIT" ]
null
null
null
pr0gramm/__init__.py
ricardoboss/python-pr0gramm-api
378bc6973e1899d027770522cb46d7e64ed9ea3c
[ "MIT" ]
null
null
null
pr0gramm/__init__.py
ricardoboss/python-pr0gramm-api
378bc6973e1899d027770522cb46d7e64ed9ea3c
[ "MIT" ]
null
null
null
__author__ = 'Ricardo Boss <contact@ricardoboss.de>' __version__ = '0.5.0' from .api import Api
19.4
52
0.731959
ace89a288a1d7ef8795f1300cb9f6d9fd120b5e6
844
py
Python
vasp-validator/src/vasp_validator/tests/__init__.py
tanshuai/reference-wallet
e8efec4acc6af6e319cf075c10693ddf7754cc83
[ "Apache-2.0" ]
14
2020-12-17T08:03:51.000Z
2022-03-26T04:21:18.000Z
vasp-validator/src/vasp_validator/tests/__init__.py
tanshuai/reference-wallet
e8efec4acc6af6e319cf075c10693ddf7754cc83
[ "Apache-2.0" ]
20
2020-12-15T12:02:56.000Z
2021-05-19T23:37:34.000Z
vasp-validator/src/vasp_validator/tests/__init__.py
tanshuai/reference-wallet
e8efec4acc6af6e319cf075c10693ddf7754cc83
[ "Apache-2.0" ]
12
2020-12-10T16:35:27.000Z
2022-02-01T04:06:10.000Z
# Copyright (c) The Diem Core Contributors # SPDX-License-Identifier: Apache-2.0 import argparse import pytest def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "vasp_proxy_module", help="Module path containing vasp_proxy_class", ) parser.add_argument( "vasp_proxy_class", help="Instances of this class will be used to communicate with the tested VASP", ) return parser.parse_args() def automatic_validation_main(): args = parse_args() pytest.main( [ "-p", "vasp_validator.tests.plugin", "--pyargs", "vasp_validator.tests.test_send_tx", "--vasp-proxy-module", args.vasp_proxy_module, "--vasp-proxy-class", args.vasp_proxy_class, ] )
24.114286
88
0.603081
ace89a58233f31a8c56ee1c5b0be7a2984d3e382
8,405
py
Python
lexico/word.py
kshitij10496/glossarist
680ce40175779fd27cb6112dd7e7dfe5f7d681e9
[ "MIT" ]
21
2017-11-13T12:51:15.000Z
2021-05-18T19:17:48.000Z
lexico/word.py
kshitij10496/glossarist
680ce40175779fd27cb6112dd7e7dfe5f7d681e9
[ "MIT" ]
16
2017-11-13T15:28:08.000Z
2018-02-28T07:12:15.000Z
lexico/word.py
kshitij10496/glossarist
680ce40175779fd27cb6112dd7e7dfe5f7d681e9
[ "MIT" ]
13
2017-11-13T14:42:47.000Z
2020-09-20T10:43:20.000Z
import json import click from wordnik import * from .utils import create_word_api, load_api_key, fetch_translations class Word(object): def __init__(self, word, **kwargs): self.word = word self._meanings = kwargs.get('_meanings', list()) self._examples = kwargs.get('_examples', list()) self._hyphenation = kwargs.get('_hyphenation', None) self._audio = kwargs.get('_audio', list()) self._text_pronunciations = kwargs.get('_text_pronunciations', list()) self._phrases = kwargs.get('_phrases', list()) self._synonyms = kwargs.get('_synonyms', list()) self._antonyms = kwargs.get('_antonyms', list()) self._translations = kwargs.get('_translations', list()) def __repr__(self): return 'Word({})'.format(self.word) @property def meanings(self): if not self._meanings: self._meanings = Word.get_meanings(self.word) return self._meanings @property def examples(self): if not self._examples: self._examples = Word.get_examples(self.word) return self._examples @property def hyphenation(self): if not self._hyphenation: self._hyphenation = Word.get_hyphenation(self.word) return self._hyphenation @property def audio(self): if not self._audio: self._audio = Word.get_audio(self.word) return self._audio @property def text_pronunciations(self): if not self._text_pronunciations: self._text_pronunciations = Word.get_text_pronunciations(self.word) return self._text_pronunciations @property def phrases(self): if not self._phrases: self._phrases = Word.get_phrases(self.word) return self._phrases @property def synonyms(self): if not self._synonyms: self._synonyms = Word.get_synonyms(self.word) return self._synonyms @property def antonyms(self): if not self._antonyms: self._antonyms = Word.get_antonyms(self.word) return self._antonyms @property def translations(self): if not self._translations: self._translations = Word.get_translations(self.word) return self._translations @staticmethod def get_meanings(word): API_KEY = load_api_key() WORD_API = create_word_api(API_KEY) definitions = WORD_API.getDefinitions(word, limit=5) data = [definition.text for definition in definitions] return data @staticmethod def get_examples(word): API_KEY = load_api_key() WORD_API = create_word_api(API_KEY) examples = WORD_API.getExamples(word, limit=3) return [example.text for example in examples.examples] @staticmethod def get_hyphenation(word): API_KEY = load_api_key() WORD_API = create_word_api(API_KEY) hyphenation = WORD_API.getHyphenation(word) if hyphenation is not None: return '-'.join(syllable.text for syllable in hyphenation) return hyphenation @staticmethod def get_audio(word): API_KEY = load_api_key() WORD_API = create_word_api(API_KEY) audio = WORD_API.getAudio(word, limit=1) # TODO: Provide flexibility in setting limit if audio is not None: return audio[0].fileUrl else: return list() @staticmethod def get_text_pronunciations(word): API_KEY = load_api_key() WORD_API = create_word_api(API_KEY) pronunciations = WORD_API.getTextPronunciations(word) return [pronunciation.raw for pronunciation in pronunciations if pronunciation.rawType != 'arpabet'] @staticmethod def get_phrases(word): API_KEY = load_api_key() WORD_API = create_word_api(API_KEY) phrases = WORD_API.getPhrases(word) if phrases is not None: return ['{} {}'.format(phrase.gram1, phrase.gram2) for phrase in phrases] else: return phrases @staticmethod def get_synonyms(word): API_KEY = load_api_key() WORD_API = create_word_api(API_KEY) synonyms = WORD_API.getRelatedWords(word, relationshipTypes='synonym') if synonyms is not None: synonym_words = [] for synonym in synonyms: if synonym.relationshipType == 'synonym': synonym_words.extend(synonym.words) return synonym_words return list() @staticmethod def get_antonyms(word): API_KEY = load_api_key() WORD_API = create_word_api(API_KEY) antonyms = WORD_API.getRelatedWords(word, relationshipTypes='antonym') if antonyms is not None: antonym_words = [] for antonym in antonyms: if antonym.relationshipType == 'antonym': antonym_words.extend(antonym.words) return antonym_words return list() @staticmethod def get_translations(word): translations = fetch_translations(word) if translations is not None: return translations return list() def stringify(self): # Representation for meanings meanings = list() for index, meaning in enumerate(self.meanings, start=1): meanings.append(click.style('{}. {}'.format(index, meaning))) # Representation for examples examples = list() for index, example in enumerate(self.examples, start=1): examples.append(click.style('{}. {}'.format(index, example), fg='cyan')) hyphenation, audio, phrases, text_pronunciations = None, None, None, None if self.hyphenation: hyphenation = click.style(self.hyphenation, fg='green') if self.audio: audio = click.style(self.audio, bg='black') # Representation for text pronunciations if self.text_pronunciations: text_pronunciations = list() for index, pronunciation in enumerate(self.text_pronunciations, start=1): text_pronunciations.append(click.style('{}. {}'.format(index, pronunciation), fg='yellow')) # Representation for phrases if self.phrases: phrases = list() for index, phrase in enumerate(self.phrases, start=1): phrases.append(click.style('{}. {}'.format(index, phrase), fg='magenta')) # Representation for synonyms synonyms, antonyms = None, None if self.synonyms: synonyms = click.style(', '.join(self.synonyms), fg='green') if self.antonyms: antonyms = click.style(', '.join(self.antonyms), fg='red') # Representation for translations if self.translations: translations = list() for index, translation in enumerate(self.translations, start=1): translations.append(click.style('{}. {}'.format(index, translation))) headings = [ ('Word', click.style(self.word, fg='red', bold=True), '\t'), ('Meanings', meanings, '\n'), ('Synonyms', synonyms, ' '), ('Antonyms', antonyms, ' '), ('Examples', examples, '\n'), ('Text Pronunciations', text_pronunciations, '\n'), ('Phrases', phrases, '\n'), ('Hyphenation', hyphenation, ' '), ('Audio', audio, ' '), ('Translations', translations, '\n') ] s = [create_entry(heading, data, separator) for heading, data, separator in headings if data is not None] return '\n\n'.join(s) def jsonify(self): return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4) def create_entry(heading, data, separator): HEADING_COLOR = 'blue' complete_heading = heading + ':' if isinstance(data, list): complete_data = '\n'.join(data) else: complete_data = data #print('Printing:', heading) #print('DATA:', data) return click.style(complete_heading, fg=HEADING_COLOR, underline=True, bold=True) + separator + complete_data
32.832031
113
0.602617
ace89b38c3a58ad7e9879ba76917ab13fd6bccbd
6,356
py
Python
test/unit/jobs/test_job_configuration.py
ramezrawas/galaxy-1
c03748dd49c060a68d07bce56eae33e0ba154414
[ "CC-BY-3.0" ]
6
2018-11-03T22:43:35.000Z
2022-02-15T17:51:33.000Z
test/unit/jobs/test_job_configuration.py
igorhollaender/OBSOLETE_sirv_dashboard
85aec60b80ef6f561d89398e3da5963d3d0f2aa4
[ "CC-BY-3.0" ]
7
2016-12-07T22:19:37.000Z
2019-01-30T15:04:26.000Z
test/unit/jobs/test_job_configuration.py
igorhollaender/OBSOLETE_sirv_dashboard
85aec60b80ef6f561d89398e3da5963d3d0f2aa4
[ "CC-BY-3.0" ]
10
2017-04-10T21:40:22.000Z
2022-02-21T16:50:10.000Z
import datetime import os import shutil import tempfile import unittest from galaxy.util import bunch from galaxy.jobs import JobConfiguration # File would be slightly more readable if contents were embedded directly, but # there are advantages to testing the documentation/examples. SIMPLE_JOB_CONF = os.path.join( os.path.dirname( __file__ ), "..", "..", "..", "config", "job_conf.xml.sample_basic" ) ADVANCED_JOB_CONF = os.path.join( os.path.dirname( __file__ ), "..", "..", "..", "config", "job_conf.xml.sample_advanced" ) class JobConfXmlParserTestCase( unittest.TestCase ): def setUp( self ): self.temp_directory = tempfile.mkdtemp() self.config = bunch.Bunch( job_config_file=os.path.join( self.temp_directory, "job_conf.xml" ), use_tasked_jobs=False, job_resource_params_file="/tmp/fake_absent_path", config_dict={}, ) self.__write_config_from( SIMPLE_JOB_CONF ) self.app = bunch.Bunch( config=self.config, job_metrics=MockJobMetrics() ) self.__job_configuration = None def tearDown( self ): shutil.rmtree( self.temp_directory ) def test_load_simple_runner( self ): runner_plugin = self.job_config.runner_plugins[ 0 ] assert runner_plugin[ "id" ] == "local" assert runner_plugin[ "load" ] == "galaxy.jobs.runners.local:LocalJobRunner" assert runner_plugin[ "workers" ] == 4 def test_tasks_disabled( self ): assert len( [ r for r in self.job_config.runner_plugins if r[ "id" ] == "tasks" ] ) == 0 def test_configuration_of_tasks( self ): self.config.use_tasked_jobs = True self.config.local_task_queue_workers = 5 task_runners = [ r for r in self.job_config.runner_plugins if r[ "id" ] == "tasks" ] assert len( task_runners ) == 1 assert task_runners[ 0 ][ "workers" ] == 5 def test_load_simple_handler( self ): main_handler = self.job_config.handlers[ "main" ] assert main_handler[ 0 ] == "main" def test_if_one_handler_implicit_default( self ): assert self.job_config.default_handler_id == "main" def test_explicit_handler_default( self ): self.__with_advanced_config() assert self.job_config.default_handler_id == "handlers" def test_handler_tag_parsing( self ): self.__with_advanced_config() assert "handler0" in self.job_config.handlers[ "handlers" ] assert "handler1" in self.job_config.handlers[ "handlers" ] def test_load_simple_destination( self ): local_dest = self.job_config.destinations[ "local" ][ 0 ] assert local_dest.id == "local" assert local_dest.runner == "local" def test_load_destination_params( self ): self.__with_advanced_config() pbs_dest = self.job_config.destinations[ "pbs_longjobs" ][ 0 ] assert pbs_dest.id == "pbs_longjobs" assert pbs_dest.runner == "pbs" dest_params = pbs_dest.params assert dest_params[ "Resource_List" ] == "walltime=72:00:00" def test_destination_tags( self ): self.__with_advanced_config() longjob_dests = self.job_config.destinations[ "longjobs" ] assert len( longjob_dests ) == 2 assert longjob_dests[ 0 ].id == "pbs_longjobs" assert longjob_dests[ 1 ].id == "remote_cluster" def test_load_tool( self ): self.__with_advanced_config() baz_tool = self.job_config.tools[ "baz" ][ 0 ] assert baz_tool.id == "baz" assert baz_tool.handler == "special_handlers" assert baz_tool.destination == "bigmem" def test_load_tool_params( self ): self.__with_advanced_config() foo_tool = self.job_config.tools[ "foo" ][ 0 ] assert foo_tool.params[ "source" ] == "trackster" def test_default_limits( self ): limits = self.job_config.limits assert limits.registered_user_concurrent_jobs is None assert limits.anonymous_user_concurrent_jobs is None assert limits.walltime is None assert limits.walltime_delta is None assert limits.output_size is None assert limits.destination_user_concurrent_jobs == {} assert limits.destination_total_concurrent_jobs == {} def test_limit_overrides( self ): self.__with_advanced_config() limits = self.job_config.limits assert limits.registered_user_concurrent_jobs == 2 assert limits.anonymous_user_concurrent_jobs == 1 assert limits.destination_user_concurrent_jobs[ "local" ] == 1 assert limits.destination_user_concurrent_jobs[ "mycluster" ] == 2 assert limits.destination_user_concurrent_jobs[ "longjobs" ] == 1 assert limits.walltime_delta == datetime.timedelta( 0, 0, 0, 0, 0, 24 ) def test_env_parsing( self ): self.__with_advanced_config() env_dest = self.job_config.destinations[ "java_cluster" ][ 0 ] assert len( env_dest.env ) == 4, len( env_dest.env ) assert env_dest.env[ 0 ][ "name" ] == "_JAVA_OPTIONS" assert env_dest.env[ 0 ][ "value" ] == '-Xmx6G' assert env_dest.env[ 1 ][ "name" ] == "ANOTHER_OPTION" assert env_dest.env[ 1 ][ "raw" ] is True assert env_dest.env[ 2 ][ "file" ] == "/mnt/java_cluster/environment_setup.sh" assert env_dest.env[ 3 ][ "execute" ] == "module load javastuff/2.10" def test_macro_expansion( self ): self.__with_advanced_config() for name in ["foo_small", "foo_medium", "foo_large", "foo_longrunning"]: assert self.job_config.destinations[ name ] # TODO: Add job metrics parsing test. @property def job_config( self ): if not self.__job_configuration: self.__job_configuration = JobConfiguration( self.app ) return self.__job_configuration def __with_advanced_config( self ): self.__write_config_from( ADVANCED_JOB_CONF ) def __write_config_from( self, path ): self.__write_config( open( path, "r" ).read() ) def __write_config( self, contents ): with open( os.path.join( self.temp_directory, "job_conf.xml" ), "w" ) as f: f.write( contents ) class MockJobMetrics( object ): def __init__( self ): pass def set_destination_conf_element( self, id, element ): pass
39.234568
123
0.661894
ace89c272c1ccb3236fe734c70d7aa124d47b7a3
485
py
Python
tests/test_callbacks.py
alercebroker/ztf-api-apf
916f02009a07e43d6ed26bdb1e2b0ec7f41321f1
[ "Apache-2.0" ]
null
null
null
tests/test_callbacks.py
alercebroker/ztf-api-apf
916f02009a07e43d6ed26bdb1e2b0ec7f41321f1
[ "Apache-2.0" ]
null
null
null
tests/test_callbacks.py
alercebroker/ztf-api-apf
916f02009a07e43d6ed26bdb1e2b0ec7f41321f1
[ "Apache-2.0" ]
null
null
null
from flask import g import logging def test_before_request(app): with app.test_request_context("/"): app.preprocess_request() assert g.time is not None def test_after_request(caplog, app): caplog.set_level(logging.DEBUG) with app.test_request_context("/"): app.preprocess_request() rv = app.dispatch_request() res = app.make_response(rv) app.process_response(res) assert "GET http /? 200 OK time:" in caplog.text
25.526316
56
0.670103
ace89d7ef975f43b6d3c9c08b49efa408dea2ad6
511
py
Python
tests/device/test_factory_reset.py
Sensirion/python-shdlc-sfc5xxx
f9bd288a996ad969ee5bbb7f52b6e8f00fdf47e5
[ "BSD-3-Clause" ]
null
null
null
tests/device/test_factory_reset.py
Sensirion/python-shdlc-sfc5xxx
f9bd288a996ad969ee5bbb7f52b6e8f00fdf47e5
[ "BSD-3-Clause" ]
null
null
null
tests/device/test_factory_reset.py
Sensirion/python-shdlc-sfc5xxx
f9bd288a996ad969ee5bbb7f52b6e8f00fdf47e5
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # (c) Copyright 2020 Sensirion AG, Switzerland from __future__ import absolute_import, division, print_function import pytest @pytest.mark.needs_device def test(device): """ Test if factory_reset() works as expected by chaning a nonvolatile setting, perform the reset, and then verifying that the setting was reset to its default value. """ device.set_user_controller_gain(0.1337) device.factory_reset() assert device.get_user_controller_gain() == 1.0
28.388889
79
0.731898
ace89f06960dc39c923abac59c39215396dc7957
527
gyp
Python
crates/neon-sys/native/binding.gyp
anton-iskryzhytskyi/neon
ec46747e87b4c49ca4bde6463814fb571d2a5952
[ "Apache-2.0", "MIT" ]
539
2015-12-24T00:12:44.000Z
2022-03-04T14:39:23.000Z
crates/neon-sys/native/binding.gyp
anton-iskryzhytskyi/neon
ec46747e87b4c49ca4bde6463814fb571d2a5952
[ "Apache-2.0", "MIT" ]
7
2015-12-17T23:17:54.000Z
2015-12-29T00:06:40.000Z
crates/neon-sys/native/binding.gyp
anton-iskryzhytskyi/neon
ec46747e87b4c49ca4bde6463814fb571d2a5952
[ "Apache-2.0", "MIT" ]
12
2015-12-24T00:11:33.000Z
2015-12-28T21:55:33.000Z
{ "targets": [{ "target_name": "neon", "sources": [ "src/neon.cc" ], "include_dirs": [ "<!(node -e \"require('nan')\")" ], 'configurations': { 'Release': { 'msvs_settings': { 'VCCLCompilerTool': { 'WholeProgramOptimization': 'false' }, 'VCLinkerTool': { 'LinkTimeCodeGeneration': 0 } } } } }] }
26.35
61
0.339658
ace89fac896c03d612d1c7531c1094b64c2d3fbf
2,231
py
Python
tests/multiple_database/models.py
marload/django
0ce8c15033c95931e5abd36cf071b76a0b19771a
[ "CNRI-Python-GPL-Compatible", "BSD-3-Clause" ]
2
2016-07-16T23:12:49.000Z
2017-11-14T21:43:10.000Z
tests/multiple_database/models.py
marload/django
0ce8c15033c95931e5abd36cf071b76a0b19771a
[ "CNRI-Python-GPL-Compatible", "BSD-3-Clause" ]
3
2016-05-15T22:05:14.000Z
2019-11-02T15:58:14.000Z
tests/multiple_database/models.py
marload/django
0ce8c15033c95931e5abd36cf071b76a0b19771a
[ "CNRI-Python-GPL-Compatible", "BSD-3-Clause" ]
2
2016-01-19T18:29:21.000Z
2021-12-23T18:17:39.000Z
from django.contrib.auth.models import User from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation, ) from django.contrib.contenttypes.models import ContentType from django.db import models class Review(models.Model): source = models.CharField(max_length=100) content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Meta: ordering = ('source',) def __str__(self): return self.source class PersonManager(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) class Person(models.Model): name = models.CharField(max_length=100, unique=True) objects = PersonManager() class Meta: ordering = ('name',) def __str__(self): return self.name # This book manager doesn't do anything interesting; it just # exists to strip out the 'extra_arg' argument to certain # calls. This argument is used to establish that the BookManager # is actually getting used when it should be. class BookManager(models.Manager): def create(self, *args, extra_arg=None, **kwargs): return super().create(*args, **kwargs) def get_or_create(self, *args, extra_arg=None, **kwargs): return super().get_or_create(*args, **kwargs) class Book(models.Model): title = models.CharField(max_length=100) published = models.DateField() authors = models.ManyToManyField(Person) editor = models.ForeignKey(Person, models.SET_NULL, null=True, related_name='edited') reviews = GenericRelation(Review) pages = models.IntegerField(default=100) objects = BookManager() class Meta: ordering = ('title',) def __str__(self): return self.title class Pet(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(Person, models.CASCADE) class Meta: ordering = ('name',) def __str__(self): return self.name class UserProfile(models.Model): user = models.OneToOneField(User, models.SET_NULL, null=True) flavor = models.CharField(max_length=100) class Meta: ordering = ('flavor',)
26.247059
89
0.698342
ace8a0193629a2b10a8a48173e7dbdbb6c9fffe3
82,724
py
Python
packages/fetchai/protocols/tac/tac_pb2.py
marcofavorito/agents-aea
e520f2f5d076a193514e194d94aa76c6423ac5bc
[ "Apache-2.0" ]
null
null
null
packages/fetchai/protocols/tac/tac_pb2.py
marcofavorito/agents-aea
e520f2f5d076a193514e194d94aa76c6423ac5bc
[ "Apache-2.0" ]
null
null
null
packages/fetchai/protocols/tac/tac_pb2.py
marcofavorito/agents-aea
e520f2f5d076a193514e194d94aa76c6423ac5bc
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: tac.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name="tac.proto", package="aea.fetchai.tac", syntax="proto3", serialized_options=None, serialized_pb=b'\n\ttac.proto\x12\x0f\x61\x65\x61.fetchai.tac"\xd0\x1e\n\nTacMessage\x12G\n\tcancelled\x18\x05 \x01(\x0b\x32\x32.aea.fetchai.tac.TacMessage.Cancelled_PerformativeH\x00\x12G\n\tgame_data\x18\x06 \x01(\x0b\x32\x32.aea.fetchai.tac.TacMessage.Game_Data_PerformativeH\x00\x12\x45\n\x08register\x18\x07 \x01(\x0b\x32\x31.aea.fetchai.tac.TacMessage.Register_PerformativeH\x00\x12G\n\ttac_error\x18\x08 \x01(\x0b\x32\x32.aea.fetchai.tac.TacMessage.Tac_Error_PerformativeH\x00\x12K\n\x0btransaction\x18\t \x01(\x0b\x32\x34.aea.fetchai.tac.TacMessage.Transaction_PerformativeH\x00\x12\x65\n\x18transaction_confirmation\x18\n \x01(\x0b\x32\x41.aea.fetchai.tac.TacMessage.Transaction_Confirmation_PerformativeH\x00\x12I\n\nunregister\x18\x0b \x01(\x0b\x32\x33.aea.fetchai.tac.TacMessage.Unregister_PerformativeH\x00\x1a\x82\x03\n\tErrorCode\x12G\n\nerror_code\x18\x01 \x01(\x0e\x32\x33.aea.fetchai.tac.TacMessage.ErrorCode.ErrorCodeEnum"\xab\x02\n\rErrorCodeEnum\x12\x11\n\rGENERIC_ERROR\x10\x00\x12\x15\n\x11REQUEST_NOT_VALID\x10\x01\x12!\n\x1d\x41GENT_ADDR_ALREADY_REGISTERED\x10\x02\x12!\n\x1d\x41GENT_NAME_ALREADY_REGISTERED\x10\x03\x12\x18\n\x14\x41GENT_NOT_REGISTERED\x10\x04\x12\x19\n\x15TRANSACTION_NOT_VALID\x10\x05\x12\x1c\n\x18TRANSACTION_NOT_MATCHING\x10\x06\x12\x1f\n\x1b\x41GENT_NAME_NOT_IN_WHITELIST\x10\x07\x12\x1b\n\x17\x43OMPETITION_NOT_RUNNING\x10\x08\x12\x19\n\x15\x44IALOGUE_INCONSISTENT\x10\t\x1a+\n\x15Register_Performative\x12\x12\n\nagent_name\x18\x01 \x01(\t\x1a\x19\n\x17Unregister_Performative\x1a\xb3\x05\n\x18Transaction_Performative\x12\x16\n\x0etransaction_id\x18\x01 \x01(\t\x12\x11\n\tledger_id\x18\x02 \x01(\t\x12\x16\n\x0esender_address\x18\x03 \x01(\t\x12\x1c\n\x14\x63ounterparty_address\x18\x04 \x01(\t\x12k\n\x15\x61mount_by_currency_id\x18\x05 \x03(\x0b\x32L.aea.fetchai.tac.TacMessage.Transaction_Performative.AmountByCurrencyIdEntry\x12\x65\n\x12\x66\x65\x65_by_currency_id\x18\x06 \x03(\x0b\x32I.aea.fetchai.tac.TacMessage.Transaction_Performative.FeeByCurrencyIdEntry\x12k\n\x15quantities_by_good_id\x18\x07 \x03(\x0b\x32L.aea.fetchai.tac.TacMessage.Transaction_Performative.QuantitiesByGoodIdEntry\x12\r\n\x05nonce\x18\x08 \x01(\t\x12\x18\n\x10sender_signature\x18\t \x01(\t\x12\x1e\n\x16\x63ounterparty_signature\x18\n \x01(\t\x1a\x39\n\x17\x41mountByCurrencyIdEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x36\n\x14\x46\x65\x65\x42yCurrencyIdEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x39\n\x17QuantitiesByGoodIdEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x18\n\x16\x43\x61ncelled_Performative\x1a\xe3\x0b\n\x16Game_Data_Performative\x12i\n\x15\x61mount_by_currency_id\x18\x01 \x03(\x0b\x32J.aea.fetchai.tac.TacMessage.Game_Data_Performative.AmountByCurrencyIdEntry\x12z\n\x1e\x65xchange_params_by_currency_id\x18\x02 \x03(\x0b\x32R.aea.fetchai.tac.TacMessage.Game_Data_Performative.ExchangeParamsByCurrencyIdEntry\x12i\n\x15quantities_by_good_id\x18\x03 \x03(\x0b\x32J.aea.fetchai.tac.TacMessage.Game_Data_Performative.QuantitiesByGoodIdEntry\x12p\n\x19utility_params_by_good_id\x18\x04 \x03(\x0b\x32M.aea.fetchai.tac.TacMessage.Game_Data_Performative.UtilityParamsByGoodIdEntry\x12\x63\n\x12\x66\x65\x65_by_currency_id\x18\x05 \x03(\x0b\x32G.aea.fetchai.tac.TacMessage.Game_Data_Performative.FeeByCurrencyIdEntry\x12\x63\n\x12\x61gent_addr_to_name\x18\x06 \x03(\x0b\x32G.aea.fetchai.tac.TacMessage.Game_Data_Performative.AgentAddrToNameEntry\x12\x65\n\x13\x63urrency_id_to_name\x18\x07 \x03(\x0b\x32H.aea.fetchai.tac.TacMessage.Game_Data_Performative.CurrencyIdToNameEntry\x12]\n\x0fgood_id_to_name\x18\x08 \x03(\x0b\x32\x44.aea.fetchai.tac.TacMessage.Game_Data_Performative.GoodIdToNameEntry\x12\x12\n\nversion_id\x18\t \x01(\t\x12J\n\x04info\x18\n \x03(\x0b\x32<.aea.fetchai.tac.TacMessage.Game_Data_Performative.InfoEntry\x12\x13\n\x0binfo_is_set\x18\x0b \x01(\x08\x1a\x39\n\x17\x41mountByCurrencyIdEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x41\n\x1f\x45xchangeParamsByCurrencyIdEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x02:\x02\x38\x01\x1a\x39\n\x17QuantitiesByGoodIdEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a<\n\x1aUtilityParamsByGoodIdEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x02:\x02\x38\x01\x1a\x36\n\x14\x46\x65\x65\x42yCurrencyIdEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x36\n\x14\x41gentAddrToNameEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x37\n\x15\x43urrencyIdToNameEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x33\n\x11GoodIdToNameEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a+\n\tInfoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\xa9\x03\n%Transaction_Confirmation_Performative\x12\x16\n\x0etransaction_id\x18\x01 \x01(\t\x12x\n\x15\x61mount_by_currency_id\x18\x02 \x03(\x0b\x32Y.aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative.AmountByCurrencyIdEntry\x12x\n\x15quantities_by_good_id\x18\x03 \x03(\x0b\x32Y.aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative.QuantitiesByGoodIdEntry\x1a\x39\n\x17\x41mountByCurrencyIdEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x39\n\x17QuantitiesByGoodIdEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\xe1\x01\n\x16Tac_Error_Performative\x12\x39\n\nerror_code\x18\x01 \x01(\x0b\x32%.aea.fetchai.tac.TacMessage.ErrorCode\x12J\n\x04info\x18\x02 \x03(\x0b\x32<.aea.fetchai.tac.TacMessage.Tac_Error_Performative.InfoEntry\x12\x13\n\x0binfo_is_set\x18\x03 \x01(\x08\x1a+\n\tInfoEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x0e\n\x0cperformativeb\x06proto3', ) _TACMESSAGE_ERRORCODE_ERRORCODEENUM = _descriptor.EnumDescriptor( name="ErrorCodeEnum", full_name="aea.fetchai.tac.TacMessage.ErrorCode.ErrorCodeEnum", filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name="GENERIC_ERROR", index=0, number=0, serialized_options=None, type=None ), _descriptor.EnumValueDescriptor( name="REQUEST_NOT_VALID", index=1, number=1, serialized_options=None, type=None, ), _descriptor.EnumValueDescriptor( name="AGENT_ADDR_ALREADY_REGISTERED", index=2, number=2, serialized_options=None, type=None, ), _descriptor.EnumValueDescriptor( name="AGENT_NAME_ALREADY_REGISTERED", index=3, number=3, serialized_options=None, type=None, ), _descriptor.EnumValueDescriptor( name="AGENT_NOT_REGISTERED", index=4, number=4, serialized_options=None, type=None, ), _descriptor.EnumValueDescriptor( name="TRANSACTION_NOT_VALID", index=5, number=5, serialized_options=None, type=None, ), _descriptor.EnumValueDescriptor( name="TRANSACTION_NOT_MATCHING", index=6, number=6, serialized_options=None, type=None, ), _descriptor.EnumValueDescriptor( name="AGENT_NAME_NOT_IN_WHITELIST", index=7, number=7, serialized_options=None, type=None, ), _descriptor.EnumValueDescriptor( name="COMPETITION_NOT_RUNNING", index=8, number=8, serialized_options=None, type=None, ), _descriptor.EnumValueDescriptor( name="DIALOGUE_INCONSISTENT", index=9, number=9, serialized_options=None, type=None, ), ], containing_type=None, serialized_options=None, serialized_start=678, serialized_end=977, ) _sym_db.RegisterEnumDescriptor(_TACMESSAGE_ERRORCODE_ERRORCODEENUM) _TACMESSAGE_ERRORCODE = _descriptor.Descriptor( name="ErrorCode", full_name="aea.fetchai.tac.TacMessage.ErrorCode", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="error_code", full_name="aea.fetchai.tac.TacMessage.ErrorCode.error_code", index=0, number=1, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[_TACMESSAGE_ERRORCODE_ERRORCODEENUM,], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=591, serialized_end=977, ) _TACMESSAGE_REGISTER_PERFORMATIVE = _descriptor.Descriptor( name="Register_Performative", full_name="aea.fetchai.tac.TacMessage.Register_Performative", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="agent_name", full_name="aea.fetchai.tac.TacMessage.Register_Performative.agent_name", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=979, serialized_end=1022, ) _TACMESSAGE_UNREGISTER_PERFORMATIVE = _descriptor.Descriptor( name="Unregister_Performative", full_name="aea.fetchai.tac.TacMessage.Unregister_Performative", filename=None, file=DESCRIPTOR, containing_type=None, fields=[], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1024, serialized_end=1049, ) _TACMESSAGE_TRANSACTION_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY = _descriptor.Descriptor( name="AmountByCurrencyIdEntry", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.AmountByCurrencyIdEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.AmountByCurrencyIdEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.AmountByCurrencyIdEntry.value", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1571, serialized_end=1628, ) _TACMESSAGE_TRANSACTION_PERFORMATIVE_FEEBYCURRENCYIDENTRY = _descriptor.Descriptor( name="FeeByCurrencyIdEntry", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.FeeByCurrencyIdEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.FeeByCurrencyIdEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.FeeByCurrencyIdEntry.value", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1630, serialized_end=1684, ) _TACMESSAGE_TRANSACTION_PERFORMATIVE_QUANTITIESBYGOODIDENTRY = _descriptor.Descriptor( name="QuantitiesByGoodIdEntry", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.QuantitiesByGoodIdEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.QuantitiesByGoodIdEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.QuantitiesByGoodIdEntry.value", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1686, serialized_end=1743, ) _TACMESSAGE_TRANSACTION_PERFORMATIVE = _descriptor.Descriptor( name="Transaction_Performative", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="transaction_id", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.transaction_id", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="ledger_id", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.ledger_id", index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="sender_address", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.sender_address", index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="counterparty_address", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.counterparty_address", index=3, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="amount_by_currency_id", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.amount_by_currency_id", index=4, number=5, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="fee_by_currency_id", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.fee_by_currency_id", index=5, number=6, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="quantities_by_good_id", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.quantities_by_good_id", index=6, number=7, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="nonce", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.nonce", index=7, number=8, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="sender_signature", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.sender_signature", index=8, number=9, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="counterparty_signature", full_name="aea.fetchai.tac.TacMessage.Transaction_Performative.counterparty_signature", index=9, number=10, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[ _TACMESSAGE_TRANSACTION_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY, _TACMESSAGE_TRANSACTION_PERFORMATIVE_FEEBYCURRENCYIDENTRY, _TACMESSAGE_TRANSACTION_PERFORMATIVE_QUANTITIESBYGOODIDENTRY, ], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1052, serialized_end=1743, ) _TACMESSAGE_CANCELLED_PERFORMATIVE = _descriptor.Descriptor( name="Cancelled_Performative", full_name="aea.fetchai.tac.TacMessage.Cancelled_Performative", filename=None, file=DESCRIPTOR, containing_type=None, fields=[], extensions=[], nested_types=[], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1745, serialized_end=1769, ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY = _descriptor.Descriptor( name="AmountByCurrencyIdEntry", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.AmountByCurrencyIdEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.AmountByCurrencyIdEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.AmountByCurrencyIdEntry.value", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1571, serialized_end=1628, ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_EXCHANGEPARAMSBYCURRENCYIDENTRY = _descriptor.Descriptor( name="ExchangeParamsByCurrencyIdEntry", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.ExchangeParamsByCurrencyIdEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.ExchangeParamsByCurrencyIdEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.ExchangeParamsByCurrencyIdEntry.value", index=1, number=2, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2826, serialized_end=2891, ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_QUANTITIESBYGOODIDENTRY = _descriptor.Descriptor( name="QuantitiesByGoodIdEntry", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.QuantitiesByGoodIdEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.QuantitiesByGoodIdEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.QuantitiesByGoodIdEntry.value", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1686, serialized_end=1743, ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_UTILITYPARAMSBYGOODIDENTRY = _descriptor.Descriptor( name="UtilityParamsByGoodIdEntry", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.UtilityParamsByGoodIdEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.UtilityParamsByGoodIdEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.UtilityParamsByGoodIdEntry.value", index=1, number=2, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=2952, serialized_end=3012, ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_FEEBYCURRENCYIDENTRY = _descriptor.Descriptor( name="FeeByCurrencyIdEntry", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.FeeByCurrencyIdEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.FeeByCurrencyIdEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.FeeByCurrencyIdEntry.value", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1630, serialized_end=1684, ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_AGENTADDRTONAMEENTRY = _descriptor.Descriptor( name="AgentAddrToNameEntry", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.AgentAddrToNameEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.AgentAddrToNameEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.AgentAddrToNameEntry.value", index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3070, serialized_end=3124, ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_CURRENCYIDTONAMEENTRY = _descriptor.Descriptor( name="CurrencyIdToNameEntry", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.CurrencyIdToNameEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.CurrencyIdToNameEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.CurrencyIdToNameEntry.value", index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3126, serialized_end=3181, ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_GOODIDTONAMEENTRY = _descriptor.Descriptor( name="GoodIdToNameEntry", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.GoodIdToNameEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.GoodIdToNameEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.GoodIdToNameEntry.value", index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3183, serialized_end=3234, ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_INFOENTRY = _descriptor.Descriptor( name="InfoEntry", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.InfoEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.InfoEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.InfoEntry.value", index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3236, serialized_end=3279, ) _TACMESSAGE_GAME_DATA_PERFORMATIVE = _descriptor.Descriptor( name="Game_Data_Performative", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="amount_by_currency_id", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.amount_by_currency_id", index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="exchange_params_by_currency_id", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.exchange_params_by_currency_id", index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="quantities_by_good_id", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.quantities_by_good_id", index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="utility_params_by_good_id", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.utility_params_by_good_id", index=3, number=4, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="fee_by_currency_id", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.fee_by_currency_id", index=4, number=5, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="agent_addr_to_name", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.agent_addr_to_name", index=5, number=6, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="currency_id_to_name", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.currency_id_to_name", index=6, number=7, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="good_id_to_name", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.good_id_to_name", index=7, number=8, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="version_id", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.version_id", index=8, number=9, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="info", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.info", index=9, number=10, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="info_is_set", full_name="aea.fetchai.tac.TacMessage.Game_Data_Performative.info_is_set", index=10, number=11, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[ _TACMESSAGE_GAME_DATA_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY, _TACMESSAGE_GAME_DATA_PERFORMATIVE_EXCHANGEPARAMSBYCURRENCYIDENTRY, _TACMESSAGE_GAME_DATA_PERFORMATIVE_QUANTITIESBYGOODIDENTRY, _TACMESSAGE_GAME_DATA_PERFORMATIVE_UTILITYPARAMSBYGOODIDENTRY, _TACMESSAGE_GAME_DATA_PERFORMATIVE_FEEBYCURRENCYIDENTRY, _TACMESSAGE_GAME_DATA_PERFORMATIVE_AGENTADDRTONAMEENTRY, _TACMESSAGE_GAME_DATA_PERFORMATIVE_CURRENCYIDTONAMEENTRY, _TACMESSAGE_GAME_DATA_PERFORMATIVE_GOODIDTONAMEENTRY, _TACMESSAGE_GAME_DATA_PERFORMATIVE_INFOENTRY, ], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1772, serialized_end=3279, ) _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY = _descriptor.Descriptor( name="AmountByCurrencyIdEntry", full_name="aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative.AmountByCurrencyIdEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative.AmountByCurrencyIdEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative.AmountByCurrencyIdEntry.value", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1571, serialized_end=1628, ) _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE_QUANTITIESBYGOODIDENTRY = _descriptor.Descriptor( name="QuantitiesByGoodIdEntry", full_name="aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative.QuantitiesByGoodIdEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative.QuantitiesByGoodIdEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative.QuantitiesByGoodIdEntry.value", index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=1686, serialized_end=1743, ) _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE = _descriptor.Descriptor( name="Transaction_Confirmation_Performative", full_name="aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="transaction_id", full_name="aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative.transaction_id", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="amount_by_currency_id", full_name="aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative.amount_by_currency_id", index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="quantities_by_good_id", full_name="aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative.quantities_by_good_id", index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[ _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY, _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE_QUANTITIESBYGOODIDENTRY, ], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3282, serialized_end=3707, ) _TACMESSAGE_TAC_ERROR_PERFORMATIVE_INFOENTRY = _descriptor.Descriptor( name="InfoEntry", full_name="aea.fetchai.tac.TacMessage.Tac_Error_Performative.InfoEntry", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="key", full_name="aea.fetchai.tac.TacMessage.Tac_Error_Performative.InfoEntry.key", index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="value", full_name="aea.fetchai.tac.TacMessage.Tac_Error_Performative.InfoEntry.value", index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode("utf-8"), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[], enum_types=[], serialized_options=b"8\001", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3236, serialized_end=3279, ) _TACMESSAGE_TAC_ERROR_PERFORMATIVE = _descriptor.Descriptor( name="Tac_Error_Performative", full_name="aea.fetchai.tac.TacMessage.Tac_Error_Performative", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="error_code", full_name="aea.fetchai.tac.TacMessage.Tac_Error_Performative.error_code", index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="info", full_name="aea.fetchai.tac.TacMessage.Tac_Error_Performative.info", index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="info_is_set", full_name="aea.fetchai.tac.TacMessage.Tac_Error_Performative.info_is_set", index=2, number=3, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[_TACMESSAGE_TAC_ERROR_PERFORMATIVE_INFOENTRY,], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=3710, serialized_end=3935, ) _TACMESSAGE = _descriptor.Descriptor( name="TacMessage", full_name="aea.fetchai.tac.TacMessage", filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name="cancelled", full_name="aea.fetchai.tac.TacMessage.cancelled", index=0, number=5, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="game_data", full_name="aea.fetchai.tac.TacMessage.game_data", index=1, number=6, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="register", full_name="aea.fetchai.tac.TacMessage.register", index=2, number=7, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="tac_error", full_name="aea.fetchai.tac.TacMessage.tac_error", index=3, number=8, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="transaction", full_name="aea.fetchai.tac.TacMessage.transaction", index=4, number=9, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="transaction_confirmation", full_name="aea.fetchai.tac.TacMessage.transaction_confirmation", index=5, number=10, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), _descriptor.FieldDescriptor( name="unregister", full_name="aea.fetchai.tac.TacMessage.unregister", index=6, number=11, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, ), ], extensions=[], nested_types=[ _TACMESSAGE_ERRORCODE, _TACMESSAGE_REGISTER_PERFORMATIVE, _TACMESSAGE_UNREGISTER_PERFORMATIVE, _TACMESSAGE_TRANSACTION_PERFORMATIVE, _TACMESSAGE_CANCELLED_PERFORMATIVE, _TACMESSAGE_GAME_DATA_PERFORMATIVE, _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE, _TACMESSAGE_TAC_ERROR_PERFORMATIVE, ], enum_types=[], serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name="performative", full_name="aea.fetchai.tac.TacMessage.performative", index=0, containing_type=None, fields=[], ), ], serialized_start=31, serialized_end=3951, ) _TACMESSAGE_ERRORCODE.fields_by_name[ "error_code" ].enum_type = _TACMESSAGE_ERRORCODE_ERRORCODEENUM _TACMESSAGE_ERRORCODE.containing_type = _TACMESSAGE _TACMESSAGE_ERRORCODE_ERRORCODEENUM.containing_type = _TACMESSAGE_ERRORCODE _TACMESSAGE_REGISTER_PERFORMATIVE.containing_type = _TACMESSAGE _TACMESSAGE_UNREGISTER_PERFORMATIVE.containing_type = _TACMESSAGE _TACMESSAGE_TRANSACTION_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY.containing_type = ( _TACMESSAGE_TRANSACTION_PERFORMATIVE ) _TACMESSAGE_TRANSACTION_PERFORMATIVE_FEEBYCURRENCYIDENTRY.containing_type = ( _TACMESSAGE_TRANSACTION_PERFORMATIVE ) _TACMESSAGE_TRANSACTION_PERFORMATIVE_QUANTITIESBYGOODIDENTRY.containing_type = ( _TACMESSAGE_TRANSACTION_PERFORMATIVE ) _TACMESSAGE_TRANSACTION_PERFORMATIVE.fields_by_name[ "amount_by_currency_id" ].message_type = _TACMESSAGE_TRANSACTION_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY _TACMESSAGE_TRANSACTION_PERFORMATIVE.fields_by_name[ "fee_by_currency_id" ].message_type = _TACMESSAGE_TRANSACTION_PERFORMATIVE_FEEBYCURRENCYIDENTRY _TACMESSAGE_TRANSACTION_PERFORMATIVE.fields_by_name[ "quantities_by_good_id" ].message_type = _TACMESSAGE_TRANSACTION_PERFORMATIVE_QUANTITIESBYGOODIDENTRY _TACMESSAGE_TRANSACTION_PERFORMATIVE.containing_type = _TACMESSAGE _TACMESSAGE_CANCELLED_PERFORMATIVE.containing_type = _TACMESSAGE _TACMESSAGE_GAME_DATA_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY.containing_type = ( _TACMESSAGE_GAME_DATA_PERFORMATIVE ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_EXCHANGEPARAMSBYCURRENCYIDENTRY.containing_type = ( _TACMESSAGE_GAME_DATA_PERFORMATIVE ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_QUANTITIESBYGOODIDENTRY.containing_type = ( _TACMESSAGE_GAME_DATA_PERFORMATIVE ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_UTILITYPARAMSBYGOODIDENTRY.containing_type = ( _TACMESSAGE_GAME_DATA_PERFORMATIVE ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_FEEBYCURRENCYIDENTRY.containing_type = ( _TACMESSAGE_GAME_DATA_PERFORMATIVE ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_AGENTADDRTONAMEENTRY.containing_type = ( _TACMESSAGE_GAME_DATA_PERFORMATIVE ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_CURRENCYIDTONAMEENTRY.containing_type = ( _TACMESSAGE_GAME_DATA_PERFORMATIVE ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_GOODIDTONAMEENTRY.containing_type = ( _TACMESSAGE_GAME_DATA_PERFORMATIVE ) _TACMESSAGE_GAME_DATA_PERFORMATIVE_INFOENTRY.containing_type = ( _TACMESSAGE_GAME_DATA_PERFORMATIVE ) _TACMESSAGE_GAME_DATA_PERFORMATIVE.fields_by_name[ "amount_by_currency_id" ].message_type = _TACMESSAGE_GAME_DATA_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY _TACMESSAGE_GAME_DATA_PERFORMATIVE.fields_by_name[ "exchange_params_by_currency_id" ].message_type = _TACMESSAGE_GAME_DATA_PERFORMATIVE_EXCHANGEPARAMSBYCURRENCYIDENTRY _TACMESSAGE_GAME_DATA_PERFORMATIVE.fields_by_name[ "quantities_by_good_id" ].message_type = _TACMESSAGE_GAME_DATA_PERFORMATIVE_QUANTITIESBYGOODIDENTRY _TACMESSAGE_GAME_DATA_PERFORMATIVE.fields_by_name[ "utility_params_by_good_id" ].message_type = _TACMESSAGE_GAME_DATA_PERFORMATIVE_UTILITYPARAMSBYGOODIDENTRY _TACMESSAGE_GAME_DATA_PERFORMATIVE.fields_by_name[ "fee_by_currency_id" ].message_type = _TACMESSAGE_GAME_DATA_PERFORMATIVE_FEEBYCURRENCYIDENTRY _TACMESSAGE_GAME_DATA_PERFORMATIVE.fields_by_name[ "agent_addr_to_name" ].message_type = _TACMESSAGE_GAME_DATA_PERFORMATIVE_AGENTADDRTONAMEENTRY _TACMESSAGE_GAME_DATA_PERFORMATIVE.fields_by_name[ "currency_id_to_name" ].message_type = _TACMESSAGE_GAME_DATA_PERFORMATIVE_CURRENCYIDTONAMEENTRY _TACMESSAGE_GAME_DATA_PERFORMATIVE.fields_by_name[ "good_id_to_name" ].message_type = _TACMESSAGE_GAME_DATA_PERFORMATIVE_GOODIDTONAMEENTRY _TACMESSAGE_GAME_DATA_PERFORMATIVE.fields_by_name[ "info" ].message_type = _TACMESSAGE_GAME_DATA_PERFORMATIVE_INFOENTRY _TACMESSAGE_GAME_DATA_PERFORMATIVE.containing_type = _TACMESSAGE _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY.containing_type = ( _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE ) _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE_QUANTITIESBYGOODIDENTRY.containing_type = ( _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE ) _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE.fields_by_name[ "amount_by_currency_id" ].message_type = ( _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY ) _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE.fields_by_name[ "quantities_by_good_id" ].message_type = ( _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE_QUANTITIESBYGOODIDENTRY ) _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE.containing_type = _TACMESSAGE _TACMESSAGE_TAC_ERROR_PERFORMATIVE_INFOENTRY.containing_type = ( _TACMESSAGE_TAC_ERROR_PERFORMATIVE ) _TACMESSAGE_TAC_ERROR_PERFORMATIVE.fields_by_name[ "error_code" ].message_type = _TACMESSAGE_ERRORCODE _TACMESSAGE_TAC_ERROR_PERFORMATIVE.fields_by_name[ "info" ].message_type = _TACMESSAGE_TAC_ERROR_PERFORMATIVE_INFOENTRY _TACMESSAGE_TAC_ERROR_PERFORMATIVE.containing_type = _TACMESSAGE _TACMESSAGE.fields_by_name[ "cancelled" ].message_type = _TACMESSAGE_CANCELLED_PERFORMATIVE _TACMESSAGE.fields_by_name[ "game_data" ].message_type = _TACMESSAGE_GAME_DATA_PERFORMATIVE _TACMESSAGE.fields_by_name["register"].message_type = _TACMESSAGE_REGISTER_PERFORMATIVE _TACMESSAGE.fields_by_name[ "tac_error" ].message_type = _TACMESSAGE_TAC_ERROR_PERFORMATIVE _TACMESSAGE.fields_by_name[ "transaction" ].message_type = _TACMESSAGE_TRANSACTION_PERFORMATIVE _TACMESSAGE.fields_by_name[ "transaction_confirmation" ].message_type = _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE _TACMESSAGE.fields_by_name[ "unregister" ].message_type = _TACMESSAGE_UNREGISTER_PERFORMATIVE _TACMESSAGE.oneofs_by_name["performative"].fields.append( _TACMESSAGE.fields_by_name["cancelled"] ) _TACMESSAGE.fields_by_name["cancelled"].containing_oneof = _TACMESSAGE.oneofs_by_name[ "performative" ] _TACMESSAGE.oneofs_by_name["performative"].fields.append( _TACMESSAGE.fields_by_name["game_data"] ) _TACMESSAGE.fields_by_name["game_data"].containing_oneof = _TACMESSAGE.oneofs_by_name[ "performative" ] _TACMESSAGE.oneofs_by_name["performative"].fields.append( _TACMESSAGE.fields_by_name["register"] ) _TACMESSAGE.fields_by_name["register"].containing_oneof = _TACMESSAGE.oneofs_by_name[ "performative" ] _TACMESSAGE.oneofs_by_name["performative"].fields.append( _TACMESSAGE.fields_by_name["tac_error"] ) _TACMESSAGE.fields_by_name["tac_error"].containing_oneof = _TACMESSAGE.oneofs_by_name[ "performative" ] _TACMESSAGE.oneofs_by_name["performative"].fields.append( _TACMESSAGE.fields_by_name["transaction"] ) _TACMESSAGE.fields_by_name["transaction"].containing_oneof = _TACMESSAGE.oneofs_by_name[ "performative" ] _TACMESSAGE.oneofs_by_name["performative"].fields.append( _TACMESSAGE.fields_by_name["transaction_confirmation"] ) _TACMESSAGE.fields_by_name[ "transaction_confirmation" ].containing_oneof = _TACMESSAGE.oneofs_by_name["performative"] _TACMESSAGE.oneofs_by_name["performative"].fields.append( _TACMESSAGE.fields_by_name["unregister"] ) _TACMESSAGE.fields_by_name["unregister"].containing_oneof = _TACMESSAGE.oneofs_by_name[ "performative" ] DESCRIPTOR.message_types_by_name["TacMessage"] = _TACMESSAGE _sym_db.RegisterFileDescriptor(DESCRIPTOR) TacMessage = _reflection.GeneratedProtocolMessageType( "TacMessage", (_message.Message,), { "ErrorCode": _reflection.GeneratedProtocolMessageType( "ErrorCode", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_ERRORCODE, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.ErrorCode) }, ), "Register_Performative": _reflection.GeneratedProtocolMessageType( "Register_Performative", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_REGISTER_PERFORMATIVE, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Register_Performative) }, ), "Unregister_Performative": _reflection.GeneratedProtocolMessageType( "Unregister_Performative", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_UNREGISTER_PERFORMATIVE, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Unregister_Performative) }, ), "Transaction_Performative": _reflection.GeneratedProtocolMessageType( "Transaction_Performative", (_message.Message,), { "AmountByCurrencyIdEntry": _reflection.GeneratedProtocolMessageType( "AmountByCurrencyIdEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_TRANSACTION_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Transaction_Performative.AmountByCurrencyIdEntry) }, ), "FeeByCurrencyIdEntry": _reflection.GeneratedProtocolMessageType( "FeeByCurrencyIdEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_TRANSACTION_PERFORMATIVE_FEEBYCURRENCYIDENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Transaction_Performative.FeeByCurrencyIdEntry) }, ), "QuantitiesByGoodIdEntry": _reflection.GeneratedProtocolMessageType( "QuantitiesByGoodIdEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_TRANSACTION_PERFORMATIVE_QUANTITIESBYGOODIDENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Transaction_Performative.QuantitiesByGoodIdEntry) }, ), "DESCRIPTOR": _TACMESSAGE_TRANSACTION_PERFORMATIVE, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Transaction_Performative) }, ), "Cancelled_Performative": _reflection.GeneratedProtocolMessageType( "Cancelled_Performative", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_CANCELLED_PERFORMATIVE, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Cancelled_Performative) }, ), "Game_Data_Performative": _reflection.GeneratedProtocolMessageType( "Game_Data_Performative", (_message.Message,), { "AmountByCurrencyIdEntry": _reflection.GeneratedProtocolMessageType( "AmountByCurrencyIdEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_GAME_DATA_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Game_Data_Performative.AmountByCurrencyIdEntry) }, ), "ExchangeParamsByCurrencyIdEntry": _reflection.GeneratedProtocolMessageType( "ExchangeParamsByCurrencyIdEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_GAME_DATA_PERFORMATIVE_EXCHANGEPARAMSBYCURRENCYIDENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Game_Data_Performative.ExchangeParamsByCurrencyIdEntry) }, ), "QuantitiesByGoodIdEntry": _reflection.GeneratedProtocolMessageType( "QuantitiesByGoodIdEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_GAME_DATA_PERFORMATIVE_QUANTITIESBYGOODIDENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Game_Data_Performative.QuantitiesByGoodIdEntry) }, ), "UtilityParamsByGoodIdEntry": _reflection.GeneratedProtocolMessageType( "UtilityParamsByGoodIdEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_GAME_DATA_PERFORMATIVE_UTILITYPARAMSBYGOODIDENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Game_Data_Performative.UtilityParamsByGoodIdEntry) }, ), "FeeByCurrencyIdEntry": _reflection.GeneratedProtocolMessageType( "FeeByCurrencyIdEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_GAME_DATA_PERFORMATIVE_FEEBYCURRENCYIDENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Game_Data_Performative.FeeByCurrencyIdEntry) }, ), "AgentAddrToNameEntry": _reflection.GeneratedProtocolMessageType( "AgentAddrToNameEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_GAME_DATA_PERFORMATIVE_AGENTADDRTONAMEENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Game_Data_Performative.AgentAddrToNameEntry) }, ), "CurrencyIdToNameEntry": _reflection.GeneratedProtocolMessageType( "CurrencyIdToNameEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_GAME_DATA_PERFORMATIVE_CURRENCYIDTONAMEENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Game_Data_Performative.CurrencyIdToNameEntry) }, ), "GoodIdToNameEntry": _reflection.GeneratedProtocolMessageType( "GoodIdToNameEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_GAME_DATA_PERFORMATIVE_GOODIDTONAMEENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Game_Data_Performative.GoodIdToNameEntry) }, ), "InfoEntry": _reflection.GeneratedProtocolMessageType( "InfoEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_GAME_DATA_PERFORMATIVE_INFOENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Game_Data_Performative.InfoEntry) }, ), "DESCRIPTOR": _TACMESSAGE_GAME_DATA_PERFORMATIVE, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Game_Data_Performative) }, ), "Transaction_Confirmation_Performative": _reflection.GeneratedProtocolMessageType( "Transaction_Confirmation_Performative", (_message.Message,), { "AmountByCurrencyIdEntry": _reflection.GeneratedProtocolMessageType( "AmountByCurrencyIdEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative.AmountByCurrencyIdEntry) }, ), "QuantitiesByGoodIdEntry": _reflection.GeneratedProtocolMessageType( "QuantitiesByGoodIdEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE_QUANTITIESBYGOODIDENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative.QuantitiesByGoodIdEntry) }, ), "DESCRIPTOR": _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Transaction_Confirmation_Performative) }, ), "Tac_Error_Performative": _reflection.GeneratedProtocolMessageType( "Tac_Error_Performative", (_message.Message,), { "InfoEntry": _reflection.GeneratedProtocolMessageType( "InfoEntry", (_message.Message,), { "DESCRIPTOR": _TACMESSAGE_TAC_ERROR_PERFORMATIVE_INFOENTRY, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Tac_Error_Performative.InfoEntry) }, ), "DESCRIPTOR": _TACMESSAGE_TAC_ERROR_PERFORMATIVE, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage.Tac_Error_Performative) }, ), "DESCRIPTOR": _TACMESSAGE, "__module__": "tac_pb2" # @@protoc_insertion_point(class_scope:aea.fetchai.tac.TacMessage) }, ) _sym_db.RegisterMessage(TacMessage) _sym_db.RegisterMessage(TacMessage.ErrorCode) _sym_db.RegisterMessage(TacMessage.Register_Performative) _sym_db.RegisterMessage(TacMessage.Unregister_Performative) _sym_db.RegisterMessage(TacMessage.Transaction_Performative) _sym_db.RegisterMessage(TacMessage.Transaction_Performative.AmountByCurrencyIdEntry) _sym_db.RegisterMessage(TacMessage.Transaction_Performative.FeeByCurrencyIdEntry) _sym_db.RegisterMessage(TacMessage.Transaction_Performative.QuantitiesByGoodIdEntry) _sym_db.RegisterMessage(TacMessage.Cancelled_Performative) _sym_db.RegisterMessage(TacMessage.Game_Data_Performative) _sym_db.RegisterMessage(TacMessage.Game_Data_Performative.AmountByCurrencyIdEntry) _sym_db.RegisterMessage( TacMessage.Game_Data_Performative.ExchangeParamsByCurrencyIdEntry ) _sym_db.RegisterMessage(TacMessage.Game_Data_Performative.QuantitiesByGoodIdEntry) _sym_db.RegisterMessage(TacMessage.Game_Data_Performative.UtilityParamsByGoodIdEntry) _sym_db.RegisterMessage(TacMessage.Game_Data_Performative.FeeByCurrencyIdEntry) _sym_db.RegisterMessage(TacMessage.Game_Data_Performative.AgentAddrToNameEntry) _sym_db.RegisterMessage(TacMessage.Game_Data_Performative.CurrencyIdToNameEntry) _sym_db.RegisterMessage(TacMessage.Game_Data_Performative.GoodIdToNameEntry) _sym_db.RegisterMessage(TacMessage.Game_Data_Performative.InfoEntry) _sym_db.RegisterMessage(TacMessage.Transaction_Confirmation_Performative) _sym_db.RegisterMessage( TacMessage.Transaction_Confirmation_Performative.AmountByCurrencyIdEntry ) _sym_db.RegisterMessage( TacMessage.Transaction_Confirmation_Performative.QuantitiesByGoodIdEntry ) _sym_db.RegisterMessage(TacMessage.Tac_Error_Performative) _sym_db.RegisterMessage(TacMessage.Tac_Error_Performative.InfoEntry) _TACMESSAGE_TRANSACTION_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY._options = None _TACMESSAGE_TRANSACTION_PERFORMATIVE_FEEBYCURRENCYIDENTRY._options = None _TACMESSAGE_TRANSACTION_PERFORMATIVE_QUANTITIESBYGOODIDENTRY._options = None _TACMESSAGE_GAME_DATA_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY._options = None _TACMESSAGE_GAME_DATA_PERFORMATIVE_EXCHANGEPARAMSBYCURRENCYIDENTRY._options = None _TACMESSAGE_GAME_DATA_PERFORMATIVE_QUANTITIESBYGOODIDENTRY._options = None _TACMESSAGE_GAME_DATA_PERFORMATIVE_UTILITYPARAMSBYGOODIDENTRY._options = None _TACMESSAGE_GAME_DATA_PERFORMATIVE_FEEBYCURRENCYIDENTRY._options = None _TACMESSAGE_GAME_DATA_PERFORMATIVE_AGENTADDRTONAMEENTRY._options = None _TACMESSAGE_GAME_DATA_PERFORMATIVE_CURRENCYIDTONAMEENTRY._options = None _TACMESSAGE_GAME_DATA_PERFORMATIVE_GOODIDTONAMEENTRY._options = None _TACMESSAGE_GAME_DATA_PERFORMATIVE_INFOENTRY._options = None _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE_AMOUNTBYCURRENCYIDENTRY._options = ( None ) _TACMESSAGE_TRANSACTION_CONFIRMATION_PERFORMATIVE_QUANTITIESBYGOODIDENTRY._options = ( None ) _TACMESSAGE_TAC_ERROR_PERFORMATIVE_INFOENTRY._options = None # @@protoc_insertion_point(module_scope)
36.831701
6,043
0.631159
ace8a02a07baa1d3676ee33620ccb26e1bf748c5
5,705
py
Python
src/predict.py
jamesmcclain/algae-model
45e3e83544034022aba16ad1ed254f1445e4bb1b
[ "MIT" ]
null
null
null
src/predict.py
jamesmcclain/algae-model
45e3e83544034022aba16ad1ed254f1445e4bb1b
[ "MIT" ]
null
null
null
src/predict.py
jamesmcclain/algae-model
45e3e83544034022aba16ad1ed254f1445e4bb1b
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import argparse import copy import logging import sys import warnings import numpy as np import rasterio as rio import torch import torch.hub import tqdm from rasterio.windows import Window BACKBONES = [ 'vgg16', 'densenet161', 'shufflenet_v2_x1_0', 'mobilenet_v2', 'mobilenet_v3_large', 'mobilenet_v3_small', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152', 'efficientnet_b0', 'efficientnet_b1', 'efficientnet_b2', 'efficientnet_b3', 'efficientnet_b4', 'efficientnet_b5', 'efficientnet_b6', 'efficientnet_b7', 'fpn_resnet18', 'fpn_resnet34', 'fpn_resnet50' ] def cli_parser(): parser = argparse.ArgumentParser() parser.add_argument('--backbone', required=True, type=str, choices=BACKBONES) parser.add_argument('--chunksize', required=False, type=int, default=256) parser.add_argument('--device', required=False, type=str, default='cuda', choices=['cuda', 'cpu']) parser.add_argument('--infile', required=True, type=str, nargs='+') parser.add_argument('--outfile', required=False, default=None, type=str, nargs='+') parser.add_argument('--prescale', required=False, type=int, default=1) parser.add_argument('--pth-load', required=True, type=str) parser.add_argument('--stride', required=False, type=int, default=13) parser.add_argument('--window-size', required=False, type=int, default=32) parser.add_argument('--ndwi-mask', required=False, dest='ndwi_mask', action='store_true') parser.set_defaults(ndwi_mask=False) return parser if __name__ == '__main__': warnings.filterwarnings('ignore') args = cli_parser().parse_args() logging.basicConfig(stream=sys.stderr, level=logging.INFO, format='%(asctime)-15s %(message)s') log = logging.getLogger() n = args.window_size device = torch.device(args.device) model = torch.hub.load('jamesmcclain/algae-classifier:730726f5bccc679fa334da91fe4dc4cb71a35208', 'make_algae_model', in_channels=[4, 12, 224], prescale=args.prescale, backbone_str=args.backbone, pretrained=False) model.load_state_dict(torch.load(args.pth_load)) model.to(device) model.eval() if args.outfile is None: model_name = args.pth_load.split('/')[-1].split('.')[0] def transmute(filename): filename = filename.split('/')[-1] filename = f"./predict-{model_name}-{filename}" if not filename.endswith('.tiff'): filename = filename.replace('.tif', '.tiff') return filename args.outfile = [transmute(f) for f in args.infile] for (infile, outfile) in zip(args.infile, args.outfile): log.info(outfile) with rio.open(infile, 'r') as infile_ds, torch.no_grad(): out_raw_profile = copy.deepcopy(infile_ds.profile) out_raw_profile.update({ 'compress': 'lzw', 'dtype': np.float32, 'count': 1, 'bigtiff': 'yes', 'sparse_ok': 'yes', 'tiled': 'yes', }) width = infile_ds.width height = infile_ds.height bandcount = infile_ds.count ar_out = torch.zeros((1, height, width), dtype=torch.float32).to(device) pixel_hits = torch.zeros((1, height, width), dtype=torch.uint8).to(device) if bandcount == 224: indexes = list(range(1, 224 + 1)) elif bandcount in {12, 13}: indexes = list(range(1, 12 + 1)) # NOTE: 13 bands does not indicate L1C support, this is # for Franklin COGs that have an extra band. bandcount = 12 elif bandcount == 4: indexes = list(range(1, 4 + 1)) elif bandcount == 5: indexes = [1, 2, 3, 5] bandcount = 4 else: raise Exception(f'bands={bandcount}') # gather up batches batches = [] for i in range(0, width - n, args.stride): for j in range(0, height - n, args.stride): batches.append((i, j)) batches = [batches[i:i + args.chunksize] for i in range(0, len(batches), args.chunksize)] for batch in tqdm.tqdm(batches): windows = [infile_ds.read(indexes, window=Window(i, j, n, n)) for (i, j) in batch] windows = [w.astype(np.float32) for w in windows] if args.ndwi_mask: windows = [w * (((w[2] - w[7]) / (w[2] + w[7])) > 0.0) for w in windows] try: windows = np.stack(windows, axis=0) except: continue windows = torch.from_numpy(windows).to(dtype=torch.float32, device=device) prob = model(windows) for k, (i, j) in enumerate(batch): if 'seg' in prob: _prob = torch.sigmoid(prob.get('seg')[k, 1]) - torch.sigmoid(prob.get('seg')[k, 0]) ar_out[0, j:(j + n), i:(i + n)] += _prob else: ar_out[0, j:(j + n), i:(i + n)] += torch.sigmoid(prob.get('class')[k, 0]) pixel_hits[0, j:(j + n), i:(i + n)] += 1 # Bring results back to CPU ar_out /= pixel_hits ar_out = ar_out.cpu().numpy() # Write results to file with rio.open(outfile, 'w', **out_raw_profile) as outfile_raw_ds: outfile_raw_ds.write(ar_out[0], indexes=1)
39.895105
107
0.564242
ace8a04c3c7955ec6c2a8dda0c05038d3e0ee7fe
457
py
Python
flaskblog/posts/forms.py
larklarky/flask_blog
deacc75b40e1e48b4dfadbfd764e91cf57811a76
[ "MIT" ]
null
null
null
flaskblog/posts/forms.py
larklarky/flask_blog
deacc75b40e1e48b4dfadbfd764e91cf57811a76
[ "MIT" ]
null
null
null
flaskblog/posts/forms.py
larklarky/flask_blog
deacc75b40e1e48b4dfadbfd764e91cf57811a76
[ "MIT" ]
null
null
null
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, TextAreaField from wtforms.validators import DataRequired from flask_wtf.file import FileField, FileAllowed class PostForm(FlaskForm): title = StringField('Title', validators=[DataRequired()]) content = TextAreaField('Content', validators=[DataRequired()]) image = FileField('Add Picture', validators=[FileAllowed(['jpg', 'png'])]) submit = SubmitField('Post')
38.083333
78
0.761488
ace8a050bf8449fe29bdf79d39cced8584ca7afa
2,433
py
Python
log_casp_act/run_model_487.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
log_casp_act/run_model_487.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
log_casp_act/run_model_487.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
import numpy as np from math import * import pymultinest import sys sys.path.insert(0, '/home/kochenma/pysb') from pysb.integrate import Solver import csv import datetime import time as tm from model_487 import model from pysb.pathfinder import set_path set_path('bng', '/home/kochenma/BioNetGen') data_object = [] with open('earm_data.csv') as data_file: reader = csv.reader(data_file) line = list(reader) for each in line: data_object.append(each) for i, each in enumerate(data_object): if i > 0: for j, item in enumerate(each): data_object[i][j] = float(data_object[i][j]) data_object = data_object[1:] time = [] for each in data_object: time.append(float(each[0])) model_solver = Solver(model, time, integrator='vode', integrator_options={'atol': 1e-12, 'rtol': 1e-12}) def prior(cube, ndim, nparams): for k, every in enumerate(model.parameters): if every.name[-3:] == '1kf': cube[k] = cube[k]*4 - 4 if every.name[-3:] == '2kf': cube[k] = cube[k]*4 - 8 if every.name[-3:] == '1kr': cube[k] = cube[k]*4 - 4 if every.name[-3:] == '1kc': cube[k] = cube[k]*4 - 1 postfixes = ['1kf', '2kf', '1kr', '1kc'] def loglike(cube, ndim, nparams): point = [] cube_index = 0 for k, every in enumerate(model.parameters): if every.name[-3:] in postfixes: point.append(10**cube[cube_index]) cube_index += 1 else: point.append(model.parameters[k].value) model_solver.run(point) failed = False for every in model_solver.yobs: for thing in every: if thing <= -0.00000001 or np.isnan(thing): failed = True if failed: return ['fail', -10000.0] else: parpc = model_solver.yobs[-1][6]/(model_solver.yobs[-1][1] + model_solver.yobs[-1][6]) if (parpc > 0.0) and (parpc < 1.00000001): print log(parpc), point return ['sim', log(parpc)] else: return ['fail', -10000.0] n_params = 0 for m, lotsa in enumerate(model.parameters): if lotsa.name[-3:] == '1kf': n_params += 1 if lotsa.name[-3:] == '2kf': n_params += 1 if lotsa.name[-3:] == '1kr': n_params += 1 if lotsa.name[-3:] == '1kc': n_params += 1 start_time = tm.clock() counts = [0, 0] pymultinest.run(loglike, prior, n_params, evidence_tolerance=0.0001, n_live_points=16000, log_zero=-1e3, sampling_efficiency=0.3, outputfiles_basename='/scratch/kochenma/log_casp_act/487/', resume = False, verbose = False, counts=counts) print counts print 'start time', start_time print 'end time', tm.clock()
25.610526
237
0.671599
ace8a07db5fd330299b8047ccef114133320144a
454
py
Python
venv/Scripts/pyi-set_version-script.py
johnarn/price_observer_bot
3e2fa54dd2217e43eef862b13c28e4afbe13ebff
[ "MIT" ]
null
null
null
venv/Scripts/pyi-set_version-script.py
johnarn/price_observer_bot
3e2fa54dd2217e43eef862b13c28e4afbe13ebff
[ "MIT" ]
null
null
null
venv/Scripts/pyi-set_version-script.py
johnarn/price_observer_bot
3e2fa54dd2217e43eef862b13c28e4afbe13ebff
[ "MIT" ]
null
null
null
#!C:\Users\johna\PycharmProjects\PriceTester\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'PyInstaller==3.5','console_scripts','pyi-set_version' __requires__ = 'PyInstaller==3.5' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('PyInstaller==3.5', 'console_scripts', 'pyi-set_version')() )
34.923077
84
0.702643
ace8a0e56ccc4d3216aa4bba9292357eeb72c362
2,705
py
Python
run.py
shishilili/LARS2Report
f4c9dd0848608e902c1e588d3da93485c5247f24
[ "MIT" ]
null
null
null
run.py
shishilili/LARS2Report
f4c9dd0848608e902c1e588d3da93485c5247f24
[ "MIT" ]
null
null
null
run.py
shishilili/LARS2Report
f4c9dd0848608e902c1e588d3da93485c5247f24
[ "MIT" ]
null
null
null
''' Change value of Output_Case accordingly by examples below Case 1 Value more than 100 needs to be reported as 99.9 95.4 needs to be reported as 95.0 95.5 needs to be reported as 95.5 95.9 needs to be reported as 95.5 Case 2 Value more than 100 needs to be reported as 99.9 95.4 needs to be reported as 95.0 95.5 needs to be reported as 95.0 95.9 needs to be reported as 95.0 ''' Output_Case = 1 import os import win32com.client #Read the path of LIS and .docx files from CURRENT folder. def FindPath() legal_path = os.path.join(os.getcwd(),"legal.LIS") permit_path = os.path.join(os.getcwd(),"permit.LIS") for item in os.listdir('.'): if item.find(".docx") != -1: summary_path = os.path.join(os.getcwd(),item) legal_file = open(legal_path, 'r') legal_list = [] for line in legal_file: legal_list.append(line) legal_values = [] for i in [0, 1, 2, 3, 4]: legal_values.append(float(legal_list[16+2*i][62:67])) legal_values.append(float(legal_list[16+2*(5+i)][62:67])) legal_values.append(legal_list[16+2*i][35]) legal_file.close() permit_file = open(permit_path, 'r') permit_list = [] for line in permit_file: permit_list.append(line) permit_values = [] for i in [0, 1, 2, 3, 4, 5, 6, 7]: permit_values.append(float(permit_list[16+2*i][62:67])) permit_values.append(float(permit_list[16+2*(8+i)][62:67])) permit_values.append(permit_list[16+2*i][35]) permit_file.close() #Function to process both the controlling stress and the load capactiy in ton. def rounddown(x): if x == 'M': return 'Moment' elif x == 'V': return 'Shear' elif x == 'S': return 'Serviceability' elif float(x)-int(x) >= 0.5: return float(int(x)+0.5) else: return str(int(x)) + '.0' # Start the transfer of values to Word Document with # win32com.client w = win32com.client.Dispatch('Word.Application') w.Visible = 0 w.DisplayAlerts = 0 doc = w.Documents.Open(FileName = summary_path) table_legal = doc.Tables(2) table_permit = doc.Tables(3) for i in xrange(5): table_legal.Cell(4+2*i,3).Range.Text = rounddown(legal_values[3*i]) for i in xrange(5): table_legal.Cell(4+2*i,4).Range.Text = rounddown(legal_values[1+3*i]) for i in xrange(5): table_legal.Cell(5+2*i,2).Range.Text = rounddown(legal_values[2+3*i]) for i in xrange(8): table_permit.Cell(4+2*i,3).Range.Text = rounddown(permit_values[3*i]) for i in xrange(8): table_permit.Cell(4+2*i,4).Range.Text = rounddown(permit_values[1+3*i]) for i in xrange(8): table_permit.Cell(5+2*i,2).Range.Text = rounddown(permit_values[2+3*i]) w.ActiveDocument.Close(SaveChanges=True) w.Quit()
25.761905
78
0.671349
ace8a17717ab0fe1042ba4f27f8f480b110837a7
5,612
py
Python
kubernetes/client/models/v1_scoped_resource_selector_requirement.py
Prahladk09/python-1
2dfb3035535e4be52ba549f1ff47acbe573b73f6
[ "Apache-2.0" ]
11
2020-10-13T05:27:59.000Z
2021-09-23T02:56:32.000Z
kubernetes/client/models/v1_scoped_resource_selector_requirement.py
Prahladk09/python-1
2dfb3035535e4be52ba549f1ff47acbe573b73f6
[ "Apache-2.0" ]
48
2020-10-15T09:53:36.000Z
2021-07-05T15:33:24.000Z
kubernetes/client/models/v1_scoped_resource_selector_requirement.py
Prahladk09/python-1
2dfb3035535e4be52ba549f1ff47acbe573b73f6
[ "Apache-2.0" ]
4
2020-12-04T08:51:35.000Z
2022-03-27T09:42:20.000Z
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.14.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class V1ScopedResourceSelectorRequirement(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_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. """ swagger_types = { 'operator': 'str', 'scope_name': 'str', 'values': 'list[str]' } attribute_map = { 'operator': 'operator', 'scope_name': 'scopeName', 'values': 'values' } def __init__(self, operator=None, scope_name=None, values=None): """ V1ScopedResourceSelectorRequirement - a model defined in Swagger """ self._operator = None self._scope_name = None self._values = None self.discriminator = None self.operator = operator self.scope_name = scope_name if values is not None: self.values = values @property def operator(self): """ Gets the operator of this V1ScopedResourceSelectorRequirement. Represents a scope's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. :return: The operator of this V1ScopedResourceSelectorRequirement. :rtype: str """ return self._operator @operator.setter def operator(self, operator): """ Sets the operator of this V1ScopedResourceSelectorRequirement. Represents a scope's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. :param operator: The operator of this V1ScopedResourceSelectorRequirement. :type: str """ if operator is None: raise ValueError("Invalid value for `operator`, must not be `None`") self._operator = operator @property def scope_name(self): """ Gets the scope_name of this V1ScopedResourceSelectorRequirement. The name of the scope that the selector applies to. :return: The scope_name of this V1ScopedResourceSelectorRequirement. :rtype: str """ return self._scope_name @scope_name.setter def scope_name(self, scope_name): """ Sets the scope_name of this V1ScopedResourceSelectorRequirement. The name of the scope that the selector applies to. :param scope_name: The scope_name of this V1ScopedResourceSelectorRequirement. :type: str """ if scope_name is None: raise ValueError("Invalid value for `scope_name`, must not be `None`") self._scope_name = scope_name @property def values(self): """ Gets the values of this V1ScopedResourceSelectorRequirement. An array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch. :return: The values of this V1ScopedResourceSelectorRequirement. :rtype: list[str] """ return self._values @values.setter def values(self, values): """ Sets the values of this V1ScopedResourceSelectorRequirement. An array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch. :param values: The values of this V1ScopedResourceSelectorRequirement. :type: list[str] """ self._values = values def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_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 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, V1ScopedResourceSelectorRequirement): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
30.335135
232
0.604241
ace8a18643e04aeb9654b04a9e9fc38a23107960
789
py
Python
tests/pyre.pkg/calc/expression_typeerror.py
rtburns-jpl/pyre
ffc4fc1b2936e355f709d084eb4055954960b3a2
[ "BSD-3-Clause" ]
null
null
null
tests/pyre.pkg/calc/expression_typeerror.py
rtburns-jpl/pyre
ffc4fc1b2936e355f709d084eb4055954960b3a2
[ "BSD-3-Clause" ]
1
2021-06-10T23:42:13.000Z
2021-06-10T23:42:13.000Z
tests/pyre.pkg/calc/expression_typeerror.py
jlmaurer/pyre
6af38a83621d7d6228d147b4bb94f97fbb10f6e2
[ "BSD-3-Clause" ]
2
2020-08-31T18:07:52.000Z
2021-12-10T08:54:39.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2020 all rights reserved # """ Verify that model initialization fails correctly in the presence of expressions that cannot be evaluated even though they have no syntax errors """ def test(): import pyre.calc # a model model = pyre.calc.model() # the nodes model["production"] = 80. model["shipping"] = 20. model["cost"] = model.expression("{production}&{shipping}") try: model["cost"] assert False except model.EvaluationError as error: pass return # main if __name__ == "__main__": # skip pyre initialization since we don't rely on the executive pyre_noboot = True # run the test test() # end of file
17.931818
94
0.638783
ace8a1a5de8c130d7202afcf3d26f9dd979ac0c9
16,078
py
Python
log_mito/model_51.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
log_mito/model_51.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
log_mito/model_51.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
# exported from PySB model 'model' from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD Model() Monomer('Ligand', ['Receptor']) Monomer('ParpU', ['C3A']) Monomer('C8A', ['BidU']) Monomer('SmacM', ['BaxA']) Monomer('BaxM', ['BidM', 'BaxA']) Monomer('Apop', ['C3pro', 'Xiap']) Monomer('Fadd', ['Receptor', 'C8pro']) Monomer('SmacC', ['Xiap']) Monomer('ParpC') Monomer('Xiap', ['SmacC', 'Apop', 'C3A']) Monomer('C9') Monomer('C3ub') Monomer('C8pro', ['Fadd']) Monomer('C3pro', ['Apop']) Monomer('CytoCM', ['BaxA']) Monomer('CytoCC') Monomer('BaxA', ['BaxM', 'BaxA_1', 'BaxA_2', 'SmacM', 'CytoCM']) Monomer('ApafI') Monomer('BidU', ['C8A']) Monomer('BidT') Monomer('C3A', ['Xiap', 'ParpU']) Monomer('ApafA') Monomer('BidM', ['BaxM']) Monomer('Receptor', ['Ligand', 'Fadd']) Parameter('bind_0_Ligand_binder_Receptor_binder_target_2kf', 1.0) Parameter('bind_0_Ligand_binder_Receptor_binder_target_1kr', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_2kf', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_1kr', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr', 1.0) Parameter('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0) Parameter('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr', 1.0) Parameter('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kf', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kr', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr', 1.0) Parameter('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr', 1.0) Parameter('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc', 1.0) Parameter('pore_formation_0_BaxA_pore_2kf', 1.0) Parameter('pore_formation_0_BaxA_pore_1kr', 1.0) Parameter('pore_formation_1_BaxA_pore_2kf', 1.0) Parameter('pore_formation_1_BaxA_pore_1kr', 1.0) Parameter('pore_formation_2_BaxA_pore_2kf', 1.0) Parameter('pore_formation_2_BaxA_pore_1kr', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc', 1.0) Parameter('Ligand_0', 1000.0) Parameter('ParpU_0', 1000000.0) Parameter('C8A_0', 0.0) Parameter('SmacM_0', 100000.0) Parameter('BaxM_0', 40000.0) Parameter('Apop_0', 0.0) Parameter('Fadd_0', 130000.0) Parameter('SmacC_0', 0.0) Parameter('ParpC_0', 0.0) Parameter('Xiap_0', 12750.0) Parameter('C9_0', 100000.0) Parameter('C3ub_0', 0.0) Parameter('C8pro_0', 130000.0) Parameter('C3pro_0', 21000.0) Parameter('CytoCM_0', 500000.0) Parameter('CytoCC_0', 0.0) Parameter('BaxA_0', 0.0) Parameter('ApafI_0', 100000.0) Parameter('BidU_0', 171000.0) Parameter('BidT_0', 0.0) Parameter('C3A_0', 0.0) Parameter('ApafA_0', 0.0) Parameter('BidM_0', 0.0) Parameter('Receptor_0', 100.0) Observable('Ligand_obs', Ligand()) Observable('ParpU_obs', ParpU()) Observable('C8A_obs', C8A()) Observable('SmacM_obs', SmacM()) Observable('BaxM_obs', BaxM()) Observable('Apop_obs', Apop()) Observable('Fadd_obs', Fadd()) Observable('SmacC_obs', SmacC()) Observable('ParpC_obs', ParpC()) Observable('Xiap_obs', Xiap()) Observable('C9_obs', C9()) Observable('C3ub_obs', C3ub()) Observable('C8pro_obs', C8pro()) Observable('C3pro_obs', C3pro()) Observable('CytoCM_obs', CytoCM()) Observable('CytoCC_obs', CytoCC()) Observable('BaxA_obs', BaxA()) Observable('ApafI_obs', ApafI()) Observable('BidU_obs', BidU()) Observable('BidT_obs', BidT()) Observable('C3A_obs', C3A()) Observable('ApafA_obs', ApafA()) Observable('BidM_obs', BidM()) Observable('Receptor_obs', Receptor()) Rule('bind_0_Ligand_binder_Receptor_binder_target', Ligand(Receptor=None) + Receptor(Ligand=None, Fadd=None) | Ligand(Receptor=1) % Receptor(Ligand=1, Fadd=None), bind_0_Ligand_binder_Receptor_binder_target_2kf, bind_0_Ligand_binder_Receptor_binder_target_1kr) Rule('bind_0_Receptor_binder_Fadd_binder_target', Receptor(Ligand=ANY, Fadd=None) + Fadd(Receptor=None, C8pro=None) | Receptor(Ligand=ANY, Fadd=1) % Fadd(Receptor=1, C8pro=None), bind_0_Receptor_binder_Fadd_binder_target_2kf, bind_0_Receptor_binder_Fadd_binder_target_1kr) Rule('substrate_binding_0_Fadd_catalyzer_C8pro_substrate', Fadd(Receptor=ANY, C8pro=None) + C8pro(Fadd=None) | Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1), substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf, substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr) Rule('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product', Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1) >> Fadd(Receptor=ANY, C8pro=None) + C8A(BidU=None), catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc) Rule('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=None) + BidU(C8A=None) | C8A(BidU=1) % BidU(C8A=1), catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf, catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr) Rule('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=1) % BidU(C8A=1) >> C8A(BidU=None) + BidT(), catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc) Rule('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex', ApafI() + CytoCC() | ApafA(), conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf, conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr) Rule('inhibition_0_SmacC_inhibitor_Xiap_inh_target', SmacC(Xiap=None) + Xiap(SmacC=None, Apop=None, C3A=None) | SmacC(Xiap=1) % Xiap(SmacC=1, Apop=None, C3A=None), inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf, inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr) Rule('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex', ApafA() + C9() | Apop(C3pro=None, Xiap=None), conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf, conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr) Rule('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=None, Xiap=None) + C3pro(Apop=None) | Apop(C3pro=1, Xiap=None) % C3pro(Apop=1), catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr) Rule('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=1, Xiap=None) % C3pro(Apop=1) >> Apop(C3pro=None, Xiap=None) + C3A(Xiap=None, ParpU=None), catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc) Rule('inhibition_0_Xiap_inhibitor_Apop_inh_target', Xiap(SmacC=None, Apop=None, C3A=None) + Apop(C3pro=None, Xiap=None) | Xiap(SmacC=None, Apop=1, C3A=None) % Apop(C3pro=None, Xiap=1), inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf, inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr) Rule('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=None) + C3A(Xiap=None, ParpU=None) | Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None), catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf, catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr) Rule('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None) >> Xiap(SmacC=None, Apop=None, C3A=None) + C3ub(), catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc) Rule('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=None) + ParpU(C3A=None) | C3A(Xiap=None, ParpU=1) % ParpU(C3A=1), catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf, catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr) Rule('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=1) % ParpU(C3A=1) >> C3A(Xiap=None, ParpU=None) + ParpC(), catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc) Rule('equilibration_0_BidT_equil_a_BidM_equil_b', BidT() | BidM(BaxM=None), equilibration_0_BidT_equil_a_BidM_equil_b_1kf, equilibration_0_BidT_equil_a_BidM_equil_b_1kr) Rule('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=None) + BaxM(BidM=None, BaxA=None) | BidM(BaxM=1) % BaxM(BidM=1, BaxA=None), catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf, catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr) Rule('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=1) % BaxM(BidM=1, BaxA=None) >> BidM(BaxM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc) Rule('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxM(BidM=None, BaxA=None) | BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1), self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf, self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr) Rule('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1) >> BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc) Rule('pore_formation_0_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None), pore_formation_0_BaxA_pore_2kf, pore_formation_0_BaxA_pore_1kr) Rule('pore_formation_1_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None), pore_formation_1_BaxA_pore_2kf, pore_formation_1_BaxA_pore_1kr) Rule('pore_formation_2_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None), pore_formation_2_BaxA_pore_2kf, pore_formation_2_BaxA_pore_1kr) Rule('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5), transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf, transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr) Rule('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacC(Xiap=None), transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc) Rule('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5), transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf, transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr) Rule('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCC(), transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc) Initial(Ligand(Receptor=None), Ligand_0) Initial(ParpU(C3A=None), ParpU_0) Initial(C8A(BidU=None), C8A_0) Initial(SmacM(BaxA=None), SmacM_0) Initial(BaxM(BidM=None, BaxA=None), BaxM_0) Initial(Apop(C3pro=None, Xiap=None), Apop_0) Initial(Fadd(Receptor=None, C8pro=None), Fadd_0) Initial(SmacC(Xiap=None), SmacC_0) Initial(ParpC(), ParpC_0) Initial(Xiap(SmacC=None, Apop=None, C3A=None), Xiap_0) Initial(C9(), C9_0) Initial(C3ub(), C3ub_0) Initial(C8pro(Fadd=None), C8pro_0) Initial(C3pro(Apop=None), C3pro_0) Initial(CytoCM(BaxA=None), CytoCM_0) Initial(CytoCC(), CytoCC_0) Initial(BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), BaxA_0) Initial(ApafI(), ApafI_0) Initial(BidU(C8A=None), BidU_0) Initial(BidT(), BidT_0) Initial(C3A(Xiap=None, ParpU=None), C3A_0) Initial(ApafA(), ApafA_0) Initial(BidM(BaxM=None), BidM_0) Initial(Receptor(Ligand=None, Fadd=None), Receptor_0)
87.857923
710
0.803458
ace8a1d4982694d6c21b44de13de44e692abcb9d
20,146
py
Python
func_moead.py
dynamic-sevn/moead_svm
0f119d5c0b840d1897b7c8067c4563285fd70031
[ "BSD-2-Clause" ]
1
2021-07-31T08:54:49.000Z
2021-07-31T08:54:49.000Z
func_moead.py
dynamic-sevn/moead_svm
0f119d5c0b840d1897b7c8067c4563285fd70031
[ "BSD-2-Clause" ]
null
null
null
func_moead.py
dynamic-sevn/moead_svm
0f119d5c0b840d1897b7c8067c4563285fd70031
[ "BSD-2-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """ Author: Xi Lin <xi.lin@my.cityu.edu.hk> website: http://www.cs.cityu.edu.hk/~xilin4/ github: This code is a demo for this paper: A Decomposition based Multiobjective Evolutionary Algorithm with Classification Xi Lin, Qingfu Zhang, Sam Kwong Proceedings of the 2016 IEEE Congress on Evolutionary Computation (CEC16) Vancouver, Canada, July 2016 """ import os import sys import copy import numpy as np import scipy from sklearn import svm from test_instances import * path = os.path.abspath(os.path.dirname(sys.argv[0])) class Problem: """Multi-objective Problem name: MoP name dim: dimension of decision space nobj:dimension of objective space domain: domain for decision variable """ def __init__(self,name,dim,nobj,domain = None): self.name = name self.dim = dim self.nobj = nobj if domain is None: self.domain = np.tile(np.array([0,1]),(self.dim,1)) def evaluate(self,x): #evaluate objective values for given decision variable return testfunc(self,x) class Params: """Parameters for MOEA/D popsize: population size niche: neighbourhood size dmethod: decomposition method iteration: number of maximum iterations in each run; not used in this demo stop_nfeval: number of maximum function evaluations in each run updatedprob: probability that parent solutions are selected from the neighbourhood, but not the whole population updatednb: maximum number of current solutions which would be replaced by each new solution F, CR: parameters for DE operator """ def __init__(self,popsize,niche,dmethod,iteration, stop_nfeval,updateprob,updatenb,F,CR): self.popsize = popsize self.niche = niche self.dmethod = dmethod self.iteration = iteration self.stop_nfeval = stop_nfeval self.updateprob = updateprob self.updatenb = updatenb self.F = F self.CR = CR class Subproblem: """Subproblem in MOEA/D weight: decomposition weight neighbour: index of neighbours curpoint: Individual Class current best solution subpoint: Individual Class current sub-best solution, for classification training """ def __init__(self,weight,mop,params): self.weight = weight self.neighbour = np.full(params.niche,np.nan) self.curpoint = np.full(mop.dim,np.nan) self.subpoint = np.full(mop.dim,np.nan) class Individual: """Solution in MOEA/D parameter: decision variable value: objective value """ def __init__(self,parameter): self.parameter = parameter self.value = float('Inf') def init_params(ins): """Initialize parameters for test instance The given parameters in this function are the same as in the paper: A Decomposition based Multiobjective Evolutionary Algorithm with Classification Xi Lin, Qingfu Zhang, Sam Kwong IEEE World Congress on Computational Intelligence(IEEE WCCI), Vancouver, Canada, July 2016 Parameters ---------- ins: name for test instance Returns ------- dim: dimension of decision space nobj: dimenson of objective space popsize: population size niche: neighbourhood size stop_nfeval: number of maximum function evaluations in each run """ if ins in ['ZDT1','ZDT2','ZDT3']: dim = 30 nobj = 2 popsize = 300 niche = 30 stop_nfeval = 100000 if ins in ['ZDT4','ZDT6']: dim = 10 nobj = 2 popsize = 300 niche = 30 stop_nfeval = 100000 if ins in ['DTLZ1']: dim = 10 nobj = 3 popsize = 595 niche = 50 stop_nfeval = 100000 if ins in ['DTLZ2']: dim = 30 nobj = 3 popsize = 595 niche = 50 stop_nfeval = 100000 if ins in ['UF1','UF2','UF3','UF4','UF5','UF6','UF7']: dim = 30 nobj = 2 popsize = 600 niche = 30 stop_nfeval = 300000 if ins in ['UF8','UF9','UF10']: dim = 30 nobj = 3 popsize = 595 niche = 50 stop_nfeval = 300000 return dim, nobj, popsize, niche, stop_nfeval def init_point(mop): """Initialize a solution with randomly generated decision variable Parameters ---------- mop: Problem Class multi-objective problem to be sloved Returns ------- point: Individual Class a solution with randomly generated decision variable, which is not evaluated yet """ lowend = mop.domain[:,0] span = mop.domain[:,1] - lowend para = lowend + span * np.random.rand(mop.dim) point = Individual(para) return point def init_subproblem_classification(mop,params): """Initialize all subproblems and ideal point for MOEA/D-SVM Parameters ---------- mop: Problem Class multi-objective problem to be sloved params: Params Class parameters for moea/d Returns ------- subproblems: Subproblem Class all subproblems initialized accroding to mop and params idealpoint: estimated idealpoint for Tchebycheff decomposition """ #load already genereted weights vector in weight file weights = np.loadtxt(path + "/weight/W%dD_%d.dat"%(mop.nobj,params.popsize)) idealpoint = np.ones(mop.nobj) * float('Inf') subproblems = [] #initialize Subproblem Class for each weight vetor for i in range(params.popsize): sub = Subproblem(weights[i],mop,params) subproblems.append(sub) #distmat[i,j] is the distance btw sub[i] and sub[j], distmat[i,i] = nan distmat = np.full([params.popsize, params.popsize],np.nan) #initialize current best/sub-best point for each subproblem and idealpoint for i in range(params.popsize): for j in range(i+1,params.popsize): a = subproblems[i].weight b = subproblems[j].weight distmat[i,j] = np.linalg.norm(a - b) distmat[j,i] = distmat[i,j] #calculate the neighbourhood for each subproblem subproblems[i].neighbour = distmat[i,].argsort()[0:params.niche] subproblems[i].curpoint = init_point(mop) subproblems[i].curpoint.value = mop.evaluate( subproblems[i].curpoint.parameter) subproblems[i].subpoint = init_point(mop) subproblems[i].subpoint.value = mop.evaluate( subproblems[i].subpoint.parameter) idealpoint = np.minimum.reduce([idealpoint, subproblems[i].curpoint.value, subproblems[i].subpoint.value]) #swap(curpoint,subpoint) if g_i(subpoint) < g_i(curpoint) #where g_i() is value function for the i-th subproblem for i in range(params.popsize): curvalue = subobjective_vec(subproblems[i].weight, subproblems[i].curpoint.value.reshape(1,-1), idealpoint,params.dmethod) subvalue = subobjective_vec(subproblems[i].weight, subproblems[i].subpoint.value.reshape(1,-1), idealpoint,params.dmethod) if subvalue < curvalue: subproblems[i].curpoint, subproblems[i].subpoint = subproblems[i].subpoint, subproblems[i].curpoint return (subproblems, idealpoint) def init_subproblem(mop,params): """Initialize all subproblems and ideal point for MOEA/D Parameters ---------- mop: Problem Class multi-objective problem to be sloved params: Params Class parameters for moea/d Returns ------- subproblems: Subproblem Class all subproblems initialized accroding to mop and params idealpoint: estimated idealpoint for Tchebycheff decomposition """ weights = np.loadtxt(path + "/weight/W%dD_%d.dat"%(mop.nobj,params.popsize)) idealpoint = np.ones(mop.nobj) * float('Inf') subproblems = [] #initialize Subproblem Class for each weight vetor for i in range(params.popsize): sub = Subproblem(weights[i],mop,params) subproblems.append(sub) #distmat[i,j] is the distance btw sub[i] and sub[j], distmat[i,i] = nan distmat = np.full([params.popsize, params.popsize],np.nan) #initialize current best/sub-best point for each subproblem and idealpoint for i in range(params.popsize): for j in range(i+1,params.popsize): a = subproblems[i].weight b = subproblems[j].weight distmat[i,j] = np.linalg.norm(a - b) distmat[j,i] = distmat[i,j] subproblems[i].neighbour = distmat[i,].argsort()[0:params.niche] subproblems[i].curpoint = init_point(mop) subproblems[i].curpoint.value = mop.evaluate( subproblems[i].curpoint.parameter) idealpoint = np.minimum(idealpoint,subproblems[i].curpoint.value) return (subproblems, idealpoint) def terminate(n,params): """Decide on whether to terminate current algo run or not Parameters ---------- n: number of total evaluations have been conducted in current run params: Params Class parameters for moea/d Returns ------- boolean expression True if number of total evaluations exceed params.stop_nfeval """ return n >= params.stop_nfeval def genetic_op(index,updateneighbour,mop, params,subproblems,ptype): """Generated a new solutions for the index-th subproblem Parameters ---------- index: subproblem index updateneighbour: boolean expression whether parent solutions are selected from the neighbourhood or not mop: Problem Class multi-objective problem to be sloved params: Params Class parameters for moea/d subproblems: Subproblem Class all subproblems ptype: the type of generated solutions, always "current" in this demo Returns ------- newpoint: Individual Class a new generated solution """ #select parents parents_index = mate_select(index,updateneighbour, subproblems,params,2) #generate a new solution using DE crossover newpoint = de_crossover(index,parents_index,subproblems, params.F,params.CR,mop,ptype) #mutate new solution mutate(newpoint,mop,1.0/mop.dim,20) return newpoint def mate_select(index,updateneighbour, subproblems,params,size): """Select parents for new solution generation Parameters ---------- index: subproblem index updateneighbour: boolean expression whether parents are selected from the neighbourhood or not subproblems: Subproblem Class all subproblems params: Params Class parameters for moea/d size: number of parents selected Returns ------- selected_list: List, len(List) = size list of selected parents' indexes """ selected_list = [] #decide on whether parents are selected from the neighbourhood or not if(updateneighbour): selindex = subproblems[index].neighbour else: selindex = range(params.popsize) #select list of selected parents' indexes while len(selected_list) < size: r = np.random.rand(1)[0] parent = selindex[np.int(np.floor(len(selindex)*r))] if (not parent in selected_list): selected_list.append(parent) return selected_list def de_crossover(index,parents_index,subproblems,F,CR,mop,ptype): """Generate a new solution using DE crossover Parameters ---------- index: subproblem index parents_index: List list of selected parents' indexes subproblems: Subproblem Class all subproblems F,CR: DE parameters mop: Problem Class multi-objective problem to be sloved ptype: the type of generated solutions, always "current" in this demo Returns ------- newpoint: Individual Class a new generated solution """ #initialize new solution with randomly generated decision variable newpoint = init_point(mop) #decide the decision variable using DE crossover if ptype == 'current': x1 = subproblems[index].curpoint.parameter x2 = subproblems[parents_index[0]].curpoint.parameter x3 = subproblems[parents_index[1]].curpoint.parameter cross = x1 + F * (x2 - x3) newpoint.parameter = np.copy(subproblems[index].curpoint.parameter) crossindex = np.random.rand(mop.dim) < CR newpoint.parameter[crossindex] = cross[crossindex] for i in range(mop.dim): r1 = np.random.rand(1)[0] if r1 < CR: newpoint.parameter[i] = cross[i] #handle the boundary lowerbound = mop.domain[i,0] upperbound = mop.domain[i,1] if newpoint.parameter[i] < lowerbound: r2 = np.random.rand(1)[0] newpoint.parameter[i] = lowerbound + r2*(x1[i] - lowerbound) if newpoint.parameter[i] > upperbound: r2 = np.random.rand(1)[0] newpoint.parameter[i] = upperbound - r2*(upperbound - x1[i]) return newpoint def mutate(newpoint,mop,rate,eta): """Mutate new generated solution Parameters ---------- index: subproblem index mop: Problem Class multi-objective problem to be sloved rate,eta: mutation parameters Returns ------- newpoint is mutable, hence no return is needed """ #polynomial mutate for i in range(mop.dim): r1 = np.random.rand(1)[0] if(r1 < rate): y = newpoint.parameter[i] yl = mop.domain[i,0] yu = mop.domain[i,1] r2 = np.random.rand(1)[0] if(r2 < 0.5): sigma = (2 * r2) ** (1.0/(eta + 1)) - 1 else: sigma = 1 - (2 - 2*r2) ** (1.0/(eta + 1)) newpoint.parameter[i] = y + sigma * (yu - yl) if newpoint.parameter[i] > yu: newpoint.parameter[i] = yu if newpoint.parameter[i] < yl: newpoint.parameter[i] = yl def subobjective_vec(weight,value,idealpoint,dmethod): """Calculate the value of subproblem with given weight, value and idealpoint Parameters ---------- weight: weight vector value: objective value idealpoint: idealpoint dmethod: decomposition method; in this demo, dmethod is always 'tc' which stands for Tchebycheff decomposition Returns ------- mutated_newpoint: Individual Class a new generated solution """ if dmethod is 'tc': new_weight = np.copy(weight) new_weight[new_weight == 0.0] = 0.0001 absdiff = np.abs(value - idealpoint) return np.amax(new_weight * absdiff,axis = 1) def update_vec(index,updateneighbour,newpoint, mop,params,subproblems,idealpoint): """Updated current population using new generated solutions Parameters ---------- index: subproblem index updateneighbour: boolean expression whether parent solutions are selected from the neighbourhood or not newpoint: Individual Class a new generated solution mop: Problem Class multi-objective problem to be sloved params: Params Class parameters for moea/d subproblems: Subproblem Class all subproblems idealpoint: estimated idealpoint Returns ------- is_updated: 1 if at least one current solution was replaced 0 otherwise """ is_updated = 0 #Classes subproblems[k] k = 1,2,..., is mutable, hence no return is needed if(updateneighbour): updateindex = np.array(subproblems[index].neighbour) else: updateindex = np.array(range(params.popsize)) np.random.shuffle(updateindex) weight_vec = np.array([subproblems[k].weight for k in updateindex]) oldvalue_vec = np.array( [subproblems[k].curpoint.value for k in updateindex]) oldobj_vec = subobjective_vec(weight_vec,oldvalue_vec, idealpoint,params.dmethod) newobj_vec = subobjective_vec(weight_vec,newpoint.value, idealpoint,params.dmethod) #contain maximum(not always) 2 elementc replaceindex = updateindex[newobj_vec < oldobj_vec][:2] for k in replaceindex: subproblems[k].subpoint = subproblems[k].curpoint subproblems[k].curpoint = newpoint is_updated = 1 return is_updated def calculateigd(truepf, pf): """Calculate IGD value for truepf and pf Parameters ---------- truepf: "true" pf value pf: estimated pf value Returns ------- igd: IGD value """ Y = scipy.spatial.distance.cdist(truepf, pf, 'euclidean') mindist = np.min(Y, axis=1) igd = np.mean(mindist) return igd def trainSVMmodel(subproblems,params,gamma=1,C=100): """Train SVM Classification model Parameters ---------- subproblems: Subproblem Class all subproblems params: Params Class parameters for moea/d gamma, C: kernel parameters In this demo, the kernel we use is always RBF kernel with fixed gamma = 1 and C = 100. Returns ------- classifier: trained SVM classifier """ #curpoints as positive samples, and subpoints as negative samples curX = np.array([subproblems[k].curpoint.parameter for k in range(params.popsize)]) subX = np.array([subproblems[k].subpoint.parameter for k in range(params.popsize)]) trainX = np.concatenate((curX, subX)) trainLabel = np.concatenate((np.ones(params.popsize), np.zeros(params.popsize))) classifier = svm.SVC(gamma = gamma, C = C) classifier.fit(trainX, trainLabel) return classifier
30.570561
112
0.563983
ace8a1f9773abc1c58292838a36b3cde87de5827
1,206
py
Python
hunk/production.py
lanius/hunk
bba04d9fb7f37c378ea41bc934c3a02401e34fe6
[ "MIT" ]
1
2015-04-03T08:35:41.000Z
2015-04-03T08:35:41.000Z
hunk/production.py
lanius/hunk
bba04d9fb7f37c378ea41bc934c3a02401e34fe6
[ "MIT" ]
null
null
null
hunk/production.py
lanius/hunk
bba04d9fb7f37c378ea41bc934c3a02401e34fe6
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ hunk.production ~~~~~~~~~~~~~~~ Provides a class to configure production environment. """ import importlib import os import sys from ._compat import urljoin, urlunsplit class ProductionEnvironment(object): """Holds information for a production environment to dispatch to it.""" def __init__(self): self.routes = set() self.scheme = 'http' self.hostname = 'localhost' self.port = 9000 def load(self, dirpath, filename): filepath = os.path.join(dirpath, filename) if not os.path.exists(filepath): return # skipped modname, _ = os.path.splitext(filename) sys.path.append(dirpath) config = importlib.import_module(modname) for attr in ['scheme', 'hostname', 'port']: if hasattr(config, attr): setattr(self, attr, getattr(config, attr)) if hasattr(config, 'routes'): self.routes.update(config.routes) def build_url(self, path): base_url = urlunsplit(( self.scheme, ':'.join([self.hostname, str(self.port)]), '', '', '' )) return urljoin(base_url, path)
24.12
75
0.586235
ace8a2e854a1e2431c523e571859d82c0cdda19e
407
py
Python
packages/python/plotly/plotly/validators/layout/xaxis/_showgrid.py
mastermind88/plotly.py
efa70710df1af22958e1be080e105130042f1839
[ "MIT" ]
null
null
null
packages/python/plotly/plotly/validators/layout/xaxis/_showgrid.py
mastermind88/plotly.py
efa70710df1af22958e1be080e105130042f1839
[ "MIT" ]
null
null
null
packages/python/plotly/plotly/validators/layout/xaxis/_showgrid.py
mastermind88/plotly.py
efa70710df1af22958e1be080e105130042f1839
[ "MIT" ]
null
null
null
import _plotly_utils.basevalidators class ShowgridValidator(_plotly_utils.basevalidators.BooleanValidator): def __init__(self, plotly_name="showgrid", parent_name="layout.xaxis", **kwargs): super(ShowgridValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "ticks"), **kwargs, )
33.916667
85
0.678133
ace8a3031607854c604b28666dd4a17727d7a170
13,403
py
Python
CPAC/utils/symlinks.py
Lawreros/C-PAC
ce26ba9a38cbd401cd405150eeed23b805007724
[ "BSD-3-Clause" ]
null
null
null
CPAC/utils/symlinks.py
Lawreros/C-PAC
ce26ba9a38cbd401cd405150eeed23b805007724
[ "BSD-3-Clause" ]
null
null
null
CPAC/utils/symlinks.py
Lawreros/C-PAC
ce26ba9a38cbd401cd405150eeed23b805007724
[ "BSD-3-Clause" ]
null
null
null
import os import errno from collections import defaultdict output_renamings = { 'anatomical_brain': 'anat', 'anatomical_brain_mask': 'anat', 'qc': 'qc', 'anatomical_reorient': 'anat', 'anatomical_to_mni_linear_xfm': 'anat', 'mni_to_anatomical_linear_xfm': 'anat', 'mni_to_anatomical_nonlinear_xfm': 'anat', 'anatomical_to_mni_nonlinear_xfm': 'anat', 'anatomical_gm_mask': 'anat', 'anatomical_csf_mask': 'anat', 'anatomical_wm_mask': 'anat', 'ants_initial_xfm': 'anat', 'ants_rigid_xfm': 'anat', 'ants_affine_xfm': 'anat', 'mean_functional': 'func', 'functional_preprocessed_mask': 'func', 'functional_to_spatial_map': 'func', 'functional_mask_to_spatial_map': 'func', 'fmap_phase_diff': 'func', 'fmap_magnitude': 'func', 'functional_distortion_corrected': 'func', 'despiked_fieldmap': 'func', 'prepared_fieldmap_map': 'func', 'fieldmap_mask': 'func', 'slice_time_corrected': 'func', 'slice_timing_corrected': 'func', 'movement_parameters': 'parameters', 'max_displacement': 'parameters', 'xform_matrix': 'parameters', 'output_means': 'parameters', 'functional_preprocessed': 'func', 'functional_brain_mask': 'func', 'motion_correct': 'func', 'motion_correct_smooth': 'func', 'motion_correct_to_standard': 'func', 'motion_correct_to_standard_smooth': 'func', 'mean_functional_in_anat': 'func', 'coordinate_transformation': 'func', 'raw_functional': 'func', 'selected_func_volume': 'func', 'anatomical_wm_edge': 'registration', 'anatomical_to_functional_xfm': 'registration', 'inverse_anatomical_to_functional_xfm': 'registration', 'functional_gm_mask': 'segmentation', 'functional_wm_mask': 'segmentation', 'functional_csf_mask': 'segmentation', 'frame_wise_displacement_power': 'parameters', 'frame_wise_displacement_jenkinson': 'parameters', 'functional_nuisance_residuals': 'func', 'functional_nuisance_regressors': 'func', 'functional_median_angle_corrected': 'func', 'power_spectrum_distribution': 'alff', 'functional_freq_filtered': 'func', 'scrubbing_movement_parameters': 'parameters', 'despiking_frames_included': 'parameters', 'despiking_frames_excluded': 'parameters', 'scrubbing_frames_included': 'parameters', 'scrubbing_frames_excluded': 'parameters', 'motion_params': 'parameters', 'power_params': 'parameters', 'scrubbed_preprocessed': 'func', 'functional_to_standard': 'func', 'functional_brain_mask_to_standard': 'func', 'mean_functional_to_standard': 'func', 'functional_to_anat_linear_xfm': 'registration', 'functional_to_mni_linear_xfm': 'registration', 'mni_to_functional_linear_xfm': 'registration', 'ants_symmetric_initial_xfm': 'registration', 'ants_symmetric_rigid_xfm': 'registration', 'ants_symmetric_affine_xfm': 'registration', 'anatomical_to_symmetric_mni_nonlinear_xfm': 'registration', 'symmetric_mni_to_anatomical_nonlinear_xfm': 'registration', 'symmetric_mni_to_anatomical_linear_xfm': 'registration', 'anat_to_symmetric_mni_ants_composite_xfm': 'registration', 'symmetric_anatomical_to_standard': 'registration', 'anatomical_to_symmetric_mni_linear_xfm': 'registration', 'anatomical_to_standard': 'anat', 'leaf_node_to_standard': 'func', 'vmhc_raw_score': 'vmhc', 'vmhc_fisher_zstd': 'vmhc', 'vmhc_fisher_zstd_zstat_map': 'vmhc', 'alff': 'alff', 'falff': 'alff', 'alff_smooth': 'alff', 'falff_smooth': 'alff', 'alff_to_standard': 'alff', 'falff_to_standard': 'alff', 'alff_to_standard_smooth': 'alff', 'falff_to_standard_smooth': 'alff', 'alff_to_standard_zstd': 'alff', 'falff_to_standard_zstd': 'alff', 'alff_to_standard_smooth_zstd': 'alff', 'falff_to_standard_smooth_zstd': 'alff', 'alff_to_standard_zstd_smooth': 'alff', 'falff_to_standard_zstd_smooth': 'alff', 'reho': 'reho', 'reho_smooth': 'reho', 'reho_to_standard': 'reho', 'reho_to_standard_smooth': 'reho', 'reho_to_standard_zstd': 'reho', 'reho_to_standard_smooth_zstd': 'reho', 'reho_to_standard_zstd_smooth': 'reho', 'connectome_PearsonCorr': 'connectome', 'connectome_PartialCorr': 'connectome', 'voxel_timeseries': 'timeseries', 'roi_timeseries': 'timeseries', 'roi_timeseries_for_SCA': 'timeseries', 'roi_timeseries_for_SCA_multreg': 'timeseries', 'sca_roi_files': 'sca_roi', 'sca_roi_files_smooth': 'sca_roi', 'sca_roi_files_to_standard': 'sca_roi', 'sca_roi_files_to_standard_smooth': 'sca_roi', 'sca_roi_files_to_standard_fisher_zstd': 'sca_roi', 'sca_roi_files_to_standard_smooth_fisher_zstd': 'sca_roi', 'sca_roi_files_to_standard_fisher_zstd_smooth': 'sca_roi', 'bbregister_registration': 'surface_registration', 'left_hemisphere_surface': 'surface_registration', 'right_hemisphere_surface': 'surface_registration', 'vertices_timeseries': 'timeseries', 'centrality': 'centrality', 'centrality_smooth': 'centrality', 'centrality_zstd': 'centrality', 'centrality_smooth_zstd': 'centrality', 'centrality_zstd_smooth': 'centrality', 'centrality_graphs': 'centrality', 'seg_probability_maps': 'anat', 'seg_mixeltype': 'anat', 'seg_partial_volume_map': 'anat', 'seg_partial_volume_files': 'anat', 'spatial_map_timeseries': 'timeseries', 'spatial_map_timeseries_for_DR': 'timeseries', 'dr_tempreg_maps_files': 'spatial_regression', 'dr_tempreg_maps_files_smooth': 'spatial_regression', 'dr_tempreg_maps_zstat_files': 'spatial_regression', 'dr_tempreg_maps_zstat_files_smooth': 'spatial_regression', 'dr_tempreg_maps_files_to_standard': 'spatial_regression', 'dr_tempreg_maps_zstat_files_to_standard': 'spatial_regression', 'dr_tempreg_maps_files_to_standard_smooth': 'spatial_regression', 'dr_tempreg_maps_zstat_files_to_standard_smooth': 'spatial_regression', 'sca_tempreg_maps_files': 'sca_roi', 'sca_tempreg_maps_files_smooth': 'sca_roi', 'sca_tempreg_maps_zstat_files': 'sca_roi', 'sca_tempreg_maps_zstat_files_smooth': 'sca_roi', } fork_ids = { 'compcor': 'nuis', 'selector': 'nuis', 'target_angle_deg': 'medang' } def group_files_in_strategies(output_dir, paths): strategies = defaultdict(set) for path in paths: pieces = path.replace(output_dir, '').split(os.sep) related_strategy = tuple([ p for p in pieces if any( p.startswith('_' + pattern) for pattern in fork_ids.keys() ) ]) strategies[related_strategy].add(path) # Get every file that is not affected by a strategy and add it to every other strategy strategies_keys = set(strategies.keys()) - set(tuple()) for paths_without_strategy in strategies[tuple()]: for strategy in strategies_keys: strategies[strategy].add(paths_without_strategy) strategies = dict(strategies) # Add every file from primary strategy into derived strategies for strategy in strategies_keys: strategy_files = strategies[strategy] has_derived_strategy = False for specialized_strategy in strategies_keys: if specialized_strategy not in strategies: continue # specialized_strategy is derived from strategy if len(specialized_strategy) > len(strategy) and \ strategy == specialized_strategy[0:len(strategy)]: strategies[specialized_strategy].update(strategy_files) has_derived_strategy = True if has_derived_strategy: del strategies[strategy] if tuple() in strategies: del strategies[tuple()] return strategies def compile_strategy_name(strategy): name = [] for s in strategy: fork = s[1:] for id in fork_ids: if fork.startswith(id): fork_name = fork_ids[id] name += [s.replace('_' + id, fork_name)] break return '__'.join(name) def create_paths_to_symlinks( output_dir, pipeline_id, subject_id, paths ): if len(paths) == 0: return {} # Mapping of paths to symlinks symlinks = {} strategies = group_files_in_strategies(output_dir, paths) for strategy, strategy_paths in strategies.items(): strategy_name = compile_strategy_name(strategy) paths_symlinks = [] for path in strategy_paths: path_parts = path.replace(output_dir, '').strip(os.sep).split(os.sep) # If file is relative to a scan, use the tag # Otherwise, set to 'scan' scan_name = [p for p in path_parts if p.startswith('_scan_')] if not scan_name: scan_name = 'scan' else: scan_name = scan_name[0] path_parts = [p for p in path_parts if p != scan_name] scan_name = scan_name.strip('_') # Treat QC differently if path_parts[2] == 'qc': output_name = path_parts[3] output_group = 'qc' output_specs = path_parts[4:-1] else: output_name = path_parts[2] output_group = output_renamings[output_name] output_specs = path_parts[3:-1] # output_specs are parameters e.g. bandpass, fwhm, and mask # Remove strategies info from path, since it is included # on the outer path output_specs = [ sp for sp in output_specs if not any( sp.startswith('_' + pattern) for pattern in fork_ids.keys() ) ] # Remove leading or trailing underscores output_specs = [sp.strip('_') for sp in output_specs] # Get the file extension output_file_ext = '' output_file_parts = path_parts[-1].split('.') if output_file_parts[-2:] == ['nii', 'gz']: output_file_ext = '.nii.gz' else: output_file_ext = '.' + output_file_parts[-1] paths_symlinks.append({ 'path': path, 'scan': scan_name, 'group': output_group, 'specs': tuple(output_specs), 'name': output_name, 'file': path_parts[-1], 'ext': output_file_ext, }) for i, path_symlink in enumerate(paths_symlinks): original_path = path_symlink['path'] remaining_paths_symlinks = paths_symlinks[0:i] + paths_symlinks[i+1:] group = path_symlink['group'] # Check if we need to keep the same basename or if we can give it # a better name, in order to avoid link collision # Outputs like from segmentation cant change its name since they # have several files (e.g. seg0, seg1, seg2) if any( rps['group'] == group and rps['scan'] == path_symlink['scan'] and rps['name'] == path_symlink['name'] and rps['specs'] == path_symlink['specs'] for rps in remaining_paths_symlinks ): symlink_basename = path_symlink['file'] # if pretty name cant be used, append it to group name group = os.path.join(group, path_symlink['name']) else: symlink_basename = path_symlink['name'] + path_symlink['ext'] sym_path = os.path.join(*[ pipeline_id, strategy_name, path_symlink['scan'], group, ] + list(path_symlink['specs']) + [symlink_basename]) symlinks[original_path] = sym_path values = list(symlinks.values()) duplicates = set([x for x in values if values.count(x) > 1]) if duplicates: raise Exception("Found duplicates: " + str(duplicates)) return symlinks def create_symlinks( output_dir, pipeline_id, subject_id, paths, relative=True, symlink_dir='sym_links' ): original_cwd = os.getcwd() try: os.chdir(output_dir) mapping = create_paths_to_symlinks( output_dir, pipeline_id, subject_id, paths ) for path, symlink in mapping.items(): relpath = path if relpath.startswith(output_dir): relpath = relpath[len(output_dir):].lstrip('/') symlink = os.path.join(symlink_dir, symlink) try: os.makedirs(os.path.dirname(symlink)) except: pass if relative: backtrack = os.path.join(*( ['..'] * (len(symlink.split('/')) - 1) )) path = os.path.join(backtrack, relpath) try: os.symlink(path, symlink) except OSError as e: if e.errno == errno.EEXIST: os.remove(symlink) os.symlink(path, symlink) else: raise e finally: os.chdir(original_cwd)
34.543814
90
0.625755
ace8a3620c18ded089c555e11d44bd59193a1f4e
6,686
py
Python
extra_apps/xadmin/models.py
hhdMrLion/mxshop-api
1472ad0d959439ea80c1f8d8bfd3629c15d3017d
[ "Apache-2.0" ]
1
2021-06-18T03:03:38.000Z
2021-06-18T03:03:38.000Z
extra_apps/xadmin/models.py
hhdMrLion/mxshop-api
1472ad0d959439ea80c1f8d8bfd3629c15d3017d
[ "Apache-2.0" ]
1
2021-08-24T07:03:05.000Z
2021-08-24T07:03:05.000Z
xadmin/models.py
sourcery-ai-bot/django-xadmin
9c501ba10e676a97a3a06fb8d996f53fe8b7cf83
[ "BSD-3-Clause" ]
2
2021-03-02T08:12:22.000Z
2021-03-03T08:44:38.000Z
import json import django from django.db import models from django.utils import timezone from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.utils.translation import ugettext_lazy as _, ugettext from django.urls.base import reverse from django.core.serializers.json import DjangoJSONEncoder from django.db.models.base import ModelBase # from django.utils.encoding import python_2_unicode_compatible, smart_text from django.utils.encoding import smart_text from six import python_2_unicode_compatible from django.db.models.signals import post_migrate from django.contrib.auth.models import Permission import datetime import decimal from xadmin.util import quote AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') def add_view_permissions(sender, **kwargs): """ This syncdb hooks takes care of adding a view permission too all our content types. """ # for each of our content types for content_type in ContentType.objects.all(): # build our permission slug codename = "view_%s" % content_type.model # if it doesn't exist.. if not Permission.objects.filter(content_type=content_type, codename=codename): # add it Permission.objects.create(content_type=content_type, codename=codename, name="Can view %s" % content_type.name) # print "Added view permission for %s" % content_type.name # check for all our view permissions after a syncdb post_migrate.connect(add_view_permissions) @python_2_unicode_compatible class Bookmark(models.Model): title = models.CharField(_(u'Title'), max_length=128) user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_(u"user"), blank=True, null=True) url_name = models.CharField(_(u'Url Name'), max_length=64) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) query = models.CharField(_(u'Query String'), max_length=1000, blank=True) is_share = models.BooleanField(_(u'Is Shared'), default=False) @property def url(self): base_url = reverse(self.url_name) if self.query: base_url = base_url + '?' + self.query return base_url def __str__(self): return self.title class Meta: verbose_name = _(u'Bookmark') verbose_name_plural = _('Bookmarks') class JSONEncoder(DjangoJSONEncoder): def default(self, o): if isinstance(o, datetime.datetime): return o.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(o, datetime.date): return o.strftime('%Y-%m-%d') elif isinstance(o, decimal.Decimal): return str(o) elif isinstance(o, ModelBase): return '%s.%s' % (o._meta.app_label, o._meta.model_name) else: try: return super(JSONEncoder, self).default(o) except Exception: return smart_text(o) @python_2_unicode_compatible class UserSettings(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_(u"user")) key = models.CharField(_('Settings Key'), max_length=256) value = models.TextField(_('Settings Content')) def json_value(self): return json.loads(self.value) def set_json(self, obj): self.value = json.dumps(obj, cls=JSONEncoder, ensure_ascii=False) def __str__(self): return "%s %s" % (self.user, self.key) class Meta: verbose_name = _(u'User Setting') verbose_name_plural = _('User Settings') @python_2_unicode_compatible class UserWidget(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_(u"user")) page_id = models.CharField(_(u"Page"), max_length=256) widget_type = models.CharField(_(u"Widget Type"), max_length=50) value = models.TextField(_(u"Widget Params")) def get_value(self): value = json.loads(self.value) value['id'] = self.id value['type'] = self.widget_type return value def set_value(self, obj): self.value = json.dumps(obj, cls=JSONEncoder, ensure_ascii=False) def save(self, *args, **kwargs): created = self.pk is None super(UserWidget, self).save(*args, **kwargs) if created: try: portal_pos = UserSettings.objects.get( user=self.user, key="dashboard:%s:pos" % self.page_id) portal_pos.value = "%s,%s" % (self.pk, portal_pos.value) if portal_pos.value else self.pk portal_pos.save() except Exception: pass def __str__(self): return "%s %s widget" % (self.user, self.widget_type) class Meta: verbose_name = _(u'User Widget') verbose_name_plural = _('User Widgets') @python_2_unicode_compatible class Log(models.Model): action_time = models.DateTimeField( _('action time'), default=timezone.now, editable=False, ) user = models.ForeignKey( AUTH_USER_MODEL, models.CASCADE, verbose_name=_('user'), ) ip_addr = models.GenericIPAddressField(_('action ip'), blank=True, null=True) content_type = models.ForeignKey( ContentType, models.SET_NULL, verbose_name=_('content type'), blank=True, null=True, ) object_id = models.TextField(_('object id'), blank=True, null=True) object_repr = models.CharField(_('object repr'), max_length=200) action_flag = models.CharField(_('action flag'), max_length=32) message = models.TextField(_('change message'), blank=True) class Meta: verbose_name = _('log entry') verbose_name_plural = _('log entries') ordering = ('-action_time',) def __repr__(self): return smart_text(self.action_time) def __str__(self): if self.action_flag == 'create': return ugettext('Added "%(object)s".') % {'object': self.object_repr} elif self.action_flag == 'change': return ugettext('Changed "%(object)s" - %(changes)s') % { 'object': self.object_repr, 'changes': self.message, } elif self.action_flag == 'delete' and self.object_repr: return ugettext('Deleted "%(object)s."') % {'object': self.object_repr} return self.message def get_edited_object(self): "Returns the edited object represented by this log entry" return self.content_type.get_object_for_this_type(pk=self.object_id)
34.822917
119
0.653006
ace8a5b15505196caad4b8edc77e57269bf3d785
10,999
py
Python
mfcc.py
CoolDadHacking/thesis
fd07e9916ca3313320b80f07d4e376a739469015
[ "Apache-2.0" ]
null
null
null
mfcc.py
CoolDadHacking/thesis
fd07e9916ca3313320b80f07d4e376a739469015
[ "Apache-2.0" ]
null
null
null
mfcc.py
CoolDadHacking/thesis
fd07e9916ca3313320b80f07d4e376a739469015
[ "Apache-2.0" ]
null
null
null
# calculate filterbank features. Provides e.g. fbank and mfcc features for use in ASR applications # Author: James Lyons 2012 from __future__ import division import numpy from python_speech_features import sigproc from scipy.fftpack import dct def mfcc(signal,samplerate=16000,winlen=0.025,winstep=0.01,numcep=13, nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97,ceplifter=22,appendEnergy=True, winfunc=lambda x:numpy.ones((x,))): """Compute MFCC features from an audio signal. :param signal: the audio signal from which to compute features. Should be an N*1 array :param samplerate: the samplerate of the signal we are working with. :param winlen: the length of the analysis window in seconds. Default is 0.025s (25 milliseconds) :param winstep: the step between successive windows in seconds. Default is 0.01s (10 milliseconds) :param numcep: the number of cepstrum to return, default 13 :param nfilt: the number of filters in the filterbank, default 26. :param nfft: the FFT size. Default is 512. :param lowfreq: lowest band edge of mel filters. In Hz, default is 0. :param highfreq: highest band edge of mel filters. In Hz, default is samplerate/2 :param preemph: apply preemphasis filter with preemph as coefficient. 0 is no filter. Default is 0.97. :param ceplifter: apply a lifter to final cepstral coefficients. 0 is no lifter. Default is 22. :param appendEnergy: if this is true, the zeroth cepstral coefficient is replaced with the log of the total frame energy. :param winfunc: the analysis window to apply to each frame. By default no window is applied. :returns: A numpy array of size (NUMFRAMES by numcep) containing features. Each row holds 1 feature vector. """ feat,energy = fbank(signal,samplerate,winlen,winstep,nfilt,nfft,lowfreq,highfreq,preemph,winfunc) feat = numpy.log(feat) feat = dct(feat, type=2, axis=1, norm='ortho')[:,:numcep] feat = lifter(feat,ceplifter) if appendEnergy: feat[:,0] = numpy.log(energy) # replace first cepstral coefficient with log of frame energy return feat def fbank(signal,samplerate=16000,winlen=0.025,winstep=0.01, nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97, winfunc=lambda x:numpy.ones((x,))): """Compute Mel-filterbank energy features from an audio signal. :param signal: the audio signal from which to compute features. Should be an N*1 array :param samplerate: the samplerate of the signal we are working with. :param winlen: the length of the analysis window in seconds. Default is 0.025s (25 milliseconds) :param winstep: the step between successive windows in seconds. Default is 0.01s (10 milliseconds) :param nfilt: the number of filters in the filterbank, default 26. :param nfft: the FFT size. Default is 512. :param lowfreq: lowest band edge of mel filters. In Hz, default is 0. :param highfreq: highest band edge of mel filters. In Hz, default is samplerate/2 :param preemph: apply preemphasis filter with preemph as coefficient. 0 is no filter. Default is 0.97. :param winfunc: the analysis window to apply to each frame. By default no window is applied. :returns: 2 values. The first is a numpy array of size (NUMFRAMES by nfilt) containing features. Each row holds 1 feature vector. The second return value is the energy in each frame (total energy, unwindowed) """ highfreq= highfreq or samplerate/2 signal = sigproc.preemphasis(signal,preemph) frames = sigproc.framesig(signal, winlen*samplerate, winstep*samplerate, winfunc) pspec = sigproc.powspec(frames,nfft) energy = numpy.sum(pspec,1) # this stores the total energy in each frame energy = numpy.where(energy == 0,numpy.finfo(float).eps,energy) # if energy is zero, we get problems with log fb = get_filterbanks(nfilt,nfft,samplerate,lowfreq,highfreq) feat = numpy.dot(pspec,fb.T) # compute the filterbank energies feat = numpy.where(feat == 0,numpy.finfo(float).eps,feat) # if feat is zero, we get problems with log return feat,energy def logfbank(signal,samplerate=16000,winlen=0.025,winstep=0.01, nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97): """Compute log Mel-filterbank energy features from an audio signal. :param signal: the audio signal from which to compute features. Should be an N*1 array :param samplerate: the samplerate of the signal we are working with. :param winlen: the length of the analysis window in seconds. Default is 0.025s (25 milliseconds) :param winstep: the step between successive windows in seconds. Default is 0.01s (10 milliseconds) :param nfilt: the number of filters in the filterbank, default 26. :param nfft: the FFT size. Default is 512. :param lowfreq: lowest band edge of mel filters. In Hz, default is 0. :param highfreq: highest band edge of mel filters. In Hz, default is samplerate/2 :param preemph: apply preemphasis filter with preemph as coefficient. 0 is no filter. Default is 0.97. :returns: A numpy array of size (NUMFRAMES by nfilt) containing features. Each row holds 1 feature vector. """ feat,energy = fbank(signal,samplerate,winlen,winstep,nfilt,nfft,lowfreq,highfreq,preemph) return numpy.log(feat) def ssc(signal,samplerate=16000,winlen=0.025,winstep=0.01, nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97, winfunc=lambda x:numpy.ones((x,))): """Compute Spectral Subband Centroid features from an audio signal. :param signal: the audio signal from which to compute features. Should be an N*1 array :param samplerate: the samplerate of the signal we are working with. :param winlen: the length of the analysis window in seconds. Default is 0.025s (25 milliseconds) :param winstep: the step between successive windows in seconds. Default is 0.01s (10 milliseconds) :param nfilt: the number of filters in the filterbank, default 26. :param nfft: the FFT size. Default is 512. :param lowfreq: lowest band edge of mel filters. In Hz, default is 0. :param highfreq: highest band edge of mel filters. In Hz, default is samplerate/2 :param preemph: apply preemphasis filter with preemph as coefficient. 0 is no filter. Default is 0.97. :param winfunc: the analysis window to apply to each frame. By default no window is applied. :returns: A numpy array of size (NUMFRAMES by nfilt) containing features. Each row holds 1 feature vector. """ highfreq= highfreq or samplerate/2 signal = sigproc.preemphasis(signal,preemph) frames = sigproc.framesig(signal, winlen*samplerate, winstep*samplerate, winfunc) pspec = sigproc.powspec(frames,nfft) pspec = numpy.where(pspec == 0,numpy.finfo(float).eps,pspec) # if things are all zeros we get problems fb = get_filterbanks(nfilt,nfft,samplerate,lowfreq,highfreq) feat = numpy.dot(pspec,fb.T) # compute the filterbank energies R = numpy.tile(numpy.linspace(1,samplerate/2,numpy.size(pspec,1)),(numpy.size(pspec,0),1)) return numpy.dot(pspec*R,fb.T) / feat def hz2mel(hz): """Convert a value in Hertz to Mels :param hz: a value in Hz. This can also be a numpy array, conversion proceeds element-wise. :returns: a value in Mels. If an array was passed in, an identical sized array is returned. """ return 2595 * numpy.log10(1+hz/700.) def mel2hz(mel): """Convert a value in Mels to Hertz :param mel: a value in Mels. This can also be a numpy array, conversion proceeds element-wise. :returns: a value in Hertz. If an array was passed in, an identical sized array is returned. """ return 700*(10**(mel/2595.0)-1) def get_filterbanks(nfilt=20,nfft=512,samplerate=16000,lowfreq=0,highfreq=None): """Compute a Mel-filterbank. The filters are stored in the rows, the columns correspond to fft bins. The filters are returned as an array of size nfilt * (nfft/2 + 1) :param nfilt: the number of filters in the filterbank, default 20. :param nfft: the FFT size. Default is 512. :param samplerate: the samplerate of the signal we are working with. Affects mel spacing. :param lowfreq: lowest band edge of mel filters, default 0 Hz :param highfreq: highest band edge of mel filters, default samplerate/2 :returns: A numpy array of size nfilt * (nfft/2 + 1) containing filterbank. Each row holds 1 filter. """ highfreq= highfreq or samplerate/2 assert highfreq <= samplerate/2, "highfreq is greater than samplerate/2" # compute points evenly spaced in mels lowmel = hz2mel(lowfreq) highmel = hz2mel(highfreq) melpoints = numpy.linspace(lowmel,highmel,nfilt+2) # our points are in Hz, but we use fft bins, so we have to convert # from Hz to fft bin number bin = numpy.floor((nfft+1)*mel2hz(melpoints)/samplerate) fbank = numpy.zeros([nfilt,nfft//2+1]) for j in range(0,nfilt): for i in range(int(bin[j]), int(bin[j+1])): fbank[j,i] = (i - bin[j]) / (bin[j+1]-bin[j]) for i in range(int(bin[j+1]), int(bin[j+2])): fbank[j,i] = (bin[j+2]-i) / (bin[j+2]-bin[j+1]) return fbank def lifter(cepstra, L=22): """Apply a cepstral lifter the the matrix of cepstra. This has the effect of increasing the magnitude of the high frequency DCT coeffs. :param cepstra: the matrix of mel-cepstra, will be numframes * numcep in size. :param L: the liftering coefficient to use. Default is 22. L <= 0 disables lifter. """ if L > 0: nframes,ncoeff = numpy.shape(cepstra) n = numpy.arange(ncoeff) lift = 1 + (L/2.)*numpy.sin(numpy.pi*n/L) return lift*cepstra else: # values of L <= 0, do nothing return cepstra def delta(feat, N): """Compute delta features from a feature vector sequence. :param feat: A numpy array of size (NUMFRAMES by number of features) containing features. Each row holds 1 feature vector. :param N: For each frame, calculate delta features based on preceding and following N frames :returns: A numpy array of size (NUMFRAMES by number of features) containing delta features. Each row holds 1 delta feature vector. """ if N < 1: raise ValueError('N must be an integer >= 1') NUMFRAMES = len(feat) denominator = 2 * sum([i**2 for i in range(1, N+1)]) delta_feat = numpy.empty_like(feat) padded = numpy.pad(feat, ((N, N), (0, 0)), mode='edge') # padded version of feat for t in range(NUMFRAMES): delta_feat[t] = numpy.dot(numpy.arange(-N, N+1), padded[t : t+2*N+1]) / denominator # [t : t+2*N+1] == [(N+t)-N : (N+t)+N+1] return delta_feat
60.434066
138
0.690517
ace8a63b67626db1d5d9d7907b7715f9a6443a79
748
py
Python
tests/test_client.py
xspdr/wex-api-client
b85b3a9ff6bd1e53e8893a8220c492c1e0dc541f
[ "MIT" ]
null
null
null
tests/test_client.py
xspdr/wex-api-client
b85b3a9ff6bd1e53e8893a8220c492c1e0dc541f
[ "MIT" ]
null
null
null
tests/test_client.py
xspdr/wex-api-client
b85b3a9ff6bd1e53e8893a8220c492c1e0dc541f
[ "MIT" ]
null
null
null
import unittest from wex.client import Client class TetClient(unittest.TestCase): def setUp(self): self.client = Client() def test_info(self): result = self.client.info() assert 'pairs' in result def test_ticker(self): result = self.client.ticker(['btc_usd', 'eth_usd']) assert result['btc_usd']['high'] >= result['btc_usd']['low'] def test_depth(self): result = self.client.depth('btc_usd', 'fake_fake', ignore_invalid=1) assert all(k in ('bids', 'asks') for k in result['btc_usd'].keys()) def test_trades(self): result = self.client.trades('btc_usd', limit=21) assert len(result['btc_usd']) == 21 if __name__ == '__main__': unittest.main()
24.933333
76
0.621658
ace8a70981d2b82b3a25b8c21b1ec51051d0488b
727
py
Python
Get Retroativo/2017_08.py
paulowiz/AiesecBot
ac77cc5426ed6382772603afa8015208020c0fba
[ "MIT" ]
6
2019-10-18T17:47:30.000Z
2021-03-18T06:04:06.000Z
Get Retroativo/2017_08.py
paulowiz/AiesecBot
ac77cc5426ed6382772603afa8015208020c0fba
[ "MIT" ]
1
2020-09-24T08:17:29.000Z
2020-09-28T08:16:39.000Z
Get Retroativo/2017_08.py
paulowiz/AiesecBot
ac77cc5426ed6382772603afa8015208020c0fba
[ "MIT" ]
3
2019-10-20T18:40:20.000Z
2021-04-15T01:27:59.000Z
import psycopg2.extras from controller import RobotRotine as rr from api import graphqlconsume, querygraphql import time import datetime import numpy as np """ current = np.datetime64(datetime.datetime.now()) currentab = np.datetime64(current) + np.timedelta64(5, 'h') lastdate = np.datetime64(currentab) - np.timedelta64(15, 'm') print(lastdate) print(currentab) print('-') """ robo5 = rr.RobotRotine() i = 0 dtinit = '2017-08-01T00:00:00' while i < 31: print(dtinit) dtfim = np.datetime64(dtinit) + np.timedelta64(24, 'h') robo5.ExecutaRotina('created_at', dtinit, dtfim, 1) i = i+1 dtinit = np.datetime64(dtinit) + np.timedelta64(24, 'h') print('Periodo Executado com sucesso')
25.964286
61
0.69326
ace8a822229e172e59fafcf90a167831a5a06181
2,956
py
Python
fairseq/modules/__init__.py
vinodganesan/hardware-aware-transformers
6243559f3186b1ed4836831352a569b68575125e
[ "MIT" ]
null
null
null
fairseq/modules/__init__.py
vinodganesan/hardware-aware-transformers
6243559f3186b1ed4836831352a569b68575125e
[ "MIT" ]
null
null
null
fairseq/modules/__init__.py
vinodganesan/hardware-aware-transformers
6243559f3186b1ed4836831352a569b68575125e
[ "MIT" ]
null
null
null
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """isort:skip_file""" from .adaptive_input import AdaptiveInput from .adaptive_softmax import AdaptiveSoftmax from .beamable_mm import BeamableMM from .character_token_embedder import CharacterTokenEmbedder from .conv_tbc import ConvTBC from .cross_entropy import cross_entropy from .downsampled_multihead_attention import DownsampledMultiHeadAttention from .dynamic_convolution import DynamicConv, DynamicConv1dTBC from .multihead_attention_super import MultiheadAttentionSuper from .dynamic_crf_layer import DynamicCRF from .fairseq_dropout import FairseqDropout from .fp32_group_norm import Fp32GroupNorm from .gelu import gelu, gelu_accurate from .grad_multiply import GradMultiply from .gumbel_vector_quantizer import GumbelVectorQuantizer from .kmeans_vector_quantizer import KmeansVectorQuantizer from .layer_drop import LayerDropModuleList from .layer_norm import Fp32LayerNorm, LayerNorm from .learned_positional_embedding import LearnedPositionalEmbedding from .lightweight_convolution import LightweightConv, LightweightConv1dTBC from .linearized_convolution import LinearizedConvolution from .multihead_attention import MultiheadAttention from .positional_embedding import PositionalEmbedding from .same_pad import SamePad from .scalar_bias import ScalarBias from .sinusoidal_positional_embedding import SinusoidalPositionalEmbedding from .transformer_sentence_encoder_layer import TransformerSentenceEncoderLayer from .transformer_sentence_encoder import TransformerSentenceEncoder from .transpose_last import TransposeLast from .unfold import unfold1d from .transformer_layer import TransformerDecoderLayer, TransformerEncoderLayer from .vggblock import VGGBlock from .embedding_super import EmbeddingSuper from .linear_super import LinearSuper from .layer_norm import LayerNormSuper __all__ = [ "AdaptiveInput", "AdaptiveSoftmax", "BeamableMM", "CharacterTokenEmbedder", "ConvTBC", "cross_entropy", "DownsampledMultiHeadAttention", "DynamicConv1dTBC", "DynamicConv", "DynamicCRF", "FairseqDropout", "Fp32GroupNorm", "Fp32LayerNorm", "gelu", "gelu_accurate", "MultiheadAttentionSuper", "GradMultiply", "GumbelVectorQuantizer", "KmeansVectorQuantizer", "LayerDropModuleList", "LayerNorm", "LearnedPositionalEmbedding", "LightweightConv1dTBC", "LightweightConv", "LinearizedConvolution", "MultiheadAttention", "PositionalEmbedding", "SamePad", "ScalarBias", "SinusoidalPositionalEmbedding", "TransformerSentenceEncoderLayer", "TransformerSentenceEncoder", "TransformerDecoderLayer", "TransformerEncoderLayer", "TransposeLast", "VGGBlock", "unfold1d", "EmbeddingSuper", "LinearSuper", "LayerNormSuper" ]
33.977011
79
0.808525
ace8a85bc1d245c53575254cb5f4e4db18f5601a
11,902
py
Python
cp2_processing/radar_codes.py
joshua-wx/cp2_processing
bedf46709b3b3c6ca4037c99b22dc8f9ba1784df
[ "MIT" ]
null
null
null
cp2_processing/radar_codes.py
joshua-wx/cp2_processing
bedf46709b3b3c6ca4037c99b22dc8f9ba1784df
[ "MIT" ]
null
null
null
cp2_processing/radar_codes.py
joshua-wx/cp2_processing
bedf46709b3b3c6ca4037c99b22dc8f9ba1784df
[ "MIT" ]
null
null
null
""" Codes for correcting and estimating various radar and meteorological parameters. @title: radar_codes @author: Valentin Louf <valentin.louf@monash.edu> @institutions: Monash University and the Australian Bureau of Meteorology @creation: 04/04/2017 @date: 14/04/2020 .. autosummary:: :toctree: generated/ _my_snr_from_reflectivity _nearest check_azimuth check_reflectivity check_year correct_rhohv correct_zdr get_radiosoundings read_radar snr_and_sounding """ # Python Standard Library import os import re import glob import time import fnmatch from datetime import datetime # Other Libraries import pyart import scipy import cftime import netCDF4 import numpy as np import pandas as pd import xarray as xr def read_csv(csv_ffn, header_line): """ CSV reader used for the radar locations file (comma delimited) Parameters: =========== csv_ffn: str Full filename to csv file header_line: int or None to use first line of csv as header = 0, use None to use column index Returns: ======== as_dict: dict csv columns are dictionary """ df = pd.read_csv(csv_ffn, header=header_line) as_dict = df.to_dict(orient='list') return as_dict def read_cal_file(cal_ffn, radar_dt): """ read Z or ZDR calibration csv file into dictionary Parameters: =========== cal_ffn: str Full filename to csv file Returns: ======== cal_dict: dict calibration data as dictionary """ #load calibration file dict_in = read_csv(cal_ffn, None) cal_dict = {} #rename dictonary fields cal_dict['cal_start'] = np.array([datetime.strptime(str(date), '%Y%m%d').date() for date in dict_in[0]]) cal_dict['cal_end'] = np.array([datetime.strptime(str(date), '%Y%m%d').date() for date in dict_in[1]]) cal_dict['cal_mean'] = np.array(list(map(float, dict_in[2]))) #find offset value offset = 0 if cal_dict: caldt_mask = np.logical_and(radar_dt.date()>=cal_dict['cal_start'], radar_dt.date()<=cal_dict['cal_end']) offset_match = cal_dict['cal_mean'][caldt_mask] if len(offset_match) == 0: print('time period not found in cal file') elif len(offset_match) > 1: print('calibration data error (multiple matches)') else: offset = float(offset_match) else: error_msg = print('no cal file found') offset = 0 #return return offset def snr_from_reflectivity(radar, refl_field='DBZ'): """ Just in case pyart.retrieve.calculate_snr_from_reflectivity, I can calculate it 'by hand'. Parameter: =========== radar: Py-ART radar structure. refl_field_name: str Name of the reflectivity field. Return: ======= snr: dict Signal to noise ratio. """ range_grid, _ = np.meshgrid(radar.range['data'], radar.azimuth['data']) range_grid += 1 # Cause of 0 # remove range scale.. This is basically the radar constant scaled dBm pseudo_power = (radar.fields[refl_field]['data'] - 20.0 * np.log10(range_grid / 1000.0)) # The noise_floor_estimate can fail sometimes in pyart, that's the reason # why this whole function exists. noise_floor_estimate = -40 snr_data = pseudo_power - noise_floor_estimate return snr_data def _nearest(items, pivot): """ Find the nearest item. Parameters: =========== items: List of item. pivot: Item we're looking for. Returns: ======== item: Value of the nearest item found. """ return min(items, key=lambda x: abs(x - pivot)) def check_reflectivity(radar, refl_field_name='DBZ'): """ Checking if radar has a proper reflectivity field. It's a minor problem concerning a few days in 2011 for CPOL. Parameters: =========== radar: Py-ART radar structure. refl_field_name: str Name of the reflectivity field. Return: ======= True if radar has a non-empty reflectivity field. """ dbz = radar.fields[refl_field_name]['data'] if np.ma.isMaskedArray(dbz): if dbz.count() == 0: # Reflectivity field is empty. return False return True def correct_rhohv(radar, rhohv_name='RHOHV', snr_name='SNR'): """ Correct cross correlation ratio (RHOHV) from noise. From the Schuur et al. 2003 NOAA report (p7 eq 5) Parameters: =========== radar: Py-ART radar structure. rhohv_name: str Cross correlation field name. snr_name: str Signal to noise ratio field name. Returns: ======== rho_corr: array Corrected cross correlation ratio. """ rhohv = radar.fields[rhohv_name]['data'].copy() # snr = radar.fields[snr_name]['data'].copy() #appears to be done onsite at CP2 # natural_snr = 10**(0.1 * snr) # natural_snr = natural_snr.filled(-9999) # rho_corr = rhohv * (1 + 1 / natural_snr) rho_corr = rhohv # Not allowing the corrected RHOHV to be lower than the raw rhohv rho_corr[rho_corr > 1] = 1 rho_corr[np.isnan(rho_corr) | (rho_corr < 0)] = 0 try: rho_corr = rho_corr.filled(1) except Exception: pass return np.ma.masked_array(rho_corr, rhohv.mask) def correct_standard_name(radar): """ 'standard_name' is a protected keyword for metadata in the CF conventions. To respect the CF conventions we can only use the standard_name field that exists in the CF table. Parameter: ========== radar: Radar object Py-ART data structure. """ try: radar.range.pop('standard_name') radar.azimuth.pop('standard_name') radar.elevation.pop('standard_name') except Exception: pass try: radar.sweep_number.pop('standard_name') radar.fixed_angle.pop('standard_name') radar.sweep_mode.pop('standard_name') except Exception: pass good_keys = ['corrected_reflectivity', 'total_power', 'radar_estimated_rain_rate', 'corrected_velocity'] for k in radar.fields.keys(): if k not in good_keys: try: radar.fields[k].pop('standard_name') except Exception: continue try: radar.fields['velocity']['standard_name'] = 'radial_velocity_of_scatterers_away_from_instrument' radar.fields['velocity']['long_name'] = 'Doppler radial velocity of scatterers away from instrument' except KeyError: pass radar.latitude['standard_name'] = 'latitude' radar.longitude['standard_name'] = 'longitude' radar.altitude['standard_name'] = 'altitude' return None def correct_zdr(radar, zdr_name='ZDR', snr_name='SNR'): """ Correct differential reflectivity (ZDR) from noise. From the Schuur et al. 2003 NOAA report (p7 eq 6) Parameters: =========== radar: Py-ART radar structure. zdr_name: str Differential reflectivity field name. snr_name: str Signal to noise ratio field name. Returns: ======== corr_zdr: array Corrected differential reflectivity. """ zdr = radar.fields[zdr_name]['data'].copy() snr = radar.fields[snr_name]['data'].copy() alpha = 1.48 natural_zdr = 10 ** (0.1 * zdr) natural_snr = 10 ** (0.1 * snr) corr_zdr = 10 * np.log10((alpha * natural_snr * natural_zdr) / (alpha * natural_snr + alpha - natural_zdr)) return corr_zdr def coverage_content_type(radar): """ Adding metadata for compatibility with ACDD-1.3 Parameter: ========== radar: Radar object Py-ART data structure. """ radar.range['coverage_content_type'] = 'coordinate' radar.azimuth['coverage_content_type'] = 'coordinate' radar.elevation['coverage_content_type'] = 'coordinate' radar.latitude['coverage_content_type'] = 'coordinate' radar.longitude['coverage_content_type'] = 'coordinate' radar.altitude['coverage_content_type'] = 'coordinate' radar.sweep_number['coverage_content_type'] = 'auxiliaryInformation' radar.fixed_angle['coverage_content_type'] = 'auxiliaryInformation' radar.sweep_mode['coverage_content_type'] = 'auxiliaryInformation' for k in radar.fields.keys(): if k == 'radar_echo_classification': radar.fields[k]['coverage_content_type'] = 'thematicClassification' elif k in ['normalized_coherent_power', 'normalized_coherent_power_v']: radar.fields[k]['coverage_content_type'] = 'qualityInformation' else: radar.fields[k]['coverage_content_type'] = 'physicalMeasurement' return None def read_radar(radar_file_name): """ Read the input radar file. Parameter: ========== radar_file_name: str Radar file name. Return: ======= radar: struct Py-ART radar structure. """ # Read the input radar file. try: #load radar radar = pyart.io.read_mdv(radar_file_name, file_field_names=True) except Exception: raise radar.fields['VEL']['units'] = "m s-1" return radar def temperature_profile(radar): """ Compute the signal-to-noise ratio as well as interpolating the radiosounding temperature on to the radar grid. The function looks for the radiosoundings that happened at the closest time from the radar. There is no time difference limit. Parameters: =========== radar: Py-ART radar object. Returns: ======== z_dict: dict Altitude in m, interpolated at each radar gates. temp_info_dict: dict Temperature in Celsius, interpolated at each radar gates. """ #set era path era5_root = '/g/data/ub4/era5/netcdf/pressure' #extract request data request_lat = radar.latitude['data'][0] request_lon = radar.longitude['data'][0] request_dt = pd.Timestamp(cftime.num2pydate(radar.time['data'][0], radar.time['units'])) #build file paths month_str = request_dt.month year_str = request_dt.year temp_ffn = glob.glob(f'{era5_root}/t/{year_str}/t_era5_aus_{year_str}{month_str:02}*.nc')[0] geop_ffn = glob.glob(f'{era5_root}/z/{year_str}/z_era5_aus_{year_str}{month_str:02}*.nc')[0] #extract data with xr.open_dataset(temp_ffn) as temp_ds: temp_data = temp_ds.t.sel(longitude=request_lon, method='nearest').sel(latitude=request_lat, method='nearest').sel(time=request_dt, method='nearest').data[:] - 273.15 #units: deg K -> C with xr.open_dataset(geop_ffn) as geop_ds: geop_data = geop_ds.z.sel(longitude=request_lon, method='nearest').sel(latitude=request_lat, method='nearest').sel(time=request_dt, method='nearest').data[:]/9.80665 #units: m**2 s**-2 -> m #flipdata (ground is first row) temp_data = np.flipud(temp_data) geop_data = np.flipud(geop_data) #append surface data using lowest level geop_data = np.append(geop_data,[0]) temp_data = np.append(temp_data, temp_data[-1]) z_dict, temp_dict = pyart.retrieve.map_profile_to_gates(temp_data, geop_data, radar) temp_info_dict = {'data': temp_dict['data'], # Switch to celsius. 'long_name': 'Sounding temperature at gate', 'standard_name': 'temperature', 'valid_min': -100, 'valid_max': 100, 'units': 'degrees Celsius', 'comment': 'Radiosounding date: %s' % (request_dt.strftime("%Y/%m/%d"))} return z_dict, temp_info_dict
29.606965
197
0.627542
ace8a8f8a938a9bc9250863a3f923cf1f73b0e2b
475
py
Python
Python/Ex103.py
EspagueteTV/Meus-Estudos-CursoEmVideo
1bf3cc367bc754625a3fd59114ab63470e8d934b
[ "MIT" ]
null
null
null
Python/Ex103.py
EspagueteTV/Meus-Estudos-CursoEmVideo
1bf3cc367bc754625a3fd59114ab63470e8d934b
[ "MIT" ]
null
null
null
Python/Ex103.py
EspagueteTV/Meus-Estudos-CursoEmVideo
1bf3cc367bc754625a3fd59114ab63470e8d934b
[ "MIT" ]
null
null
null
def ficha(jog='<desconhecido>', gol=0): """ -> Mostrar o nome e quantidade de gols de um jogador :param n: Nome do jogador :param g: Quantidade de gols do jogador :return: sem retorno """ print(f'O jogador {jog} fez {gol} gol(s) no campeonato') #Programa Principal: n = str(input('Nome do jogador: ')) g = str(input('Número de gols: ')) if g.isnumeric(): g = int(g) else: g = 0 if n.strip() == '': ficha(gol=g) else: ficha(n, g)
21.590909
60
0.595789
ace8a927d84a896120e353dbefa19aa142148e26
424
py
Python
pucadmin/organisations/migrations/0005_alter_course_name.py
JobDoesburg/PUC-admin
ab61478cbf1cb0ddb57661a7508e70b23642810b
[ "MIT" ]
null
null
null
pucadmin/organisations/migrations/0005_alter_course_name.py
JobDoesburg/PUC-admin
ab61478cbf1cb0ddb57661a7508e70b23642810b
[ "MIT" ]
null
null
null
pucadmin/organisations/migrations/0005_alter_course_name.py
JobDoesburg/PUC-admin
ab61478cbf1cb0ddb57661a7508e70b23642810b
[ "MIT" ]
null
null
null
# Generated by Django 3.2.5 on 2021-12-04 19:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("organisations", "0004_auto_20210718_1147"), ] operations = [ migrations.AlterField( model_name="course", name="name", field=models.CharField(max_length=40, unique=True, verbose_name="name"), ), ]
22.315789
84
0.615566
ace8a99fb7930e656b74e5f926f00f12a7c8d40b
33,250
py
Python
tuf/formats.py
omerlh/tuf
f496c83e78b05c2f50a0bd5dde197782a839177b
[ "Apache-2.0", "MIT" ]
1
2021-07-03T18:53:46.000Z
2021-07-03T18:53:46.000Z
tuf/formats.py
omerlh/tuf
f496c83e78b05c2f50a0bd5dde197782a839177b
[ "Apache-2.0", "MIT" ]
57
2021-01-14T14:34:34.000Z
2022-03-17T10:11:53.000Z
tuf/formats.py
menendezjaume/tuf
41f7e809fef4cfe578cd2bd96f497da74b1bce15
[ "Apache-2.0", "MIT" ]
null
null
null
#!/usr/bin/env python # Copyright 2012 - 2017, New York University and the TUF contributors # SPDX-License-Identifier: MIT OR Apache-2.0 """ <Program Name> formats.py <Author> Geremy Condra Vladimir Diaz <vladimir.v.diaz@gmail.com> <Started> Refactored April 30, 2012. -vladimir.v.diaz <Copyright> See LICENSE-MIT OR LICENSE for licensing information. <Purpose> A central location for all format-related checking of TUF objects. Some crypto-related formats may also be defined in securesystemslib. Note: 'formats.py' depends heavily on 'schema.py', so the 'schema.py' module should be read and understood before tackling this module. 'formats.py' can be broken down into two sections. (1) Schemas and object matching. (2) Functions that help produce or verify TUF objects. The first section deals with schemas and object matching based on format. There are two ways of checking the format of objects. The first method raises a 'securesystemslib.exceptions.FormatError' exception if the match fails and the other returns a Boolean result. tuf.formats.<SCHEMA>.check_match(object) tuf.formats.<SCHEMA>.matches(object) Example: rsa_key = {'keytype': 'rsa' 'keyid': 34892fc465ac76bc3232fab 'keyval': {'public': 'public_key', 'private': 'private_key'} securesystemslib.formats.RSAKEY_SCHEMA.check_match(rsa_key) securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key) In this example, if a dict key or dict value is missing or incorrect, the match fails. There are numerous variations of object checking provided by 'formats.py' and 'schema.py'. The second section contains miscellaneous functions related to the format of TUF objects. Example: signable_object = make_signable(unsigned_object) """ import binascii import calendar import datetime import time import copy from securesystemslib import exceptions as sslib_exceptions from securesystemslib import formats as sslib_formats from securesystemslib import schema as SCHEMA import tuf from tuf import exceptions # As per TUF spec 1.0.0 the spec version field must follow the Semantic # Versioning 2.0.0 (semver) format. The regex pattern is provided by semver. # https://semver.org/spec/v2.0.0.html#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string SEMVER_2_0_0_SCHEMA = SCHEMA.RegularExpression( r'(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)' r'(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)' r'(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?' r'(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?' ) SPECIFICATION_VERSION_SCHEMA = SCHEMA.OneOf([ # However, temporarily allow "1.0" for backwards-compatibility in tuf-0.12.PATCH. SCHEMA.String("1.0"), SEMVER_2_0_0_SCHEMA ]) # A datetime in 'YYYY-MM-DDTHH:MM:SSZ' ISO 8601 format. The "Z" zone designator # for the zero UTC offset is always used (i.e., a numerical offset is not # supported.) Example: '2015-10-21T13:20:00Z'. Note: This is a simple format # check, and an ISO8601 string should be fully verified when it is parsed. ISO8601_DATETIME_SCHEMA = SCHEMA.RegularExpression(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z') # An integer representing the numbered version of a metadata file. # Must be 1, or greater. METADATAVERSION_SCHEMA = SCHEMA.Integer(lo=0) # A relative file path (e.g., 'metadata/root/'). RELPATH_SCHEMA = SCHEMA.AnyString() RELPATHS_SCHEMA = SCHEMA.ListOf(RELPATH_SCHEMA) VERSIONINFO_SCHEMA = SCHEMA.Object( object_name = 'VERSIONINFO_SCHEMA', version = METADATAVERSION_SCHEMA) # A string representing a role's name. ROLENAME_SCHEMA = SCHEMA.AnyString() # A role's threshold value (i.e., the minimum number # of signatures required to sign a metadata file). # Must be 1 and greater. THRESHOLD_SCHEMA = SCHEMA.Integer(lo=1) # A hexadecimal value in '23432df87ab..' format. HEX_SCHEMA = SCHEMA.RegularExpression(r'[a-fA-F0-9]+') # A path hash prefix is a hexadecimal string. PATH_HASH_PREFIX_SCHEMA = HEX_SCHEMA # A list of path hash prefixes. PATH_HASH_PREFIXES_SCHEMA = SCHEMA.ListOf(PATH_HASH_PREFIX_SCHEMA) # Role object in {'keyids': [keydids..], 'name': 'ABC', 'threshold': 1, # 'paths':[filepaths..]} format. # TODO: This is not a role. In further #660-related PRs, fix it, similar to # the way I did in Uptane's TUF fork. ROLE_SCHEMA = SCHEMA.Object( object_name = 'ROLE_SCHEMA', name = SCHEMA.Optional(ROLENAME_SCHEMA), keyids = sslib_formats.KEYIDS_SCHEMA, threshold = THRESHOLD_SCHEMA, terminating = SCHEMA.Optional(sslib_formats.BOOLEAN_SCHEMA), paths = SCHEMA.Optional(RELPATHS_SCHEMA), path_hash_prefixes = SCHEMA.Optional(PATH_HASH_PREFIXES_SCHEMA)) # A dict of roles where the dict keys are role names and the dict values holding # the role data/information. ROLEDICT_SCHEMA = SCHEMA.DictOf( key_schema = ROLENAME_SCHEMA, value_schema = ROLE_SCHEMA) # A dictionary of ROLEDICT, where dictionary keys can be repository names, and # dictionary values containing information for each role available on the # repository (corresponding to the repository belonging to named repository in # the dictionary key) ROLEDICTDB_SCHEMA = SCHEMA.DictOf( key_schema = sslib_formats.NAME_SCHEMA, value_schema = ROLEDICT_SCHEMA) # Command argument list, as used by the CLI tool. # Example: {'keytype': ed25519, 'expires': 365,} COMMAND_SCHEMA = SCHEMA.DictOf( key_schema = sslib_formats.NAME_SCHEMA, value_schema = SCHEMA.Any()) # A dictionary holding version information. VERSION_SCHEMA = SCHEMA.Object( object_name = 'VERSION_SCHEMA', major = SCHEMA.Integer(lo=0), minor = SCHEMA.Integer(lo=0), fix = SCHEMA.Integer(lo=0)) # A value that is either True or False, on or off, etc. BOOLEAN_SCHEMA = SCHEMA.Boolean() # A hexadecimal value in '23432df87ab..' format. HASH_SCHEMA = SCHEMA.RegularExpression(r'[a-fA-F0-9]+') # A key identifier (e.g., a hexadecimal value identifying an RSA key). KEYID_SCHEMA = HASH_SCHEMA # A list of KEYID_SCHEMA. KEYIDS_SCHEMA = SCHEMA.ListOf(KEYID_SCHEMA) # The actual values of a key, as opposed to meta data such as a key type and # key identifier ('rsa', 233df889cb). For RSA keys, the key value is a pair of # public and private keys in PEM Format stored as strings. KEYVAL_SCHEMA = SCHEMA.Object( object_name = 'KEYVAL_SCHEMA', public = SCHEMA.AnyString(), private = SCHEMA.Optional(SCHEMA.AnyString())) # A generic TUF key. All TUF keys should be saved to metadata files in this # format. KEY_SCHEMA = SCHEMA.Object( object_name = 'KEY_SCHEMA', keytype = SCHEMA.AnyString(), keyval = KEYVAL_SCHEMA, expires = SCHEMA.Optional(ISO8601_DATETIME_SCHEMA)) # A dict where the dict keys hold a keyid and the dict values a key object. KEYDICT_SCHEMA = SCHEMA.DictOf( key_schema = KEYID_SCHEMA, value_schema = KEY_SCHEMA) # The format used by the key database to store keys. The dict keys hold a key # identifier and the dict values any object. The key database should store # key objects in the values (e.g., 'RSAKEY_SCHEMA', 'DSAKEY_SCHEMA'). KEYDB_SCHEMA = SCHEMA.DictOf( key_schema = KEYID_SCHEMA, value_schema = SCHEMA.Any()) # A schema holding the result of checking the signatures of a particular # 'SIGNABLE_SCHEMA' role. # For example, how many of the signatures for the 'Target' role are # valid? This SCHEMA holds this information. See 'sig.py' for # more information. SIGNATURESTATUS_SCHEMA = SCHEMA.Object( object_name = 'SIGNATURESTATUS_SCHEMA', threshold = SCHEMA.Integer(), good_sigs = KEYIDS_SCHEMA, bad_sigs = KEYIDS_SCHEMA, unknown_sigs = KEYIDS_SCHEMA, untrusted_sigs = KEYIDS_SCHEMA) # An integer representing length. Must be 0, or greater. LENGTH_SCHEMA = SCHEMA.Integer(lo=0) # A dict in {'sha256': '23432df87ab..', 'sha512': '34324abc34df..', ...} format. HASHDICT_SCHEMA = SCHEMA.DictOf( key_schema = SCHEMA.AnyString(), value_schema = HASH_SCHEMA) # Information about target files, like file length and file hash(es). This # schema allows the storage of multiple hashes for the same file (e.g., sha256 # and sha512 may be computed for the same file and stored). TARGETS_FILEINFO_SCHEMA = SCHEMA.Object( object_name = 'TARGETS_FILEINFO_SCHEMA', length = LENGTH_SCHEMA, hashes = HASHDICT_SCHEMA, custom = SCHEMA.Optional(SCHEMA.Object())) # Information about snapshot and timestamp files. This schema allows for optional # length and hashes, but version is mandatory. METADATA_FILEINFO_SCHEMA = SCHEMA.Object( object_name = 'METADATA_FILEINFO_SCHEMA', length = SCHEMA.Optional(LENGTH_SCHEMA), hashes = SCHEMA.Optional(HASHDICT_SCHEMA), version = METADATAVERSION_SCHEMA) # A dict holding the version or file information for a particular metadata # role. The dict keys hold the relative file paths, and the dict values the # corresponding version numbers and/or file information. FILEINFODICT_SCHEMA = SCHEMA.DictOf( key_schema = RELPATH_SCHEMA, value_schema = SCHEMA.OneOf([VERSIONINFO_SCHEMA, METADATA_FILEINFO_SCHEMA])) # A dict holding the information for a particular target / file. The dict keys # hold the relative file paths, and the dict values the corresponding file # information. FILEDICT_SCHEMA = SCHEMA.DictOf( key_schema = RELPATH_SCHEMA, value_schema = TARGETS_FILEINFO_SCHEMA) # A dict holding a target info. TARGETINFO_SCHEMA = SCHEMA.Object( object_name = 'TARGETINFO_SCHEMA', filepath = RELPATH_SCHEMA, fileinfo = TARGETS_FILEINFO_SCHEMA) # A list of TARGETINFO_SCHEMA. TARGETINFOS_SCHEMA = SCHEMA.ListOf(TARGETINFO_SCHEMA) # A string representing a named oject. NAME_SCHEMA = SCHEMA.AnyString() # A dict of repository names to mirrors. REPO_NAMES_TO_MIRRORS_SCHEMA = SCHEMA.DictOf( key_schema = NAME_SCHEMA, value_schema = SCHEMA.ListOf(sslib_formats.URL_SCHEMA)) # An object containing the map file's "mapping" attribute. MAPPING_SCHEMA = SCHEMA.ListOf(SCHEMA.Object( paths = RELPATHS_SCHEMA, repositories = SCHEMA.ListOf(NAME_SCHEMA), terminating = BOOLEAN_SCHEMA, threshold = THRESHOLD_SCHEMA)) # A dict containing the map file (named 'map.json', by default). The format of # the map file is covered in TAP 4: Multiple repository consensus on entrusted # targets. MAPFILE_SCHEMA = SCHEMA.Object( repositories = REPO_NAMES_TO_MIRRORS_SCHEMA, mapping = MAPPING_SCHEMA) # Like ROLEDICT_SCHEMA, except that ROLE_SCHEMA instances are stored in order. ROLELIST_SCHEMA = SCHEMA.ListOf(ROLE_SCHEMA) # The delegated roles of a Targets role (a parent). DELEGATIONS_SCHEMA = SCHEMA.Object( keys = KEYDICT_SCHEMA, roles = ROLELIST_SCHEMA) # The number of hashed bins, or the number of delegated roles. See # delegate_hashed_bins() in 'repository_tool.py' for an example. Note: # Tools may require further restrictions on the number of bins, such # as requiring them to be a power of 2. NUMBINS_SCHEMA = SCHEMA.Integer(lo=1) # The fileinfo format of targets specified in the repository and # developer tools. The fields match that of TARGETS_FILEINFO_SCHEMA, only all # fields are optional. CUSTOM_SCHEMA = SCHEMA.DictOf( key_schema = SCHEMA.AnyString(), value_schema = SCHEMA.Any() ) LOOSE_TARGETS_FILEINFO_SCHEMA = SCHEMA.Object( object_name = "LOOSE_TARGETS_FILEINFO_SCHEMA", length = SCHEMA.Optional(LENGTH_SCHEMA), hashes = SCHEMA.Optional(HASHDICT_SCHEMA), version = SCHEMA.Optional(METADATAVERSION_SCHEMA), custom = SCHEMA.Optional(SCHEMA.Object()) ) PATH_FILEINFO_SCHEMA = SCHEMA.DictOf( key_schema = RELPATH_SCHEMA, value_schema = LOOSE_TARGETS_FILEINFO_SCHEMA) # TUF roledb ROLEDB_SCHEMA = SCHEMA.Object( object_name = 'ROLEDB_SCHEMA', keyids = SCHEMA.Optional(KEYIDS_SCHEMA), signing_keyids = SCHEMA.Optional(KEYIDS_SCHEMA), previous_keyids = SCHEMA.Optional(KEYIDS_SCHEMA), threshold = SCHEMA.Optional(THRESHOLD_SCHEMA), previous_threshold = SCHEMA.Optional(THRESHOLD_SCHEMA), version = SCHEMA.Optional(METADATAVERSION_SCHEMA), expires = SCHEMA.Optional(ISO8601_DATETIME_SCHEMA), signatures = SCHEMA.Optional(sslib_formats.SIGNATURES_SCHEMA), paths = SCHEMA.Optional(SCHEMA.OneOf([RELPATHS_SCHEMA, PATH_FILEINFO_SCHEMA])), path_hash_prefixes = SCHEMA.Optional(PATH_HASH_PREFIXES_SCHEMA), delegations = SCHEMA.Optional(DELEGATIONS_SCHEMA), partial_loaded = SCHEMA.Optional(BOOLEAN_SCHEMA)) # A signable object. Holds the signing role and its associated signatures. SIGNABLE_SCHEMA = SCHEMA.Object( object_name = 'SIGNABLE_SCHEMA', signed = SCHEMA.Any(), signatures = SCHEMA.ListOf(sslib_formats.SIGNATURE_SCHEMA)) # Root role: indicates root keys and top-level roles. ROOT_SCHEMA = SCHEMA.Object( object_name = 'ROOT_SCHEMA', _type = SCHEMA.String('root'), spec_version = SPECIFICATION_VERSION_SCHEMA, version = METADATAVERSION_SCHEMA, consistent_snapshot = BOOLEAN_SCHEMA, expires = ISO8601_DATETIME_SCHEMA, keys = KEYDICT_SCHEMA, roles = ROLEDICT_SCHEMA) # Targets role: Indicates targets and delegates target paths to other roles. TARGETS_SCHEMA = SCHEMA.Object( object_name = 'TARGETS_SCHEMA', _type = SCHEMA.String('targets'), spec_version = SPECIFICATION_VERSION_SCHEMA, version = METADATAVERSION_SCHEMA, expires = ISO8601_DATETIME_SCHEMA, targets = FILEDICT_SCHEMA, delegations = SCHEMA.Optional(DELEGATIONS_SCHEMA)) # Snapshot role: indicates the latest versions of all metadata (except # timestamp). SNAPSHOT_SCHEMA = SCHEMA.Object( object_name = 'SNAPSHOT_SCHEMA', _type = SCHEMA.String('snapshot'), version = METADATAVERSION_SCHEMA, expires = sslib_formats.ISO8601_DATETIME_SCHEMA, spec_version = SPECIFICATION_VERSION_SCHEMA, meta = FILEINFODICT_SCHEMA) # Timestamp role: indicates the latest version of the snapshot file. TIMESTAMP_SCHEMA = SCHEMA.Object( object_name = 'TIMESTAMP_SCHEMA', _type = SCHEMA.String('timestamp'), spec_version = SPECIFICATION_VERSION_SCHEMA, version = METADATAVERSION_SCHEMA, expires = sslib_formats.ISO8601_DATETIME_SCHEMA, meta = FILEINFODICT_SCHEMA) # project.cfg file: stores information about the project in a json dictionary PROJECT_CFG_SCHEMA = SCHEMA.Object( object_name = 'PROJECT_CFG_SCHEMA', project_name = SCHEMA.AnyString(), layout_type = SCHEMA.OneOf([SCHEMA.String('repo-like'), SCHEMA.String('flat')]), targets_location = sslib_formats.PATH_SCHEMA, metadata_location = sslib_formats.PATH_SCHEMA, prefix = sslib_formats.PATH_SCHEMA, public_keys = sslib_formats.KEYDICT_SCHEMA, threshold = SCHEMA.Integer(lo = 0, hi = 2) ) # A schema containing information a repository mirror may require, # such as a url, the path of the directory metadata files, etc. MIRROR_SCHEMA = SCHEMA.Object( object_name = 'MIRROR_SCHEMA', url_prefix = sslib_formats.URL_SCHEMA, metadata_path = SCHEMA.Optional(RELPATH_SCHEMA), targets_path = SCHEMA.Optional(RELPATH_SCHEMA), confined_target_dirs = SCHEMA.Optional(RELPATHS_SCHEMA), custom = SCHEMA.Optional(SCHEMA.Object())) # A dictionary of mirrors where the dict keys hold the mirror's name and # and the dict values the mirror's data (i.e., 'MIRROR_SCHEMA'). # The repository class of 'updater.py' accepts dictionaries # of this type provided by the TUF client. MIRRORDICT_SCHEMA = SCHEMA.DictOf( key_schema = SCHEMA.AnyString(), value_schema = MIRROR_SCHEMA) # A Mirrorlist: indicates all the live mirrors, and what documents they # serve. MIRRORLIST_SCHEMA = SCHEMA.Object( object_name = 'MIRRORLIST_SCHEMA', _type = SCHEMA.String('mirrors'), version = METADATAVERSION_SCHEMA, expires = sslib_formats.ISO8601_DATETIME_SCHEMA, mirrors = SCHEMA.ListOf(MIRROR_SCHEMA)) # Any of the role schemas (e.g., TIMESTAMP_SCHEMA, SNAPSHOT_SCHEMA, etc.) ANYROLE_SCHEMA = SCHEMA.OneOf([ROOT_SCHEMA, TARGETS_SCHEMA, SNAPSHOT_SCHEMA, TIMESTAMP_SCHEMA, MIRROR_SCHEMA]) # The format of the resulting "scp config dict" after extraction from the # push configuration file (i.e., push.cfg). In the case of a config file # utilizing the scp transfer module, it must contain the 'general' and 'scp' # sections, where 'general' must contain a 'transfer_module' and # 'metadata_path' entry, and 'scp' the 'host', 'user', 'identity_file', and # 'remote_directory' entries. SCPCONFIG_SCHEMA = SCHEMA.Object( object_name = 'SCPCONFIG_SCHEMA', general = SCHEMA.Object( object_name = '[general]', transfer_module = SCHEMA.String('scp'), metadata_path = sslib_formats.PATH_SCHEMA, targets_directory = sslib_formats.PATH_SCHEMA), scp=SCHEMA.Object( object_name = '[scp]', host = sslib_formats.URL_SCHEMA, user = sslib_formats.NAME_SCHEMA, identity_file = sslib_formats.PATH_SCHEMA, remote_directory = sslib_formats.PATH_SCHEMA)) # The format of the resulting "receive config dict" after extraction from the # receive configuration file (i.e., receive.cfg). The receive config file # must contain a 'general' section, and this section the 'pushroots', # 'repository_directory', 'metadata_directory', 'targets_directory', and # 'backup_directory' entries. RECEIVECONFIG_SCHEMA = SCHEMA.Object( object_name = 'RECEIVECONFIG_SCHEMA', general=SCHEMA.Object( object_name = '[general]', pushroots = SCHEMA.ListOf(sslib_formats.PATH_SCHEMA), repository_directory = sslib_formats.PATH_SCHEMA, metadata_directory = sslib_formats.PATH_SCHEMA, targets_directory = sslib_formats.PATH_SCHEMA, backup_directory = sslib_formats.PATH_SCHEMA)) def make_signable(role_schema): """ <Purpose> Return the role metadata 'role_schema' in 'SIGNABLE_SCHEMA' format. 'role_schema' is added to the 'signed' key, and an empty list initialized to the 'signatures' key. The caller adds signatures to this second field. Note: check_signable_object_format() should be called after make_signable() and signatures added to ensure the final signable object has a valid format (i.e., a signable containing a supported role metadata). <Arguments> role_schema: A role schema dict (e.g., 'ROOT_SCHEMA', 'SNAPSHOT_SCHEMA'). <Exceptions> None. <Side Effects> None. <Returns> A dict in 'SIGNABLE_SCHEMA' format. """ if not isinstance(role_schema, dict) or 'signed' not in role_schema: return { 'signed' : role_schema, 'signatures' : [] } else: return role_schema def build_dict_conforming_to_schema(schema, **kwargs): """ <Purpose> Given a schema.Object object (for example, TIMESTAMP_SCHEMA from this module) and a set of keyword arguments, create a dictionary that conforms to the given schema, using the keyword arguments to define the elements of the new dict. Checks the result to make sure that it conforms to the given schema, raising an error if not. <Arguments> schema A schema.Object, like TIMESTAMP_SCHEMA, TARGETS_FILEINFO_SCHEMA, securesystemslib.formats.SIGNATURE_SCHEMA, etc. **kwargs A keyword argument for each element of the schema. Optional arguments may be included or skipped, but all required arguments must be included. For example, for TIMESTAMP_SCHEMA, a call might look like: build_dict_conforming_to_schema( TIMESTAMP_SCHEMA, _type='timestamp', spec_version='1.0.0', version=1, expires='2020-01-01T00:00:00Z', meta={...}) Some arguments will be filled in if excluded: _type, spec_version <Returns> A dictionary conforming to the given schema. Adds certain required fields if they are missing and can be deduced from the schema. The data returned is a deep copy. <Exceptions> securesystemslib.exceptions.FormatError if the provided data does not match the schema when assembled. <Side Effects> None. In particular, the provided values are not modified, and the returned dictionary does not include references to them. """ # Check the schema argument type (must provide check_match and _required). if not isinstance(schema, SCHEMA.Object): raise ValueError( 'The first argument must be a schema.Object instance, but is not. ' 'Given schema: ' + repr(schema)) # Make a copy of the provided fields so that the caller's provided values # do not change when the returned values are changed. dictionary = copy.deepcopy(kwargs) # Automatically provide certain schema properties if they are not already # provided and are required in objects of class <schema>. # This includes: # _type: <securesystemslib.schema.String object> # spec_version: SPECIFICATION_VERSION_SCHEMA # # (Please note that _required is slightly misleading, as it includes both # required and optional elements. It should probably be called _components.) # for key, element_type in schema._required: #pylint: disable=protected-access if key in dictionary: # If the field has been provided, proceed normally. continue elif isinstance(element_type, SCHEMA.Optional): # If the field has NOT been provided but IS optional, proceed without it. continue else: # If the field has not been provided and is required, check to see if # the field is one of the fields we automatically fill. # Currently, the list is limited to ['_type', 'spec_version']. if key == '_type' and isinstance(element_type, SCHEMA.String): # A SCHEMA.String stores its expected value in _string, so use that. dictionary[key] = element_type._string #pylint: disable=protected-access elif (key == 'spec_version' and element_type == SPECIFICATION_VERSION_SCHEMA): # If not provided, use the specification version in tuf/__init__.py dictionary[key] = tuf.SPECIFICATION_VERSION # If what we produce does not match the provided schema, raise a FormatError. schema.check_match(dictionary) return dictionary # A dict holding the recognized schemas for the top-level roles. SCHEMAS_BY_TYPE = { 'root' : ROOT_SCHEMA, 'targets' : TARGETS_SCHEMA, 'snapshot' : SNAPSHOT_SCHEMA, 'timestamp' : TIMESTAMP_SCHEMA, 'mirrors' : MIRRORLIST_SCHEMA} def expiry_string_to_datetime(expires): """ <Purpose> Convert an expiry string to a datetime object. <Arguments> expires: The expiry date-time string in the ISO8601 format that is defined in securesystemslib.ISO8601_DATETIME_SCHEMA. E.g. '2038-01-19T03:14:08Z' <Exceptions> securesystemslib.exceptions.FormatError, if 'expires' cannot be parsed correctly. <Side Effects> None. <Returns> A datetime object representing the expiry time. """ # Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch. sslib_formats.ISO8601_DATETIME_SCHEMA.check_match(expires) try: return datetime.datetime.strptime(expires, "%Y-%m-%dT%H:%M:%SZ") except ValueError as error: raise sslib_exceptions.FormatError( 'Failed to parse ' + repr(expires) + ' as an expiry time') from error def datetime_to_unix_timestamp(datetime_object): """ <Purpose> Convert 'datetime_object' (in datetime.datetime()) format) to a Unix/POSIX timestamp. For example, Python's time.time() returns a Unix timestamp, and includes the number of microseconds. 'datetime_object' is converted to UTC. >>> datetime_object = datetime.datetime(1985, 10, 26, 1, 22) >>> timestamp = datetime_to_unix_timestamp(datetime_object) >>> timestamp 499137720 <Arguments> datetime_object: The datetime.datetime() object to convert to a Unix timestamp. <Exceptions> securesystemslib.exceptions.FormatError, if 'datetime_object' is not a datetime.datetime() object. <Side Effects> None. <Returns> A unix (posix) timestamp (e.g., 499137660). """ # Is 'datetime_object' a datetime.datetime() object? # Raise 'securesystemslib.exceptions.FormatError' if not. if not isinstance(datetime_object, datetime.datetime): message = repr(datetime_object) + ' is not a datetime.datetime() object.' raise sslib_exceptions.FormatError(message) unix_timestamp = calendar.timegm(datetime_object.timetuple()) return unix_timestamp def unix_timestamp_to_datetime(unix_timestamp): """ <Purpose> Convert 'unix_timestamp' (i.e., POSIX time, in UNIX_TIMESTAMP_SCHEMA format) to a datetime.datetime() object. 'unix_timestamp' is the number of seconds since the epoch (January 1, 1970.) >>> datetime_object = unix_timestamp_to_datetime(1445455680) >>> datetime_object datetime.datetime(2015, 10, 21, 19, 28) <Arguments> unix_timestamp: An integer representing the time (e.g., 1445455680). Conformant to 'securesystemslib.formats.UNIX_TIMESTAMP_SCHEMA'. <Exceptions> securesystemslib.exceptions.FormatError, if 'unix_timestamp' is improperly formatted. <Side Effects> None. <Returns> A datetime.datetime() object corresponding to 'unix_timestamp'. """ # Is 'unix_timestamp' properly formatted? # Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch. sslib_formats.UNIX_TIMESTAMP_SCHEMA.check_match(unix_timestamp) # Convert 'unix_timestamp' to a 'time.struct_time', in UTC. The Daylight # Savings Time (DST) flag is set to zero. datetime.fromtimestamp() is not # used because it returns a local datetime. struct_time = time.gmtime(unix_timestamp) # Extract the (year, month, day, hour, minutes, seconds) arguments for the # datetime object to be returned. datetime_object = datetime.datetime(*struct_time[:6]) return datetime_object def format_base64(data): """ <Purpose> Return the base64 encoding of 'data' with whitespace and '=' signs omitted. <Arguments> data: Binary or buffer of data to convert. <Exceptions> securesystemslib.exceptions.FormatError, if the base64 encoding fails or the argument is invalid. <Side Effects> None. <Returns> A base64-encoded string. """ try: return binascii.b2a_base64(data).decode('utf-8').rstrip('=\n ') except (TypeError, binascii.Error) as e: raise sslib_exceptions.FormatError('Invalid base64' ' encoding: ' + str(e)) def parse_base64(base64_string): """ <Purpose> Parse a base64 encoding with whitespace and '=' signs omitted. <Arguments> base64_string: A string holding a base64 value. <Exceptions> securesystemslib.exceptions.FormatError, if 'base64_string' cannot be parsed due to an invalid base64 encoding. <Side Effects> None. <Returns> A byte string representing the parsed based64 encoding of 'base64_string'. """ if not isinstance(base64_string, str): message = 'Invalid argument: '+repr(base64_string) raise sslib_exceptions.FormatError(message) extra = len(base64_string) % 4 if extra: padding = '=' * (4 - extra) base64_string = base64_string + padding try: return binascii.a2b_base64(base64_string.encode('utf-8')) except (TypeError, binascii.Error) as e: raise sslib_exceptions.FormatError('Invalid base64' ' encoding: ' + str(e)) def make_targets_fileinfo(length, hashes, custom=None): """ <Purpose> Create a dictionary conformant to 'TARGETS_FILEINFO_SCHEMA'. This dict describes a target file. <Arguments> length: An integer representing the size of the file. hashes: A dict of hashes in 'HASHDICT_SCHEMA' format, which has the form: {'sha256': 123df8a9b12, 'sha512': 324324dfc121, ...} custom: An optional object providing additional information about the file. <Exceptions> securesystemslib.exceptions.FormatError, if the 'TARGETS_FILEINFO_SCHEMA' to be returned does not have the correct format. <Returns> A dictionary conformant to 'TARGETS_FILEINFO_SCHEMA', representing the file information of a target file. """ fileinfo = {'length' : length, 'hashes' : hashes} if custom is not None: fileinfo['custom'] = custom # Raise 'securesystemslib.exceptions.FormatError' if the check fails. TARGETS_FILEINFO_SCHEMA.check_match(fileinfo) return fileinfo def make_metadata_fileinfo(version, length=None, hashes=None): """ <Purpose> Create a dictionary conformant to 'METADATA_FILEINFO_SCHEMA'. This dict describes one of the metadata files used for timestamp and snapshot roles. <Arguments> version: An integer representing the version of the file. length: An optional integer representing the size of the file. hashes: An optional dict of hashes in 'HASHDICT_SCHEMA' format, which has the form: {'sha256': 123df8a9b12, 'sha512': 324324dfc121, ...} <Exceptions> securesystemslib.exceptions.FormatError, if the 'METADATA_FILEINFO_SCHEMA' to be returned does not have the correct format. <Returns> A dictionary conformant to 'METADATA_FILEINFO_SCHEMA', representing the file information of a metadata file. """ fileinfo = {'version' : version} if length: fileinfo['length'] = length if hashes: fileinfo['hashes'] = hashes # Raise 'securesystemslib.exceptions.FormatError' if the check fails. METADATA_FILEINFO_SCHEMA.check_match(fileinfo) return fileinfo def make_versioninfo(version_number): """ <Purpose> Create a dictionary conformant to 'VERSIONINFO_SCHEMA'. This dict describes both metadata and target files. <Arguments> version_number: An integer representing the version of a particular metadata role. The dictionary returned by this function is expected to be included in Snapshot metadata. <Exceptions> securesystemslib.exceptions.FormatError, if the dict to be returned does not have the correct format (i.e., VERSIONINFO_SCHEMA). <Side Effects> None. <Returns> A dictionary conformant to 'VERSIONINFO_SCHEMA', containing the version information of a metadata role. """ versioninfo = {'version': version_number} # Raise 'securesystemslib.exceptions.FormatError' if 'versioninfo' is # improperly formatted. VERSIONINFO_SCHEMA.check_match(versioninfo) return versioninfo def expected_meta_rolename(meta_rolename): """ <Purpose> Ensure 'meta_rolename' is properly formatted. 'targets' is returned as 'Targets'. 'targets role1' is returned as 'Targets Role1'. The words in the string (i.e., separated by whitespace) are capitalized. <Arguments> meta_rolename: A string representing the rolename. E.g., 'root', 'targets'. <Exceptions> securesystemslib.exceptions.FormatError, if 'meta_rolename' is improperly formatted. <Side Effects> None. <Returns> A string (e.g., 'Root', 'Targets'). """ # Does 'meta_rolename' have the correct type? # This check ensures 'meta_rolename' conforms to # 'securesystemslib.formats.NAME_SCHEMA'. # Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch. sslib_formats.NAME_SCHEMA.check_match(meta_rolename) return meta_rolename.lower() def check_signable_object_format(signable): """ <Purpose> Ensure 'signable' is properly formatted, conformant to 'SIGNABLE_SCHEMA'. Return the signing role on success. Note: The 'signed' field of a 'SIGNABLE_SCHEMA' is checked against securesystemslib.schema.Any(). The 'signed' field, however, should actually hold one of the supported role schemas (e.g., 'ROOT_SCHEMA', 'TARGETS_SCHEMA'). The role schemas all differ in their format, so this function determines exactly which schema is listed in the 'signed' field. <Arguments> signable: The signable object compared against 'SIGNABLE.SCHEMA'. <Exceptions> securesystemslib.exceptions.FormatError, if 'signable' does not have the correct format. tuf.exceptions.UnsignedMetadataError, if 'signable' does not have any signatures <Side Effects> None. <Returns> A string representing the signing role (e.g., 'root', 'targets'). The role string is returned with characters all lower case. """ # Does 'signable' have the correct type? # This check ensures 'signable' conforms to # 'SIGNABLE_SCHEMA'. SIGNABLE_SCHEMA.check_match(signable) try: role_type = signable['signed']['_type'] except (KeyError, TypeError) as error: raise sslib_exceptions.FormatError('Untyped signable object.') from error try: schema = SCHEMAS_BY_TYPE[role_type] except KeyError as error: raise sslib_exceptions.FormatError('Unrecognized type ' + repr(role_type)) from error if not signable['signatures']: raise exceptions.UnsignedMetadataError('Signable object of type ' + repr(role_type) + ' has no signatures ', signable) # 'securesystemslib.exceptions.FormatError' raised if 'signable' does not # have a properly formatted role schema. schema.check_match(signable['signed']) return role_type.lower() if __name__ == '__main__': # The interactive sessions of the documentation strings can # be tested by running formats.py as a standalone module. # python -B formats.py import doctest doctest.testmod()
32.920792
108
0.735459
ace8abbc45a778dfafd830618a04fe4297f6216c
239
py
Python
code/trains/py202.py
ichengplus/python1024
5c9dd1dbb82f87f21e3b0e78c5fdc8386049bab0
[ "Apache-2.0" ]
null
null
null
code/trains/py202.py
ichengplus/python1024
5c9dd1dbb82f87f21e3b0e78c5fdc8386049bab0
[ "Apache-2.0" ]
8
2020-11-13T19:02:42.000Z
2022-01-13T03:13:41.000Z
code/trains/py202.py
ichengplus/python1024
5c9dd1dbb82f87f21e3b0e78c5fdc8386049bab0
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 """ 输入成绩 输出对应等级 Version: 0.0.1 Author : yichu.cheng """ s = float(input('输入成绩: ')) if s >= 90: g = 'A' elif s >= 80: g = 'B' elif s >= 70: g = 'C' elif s >= 60: g = 'D' else: g = 'E' print('对应等级:', g)
10.391304
26
0.464435
ace8ad599eec1d7aa3f7ec6e13573dc53250c762
6,144
py
Python
nova/tests/unit/scheduler/weights/test_weights_affinity.py
ebalduf/nova-backports
6bf97ec73467de522d34ab7a17ca0e0874baa7f9
[ "Apache-2.0" ]
5
2016-04-28T16:20:38.000Z
2021-04-25T11:19:03.000Z
nova/tests/unit/scheduler/weights/test_weights_affinity.py
ebalduf/nova-backports
6bf97ec73467de522d34ab7a17ca0e0874baa7f9
[ "Apache-2.0" ]
null
null
null
nova/tests/unit/scheduler/weights/test_weights_affinity.py
ebalduf/nova-backports
6bf97ec73467de522d34ab7a17ca0e0874baa7f9
[ "Apache-2.0" ]
5
2020-04-08T20:24:45.000Z
2020-10-05T19:02:13.000Z
# Copyright (c) 2015 Ericsson AB # 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. import mock from nova import objects from nova.scheduler import weights from nova.scheduler.weights import affinity from nova import test from nova.tests.unit.scheduler import fakes class SoftWeigherTestBase(test.NoDBTestCase): def setUp(self): super(SoftWeigherTestBase, self).setUp() self.weight_handler = weights.HostWeightHandler() self.weighers = [] def _get_weighed_host(self, hosts, policy): request_spec = objects.RequestSpec( instance_group=objects.InstanceGroup( policies=[policy], members=['member1', 'member2', 'member3', 'member4', 'member5', 'member6', 'member7'])) return self.weight_handler.get_weighed_objects(self.weighers, hosts, request_spec)[0] def _get_all_hosts(self): host_values = [ ('host1', 'node1', {'instances': { 'member1': mock.sentinel, 'instance13': mock.sentinel }}), ('host2', 'node2', {'instances': { 'member2': mock.sentinel, 'member3': mock.sentinel, 'member4': mock.sentinel, 'member5': mock.sentinel, 'instance14': mock.sentinel }}), ('host3', 'node3', {'instances': { 'instance15': mock.sentinel }}), ('host4', 'node4', {'instances': { 'member6': mock.sentinel, 'member7': mock.sentinel, 'instance16': mock.sentinel }})] return [fakes.FakeHostState(host, node, values) for host, node, values in host_values] def _do_test(self, policy, expected_weight, expected_host): hostinfo_list = self._get_all_hosts() weighed_host = self._get_weighed_host(hostinfo_list, policy) self.assertEqual(expected_weight, weighed_host.weight) if expected_host: self.assertEqual(expected_host, weighed_host.obj.host) class SoftAffinityWeigherTestCase(SoftWeigherTestBase): def setUp(self): super(SoftAffinityWeigherTestCase, self).setUp() self.weighers = [affinity.ServerGroupSoftAffinityWeigher()] def test_soft_affinity_weight_multiplier_by_default(self): self._do_test(policy='soft-affinity', expected_weight=1.0, expected_host='host2') def test_soft_affinity_weight_multiplier_zero_value(self): # We do not know the host, all have same weight. self.flags(soft_affinity_weight_multiplier=0.0) self._do_test(policy='soft-affinity', expected_weight=0.0, expected_host=None) def test_soft_affinity_weight_multiplier_positive_value(self): self.flags(soft_affinity_weight_multiplier=2.0) self._do_test(policy='soft-affinity', expected_weight=2.0, expected_host='host2') @mock.patch.object(affinity, 'LOG') def test_soft_affinity_weight_multiplier_negative_value(self, mock_log): self.flags(soft_affinity_weight_multiplier=-1.0) self._do_test(policy='soft-affinity', expected_weight=0.0, expected_host='host3') # call twice and assert that only one warning is emitted self._do_test(policy='soft-affinity', expected_weight=0.0, expected_host='host3') self.assertEqual(1, mock_log.warn.call_count) class SoftAntiAffinityWeigherTestCase(SoftWeigherTestBase): def setUp(self): super(SoftAntiAffinityWeigherTestCase, self).setUp() self.weighers = [affinity.ServerGroupSoftAntiAffinityWeigher()] def test_soft_anti_affinity_weight_multiplier_by_default(self): self._do_test(policy='soft-anti-affinity', expected_weight=1.0, expected_host='host3') def test_soft_anti_affinity_weight_multiplier_zero_value(self): # We do not know the host, all have same weight. self.flags(soft_anti_affinity_weight_multiplier=0.0) self._do_test(policy='soft-anti-affinity', expected_weight=0.0, expected_host=None) def test_soft_anti_affinity_weight_multiplier_positive_value(self): self.flags(soft_anti_affinity_weight_multiplier=2.0) self._do_test(policy='soft-anti-affinity', expected_weight=2.0, expected_host='host3') @mock.patch.object(affinity, 'LOG') def test_soft_anti_affinity_weight_multiplier_negative_value(self, mock_log): self.flags(soft_anti_affinity_weight_multiplier=-1.0) self._do_test(policy='soft-anti-affinity', expected_weight=0.0, expected_host='host2') # call twice and assert that only one warning is emitted self._do_test(policy='soft-anti-affinity', expected_weight=0.0, expected_host='host2') self.assertEqual(1, mock_log.warn.call_count)
39.896104
78
0.595378
ace8ae7e2ac2fbe3dc3d1c221b6f5d747937d663
350
py
Python
recipe/oven/drivers/standard_oven.py
juiceinc/recipe
ef3c5af58e2d68892d54285a24b78565f6401ef4
[ "MIT" ]
5
2017-10-26T10:44:07.000Z
2021-08-30T16:35:55.000Z
recipe/oven/drivers/standard_oven.py
juiceinc/recipe
ef3c5af58e2d68892d54285a24b78565f6401ef4
[ "MIT" ]
56
2017-10-23T14:01:37.000Z
2022-02-17T17:07:41.000Z
recipe/oven/drivers/standard_oven.py
juiceinc/recipe
ef3c5af58e2d68892d54285a24b78565f6401ef4
[ "MIT" ]
null
null
null
from recipe.oven.base import OvenBase class StandardOven(OvenBase): """Concrete Implementation of OvenBase """ def init_engine(self, connection_string=None, **kwargs): return super(StandardOven, self).init_engine(connection_string, **kwargs) def init_session(self): return super(StandardOven, self).init_session()
26.923077
81
0.722857
ace8aefeb489a082f2afd35767ff7ad3c3186ed3
16,122
py
Python
yasa/features.py
snwnde/yasa
71c0a8245c61b328a82ab1197c34b673333120a3
[ "BSD-3-Clause" ]
null
null
null
yasa/features.py
snwnde/yasa
71c0a8245c61b328a82ab1197c34b673333120a3
[ "BSD-3-Clause" ]
null
null
null
yasa/features.py
snwnde/yasa
71c0a8245c61b328a82ab1197c34b673333120a3
[ "BSD-3-Clause" ]
null
null
null
""" Sleep features. This file calculates a set of features from the PSG sleep data. These include: - Spectral power (with and without adjustement for 1/f) - Spindles and slow-waves detection - Slow-waves / spindles phase-amplitude coupling - Entropy and fractal dimension Author: Dr Raphael Vallat <raphaelvallat@berkeley.edu>, UC Berkeley. Date: March 2021 DANGER: This function has not been extensively debugged and validated. Use at your own risk. """ import mne import yasa import logging import numpy as np import pandas as pd import antropy as ant import scipy.signal as sp_sig import scipy.stats as sp_stats logger = logging.getLogger('yasa') __all__ = ['compute_features_stage'] def compute_features_stage(raw, hypno, max_freq=35, spindles_params=dict(), sw_params=dict(), do_1f=True): """Calculate a set of features for each sleep stage from PSG data. Features are calculated for N2, N3, NREM (= N2 + N3) and REM sleep. Parameters ---------- raw : :py:class:`mne.io.BaseRaw` An MNE Raw instance. hypno : array_like Sleep stage (hypnogram). The hypnogram must have the exact same number of samples as ``data``. To upsample your hypnogram, please refer to :py:func:`yasa.hypno_upsample_to_data`. .. note:: The default hypnogram format in YASA is a 1D integer vector where: - -2 = Unscored - -1 = Artefact / Movement - 0 = Wake - 1 = N1 sleep - 2 = N2 sleep - 3 = N3 sleep - 4 = REM sleep max_freq : int Maximum frequency. This will be used to bandpass-filter the data and to calculate 1 Hz bins bandpower. kwargs_sp : dict Optional keywords arguments that are passed to the :py:func:`yasa.spindles_detect` function. We strongly recommend adapting the thresholds to your population (e.g. more liberal for older adults). kwargs_sw : dict Optional keywords arguments that are passed to the :py:func:`yasa.sw_detect` function. We strongly recommend adapting the thresholds to your population (e.g. more liberal for older adults). Returns ------- feature : pd.DataFrame A long-format dataframe with stage and channel as index and all the calculated metrics as columns. """ # ######################################################################### # 1) PREPROCESSING # ######################################################################### # Safety checks assert isinstance(max_freq, int), "`max_freq` must be int." assert isinstance(raw, mne.io.BaseRaw), "`raw` must be a MNE Raw object." assert isinstance(spindles_params, dict) assert isinstance(sw_params, dict) # Define 1 Hz bins frequency bands for bandpower # Similar to [(0.5, 1, "0.5-1"), (1, 2, "1-2"), ..., (34, 35, "34-35")] bands = [] freqs = [0.5] + list(range(1, max_freq + 1)) for i, b in enumerate(freqs[:-1]): bands.append(tuple((b, freqs[i + 1], "%s-%s" % (b, freqs[i + 1])))) # Append traditional bands bands_classic = [ (0.5, 1, 'slowdelta'), (1, 4, 'fastdelta'), (0.5, 4, 'delta'), (4, 8, 'theta'), (8, 12, 'alpha'), (12, 16, 'sigma'), (16, 30, 'beta'), (30, max_freq, 'gamma')] bands = bands_classic + bands # Find min and maximum frequencies. These will be used for bandpass-filter # and 1/f adjustement of bandpower. l_freq = 0.5 / h_freq = 35 Hz. all_freqs_sorted = np.sort(np.unique( [b[0] for b in bands] + [b[1] for b in bands])) l_freq = all_freqs_sorted[0] h_freq = all_freqs_sorted[-1] # Mapping dictionnary integer to string for sleep stages (2 --> N2) stage_mapping = { -2: 'Unscored', -1: 'Artefact', 0: 'Wake', 1: 'N1', 2: 'N2', 3: 'N3', 4: 'REM', 6: 'NREM', 7: 'WN' # Whole night = N2 + N3 + REM } # Hypnogram check + calculate NREM hypnogram hypno = np.asarray(hypno, dtype=int) assert hypno.ndim == 1, 'Hypno must be one dimensional.' unique_hypno = np.unique(hypno) logger.info('Number of unique values in hypno = %i', unique_hypno.size) # IMPORTANT: NREM is defined as N2 + N3, excluding N1 sleep. hypno_NREM = pd.Series(hypno).replace({2: 6, 3: 6}).to_numpy() minutes_of_NREM = (hypno_NREM == 6).sum() / (60 * raw.info['sfreq']) # WN = Whole night = N2 + N3 + REM (excluding N1) hypno_WN = pd.Series(hypno).replace({2: 7, 3: 7, 4: 7}).to_numpy() # minutes_of_WN = (hypno_WN == 7).sum() / (60 * raw.info['sfreq']) # Keep only EEG channels and copy to avoid in-place modification raw_eeg = raw.copy().pick_types(eeg=True) # Remove flat channels bool_flat = raw_eeg.get_data().std(axis=1) == 0 chan_flat = np.array(raw_eeg.ch_names)[bool_flat].tolist() if len(chan_flat): logger.warning("Removing flat channel(s): %s" % chan_flat) raw_eeg.drop_channels(chan_flat) # Remove suffix from channels: C4-M1 --> C4 chan_nosuffix = [c.split('-')[0] for c in raw_eeg.ch_names] raw_eeg.rename_channels(dict(zip(raw_eeg.ch_names, chan_nosuffix))) # Rename P7/T5 --> P7 chan_noslash = [c.split('/')[0] for c in raw_eeg.ch_names] raw_eeg.rename_channels(dict(zip(raw_eeg.ch_names, chan_noslash))) chan = raw_eeg.ch_names # Resample to 100 Hz and bandpass-filter raw_eeg.resample(100, verbose=False) raw_eeg.filter(l_freq, h_freq, verbose=False) # Extract data and sf data = raw_eeg.get_data() * 1e6 # Scale from Volts (MNE default) to uV sf = raw_eeg.info['sfreq'] assert data.ndim == 2, 'data must be 2D (chan, times).' assert hypno.size == data.shape[1], 'Hypno must have same size as data.' # ######################################################################### # 2) SPECTRAL POWER # ######################################################################### print(" ..calculating spectral powers") # 2.1) 1Hz bins, N2 / N3 / REM # win_sec = 4 sec = 0.25 Hz freq resolution df_bp = yasa.bandpower(raw_eeg, hypno=hypno, bands=bands, win_sec=4, include=(2, 3, 4)) # Same for NREM / WN df_bp_NREM = yasa.bandpower(raw_eeg, hypno=hypno_NREM, bands=bands, include=6) df_bp_WN = yasa.bandpower(raw_eeg, hypno=hypno_WN, bands=bands, include=7) df_bp = pd.concat([df_bp, df_bp_NREM, df_bp_WN], axis=0) df_bp.drop(columns=['TotalAbsPow', 'FreqRes', 'Relative'], inplace=True) df_bp = df_bp.add_prefix('bp_').reset_index() # Replace 2 --> N2 df_bp['Stage'] = df_bp['Stage'].map(stage_mapping) # Assert that there are no negative values (see below issue on 1/f) assert not (df_bp._get_numeric_data() < 0).any().any() df_bp.columns = df_bp.columns.str.lower() # 2.2) Same but after adjusting for 1/F (VERY SLOW!) # This is based on the IRASA method described in Wen & Liu 2016. if do_1f: df_bp_1f = [] for stage in [2, 3, 4, 6, 7]: if stage == 6: # Use hypno_NREM data_stage = data[:, hypno_NREM == stage] elif stage == 7: # Use hypno_WN data_stage = data[:, hypno_WN == stage] else: data_stage = data[:, hypno == stage] # Skip if stage is not present in data if data_stage.shape[-1] == 0: continue # Calculate aperiodic / oscillatory PSD + slope freqs, _, psd_osc, fit_params = yasa.irasa( data_stage, sf, ch_names=chan, band=(l_freq, h_freq), win_sec=4) # Make sure that we don't have any negative values in PSD # See https://github.com/raphaelvallat/yasa/issues/29 psd_osc = psd_osc - psd_osc.min(axis=-1, keepdims=True) # Calculate bandpower bp = yasa.bandpower_from_psd(psd_osc, freqs, ch_names=chan, bands=bands) # Add 1/f slope to dataframe and sleep stage bp['1f_slope'] = np.abs(fit_params['Slope'].to_numpy()) bp.insert(loc=0, column="Stage", value=stage_mapping[stage]) df_bp_1f.append(bp) # Convert to a dataframe df_bp_1f = pd.concat(df_bp_1f) # Remove the TotalAbsPower column, incorrect because of negative values df_bp_1f.drop(columns=['TotalAbsPow', 'FreqRes', 'Relative'], inplace=True) df_bp_1f.columns = [c if c in ['Stage', 'Chan', '1f_slope'] else 'bp_adj_' + c for c in df_bp_1f.columns] assert not (df_bp_1f._get_numeric_data() < 0).any().any() df_bp_1f.columns = df_bp_1f.columns.str.lower() # Merge with the main bandpower dataframe df_bp = df_bp.merge(df_bp_1f, how="outer") # ######################################################################### # 3) SPINDLES DETECTION # ######################################################################### print(" ..detecting sleep spindles") spindles_params.update(include=(2, 3)) # Detect spindles in N2 and N3 # Thresholds have to be tuned with visual scoring of a subset of data # https://raphaelvallat.com/yasa/build/html/generated/yasa.spindles_detect.html sp = yasa.spindles_detect(raw_eeg, hypno=hypno, **spindles_params) df_sp = sp.summary(grp_chan=True, grp_stage=True).reset_index() df_sp['Stage'] = df_sp['Stage'].map(stage_mapping) # Aggregate using the mean (adding NREM = N2 + N3) df_sp = sp.summary(grp_chan=True, grp_stage=True) df_sp_NREM = sp.summary(grp_chan=True).reset_index() df_sp_NREM['Stage'] = 6 df_sp_NREM.set_index(['Stage', 'Channel'], inplace=True) density_NREM = df_sp_NREM['Count'] / minutes_of_NREM df_sp_NREM.insert(loc=1, column='Density', value=density_NREM.to_numpy()) df_sp = pd.concat([df_sp, df_sp_NREM], axis=0) df_sp.columns = ['sp_' + c if c in ['Count', 'Density'] else 'sp_mean_' + c for c in df_sp.columns] # Prepare to export df_sp.reset_index(inplace=True) df_sp['Stage'] = df_sp['Stage'].map(stage_mapping) df_sp.columns = df_sp.columns.str.lower() df_sp.rename(columns={'channel': 'chan'}, inplace=True) # ######################################################################### # 4) SLOW-WAVES DETECTION & SW-Sigma COUPLING # ######################################################################### print(" ..detecting slow-waves") # Make sure we calculate coupling sw_params.update(coupling=True) # Detect slow-waves # Option 1: Using absolute thresholds # IMPORTANT: THRESHOLDS MUST BE ADJUSTED ACCORDING TO AGE! sw = yasa.sw_detect(raw_eeg, hypno=hypno, **sw_params) # Aggregate using the mean per channel x stage df_sw = sw.summary(grp_chan=True, grp_stage=True) # Add NREM df_sw_NREM = sw.summary(grp_chan=True).reset_index() df_sw_NREM['Stage'] = 6 df_sw_NREM.set_index(['Stage', 'Channel'], inplace=True) density_NREM = df_sw_NREM['Count'] / minutes_of_NREM df_sw_NREM.insert(loc=1, column='Density', value=density_NREM.to_numpy()) df_sw = pd.concat([df_sw, df_sw_NREM]) df_sw = df_sw[['Count', 'Density', 'Duration', 'PTP', 'Frequency', 'ndPAC']] df_sw.columns = ['sw_' + c if c in ['Count', 'Density'] else 'sw_mean_' + c for c in df_sw.columns] # Aggregate using the coefficient of variation # The CV is a normalized (unitless) standard deviation. Lower # values mean that slow-waves are more similar to each other. # We keep only spefific columns of interest. Not duration because it # is highly correlated with frequency (r=0.99). df_sw_cv = sw.summary( grp_chan=True, grp_stage=True, aggfunc=sp_stats.variation )[['PTP', 'Frequency', 'ndPAC']] # Add NREM df_sw_cv_NREM = sw.summary( grp_chan=True, grp_stage=False, aggfunc=sp_stats.variation )[['PTP', 'Frequency', 'ndPAC']].reset_index() df_sw_cv_NREM['Stage'] = 6 df_sw_cv_NREM.set_index(['Stage', 'Channel'], inplace=True) df_sw_cv = pd.concat([df_sw_cv, df_sw_cv_NREM], axis=0) df_sw_cv.columns = ['sw_cv_' + c for c in df_sw_cv.columns] # Combine the mean and CV into a single dataframe df_sw = df_sw.join(df_sw_cv).reset_index() df_sw['Stage'] = df_sw['Stage'].map(stage_mapping) df_sw.columns = df_sw.columns.str.lower() df_sw.rename(columns={'channel': 'chan'}, inplace=True) # ######################################################################### # 5) ENTROPY & FRACTAL DIMENSION # ######################################################################### print(" ..calculating entropy measures") # Filter data in the delta band and calculate envelope for CVE data_delta = mne.filter.filter_data( data, sfreq=sf, l_freq=0.5, h_freq=4, l_trans_bandwidth=0.2, h_trans_bandwidth=0.2, verbose=False) env_delta = np.abs(sp_sig.hilbert(data_delta)) # Initialize dataframe idx_ent = pd.MultiIndex.from_product( [[2, 3, 4, 6, 7], chan], names=['stage', 'chan']) df_ent = pd.DataFrame(index=idx_ent) for stage in [2, 3, 4, 6, 7]: if stage == 6: # Use hypno_NREM data_stage = data[:, hypno_NREM == stage] data_stage_delta = data_delta[:, hypno_NREM == stage] env_stage_delta = env_delta[:, hypno_NREM == stage] elif stage == 7: # Use hypno_WN data_stage = data[:, hypno_WN == stage] data_stage_delta = data_delta[:, hypno_WN == stage] env_stage_delta = env_delta[:, hypno_WN == stage] else: data_stage = data[:, hypno == stage] data_stage_delta = data_delta[:, hypno == stage] env_stage_delta = env_delta[:, hypno == stage] # Skip if stage is not present in data if data_stage.shape[-1] == 0: continue # Entropy and fractal dimension (FD) # See review here: https://pubmed.ncbi.nlm.nih.gov/33286013/ # These are calculated on the broadband signal. # - DFA not implemented because it is dependent on data length. # - Sample / app entropy not implemented because it is too slow to # calculate. from numpy import apply_along_axis as aal df_ent.loc[stage, 'ent_svd'] = aal( ant.svd_entropy, axis=1, arr=data_stage, normalize=True) df_ent.loc[stage, 'ent_perm'] = aal( ant.perm_entropy, axis=1, arr=data_stage, normalize=True) df_ent.loc[stage, 'ent_spec'] = ant.spectral_entropy( data_stage, sf, method="welch", nperseg=(5 * int(sf)), normalize=True, axis=1) df_ent.loc[stage, 'ent_higuchi'] = aal( ant.higuchi_fd, axis=1, arr=data_stage) # We also add the coefficient of variation of the delta envelope # (CVE), a measure of "slow-wave stability". # See Diaz et al 2018, NeuroImage / Park et al 2021, Sci. Rep. # Lower values = more stable slow-waves (= more sinusoidal) denom = np.sqrt(4 / np.pi - 1) # approx 0.5227 cve = sp_stats.variation(env_stage_delta, axis=1) / denom df_ent.loc[stage, 'ent_cve_delta'] = cve # Other metrics of slow-wave (= delta) stability df_ent.loc[stage, 'ent_higuchi_delta'] = aal( ant.higuchi_fd, axis=1, arr=data_stage_delta) df_ent = df_ent.dropna(how="all").reset_index() df_ent['stage'] = df_ent['stage'].map(stage_mapping) # ######################################################################### # 5) MERGE ALL DATAFRAMES # ######################################################################### df = (df_bp .merge(df_sp, how='outer') .merge(df_sw, how='outer') .merge(df_ent, how='outer')) return df.set_index(['stage', 'chan'])
40.918782
91
0.588451
ace8b0f3296b323d0414b68997940f5f81ee23e9
11,495
py
Python
hearthbreaker/cards/minions/druid.py
yoazmenda/Hearthstone_deck_builder
b8fd89295b70d45f22a9e1834de789dc57c2ab54
[ "MIT" ]
null
null
null
hearthbreaker/cards/minions/druid.py
yoazmenda/Hearthstone_deck_builder
b8fd89295b70d45f22a9e1834de789dc57c2ab54
[ "MIT" ]
null
null
null
hearthbreaker/cards/minions/druid.py
yoazmenda/Hearthstone_deck_builder
b8fd89295b70d45f22a9e1834de789dc57c2ab54
[ "MIT" ]
null
null
null
from hearthbreaker.cards.base import MinionCard, ChoiceCard from hearthbreaker.game_objects import Minion from hearthbreaker.tags.action import Give, Damage, Silence, Transform, Draw, Heal, \ Summon, AddCard, GiveManaCrystal, Remove, Kill from hearthbreaker.tags.base import Choice, Buff, Effect, CardQuery, CARD_SOURCE, Battlecry, Deathrattle, ActionTag from hearthbreaker.tags.condition import IsType, GreaterThan from hearthbreaker.tags.event import Damaged, TurnEnded from hearthbreaker.tags.selector import CharacterSelector, MinionSelector, SelfSelector, UserPicker, BothPlayer, \ PlayerSelector, HeroSelector, Count, DeadMinionSelector from hearthbreaker.constants import CHARACTER_CLASS, CARD_RARITY, MINION_TYPE from hearthbreaker.tags.status import ChangeAttack, ChangeHealth, Taunt, ManaChange from hearthbreaker.cards.spells.neutral import spare_part_list class Moonfire(ChoiceCard): def __init__(self): super().__init__("Moonfire", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, ref_name="moonfire_keeper") class Dispel(ChoiceCard): def __init__(self): super().__init__("Dispel", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) class KeeperOfTheGrove(MinionCard): def __init__(self): super().__init__("Keeper of the Grove", 4, CHARACTER_CLASS.DRUID, CARD_RARITY.RARE, choices=[ Choice(Moonfire(), Damage(2), CharacterSelector(players=BothPlayer(), picker=UserPicker())), Choice(Dispel(), Silence(), MinionSelector(players=BothPlayer(), picker=UserPicker())) ]) def create_minion(self, player): return Minion(2, 4) class CatDruid(MinionCard): def __init__(self): super().__init__("Druid of the Claw", 5, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False, MINION_TYPE.BEAST, ref_name="Druid of the Claw (cat)") def create_minion(self, p): return Minion(4, 4, charge=True) class BearDruid(MinionCard): def __init__(self): super().__init__("Druid of the Claw", 5, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False, MINION_TYPE.BEAST, ref_name="Druid of the Claw (bear)") def create_minion(self, p): return Minion(4, 6, taunt=True) class CatForm(ChoiceCard): def __init__(self): super().__init__("Cat Form", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) class BearForm(ChoiceCard): def __init__(self): super().__init__("Bear Form", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) class DruidOfTheClaw(MinionCard): def __init__(self): super().__init__("Druid of the Claw", 5, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, choices=[ Choice(CatForm(), Transform(CatDruid()), SelfSelector()), Choice(BearForm(), Transform(BearDruid()), SelfSelector()) ]) def create_minion(self, player): return Minion(4, 4) class AncientSecrets(ChoiceCard): def __init__(self): super().__init__("Ancient Secrets", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) class AncientTeachings(ChoiceCard): def __init__(self): super().__init__("Ancient Teachings", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) class AncientOfLore(MinionCard): def __init__(self): super().__init__("Ancient of Lore", 7, CHARACTER_CLASS.DRUID, CARD_RARITY.EPIC, choices=[ Choice(AncientSecrets(), Heal(5), HeroSelector()), Choice(AncientTeachings(), Draw(3), PlayerSelector()) ]) def create_minion(self, player): return Minion(5, 5) class Health(ChoiceCard): def __init__(self): super().__init__("Rooted", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) class Attack(ChoiceCard): def __init__(self): super().__init__("Uproot", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) class AncientOfWar(MinionCard): def __init__(self): super().__init__("Ancient of War", 7, CHARACTER_CLASS.DRUID, CARD_RARITY.EPIC, choices=[ Choice(Health(), Give([Buff(ChangeHealth(5)), Buff(Taunt())]), SelfSelector()), Choice(Attack(), Give([Buff(ChangeAttack(5))]), SelfSelector()), ]) def create_minion(self, player): return Minion(5, 5) class IronbarkProtector(MinionCard): def __init__(self): super().__init__("Ironbark Protector", 8, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) def create_minion(self, player): return Minion(8, 8, taunt=True) class TauntTreant(MinionCard): def __init__(self): super().__init__("Treant", 1, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, ref_name="Treant (taunt)") def create_minion(self, p): return Minion(2, 2, taunt=True) class Treant(MinionCard): def __init__(self): super().__init__("Treant", 1, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) def create_minion(self, _): return Minion(2, 2) class ChargeTreant(MinionCard): def __init__(self): super().__init__("Treant", 1, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False, ref_name="Treant (charge)") def create_minion(self, player): return Minion(2, 2, charge=True, effects=[Effect(TurnEnded(), ActionTag(Kill(), SelfSelector()))]) class PoisonSeedsTreant(MinionCard): def __init__(self): super().__init__("Treant", 1, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False, ref_name="Treant (poison seeds)") def create_minion(self, player): return Minion(2, 2) class Panther(MinionCard): def __init__(self): super().__init__("Panther", 2, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False, MINION_TYPE.BEAST) def create_minion(self, _): return Minion(3, 2, MINION_TYPE.BEAST) class IncreaseStats(ChoiceCard): def __init__(self): super().__init__("Give your other minions +2/+2 and taunt", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.LEGENDARY, False) class SummonTreants(ChoiceCard): def __init__(self): super().__init__("Summon two 2/2 Treants with taunt", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.LEGENDARY, False) class Cenarius(MinionCard): def __init__(self): super().__init__("Cenarius", 9, CHARACTER_CLASS.DRUID, CARD_RARITY.LEGENDARY, choices=[ Choice(IncreaseStats(), Give([Buff(ChangeAttack(2)), Buff(ChangeHealth(2)), Buff(Taunt())]), MinionSelector()), Choice(SummonTreants(), Summon(TauntTreant(), 2), PlayerSelector()) ]) def create_minion(self, player): return Minion(5, 8) class AttackMode(ChoiceCard): def __init__(self): super().__init__("Attack Mode", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) class TankMode(ChoiceCard): def __init__(self): super().__init__("Tank Mode", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) class AnodizedRoboCub(MinionCard): def __init__(self): super().__init__("Anodized Robo Cub", 2, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, minion_type=MINION_TYPE.MECH, choices=[Choice(AttackMode(), Give([Buff(ChangeAttack(1))]), SelfSelector()), Choice(TankMode(), Give([Buff(ChangeHealth(1))]), SelfSelector())]) def create_minion(self, player): return Minion(2, 2, taunt=True) class MechBearCat(MinionCard): def __init__(self): super().__init__("Mech-Bear-Cat", 6, CHARACTER_CLASS.DRUID, CARD_RARITY.RARE, minion_type=MINION_TYPE.MECH) def create_minion(self, player): return Minion(7, 6, effects=[Effect(Damaged(), ActionTag(AddCard(CardQuery(source=CARD_SOURCE.LIST, source_list=spare_part_list)), PlayerSelector()))]) class CobraForm(MinionCard): def __init__(self): super().__init__("Druid of the Fang", 5, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False, MINION_TYPE.BEAST, ref_name="Druid of the Fang (cobra)") def create_minion(self, player): return Minion(7, 7) class DruidOfTheFang(MinionCard): def __init__(self): super().__init__("Druid of the Fang", 5, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, battlecry=Battlecry(Transform(CobraForm()), SelfSelector(), GreaterThan(Count(MinionSelector(IsType(MINION_TYPE.BEAST))), value=0))) def create_minion(self, player): return Minion(4, 4) class Malorne(MinionCard): def __init__(self): super().__init__("Malorne", 7, CHARACTER_CLASS.DRUID, CARD_RARITY.LEGENDARY, minion_type=MINION_TYPE.BEAST) def create_minion(self, player): return Minion(9, 7, deathrattle=[Deathrattle(AddCard(CardQuery(source=CARD_SOURCE.MINION, minion=SelfSelector()), add_to_deck=True), PlayerSelector()), Deathrattle(Remove(), SelfSelector())]) class GiftOfMana(ChoiceCard): def __init__(self): super().__init__("Gift of Mana", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.RARE) class GiftOfCards(ChoiceCard): def __init__(self): super().__init__("Gift of Cards", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.RARE) class GroveTender(MinionCard): def __init__(self): super().__init__("Grove Tender", 3, CHARACTER_CLASS.DRUID, CARD_RARITY.RARE, choices=[ Choice(GiftOfMana(), GiveManaCrystal(), PlayerSelector(players=BothPlayer())), Choice(GiftOfCards(), Draw(), PlayerSelector(players=BothPlayer())) ]) def create_minion(self, player): return Minion(2, 4) class FlameCat(MinionCard): def __init__(self): super().__init__("Druid of the Flame", 3, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False, MINION_TYPE.BEAST, ref_name="Druid of the Flame (cat)") def create_minion(self, p): return Minion(5, 2) class FlameBird(MinionCard): def __init__(self): super().__init__("Druid of the Flame", 3, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False, MINION_TYPE.BEAST, ref_name="Druid of the Flame (bird)") def create_minion(self, p): return Minion(2, 5) class FlameCatForm(ChoiceCard): def __init__(self): super().__init__("Flame Cat Form", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) class FlameBirdForm(ChoiceCard): def __init__(self): super().__init__("Flame Bird Form", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) class DruidOfTheFlame(MinionCard): def __init__(self): super().__init__("Druid of the Flame", 3, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, choices=[ Choice(FlameCatForm(), Transform(FlameCat()), SelfSelector()), Choice(FlameBirdForm(), Transform(FlameBird()), SelfSelector()) ]) def create_minion(self, player): return Minion(2, 2) class VolcanicLumberer(MinionCard): def __init__(self): super().__init__("Volcanic Lumberer", 9, CHARACTER_CLASS.DRUID, CARD_RARITY.RARE, buffs=[Buff(ManaChange(Count(DeadMinionSelector(players=BothPlayer())), -1))]) def create_minion(self, player): return Minion(7, 8, taunt=True)
35.698758
120
0.656111
ace8b10b2012ac336a016c3ee6dd3c94aff807f4
2,971
py
Python
tests/integration/tools/test_zoom_out_tool.py
jensencl/bokeh_composite_formatter
fe497342779fe3d78a4710bd4dd6b48f2ffeb9a9
[ "BSD-3-Clause" ]
1
2020-02-07T16:57:56.000Z
2020-02-07T16:57:56.000Z
tests/integration/tools/test_zoom_out_tool.py
jakubwro/bokeh
950f133f033df349d6f63b9750a909d5e64de21d
[ "BSD-3-Clause" ]
null
null
null
tests/integration/tools/test_zoom_out_tool.py
jakubwro/bokeh
950f133f033df349d6f63b9750a909d5e64de21d
[ "BSD-3-Clause" ]
null
null
null
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import pytest ; pytest #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from bokeh._testing.util.selenium import RECORD from bokeh.models import ( ColumnDataSource, CustomAction, CustomJS, Plot, Range1d, Rect, ZoomOutTool, ) #----------------------------------------------------------------------------- # Tests #----------------------------------------------------------------------------- pytest_plugins = ( "bokeh._testing.plugins.project", ) def _make_plot(): source = ColumnDataSource(dict(x=[1, 2], y=[1, 1])) plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0) plot.add_glyph(source, Rect(x='x', y='y', width=0.9, height=0.9)) plot.add_tools(ZoomOutTool()) code = RECORD("xrstart", "p.x_range.start", final=False) + \ RECORD("xrend", "p.x_range.end", final=False) + \ RECORD("yrstart", "p.y_range.start", final=False) + \ RECORD("yrend", "p.y_range.end") plot.add_tools(CustomAction(callback=CustomJS(args=dict(p=plot), code=code))) plot.toolbar_sticky = False return plot @pytest.mark.integration @pytest.mark.selenium class Test_ZoomOutTool(object): def test_deselected_by_default(self, single_plot_page) -> None: plot = _make_plot() page = single_plot_page(plot) button = page.get_toolbar_button('zoom-out') assert 'active' not in button.get_attribute('class') assert page.has_no_console_errors() def test_clicking_zooms_out(self, single_plot_page) -> None: plot = _make_plot() page = single_plot_page(plot) button = page.get_toolbar_button('zoom-out') button.click() page.click_custom_action() first = page.results assert first['xrstart'] < 0 assert first['xrend'] > 1 assert first['yrstart'] < 0 assert first['yrend'] > 1 button = page.get_toolbar_button('zoom-out') button.click() page.click_custom_action() second = page.results assert second['xrstart'] < first['xrstart'] assert second['xrend'] > first['xrend'] assert second['yrstart'] < first['yrstart'] assert second['yrend'] > first['yrend'] assert page.has_no_console_errors()
31.946237
108
0.509593