Dataset Viewer
Auto-converted to Parquet
hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
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
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
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
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
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
2
1.02M
avg_line_length
float64
1
958k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
2 classes
is_sharp_comment_removed
bool
1 class
f70001f658d4dfaa72dd4f0d1b3176492f6658bb
6,442
py
Python
spider/openwrt.py
CNDB/CNDB
2e3a41111f604cf2f4f22a7c9370bb3f753e3e88
[ "BSD-3-Clause" ]
null
null
null
spider/openwrt.py
CNDB/CNDB
2e3a41111f604cf2f4f22a7c9370bb3f753e3e88
[ "BSD-3-Clause" ]
null
null
null
spider/openwrt.py
CNDB/CNDB
2e3a41111f604cf2f4f22a7c9370bb3f753e3e88
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- # #*** <License> ************************************************************# # This module is part of the repository CNDB. # # This module is licensed under the terms of the BSD 3-Clause License # <http://www.c-tanzer.at/license/bsd_3c.html>. # #*** </License> ***********************************************************# from _TFL.pyk import pyk from rsclib.HTML_Parse import tag, Page_Tree from rsclib.autosuper import autosuper from spider.common import Interface, Inet4, Inet6, unroutable from spider.common import WLAN_Config from spider.luci import Version_Mixin class Status (Page_Tree, Version_Mixin) : url = 'cgi-bin/luci/freifunk/status/status' retries = 2 timeout = 10 html_charset = 'utf-8' # force utf-8 encoding wl_names = dict \ ( ssid = 'ssid' , _bsiid = 'bssid' , channel = 'channel' , mode = 'mode' ) def parse (self) : root = self.tree.getroot () self.wlans = [] self.routes = {} for div in root.findall (".//%s" % tag ("div")) : id = div.get ('id') if id == 'cbi-wireless' : wlan_div = div elif id == 'cbi-routes' : route_div = div self.try_get_version (div) for d in self.tbl_iter (wlan_div) : for k, newkey in pyk.iteritems (self.wl_names) : if k in d : d [newkey] = d [k] wl = WLAN_Config (** d) self.wlans.append (wl) for d in self.tbl_iter (route_div) : iface = d.get ('iface') gw = d.get ('gateway') if iface and gw : self.routes [iface] = gw self.set_version (root) # end def parse def tbl_iter (self, div) : tbl = div.find (".//%s" % tag ("table")) assert tbl.get ('class') == 'cbi-section-table' d = {} for tr in tbl : if 'cbi-section-table-row' not in tr.get ('class').split () : continue for input in tr.findall (".//%s" % tag ('input')) : name = input.get ('id').split ('.') [-1] val = input.get ('value') d [name] = val if not d : continue yield d # end def tbl_iter # end class Status class Table_Iter (Page_Tree) : def table_iter (self) : root = self.tree.getroot () for div in root.findall (".//%s" % tag ("div")) : if div.get ('id') == 'maincontent' : break tbl = div.find (".//%s" % tag ("table")) if tbl is None : return for tr in tbl : if tr [0].tag == tag ('th') : continue yield (self.tree.get_text (x) for x in tr) # end def table_iter # end class Table_Iter class OLSR_Connections (Table_Iter) : url = 'cgi-bin/luci/freifunk/olsr/' retries = 2 timeout = 10 html_charset = 'utf-8' # force utf-8 encoding def parse (self) : self.neighbors = {} for l in self.table_iter () : neighbor, ip, lq, nlq, etx = l lq, nlq, etx = (float (x) for x in (lq, nlq, etx)) self.neighbors [neighbor] = [ip, lq, nlq, etx] # end def parse # end class OLSR_Connections class OLSR_Routes (Table_Iter) : url = 'cgi-bin/luci/freifunk/olsr/routes' retries = 2 timeout = 10 html_charset = 'utf-8' # force utf-8 encoding def parse (self) : self.iface_by_gw = {} for l in self.table_iter () : announced, gw, iface, metric, etx = l if gw in self.iface_by_gw : assert iface == self.iface_by_gw [gw] else : self.iface_by_gw [gw] = iface # end def parse # end class OLSR_Routes class OpenWRT (autosuper) : def __init__ (self, site, request) : self.site = site self.request = request if 'interfaces' in self.request or 'ips' in self.request : st = Status (site = site) conn = OLSR_Connections (site = site) route = OLSR_Routes (site = site) self.version = st.version assert len (st.wlans) <= 1 interfaces = {} ips = {} count = 0 for gw, ifname in pyk.iteritems (route.iface_by_gw) : ip, lq, nlq, etx = conn.neighbors [gw] i4 = Inet4 (ip, None, None, iface = ifname) ips [i4] = 1 is_wlan = True if lq == nlq == etx == 1.0 : is_wlan = False if ifname in interfaces : iface = interfaces [ifname] if not iface.is_wlan and is_wlan : iface.is_wlan = True iface.wlan_info = st.wlans [0] else : iface = Interface (count, ifname, None) iface.is_wlan = is_wlan if is_wlan : iface.wlan_info = st.wlans [0] count += 1 interfaces [ifname] = iface if i4 not in iface.inet4 : iface.append_inet4 (i4) wl_if = None for iface in pyk.itervalues (interfaces) : if iface.is_wlan : if wl_if : m = "Duplicate wlan: %s/%s" % (iface.name, wl_if.name) raise ValueError (m) wl_if = iface # check own ip n = 'unknown' i4 = Inet4 (self.request ['ip'], None, None, iface = n) if i4 not in ips : assert n not in interfaces iface = interfaces [n] = Interface (count, n, None) iface.append_inet4 (i4) iface.is_wlan = False if not wl_if and st.wlans : iface.is_wlan = True iface.wlan_info = st.wlans [0] ips [i4] = True self.request ['ips'] = ips self.request ['interfaces'] = interfaces self.request ['version'] = st.version # end def __init__ # end class OpenWRT
34.449198
78
0.472369
from _TFL.pyk import pyk from rsclib.HTML_Parse import tag, Page_Tree from rsclib.autosuper import autosuper from spider.common import Interface, Inet4, Inet6, unroutable from spider.common import WLAN_Config from spider.luci import Version_Mixin class Status (Page_Tree, Version_Mixin) : url = 'cgi-bin/luci/freifunk/status/status' retries = 2 timeout = 10 html_charset = 'utf-8' wl_names = dict \ ( ssid = 'ssid' , _bsiid = 'bssid' , channel = 'channel' , mode = 'mode' ) def parse (self) : root = self.tree.getroot () self.wlans = [] self.routes = {} for div in root.findall (".//%s" % tag ("div")) : id = div.get ('id') if id == 'cbi-wireless' : wlan_div = div elif id == 'cbi-routes' : route_div = div self.try_get_version (div) for d in self.tbl_iter (wlan_div) : for k, newkey in pyk.iteritems (self.wl_names) : if k in d : d [newkey] = d [k] wl = WLAN_Config (** d) self.wlans.append (wl) for d in self.tbl_iter (route_div) : iface = d.get ('iface') gw = d.get ('gateway') if iface and gw : self.routes [iface] = gw self.set_version (root) def tbl_iter (self, div) : tbl = div.find (".//%s" % tag ("table")) assert tbl.get ('class') == 'cbi-section-table' d = {} for tr in tbl : if 'cbi-section-table-row' not in tr.get ('class').split () : continue for input in tr.findall (".//%s" % tag ('input')) : name = input.get ('id').split ('.') [-1] val = input.get ('value') d [name] = val if not d : continue yield d class Table_Iter (Page_Tree) : def table_iter (self) : root = self.tree.getroot () for div in root.findall (".//%s" % tag ("div")) : if div.get ('id') == 'maincontent' : break tbl = div.find (".//%s" % tag ("table")) if tbl is None : return for tr in tbl : if tr [0].tag == tag ('th') : continue yield (self.tree.get_text (x) for x in tr) class OLSR_Connections (Table_Iter) : url = 'cgi-bin/luci/freifunk/olsr/' retries = 2 timeout = 10 html_charset = 'utf-8' def parse (self) : self.neighbors = {} for l in self.table_iter () : neighbor, ip, lq, nlq, etx = l lq, nlq, etx = (float (x) for x in (lq, nlq, etx)) self.neighbors [neighbor] = [ip, lq, nlq, etx] class OLSR_Routes (Table_Iter) : url = 'cgi-bin/luci/freifunk/olsr/routes' retries = 2 timeout = 10 html_charset = 'utf-8' def parse (self) : self.iface_by_gw = {} for l in self.table_iter () : announced, gw, iface, metric, etx = l if gw in self.iface_by_gw : assert iface == self.iface_by_gw [gw] else : self.iface_by_gw [gw] = iface class OpenWRT (autosuper) : def __init__ (self, site, request) : self.site = site self.request = request if 'interfaces' in self.request or 'ips' in self.request : st = Status (site = site) conn = OLSR_Connections (site = site) route = OLSR_Routes (site = site) self.version = st.version assert len (st.wlans) <= 1 interfaces = {} ips = {} count = 0 for gw, ifname in pyk.iteritems (route.iface_by_gw) : ip, lq, nlq, etx = conn.neighbors [gw] i4 = Inet4 (ip, None, None, iface = ifname) ips [i4] = 1 is_wlan = True if lq == nlq == etx == 1.0 : is_wlan = False if ifname in interfaces : iface = interfaces [ifname] if not iface.is_wlan and is_wlan : iface.is_wlan = True iface.wlan_info = st.wlans [0] else : iface = Interface (count, ifname, None) iface.is_wlan = is_wlan if is_wlan : iface.wlan_info = st.wlans [0] count += 1 interfaces [ifname] = iface if i4 not in iface.inet4 : iface.append_inet4 (i4) wl_if = None for iface in pyk.itervalues (interfaces) : if iface.is_wlan : if wl_if : m = "Duplicate wlan: %s/%s" % (iface.name, wl_if.name) raise ValueError (m) wl_if = iface n = 'unknown' i4 = Inet4 (self.request ['ip'], None, None, iface = n) if i4 not in ips : assert n not in interfaces iface = interfaces [n] = Interface (count, n, None) iface.append_inet4 (i4) iface.is_wlan = False if not wl_if and st.wlans : iface.is_wlan = True iface.wlan_info = st.wlans [0] ips [i4] = True self.request ['ips'] = ips self.request ['interfaces'] = interfaces self.request ['version'] = st.version
true
true
f7000273e22d5a0f2d5b40c38a0ed8511d1b8995
2,250
py
Python
utils/compare.py
adcrn/knest
a274dc9ddb642cc30f837e225f000bf33430eb43
[ "BSD-3-Clause" ]
8
2018-03-15T23:42:51.000Z
2020-03-10T06:21:03.000Z
utils/compare.py
deekerno/knest
a274dc9ddb642cc30f837e225f000bf33430eb43
[ "BSD-3-Clause" ]
12
2018-03-15T19:11:02.000Z
2018-10-30T10:02:45.000Z
utils/compare.py
adcrn/knest
a274dc9ddb642cc30f837e225f000bf33430eb43
[ "BSD-3-Clause" ]
null
null
null
# UCF Senior Design 2017-18 # Group 38 from PIL import Image import cv2 import imagehash import math import numpy as np DIFF_THRES = 20 LIMIT = 2 RESIZE = 1000 def calc_hash(img): """ Calculate the wavelet hash of the image img: (ndarray) image file """ # resize image if height > 1000 img = resize(img) return imagehash.whash(Image.fromarray(img)) def compare(hash1, hash2): """ Calculate the difference between two images hash1: (array) first wavelet hash hash2: (array) second wavelet hash """ return hash1 - hash2 def limit(img, std_hash, count): """ Determine whether image should be removed from image dictionary in main.py img: (ndarray) image file std_hash: (array) wavelet hash of comparison standard count: (int) global count of images similar to comparison standard """ # calculate hash for given image cmp_hash = calc_hash(img) # compare to standard diff = compare(std_hash, cmp_hash) # image is similar to standard if diff <= DIFF_THRES: # if there are 3 similar images already, remove image if count >= LIMIT: return 'remove' # non-similar image found else: # update comparison standard return 'update_std' # else continue reading images with same standard return 'continue' def resize(img): """ Resize an image img: (ndarray) RGB color image """ # get dimensions of image width = np.shape(img)[1] height = np.shape(img)[0] # if height of image is greater than 1000, resize it to 1000 if width > RESIZE: # keep resize proportional scale = RESIZE / width resized_img = cv2.resize( img, (RESIZE, math.floor(height / scale)), cv2.INTER_AREA) # return resized image return resized_img # if height of image is less than 1000, return image unresized return img def set_standard(images, filename): """ Set new comparison standard and update information images: (dictionary) dictionary containing all the image data filename: (String) name of the image file """ return filename, calc_hash(images[filename]), 0
24.725275
78
0.646667
from PIL import Image import cv2 import imagehash import math import numpy as np DIFF_THRES = 20 LIMIT = 2 RESIZE = 1000 def calc_hash(img): img = resize(img) return imagehash.whash(Image.fromarray(img)) def compare(hash1, hash2): return hash1 - hash2 def limit(img, std_hash, count): cmp_hash = calc_hash(img) diff = compare(std_hash, cmp_hash) if diff <= DIFF_THRES: if count >= LIMIT: return 'remove' else: return 'update_std' return 'continue' def resize(img): width = np.shape(img)[1] height = np.shape(img)[0] if width > RESIZE: scale = RESIZE / width resized_img = cv2.resize( img, (RESIZE, math.floor(height / scale)), cv2.INTER_AREA) return resized_img return img def set_standard(images, filename): return filename, calc_hash(images[filename]), 0
true
true
f70002926d1d600b4b068459c9dd40ebf3aef47d
757
py
Python
sdk/python/kfp/__main__.py
ConverJens/pipelines
a1d453af214ec9eebad73fb05845dd3499d60d00
[ "Apache-2.0" ]
6
2020-05-19T02:35:11.000Z
2020-05-29T17:58:42.000Z
sdk/python/kfp/__main__.py
ConverJens/pipelines
a1d453af214ec9eebad73fb05845dd3499d60d00
[ "Apache-2.0" ]
1,932
2021-01-25T11:23:37.000Z
2022-03-31T17:10:18.000Z
sdk/python/kfp/__main__.py
ConverJens/pipelines
a1d453af214ec9eebad73fb05845dd3499d60d00
[ "Apache-2.0" ]
11
2020-05-19T22:26:41.000Z
2021-01-25T09:56:21.000Z
# Copyright 2018 Google LLC # # 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. from .cli.cli import main # TODO(hongyes): add more commands: # kfp compile (migrate from dsl-compile) # kfp experiment (manage experiments) if __name__ == '__main__': main()
32.913043
74
0.749009
from .cli.cli import main if __name__ == '__main__': main()
true
true
f7000327daf9ff11a381ce6d5de401ff007d1323
1,094
py
Python
TestProject/app/view/RoomItem.py
ChinSing00/ChatChat
48654e2e125298c00a558449353e38d0cec06d03
[ "MIT" ]
null
null
null
TestProject/app/view/RoomItem.py
ChinSing00/ChatChat
48654e2e125298c00a558449353e38d0cec06d03
[ "MIT" ]
null
null
null
TestProject/app/view/RoomItem.py
ChinSing00/ChatChat
48654e2e125298c00a558449353e38d0cec06d03
[ "MIT" ]
null
null
null
import time from PyQt5 import QtGui, QtCore from ui.room_item import Ui_Form from PyQt5.QtWidgets import QWidget class Room_Item(QWidget,Ui_Form): def __init__(self,parent=None,room_data=None): super(Room_Item,self).__init__(parent) self.setupUi(self) self.data = room_data self.setRoomInfo() def setRoomInfo(self): self.room_name.setText('{}({})'.format(self.data['naturalName'], self.data['roomName'])) self.description.setText("<a style='color:#BCBCBC'>{}</a>".format(self.data['description'])) timeStamp = int(self.data['creationDate']) / 1000 timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y-%m-%d", timeArray) self.create_time.setText("<a style='color:#BCBCBC'>{}</a>".format(otherStyleTime)) members = len(self.data['owners']) + len(self.data['admins']) + len(self.data['members']) memberCounter = "<a style='color:#BCBCBC'>{}/{}</a>".format(members, ('∞' if self.data['maxUsers']==0 else self.data['maxUsers'])) self.member.setText(memberCounter)
45.583333
138
0.659049
import time from PyQt5 import QtGui, QtCore from ui.room_item import Ui_Form from PyQt5.QtWidgets import QWidget class Room_Item(QWidget,Ui_Form): def __init__(self,parent=None,room_data=None): super(Room_Item,self).__init__(parent) self.setupUi(self) self.data = room_data self.setRoomInfo() def setRoomInfo(self): self.room_name.setText('{}({})'.format(self.data['naturalName'], self.data['roomName'])) self.description.setText("<a style='color:#BCBCBC'>{}</a>".format(self.data['description'])) timeStamp = int(self.data['creationDate']) / 1000 timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y-%m-%d", timeArray) self.create_time.setText("<a style='color:#BCBCBC'>{}</a>".format(otherStyleTime)) members = len(self.data['owners']) + len(self.data['admins']) + len(self.data['members']) memberCounter = "<a style='color:#BCBCBC'>{}/{}</a>".format(members, ('∞' if self.data['maxUsers']==0 else self.data['maxUsers'])) self.member.setText(memberCounter)
true
true
f7000371f0315cd55c0b14b33e7e8e56697cfc2e
10,498
py
Python
src/winforms/toga_winforms/app.py
holg/toga
9dd766e749c6cf29cdb1127c7637150381ac396d
[ "BSD-3-Clause" ]
1
2020-07-16T00:46:24.000Z
2020-07-16T00:46:24.000Z
src/winforms/toga_winforms/app.py
holg/toga
9dd766e749c6cf29cdb1127c7637150381ac396d
[ "BSD-3-Clause" ]
null
null
null
src/winforms/toga_winforms/app.py
holg/toga
9dd766e749c6cf29cdb1127c7637150381ac396d
[ "BSD-3-Clause" ]
null
null
null
import asyncio import re import sys import traceback import toga from toga import Key from .keys import toga_to_winforms_key from .libs import Threading, WinForms, shcore, user32, win_version from .libs.proactor import WinformsProactorEventLoop from .window import Window class MainWindow(Window): def winforms_FormClosing(self, sender, event): if not self.interface.app._impl._is_exiting: event.Cancel = not self.interface.app.exit() class App: _MAIN_WINDOW_CLASS = MainWindow def __init__(self, interface): self.interface = interface self.interface._impl = self # Winforms app exit is tightly bound to the close of the MainWindow. # The FormClosing message on MainWindow calls app.exit(), which # will then trigger the "on_exit" handler (which might abort the # close). However, if app.exit() succeeds, it will request the # Main Window to close... which calls app.exit(). # So - we have a flag that is only ever sent once a request has been # made to exit the native app. This flag can be used to shortcut any # window-level close handling. self._is_exiting = False self.loop = WinformsProactorEventLoop() asyncio.set_event_loop(self.loop) def create(self): self.native = WinForms.Application self.app_context = WinForms.ApplicationContext() # Check the version of windows and make sure we are setting the DPI mode # with the most up to date API # Windows Versioning Check Sources : https://www.lifewire.com/windows-version-numbers-2625171 # and https://docs.microsoft.com/en-us/windows/release-information/ if win_version.Major >= 6: # Checks for Windows Vista or later # Represents Windows 8.1 up to Windows 10 before Build 1703 which should use # SetProcessDpiAwareness(True) if ((win_version.Major == 6 and win_version.Minor == 3) or (win_version.Major == 10 and win_version.Build < 15063)): shcore.SetProcessDpiAwareness(True) # Represents Windows 10 Build 1703 and beyond which should use # SetProcessDpiAwarenessContext(-2) elif win_version.Major == 10 and win_version.Build >= 15063: user32.SetProcessDpiAwarenessContext(-2) # Any other version of windows should use SetProcessDPIAware() else: user32.SetProcessDPIAware() self.native.EnableVisualStyles() self.native.SetCompatibleTextRenderingDefault(False) self.interface.commands.add( toga.Command( lambda _: self.interface.about(), 'About {}'.format(self.interface.name), group=toga.Group.HELP ), toga.Command(None, 'Preferences', group=toga.Group.FILE), # Quit should always be the last item, in a section on it's own toga.Command( lambda _: self.interface.exit(), 'Exit ' + self.interface.name, shortcut=Key.MOD_1 + 'q', group=toga.Group.FILE, section=sys.maxsize ), toga.Command( lambda _: self.interface.visit_homepage(), 'Visit homepage', enabled=self.interface.home_page is not None, group=toga.Group.HELP ) ) self._create_app_commands() # Call user code to populate the main window self.interface.startup() self.create_menus() self.interface.icon.bind(self.interface.factory) self.interface.main_window._impl.set_app(self) def create_menus(self): self._menu_items = {} self._menu_groups = {} toga.Group.FILE.order = 0 menubar = WinForms.MenuStrip() submenu = None for cmd in self.interface.commands: if cmd == toga.GROUP_BREAK: submenu = None elif cmd == toga.SECTION_BREAK: submenu.DropDownItems.Add('-') else: submenu = self._submenu(cmd.group, menubar) item = WinForms.ToolStripMenuItem(cmd.label) if cmd.action: item.Click += cmd._impl.as_handler() item.Enabled = cmd.enabled if cmd.shortcut is not None: shortcut_keys = toga_to_winforms_key(cmd.shortcut) item.ShortcutKeys = shortcut_keys item.ShowShortcutKeys = True cmd._impl.native.append(item) self._menu_items[item] = cmd submenu.DropDownItems.Add(item) self.interface.main_window._impl.native.Controls.Add(menubar) self.interface.main_window._impl.native.MainMenuStrip = menubar self.interface.main_window.content.refresh() def _submenu(self, group, menubar): try: return self._menu_groups[group] except KeyError: if group is None: submenu = menubar else: parent_menu = self._submenu(group.parent, menubar) submenu = WinForms.ToolStripMenuItem(group.label) # Top level menus are added in a different way to submenus if group.parent is None: parent_menu.Items.Add(submenu) else: parent_menu.DropDownItems.Add(submenu) self._menu_groups[group] = submenu return submenu def _create_app_commands(self): # No extra menus pass def open_document(self, fileURL): '''Add a new document to this app.''' print("STUB: If you want to handle opening documents, implement App.open_document(fileURL)") def winforms_thread_exception(self, sender, winforms_exc): # The PythonException returned by Winforms doesn't give us # easy access to the underlying Python stacktrace; so we # reconstruct it from the string message. # The Python message is helpfully included in square brackets, # as the context for the first line in the .net stack trace. # So, look for the closing bracket and the start of the Python.net # stack trace. Then, reconstruct the line breaks internal to the # remaining string. print("Traceback (most recent call last):") py_exc = winforms_exc.get_Exception() full_stack_trace = py_exc.StackTrace regex = re.compile( r"^\[(?:'(.*?)', )*(?:'(.*?)')\] (?:.*?) Python\.Runtime", re.DOTALL | re.UNICODE ) stacktrace_relevant_lines = regex.findall(full_stack_trace) if len(stacktrace_relevant_lines) == 0: self.print_stack_trace(full_stack_trace) else: for lines in stacktrace_relevant_lines: for line in lines: self.print_stack_trace(line) print(py_exc.Message) @classmethod def print_stack_trace(cls, stack_trace_line): for level in stack_trace_line.split("', '"): for line in level.split("\\n"): if line: print(line) def run_app(self): try: self.create() self.native.ThreadException += self.winforms_thread_exception self.loop.run_forever(self.app_context) except: # NOQA traceback.print_exc() def main_loop(self): thread = Threading.Thread(Threading.ThreadStart(self.run_app)) thread.SetApartmentState(Threading.ApartmentState.STA) thread.Start() thread.Join() def show_about_dialog(self): message_parts = [] if self.interface.name is not None: if self.interface.version is not None: message_parts.append( "{name} v{version}".format( name=self.interface.name, version=self.interface.version, ) ) else: message_parts.append( "{name}".format(name=self.interface.name) ) elif self.interface.version is not None: message_parts.append( "v{version}".format(version=self.interface.version) ) if self.interface.author is not None: message_parts.append( "Author: {author}".format(author=self.interface.author) ) if self.interface.description is not None: message_parts.append( "\n{description}".format( description=self.interface.description ) ) self.interface.main_window.info_dialog( 'About {}'.format(self.interface.name), "\n".join(message_parts) ) def exit(self): self._is_exiting = True self.native.Exit() def set_main_window(self, window): self.app_context.MainForm = window._impl.native def set_on_exit(self, value): pass def current_window(self): self.interface.factory.not_implemented('App.current_window()') def enter_full_screen(self, windows): self.interface.factory.not_implemented('App.enter_full_screen()') def exit_full_screen(self, windows): self.interface.factory.not_implemented('App.exit_full_screen()') def set_cursor(self, value): self.interface.factory.not_implemented('App.set_cursor()') def show_cursor(self): self.interface.factory.not_implemented('App.show_cursor()') def hide_cursor(self): self.interface.factory.not_implemented('App.hide_cursor()') def add_background_task(self, handler): self.loop.call_soon(handler, self) class DocumentApp(App): def _create_app_commands(self): self.interface.commands.add( toga.Command( lambda w: self.open_file, label='Open...', shortcut=Key.MOD_1 + 'o', group=toga.Group.FILE, section=0 ), ) def open_document(self, fileURL): """Open a new document in this app. Args: fileURL (str): The URL/path to the file to add as a document. """ self.interface.factory.not_implemented('DocumentApp.open_document()')
35.952055
101
0.597638
import asyncio import re import sys import traceback import toga from toga import Key from .keys import toga_to_winforms_key from .libs import Threading, WinForms, shcore, user32, win_version from .libs.proactor import WinformsProactorEventLoop from .window import Window class MainWindow(Window): def winforms_FormClosing(self, sender, event): if not self.interface.app._impl._is_exiting: event.Cancel = not self.interface.app.exit() class App: _MAIN_WINDOW_CLASS = MainWindow def __init__(self, interface): self.interface = interface self.interface._impl = self self._is_exiting = False self.loop = WinformsProactorEventLoop() asyncio.set_event_loop(self.loop) def create(self): self.native = WinForms.Application self.app_context = WinForms.ApplicationContext() if win_version.Major >= 6: if ((win_version.Major == 6 and win_version.Minor == 3) or (win_version.Major == 10 and win_version.Build < 15063)): shcore.SetProcessDpiAwareness(True) elif win_version.Major == 10 and win_version.Build >= 15063: user32.SetProcessDpiAwarenessContext(-2) else: user32.SetProcessDPIAware() self.native.EnableVisualStyles() self.native.SetCompatibleTextRenderingDefault(False) self.interface.commands.add( toga.Command( lambda _: self.interface.about(), 'About {}'.format(self.interface.name), group=toga.Group.HELP ), toga.Command(None, 'Preferences', group=toga.Group.FILE), toga.Command( lambda _: self.interface.exit(), 'Exit ' + self.interface.name, shortcut=Key.MOD_1 + 'q', group=toga.Group.FILE, section=sys.maxsize ), toga.Command( lambda _: self.interface.visit_homepage(), 'Visit homepage', enabled=self.interface.home_page is not None, group=toga.Group.HELP ) ) self._create_app_commands() # Call user code to populate the main window self.interface.startup() self.create_menus() self.interface.icon.bind(self.interface.factory) self.interface.main_window._impl.set_app(self) def create_menus(self): self._menu_items = {} self._menu_groups = {} toga.Group.FILE.order = 0 menubar = WinForms.MenuStrip() submenu = None for cmd in self.interface.commands: if cmd == toga.GROUP_BREAK: submenu = None elif cmd == toga.SECTION_BREAK: submenu.DropDownItems.Add('-') else: submenu = self._submenu(cmd.group, menubar) item = WinForms.ToolStripMenuItem(cmd.label) if cmd.action: item.Click += cmd._impl.as_handler() item.Enabled = cmd.enabled if cmd.shortcut is not None: shortcut_keys = toga_to_winforms_key(cmd.shortcut) item.ShortcutKeys = shortcut_keys item.ShowShortcutKeys = True cmd._impl.native.append(item) self._menu_items[item] = cmd submenu.DropDownItems.Add(item) self.interface.main_window._impl.native.Controls.Add(menubar) self.interface.main_window._impl.native.MainMenuStrip = menubar self.interface.main_window.content.refresh() def _submenu(self, group, menubar): try: return self._menu_groups[group] except KeyError: if group is None: submenu = menubar else: parent_menu = self._submenu(group.parent, menubar) submenu = WinForms.ToolStripMenuItem(group.label) # Top level menus are added in a different way to submenus if group.parent is None: parent_menu.Items.Add(submenu) else: parent_menu.DropDownItems.Add(submenu) self._menu_groups[group] = submenu return submenu def _create_app_commands(self): # No extra menus pass def open_document(self, fileURL): print("STUB: If you want to handle opening documents, implement App.open_document(fileURL)") def winforms_thread_exception(self, sender, winforms_exc): # The PythonException returned by Winforms doesn't give us print("Traceback (most recent call last):") py_exc = winforms_exc.get_Exception() full_stack_trace = py_exc.StackTrace regex = re.compile( r"^\[(?:'(.*?)', )*(?:'(.*?)')\] (?:.*?) Python\.Runtime", re.DOTALL | re.UNICODE ) stacktrace_relevant_lines = regex.findall(full_stack_trace) if len(stacktrace_relevant_lines) == 0: self.print_stack_trace(full_stack_trace) else: for lines in stacktrace_relevant_lines: for line in lines: self.print_stack_trace(line) print(py_exc.Message) @classmethod def print_stack_trace(cls, stack_trace_line): for level in stack_trace_line.split("', '"): for line in level.split("\\n"): if line: print(line) def run_app(self): try: self.create() self.native.ThreadException += self.winforms_thread_exception self.loop.run_forever(self.app_context) except: traceback.print_exc() def main_loop(self): thread = Threading.Thread(Threading.ThreadStart(self.run_app)) thread.SetApartmentState(Threading.ApartmentState.STA) thread.Start() thread.Join() def show_about_dialog(self): message_parts = [] if self.interface.name is not None: if self.interface.version is not None: message_parts.append( "{name} v{version}".format( name=self.interface.name, version=self.interface.version, ) ) else: message_parts.append( "{name}".format(name=self.interface.name) ) elif self.interface.version is not None: message_parts.append( "v{version}".format(version=self.interface.version) ) if self.interface.author is not None: message_parts.append( "Author: {author}".format(author=self.interface.author) ) if self.interface.description is not None: message_parts.append( "\n{description}".format( description=self.interface.description ) ) self.interface.main_window.info_dialog( 'About {}'.format(self.interface.name), "\n".join(message_parts) ) def exit(self): self._is_exiting = True self.native.Exit() def set_main_window(self, window): self.app_context.MainForm = window._impl.native def set_on_exit(self, value): pass def current_window(self): self.interface.factory.not_implemented('App.current_window()') def enter_full_screen(self, windows): self.interface.factory.not_implemented('App.enter_full_screen()') def exit_full_screen(self, windows): self.interface.factory.not_implemented('App.exit_full_screen()') def set_cursor(self, value): self.interface.factory.not_implemented('App.set_cursor()') def show_cursor(self): self.interface.factory.not_implemented('App.show_cursor()') def hide_cursor(self): self.interface.factory.not_implemented('App.hide_cursor()') def add_background_task(self, handler): self.loop.call_soon(handler, self) class DocumentApp(App): def _create_app_commands(self): self.interface.commands.add( toga.Command( lambda w: self.open_file, label='Open...', shortcut=Key.MOD_1 + 'o', group=toga.Group.FILE, section=0 ), ) def open_document(self, fileURL): self.interface.factory.not_implemented('DocumentApp.open_document()')
true
true
f7000456815408e3a0899443a0df077b039855c4
1,731
py
Python
__init__.py
luoxiangyong/qgissprp
4698462743e11eac486af4b60046b99ae2abc1b0
[ "BSD-2-Clause" ]
null
null
null
__init__.py
luoxiangyong/qgissprp
4698462743e11eac486af4b60046b99ae2abc1b0
[ "BSD-2-Clause" ]
null
null
null
__init__.py
luoxiangyong/qgissprp
4698462743e11eac486af4b60046b99ae2abc1b0
[ "BSD-2-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """ /*************************************************************************** SimplePhotogrammetryRoutePlanner A QGIS plugin A imple photogrammetry route planner. Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/ ------------------- begin : 2021-04-24 copyright : (C) 2021 by Xiangyong Luo email : [email protected] git sha : $Format:%H$ ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ This script initializes the plugin, making it known to QGIS. """ __version__ = "0.4.0" # noinspection PyPep8Naming def classFactory(iface): # pylint: disable=invalid-name """Load SimplePhotogrammetryRoutePlanner class from file SimplePhotogrammetryRoutePlanner. :param iface: A QGIS interface instance. :type iface: QgsInterface """ # from .SimplePhotogrammetryRoutePlanner import SimplePhotogrammetryRoutePlanner return SimplePhotogrammetryRoutePlanner(iface)
46.783784
94
0.458117
__version__ = "0.4.0" def classFactory(iface): from .SimplePhotogrammetryRoutePlanner import SimplePhotogrammetryRoutePlanner return SimplePhotogrammetryRoutePlanner(iface)
true
true
f70004a44b39e2f1be17fb0ebfe7da0897c5e85d
671
py
Python
eslearn/utils/lc_featureSelection_variance.py
dongmengshi/easylearn
df528aaa69c3cf61f5459a04671642eb49421dfb
[ "MIT" ]
19
2020-02-29T06:00:18.000Z
2022-01-24T01:30:14.000Z
eslearn/utils/lc_featureSelection_variance.py
dongmengshi/easylearn
df528aaa69c3cf61f5459a04671642eb49421dfb
[ "MIT" ]
7
2020-04-02T03:05:21.000Z
2020-11-11T11:45:05.000Z
eslearn/utils/lc_featureSelection_variance.py
dongmengshi/easylearn
df528aaa69c3cf61f5459a04671642eb49421dfb
[ "MIT" ]
11
2020-03-03T03:02:15.000Z
2020-11-11T14:09:55.000Z
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 14:38:20 2018 dimension reduction with VarianceThreshold using sklearn. Feature selector that removes all low-variance features. @author: lenovo """ from sklearn.feature_selection import VarianceThreshold import numpy as np # np.random.seed(1) X = np.random.randn(100, 10) X = np.hstack([X, np.zeros([100, 5])]) # def featureSelection_variance(X, thrd): sel = VarianceThreshold(threshold=thrd) X_selected = sel.fit_transform(X) mask = sel.get_support() return X_selected, mask X = [[0, 2, 0, 3], [0, 1, 4, 3], [0, 1, 1, 3]] selector = VarianceThreshold() selector.fit_transform(X) selector.variances_
23.964286
57
0.709389
from sklearn.feature_selection import VarianceThreshold import numpy as np np.random.seed(1) X = np.random.randn(100, 10) X = np.hstack([X, np.zeros([100, 5])]) def featureSelection_variance(X, thrd): sel = VarianceThreshold(threshold=thrd) X_selected = sel.fit_transform(X) mask = sel.get_support() return X_selected, mask X = [[0, 2, 0, 3], [0, 1, 4, 3], [0, 1, 1, 3]] selector = VarianceThreshold() selector.fit_transform(X) selector.variances_
true
true
f70004bcd049386ad073e2d45bf8fe56d0639a36
3,382
py
Python
mnist/my_multi_tune3.py
silent567/examples
e9de12549125ecd93a4924f6b8e2bbf66d7635d9
[ "BSD-3-Clause" ]
null
null
null
mnist/my_multi_tune3.py
silent567/examples
e9de12549125ecd93a4924f6b8e2bbf66d7635d9
[ "BSD-3-Clause" ]
null
null
null
mnist/my_multi_tune3.py
silent567/examples
e9de12549125ecd93a4924f6b8e2bbf66d7635d9
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # coding=utf-8 from my_multi_main3 import main import numpy as np import argparse import time parser = argparse.ArgumentParser(description='PyTorch MNIST Example') parser.add_argument('--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N', help='input batch size for testing (default: 1000)') parser.add_argument('--epochs', type=int, default=10, metavar='N', help='number of epochs to train (default: 10)') parser.add_argument('--lr', type=float, default=0.01, metavar='LR', help='learning rate (default: 0.01)') parser.add_argument('--momentum', type=float, default=0.5, metavar='M', help='SGD momentum (default: 0.5)') parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)') parser.add_argument('--log-interval', type=int, default=10, metavar='N', help='how many batches to wait before logging training status') parser.add_argument('--save-model', action='store_true', default=False, help='For Saving the current Model') parser.add_argument('--norm-flag', type=bool, default=False, help='Triggering the Layer Normalization flag for attention scores') parser.add_argument('--gamma', type=float, default=None, help='Controlling the sparisty of gfusedmax/sparsemax, the smaller, the more sparse') parser.add_argument('--lam', type=float, default=1.0, help='Lambda: Controlling the smoothness of gfusedmax, the larger, the smoother') parser.add_argument('--max-type', type=str, default='softmax',choices=['softmax','sparsemax','gfusedmax'], help='mapping function in attention') parser.add_argument('--optim-type', type=str, default='SGD',choices=['SGD','Adam'], help='mapping function in attention') parser.add_argument('--head-cnt', type=int, default=2, metavar='S', choices=[1,2,4,5,10], help='Number of heads for attention (default: 1)') args = parser.parse_args() hyperparameter_choices = { 'lr':list(10**np.arange(-4,-1,0.5)), 'norm_flag': [True,False], 'gamma':list(10**np.arange(-1,3,0.5))+[None,], 'lam':list(10**np.arange(-2,2,0.5)), 'max_type':['softmax','sparsemax','gfusedmax'], # 'max_type':['sparsemax'], 'optim_type':['SGD','Adam'], 'head_cnt':[1,2,4,5,10,20] } param_num = 25 record = np.zeros([param_num,len(hyperparameter_choices)+1]) record_name = 'record3_multi_%s.csv'%time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime()) for n in range(param_num): for param_index,(k,v) in enumerate(hyperparameter_choices.items()): print(param_index,k) value_index = np.random.choice(len(v)) if isinstance(v[value_index],str) or isinstance(v[value_index],bool) or v[value_index] is None: record[n,param_index] = value_index else: record[n,param_index] = v[value_index] setattr(args,k,v[value_index]) record[n,-1] = main(args) np.savetxt(record_name, record, delimiter=',')
47.633803
106
0.642815
from my_multi_main3 import main import numpy as np import argparse import time parser = argparse.ArgumentParser(description='PyTorch MNIST Example') parser.add_argument('--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N', help='input batch size for testing (default: 1000)') parser.add_argument('--epochs', type=int, default=10, metavar='N', help='number of epochs to train (default: 10)') parser.add_argument('--lr', type=float, default=0.01, metavar='LR', help='learning rate (default: 0.01)') parser.add_argument('--momentum', type=float, default=0.5, metavar='M', help='SGD momentum (default: 0.5)') parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)') parser.add_argument('--log-interval', type=int, default=10, metavar='N', help='how many batches to wait before logging training status') parser.add_argument('--save-model', action='store_true', default=False, help='For Saving the current Model') parser.add_argument('--norm-flag', type=bool, default=False, help='Triggering the Layer Normalization flag for attention scores') parser.add_argument('--gamma', type=float, default=None, help='Controlling the sparisty of gfusedmax/sparsemax, the smaller, the more sparse') parser.add_argument('--lam', type=float, default=1.0, help='Lambda: Controlling the smoothness of gfusedmax, the larger, the smoother') parser.add_argument('--max-type', type=str, default='softmax',choices=['softmax','sparsemax','gfusedmax'], help='mapping function in attention') parser.add_argument('--optim-type', type=str, default='SGD',choices=['SGD','Adam'], help='mapping function in attention') parser.add_argument('--head-cnt', type=int, default=2, metavar='S', choices=[1,2,4,5,10], help='Number of heads for attention (default: 1)') args = parser.parse_args() hyperparameter_choices = { 'lr':list(10**np.arange(-4,-1,0.5)), 'norm_flag': [True,False], 'gamma':list(10**np.arange(-1,3,0.5))+[None,], 'lam':list(10**np.arange(-2,2,0.5)), 'max_type':['softmax','sparsemax','gfusedmax'], 'optim_type':['SGD','Adam'], 'head_cnt':[1,2,4,5,10,20] } param_num = 25 record = np.zeros([param_num,len(hyperparameter_choices)+1]) record_name = 'record3_multi_%s.csv'%time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime()) for n in range(param_num): for param_index,(k,v) in enumerate(hyperparameter_choices.items()): print(param_index,k) value_index = np.random.choice(len(v)) if isinstance(v[value_index],str) or isinstance(v[value_index],bool) or v[value_index] is None: record[n,param_index] = value_index else: record[n,param_index] = v[value_index] setattr(args,k,v[value_index]) record[n,-1] = main(args) np.savetxt(record_name, record, delimiter=',')
true
true
f70004db8d93803fe1fd484a52ec6add2822ccb6
1,050
py
Python
spiker/data/hdf5.py
duguyue100/spiker
09437be393d7adf132f8ee2682e5b5b009c793a1
[ "MIT" ]
1
2021-01-13T10:46:44.000Z
2021-01-13T10:46:44.000Z
spiker/data/hdf5.py
duguyue100/spiker
09437be393d7adf132f8ee2682e5b5b009c793a1
[ "MIT" ]
null
null
null
spiker/data/hdf5.py
duguyue100/spiker
09437be393d7adf132f8ee2682e5b5b009c793a1
[ "MIT" ]
null
null
null
"""HDF5 related files. This file contains a set of functions that related to read and write HDF5 files. Author: Yuhuang Hu Email : [email protected] """ from __future__ import print_function, absolute_import import h5py from spiker import log logger = log.get_logger("data-hdf5", log.DEBUG) def init_hdf5(file_path, mode="w", cam_type="davis"): """Init HDF5 file object. # Parameters file_path : str absolute path for the HDF5 file. mode : str w : for writing r : for reading cam_type : str davis : for DAVIS camera dvs : for DVS camera # Returns dataset : h5py.File The file object of the given dataset """ if mode == "w": dataset = h5py.File(file_path, mode=mode) dataset.create_group("dvs") dataset.create_group("extra") if cam_type == "davis": dataset.create_group("aps") dataset.create_group("imu") elif mode == "r": dataset = h5py.File(file_path, mode=mode) return dataset
22.826087
68
0.629524
from __future__ import print_function, absolute_import import h5py from spiker import log logger = log.get_logger("data-hdf5", log.DEBUG) def init_hdf5(file_path, mode="w", cam_type="davis"): if mode == "w": dataset = h5py.File(file_path, mode=mode) dataset.create_group("dvs") dataset.create_group("extra") if cam_type == "davis": dataset.create_group("aps") dataset.create_group("imu") elif mode == "r": dataset = h5py.File(file_path, mode=mode) return dataset
true
true
f70006680091e477a9da34fc8c775b99d72def25
951
py
Python
thirdparty/org/apache/arrow/flatbuf/FloatingPoint.py
mrocklin/pygdf
2de9407427da9497ebdf8951a12857be0fab31bb
[ "Apache-2.0" ]
5
2018-10-17T20:28:42.000Z
2022-02-15T17:33:01.000Z
thirdparty/org/apache/arrow/flatbuf/FloatingPoint.py
mrocklin/pygdf
2de9407427da9497ebdf8951a12857be0fab31bb
[ "Apache-2.0" ]
19
2018-07-18T07:15:44.000Z
2021-02-22T17:00:18.000Z
thirdparty/org/apache/arrow/flatbuf/FloatingPoint.py
mrocklin/pygdf
2de9407427da9497ebdf8951a12857be0fab31bb
[ "Apache-2.0" ]
2
2020-05-01T09:54:34.000Z
2021-04-17T10:57:07.000Z
# automatically generated by the FlatBuffers compiler, do not modify # namespace: flatbuf import flatbuffers class FloatingPoint(object): __slots__ = ['_tab'] @classmethod def GetRootAsFloatingPoint(cls, buf, offset): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = FloatingPoint() x.Init(buf, n + offset) return x # FloatingPoint def Init(self, buf, pos): self._tab = flatbuffers.table.Table(buf, pos) # FloatingPoint def Precision(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) if o != 0: return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos) return 0 def FloatingPointStart(builder): builder.StartObject(1) def FloatingPointAddPrecision(builder, precision): builder.PrependInt16Slot(0, precision, 0) def FloatingPointEnd(builder): return builder.EndObject()
30.677419
92
0.698212
import flatbuffers class FloatingPoint(object): __slots__ = ['_tab'] @classmethod def GetRootAsFloatingPoint(cls, buf, offset): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = FloatingPoint() x.Init(buf, n + offset) return x def Init(self, buf, pos): self._tab = flatbuffers.table.Table(buf, pos) def Precision(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) if o != 0: return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos) return 0 def FloatingPointStart(builder): builder.StartObject(1) def FloatingPointAddPrecision(builder, precision): builder.PrependInt16Slot(0, precision, 0) def FloatingPointEnd(builder): return builder.EndObject()
true
true
f70006c8c5153a3a1bb1f109dc563a53c20f0e43
162
py
Python
.history/Classiles/scynced_lights_20210615191535.py
minefarmer/Coding101-OOP
d5655977559e3bd1acf6a4f185a6121cc3b05ce4
[ "Unlicense" ]
null
null
null
.history/Classiles/scynced_lights_20210615191535.py
minefarmer/Coding101-OOP
d5655977559e3bd1acf6a4f185a6121cc3b05ce4
[ "Unlicense" ]
null
null
null
.history/Classiles/scynced_lights_20210615191535.py
minefarmer/Coding101-OOP
d5655977559e3bd1acf6a4f185a6121cc3b05ce4
[ "Unlicense" ]
null
null
null
"""[Scynced Lights] Class attributes are "shared" Instance attributes are not shared. """ def sub(x, y): f class Light: pass a = Light() b = Ligth()
10.125
35
0.62963
def sub(x, y): f class Light: pass a = Light() b = Ligth()
true
true
f70006d0df161d84dd7ec30a6d7506b5802d1f0c
9,378
py
Python
pyspider/libs/counter.py
willworks/pyspider
9fc2ffa57324d1a42ef767289faa3a04f4d20f2e
[ "Apache-2.0" ]
1
2015-11-08T07:33:31.000Z
2015-11-08T07:33:31.000Z
pyspider/libs/counter.py
willworks/pyspider
9fc2ffa57324d1a42ef767289faa3a04f4d20f2e
[ "Apache-2.0" ]
null
null
null
pyspider/libs/counter.py
willworks/pyspider
9fc2ffa57324d1a42ef767289faa3a04f4d20f2e
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<[email protected]> # http://binux.me # Created on 2012-11-14 17:09:50 from __future__ import unicode_literals, division, absolute_import import time import logging from collections import deque try: from UserDict import DictMixin except ImportError: from collections import Mapping as DictMixin import six from six import iteritems from six.moves import cPickle class BaseCounter(object): def __init__(self): raise NotImplementedError def event(self, value=1): """Fire a event.""" raise NotImplementedError def value(self, value): """Set counter value.""" raise NotImplementedError @property def avg(self): """Get average value""" raise NotImplementedError @property def sum(self): """Get sum of counter""" raise NotImplementedError def empty(self): """Clear counter""" raise NotImplementedError class TotalCounter(BaseCounter): """Total counter""" def __init__(self): self.cnt = 0 def event(self, value=1): self.cnt += value def value(self, value): self.cnt = value @property def avg(self): return self.cnt @property def sum(self): return self.cnt def empty(self): return self.cnt == 0 class AverageWindowCounter(BaseCounter): """ Record last N(window) value """ def __init__(self, window_size=300): self.window_size = window_size self.values = deque(maxlen=window_size) def event(self, value=1): self.values.append(value) value = event @property def avg(self): return self.sum / len(self.values) @property def sum(self): return sum(self.values) def empty(self): if not self.values: return True class TimebaseAverageWindowCounter(BaseCounter): """ Record last window_size * window_interval seconds values. records will trim evert window_interval seconds """ def __init__(self, window_size=30, window_interval=10): self.max_window_size = window_size self.window_size = 0 self.window_interval = window_interval self.values = deque(maxlen=window_size) self.times = deque(maxlen=window_size) self.cache_value = 0 self.cache_start = None self._first_data_time = None def event(self, value=1): now = time.time() if self._first_data_time is None: self._first_data_time = now if self.cache_start is None: self.cache_value = value self.cache_start = now elif now - self.cache_start > self.window_interval: self.values.append(self.cache_value) self.times.append(self.cache_start) self.on_append(self.cache_value, self.cache_start) self.cache_value = value self.cache_start = now else: self.cache_value += value return self def value(self, value): self.cache_value = value def _trim_window(self): now = time.time() if self.cache_start and now - self.cache_start > self.window_interval: self.values.append(self.cache_value) self.times.append(self.cache_start) self.on_append(self.cache_value, self.cache_start) self.cache_value = 0 self.cache_start = None if self.window_size != self.max_window_size and self._first_data_time is not None: time_passed = now - self._first_data_time self.window_size = min(self.max_window_size, time_passed / self.window_interval) window_limit = now - self.window_size * self.window_interval while self.times and self.times[0] < window_limit: self.times.popleft() self.values.popleft() @property def avg(self): sum = float(self.sum) if not self.window_size: return 0 return sum / self.window_size / self.window_interval @property def sum(self): self._trim_window() return sum(self.values) + self.cache_value def empty(self): self._trim_window() if not self.values and not self.cache_start: return True def on_append(self, value, time): pass class CounterValue(DictMixin): """ A dict like value item for CounterManager. """ def __init__(self, manager, keys): self.manager = manager self._keys = keys def __getitem__(self, key): if key == '__value__': key = self._keys return self.manager.counters[key] else: key = self._keys + (key, ) available_keys = [] for _key in self.manager.counters: if _key[:len(key)] == key: available_keys.append(_key) if len(available_keys) == 0: raise KeyError elif len(available_keys) == 1: if available_keys[0] == key: return self.manager.counters[key] else: return CounterValue(self.manager, key) else: return CounterValue(self.manager, key) def __len__(self): return len(self.keys()) def __iter__(self): return iter(self.keys()) def __contains__(self, key): return key in self.keys() def keys(self): result = set() for key in self.manager.counters: if key[:len(self._keys)] == self._keys: key = key[len(self._keys):] result.add(key[0] if key else '__value__') return result def to_dict(self, get_value=None): """Dump counters as a dict""" result = {} for key, value in iteritems(self): if isinstance(value, BaseCounter): if get_value is not None: value = getattr(value, get_value) result[key] = value else: result[key] = value.to_dict(get_value) return result class CounterManager(DictMixin): """ A dict like counter manager. When using a tuple as event key, say: ('foo', 'bar'), You can visite counter with manager['foo']['bar']. Or get all counters which first element is 'foo' by manager['foo']. It's useful for a group of counters. """ def __init__(self, cls=TimebaseAverageWindowCounter): """init manager with Counter cls""" self.cls = cls self.counters = {} def event(self, key, value=1): """Fire a event of a counter by counter key""" if isinstance(key, six.string_types): key = (key, ) assert isinstance(key, tuple), "event key type error" if key not in self.counters: self.counters[key] = self.cls() self.counters[key].event(value) return self def value(self, key, value=1): """Set value of a counter by counter key""" if isinstance(key, six.string_types): key = (key, ) assert isinstance(key, tuple), "event key type error" if key not in self.counters: self.counters[key] = self.cls() self.counters[key].value(value) return self def trim(self): """Clear not used counters""" for key, value in list(iteritems(self.counters)): if value.empty(): del self.counters[key] def __getitem__(self, key): key = (key, ) available_keys = [] for _key in self.counters: if _key[:len(key)] == key: available_keys.append(_key) if len(available_keys) == 0: raise KeyError elif len(available_keys) == 1: if available_keys[0] == key: return self.counters[key] else: return CounterValue(self, key) else: return CounterValue(self, key) def __iter__(self): return iter(self.keys()) def __len__(self): return len(self.keys()) def keys(self): result = set() for key in self.counters: result.add(key[0] if key else ()) return result def to_dict(self, get_value=None): """Dump counters as a dict""" self.trim() result = {} for key, value in iteritems(self): if isinstance(value, BaseCounter): if get_value is not None: value = getattr(value, get_value) result[key] = value else: result[key] = value.to_dict(get_value) return result def dump(self, filename): """Dump counters to file""" try: with open(filename, 'wb') as fp: cPickle.dump(self.counters, fp) except: logging.error("can't dump counter to file: %s" % filename) return False return True def load(self, filename): """Load counters to file""" try: with open(filename) as fp: self.counters = cPickle.load(fp) except: logging.debug("can't load counter from file: %s" % filename) return False return True
27.341108
92
0.579335
from __future__ import unicode_literals, division, absolute_import import time import logging from collections import deque try: from UserDict import DictMixin except ImportError: from collections import Mapping as DictMixin import six from six import iteritems from six.moves import cPickle class BaseCounter(object): def __init__(self): raise NotImplementedError def event(self, value=1): raise NotImplementedError def value(self, value): raise NotImplementedError @property def avg(self): raise NotImplementedError @property def sum(self): raise NotImplementedError def empty(self): raise NotImplementedError class TotalCounter(BaseCounter): def __init__(self): self.cnt = 0 def event(self, value=1): self.cnt += value def value(self, value): self.cnt = value @property def avg(self): return self.cnt @property def sum(self): return self.cnt def empty(self): return self.cnt == 0 class AverageWindowCounter(BaseCounter): def __init__(self, window_size=300): self.window_size = window_size self.values = deque(maxlen=window_size) def event(self, value=1): self.values.append(value) value = event @property def avg(self): return self.sum / len(self.values) @property def sum(self): return sum(self.values) def empty(self): if not self.values: return True class TimebaseAverageWindowCounter(BaseCounter): def __init__(self, window_size=30, window_interval=10): self.max_window_size = window_size self.window_size = 0 self.window_interval = window_interval self.values = deque(maxlen=window_size) self.times = deque(maxlen=window_size) self.cache_value = 0 self.cache_start = None self._first_data_time = None def event(self, value=1): now = time.time() if self._first_data_time is None: self._first_data_time = now if self.cache_start is None: self.cache_value = value self.cache_start = now elif now - self.cache_start > self.window_interval: self.values.append(self.cache_value) self.times.append(self.cache_start) self.on_append(self.cache_value, self.cache_start) self.cache_value = value self.cache_start = now else: self.cache_value += value return self def value(self, value): self.cache_value = value def _trim_window(self): now = time.time() if self.cache_start and now - self.cache_start > self.window_interval: self.values.append(self.cache_value) self.times.append(self.cache_start) self.on_append(self.cache_value, self.cache_start) self.cache_value = 0 self.cache_start = None if self.window_size != self.max_window_size and self._first_data_time is not None: time_passed = now - self._first_data_time self.window_size = min(self.max_window_size, time_passed / self.window_interval) window_limit = now - self.window_size * self.window_interval while self.times and self.times[0] < window_limit: self.times.popleft() self.values.popleft() @property def avg(self): sum = float(self.sum) if not self.window_size: return 0 return sum / self.window_size / self.window_interval @property def sum(self): self._trim_window() return sum(self.values) + self.cache_value def empty(self): self._trim_window() if not self.values and not self.cache_start: return True def on_append(self, value, time): pass class CounterValue(DictMixin): def __init__(self, manager, keys): self.manager = manager self._keys = keys def __getitem__(self, key): if key == '__value__': key = self._keys return self.manager.counters[key] else: key = self._keys + (key, ) available_keys = [] for _key in self.manager.counters: if _key[:len(key)] == key: available_keys.append(_key) if len(available_keys) == 0: raise KeyError elif len(available_keys) == 1: if available_keys[0] == key: return self.manager.counters[key] else: return CounterValue(self.manager, key) else: return CounterValue(self.manager, key) def __len__(self): return len(self.keys()) def __iter__(self): return iter(self.keys()) def __contains__(self, key): return key in self.keys() def keys(self): result = set() for key in self.manager.counters: if key[:len(self._keys)] == self._keys: key = key[len(self._keys):] result.add(key[0] if key else '__value__') return result def to_dict(self, get_value=None): result = {} for key, value in iteritems(self): if isinstance(value, BaseCounter): if get_value is not None: value = getattr(value, get_value) result[key] = value else: result[key] = value.to_dict(get_value) return result class CounterManager(DictMixin): def __init__(self, cls=TimebaseAverageWindowCounter): self.cls = cls self.counters = {} def event(self, key, value=1): if isinstance(key, six.string_types): key = (key, ) assert isinstance(key, tuple), "event key type error" if key not in self.counters: self.counters[key] = self.cls() self.counters[key].event(value) return self def value(self, key, value=1): if isinstance(key, six.string_types): key = (key, ) assert isinstance(key, tuple), "event key type error" if key not in self.counters: self.counters[key] = self.cls() self.counters[key].value(value) return self def trim(self): for key, value in list(iteritems(self.counters)): if value.empty(): del self.counters[key] def __getitem__(self, key): key = (key, ) available_keys = [] for _key in self.counters: if _key[:len(key)] == key: available_keys.append(_key) if len(available_keys) == 0: raise KeyError elif len(available_keys) == 1: if available_keys[0] == key: return self.counters[key] else: return CounterValue(self, key) else: return CounterValue(self, key) def __iter__(self): return iter(self.keys()) def __len__(self): return len(self.keys()) def keys(self): result = set() for key in self.counters: result.add(key[0] if key else ()) return result def to_dict(self, get_value=None): self.trim() result = {} for key, value in iteritems(self): if isinstance(value, BaseCounter): if get_value is not None: value = getattr(value, get_value) result[key] = value else: result[key] = value.to_dict(get_value) return result def dump(self, filename): try: with open(filename, 'wb') as fp: cPickle.dump(self.counters, fp) except: logging.error("can't dump counter to file: %s" % filename) return False return True def load(self, filename): try: with open(filename) as fp: self.counters = cPickle.load(fp) except: logging.debug("can't load counter from file: %s" % filename) return False return True
true
true
f700088372c0eeaff049211c5fe92cdccb5fa804
6,706
py
Python
src/transformers/models/vit/feature_extraction_vit.py
djroxx2000/transformers
77770ec79883343d32051cfb6a04f64523cd8df1
[ "Apache-2.0" ]
723
2020-07-16T13:02:25.000Z
2022-03-31T21:03:55.000Z
src/transformers/models/vit/feature_extraction_vit.py
4nalog/transformers
76cadb7943c8492ec481f4f3925e9e8793a32c9d
[ "Apache-2.0" ]
170
2020-07-16T14:39:11.000Z
2022-03-31T13:02:11.000Z
src/transformers/models/vit/feature_extraction_vit.py
4nalog/transformers
76cadb7943c8492ec481f4f3925e9e8793a32c9d
[ "Apache-2.0" ]
131
2020-07-16T14:38:16.000Z
2022-03-29T19:43:18.000Z
# coding=utf-8 # Copyright 2021 The HuggingFace Inc. team. 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. """Feature extractor class for ViT.""" from typing import List, Optional, Union import numpy as np from PIL import Image from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...file_utils import TensorType from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ImageFeatureExtractionMixin, is_torch_tensor from ...utils import logging logger = logging.get_logger(__name__) class ViTFeatureExtractor(FeatureExtractionMixin, ImageFeatureExtractionMixin): r""" Constructs a ViT feature extractor. This feature extractor inherits from :class:`~transformers.FeatureExtractionMixin` which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. Args: do_resize (:obj:`bool`, `optional`, defaults to :obj:`True`): Whether to resize the input to a certain :obj:`size`. size (:obj:`int` or :obj:`Tuple(int)`, `optional`, defaults to 224): Resize the input to the given size. If a tuple is provided, it should be (width, height). If only an integer is provided, then the input will be resized to (size, size). Only has an effect if :obj:`do_resize` is set to :obj:`True`. resample (:obj:`int`, `optional`, defaults to :obj:`PIL.Image.BILINEAR`): An optional resampling filter. This can be one of :obj:`PIL.Image.NEAREST`, :obj:`PIL.Image.BOX`, :obj:`PIL.Image.BILINEAR`, :obj:`PIL.Image.HAMMING`, :obj:`PIL.Image.BICUBIC` or :obj:`PIL.Image.LANCZOS`. Only has an effect if :obj:`do_resize` is set to :obj:`True`. do_normalize (:obj:`bool`, `optional`, defaults to :obj:`True`): Whether or not to normalize the input with mean and standard deviation. image_mean (:obj:`List[int]`, defaults to :obj:`[0.5, 0.5, 0.5]`): The sequence of means for each channel, to be used when normalizing images. image_std (:obj:`List[int]`, defaults to :obj:`[0.5, 0.5, 0.5]`): The sequence of standard deviations for each channel, to be used when normalizing images. """ model_input_names = ["pixel_values"] def __init__( self, do_resize=True, size=224, resample=Image.BILINEAR, do_normalize=True, image_mean=None, image_std=None, **kwargs ): super().__init__(**kwargs) self.do_resize = do_resize self.size = size self.resample = resample self.do_normalize = do_normalize self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD def __call__( self, images: Union[ Image.Image, np.ndarray, "torch.Tensor", List[Image.Image], List[np.ndarray], List["torch.Tensor"] # noqa ], return_tensors: Optional[Union[str, TensorType]] = None, **kwargs ) -> BatchFeature: """ Main method to prepare for the model one or several image(s). .. warning:: NumPy arrays and PyTorch tensors are converted to PIL images when resizing, so the most efficient is to pass PIL images. Args: images (:obj:`PIL.Image.Image`, :obj:`np.ndarray`, :obj:`torch.Tensor`, :obj:`List[PIL.Image.Image]`, :obj:`List[np.ndarray]`, :obj:`List[torch.Tensor]`): The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a number of channels, H and W are image height and width. return_tensors (:obj:`str` or :class:`~transformers.file_utils.TensorType`, `optional`, defaults to :obj:`'np'`): If set, will return tensors of a particular framework. Acceptable values are: * :obj:`'tf'`: Return TensorFlow :obj:`tf.constant` objects. * :obj:`'pt'`: Return PyTorch :obj:`torch.Tensor` objects. * :obj:`'np'`: Return NumPy :obj:`np.ndarray` objects. * :obj:`'jax'`: Return JAX :obj:`jnp.ndarray` objects. Returns: :class:`~transformers.BatchFeature`: A :class:`~transformers.BatchFeature` with the following fields: - **pixel_values** -- Pixel values to be fed to a model, of shape (batch_size, num_channels, height, width). """ # Input type checking for clearer error valid_images = False # Check that images has a valid type if isinstance(images, (Image.Image, np.ndarray)) or is_torch_tensor(images): valid_images = True elif isinstance(images, (list, tuple)): if len(images) == 0 or isinstance(images[0], (Image.Image, np.ndarray)) or is_torch_tensor(images[0]): valid_images = True if not valid_images: raise ValueError( "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example)," "`List[PIL.Image.Image]`, `List[np.ndarray]` or `List[torch.Tensor]` (batch of examples)." ) is_batched = bool( isinstance(images, (list, tuple)) and (isinstance(images[0], (Image.Image, np.ndarray)) or is_torch_tensor(images[0])) ) if not is_batched: images = [images] # transformations (resizing + normalization) if self.do_resize and self.size is not None: images = [self.resize(image=image, size=self.size, resample=self.resample) for image in images] if self.do_normalize: images = [self.normalize(image=image, mean=self.image_mean, std=self.image_std) for image in images] # return as BatchFeature data = {"pixel_values": images} encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors) return encoded_inputs
45.310811
166
0.646287
from typing import List, Optional, Union import numpy as np from PIL import Image from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...file_utils import TensorType from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ImageFeatureExtractionMixin, is_torch_tensor from ...utils import logging logger = logging.get_logger(__name__) class ViTFeatureExtractor(FeatureExtractionMixin, ImageFeatureExtractionMixin): model_input_names = ["pixel_values"] def __init__( self, do_resize=True, size=224, resample=Image.BILINEAR, do_normalize=True, image_mean=None, image_std=None, **kwargs ): super().__init__(**kwargs) self.do_resize = do_resize self.size = size self.resample = resample self.do_normalize = do_normalize self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD def __call__( self, images: Union[ Image.Image, np.ndarray, "torch.Tensor", List[Image.Image], List[np.ndarray], List["torch.Tensor"] ], return_tensors: Optional[Union[str, TensorType]] = None, **kwargs ) -> BatchFeature: valid_images = False if isinstance(images, (Image.Image, np.ndarray)) or is_torch_tensor(images): valid_images = True elif isinstance(images, (list, tuple)): if len(images) == 0 or isinstance(images[0], (Image.Image, np.ndarray)) or is_torch_tensor(images[0]): valid_images = True if not valid_images: raise ValueError( "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example)," "`List[PIL.Image.Image]`, `List[np.ndarray]` or `List[torch.Tensor]` (batch of examples)." ) is_batched = bool( isinstance(images, (list, tuple)) and (isinstance(images[0], (Image.Image, np.ndarray)) or is_torch_tensor(images[0])) ) if not is_batched: images = [images] if self.do_resize and self.size is not None: images = [self.resize(image=image, size=self.size, resample=self.resample) for image in images] if self.do_normalize: images = [self.normalize(image=image, mean=self.image_mean, std=self.image_std) for image in images] data = {"pixel_values": images} encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors) return encoded_inputs
true
true
f700096cbce5db1538215892bb1dcc76b6c37987
734
py
Python
hier/project-euler/euler-067-hackerrank/euler067.py
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
hier/project-euler/euler-067-hackerrank/euler067.py
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
hier/project-euler/euler-067-hackerrank/euler067.py
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
#!/usr/bin/env python3 UNKNOWN = -1 def read_val(): return int(input()) def read_row(): return list(map(int, input().split())) def read_grid(): return [read_row() for _ in range(read_val())] def make_blank_row(i): return [UNKNOWN] * i def make_blank_grid(n): return [make_blank_row(i) for i in range(1, n + 1)] def compute_max_path_sum(grid): memo = make_blank_grid(len(grid)) def dfs(i, j): if i == len(grid): return 0 if memo[i][j] == UNKNOWN: memo[i][j] = grid[i][j] + max(dfs(i + 1, j), dfs(i + 1, j + 1)) return memo[i][j] return dfs(0, 0) for t in range(read_val()): print(compute_max_path_sum(read_grid()))
20.388889
75
0.564033
UNKNOWN = -1 def read_val(): return int(input()) def read_row(): return list(map(int, input().split())) def read_grid(): return [read_row() for _ in range(read_val())] def make_blank_row(i): return [UNKNOWN] * i def make_blank_grid(n): return [make_blank_row(i) for i in range(1, n + 1)] def compute_max_path_sum(grid): memo = make_blank_grid(len(grid)) def dfs(i, j): if i == len(grid): return 0 if memo[i][j] == UNKNOWN: memo[i][j] = grid[i][j] + max(dfs(i + 1, j), dfs(i + 1, j + 1)) return memo[i][j] return dfs(0, 0) for t in range(read_val()): print(compute_max_path_sum(read_grid()))
true
true
f7000a85ea7a735edb59575f149fc6ff7ce4b461
1,866
py
Python
tools/apps/find_blender.py
SeijiEmery/unity_tools
cb401e6979b95c081a2ab3f944fc6e4419ccfd0e
[ "MIT" ]
null
null
null
tools/apps/find_blender.py
SeijiEmery/unity_tools
cb401e6979b95c081a2ab3f944fc6e4419ccfd0e
[ "MIT" ]
null
null
null
tools/apps/find_blender.py
SeijiEmery/unity_tools
cb401e6979b95c081a2ab3f944fc6e4419ccfd0e
[ "MIT" ]
null
null
null
import platform # print(platform.system()) operating_system = platform.system().lower() if operating_system == 'darwin': from .blender_utils_macos import get_installed_blender_versions operating_system_name = 'macos' elif operating_system == 'linux': from .blender_utils_linux import get_installed_blender_versions operating_system_name = 'linux' elif operating_system == 'windows': from .blender_utils_windows import get_installed_blender_versions operating_system_name = 'windows' else: raise Exception("Unimplemented for OS {}".format(operating_system)) from .blender_utils_web import get_blender_version_download_links def find_blender(version): # TODO: add fuzzy version matching, ie. '>=2.80', '~2.80', '<2.80', etc. installed_versions = get_installed_blender_versions() if version in installed_versions: return installed_versions[version] else: print("blender version '{}' not found; found {} version(s):".format(version, len(installed_versions))) for v, path in installed_versions.items(): print(" {}: {}".format(v, path)) print("searching web archive...") versions = get_blender_version_download_links(version, operating_system_name) print("found {} download(s) for blender version '{}', platform '{}':".format(len(versions), version, operating_system_name)) for url in versions: print(" {}".format(url)) if __name__ == '__main__': for version, exec_path in get_installed_blender_versions().items(): print("found blender {version}: {path}".format(version=version, path=exec_path)) blender = find_blender('2.80') if blender: print("Found blender: '{}'".format(blender)) else: print("No matching blender version installed :(")
40.565217
132
0.681136
import platform operating_system = platform.system().lower() if operating_system == 'darwin': from .blender_utils_macos import get_installed_blender_versions operating_system_name = 'macos' elif operating_system == 'linux': from .blender_utils_linux import get_installed_blender_versions operating_system_name = 'linux' elif operating_system == 'windows': from .blender_utils_windows import get_installed_blender_versions operating_system_name = 'windows' else: raise Exception("Unimplemented for OS {}".format(operating_system)) from .blender_utils_web import get_blender_version_download_links def find_blender(version): installed_versions = get_installed_blender_versions() if version in installed_versions: return installed_versions[version] else: print("blender version '{}' not found; found {} version(s):".format(version, len(installed_versions))) for v, path in installed_versions.items(): print(" {}: {}".format(v, path)) print("searching web archive...") versions = get_blender_version_download_links(version, operating_system_name) print("found {} download(s) for blender version '{}', platform '{}':".format(len(versions), version, operating_system_name)) for url in versions: print(" {}".format(url)) if __name__ == '__main__': for version, exec_path in get_installed_blender_versions().items(): print("found blender {version}: {path}".format(version=version, path=exec_path)) blender = find_blender('2.80') if blender: print("Found blender: '{}'".format(blender)) else: print("No matching blender version installed :(")
true
true
f7000b2945cb3703ec7fbc7ccf8cd64d39f12e81
8,196
py
Python
codes/data/image_corruptor.py
neonbjb/DL-Art-School
a6f0f854b987ac724e258af8b042ea4459a571bc
[ "Apache-2.0" ]
12
2020-12-13T12:45:03.000Z
2022-03-29T09:58:15.000Z
codes/data/image_corruptor.py
neonbjb/DL-Art-School
a6f0f854b987ac724e258af8b042ea4459a571bc
[ "Apache-2.0" ]
1
2020-12-31T01:12:45.000Z
2021-03-31T11:43:52.000Z
codes/data/image_corruptor.py
neonbjb/DL-Art-School
a6f0f854b987ac724e258af8b042ea4459a571bc
[ "Apache-2.0" ]
3
2020-12-14T06:04:04.000Z
2020-12-26T19:11:41.000Z
import functools import random from math import cos, pi import cv2 import kornia import numpy as np import torch from kornia.augmentation import ColorJitter from data.util import read_img from PIL import Image from io import BytesIO # Get a rough visualization of the above distribution. (Y-axis is meaningless, just spreads data) from utils.util import opt_get ''' if __name__ == '__main__': import numpy as np import matplotlib.pyplot as plt data = np.asarray([get_rand() for _ in range(5000)]) plt.plot(data, np.random.uniform(size=(5000,)), 'x') plt.show() ''' def kornia_color_jitter_numpy(img, setting): if setting * 255 > 1: # I'm using Kornia's ColorJitter, which requires pytorch arrays in b,c,h,w format. img = torch.from_numpy(img).permute(2,0,1).unsqueeze(0) img = ColorJitter(setting, setting, setting, setting)(img) img = img.squeeze(0).permute(1,2,0).numpy() return img # Performs image corruption on a list of images from a configurable set of corruption # options. class ImageCorruptor: def __init__(self, opt): self.opt = opt self.reset_random() self.blur_scale = opt['corruption_blur_scale'] if 'corruption_blur_scale' in opt.keys() else 1 self.fixed_corruptions = opt['fixed_corruptions'] if 'fixed_corruptions' in opt.keys() else [] self.num_corrupts = opt['num_corrupts_per_image'] if 'num_corrupts_per_image' in opt.keys() else 0 self.cosine_bias = opt_get(opt, ['cosine_bias'], True) if self.num_corrupts == 0: return else: self.random_corruptions = opt['random_corruptions'] if 'random_corruptions' in opt.keys() else [] def reset_random(self): if 'random_seed' in self.opt.keys(): self.rand = random.Random(self.opt['random_seed']) else: self.rand = random.Random() # Feeds a random uniform through a cosine distribution to slightly bias corruptions towards "uncorrupted". # Return is on [0,1] with a bias towards 0. def get_rand(self): r = self.rand.random() if self.cosine_bias: return 1 - cos(r * pi / 2) else: return r def corrupt_images(self, imgs, return_entropy=False): if self.num_corrupts == 0 and not self.fixed_corruptions: if return_entropy: return imgs, [] else: return imgs if self.num_corrupts == 0: augmentations = [] else: augmentations = random.choices(self.random_corruptions, k=self.num_corrupts) # Sources of entropy corrupted_imgs = [] entropy = [] undo_fns = [] applied_augs = augmentations + self.fixed_corruptions for img in imgs: for aug in augmentations: r = self.get_rand() img, undo_fn = self.apply_corruption(img, aug, r, applied_augs) if undo_fn is not None: undo_fns.append(undo_fn) for aug in self.fixed_corruptions: r = self.get_rand() img, undo_fn = self.apply_corruption(img, aug, r, applied_augs) entropy.append(r) if undo_fn is not None: undo_fns.append(undo_fn) # Apply undo_fns after all corruptions are finished, in same order. for ufn in undo_fns: img = ufn(img) corrupted_imgs.append(img) if return_entropy: return corrupted_imgs, entropy else: return corrupted_imgs def apply_corruption(self, img, aug, rand_val, applied_augmentations): undo_fn = None if 'color_quantization' in aug: # Color quantization quant_div = 2 ** (int(rand_val * 10 / 3) + 2) img = img * 255 img = (img // quant_div) * quant_div img = img / 255 elif 'color_jitter' in aug: lo_end = 0 hi_end = .2 setting = rand_val * (hi_end - lo_end) + lo_end img = kornia_color_jitter_numpy(img, setting) elif 'gaussian_blur' in aug: img = cv2.GaussianBlur(img, (0,0), self.blur_scale*rand_val*1.5) elif 'motion_blur' in aug: # Motion blur intensity = self.blur_scale*rand_val * 3 + 1 angle = random.randint(0,360) k = np.zeros((intensity, intensity), dtype=np.float32) k[(intensity - 1) // 2, :] = np.ones(intensity, dtype=np.float32) k = cv2.warpAffine(k, cv2.getRotationMatrix2D((intensity / 2 - 0.5, intensity / 2 - 0.5), angle, 1.0), (intensity, intensity)) k = k * (1.0 / np.sum(k)) img = cv2.filter2D(img, -1, k) elif 'block_noise' in aug: # Large distortion blocks in part of an img, such as is used to mask out a face. pass elif 'lq_resampling' in aug: # Random mode interpolation HR->LR->HR if 'lq_resampling4x' == aug: scale = 4 else: if rand_val < .3: scale = 1 elif rand_val < .7: scale = 2 else: scale = 4 if scale > 1: interpolation_modes = [cv2.INTER_NEAREST, cv2.INTER_CUBIC, cv2.INTER_LINEAR, cv2.INTER_LANCZOS4] mode = random.randint(0,4) % len(interpolation_modes) # Downsample first, then upsample using the random mode. img = cv2.resize(img, dsize=(img.shape[1]//scale, img.shape[0]//scale), interpolation=mode) def lq_resampling_undo_fn(scale, img): return cv2.resize(img, dsize=(img.shape[1]*scale, img.shape[0]*scale), interpolation=cv2.INTER_LINEAR) undo_fn = functools.partial(lq_resampling_undo_fn, scale) elif 'color_shift' in aug: # Color shift pass elif 'interlacing' in aug: # Interlacing distortion pass elif 'chromatic_aberration' in aug: # Chromatic aberration pass elif 'noise' in aug: # Random noise if 'noise-5' == aug: noise_intensity = 5 / 255.0 else: noise_intensity = (rand_val*6) / 255.0 img += np.random.rand(*img.shape) * noise_intensity elif 'jpeg' in aug: if 'noise' not in applied_augmentations and 'noise-5' not in applied_augmentations: if aug == 'jpeg': lo=10 range=20 elif aug == 'jpeg-low': lo=15 range=10 elif aug == 'jpeg-medium': lo=23 range=25 elif aug == 'jpeg-broad': lo=15 range=60 elif aug == 'jpeg-normal': lo=47 range=35 else: raise NotImplementedError("specified jpeg corruption doesn't exist") # JPEG compression qf = (int((1-rand_val)*range) + lo) # Use PIL to perform a mock compression to a data buffer, then swap back to cv2. img = (img * 255).astype(np.uint8) img = Image.fromarray(img) buffer = BytesIO() img.save(buffer, "JPEG", quality=qf, optimize=True) buffer.seek(0) jpeg_img_bytes = np.asarray(bytearray(buffer.read()), dtype="uint8") img = read_img("buffer", jpeg_img_bytes, rgb=True) elif 'saturation' in aug: # Lightening / saturation saturation = rand_val * .3 img = np.clip(img + saturation, a_max=1, a_min=0) elif 'greyscale' in aug: img = np.tile(np.mean(img, axis=2, keepdims=True), [1,1,3]) elif 'none' not in aug: raise NotImplementedError("Augmentation doesn't exist") return img, undo_fn
39.028571
122
0.554173
import functools import random from math import cos, pi import cv2 import kornia import numpy as np import torch from kornia.augmentation import ColorJitter from data.util import read_img from PIL import Image from io import BytesIO from utils.util import opt_get def kornia_color_jitter_numpy(img, setting): if setting * 255 > 1: img = torch.from_numpy(img).permute(2,0,1).unsqueeze(0) img = ColorJitter(setting, setting, setting, setting)(img) img = img.squeeze(0).permute(1,2,0).numpy() return img class ImageCorruptor: def __init__(self, opt): self.opt = opt self.reset_random() self.blur_scale = opt['corruption_blur_scale'] if 'corruption_blur_scale' in opt.keys() else 1 self.fixed_corruptions = opt['fixed_corruptions'] if 'fixed_corruptions' in opt.keys() else [] self.num_corrupts = opt['num_corrupts_per_image'] if 'num_corrupts_per_image' in opt.keys() else 0 self.cosine_bias = opt_get(opt, ['cosine_bias'], True) if self.num_corrupts == 0: return else: self.random_corruptions = opt['random_corruptions'] if 'random_corruptions' in opt.keys() else [] def reset_random(self): if 'random_seed' in self.opt.keys(): self.rand = random.Random(self.opt['random_seed']) else: self.rand = random.Random() def get_rand(self): r = self.rand.random() if self.cosine_bias: return 1 - cos(r * pi / 2) else: return r def corrupt_images(self, imgs, return_entropy=False): if self.num_corrupts == 0 and not self.fixed_corruptions: if return_entropy: return imgs, [] else: return imgs if self.num_corrupts == 0: augmentations = [] else: augmentations = random.choices(self.random_corruptions, k=self.num_corrupts) corrupted_imgs = [] entropy = [] undo_fns = [] applied_augs = augmentations + self.fixed_corruptions for img in imgs: for aug in augmentations: r = self.get_rand() img, undo_fn = self.apply_corruption(img, aug, r, applied_augs) if undo_fn is not None: undo_fns.append(undo_fn) for aug in self.fixed_corruptions: r = self.get_rand() img, undo_fn = self.apply_corruption(img, aug, r, applied_augs) entropy.append(r) if undo_fn is not None: undo_fns.append(undo_fn) for ufn in undo_fns: img = ufn(img) corrupted_imgs.append(img) if return_entropy: return corrupted_imgs, entropy else: return corrupted_imgs def apply_corruption(self, img, aug, rand_val, applied_augmentations): undo_fn = None if 'color_quantization' in aug: quant_div = 2 ** (int(rand_val * 10 / 3) + 2) img = img * 255 img = (img // quant_div) * quant_div img = img / 255 elif 'color_jitter' in aug: lo_end = 0 hi_end = .2 setting = rand_val * (hi_end - lo_end) + lo_end img = kornia_color_jitter_numpy(img, setting) elif 'gaussian_blur' in aug: img = cv2.GaussianBlur(img, (0,0), self.blur_scale*rand_val*1.5) elif 'motion_blur' in aug: intensity = self.blur_scale*rand_val * 3 + 1 angle = random.randint(0,360) k = np.zeros((intensity, intensity), dtype=np.float32) k[(intensity - 1) // 2, :] = np.ones(intensity, dtype=np.float32) k = cv2.warpAffine(k, cv2.getRotationMatrix2D((intensity / 2 - 0.5, intensity / 2 - 0.5), angle, 1.0), (intensity, intensity)) k = k * (1.0 / np.sum(k)) img = cv2.filter2D(img, -1, k) elif 'block_noise' in aug: pass elif 'lq_resampling' in aug: if 'lq_resampling4x' == aug: scale = 4 else: if rand_val < .3: scale = 1 elif rand_val < .7: scale = 2 else: scale = 4 if scale > 1: interpolation_modes = [cv2.INTER_NEAREST, cv2.INTER_CUBIC, cv2.INTER_LINEAR, cv2.INTER_LANCZOS4] mode = random.randint(0,4) % len(interpolation_modes) img = cv2.resize(img, dsize=(img.shape[1]//scale, img.shape[0]//scale), interpolation=mode) def lq_resampling_undo_fn(scale, img): return cv2.resize(img, dsize=(img.shape[1]*scale, img.shape[0]*scale), interpolation=cv2.INTER_LINEAR) undo_fn = functools.partial(lq_resampling_undo_fn, scale) elif 'color_shift' in aug: pass elif 'interlacing' in aug: pass elif 'chromatic_aberration' in aug: pass elif 'noise' in aug: if 'noise-5' == aug: noise_intensity = 5 / 255.0 else: noise_intensity = (rand_val*6) / 255.0 img += np.random.rand(*img.shape) * noise_intensity elif 'jpeg' in aug: if 'noise' not in applied_augmentations and 'noise-5' not in applied_augmentations: if aug == 'jpeg': lo=10 range=20 elif aug == 'jpeg-low': lo=15 range=10 elif aug == 'jpeg-medium': lo=23 range=25 elif aug == 'jpeg-broad': lo=15 range=60 elif aug == 'jpeg-normal': lo=47 range=35 else: raise NotImplementedError("specified jpeg corruption doesn't exist") # JPEG compression qf = (int((1-rand_val)*range) + lo) # Use PIL to perform a mock compression to a data buffer, then swap back to cv2. img = (img * 255).astype(np.uint8) img = Image.fromarray(img) buffer = BytesIO() img.save(buffer, "JPEG", quality=qf, optimize=True) buffer.seek(0) jpeg_img_bytes = np.asarray(bytearray(buffer.read()), dtype="uint8") img = read_img("buffer", jpeg_img_bytes, rgb=True) elif 'saturation' in aug: # Lightening / saturation saturation = rand_val * .3 img = np.clip(img + saturation, a_max=1, a_min=0) elif 'greyscale' in aug: img = np.tile(np.mean(img, axis=2, keepdims=True), [1,1,3]) elif 'none' not in aug: raise NotImplementedError("Augmentation doesn't exist") return img, undo_fn
true
true
f7000b6751e6ca87c8cdd1ca6b7921d866ec80c7
159
py
Python
tests/basics/bytes_format_modulo.py
geowor01/micropython
7fb13eeef4a85f21cae36f1d502bcc53880e1815
[ "MIT" ]
7
2019-10-18T13:41:39.000Z
2022-03-15T17:27:57.000Z
tests/basics/bytes_format_modulo.py
geowor01/micropython
7fb13eeef4a85f21cae36f1d502bcc53880e1815
[ "MIT" ]
null
null
null
tests/basics/bytes_format_modulo.py
geowor01/micropython
7fb13eeef4a85f21cae36f1d502bcc53880e1815
[ "MIT" ]
2
2020-06-23T09:10:15.000Z
2020-12-22T06:42:14.000Z
# This test requires CPython3.5 print(b"%%" % ()) print(b"=%d=" % 1) print(b"=%d=%d=" % (1, 2)) print(b"=%s=" % b"str") print(b"=%r=" % b"str") print("PASS")
17.666667
31
0.503145
print(b"%%" % ()) print(b"=%d=" % 1) print(b"=%d=%d=" % (1, 2)) print(b"=%s=" % b"str") print(b"=%r=" % b"str") print("PASS")
true
true
f7000bbc055be36dc38b5ab214bad87b6d24f064
2,102
py
Python
tests/test_JpegCompression.py
tt195361/TfDataAugmentation
0deb987ae5a37816d88eec302bc42db7479ea8df
[ "MIT" ]
null
null
null
tests/test_JpegCompression.py
tt195361/TfDataAugmentation
0deb987ae5a37816d88eec302bc42db7479ea8df
[ "MIT" ]
null
null
null
tests/test_JpegCompression.py
tt195361/TfDataAugmentation
0deb987ae5a37816d88eec302bc42db7479ea8df
[ "MIT" ]
null
null
null
# # test_JpegCompression.py # import pytest import albumentations as A from .context import TfDataAugmentation as Tfda from . import test_utils from .test_utils import TestResult @pytest.mark.parametrize( "quality_lower, quality_upper, expected, message", [ # quality_lower (-1, 100, TestResult.Error, "quality_lower < min => Error"), (0, 100, TestResult.OK, "quality_lower == min => OK"), (100, 100, TestResult.OK, "quality_lower == max => OK"), (101, 100, TestResult.Error, "quality_lower >= max => Error"), # quality_upper (0, -1, TestResult.Error, "quality_upper < min => Error"), (0, 0, TestResult.OK, "quality_upper == min => OK"), (0, 100, TestResult.OK, "quality_upper == max => OK"), (0, 101, TestResult.Error, "quality_upper > max => Error"), # Relation (50, 50, TestResult.OK, "quality_lower == quality_upper => OK"), (51, 50, TestResult.Error, "quality_lower > quality_upper => Error"), ]) def test_hue_shift_limit_value( quality_lower, quality_upper, expected, message): try: Tfda.JpegCompression( quality_lower=quality_lower, quality_upper=quality_upper) actual = TestResult.OK except ValueError: actual = TestResult.Error assert expected == actual, message def test_call(): quality_lower = 50 quality_upper = 100 tgt_jpeg = Tfda.JpegCompression( quality_lower=quality_lower, quality_upper=quality_upper, p=1.0) tgt_transform = \ test_utils.make_tgt_transform(tgt_jpeg) image = test_utils.make_test_image() tgt_result = tgt_transform(image=image) actual_image = tgt_result['image'] image_np = image.numpy() quality = float(tgt_jpeg.get_param('quality')) expected_image = A.image_compression( image_np, quality, image_type='.jpg') test_utils.partial_assert_array( expected_image, actual_image, 0.6, "image", eps=0.1)
28.794521
60
0.621313
import pytest import albumentations as A from .context import TfDataAugmentation as Tfda from . import test_utils from .test_utils import TestResult @pytest.mark.parametrize( "quality_lower, quality_upper, expected, message", [ (-1, 100, TestResult.Error, "quality_lower < min => Error"), (0, 100, TestResult.OK, "quality_lower == min => OK"), (100, 100, TestResult.OK, "quality_lower == max => OK"), (101, 100, TestResult.Error, "quality_lower >= max => Error"), (0, -1, TestResult.Error, "quality_upper < min => Error"), (0, 0, TestResult.OK, "quality_upper == min => OK"), (0, 100, TestResult.OK, "quality_upper == max => OK"), (0, 101, TestResult.Error, "quality_upper > max => Error"), (50, 50, TestResult.OK, "quality_lower == quality_upper => OK"), (51, 50, TestResult.Error, "quality_lower > quality_upper => Error"), ]) def test_hue_shift_limit_value( quality_lower, quality_upper, expected, message): try: Tfda.JpegCompression( quality_lower=quality_lower, quality_upper=quality_upper) actual = TestResult.OK except ValueError: actual = TestResult.Error assert expected == actual, message def test_call(): quality_lower = 50 quality_upper = 100 tgt_jpeg = Tfda.JpegCompression( quality_lower=quality_lower, quality_upper=quality_upper, p=1.0) tgt_transform = \ test_utils.make_tgt_transform(tgt_jpeg) image = test_utils.make_test_image() tgt_result = tgt_transform(image=image) actual_image = tgt_result['image'] image_np = image.numpy() quality = float(tgt_jpeg.get_param('quality')) expected_image = A.image_compression( image_np, quality, image_type='.jpg') test_utils.partial_assert_array( expected_image, actual_image, 0.6, "image", eps=0.1)
true
true
f7000bc963cc817a5a5dca6aba86f5ea6dde667e
3,008
py
Python
tests/test_background_swap.py
pclucas14/continuum
3b9b0fc3c2f21dcaeafbccfa29987cefe55f37a0
[ "MIT" ]
4
2020-04-15T14:31:42.000Z
2020-04-24T17:07:34.000Z
tests/test_background_swap.py
pclucas14/continuum
3b9b0fc3c2f21dcaeafbccfa29987cefe55f37a0
[ "MIT" ]
18
2020-04-15T14:57:27.000Z
2020-05-02T14:05:36.000Z
tests/test_background_swap.py
arthurdouillard/continual_loader
09034db1371e9646ca660fd4d4df73e61bf77067
[ "MIT" ]
1
2020-04-15T15:50:28.000Z
2020-04-15T15:50:28.000Z
import os from torch.utils.data import DataLoader from continuum.datasets import CIFAR10, InMemoryDataset from continuum.datasets import MNIST import torchvision from continuum.scenarios import TransformationIncremental import pytest import numpy as np from continuum.transforms.bg_swap import BackgroundSwap DATA_PATH = os.environ.get("CONTINUUM_DATA_PATH") # Uncomment for debugging via image output # import matplotlib.pyplot as plt def test_bg_swap_fast(): """ Fast test for background swap. """ bg_x = np.ones(shape=[2, 5, 5, 3]) * -1 bg_y = np.random.rand(2) fg = np.random.normal(loc=.5, scale=.1, size=[5, 5]) bg = InMemoryDataset(bg_x, bg_y) bg_swap = BackgroundSwap(bg, input_dim=(5, 5), normalize_bg=None) spliced_1_channel = bg_swap(fg)[:, :, 0] assert np.array_equal((spliced_1_channel <= -1), (fg <= .5)) @pytest.mark.slow def test_background_swap_numpy(): """ Test background swap on a single ndarray input. """ mnist = MNIST(DATA_PATH, download=True, train=True) cifar = CIFAR10(DATA_PATH, download=True, train=True) bg_swap = BackgroundSwap(cifar, input_dim=(28, 28)) im = mnist.get_data()[0][0] im = bg_swap(im) # Uncomment for debugging # plt.imshow(im, interpolation='nearest') # plt.show() @pytest.mark.slow def test_background_swap_torch(): """ Test background swap on a single tensor input. """ cifar = CIFAR10(DATA_PATH, download=True, train=True) mnist = torchvision.datasets.MNIST(DATA_PATH, train=True, download=True, transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor() ])) bg_swap = BackgroundSwap(cifar, input_dim=(28, 28)) im = mnist[0][0] im = bg_swap(im) # Uncomment for debugging # plt.imshow(im.permute(1, 2, 0), interpolation='nearest') # plt.show() @pytest.mark.slow def test_background_tranformation(): """ Example code using TransformationIncremental to create a setting with 3 tasks. """ cifar = CIFAR10(DATA_PATH, train=True) mnist = MNIST(DATA_PATH, download=False, train=True) nb_task = 3 list_trsf = [] for i in range(nb_task): list_trsf.append([torchvision.transforms.ToTensor(), BackgroundSwap(cifar, bg_label=i, input_dim=(28, 28)), torchvision.transforms.ToPILImage()]) scenario = TransformationIncremental(mnist, base_transformations=[torchvision.transforms.ToTensor()], incremental_transformations=list_trsf) folder = "tests/samples/background_trsf/" if not os.path.exists(folder): os.makedirs(folder) for task_id, task_data in enumerate(scenario): task_data.plot(path=folder, title=f"background_{task_id}.jpg", nb_samples=100, shape=[28, 28, 3]) loader = DataLoader(task_data) _, _, _ = next(iter(loader))
31.010309
115
0.657247
import os from torch.utils.data import DataLoader from continuum.datasets import CIFAR10, InMemoryDataset from continuum.datasets import MNIST import torchvision from continuum.scenarios import TransformationIncremental import pytest import numpy as np from continuum.transforms.bg_swap import BackgroundSwap DATA_PATH = os.environ.get("CONTINUUM_DATA_PATH") def test_bg_swap_fast(): bg_x = np.ones(shape=[2, 5, 5, 3]) * -1 bg_y = np.random.rand(2) fg = np.random.normal(loc=.5, scale=.1, size=[5, 5]) bg = InMemoryDataset(bg_x, bg_y) bg_swap = BackgroundSwap(bg, input_dim=(5, 5), normalize_bg=None) spliced_1_channel = bg_swap(fg)[:, :, 0] assert np.array_equal((spliced_1_channel <= -1), (fg <= .5)) @pytest.mark.slow def test_background_swap_numpy(): mnist = MNIST(DATA_PATH, download=True, train=True) cifar = CIFAR10(DATA_PATH, download=True, train=True) bg_swap = BackgroundSwap(cifar, input_dim=(28, 28)) im = mnist.get_data()[0][0] im = bg_swap(im) @pytest.mark.slow def test_background_swap_torch(): cifar = CIFAR10(DATA_PATH, download=True, train=True) mnist = torchvision.datasets.MNIST(DATA_PATH, train=True, download=True, transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor() ])) bg_swap = BackgroundSwap(cifar, input_dim=(28, 28)) im = mnist[0][0] im = bg_swap(im) @pytest.mark.slow def test_background_tranformation(): cifar = CIFAR10(DATA_PATH, train=True) mnist = MNIST(DATA_PATH, download=False, train=True) nb_task = 3 list_trsf = [] for i in range(nb_task): list_trsf.append([torchvision.transforms.ToTensor(), BackgroundSwap(cifar, bg_label=i, input_dim=(28, 28)), torchvision.transforms.ToPILImage()]) scenario = TransformationIncremental(mnist, base_transformations=[torchvision.transforms.ToTensor()], incremental_transformations=list_trsf) folder = "tests/samples/background_trsf/" if not os.path.exists(folder): os.makedirs(folder) for task_id, task_data in enumerate(scenario): task_data.plot(path=folder, title=f"background_{task_id}.jpg", nb_samples=100, shape=[28, 28, 3]) loader = DataLoader(task_data) _, _, _ = next(iter(loader))
true
true
f7000c3468a0624d54db99fbbde0ac002173b532
2,025
py
Python
python/communitymanager/lib/const.py
OpenCIOC/communityrepo
63199a7b620f5c08624e534faf771e5dd2243adb
[ "Apache-2.0" ]
2
2016-01-25T14:40:44.000Z
2018-01-31T04:30:23.000Z
python/communitymanager/lib/const.py
OpenCIOC/communityrepo
63199a7b620f5c08624e534faf771e5dd2243adb
[ "Apache-2.0" ]
5
2018-02-07T20:16:49.000Z
2021-12-13T19:41:43.000Z
python/communitymanager/lib/const.py
OpenCIOC/communityrepo
63199a7b620f5c08624e534faf771e5dd2243adb
[ "Apache-2.0" ]
1
2018-02-07T20:37:52.000Z
2018-02-07T20:37:52.000Z
# ========================================================================================= # Copyright 2015 Community Information Online Consortium (CIOC) and KCL Software Solutions # # 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. # ========================================================================================= # std lib import os # jQuery and jQueryUI versions JQUERY_VERSION = "1.6.2" JQUERY_UI_VERSION = "1.8.16" # formatting constants DATE_TEXT_SIZE = 25 TEXT_SIZE = 85 TEXTAREA_COLS = 85 TEXTAREA_ROWS_SHORT = 2 TEXTAREA_ROWS_LONG = 4 TEXTAREA_ROWS_XLONG = 10 MAX_LENGTH_CHECKLIST_NOTES = 255 EMAIL_LENGTH = 60 # application running constants _app_path = None _config_file = None _app_name = None session_lock_dir = None publish_dir = None def update_cache_values(): # called from application init at startup global _app_path, _config_file, _app_name, session_lock_dir, publish_dir if _app_path is None: _app_path = os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) _app_name = os.path.split(_app_path)[1] _config_file = os.path.join(_app_path, '..', '..', 'config', _app_name + '.ini') session_lock_dir = os.path.join(_app_path, 'python', 'session_lock') publish_dir = os.path.join(_app_path, 'python', 'published_files') try: os.makedirs(session_lock_dir) except os.error: pass try: os.makedirs(publish_dir) except os.error: pass
32.142857
95
0.640494
import os JQUERY_VERSION = "1.6.2" JQUERY_UI_VERSION = "1.8.16" DATE_TEXT_SIZE = 25 TEXT_SIZE = 85 TEXTAREA_COLS = 85 TEXTAREA_ROWS_SHORT = 2 TEXTAREA_ROWS_LONG = 4 TEXTAREA_ROWS_XLONG = 10 MAX_LENGTH_CHECKLIST_NOTES = 255 EMAIL_LENGTH = 60 _app_path = None _config_file = None _app_name = None session_lock_dir = None publish_dir = None def update_cache_values(): global _app_path, _config_file, _app_name, session_lock_dir, publish_dir if _app_path is None: _app_path = os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) _app_name = os.path.split(_app_path)[1] _config_file = os.path.join(_app_path, '..', '..', 'config', _app_name + '.ini') session_lock_dir = os.path.join(_app_path, 'python', 'session_lock') publish_dir = os.path.join(_app_path, 'python', 'published_files') try: os.makedirs(session_lock_dir) except os.error: pass try: os.makedirs(publish_dir) except os.error: pass
true
true
f7000d37df1b082b8f943334e45282014877347e
3,280
py
Python
sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2015_08_01/aio/_configuration.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
2,728
2015-01-09T10:19:32.000Z
2022-03-31T14:50:33.000Z
sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2015_08_01/aio/_configuration.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
17,773
2015-01-05T15:57:17.000Z
2022-03-31T23:50:25.000Z
sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2015_08_01/aio/_configuration.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
1,916
2015-01-19T05:05:41.000Z
2022-03-31T19:36:44.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy from .._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class WebSiteManagementClientConfiguration(Configuration): """Configuration for WebSiteManagementClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). :type subscription_id: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any ) -> None: if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") super(WebSiteManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id self.api_version = "2015-08-01" self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) kwargs.setdefault('sdk_moniker', 'mgmt-web/{}'.format(VERSION)) self._configure(**kwargs) def _configure( self, **kwargs: Any ) -> None: self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs)
48.235294
134
0.699695
from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy from .._version import VERSION if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential class WebSiteManagementClientConfiguration(Configuration): def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any ) -> None: if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") super(WebSiteManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id self.api_version = "2015-08-01" self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) kwargs.setdefault('sdk_moniker', 'mgmt-web/{}'.format(VERSION)) self._configure(**kwargs) def _configure( self, **kwargs: Any ) -> None: self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs)
true
true
f7000e80dc69165127d93dc9b2a8e5454d07d8ca
852
py
Python
spongeauth/core/tests/test_x_real_ip_middleware.py
felixoi/SpongeAuth
d44ee52d0b35b2e1909c7bf6bad29aa7b4835b26
[ "MIT" ]
10
2016-11-18T12:37:24.000Z
2022-03-04T09:25:25.000Z
spongeauth/core/tests/test_x_real_ip_middleware.py
felixoi/SpongeAuth
d44ee52d0b35b2e1909c7bf6bad29aa7b4835b26
[ "MIT" ]
794
2016-11-19T18:34:37.000Z
2022-03-31T16:49:11.000Z
spongeauth/core/tests/test_x_real_ip_middleware.py
PowerNukkit/OreAuth
96a2926c9601fce6fac471bdb997077f07e8bf9a
[ "MIT" ]
11
2016-11-26T22:30:17.000Z
2022-03-16T17:20:14.000Z
import django.http import unittest.mock from .. import middleware def get_response(req): # dummy get_response, just return an empty response return django.http.HttpResponse() def test_leaves_remote_addr_alone_if_no_real_ip(): remote_addr = object() request = unittest.mock.MagicMock() request.META = {"REMOTE_ADDR": remote_addr} middleware.XRealIPMiddleware(get_response)(request) assert request.META["REMOTE_ADDR"] is remote_addr def test_switches_out_x_real_ip_if_available(): remote_addr = object() x_real_ip = object() request = unittest.mock.MagicMock() request.META = {"REMOTE_ADDR": remote_addr, "HTTP_X_REAL_IP": x_real_ip} middleware.XRealIPMiddleware(get_response)(request) assert request.META["REMOTE_ADDR"] is x_real_ip assert request.META["HTTP_X_REAL_IP"] is x_real_ip
25.058824
76
0.75
import django.http import unittest.mock from .. import middleware def get_response(req): return django.http.HttpResponse() def test_leaves_remote_addr_alone_if_no_real_ip(): remote_addr = object() request = unittest.mock.MagicMock() request.META = {"REMOTE_ADDR": remote_addr} middleware.XRealIPMiddleware(get_response)(request) assert request.META["REMOTE_ADDR"] is remote_addr def test_switches_out_x_real_ip_if_available(): remote_addr = object() x_real_ip = object() request = unittest.mock.MagicMock() request.META = {"REMOTE_ADDR": remote_addr, "HTTP_X_REAL_IP": x_real_ip} middleware.XRealIPMiddleware(get_response)(request) assert request.META["REMOTE_ADDR"] is x_real_ip assert request.META["HTTP_X_REAL_IP"] is x_real_ip
true
true
f7000f03c62e8b3dcc7083fb8b218b5a6f499aa8
198
py
Python
test-relay.py
rn-santos227/medsys
d72ef3b419bdb84cc21022af7ce43813090ef211
[ "MIT" ]
null
null
null
test-relay.py
rn-santos227/medsys
d72ef3b419bdb84cc21022af7ce43813090ef211
[ "MIT" ]
null
null
null
test-relay.py
rn-santos227/medsys
d72ef3b419bdb84cc21022af7ce43813090ef211
[ "MIT" ]
null
null
null
#!/usr/bin/env python import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(21, GPIO.OUT) GPIO.output(21, GPIO.LOW) time.sleep(3.00) GPIO.output(21, GPIO.HIGH) GPIO.cleanup()
11.647059
26
0.717172
import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(21, GPIO.OUT) GPIO.output(21, GPIO.LOW) time.sleep(3.00) GPIO.output(21, GPIO.HIGH) GPIO.cleanup()
true
true
f7000f942ae83e6e025768748f579184365a76d4
305
py
Python
server/objects/notifier.py
jaxsenh/the-devil-that-lurks
89fa85c461a8da55a0b7d28e32dd8144d6cac8ca
[ "MIT" ]
1
2020-05-28T03:21:44.000Z
2020-05-28T03:21:44.000Z
server/objects/notifier.py
jaxsenh/the-devil-that-lurks
89fa85c461a8da55a0b7d28e32dd8144d6cac8ca
[ "MIT" ]
null
null
null
server/objects/notifier.py
jaxsenh/the-devil-that-lurks
89fa85c461a8da55a0b7d28e32dd8144d6cac8ca
[ "MIT" ]
null
null
null
from direct.directnotify.DirectNotifyGlobal import directNotify class Notifier: def __init__(self, name): """ @param name: The name of the notifier. Be sure to add it to your config/Config.prc! @type name: str """ self.notify = directNotify.newCategory(name)
27.727273
91
0.659016
from direct.directnotify.DirectNotifyGlobal import directNotify class Notifier: def __init__(self, name): self.notify = directNotify.newCategory(name)
true
true
f70011c6182da69473e565cf0d8aee9ee61da27a
221
py
Python
packaging/squarer/ml_squarer.py
g-nightingale/tox_examples
d7714375c764580b4b8af9db61332ced4e851def
[ "BSD-3-Clause" ]
10
2020-05-23T15:40:43.000Z
2022-02-06T22:34:10.000Z
packaging/squarer/ml_squarer.py
g-nightingale/tox_examples
d7714375c764580b4b8af9db61332ced4e851def
[ "BSD-3-Clause" ]
null
null
null
packaging/squarer/ml_squarer.py
g-nightingale/tox_examples
d7714375c764580b4b8af9db61332ced4e851def
[ "BSD-3-Clause" ]
12
2020-08-04T11:37:56.000Z
2022-03-31T23:21:13.000Z
import numpy as np def train_ml_squarer() -> None: print("Training!") def square() -> int: """Square a number...maybe""" return np.random.randint(1, 100) if __name__ == '__main__': train_ml_squarer()
15.785714
36
0.633484
import numpy as np def train_ml_squarer() -> None: print("Training!") def square() -> int: return np.random.randint(1, 100) if __name__ == '__main__': train_ml_squarer()
true
true
f70012b80af6d540ea4880f63579ca63dcbdd2f2
6,034
py
Python
arcade/examples/platform_tutorial/09_load_map.py
yegarti/arcade
1862e61aab9a7dc646265005b0e808d953a9dfe3
[ "MIT" ]
null
null
null
arcade/examples/platform_tutorial/09_load_map.py
yegarti/arcade
1862e61aab9a7dc646265005b0e808d953a9dfe3
[ "MIT" ]
null
null
null
arcade/examples/platform_tutorial/09_load_map.py
yegarti/arcade
1862e61aab9a7dc646265005b0e808d953a9dfe3
[ "MIT" ]
null
null
null
""" Platformer Game """ import arcade # Constants SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 650 SCREEN_TITLE = "Platformer" # Constants used to scale our sprites from their original size CHARACTER_SCALING = 1 TILE_SCALING = 0.5 COIN_SCALING = 0.5 SPRITE_PIXEL_SIZE = 128 GRID_PIXEL_SIZE = SPRITE_PIXEL_SIZE * TILE_SCALING # Movement speed of player, in pixels per frame PLAYER_MOVEMENT_SPEED = 10 GRAVITY = 1 PLAYER_JUMP_SPEED = 20 class MyGame(arcade.Window): """ Main application class. """ def __init__(self): # Call the parent class and set up the window super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) # Our TileMap Object self.tile_map = None # Our Scene Object self.scene = None # Separate variable that holds the player sprite self.player_sprite = None # Our physics engine self.physics_engine = None # A Camera that can be used for scrolling the screen self.camera = None # A Camera that can be used to draw GUI elements self.gui_camera = None # Keep track of the score self.score = 0 # Load sounds self.collect_coin_sound = arcade.load_sound(":resources:sounds/coin1.wav") self.jump_sound = arcade.load_sound(":resources:sounds/jump1.wav") arcade.set_background_color(arcade.csscolor.CORNFLOWER_BLUE) def setup(self): """Set up the game here. Call this function to restart the game.""" # Setup the Cameras self.camera = arcade.Camera(self.width, self.height) self.gui_camera = arcade.Camera(self.width, self.height) # Name of map file to load map_name = ":resources:tiled_maps/map.json" # Layer specific options are defined based on Layer names in a dictionary # Doing this will make the SpriteList for the platforms layer # use spatial hashing for detection. layer_options = { "Platforms": { "use_spatial_hash": True, }, } # Read in the tiled map self.tile_map = arcade.load_tilemap(map_name, TILE_SCALING, layer_options) # Initialize Scene with our TileMap, this will automatically add all layers # from the map as SpriteLists in the scene in the proper order. self.scene = arcade.Scene.from_tilemap(self.tile_map) # Keep track of the score self.score = 0 # Set up the player, specifically placing it at these coordinates. image_source = ":resources:images/animated_characters/female_adventurer/femaleAdventurer_idle.png" self.player_sprite = arcade.Sprite(image_source, CHARACTER_SCALING) self.player_sprite.center_x = 128 self.player_sprite.center_y = 128 self.scene.add_sprite("Player", self.player_sprite) # --- Other stuff # Set the background color if self.tile_map.background_color: arcade.set_background_color(self.tile_map.background_color) # Create the 'physics engine' self.physics_engine = arcade.PhysicsEnginePlatformer( self.player_sprite, gravity_constant=GRAVITY, walls=self.scene["Platforms"] ) def on_draw(self): """Render the screen.""" # Clear the screen to the background color arcade.start_render() # Activate the game camera self.camera.use() # Draw our Scene self.scene.draw() # Activate the GUI camera before drawing GUI elements self.gui_camera.use() # Draw our score on the screen, scrolling it with the viewport score_text = f"Score: {self.score}" arcade.draw_text( score_text, 10, 10, arcade.csscolor.WHITE, 18, ) def on_key_press(self, key, modifiers): """Called whenever a key is pressed.""" if key == arcade.key.UP or key == arcade.key.W: if self.physics_engine.can_jump(): self.player_sprite.change_y = PLAYER_JUMP_SPEED arcade.play_sound(self.jump_sound) elif key == arcade.key.LEFT or key == arcade.key.A: self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED elif key == arcade.key.RIGHT or key == arcade.key.D: self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED def on_key_release(self, key, modifiers): """Called when the user releases a key.""" if key == arcade.key.LEFT or key == arcade.key.A: self.player_sprite.change_x = 0 elif key == arcade.key.RIGHT or key == arcade.key.D: self.player_sprite.change_x = 0 def center_camera_to_player(self): screen_center_x = self.player_sprite.center_x - (self.camera.viewport_width / 2) screen_center_y = self.player_sprite.center_y - ( self.camera.viewport_height / 2 ) if screen_center_x < 0: screen_center_x = 0 if screen_center_y < 0: screen_center_y = 0 player_centered = screen_center_x, screen_center_y self.camera.move_to(player_centered) def on_update(self, delta_time): """Movement and game logic""" # Move the player with the physics engine self.physics_engine.update() # See if we hit any coins coin_hit_list = arcade.check_for_collision_with_list( self.player_sprite, self.scene["Coins"] ) # Loop through each coin we hit (if any) and remove it for coin in coin_hit_list: # Remove the coin coin.remove_from_sprite_lists() # Play a sound arcade.play_sound(self.collect_coin_sound) # Add one to the score self.score += 1 # Position the camera self.center_camera_to_player() def main(): """Main function""" window = MyGame() window.setup() arcade.run() if __name__ == "__main__": main()
30.474747
106
0.632748
import arcade SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 650 SCREEN_TITLE = "Platformer" CHARACTER_SCALING = 1 TILE_SCALING = 0.5 COIN_SCALING = 0.5 SPRITE_PIXEL_SIZE = 128 GRID_PIXEL_SIZE = SPRITE_PIXEL_SIZE * TILE_SCALING PLAYER_MOVEMENT_SPEED = 10 GRAVITY = 1 PLAYER_JUMP_SPEED = 20 class MyGame(arcade.Window): def __init__(self): super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) self.tile_map = None self.scene = None self.player_sprite = None self.physics_engine = None self.camera = None self.gui_camera = None self.score = 0 self.collect_coin_sound = arcade.load_sound(":resources:sounds/coin1.wav") self.jump_sound = arcade.load_sound(":resources:sounds/jump1.wav") arcade.set_background_color(arcade.csscolor.CORNFLOWER_BLUE) def setup(self): self.camera = arcade.Camera(self.width, self.height) self.gui_camera = arcade.Camera(self.width, self.height) map_name = ":resources:tiled_maps/map.json" layer_options = { "Platforms": { "use_spatial_hash": True, }, } self.tile_map = arcade.load_tilemap(map_name, TILE_SCALING, layer_options) self.scene = arcade.Scene.from_tilemap(self.tile_map) self.score = 0 image_source = ":resources:images/animated_characters/female_adventurer/femaleAdventurer_idle.png" self.player_sprite = arcade.Sprite(image_source, CHARACTER_SCALING) self.player_sprite.center_x = 128 self.player_sprite.center_y = 128 self.scene.add_sprite("Player", self.player_sprite) if self.tile_map.background_color: arcade.set_background_color(self.tile_map.background_color) self.physics_engine = arcade.PhysicsEnginePlatformer( self.player_sprite, gravity_constant=GRAVITY, walls=self.scene["Platforms"] ) def on_draw(self): arcade.start_render() self.camera.use() self.scene.draw() self.gui_camera.use() score_text = f"Score: {self.score}" arcade.draw_text( score_text, 10, 10, arcade.csscolor.WHITE, 18, ) def on_key_press(self, key, modifiers): if key == arcade.key.UP or key == arcade.key.W: if self.physics_engine.can_jump(): self.player_sprite.change_y = PLAYER_JUMP_SPEED arcade.play_sound(self.jump_sound) elif key == arcade.key.LEFT or key == arcade.key.A: self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED elif key == arcade.key.RIGHT or key == arcade.key.D: self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED def on_key_release(self, key, modifiers): if key == arcade.key.LEFT or key == arcade.key.A: self.player_sprite.change_x = 0 elif key == arcade.key.RIGHT or key == arcade.key.D: self.player_sprite.change_x = 0 def center_camera_to_player(self): screen_center_x = self.player_sprite.center_x - (self.camera.viewport_width / 2) screen_center_y = self.player_sprite.center_y - ( self.camera.viewport_height / 2 ) if screen_center_x < 0: screen_center_x = 0 if screen_center_y < 0: screen_center_y = 0 player_centered = screen_center_x, screen_center_y self.camera.move_to(player_centered) def on_update(self, delta_time): self.physics_engine.update() coin_hit_list = arcade.check_for_collision_with_list( self.player_sprite, self.scene["Coins"] ) for coin in coin_hit_list: coin.remove_from_sprite_lists() arcade.play_sound(self.collect_coin_sound) self.score += 1 self.center_camera_to_player() def main(): window = MyGame() window.setup() arcade.run() if __name__ == "__main__": main()
true
true
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
14