hexsha
stringlengths 40
40
| size
int64 4
996k
| ext
stringclasses 8
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
listlengths 1
10
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
245
| max_issues_repo_name
stringlengths 6
130
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
245
| max_forks_repo_name
stringlengths 6
130
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 4
996k
| avg_line_length
float64 1.33
58.2k
| max_line_length
int64 2
323k
| alphanum_fraction
float64 0
0.97
| content_no_comment
stringlengths 0
946k
| is_comment_constant_removed
bool 2
classes | is_sharp_comment_removed
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
790e2a1a50362588a76240d2a0bca349b6970a3b
| 1,619
|
py
|
Python
|
Application/ReclamaCaicoProject/ReclamaCaicoApp/forms.py
|
WesleyVitor/ReclamaCaico
|
df67997821fc00236f1d9c77e8685ed8e4a6934b
|
[
"MIT"
] | null | null | null |
Application/ReclamaCaicoProject/ReclamaCaicoApp/forms.py
|
WesleyVitor/ReclamaCaico
|
df67997821fc00236f1d9c77e8685ed8e4a6934b
|
[
"MIT"
] | null | null | null |
Application/ReclamaCaicoProject/ReclamaCaicoApp/forms.py
|
WesleyVitor/ReclamaCaico
|
df67997821fc00236f1d9c77e8685ed8e4a6934b
|
[
"MIT"
] | null | null | null |
from django import forms
from .models import Reclamacao,Login,Comentario
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class CadastraReclamacaoForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CadastraReclamacaoForm,self).__init__(*args, **kwargs)
self.fields['titulo'].required = True
self.fields['bairro'].required = True
self.fields['rua'].required = True
self.fields['descricao'].required = True
self.fields['foto'].required = False
class Meta:
model = Reclamacao
fields = ('titulo','bairro','rua','descricao', 'foto',)
class LoginUsuarioForm(forms.ModelForm):
class Meta:
model = Login
fields = ('username','password',)
widgets = {
'password': forms.PasswordInput(),
}
class SignUpForm(UserCreationForm):
cpf = forms.CharField(max_length=11, required=True)
bairro = forms.CharField(max_length=30, required=True)
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
class Meta:
model = User
fields = ('username', 'cpf', 'bairro', 'email', 'password1', 'password2', )
#class CadastraForum(forms.ModelForm):
# class Meta:
# model = Forum
# fields = ('text',)
class RegistroDeComentarioForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(RegistroDeComentarioForm,self).__init__(*args, **kwargs)
self.fields['text1'].required = True
class Meta:
model = Comentario
fields = ('text1',)
| 33.040816
| 97
| 0.657196
|
from django import forms
from .models import Reclamacao,Login,Comentario
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class CadastraReclamacaoForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CadastraReclamacaoForm,self).__init__(*args, **kwargs)
self.fields['titulo'].required = True
self.fields['bairro'].required = True
self.fields['rua'].required = True
self.fields['descricao'].required = True
self.fields['foto'].required = False
class Meta:
model = Reclamacao
fields = ('titulo','bairro','rua','descricao', 'foto',)
class LoginUsuarioForm(forms.ModelForm):
class Meta:
model = Login
fields = ('username','password',)
widgets = {
'password': forms.PasswordInput(),
}
class SignUpForm(UserCreationForm):
cpf = forms.CharField(max_length=11, required=True)
bairro = forms.CharField(max_length=30, required=True)
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
class Meta:
model = User
fields = ('username', 'cpf', 'bairro', 'email', 'password1', 'password2', )
class RegistroDeComentarioForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(RegistroDeComentarioForm,self).__init__(*args, **kwargs)
self.fields['text1'].required = True
class Meta:
model = Comentario
fields = ('text1',)
| true
| true
|
790e2a29bb037db669a415534e68bfcb8ec39c40
| 834
|
py
|
Python
|
sukh_site_v1/sukh_site_v1/urls.py
|
sbhuller98/main_django
|
6c54aef90cf222dac608f6742251d3a83934fc82
|
[
"MIT"
] | 1
|
2021-02-09T21:38:02.000Z
|
2021-02-09T21:38:02.000Z
|
sukh_site_v1/sukh_site_v1/urls.py
|
sbhuller98/main_django
|
6c54aef90cf222dac608f6742251d3a83934fc82
|
[
"MIT"
] | null | null | null |
sukh_site_v1/sukh_site_v1/urls.py
|
sbhuller98/main_django
|
6c54aef90cf222dac608f6742251d3a83934fc82
|
[
"MIT"
] | null | null | null |
"""sukh_site_v1 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('mysite.urls')),
]
| 34.75
| 77
| 0.708633
|
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('mysite.urls')),
]
| true
| true
|
790e2c0f81736d4d3a5ba35c4c9cf12d9ddd6c8b
| 1,842
|
py
|
Python
|
test/test_get_extended_contact_details_statistics.py
|
Danilka/APIv3-python-library
|
c96472f47d652d2e09e8b4a48a80e33fde06e7f1
|
[
"MIT"
] | null | null | null |
test/test_get_extended_contact_details_statistics.py
|
Danilka/APIv3-python-library
|
c96472f47d652d2e09e8b4a48a80e33fde06e7f1
|
[
"MIT"
] | null | null | null |
test/test_get_extended_contact_details_statistics.py
|
Danilka/APIv3-python-library
|
c96472f47d652d2e09e8b4a48a80e33fde06e7f1
|
[
"MIT"
] | null | null | null |
# coding: utf-8
"""
SendinBlue API
SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at https://github.com/orgs/sendinblue **Possible responses** | Code | Message | | :-------------: | ------------- | | 200 | OK. Successful Request | | 201 | OK. Successful Creation | | 202 | OK. Request accepted | | 204 | OK. Successful Update/Deletion | | 400 | Error. Bad Request | | 401 | Error. Authentication Needed | | 402 | Error. Not enough credit, plan upgrade needed | | 403 | Error. Permission denied | | 404 | Error. Object does not exist | | 405 | Error. Method not allowed | # noqa: E501
OpenAPI spec version: 3.0.0
Contact: contact@sendinblue.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import sib_api_v3_sdk
from sib_api_v3_sdk.models.get_extended_contact_details_statistics import GetExtendedContactDetailsStatistics # noqa: E501
from sib_api_v3_sdk.rest import ApiException
class TestGetExtendedContactDetailsStatistics(unittest.TestCase):
"""GetExtendedContactDetailsStatistics unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testGetExtendedContactDetailsStatistics(self):
"""Test GetExtendedContactDetailsStatistics"""
# FIXME: construct object with mandatory attributes with example values
# model = sib_api_v3_sdk.models.get_extended_contact_details_statistics.GetExtendedContactDetailsStatistics() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| 44.926829
| 820
| 0.704126
|
from __future__ import absolute_import
import unittest
import sib_api_v3_sdk
from sib_api_v3_sdk.models.get_extended_contact_details_statistics import GetExtendedContactDetailsStatistics
from sib_api_v3_sdk.rest import ApiException
class TestGetExtendedContactDetailsStatistics(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testGetExtendedContactDetailsStatistics(self):
s
if __name__ == '__main__':
unittest.main()
| true
| true
|
790e2c4249252004a98d8571062b891cd4898944
| 259
|
py
|
Python
|
backend/edw_shop/money/__init__.py
|
infolabs/django-edw-shop
|
2f83235361ce89199dc867b06930440904a54db6
|
[
"BSD-3-Clause"
] | null | null | null |
backend/edw_shop/money/__init__.py
|
infolabs/django-edw-shop
|
2f83235361ce89199dc867b06930440904a54db6
|
[
"BSD-3-Clause"
] | null | null | null |
backend/edw_shop/money/__init__.py
|
infolabs/django-edw-shop
|
2f83235361ce89199dc867b06930440904a54db6
|
[
"BSD-3-Clause"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
Source: https://github.com/awesto/django-shop/blob/12e246b356dbc1bc5bbdc8f056e3cb109c617997/shop/money/__init__.py
"""
from .money_maker import MoneyMaker, AbstractMoney
# The default Money type for this shop
Money = MoneyMaker()
| 28.777778
| 114
| 0.764479
|
from .money_maker import MoneyMaker, AbstractMoney
Money = MoneyMaker()
| true
| true
|
790e2c73153e861a996df906a6e26ba5aaabf8e7
| 149
|
py
|
Python
|
igov_main/apps.py
|
morrisedu/igov_africa
|
d1a96c18e22034a32f122b2369940583e6719194
|
[
"MIT"
] | null | null | null |
igov_main/apps.py
|
morrisedu/igov_africa
|
d1a96c18e22034a32f122b2369940583e6719194
|
[
"MIT"
] | null | null | null |
igov_main/apps.py
|
morrisedu/igov_africa
|
d1a96c18e22034a32f122b2369940583e6719194
|
[
"MIT"
] | null | null | null |
from django.apps import AppConfig
class IgovMainConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'igov_main'
| 21.285714
| 56
| 0.765101
|
from django.apps import AppConfig
class IgovMainConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'igov_main'
| true
| true
|
790e2d0bf96b7645e968f6589fc30a1e66e201e2
| 411
|
py
|
Python
|
leetcode/12.integer-to-roman.py
|
geemaple/algorithm
|
68bc5032e1ee52c22ef2f2e608053484c487af54
|
[
"MIT"
] | 177
|
2017-08-21T08:57:43.000Z
|
2020-06-22T03:44:22.000Z
|
leetcode/12.integer-to-roman.py
|
geemaple/leetcode
|
68bc5032e1ee52c22ef2f2e608053484c487af54
|
[
"MIT"
] | 2
|
2020-09-22T09:51:17.000Z
|
2021-12-25T08:18:45.000Z
|
leetcode/12.integer-to-roman.py
|
geemaple/algorithm
|
68bc5032e1ee52c22ef2f2e608053484c487af54
|
[
"MIT"
] | 23
|
2017-08-23T06:01:28.000Z
|
2020-04-20T03:17:36.000Z
|
class Solution:
def intToRoman(self, num: int) -> str:
romans = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
res = ''
for i in range(len(romans)):
while (num - values[i] >= 0):
res += romans[i]
num -= values[i]
return res
| 31.615385
| 88
| 0.403893
|
class Solution:
def intToRoman(self, num: int) -> str:
romans = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
res = ''
for i in range(len(romans)):
while (num - values[i] >= 0):
res += romans[i]
num -= values[i]
return res
| true
| true
|
790e2edf5bdcb3eefc1ecc68d696dba2da95267d
| 1,414
|
py
|
Python
|
GoldenTimes/urls.py
|
liuxue0905/GoldenTimes
|
9cc1fdd0b8c4b06e1f4f932baba0db02e895bc41
|
[
"BSD-3-Clause"
] | null | null | null |
GoldenTimes/urls.py
|
liuxue0905/GoldenTimes
|
9cc1fdd0b8c4b06e1f4f932baba0db02e895bc41
|
[
"BSD-3-Clause"
] | 10
|
2020-06-20T02:04:24.000Z
|
2021-12-13T19:47:35.000Z
|
GoldenTimes/urls.py
|
liuxue0905/GoldenTimes
|
9cc1fdd0b8c4b06e1f4f932baba0db02e895bc41
|
[
"BSD-3-Clause"
] | null | null | null |
"""GoldenTimes URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from django.views.generic import RedirectView
urlpatterns = [
# url(r'^$', RedirectView.as_view(url='http://liujin.jios.org:8888')),
url(r'^$', RedirectView.as_view(url='/portal/')),
url(r'^admin/', admin.site.urls),
url(r'^portal/', include('portal.urls')),
url(r'^api/', include('api.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| 35.35
| 91
| 0.719236
|
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from django.views.generic import RedirectView
urlpatterns = [
url(r'^$', RedirectView.as_view(url='/portal/')),
url(r'^admin/', admin.site.urls),
url(r'^portal/', include('portal.urls')),
url(r'^api/', include('api.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| true
| true
|
790e2f1206912b7fe22dd2186353a00b583aeb88
| 812
|
py
|
Python
|
bag.py
|
schwehr/bag-py
|
3805a85a57d993ea12af228076eb5d8ac5b011fd
|
[
"Apache-2.0"
] | 7
|
2015-03-25T01:28:47.000Z
|
2020-06-16T14:02:20.000Z
|
bag.py
|
xavierherron/bag-py
|
3805a85a57d993ea12af228076eb5d8ac5b011fd
|
[
"Apache-2.0"
] | null | null | null |
bag.py
|
xavierherron/bag-py
|
3805a85a57d993ea12af228076eb5d8ac5b011fd
|
[
"Apache-2.0"
] | 4
|
2015-02-08T13:31:52.000Z
|
2021-05-18T19:09:22.000Z
|
#!/usr/bin/env python
import h5py
f = h5py.File('H11302_OLS_OSS/H11302_2m_1.bag')
print f.listobjects()
print f.listitems()
bag_root = f['/BAG_root']
metadata = ''.join(bag_root['metadata'])
o = file('metadata.xml','w')
o.write(metadata)
del o
#print metadata #[0:200]
elevation = bag_root['elevation']
print 'shape:',elevation.shape
data = elevation.value
#print type(data)
#print data
print 'range:',data.min(), data.max()
#import matplotlib.mlab as mlab
#import matplotlib.pyplot as plt
o = file('out.xyz','w')
for y in range(elevation.shape[1]):
#for x,z in enumerate(elevation[y]):
for x in range(elevation.shape[0]):
z = elevation[x,y]
if z>=1000000-1:
continue
#o.write('{x} {y} {z}\n'.format(x=x,y=y,z=z))
o.write('%d %d %0.2f\n'% (x,y,z))
| 19.804878
| 53
| 0.635468
|
import h5py
f = h5py.File('H11302_OLS_OSS/H11302_2m_1.bag')
print f.listobjects()
print f.listitems()
bag_root = f['/BAG_root']
metadata = ''.join(bag_root['metadata'])
o = file('metadata.xml','w')
o.write(metadata)
del o
ion = bag_root['elevation']
print 'shape:',elevation.shape
data = elevation.value
print 'range:',data.min(), data.max()
o = file('out.xyz','w')
for y in range(elevation.shape[1]):
for x in range(elevation.shape[0]):
z = elevation[x,y]
if z>=1000000-1:
continue
o.write('%d %d %0.2f\n'% (x,y,z))
| false
| true
|
790e30859321a5e763de3820ea1fea1dd98d732c
| 11,751
|
py
|
Python
|
sorolla/sorolla.py
|
bq/sorolla
|
f9fc2f35a673f2f11d370975be4e06c520341d88
|
[
"Apache-2.0"
] | 16
|
2015-04-22T09:17:17.000Z
|
2015-12-05T17:17:22.000Z
|
sorolla/sorolla.py
|
bq/sorolla
|
f9fc2f35a673f2f11d370975be4e06c520341d88
|
[
"Apache-2.0"
] | null | null | null |
sorolla/sorolla.py
|
bq/sorolla
|
f9fc2f35a673f2f11d370975be4e06c520341d88
|
[
"Apache-2.0"
] | null | null | null |
import subprocess
import math
import os
from pipes import quote
import platform
class Sorolla:
"""
Main class which will launch ImageMagick commands to apply selected
transformations to the given images.
It needs ImageMagick & GhostScript installed in the system and in PATH
to work properly
"""
@staticmethod
def scale_resource(source_file, dest_file, scale):
"""
Scales a resource; detects if it's a nine-patch via filename in order
to scale it properly
Arguments:
source_file Source file to convert. Path can be relative or
absolute
dest_file Destination file where the converted file will be
saved. Path can be relative or absolute
scale Scale value as a float. If it's greater than zero, the
function upscales the image; if less than zero,
it downscales the image
Returns:
Whether the action could be run or not
"""
if not Sorolla._check_needed_commands:
return False
# Default base density in dpi, set by Imagemagick
base_pdf_density_dpi = 72
try:
command = ""
if ".9." not in source_file:
# Not a resource identified as nine-patch
density = int(scale * base_pdf_density_dpi)
# Scales a vector resource to the desired density
command = 'convert -background transparent -density {0} {1} {2}'
command = command.format(
density,
Sorolla._shellquote(source_file),
Sorolla._shellquote(dest_file),
)
else:
# Resource defined as nine-patch
# Attributes used in Imagemagick command
imagemagick_scale = scale * 100
border_size = math.ceil(scale)
# The following ImageMagick command works as follows (each step
# generates a temporary image)
#
# 0. Tell convert the image that we're going to use, and that
# we want a transparent background
# 1. Create a copy of (0) with our base density (72 DPI)
# 2. Remove 9-patch border from (1) and replace it with
# color
# 3. Mix (1) & (2) so that 9-patch borders are extracted from
# the transparent original image
# 4. Resize (3) to 'imagemagick_scale'. We get scaled 9-patch
# borders, but there will be semi-transparent pixels
# 5. Apply a threshold in (4)'s alpha channel so we can make
# semi-transparent pixels fully opaque
# 6-7. Same process as in 2-3 to extract a bigger 9-patch
# border
# 8-12. Process to adjust the 9-patch border in (7) so we don't
# leave extra space between the border & the image
# 13. Create a raster of the original image (0), keeping
# original quality if PDF or SVG
# 14. Remove 9-patch border of (13) depending on the scale used
# 15. Merge (14) with (12) so we finally have the result
# 9-patch for the given dpi scale
# 16. Delete all generated files in each step
#
# There might be some pixel data loss in ldpi & hdpi
# resolutions as they use float scales to resize the source
# files
#
# In order to debug the process, copy the command to your
# console, remove the 'delete' parenthesis block and add
# '-append' before the destination file. This'll generate a
# .png with all the image steps described by the commands
command = 'convert {0} -background transparent '\
'\( +clone -density {1} \) '\
'\( +clone -shave 1x1 -bordercolor transparent -border 1x1 \) '\
'\( -clone 1 +clone -compose ChangeMask -composite -compose Over \) '\
'\( +clone -resize {2}%% \) '\
'\( +clone -channel A -threshold 50%% +channel \) '\
'\( +clone -shave 1x1 -bordercolor transparent -border 1x1 \) ' \
'\( -clone 5 +clone -compose ChangeMask -composite -compose Over \) '\
'\( -clone 7 -repage +{3}+0 -background none -flatten \) '\
'\( -clone 7 -repage +0+{3} -background none -flatten \) '\
'\( -clone 7 -repage -{3}+0 -background none -flatten \) '\
'\( -clone 7 -repage +0-{3} -background none -flatten \) '\
'\( -clone 8 -clone 9 -compose Over -composite -clone 10 -composite -clone 11 -composite -shave {3}x{3} \) '\
'\( -clone 0 -scale {2}% \) '\
'\( +clone -shave {4}x{4} -bordercolor transparent -border 1x1 \) '\
'\( +clone -clone 12 -composite \) '\
'\( -delete 0-14 \) '\
'{5}'.format(
Sorolla._shellquote(
os.path.abspath(source_file)),
base_pdf_density_dpi,
imagemagick_scale,
border_size - 1,
border_size,
Sorolla._shellquote(os.path.abspath(dest_file))
)
return Sorolla._run_command(command)
except Exception as e:
print e.errno, e.strerror
return False
@staticmethod
def color_resource(source_file, dest_file, fill_color):
"""
Colors a raster resource; detects if it's a nine-patch via filename in
order to scale it properly
Arguments:
source_file Source file to color. Path can be relative or
absolute
dest_file Destination file where the colored file will be
saved. Path can be relative or absolute
fill_color Color to fill the resource. Must be a RRGGBB string.
Returns:
Whether the action could be run or not
"""
if not Sorolla._check_needed_commands:
return False
try:
command = ""
if ".9." not in source_file:
# Not a resource identified as nine-patch
command = 'convert -background transparent {0} +level-colors "#{1}", '\
'{2}'.format(
Sorolla._shellquote(
os.path.abspath(source_file)),
fill_color,
Sorolla._shellquote(os.path.abspath(dest_file)),
)
else:
# nine-patch
command = 'convert -background transparent {0} '\
'\( +clone -shave 1x1 -bordercolor transparent -border 1x1 +level-colors "#{1}", \) '\
'\( -clone 0 +clone -composite \) '\
'\( -delete 0-1 \) '\
'{2}'.format(
Sorolla._shellquote(
os.path.abspath(source_file)),
fill_color,
Sorolla._shellquote(os.path.abspath(dest_file))
)
return Sorolla._run_command(command)
except Exception as e:
print e.value
return False
@staticmethod
def tint_resource(source_file, dest_file, tint_color):
"""
Tints a gray-scaled raster resource; detects if it's a nine-patch via
filename in order to tint it properly
Arguments:
source_file Source file to tint. Path can be relative or
absolute
dest_file Destination file where the tinted file will be
saved. Path can be relative or absolute
fill_color Color to tint the resource. Must be a RRGGBB string.
Returns:
Whether the action could be run or not
"""
if not Sorolla._check_needed_commands:
return False
try:
command = ""
if ".9." not in source_file:
# Not a resource identified as nine-patch
# Check http://www.imagemagick.org/Usage/color_mods/#tint_overlay
command = 'convert -background transparent {0} '\
'\( +clone +matte -fill "#{1}" -colorize 100%% +clone +swap -compose overlay -composite \) '\
'-compose SrcIn -composite {2}'.format(
Sorolla._shellquote(
os.path.abspath(source_file)),
tint_color,
Sorolla._shellquote(os.path.abspath(dest_file))
)
else:
# nine-patch
command = 'convert -background transparent {0} '\
'\( +clone -shave 1x1 -bordercolor transparent -border 1x1 \) '\
'\( +clone +matte -fill "#{1}" -colorize 100%% \) '\
'\( -clone 0 +clone -compose overlay -composite \) '\
'\( -clone 0 +clone -compose SrcIn -composite \) '\
'\( -delete 0-3 \) {2}'.format(
Sorolla._shellquote(
os.path.abspath(source_file)),
tint_color,
Sorolla._shellquote(os.path.abspath(dest_file))
)
return Sorolla._run_command(command)
except Exception as e:
print e.value
return False
@staticmethod
def _run_command(command):
"""
Runs a given ImageMagick command
"""
# Windows check; remove escape sequences from parentheses so cmd can
# properly launch the command
if Sorolla._is_windows():
command = command.replace('\\(', '(').replace('\\)', ')')
return subprocess.call(command, shell=True) == 0
@staticmethod
def _shellquote(s):
"""
Util method to escape data in order to use it in shell commands
"""
# return "'" + s.replace("'", "'\\''") + "'"
# Windows check
if not Sorolla._is_windows():
return quote(s)
else:
return '"{0}"'.format(s)
@staticmethod
def _check_command(command, args=[]):
"""
Checks if a command can be executed in the file-system
"""
devnull = open(os.devnull, 'w')
try:
status = subprocess.call(
[command] + args, stdout=devnull, stderr=devnull)
return status == 0
except Exception as e:
print e
return False
@staticmethod
def _check_needed_commands():
"""
Check needed commands: ImageMagick's convert & GhostScript
"""
# Imagemagick check
if not Sorolla._check_command("convert"):
print "Imagemagick is not installed"
return False
# Ghostscript check
if not Sorolla._check_command("gs", ["-version"]):
print "GhostScript is not installed"
return False
return True
@staticmethod
def _is_windows():
"""
Check if the current platform is Windows
"""
return platform.uname()[0].find("Win") != -1
| 41.522968
| 129
| 0.512722
|
import subprocess
import math
import os
from pipes import quote
import platform
class Sorolla:
"""
Main class which will launch ImageMagick commands to apply selected
transformations to the given images.
It needs ImageMagick & GhostScript installed in the system and in PATH
to work properly
"""
@staticmethod
def scale_resource(source_file, dest_file, scale):
"""
Scales a resource; detects if it's a nine-patch via filename in order
to scale it properly
Arguments:
source_file Source file to convert. Path can be relative or
absolute
dest_file Destination file where the converted file will be
saved. Path can be relative or absolute
scale Scale value as a float. If it's greater than zero, the
function upscales the image; if less than zero,
it downscales the image
Returns:
Whether the action could be run or not
"""
if not Sorolla._check_needed_commands:
return False
base_pdf_density_dpi = 72
try:
command = ""
if ".9." not in source_file:
density = int(scale * base_pdf_density_dpi)
command = 'convert -background transparent -density {0} {1} {2}'
command = command.format(
density,
Sorolla._shellquote(source_file),
Sorolla._shellquote(dest_file),
)
else:
imagemagick_scale = scale * 100
border_size = math.ceil(scale)
# we want a transparent background
# 1. Create a copy of (0) with our base density (72 DPI)
# 2. Remove 9-patch border from (1) and replace it with
# color
# 3. Mix (1) & (2) so that 9-patch borders are extracted from
# the transparent original image
# 4. Resize (3) to 'imagemagick_scale'. We get scaled 9-patch
# borders, but there will be semi-transparent pixels
# 5. Apply a threshold in (4)'s alpha channel so we can make
# leave extra space between the border & the image
# 13. Create a raster of the original image (0), keeping
# original quality if PDF or SVG
# 14. Remove 9-patch border of (13) depending on the scale used
# 15. Merge (14) with (12) so we finally have the result
# 9-patch for the given dpi scale
# 16. Delete all generated files in each step
#
# There might be some pixel data loss in ldpi & hdpi
# resolutions as they use float scales to resize the source
# files
#
# In order to debug the process, copy the command to your
# console, remove the 'delete' parenthesis block and add
# '-append' before the destination file. This'll generate a
command = 'convert {0} -background transparent '\
'\( +clone -density {1} \) '\
'\( +clone -shave 1x1 -bordercolor transparent -border 1x1 \) '\
'\( -clone 1 +clone -compose ChangeMask -composite -compose Over \) '\
'\( +clone -resize {2}%% \) '\
'\( +clone -channel A -threshold 50%% +channel \) '\
'\( +clone -shave 1x1 -bordercolor transparent -border 1x1 \) ' \
'\( -clone 5 +clone -compose ChangeMask -composite -compose Over \) '\
'\( -clone 7 -repage +{3}+0 -background none -flatten \) '\
'\( -clone 7 -repage +0+{3} -background none -flatten \) '\
'\( -clone 7 -repage -{3}+0 -background none -flatten \) '\
'\( -clone 7 -repage +0-{3} -background none -flatten \) '\
'\( -clone 8 -clone 9 -compose Over -composite -clone 10 -composite -clone 11 -composite -shave {3}x{3} \) '\
'\( -clone 0 -scale {2}% \) '\
'\( +clone -shave {4}x{4} -bordercolor transparent -border 1x1 \) '\
'\( +clone -clone 12 -composite \) '\
'\( -delete 0-14 \) '\
'{5}'.format(
Sorolla._shellquote(
os.path.abspath(source_file)),
base_pdf_density_dpi,
imagemagick_scale,
border_size - 1,
border_size,
Sorolla._shellquote(os.path.abspath(dest_file))
)
return Sorolla._run_command(command)
except Exception as e:
print e.errno, e.strerror
return False
@staticmethod
def color_resource(source_file, dest_file, fill_color):
"""
Colors a raster resource; detects if it's a nine-patch via filename in
order to scale it properly
Arguments:
source_file Source file to color. Path can be relative or
absolute
dest_file Destination file where the colored file will be
saved. Path can be relative or absolute
fill_color Color to fill the resource. Must be a RRGGBB string.
Returns:
Whether the action could be run or not
"""
if not Sorolla._check_needed_commands:
return False
try:
command = ""
if ".9." not in source_file:
# Not a resource identified as nine-patch
command = 'convert -background transparent {0} +level-colors "#{1}", '\
'{2}'.format(
Sorolla._shellquote(
os.path.abspath(source_file)),
fill_color,
Sorolla._shellquote(os.path.abspath(dest_file)),
)
else:
# nine-patch
command = 'convert -background transparent {0} '\
'\( +clone -shave 1x1 -bordercolor transparent -border 1x1 +level-colors "#{1}", \) '\
'\( -clone 0 +clone -composite \) '\
'\( -delete 0-1 \) '\
'{2}'.format(
Sorolla._shellquote(
os.path.abspath(source_file)),
fill_color,
Sorolla._shellquote(os.path.abspath(dest_file))
)
return Sorolla._run_command(command)
except Exception as e:
print e.value
return False
@staticmethod
def tint_resource(source_file, dest_file, tint_color):
"""
Tints a gray-scaled raster resource; detects if it's a nine-patch via
filename in order to tint it properly
Arguments:
source_file Source file to tint. Path can be relative or
absolute
dest_file Destination file where the tinted file will be
saved. Path can be relative or absolute
fill_color Color to tint the resource. Must be a RRGGBB string.
Returns:
Whether the action could be run or not
"""
if not Sorolla._check_needed_commands:
return False
try:
command = ""
if ".9." not in source_file:
command = 'convert -background transparent {0} '\
'\( +clone +matte -fill "#{1}" -colorize 100%% +clone +swap -compose overlay -composite \) '\
'-compose SrcIn -composite {2}'.format(
Sorolla._shellquote(
os.path.abspath(source_file)),
tint_color,
Sorolla._shellquote(os.path.abspath(dest_file))
)
else:
command = 'convert -background transparent {0} '\
'\( +clone -shave 1x1 -bordercolor transparent -border 1x1 \) '\
'\( +clone +matte -fill "#{1}" -colorize 100%% \) '\
'\( -clone 0 +clone -compose overlay -composite \) '\
'\( -clone 0 +clone -compose SrcIn -composite \) '\
'\( -delete 0-3 \) {2}'.format(
Sorolla._shellquote(
os.path.abspath(source_file)),
tint_color,
Sorolla._shellquote(os.path.abspath(dest_file))
)
return Sorolla._run_command(command)
except Exception as e:
print e.value
return False
@staticmethod
def _run_command(command):
"""
Runs a given ImageMagick command
"""
if Sorolla._is_windows():
command = command.replace('\\(', '(').replace('\\)', ')')
return subprocess.call(command, shell=True) == 0
@staticmethod
def _shellquote(s):
"""
Util method to escape data in order to use it in shell commands
"""
if not Sorolla._is_windows():
return quote(s)
else:
return '"{0}"'.format(s)
@staticmethod
def _check_command(command, args=[]):
"""
Checks if a command can be executed in the file-system
"""
devnull = open(os.devnull, 'w')
try:
status = subprocess.call(
[command] + args, stdout=devnull, stderr=devnull)
return status == 0
except Exception as e:
print e
return False
@staticmethod
def _check_needed_commands():
"""
Check needed commands: ImageMagick's convert & GhostScript
"""
# Imagemagick check
if not Sorolla._check_command("convert"):
print "Imagemagick is not installed"
return False
# Ghostscript check
if not Sorolla._check_command("gs", ["-version"]):
print "GhostScript is not installed"
return False
return True
@staticmethod
def _is_windows():
"""
Check if the current platform is Windows
"""
return platform.uname()[0].find("Win") != -1
| false
| true
|
790e3123cdc9d99b9090abcfcb239142e7d814c9
| 9,153
|
py
|
Python
|
dm/templates/external_load_balancer/external_load_balancer.py
|
trevorjwilliams/cloud-foundation-toolkit
|
5abcd362f118c7721cf10ba22d038517df421b73
|
[
"Apache-2.0"
] | null | null | null |
dm/templates/external_load_balancer/external_load_balancer.py
|
trevorjwilliams/cloud-foundation-toolkit
|
5abcd362f118c7721cf10ba22d038517df421b73
|
[
"Apache-2.0"
] | null | null | null |
dm/templates/external_load_balancer/external_load_balancer.py
|
trevorjwilliams/cloud-foundation-toolkit
|
5abcd362f118c7721cf10ba22d038517df421b73
|
[
"Apache-2.0"
] | 1
|
2020-06-20T09:45:29.000Z
|
2020-06-20T09:45:29.000Z
|
# Copyright 2018 Google Inc. 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.
""" This template creates an external load balancer. """
import copy
from hashlib import sha1
import json
def set_optional_property(destination, source, prop_name):
""" Copies the property value if present. """
if prop_name in source:
destination[prop_name] = source[prop_name]
def get_backend_service(properties, backend_spec, res_name, project_id):
""" Creates the backend service. """
name = backend_spec.get('resourceName', res_name)
backend_name = backend_spec.get('name', name)
backend_properties = {
'name': backend_name,
'project': project_id,
'loadBalancingScheme': 'EXTERNAL',
'protocol': get_protocol(properties),
}
backend_resource = {
'name': name,
'type': 'backend_service.py',
'properties': backend_properties
}
optional_properties = [
'description',
'backends',
'timeoutSec',
'sessionAffinity',
'connectionDraining',
'backends',
'healthCheck',
'healthChecks',
'portName',
'enableCDN',
'affinityCookieTtlSec'
]
for prop in optional_properties:
set_optional_property(backend_properties, backend_spec, prop)
return [backend_resource], [
{
'name': 'backendServiceName',
'value': backend_name,
},
{
'name': 'backendServiceSelfLink',
'value': '$(ref.{}.selfLink)'.format(name),
},
]
def get_forwarding_rule(properties, target, res_name, project_id):
""" Creates the forwarding rule. """
name = '{}-forwarding-rule'.format(res_name)
rule_properties = {
'name': properties.get('name', res_name),
'project': project_id,
'loadBalancingScheme': 'EXTERNAL',
'target': '$(ref.{}.selfLink)'.format(target['name']),
'IPProtocol': 'TCP',
}
rule_resource = {
'name': name,
'type': 'forwarding_rule.py',
'properties': rule_properties,
'metadata': {
'dependsOn': [target['name']],
},
}
optional_properties = [
'description',
'IPAddress',
'ipVersion',
'portRange',
]
for prop in optional_properties:
set_optional_property(rule_properties, properties, prop)
return [rule_resource], [
{
'name': 'forwardingRuleName',
'value': rule_properties['name'],
},
{
'name': 'forwardingRuleSelfLink',
'value': '$(ref.{}.selfLink)'.format(name),
},
{
'name': 'IPAddress',
'value': '$(ref.{}.IPAddress)'.format(name),
},
]
def get_backend_services(properties, res_name, project_id):
""" Creates all backend services to be used by the load balancer. """
backend_resources = []
backend_outputs_map = {
'backendServiceName': [],
'backendServiceSelfLink': []
}
backend_specs = properties['backendServices']
for backend_spec in backend_specs:
backend_res_name = '{}-backend-service-{}'.format(res_name, sha1(json.dumps(backend_spec).encode('utf-8')).hexdigest()[:10])
resources, outputs = get_backend_service(properties, backend_spec, backend_res_name, project_id)
backend_resources += resources
# Merge outputs with the same name.
for output in outputs:
backend_outputs_map[output['name']].append(output['value'])
backend_outputs = []
for key, value in backend_outputs_map.items():
backend_outputs.append({'name': key + 's', 'value': value})
return backend_resources, backend_outputs
def get_ref(name, prop='selfLink'):
""" Creates reference to a property of a given resource. """
return '$(ref.{}.{})'.format(name, prop)
def update_refs_recursively(properties):
""" Replaces service names with the service selflinks recursively. """
for prop in properties:
value = properties[prop]
if prop == 'defaultService' or prop == 'service':
is_regular_name = not '.' in value and not '/' in value
if is_regular_name:
properties[prop] = get_ref(value)
elif isinstance(value, dict):
update_refs_recursively(value)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
update_refs_recursively(item)
def get_url_map(properties, res_name, project_id):
""" Creates a UrlMap resource. """
spec = copy.deepcopy(properties)
spec['project'] = project_id
spec['name'] = properties.get('name', res_name)
update_refs_recursively(spec)
resource = {
'name': res_name,
'type': 'url_map.py',
'properties': spec,
}
self_link = '$(ref.{}.selfLink)'.format(res_name)
return self_link, [resource], [
{
'name': 'urlMapName',
'value': '$(ref.{}.name)'.format(res_name)
},
{
'name': 'urlMapSelfLink',
'value': self_link
}
]
def get_target_proxy(properties, res_name, project_id, bs_resources):
""" Creates a target proxy resource. """
protocol = get_protocol(properties)
depends = []
if 'HTTP' in protocol:
urlMap = copy.deepcopy(properties['urlMap'])
if 'name' not in urlMap and 'name' in properties:
urlMap['name'] = '{}-url-map'.format(properties['name'])
target, resources, outputs = get_url_map(
urlMap,
'{}-url-map'.format(res_name),
project_id
)
depends.append(resources[0]['name'])
else:
depends.append(bs_resources[0]['name'])
target = get_ref(bs_resources[0]['name'])
resources = []
outputs = []
name = '{}-target'.format(res_name)
proxy = {
'name': name,
'type': 'target_proxy.py',
'properties': {
'name': '{}-target'.format(properties.get('name', res_name)),
'project': project_id,
'protocol': protocol,
'target': target,
},
'metadata': {
'dependsOn': [depends],
},
}
for prop in ['proxyHeader', 'quicOverride']:
set_optional_property(proxy['properties'], properties, prop)
outputs.extend(
[
{
'name': 'targetProxyName',
'value': '$(ref.{}.name)'.format(name)
},
{
'name': 'targetProxySelfLink',
'value': '$(ref.{}.selfLink)'.format(name)
},
{
'name': 'targetProxyKind',
'value': '$(ref.{}.kind)'.format(name)
}
]
)
if 'ssl' in properties:
ssl_spec = properties['ssl']
proxy['properties']['ssl'] = ssl_spec
creates_new_certificate = not 'url' in ssl_spec['certificate']
if creates_new_certificate:
outputs.extend(
[
{
'name': 'certificateName',
'value': '$(ref.{}.certificateName)'.format(name)
},
{
'name': 'certificateSelfLink',
'value': '$(ref.{}.certificateSelfLink)'.format(name)
}
]
)
return [proxy] + resources, outputs
def get_protocol(properties):
""" Finds what network protocol to use. """
is_web = 'urlMap' in properties
is_secure = 'ssl' in properties
if is_web:
if is_secure:
return 'HTTPS'
return 'HTTP'
if is_secure:
return 'SSL'
return 'TCP'
def generate_config(context):
""" Entry point for the deployment resources. """
properties = context.properties
project_id = properties.get('project', context.env['project'])
# Forwarding rule + target proxy + backend service = ELB
bs_resources, bs_outputs = get_backend_services(properties, context.env['name'], project_id)
target_resources, target_outputs = get_target_proxy(properties, context.env['name'], project_id, bs_resources)
rule_resources, rule_outputs = get_forwarding_rule(
properties,
target_resources[0],
context.env['name'],
project_id
)
return {
'resources': bs_resources + target_resources + rule_resources,
'outputs': bs_outputs + target_outputs + rule_outputs,
}
| 29.336538
| 132
| 0.57839
|
import copy
from hashlib import sha1
import json
def set_optional_property(destination, source, prop_name):
if prop_name in source:
destination[prop_name] = source[prop_name]
def get_backend_service(properties, backend_spec, res_name, project_id):
name = backend_spec.get('resourceName', res_name)
backend_name = backend_spec.get('name', name)
backend_properties = {
'name': backend_name,
'project': project_id,
'loadBalancingScheme': 'EXTERNAL',
'protocol': get_protocol(properties),
}
backend_resource = {
'name': name,
'type': 'backend_service.py',
'properties': backend_properties
}
optional_properties = [
'description',
'backends',
'timeoutSec',
'sessionAffinity',
'connectionDraining',
'backends',
'healthCheck',
'healthChecks',
'portName',
'enableCDN',
'affinityCookieTtlSec'
]
for prop in optional_properties:
set_optional_property(backend_properties, backend_spec, prop)
return [backend_resource], [
{
'name': 'backendServiceName',
'value': backend_name,
},
{
'name': 'backendServiceSelfLink',
'value': '$(ref.{}.selfLink)'.format(name),
},
]
def get_forwarding_rule(properties, target, res_name, project_id):
name = '{}-forwarding-rule'.format(res_name)
rule_properties = {
'name': properties.get('name', res_name),
'project': project_id,
'loadBalancingScheme': 'EXTERNAL',
'target': '$(ref.{}.selfLink)'.format(target['name']),
'IPProtocol': 'TCP',
}
rule_resource = {
'name': name,
'type': 'forwarding_rule.py',
'properties': rule_properties,
'metadata': {
'dependsOn': [target['name']],
},
}
optional_properties = [
'description',
'IPAddress',
'ipVersion',
'portRange',
]
for prop in optional_properties:
set_optional_property(rule_properties, properties, prop)
return [rule_resource], [
{
'name': 'forwardingRuleName',
'value': rule_properties['name'],
},
{
'name': 'forwardingRuleSelfLink',
'value': '$(ref.{}.selfLink)'.format(name),
},
{
'name': 'IPAddress',
'value': '$(ref.{}.IPAddress)'.format(name),
},
]
def get_backend_services(properties, res_name, project_id):
backend_resources = []
backend_outputs_map = {
'backendServiceName': [],
'backendServiceSelfLink': []
}
backend_specs = properties['backendServices']
for backend_spec in backend_specs:
backend_res_name = '{}-backend-service-{}'.format(res_name, sha1(json.dumps(backend_spec).encode('utf-8')).hexdigest()[:10])
resources, outputs = get_backend_service(properties, backend_spec, backend_res_name, project_id)
backend_resources += resources
for output in outputs:
backend_outputs_map[output['name']].append(output['value'])
backend_outputs = []
for key, value in backend_outputs_map.items():
backend_outputs.append({'name': key + 's', 'value': value})
return backend_resources, backend_outputs
def get_ref(name, prop='selfLink'):
return '$(ref.{}.{})'.format(name, prop)
def update_refs_recursively(properties):
for prop in properties:
value = properties[prop]
if prop == 'defaultService' or prop == 'service':
is_regular_name = not '.' in value and not '/' in value
if is_regular_name:
properties[prop] = get_ref(value)
elif isinstance(value, dict):
update_refs_recursively(value)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
update_refs_recursively(item)
def get_url_map(properties, res_name, project_id):
spec = copy.deepcopy(properties)
spec['project'] = project_id
spec['name'] = properties.get('name', res_name)
update_refs_recursively(spec)
resource = {
'name': res_name,
'type': 'url_map.py',
'properties': spec,
}
self_link = '$(ref.{}.selfLink)'.format(res_name)
return self_link, [resource], [
{
'name': 'urlMapName',
'value': '$(ref.{}.name)'.format(res_name)
},
{
'name': 'urlMapSelfLink',
'value': self_link
}
]
def get_target_proxy(properties, res_name, project_id, bs_resources):
protocol = get_protocol(properties)
depends = []
if 'HTTP' in protocol:
urlMap = copy.deepcopy(properties['urlMap'])
if 'name' not in urlMap and 'name' in properties:
urlMap['name'] = '{}-url-map'.format(properties['name'])
target, resources, outputs = get_url_map(
urlMap,
'{}-url-map'.format(res_name),
project_id
)
depends.append(resources[0]['name'])
else:
depends.append(bs_resources[0]['name'])
target = get_ref(bs_resources[0]['name'])
resources = []
outputs = []
name = '{}-target'.format(res_name)
proxy = {
'name': name,
'type': 'target_proxy.py',
'properties': {
'name': '{}-target'.format(properties.get('name', res_name)),
'project': project_id,
'protocol': protocol,
'target': target,
},
'metadata': {
'dependsOn': [depends],
},
}
for prop in ['proxyHeader', 'quicOverride']:
set_optional_property(proxy['properties'], properties, prop)
outputs.extend(
[
{
'name': 'targetProxyName',
'value': '$(ref.{}.name)'.format(name)
},
{
'name': 'targetProxySelfLink',
'value': '$(ref.{}.selfLink)'.format(name)
},
{
'name': 'targetProxyKind',
'value': '$(ref.{}.kind)'.format(name)
}
]
)
if 'ssl' in properties:
ssl_spec = properties['ssl']
proxy['properties']['ssl'] = ssl_spec
creates_new_certificate = not 'url' in ssl_spec['certificate']
if creates_new_certificate:
outputs.extend(
[
{
'name': 'certificateName',
'value': '$(ref.{}.certificateName)'.format(name)
},
{
'name': 'certificateSelfLink',
'value': '$(ref.{}.certificateSelfLink)'.format(name)
}
]
)
return [proxy] + resources, outputs
def get_protocol(properties):
is_web = 'urlMap' in properties
is_secure = 'ssl' in properties
if is_web:
if is_secure:
return 'HTTPS'
return 'HTTP'
if is_secure:
return 'SSL'
return 'TCP'
def generate_config(context):
properties = context.properties
project_id = properties.get('project', context.env['project'])
bs_resources, bs_outputs = get_backend_services(properties, context.env['name'], project_id)
target_resources, target_outputs = get_target_proxy(properties, context.env['name'], project_id, bs_resources)
rule_resources, rule_outputs = get_forwarding_rule(
properties,
target_resources[0],
context.env['name'],
project_id
)
return {
'resources': bs_resources + target_resources + rule_resources,
'outputs': bs_outputs + target_outputs + rule_outputs,
}
| true
| true
|
790e316af9a26848af5da0502b2886d875c009bd
| 3,324
|
py
|
Python
|
smarts/core/tests/test_sensors.py
|
zbzhu99/SMARTS
|
652aa23e71bd4e2732e2742140cfcd0ec082a7da
|
[
"MIT"
] | null | null | null |
smarts/core/tests/test_sensors.py
|
zbzhu99/SMARTS
|
652aa23e71bd4e2732e2742140cfcd0ec082a7da
|
[
"MIT"
] | null | null | null |
smarts/core/tests/test_sensors.py
|
zbzhu99/SMARTS
|
652aa23e71bd4e2732e2742140cfcd0ec082a7da
|
[
"MIT"
] | null | null | null |
# MIT License
#
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from unittest import mock
import numpy as np
import pytest
from helpers.scenario import temp_scenario
from smarts.core.agent_interface import AgentInterface
from smarts.core.coordinates import Heading, Pose
from smarts.core.plan import Plan
from smarts.core.scenario import Scenario
from smarts.core.sensors import DrivenPathSensor, WaypointsSensor
from smarts.sstudio import gen_scenario
from smarts.sstudio import types as t
AGENT_ID = "Agent-007"
def test_driven_path_sensor():
vehicle = mock.Mock()
sim = mock.Mock()
max_path_length = 5
sensor = DrivenPathSensor(vehicle, max_path_length=max_path_length)
positions = [(x, 0, 0) for x in range(0, 100, 10)]
sim_times = list(range(0, 50, 5))
for idx, (position, sim_time) in enumerate(zip(positions, sim_times)):
sim.elapsed_sim_time = sim_time
vehicle.position = position
sensor.track_latest_driven_path(sim)
if idx >= 3:
assert sensor.distance_travelled(sim, last_n_steps=3) == 30
assert sensor.distance_travelled(sim, last_n_seconds=10) == 20
assert len(sensor()) <= max_path_length
sensor.teardown()
@pytest.fixture
def scenarios():
with temp_scenario(name="straight", map="maps/6lane.net.xml") as scenario_root:
ego_missions = [
t.Mission(
t.Route(
begin=("edge-west-WE", 0, 10),
end=("edge-east-WE", 0, "max"),
)
),
]
gen_scenario(
t.Scenario(ego_missions=ego_missions),
output_dir=scenario_root,
)
yield Scenario.variations_for_all_scenario_roots(
[str(scenario_root)], [AGENT_ID]
)
def test_waypoints_sensor(scenarios):
scenario = next(scenarios)
sim = mock.Mock()
vehicle = mock.Mock()
vehicle.pose = Pose(
position=np.array([33, -65, 0]),
orientation=[0, 0, 0, 0],
heading_=Heading(0),
)
mission = scenario.missions[AGENT_ID]
plan = Plan(scenario.road_map, mission)
sensor = WaypointsSensor(vehicle, plan)
waypoints = sensor()
assert len(waypoints) == 3
| 33.24
| 83
| 0.690734
|
from unittest import mock
import numpy as np
import pytest
from helpers.scenario import temp_scenario
from smarts.core.agent_interface import AgentInterface
from smarts.core.coordinates import Heading, Pose
from smarts.core.plan import Plan
from smarts.core.scenario import Scenario
from smarts.core.sensors import DrivenPathSensor, WaypointsSensor
from smarts.sstudio import gen_scenario
from smarts.sstudio import types as t
AGENT_ID = "Agent-007"
def test_driven_path_sensor():
vehicle = mock.Mock()
sim = mock.Mock()
max_path_length = 5
sensor = DrivenPathSensor(vehicle, max_path_length=max_path_length)
positions = [(x, 0, 0) for x in range(0, 100, 10)]
sim_times = list(range(0, 50, 5))
for idx, (position, sim_time) in enumerate(zip(positions, sim_times)):
sim.elapsed_sim_time = sim_time
vehicle.position = position
sensor.track_latest_driven_path(sim)
if idx >= 3:
assert sensor.distance_travelled(sim, last_n_steps=3) == 30
assert sensor.distance_travelled(sim, last_n_seconds=10) == 20
assert len(sensor()) <= max_path_length
sensor.teardown()
@pytest.fixture
def scenarios():
with temp_scenario(name="straight", map="maps/6lane.net.xml") as scenario_root:
ego_missions = [
t.Mission(
t.Route(
begin=("edge-west-WE", 0, 10),
end=("edge-east-WE", 0, "max"),
)
),
]
gen_scenario(
t.Scenario(ego_missions=ego_missions),
output_dir=scenario_root,
)
yield Scenario.variations_for_all_scenario_roots(
[str(scenario_root)], [AGENT_ID]
)
def test_waypoints_sensor(scenarios):
scenario = next(scenarios)
sim = mock.Mock()
vehicle = mock.Mock()
vehicle.pose = Pose(
position=np.array([33, -65, 0]),
orientation=[0, 0, 0, 0],
heading_=Heading(0),
)
mission = scenario.missions[AGENT_ID]
plan = Plan(scenario.road_map, mission)
sensor = WaypointsSensor(vehicle, plan)
waypoints = sensor()
assert len(waypoints) == 3
| true
| true
|
790e31b1372979e39e09f95e42d22ae54b2a220b
| 8,385
|
py
|
Python
|
pythran/tests/pydata/compute_mask.py
|
davidbrochart/pythran
|
24b6c8650fe99791a4091cbdc2c24686e86aa67c
|
[
"BSD-3-Clause"
] | 1,647
|
2015-01-13T01:45:38.000Z
|
2022-03-28T01:23:41.000Z
|
pythran/tests/pydata/compute_mask.py
|
davidbrochart/pythran
|
24b6c8650fe99791a4091cbdc2c24686e86aa67c
|
[
"BSD-3-Clause"
] | 1,116
|
2015-01-01T09:52:05.000Z
|
2022-03-18T21:06:40.000Z
|
pythran/tests/pydata/compute_mask.py
|
davidbrochart/pythran
|
24b6c8650fe99791a4091cbdc2c24686e86aa67c
|
[
"BSD-3-Clause"
] | 180
|
2015-02-12T02:47:28.000Z
|
2022-03-14T10:28:18.000Z
|
#pythran export compute_mask(int[:,:], int[:,:])
#runas import numpy as np; coords = np.array([[0, 0, 1, 1, 2, 2]]); indices = np.array([[0, 3, 2]]); compute_mask(coords, indices)
import numpy as np
def compute_mask(coords, indices): # pragma: no cover
"""
Gets the mask for the coords given the indices in slice format.
Works with either start-stop ranges of matching indices into coords
called "pairs" (start-stop pairs) or filters the mask directly, based
on which is faster.
Exploits the structure in sorted coords, which is that for a constant
value of coords[i - 1], coords[i - 2] and so on, coords[i] is sorted.
Concretely, ``coords[i, coords[i - 1] == v1 & coords[i - 2] = v2, ...]``
is always sorted. It uses this sortedness to find sub-pairs for each
dimension given the previous, and so on. This is efficient for small
slices or ints, but not for large ones.
After it detects that working with pairs is rather inefficient (or after
going through each possible index), it constructs a filtered mask from the
start-stop pairs.
Parameters
----------
coords : np.ndarray
The coordinates of the array.
indices : np.ndarray
The indices in the form of slices such that indices[:, 0] are starts,
indices[:, 1] are stops and indices[:, 2] are steps.
Returns
-------
mask : np.ndarray
The starts and stops in the mask.
is_slice : bool
Whether or not the array represents a continuous slice.
Examples
--------
Let's create some mock coords and indices
>>> import numpy as np
>>> coords = np.array([[0, 0, 1, 1, 2, 2]])
>>> indices = np.array([[0, 3, 2]]) # Equivalent to slice(0, 3, 2)
Now let's get the mask. Notice that the indices of ``0`` and ``2`` are matched.
>>> _compute_mask(coords, indices)
(array([0, 1, 4, 5]), False)
Now, let's try with a more "continuous" slice. Matches ``0`` and ``1``.
>>> indices = np.array([[0, 2, 1]])
>>> _compute_mask(coords, indices)
(array([0, 4]), True)
This is equivalent to mask being ``slice(0, 4, 1)``.
"""
# Set the initial mask to be the entire range of coordinates.
starts = [0]
stops = [coords.shape[1]]
n_matches = coords.shape[1]
i = 0
while i < len(indices):
# Guesstimate whether working with pairs is more efficient or
# working with the mask directly.
# One side is the estimate of time taken for binary searches
# (n_searches * log(avg_length))
# The other is an estimated time of a linear filter for the mask.
n_pairs = len(starts)
n_current_slices = _get_slice_len(indices[i]) * n_pairs + 2
if n_current_slices * np.log(n_current_slices / max(n_pairs, 1)) > \
n_matches + n_pairs:
break
# For each of the pairs, search inside the coordinates for other
# matching sub-pairs.
# This gets the start-end coordinates in coords for each 'sub-array'
# Which would come out of indexing a single integer.
starts, stops, n_matches = _get_mask_pairs(starts, stops, coords[i], indices[i])
i += 1
# Combine adjacent pairs
starts, stops = _join_adjacent_pairs(starts, stops)
# If just one pair is left over, treat it as a slice.
if i == len(indices) and len(starts) == 1:
return np.array([starts[0], stops[0]]), True
# Convert start-stop pairs into mask, filtering by remaining
# coordinates.
mask = _filter_pairs(starts, stops, coords[i:], indices[i:])
return np.array(mask, dtype=np.intp), False
def _get_slice_len(idx):
"""
Get the number of elements in a slice.
Parameters
----------
idx : np.ndarray
A (3,) shaped array containing start, stop, step
Returns
-------
n : int
The length of the slice.
Examples
--------
>>> idx = np.array([5, 15, 5])
>>> _get_slice_len(idx)
2
"""
start, stop, step = idx[0], idx[1], idx[2]
if step > 0:
return (stop - start + step - 1) // step
else:
return (start - stop - step - 1) // (-step)
def _get_mask_pairs(starts_old, stops_old, c, idx): # pragma: no cover
"""
Gets the pairs for a following dimension given the pairs for
a dimension.
For each pair, it searches in the following dimension for
matching coords and returns those.
The total combined length of all pairs is returned to
help with the performance guesstimate.
Parameters
----------
starts_old, stops_old : list[int]
The starts and stops from the previous index.
c : np.ndarray
The coords for this index's dimension.
idx : np.ndarray
The index in the form of a slice.
idx[0], idx[1], idx[2] = start, stop, step
Returns
-------
starts, stops: list
The starts and stops after applying the current index.
n_matches : int
The sum of elements in all ranges.
Examples
--------
>>> c = np.array([1, 2, 1, 2, 1, 1, 2, 2])
>>> starts_old = [4]
>>> stops_old = [8]
>>> idx = np.array([1, 2, 1])
>>> _get_mask_pairs(starts_old, stops_old, c, idx)
([4], [6], 2)
"""
starts = []
stops = []
n_matches = 0
for j in range(len(starts_old)):
# For each matching "integer" in the slice, search within the "sub-coords"
# Using binary search.
for p_match in range(idx[0], idx[1], idx[2]):
start = np.searchsorted(c[starts_old[j]:stops_old[j]], p_match) + starts_old[j]
stop = np.searchsorted(c[starts_old[j]:stops_old[j]], p_match + 1) + starts_old[j]
if start != stop:
starts.append(start)
stops.append(stop)
n_matches += stop - start
return starts, stops, n_matches
def _join_adjacent_pairs(starts_old, stops_old): # pragma: no cover
"""
Joins adjacent pairs into one. For example, 2-5 and 5-7
will reduce to 2-7 (a single pair). This may help in
returning a slice in the end which could be faster.
Parameters
----------
starts_old, stops_old : list[int]
The input starts and stops
Returns
-------
starts, stops : list[int]
The reduced starts and stops.
Examples
--------
>>> starts = [2, 5]
>>> stops = [5, 7]
>>> _join_adjacent_pairs(starts, stops)
([2], [7])
"""
if len(starts_old) <= 1:
return starts_old, stops_old
starts = [starts_old[0]]
stops = []
for i in range(1, len(starts_old)):
if starts_old[i] != stops_old[i - 1]:
starts.append(starts_old[i])
stops.append(stops_old[i - 1])
stops.append(stops_old[-1])
return starts, stops
def _filter_pairs(starts, stops, coords, indices): # pragma: no cover
"""
Converts all the pairs into a single integer mask, additionally filtering
by the indices.
Parameters
----------
starts, stops : list[int]
The starts and stops to convert into an array.
coords : np.ndarray
The coordinates to filter by.
indices : np.ndarray
The indices in the form of slices such that indices[:, 0] are starts,
indices[:, 1] are stops and indices[:, 2] are steps.
Returns
-------
mask : list
The output integer mask.
Examples
--------
>>> import numpy as np
>>> starts = [2]
>>> stops = [7]
>>> coords = np.array([[0, 1, 2, 3, 4, 5, 6, 7]])
>>> indices = np.array([[2, 8, 2]]) # Start, stop, step pairs
>>> _filter_pairs(starts, stops, coords, indices)
[2, 4, 6]
"""
mask = []
# For each pair,
for i in range(len(starts)):
# For each element match within the pair range
for j in range(starts[i], stops[i]):
match = True
# Check if it matches all indices
for k in range(len(indices)):
idx = indices[k]
elem = coords[k, j]
match &= ((elem - idx[0]) % idx[2] == 0 and
((idx[2] > 0 and idx[0] <= elem < idx[1])
or (idx[2] < 0 and idx[0] >= elem > idx[1])))
# and append to the mask if so.
if match:
mask.append(j)
return mask
| 30.714286
| 130
| 0.584377
|
import numpy as np
def compute_mask(coords, indices):
starts = [0]
stops = [coords.shape[1]]
n_matches = coords.shape[1]
i = 0
while i < len(indices):
n_pairs = len(starts)
n_current_slices = _get_slice_len(indices[i]) * n_pairs + 2
if n_current_slices * np.log(n_current_slices / max(n_pairs, 1)) > \
n_matches + n_pairs:
break
starts, stops, n_matches = _get_mask_pairs(starts, stops, coords[i], indices[i])
i += 1
starts, stops = _join_adjacent_pairs(starts, stops)
if i == len(indices) and len(starts) == 1:
return np.array([starts[0], stops[0]]), True
mask = _filter_pairs(starts, stops, coords[i:], indices[i:])
return np.array(mask, dtype=np.intp), False
def _get_slice_len(idx):
start, stop, step = idx[0], idx[1], idx[2]
if step > 0:
return (stop - start + step - 1) // step
else:
return (start - stop - step - 1) // (-step)
def _get_mask_pairs(starts_old, stops_old, c, idx):
starts = []
stops = []
n_matches = 0
for j in range(len(starts_old)):
for p_match in range(idx[0], idx[1], idx[2]):
start = np.searchsorted(c[starts_old[j]:stops_old[j]], p_match) + starts_old[j]
stop = np.searchsorted(c[starts_old[j]:stops_old[j]], p_match + 1) + starts_old[j]
if start != stop:
starts.append(start)
stops.append(stop)
n_matches += stop - start
return starts, stops, n_matches
def _join_adjacent_pairs(starts_old, stops_old):
if len(starts_old) <= 1:
return starts_old, stops_old
starts = [starts_old[0]]
stops = []
for i in range(1, len(starts_old)):
if starts_old[i] != stops_old[i - 1]:
starts.append(starts_old[i])
stops.append(stops_old[i - 1])
stops.append(stops_old[-1])
return starts, stops
def _filter_pairs(starts, stops, coords, indices):
mask = []
for i in range(len(starts)):
for j in range(starts[i], stops[i]):
match = True
for k in range(len(indices)):
idx = indices[k]
elem = coords[k, j]
match &= ((elem - idx[0]) % idx[2] == 0 and
((idx[2] > 0 and idx[0] <= elem < idx[1])
or (idx[2] < 0 and idx[0] >= elem > idx[1])))
if match:
mask.append(j)
return mask
| true
| true
|
790e32c1527812cf451bbea000970659b3399682
| 6,233
|
py
|
Python
|
soccer/gameplay/skills/angle_receive.py
|
Alex-Gurung/robocup-software
|
9271df5ed16928f0081fc81c50affb0a08dd54bd
|
[
"Apache-2.0"
] | 1
|
2019-01-18T02:03:26.000Z
|
2019-01-18T02:03:26.000Z
|
soccer/gameplay/skills/angle_receive.py
|
Alex-Gurung/robocup-software
|
9271df5ed16928f0081fc81c50affb0a08dd54bd
|
[
"Apache-2.0"
] | null | null | null |
soccer/gameplay/skills/angle_receive.py
|
Alex-Gurung/robocup-software
|
9271df5ed16928f0081fc81c50affb0a08dd54bd
|
[
"Apache-2.0"
] | null | null | null |
import robocup
import constants
import main
import math
import skills.touch_ball
import skills._kick
import skills.pass_receive
## AngleReceive accepts a receive_point as a parameter and gets setup there to catch the ball
# It transitions to the 'aligned' state once it's there within its error thresholds and is steady
# Set its 'ball_kicked' property to True to tell it to dynamically update its position based on where
# the ball is moving and attempt to catch it.
# It will move to the 'completed' state if it catches the ball, otherwise it will go to 'failed'.
# Kick is a single_robot_behavior, so no need to import both
class AngleReceive(skills.pass_receive.PassReceive):
def __init__(self):
super().__init__(
captureFunction=(lambda: skills.touch_ball.TouchBall()))
self._target_point = None
self.kick_power = 1
self.target_point = constants.Field.TheirGoalSegment.center()
self.ball_kicked = False
self.target_angle = 0
## The point that the receiver should expect the ball to hit it's mouth
# Default: constants.Field.TheirGoalSegment.center()
@property
def target_point(self):
return self._target_point
@target_point.setter
def target_point(self, value):
self._target_point = value
self.recalculate()
## Returns an adjusted angle with account for ball speed
#
# First finds the rejection, which is the X component of the ball's velocity in the reference
# frame of the robot, with the mouth facing the y axis. Then we calculate the angle required to
# offset this rejection angle (if possible).
def adjust_angle(self, target_angle, ball_angle=None, ball_speed=None):
ball = main.ball()
if ball_angle == None:
ball_angle = (ball.vel).angle()
if ball_speed == None:
ball_speed = ball.vel.mag()
angle_diff = target_angle - ball_angle
rejection = math.sin(angle_diff) * ball_speed
# The min/max is to bound the value by -1 and 1.
adjust = math.asin(min(1, max(-1, rejection /
constants.Robot.MaxKickSpeed)))
return adjust + target_angle
# calculates:
# self._pass_line - the line from the ball along where we think we're going
# self._target_pos - where the bot should be
# self._angle_error - difference in where we're facing and where we want to face (in radians)
# self._x_error
# self._y_error
def recalculate(self):
# can't do squat if we don't know what we're supposed to do
if self.receive_point == None or self.robot == None or self.target_point == None:
return
ball = main.ball()
if self.ball_kicked:
# when the ball's in motion, the line is based on the ball's velocity
self._pass_line = robocup.Line(ball.pos, ball.pos + ball.vel * 10)
# After kicking, apply angle calculations
target_angle_rad = self.adjust_angle((self.target_point -
self.robot.pos).angle())
# Removes angle adjustment
# target_angle_rad = (self.target_point - self.robot.pos).angle()
self._kick_line = robocup.Line(self.robot.pos, robocup.Point(
self.robot.pos.x + math.cos(self.robot.angle) * 10,
self.robot.pos.y + math.sin(self.robot.angle) * 10))
else:
# if the ball hasn't been kicked yet, we assume it's going to go through the receive point
self._pass_line = robocup.Line(ball.pos, self.receive_point)
# Assume ball is kicked at max speed and is coming from the ball point to the location of our robot. Then average this with the target angle.
target_angle_rad = self.adjust_angle(
(self.target_point - self.robot.pos).angle(),
(self.robot.pos - main.ball().pos).angle(),
constants.Robot.MaxKickSpeed)
# TODO make this faster by caching the .angle() part
target_angle_rad = (
target_angle_rad +
(self.target_point - self.robot.pos).angle()) / 2
self._kick_line = robocup.Line(self.receive_point,
self.target_point)
self._angle_facing = target_angle_rad
self.target_angle = target_angle_rad
angle_rad = self.robot.angle
self._angle_error = target_angle_rad - angle_rad
if self.ball_kicked:
receive_before_adjust = self._pass_line.nearest_point(
self.robot.pos)
else:
receive_before_adjust = self.receive_point
# Make the receive point be the mouth, rather than the center of the robot.
# Assumes mouth of robot is at the edge.
self._target_pos = receive_before_adjust - robocup.Point(
constants.Robot.Radius * math.cos(self.robot.angle),
constants.Robot.Radius * math.sin(self.robot.angle))
# Code to provide slipback when receiving the ball
# pass_line_dir = (self._pass_line.get_pt(1) - self._pass_line.get_pt(0)).normalized()
# self._target_pos = actual_receive_point + pass_line_dir * constants.Robot.Radius
# vector pointing down the pass line toward the kicker
self._x_error = self._target_pos.x - self.robot.pos.x
self._y_error = self._target_pos.y - self.robot.pos.y
def execute_running(self):
super().execute_running()
self.recalculate()
self.robot.face(self.robot.pos + robocup.Point(
math.cos(self._angle_facing), math.sin(self._angle_facing)))
if self._kick_line != None:
main.system_state().draw_line(self._kick_line,
constants.Colors.Red, "Shot")
def execute_receiving(self):
super().execute_receiving()
self.ball_kicked = True
# Kick the ball!
self.robot.kick(self.kick_power)
if self.target_point != None:
main.system_state().draw_circle(self.target_point, 0.03,
constants.Colors.Blue, "Target")
| 42.691781
| 153
| 0.636932
|
import robocup
import constants
import main
import math
import skills.touch_ball
import skills._kick
import skills.pass_receive
ed on where
# the ball is moving and attempt to catch it.
# It will move to the 'completed' state if it catches the ball, otherwise it will go to 'failed'.
# Kick is a single_robot_behavior, so no need to import both
class AngleReceive(skills.pass_receive.PassReceive):
def __init__(self):
super().__init__(
captureFunction=(lambda: skills.touch_ball.TouchBall()))
self._target_point = None
self.kick_power = 1
self.target_point = constants.Field.TheirGoalSegment.center()
self.ball_kicked = False
self.target_angle = 0
## The point that the receiver should expect the ball to hit it's mouth
@property
def target_point(self):
return self._target_point
@target_point.setter
def target_point(self, value):
self._target_point = value
self.recalculate()
ing the y axis. Then we calculate the angle required to
# offset this rejection angle (if possible).
def adjust_angle(self, target_angle, ball_angle=None, ball_speed=None):
ball = main.ball()
if ball_angle == None:
ball_angle = (ball.vel).angle()
if ball_speed == None:
ball_speed = ball.vel.mag()
angle_diff = target_angle - ball_angle
rejection = math.sin(angle_diff) * ball_speed
# The min/max is to bound the value by -1 and 1.
adjust = math.asin(min(1, max(-1, rejection /
constants.Robot.MaxKickSpeed)))
return adjust + target_angle
# calculates:
# self._pass_line - the line from the ball along where we think we're going
# self._x_error
# self._y_error
def recalculate(self):
# can't do squat if we don't know what we're supposed to do
if self.receive_point == None or self.robot == None or self.target_point == None:
return
ball = main.ball()
if self.ball_kicked:
self._pass_line = robocup.Line(ball.pos, ball.pos + ball.vel * 10)
target_angle_rad = self.adjust_angle((self.target_point -
self.robot.pos).angle())
self._kick_line = robocup.Line(self.robot.pos, robocup.Point(
self.robot.pos.x + math.cos(self.robot.angle) * 10,
self.robot.pos.y + math.sin(self.robot.angle) * 10))
else:
self._pass_line = robocup.Line(ball.pos, self.receive_point)
target_angle_rad = self.adjust_angle(
(self.target_point - self.robot.pos).angle(),
(self.robot.pos - main.ball().pos).angle(),
constants.Robot.MaxKickSpeed)
target_angle_rad = (
target_angle_rad +
(self.target_point - self.robot.pos).angle()) / 2
self._kick_line = robocup.Line(self.receive_point,
self.target_point)
self._angle_facing = target_angle_rad
self.target_angle = target_angle_rad
angle_rad = self.robot.angle
self._angle_error = target_angle_rad - angle_rad
if self.ball_kicked:
receive_before_adjust = self._pass_line.nearest_point(
self.robot.pos)
else:
receive_before_adjust = self.receive_point
self._target_pos = receive_before_adjust - robocup.Point(
constants.Robot.Radius * math.cos(self.robot.angle),
constants.Robot.Radius * math.sin(self.robot.angle))
self._x_error = self._target_pos.x - self.robot.pos.x
self._y_error = self._target_pos.y - self.robot.pos.y
def execute_running(self):
super().execute_running()
self.recalculate()
self.robot.face(self.robot.pos + robocup.Point(
math.cos(self._angle_facing), math.sin(self._angle_facing)))
if self._kick_line != None:
main.system_state().draw_line(self._kick_line,
constants.Colors.Red, "Shot")
def execute_receiving(self):
super().execute_receiving()
self.ball_kicked = True
self.robot.kick(self.kick_power)
if self.target_point != None:
main.system_state().draw_circle(self.target_point, 0.03,
constants.Colors.Blue, "Target")
| true
| true
|
790e357d014fdc21403ef02d0e57957a4fa0e0e7
| 1,012
|
py
|
Python
|
utils/args.py
|
BruceWW/odyn
|
aac5887ecd3daf5864aa99db0927ed86857dfb09
|
[
"Apache-2.0"
] | null | null | null |
utils/args.py
|
BruceWW/odyn
|
aac5887ecd3daf5864aa99db0927ed86857dfb09
|
[
"Apache-2.0"
] | null | null | null |
utils/args.py
|
BruceWW/odyn
|
aac5887ecd3daf5864aa99db0927ed86857dfb09
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python
# -*- coding:utf-8 _*-
# @author : Lin Luo / Bruce Liu
# @time : 2020/1/3 21:35
# @contact : 15869300264@163.com / bruce.w.y.liu@gmail.com
import argparse
parser = argparse.ArgumentParser()
parser.add_argument_group()
parser.add_argument('-c', '--config', help='config file for run and operation', required=False)
group = parser.add_mutually_exclusive_group()
group.add_argument('-a', '--add', help='add sk with ip', required=False)
group.add_argument('-d', '--delete', help='delete sk by sk or ip', required=False)
# group.add_argument('-e', '-examine', help='examine the status of ip', required=False)
group.add_argument('-r', '--run', help='run the main project', action='store_true', required=False)
group.add_argument('-t', '--test', help='test the config file, default path is conf/odyn.conf', action='store_true',
required=False)
group.add_argument('-s', '--stop', help='stop the main project', action='store_true', required=False)
args = parser.parse_args()
| 50.6
| 116
| 0.697628
|
import argparse
parser = argparse.ArgumentParser()
parser.add_argument_group()
parser.add_argument('-c', '--config', help='config file for run and operation', required=False)
group = parser.add_mutually_exclusive_group()
group.add_argument('-a', '--add', help='add sk with ip', required=False)
group.add_argument('-d', '--delete', help='delete sk by sk or ip', required=False)
group.add_argument('-r', '--run', help='run the main project', action='store_true', required=False)
group.add_argument('-t', '--test', help='test the config file, default path is conf/odyn.conf', action='store_true',
required=False)
group.add_argument('-s', '--stop', help='stop the main project', action='store_true', required=False)
args = parser.parse_args()
| true
| true
|
790e36494da98b513d2ae9804861c0907501b1cd
| 5,611
|
py
|
Python
|
osc_bge/agent/models.py
|
jisuhan3201/osc-bge
|
125c441d23d7f1fdb2d9b8f42f859082e757e25a
|
[
"MIT"
] | null | null | null |
osc_bge/agent/models.py
|
jisuhan3201/osc-bge
|
125c441d23d7f1fdb2d9b8f42f859082e757e25a
|
[
"MIT"
] | 5
|
2020-06-05T19:49:47.000Z
|
2021-09-08T00:50:55.000Z
|
osc_bge/agent/models.py
|
jisuhan3201/osc-bge
|
125c441d23d7f1fdb2d9b8f42f859082e757e25a
|
[
"MIT"
] | null | null | null |
from django.db import models
from osc_bge.users import models as user_models
# Create your models here.
class TimeStampedModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True, null=True)
updated_at = models.DateTimeField(auto_now=True, null=True)
class Meta:
abstract = True
#Agent Head Table
class AgencyHead(TimeStampedModel):
PROGRAM_CHOICES = (
('secondary', 'Secondary'),
('college', 'College'),
('camp', 'Camp'),
)
name = models.CharField(max_length=80, null=True, blank=True)
location = models.CharField(max_length=140, null=True, blank=True)
number_branches = models.CharField(max_length=80, null=True, blank=True)
capacity_students = models.CharField(max_length=255, null=True, blank=True)
commission = models.CharField(max_length=140, null=True, blank=True)
promotion = models.CharField(max_length=255, null=True, blank=True)
others = models.CharField(max_length=255, null=True, blank=True)
comment = models.TextField(null=True, blank=True)
def __str__(self):
return "{}".format(self.name)
class AgencyProgram(TimeStampedModel):
head = models.ForeignKey(AgencyHead, on_delete=models.CASCADE, null=True)
program = models.CharField(max_length=80, null=True, blank=True)
#Agent Branch Table
class Agency(TimeStampedModel):
head = models.ForeignKey(AgencyHead, on_delete=models.CASCADE, null=True, related_name='agent_branch')
name = models.CharField(max_length=140, null=True, blank=True)
location = models.CharField(max_length=140, null=True, blank=True)
capacity_students = models.CharField(max_length=255, null=True, blank=True)
commission = models.CharField(max_length=140, null=True, blank=True)
promotion = models.CharField(max_length=255, null=True, blank=True)
others = models.CharField(max_length=255, null=True, blank=True)
comment = models.TextField(null=True, blank=True)
def __str__(self):
return "{}".format(self.name)
class AgencyBranchProgram(TimeStampedModel):
branch = models.ForeignKey(Agency, on_delete=models.CASCADE, null=True)
program = models.CharField(max_length=80, null=True, blank=True)
def set_filename_format(now, instance, filename):
return "{schoolname}-{microsecond}".format(
agentname=instance.agency,
microsecond=now.microsecond,
)
def agent_directory_path(instance, filename):
now = datetime.datetime.now()
path = "agents/{agentname}/{filename}".format(
agentname=instance.agency,
filename=set_filename_format(now, instance, filename),
)
return path
class AgencyHeadContactInfo(TimeStampedModel):
LEVEL_CHOICES = (
('s', 'S'),
('a', 'A'),
('b', 'B'),
('c', 'C'),
('d', 'D'),
)
agent = models.ForeignKey(AgencyHead, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=80, null=True, blank=True)
contracted_date = models.DateTimeField(auto_now=True, null=True)
phone = models.CharField(max_length=80, null=True, blank=True)
email = models.CharField(max_length=140, null=True, blank=True)
skype = models.CharField(max_length=80, null=True, blank=True)
wechat = models.CharField(max_length=80, null=True, blank=True)
location = models.CharField(max_length=140, null=True, blank=True)
level = models.CharField(max_length=80, null=True, blank=True)
image = models.ImageField(upload_to=agent_directory_path, null=True, blank=True)
def __str__(self):
return "{}".format(self.name)
class AgentRelationshipHistory(TimeStampedModel):
head = models.ForeignKey(AgencyHead, on_delete=models.CASCADE, null=True)
writer = models.CharField(max_length=80, null=True, blank=True)
name = models.CharField(max_length=80, null=True, blank=True)
date = models.DateField(null=True, blank=True)
location = models.CharField(max_length=140, null=True, blank=True)
category = models.CharField(max_length=80, null=True, blank=True)
priority = models.IntegerField(null=True, blank=True)
comment = models.TextField(null=True, blank=True)
class SecodnaryProgram(TimeStampedModel):
agent = models.ForeignKey(AgencyHead, on_delete=models.CASCADE, null=True)
preriod = models.CharField(max_length=80, null=True, blank=True)
target = models.IntegerField(null=True, blank=True)
new_students_fall = models.IntegerField(null=True, blank=True)
new_students_spring = models.IntegerField(null=True, blank=True)
total_new_students_bge = models.IntegerField(null=True, blank=True)
total_students_bge = models.IntegerField(null=True, blank=True)
terminating_students = models.IntegerField(null=True, blank=True)
comments = models.TextField(null=True, blank=True)
class Camp(TimeStampedModel):
agent = models.ForeignKey(AgencyHead, on_delete=models.CASCADE, null=True)
preriod = models.CharField(max_length=80, null=True, blank=True)
target = models.IntegerField(null=True, blank=True)
summer_camp = models.IntegerField(null=True, blank=True)
winter_camp = models.IntegerField(null=True, blank=True)
comments = models.TextField(null=True, blank=True)
class CollegeApplication(TimeStampedModel):
agent = models.ForeignKey(AgencyHead, on_delete=models.CASCADE, null=True)
preriod = models.CharField(max_length=80, null=True, blank=True)
college_application = models.IntegerField(null=True, blank=True)
other_program = models.IntegerField(null=True, blank=True)
comments = models.TextField(null=True, blank=True)
| 38.696552
| 106
| 0.724826
|
from django.db import models
from osc_bge.users import models as user_models
class TimeStampedModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True, null=True)
updated_at = models.DateTimeField(auto_now=True, null=True)
class Meta:
abstract = True
class AgencyHead(TimeStampedModel):
PROGRAM_CHOICES = (
('secondary', 'Secondary'),
('college', 'College'),
('camp', 'Camp'),
)
name = models.CharField(max_length=80, null=True, blank=True)
location = models.CharField(max_length=140, null=True, blank=True)
number_branches = models.CharField(max_length=80, null=True, blank=True)
capacity_students = models.CharField(max_length=255, null=True, blank=True)
commission = models.CharField(max_length=140, null=True, blank=True)
promotion = models.CharField(max_length=255, null=True, blank=True)
others = models.CharField(max_length=255, null=True, blank=True)
comment = models.TextField(null=True, blank=True)
def __str__(self):
return "{}".format(self.name)
class AgencyProgram(TimeStampedModel):
head = models.ForeignKey(AgencyHead, on_delete=models.CASCADE, null=True)
program = models.CharField(max_length=80, null=True, blank=True)
class Agency(TimeStampedModel):
head = models.ForeignKey(AgencyHead, on_delete=models.CASCADE, null=True, related_name='agent_branch')
name = models.CharField(max_length=140, null=True, blank=True)
location = models.CharField(max_length=140, null=True, blank=True)
capacity_students = models.CharField(max_length=255, null=True, blank=True)
commission = models.CharField(max_length=140, null=True, blank=True)
promotion = models.CharField(max_length=255, null=True, blank=True)
others = models.CharField(max_length=255, null=True, blank=True)
comment = models.TextField(null=True, blank=True)
def __str__(self):
return "{}".format(self.name)
class AgencyBranchProgram(TimeStampedModel):
branch = models.ForeignKey(Agency, on_delete=models.CASCADE, null=True)
program = models.CharField(max_length=80, null=True, blank=True)
def set_filename_format(now, instance, filename):
return "{schoolname}-{microsecond}".format(
agentname=instance.agency,
microsecond=now.microsecond,
)
def agent_directory_path(instance, filename):
now = datetime.datetime.now()
path = "agents/{agentname}/{filename}".format(
agentname=instance.agency,
filename=set_filename_format(now, instance, filename),
)
return path
class AgencyHeadContactInfo(TimeStampedModel):
LEVEL_CHOICES = (
('s', 'S'),
('a', 'A'),
('b', 'B'),
('c', 'C'),
('d', 'D'),
)
agent = models.ForeignKey(AgencyHead, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=80, null=True, blank=True)
contracted_date = models.DateTimeField(auto_now=True, null=True)
phone = models.CharField(max_length=80, null=True, blank=True)
email = models.CharField(max_length=140, null=True, blank=True)
skype = models.CharField(max_length=80, null=True, blank=True)
wechat = models.CharField(max_length=80, null=True, blank=True)
location = models.CharField(max_length=140, null=True, blank=True)
level = models.CharField(max_length=80, null=True, blank=True)
image = models.ImageField(upload_to=agent_directory_path, null=True, blank=True)
def __str__(self):
return "{}".format(self.name)
class AgentRelationshipHistory(TimeStampedModel):
head = models.ForeignKey(AgencyHead, on_delete=models.CASCADE, null=True)
writer = models.CharField(max_length=80, null=True, blank=True)
name = models.CharField(max_length=80, null=True, blank=True)
date = models.DateField(null=True, blank=True)
location = models.CharField(max_length=140, null=True, blank=True)
category = models.CharField(max_length=80, null=True, blank=True)
priority = models.IntegerField(null=True, blank=True)
comment = models.TextField(null=True, blank=True)
class SecodnaryProgram(TimeStampedModel):
agent = models.ForeignKey(AgencyHead, on_delete=models.CASCADE, null=True)
preriod = models.CharField(max_length=80, null=True, blank=True)
target = models.IntegerField(null=True, blank=True)
new_students_fall = models.IntegerField(null=True, blank=True)
new_students_spring = models.IntegerField(null=True, blank=True)
total_new_students_bge = models.IntegerField(null=True, blank=True)
total_students_bge = models.IntegerField(null=True, blank=True)
terminating_students = models.IntegerField(null=True, blank=True)
comments = models.TextField(null=True, blank=True)
class Camp(TimeStampedModel):
agent = models.ForeignKey(AgencyHead, on_delete=models.CASCADE, null=True)
preriod = models.CharField(max_length=80, null=True, blank=True)
target = models.IntegerField(null=True, blank=True)
summer_camp = models.IntegerField(null=True, blank=True)
winter_camp = models.IntegerField(null=True, blank=True)
comments = models.TextField(null=True, blank=True)
class CollegeApplication(TimeStampedModel):
agent = models.ForeignKey(AgencyHead, on_delete=models.CASCADE, null=True)
preriod = models.CharField(max_length=80, null=True, blank=True)
college_application = models.IntegerField(null=True, blank=True)
other_program = models.IntegerField(null=True, blank=True)
comments = models.TextField(null=True, blank=True)
| true
| true
|
790e38bcf40153c2751ff631c6ec731a3fac3b77
| 363
|
py
|
Python
|
Statistics/SampleMean.py
|
brittrubil/miniProject2-601
|
eccc43b52de55e2f3ea5400c6b28309aabef1596
|
[
"MIT"
] | null | null | null |
Statistics/SampleMean.py
|
brittrubil/miniProject2-601
|
eccc43b52de55e2f3ea5400c6b28309aabef1596
|
[
"MIT"
] | null | null | null |
Statistics/SampleMean.py
|
brittrubil/miniProject2-601
|
eccc43b52de55e2f3ea5400c6b28309aabef1596
|
[
"MIT"
] | null | null | null |
def sample_mean(a, b, c):
try:
a = int(a)
b = int(b)
c = int(c)
mean_numbers = [a, b, c]
d = len(mean_numbers)
result_mean = (a + b + c)/d
return float(result_mean)
except ZeroDivisionError:
print("Error: Number Not Valid")
except ValueError:
print("Error: Only Numeric Values")
| 25.928571
| 43
| 0.53168
|
def sample_mean(a, b, c):
try:
a = int(a)
b = int(b)
c = int(c)
mean_numbers = [a, b, c]
d = len(mean_numbers)
result_mean = (a + b + c)/d
return float(result_mean)
except ZeroDivisionError:
print("Error: Number Not Valid")
except ValueError:
print("Error: Only Numeric Values")
| true
| true
|
790e392b371d6772f622e6b0553821d52a55e346
| 273
|
py
|
Python
|
CSCS/benchmarks/cosmoflow/implementations/cosmoflow-benchmark/utils/distributed.py
|
bgerofi/hpc_results_v0.7
|
9cd9fa80ebc57db8438b1ac8dbd2d49232da6c2e
|
[
"Apache-2.0"
] | 2
|
2021-06-09T19:38:22.000Z
|
2021-11-15T18:01:21.000Z
|
CSCS/benchmarks/cosmoflow/implementations/cosmoflow-benchmark/utils/distributed.py
|
bgerofi/hpc_results_v0.7
|
9cd9fa80ebc57db8438b1ac8dbd2d49232da6c2e
|
[
"Apache-2.0"
] | null | null | null |
CSCS/benchmarks/cosmoflow/implementations/cosmoflow-benchmark/utils/distributed.py
|
bgerofi/hpc_results_v0.7
|
9cd9fa80ebc57db8438b1ac8dbd2d49232da6c2e
|
[
"Apache-2.0"
] | 3
|
2021-01-20T13:57:25.000Z
|
2021-08-05T06:48:58.000Z
|
"""Utilties for distributed processing"""
import horovod.tensorflow.keras as hvd
def rank():
try:
return hvd.rank()
except ValueError:
return 0
def barrier():
try:
hvd.allreduce([], name='Barrier')
except ValueError:
pass
| 17.0625
| 41
| 0.611722
|
import horovod.tensorflow.keras as hvd
def rank():
try:
return hvd.rank()
except ValueError:
return 0
def barrier():
try:
hvd.allreduce([], name='Barrier')
except ValueError:
pass
| true
| true
|
790e39373087442606769c88aa4dccc98ac7794d
| 807
|
py
|
Python
|
code/grab_foreground.py
|
ultimus11/Foreground-Detection-OpenCV
|
910d6ffa2d37b999ed746ebc69da289d9b48bdf1
|
[
"MIT"
] | 3
|
2021-02-15T13:38:07.000Z
|
2022-03-16T07:52:58.000Z
|
code/grab_foreground.py
|
ultimus11/Foreground-Detection-OpenCV
|
910d6ffa2d37b999ed746ebc69da289d9b48bdf1
|
[
"MIT"
] | null | null | null |
code/grab_foreground.py
|
ultimus11/Foreground-Detection-OpenCV
|
910d6ffa2d37b999ed746ebc69da289d9b48bdf1
|
[
"MIT"
] | null | null | null |
import numpy as np
import cv2
import matplotlib.pyplot as plt
#read image
img = np.array(cv2.imread('1.jpg'))
#this is mask
mask = np.zeros(img.shape[:2],np.uint8)
#this bgdModel and fgdModel is used in background
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
#This is a rectangular cross section of given image where it will search for foreground
rect = (35,30,330,312)
#This is a grabcut func from opencv which is used to detect foreground
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]
#here we show our image
plt.imshow(img)
plt.colorbar()
plt.show()
cv2.imshow("sdfg",img)
cv2.waitKey(0)
cv2.imwrite("foreground.jpg",img)
| 26.9
| 88
| 0.708798
|
import numpy as np
import cv2
import matplotlib.pyplot as plt
img = np.array(cv2.imread('1.jpg'))
mask = np.zeros(img.shape[:2],np.uint8)
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
rect = (35,30,330,312)
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]
plt.imshow(img)
plt.colorbar()
plt.show()
cv2.imshow("sdfg",img)
cv2.waitKey(0)
cv2.imwrite("foreground.jpg",img)
| true
| true
|
790e39f443da1284ca39de4fbc82304831509a67
| 1,324
|
py
|
Python
|
update_results.py
|
tomaszwozniak/behave-docker-parallel
|
b0e8f6083c46e8cb375f2e989d6a85b14363ca14
|
[
"Apache-2.0"
] | 5
|
2018-08-28T07:38:31.000Z
|
2020-11-26T16:09:01.000Z
|
update_results.py
|
tomaszwozniak/behave-docker-parallel
|
b0e8f6083c46e8cb375f2e989d6a85b14363ca14
|
[
"Apache-2.0"
] | null | null | null |
update_results.py
|
tomaszwozniak/behave-docker-parallel
|
b0e8f6083c46e8cb375f2e989d6a85b14363ca14
|
[
"Apache-2.0"
] | 3
|
2018-11-08T15:51:28.000Z
|
2021-01-30T22:19:23.000Z
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os
import sys
def update_allure_feature_name(results_dir: str, prefix: str):
"""Make Allure JSON results unique by pre-pending a prefix to: name, historyId & uuid.
Use it when not all of the test results show up in the Allure report.
This is because tests from different workers can actually have the same: historyId & uuid values.
You can use e.g. browser name as the prefix.
"""
results_dir_path = os.path.join(".", results_dir)
update_count = 0
for filename in os.listdir(results_dir_path):
if filename.endswith(".json"):
result_file = os.path.join(results_dir_path, filename)
with open(result_file, "r") as json_file:
report = json.loads(json_file.read())
report["name"] = f"{prefix} - {report['name']}"
report["historyId"] = f"{prefix}{report['historyId']}"
report["uuid"] = f"{prefix}{report['uuid']}"
with open(result_file, "w") as json_file:
json.dump(report, json_file, indent=2, ensure_ascii=False)
update_count += 1
print(f"Updated {update_count} JSON reports")
if __name__ == "__main__":
update_allure_feature_name(results_dir=sys.argv[1], prefix=sys.argv[2])
| 38.941176
| 101
| 0.638218
|
import json
import os
import sys
def update_allure_feature_name(results_dir: str, prefix: str):
results_dir_path = os.path.join(".", results_dir)
update_count = 0
for filename in os.listdir(results_dir_path):
if filename.endswith(".json"):
result_file = os.path.join(results_dir_path, filename)
with open(result_file, "r") as json_file:
report = json.loads(json_file.read())
report["name"] = f"{prefix} - {report['name']}"
report["historyId"] = f"{prefix}{report['historyId']}"
report["uuid"] = f"{prefix}{report['uuid']}"
with open(result_file, "w") as json_file:
json.dump(report, json_file, indent=2, ensure_ascii=False)
update_count += 1
print(f"Updated {update_count} JSON reports")
if __name__ == "__main__":
update_allure_feature_name(results_dir=sys.argv[1], prefix=sys.argv[2])
| true
| true
|
790e3b7b85a16d9b17ada753ea275397735d7da4
| 4,217
|
py
|
Python
|
Code/EvaluationsStub.py
|
isibord/LogisticRegression
|
5802e8fd3acd73993e0e8891adcb3ab1f58e4544
|
[
"MIT"
] | null | null | null |
Code/EvaluationsStub.py
|
isibord/LogisticRegression
|
5802e8fd3acd73993e0e8891adcb3ab1f58e4544
|
[
"MIT"
] | null | null | null |
Code/EvaluationsStub.py
|
isibord/LogisticRegression
|
5802e8fd3acd73993e0e8891adcb3ab1f58e4544
|
[
"MIT"
] | null | null | null |
import math
import collections
import numpy as np
def __CheckEvaluationInput(y, yPredicted):
# Check sizes
if(len(y) != len(yPredicted)):
raise UserWarning("Attempting to evaluate between the true labels and predictions.\n Arrays contained different numbers of samples. Check your work and try again.")
# Check values
valueError = False
for value in y:
if value not in [0, 1]:
valueError = True
for value in yPredicted:
if value not in [0, 1]:
valueError = True
if valueError:
raise UserWarning("Attempting to evaluate between the true labels and predictions.\n Arrays contained unexpected value. Must be 0 or 1.")
def __CheckEvaluationCount(y, yPredicted):
# Check sizes
if(len(y) != len(yPredicted)):
raise UserWarning("Attempting to evaluate between the true labels and predictions.\n Arrays contained different numbers of samples. Check your work and try again.")
def Accuracy(y, yPredicted):
__CheckEvaluationInput(y, yPredicted)
correct = []
for i in range(len(y)):
if(y[i] == yPredicted[i]):
correct.append(1)
else:
correct.append(0)
return sum(correct)/len(correct)
def CountCorrect(y, yPredicted):
__CheckEvaluationInput(y, yPredicted)
correct = []
for i in range(len(y)):
if(y[i] == yPredicted[i]):
correct.append(1)
else:
correct.append(0)
return sum(correct)
def PredictionDiff(xTestRaw, y, yPredicted):
__CheckEvaluationCount(y, yPredicted)
__CheckEvaluationCount(xTestRaw, y)
predictionRange = {}
for i in range(len(y)):
predictionRange[xTestRaw[i]] = y[i] - yPredicted[i]
return predictionRange
def Precision(y, yPredicted):
numerator = TPCount(y, yPredicted)
denominator = (numerator + FPCount(y, yPredicted))
return 0.0 if denominator == 0 else numerator / denominator
def Recall(y, yPredicted):
numerator = TPCount(y, yPredicted)
denominator = (numerator + FNCount(y, yPredicted))
return 0.0 if denominator == 0 else numerator / denominator
def FalseNegativeRate(y, yPredicted):
numerator = FNCount(y, yPredicted)
denominator = numerator + TPCount(y, yPredicted)
return 0.0 if denominator == 0 else numerator / denominator
def FalsePositiveRate(y, yPredicted):
numerator = FPCount(y, yPredicted)
denominator = numerator + TNCount(y, yPredicted)
return 0.0 if denominator == 0 else numerator / denominator
def FNCount(y, yPredicted):
counter = 0
for i in range(len(y)):
if(y[i] == 1 and yPredicted[i] == 0):
counter += 1
return counter
def FPCount(y, yPredicted):
counter = 0
for i in range(len(y)):
if(y[i] == 0 and yPredicted[i] == 1):
counter += 1
return counter
def TNCount(y, yPredicted):
counter = 0
for i in range(len(y)):
if(y[i] == 0 and yPredicted[i] == 0):
counter += 1
return counter
def TPCount(y, yPredicted):
counter = 0
for i in range(len(y)):
if(y[i] == 1 and yPredicted[i] == 1):
counter += 1
return counter
def UpperAccRange(Accuracy, n):
return Accuracy + 1.96 * math.sqrt((Accuracy * (1 - Accuracy) / n))
def LowerAccRange(Accuracy, n):
return Accuracy - 1.96 * math.sqrt((Accuracy * (1 - Accuracy) / n))
def ConfusionMatrix(y, yPredicted):
print(" Predicted Negative | Predicted Positive")
print("Actual Negative | TN: " + str(TNCount(y, yPredicted)) + " | FP: " + str(FPCount(y, yPredicted)))
print("Actual Positive | FN: " + str(FNCount(y, yPredicted)) + " | TP: " + str(TPCount(y, yPredicted)))
def ExecuteAll(y, yPredicted):
accuracyVal = Accuracy(y, yPredicted)
print(ConfusionMatrix(y, yPredicted))
print("Accuracy:", accuracyVal)
print("Precision:", Precision(y, yPredicted))
print("Recall:", Recall(y, yPredicted))
print("FPR:", FalsePositiveRate(y, yPredicted))
print("FNR:", FalseNegativeRate(y, yPredicted))
print("95% confidence range:", LowerAccRange(accuracyVal, len(y)), "to", UpperAccRange(accuracyVal, len(y)) )
| 30.781022
| 174
| 0.641688
|
import math
import collections
import numpy as np
def __CheckEvaluationInput(y, yPredicted):
if(len(y) != len(yPredicted)):
raise UserWarning("Attempting to evaluate between the true labels and predictions.\n Arrays contained different numbers of samples. Check your work and try again.")
valueError = False
for value in y:
if value not in [0, 1]:
valueError = True
for value in yPredicted:
if value not in [0, 1]:
valueError = True
if valueError:
raise UserWarning("Attempting to evaluate between the true labels and predictions.\n Arrays contained unexpected value. Must be 0 or 1.")
def __CheckEvaluationCount(y, yPredicted):
if(len(y) != len(yPredicted)):
raise UserWarning("Attempting to evaluate between the true labels and predictions.\n Arrays contained different numbers of samples. Check your work and try again.")
def Accuracy(y, yPredicted):
__CheckEvaluationInput(y, yPredicted)
correct = []
for i in range(len(y)):
if(y[i] == yPredicted[i]):
correct.append(1)
else:
correct.append(0)
return sum(correct)/len(correct)
def CountCorrect(y, yPredicted):
__CheckEvaluationInput(y, yPredicted)
correct = []
for i in range(len(y)):
if(y[i] == yPredicted[i]):
correct.append(1)
else:
correct.append(0)
return sum(correct)
def PredictionDiff(xTestRaw, y, yPredicted):
__CheckEvaluationCount(y, yPredicted)
__CheckEvaluationCount(xTestRaw, y)
predictionRange = {}
for i in range(len(y)):
predictionRange[xTestRaw[i]] = y[i] - yPredicted[i]
return predictionRange
def Precision(y, yPredicted):
numerator = TPCount(y, yPredicted)
denominator = (numerator + FPCount(y, yPredicted))
return 0.0 if denominator == 0 else numerator / denominator
def Recall(y, yPredicted):
numerator = TPCount(y, yPredicted)
denominator = (numerator + FNCount(y, yPredicted))
return 0.0 if denominator == 0 else numerator / denominator
def FalseNegativeRate(y, yPredicted):
numerator = FNCount(y, yPredicted)
denominator = numerator + TPCount(y, yPredicted)
return 0.0 if denominator == 0 else numerator / denominator
def FalsePositiveRate(y, yPredicted):
numerator = FPCount(y, yPredicted)
denominator = numerator + TNCount(y, yPredicted)
return 0.0 if denominator == 0 else numerator / denominator
def FNCount(y, yPredicted):
counter = 0
for i in range(len(y)):
if(y[i] == 1 and yPredicted[i] == 0):
counter += 1
return counter
def FPCount(y, yPredicted):
counter = 0
for i in range(len(y)):
if(y[i] == 0 and yPredicted[i] == 1):
counter += 1
return counter
def TNCount(y, yPredicted):
counter = 0
for i in range(len(y)):
if(y[i] == 0 and yPredicted[i] == 0):
counter += 1
return counter
def TPCount(y, yPredicted):
counter = 0
for i in range(len(y)):
if(y[i] == 1 and yPredicted[i] == 1):
counter += 1
return counter
def UpperAccRange(Accuracy, n):
return Accuracy + 1.96 * math.sqrt((Accuracy * (1 - Accuracy) / n))
def LowerAccRange(Accuracy, n):
return Accuracy - 1.96 * math.sqrt((Accuracy * (1 - Accuracy) / n))
def ConfusionMatrix(y, yPredicted):
print(" Predicted Negative | Predicted Positive")
print("Actual Negative | TN: " + str(TNCount(y, yPredicted)) + " | FP: " + str(FPCount(y, yPredicted)))
print("Actual Positive | FN: " + str(FNCount(y, yPredicted)) + " | TP: " + str(TPCount(y, yPredicted)))
def ExecuteAll(y, yPredicted):
accuracyVal = Accuracy(y, yPredicted)
print(ConfusionMatrix(y, yPredicted))
print("Accuracy:", accuracyVal)
print("Precision:", Precision(y, yPredicted))
print("Recall:", Recall(y, yPredicted))
print("FPR:", FalsePositiveRate(y, yPredicted))
print("FNR:", FalseNegativeRate(y, yPredicted))
print("95% confidence range:", LowerAccRange(accuracyVal, len(y)), "to", UpperAccRange(accuracyVal, len(y)) )
| true
| true
|
790e3b9c411165a5658a226e6f906ced62de333a
| 7,739
|
py
|
Python
|
plugins/cosigner_pool/qt.py
|
SirSevenG/electrum-komodo
|
a38d01baf216aad9429ac8f3707a12818c30a4a2
|
[
"MIT"
] | 4
|
2019-06-21T10:22:07.000Z
|
2020-01-03T16:02:48.000Z
|
plugins/cosigner_pool/qt.py
|
SirSevenG/electrum-komodo
|
a38d01baf216aad9429ac8f3707a12818c30a4a2
|
[
"MIT"
] | 28
|
2019-07-24T12:37:44.000Z
|
2020-10-12T11:21:28.000Z
|
plugins/cosigner_pool/qt.py
|
SirSevenG/electrum-komodo
|
a38d01baf216aad9429ac8f3707a12818c30a4a2
|
[
"MIT"
] | 9
|
2019-09-13T08:04:44.000Z
|
2020-09-17T01:19:23.000Z
|
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2014 Thomas Voegtlin
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import time
from xmlrpc.client import ServerProxy
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QPushButton
from electrum_zcash import bitcoin, util
from electrum_zcash import transaction
from electrum_zcash.plugins import BasePlugin, hook
from electrum_zcash.i18n import _
from electrum_zcash.wallet import Multisig_Wallet
from electrum_zcash.util import bh2u, bfh
from electrum_zcash_gui.qt.transaction_dialog import show_transaction
import sys
import traceback
server = ServerProxy('https://cosigner.electrum.org/', allow_none=True)
class Listener(util.DaemonThread):
def __init__(self, parent):
util.DaemonThread.__init__(self)
self.daemon = True
self.parent = parent
self.received = set()
self.keyhashes = []
def set_keyhashes(self, keyhashes):
self.keyhashes = keyhashes
def clear(self, keyhash):
server.delete(keyhash)
self.received.remove(keyhash)
def run(self):
while self.running:
if not self.keyhashes:
time.sleep(2)
continue
for keyhash in self.keyhashes:
if keyhash in self.received:
continue
try:
message = server.get(keyhash)
except Exception as e:
self.print_error("cannot contact cosigner pool")
time.sleep(30)
continue
if message:
self.received.add(keyhash)
self.print_error("received message for", keyhash)
self.parent.obj.cosigner_receive_signal.emit(
keyhash, message)
# poll every 30 seconds
time.sleep(30)
class QReceiveSignalObject(QObject):
cosigner_receive_signal = pyqtSignal(object, object)
class Plugin(BasePlugin):
def __init__(self, parent, config, name):
BasePlugin.__init__(self, parent, config, name)
self.listener = None
self.obj = QReceiveSignalObject()
self.obj.cosigner_receive_signal.connect(self.on_receive)
self.keys = []
self.cosigner_list = []
@hook
def init_qt(self, gui):
for window in gui.windows:
self.on_new_window(window)
@hook
def on_new_window(self, window):
self.update(window)
@hook
def on_close_window(self, window):
self.update(window)
def is_available(self):
return True
def update(self, window):
wallet = window.wallet
if type(wallet) != Multisig_Wallet:
return
if self.listener is None:
self.print_error("starting listener")
self.listener = Listener(self)
self.listener.start()
elif self.listener:
self.print_error("shutting down listener")
self.listener.stop()
self.listener = None
self.keys = []
self.cosigner_list = []
for key, keystore in wallet.keystores.items():
xpub = keystore.get_master_public_key()
K = bitcoin.deserialize_xpub(xpub)[-1]
_hash = bh2u(bitcoin.Hash(K))
if not keystore.is_watching_only():
self.keys.append((key, _hash, window))
else:
self.cosigner_list.append((window, xpub, K, _hash))
if self.listener:
self.listener.set_keyhashes([t[1] for t in self.keys])
@hook
def transaction_dialog(self, d):
d.cosigner_send_button = b = QPushButton(_("Send to cosigner"))
b.clicked.connect(lambda: self.do_send(d.tx))
d.buttons.insert(0, b)
self.transaction_dialog_update(d)
@hook
def transaction_dialog_update(self, d):
if d.tx.is_complete() or d.wallet.can_sign(d.tx):
d.cosigner_send_button.hide()
return
for window, xpub, K, _hash in self.cosigner_list:
if window.wallet == d.wallet and self.cosigner_can_sign(d.tx, xpub):
d.cosigner_send_button.show()
break
else:
d.cosigner_send_button.hide()
def cosigner_can_sign(self, tx, cosigner_xpub):
from electrum_zcash.keystore import is_xpubkey, parse_xpubkey
xpub_set = set([])
for txin in tx.inputs():
for x_pubkey in txin['x_pubkeys']:
if is_xpubkey(x_pubkey):
xpub, s = parse_xpubkey(x_pubkey)
xpub_set.add(xpub)
return cosigner_xpub in xpub_set
def do_send(self, tx):
for window, xpub, K, _hash in self.cosigner_list:
if not self.cosigner_can_sign(tx, xpub):
continue
raw_tx_bytes = bfh(str(tx))
message = bitcoin.encrypt_message(raw_tx_bytes, bh2u(K)).decode('ascii')
try:
server.put(_hash, message)
except Exception as e:
traceback.print_exc(file=sys.stdout)
window.show_message("Failed to send transaction to cosigning pool.")
return
window.show_message("Your transaction was sent to the cosigning pool.\nOpen your cosigner wallet to retrieve it.")
def on_receive(self, keyhash, message):
self.print_error("signal arrived for", keyhash)
for key, _hash, window in self.keys:
if _hash == keyhash:
break
else:
self.print_error("keyhash not found")
return
wallet = window.wallet
if wallet.has_keystore_encryption():
password = window.password_dialog('An encrypted transaction was retrieved from cosigning pool.\nPlease enter your password to decrypt it.')
if not password:
return
else:
password = None
if not window.question(_("An encrypted transaction was retrieved from cosigning pool.\nDo you want to open it now?")):
return
xprv = wallet.keystore.get_master_private_key(password)
if not xprv:
return
try:
k = bh2u(bitcoin.deserialize_xprv(xprv)[-1])
EC = bitcoin.EC_KEY(bfh(k))
message = bh2u(EC.decrypt_message(message))
except Exception as e:
traceback.print_exc(file=sys.stdout)
window.show_message(str(e))
return
self.listener.clear(keyhash)
tx = transaction.Transaction(message)
show_transaction(tx, window, prompt_if_unsaved=True)
| 35.177273
| 151
| 0.628117
|
import time
from xmlrpc.client import ServerProxy
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QPushButton
from electrum_zcash import bitcoin, util
from electrum_zcash import transaction
from electrum_zcash.plugins import BasePlugin, hook
from electrum_zcash.i18n import _
from electrum_zcash.wallet import Multisig_Wallet
from electrum_zcash.util import bh2u, bfh
from electrum_zcash_gui.qt.transaction_dialog import show_transaction
import sys
import traceback
server = ServerProxy('https://cosigner.electrum.org/', allow_none=True)
class Listener(util.DaemonThread):
def __init__(self, parent):
util.DaemonThread.__init__(self)
self.daemon = True
self.parent = parent
self.received = set()
self.keyhashes = []
def set_keyhashes(self, keyhashes):
self.keyhashes = keyhashes
def clear(self, keyhash):
server.delete(keyhash)
self.received.remove(keyhash)
def run(self):
while self.running:
if not self.keyhashes:
time.sleep(2)
continue
for keyhash in self.keyhashes:
if keyhash in self.received:
continue
try:
message = server.get(keyhash)
except Exception as e:
self.print_error("cannot contact cosigner pool")
time.sleep(30)
continue
if message:
self.received.add(keyhash)
self.print_error("received message for", keyhash)
self.parent.obj.cosigner_receive_signal.emit(
keyhash, message)
time.sleep(30)
class QReceiveSignalObject(QObject):
cosigner_receive_signal = pyqtSignal(object, object)
class Plugin(BasePlugin):
def __init__(self, parent, config, name):
BasePlugin.__init__(self, parent, config, name)
self.listener = None
self.obj = QReceiveSignalObject()
self.obj.cosigner_receive_signal.connect(self.on_receive)
self.keys = []
self.cosigner_list = []
@hook
def init_qt(self, gui):
for window in gui.windows:
self.on_new_window(window)
@hook
def on_new_window(self, window):
self.update(window)
@hook
def on_close_window(self, window):
self.update(window)
def is_available(self):
return True
def update(self, window):
wallet = window.wallet
if type(wallet) != Multisig_Wallet:
return
if self.listener is None:
self.print_error("starting listener")
self.listener = Listener(self)
self.listener.start()
elif self.listener:
self.print_error("shutting down listener")
self.listener.stop()
self.listener = None
self.keys = []
self.cosigner_list = []
for key, keystore in wallet.keystores.items():
xpub = keystore.get_master_public_key()
K = bitcoin.deserialize_xpub(xpub)[-1]
_hash = bh2u(bitcoin.Hash(K))
if not keystore.is_watching_only():
self.keys.append((key, _hash, window))
else:
self.cosigner_list.append((window, xpub, K, _hash))
if self.listener:
self.listener.set_keyhashes([t[1] for t in self.keys])
@hook
def transaction_dialog(self, d):
d.cosigner_send_button = b = QPushButton(_("Send to cosigner"))
b.clicked.connect(lambda: self.do_send(d.tx))
d.buttons.insert(0, b)
self.transaction_dialog_update(d)
@hook
def transaction_dialog_update(self, d):
if d.tx.is_complete() or d.wallet.can_sign(d.tx):
d.cosigner_send_button.hide()
return
for window, xpub, K, _hash in self.cosigner_list:
if window.wallet == d.wallet and self.cosigner_can_sign(d.tx, xpub):
d.cosigner_send_button.show()
break
else:
d.cosigner_send_button.hide()
def cosigner_can_sign(self, tx, cosigner_xpub):
from electrum_zcash.keystore import is_xpubkey, parse_xpubkey
xpub_set = set([])
for txin in tx.inputs():
for x_pubkey in txin['x_pubkeys']:
if is_xpubkey(x_pubkey):
xpub, s = parse_xpubkey(x_pubkey)
xpub_set.add(xpub)
return cosigner_xpub in xpub_set
def do_send(self, tx):
for window, xpub, K, _hash in self.cosigner_list:
if not self.cosigner_can_sign(tx, xpub):
continue
raw_tx_bytes = bfh(str(tx))
message = bitcoin.encrypt_message(raw_tx_bytes, bh2u(K)).decode('ascii')
try:
server.put(_hash, message)
except Exception as e:
traceback.print_exc(file=sys.stdout)
window.show_message("Failed to send transaction to cosigning pool.")
return
window.show_message("Your transaction was sent to the cosigning pool.\nOpen your cosigner wallet to retrieve it.")
def on_receive(self, keyhash, message):
self.print_error("signal arrived for", keyhash)
for key, _hash, window in self.keys:
if _hash == keyhash:
break
else:
self.print_error("keyhash not found")
return
wallet = window.wallet
if wallet.has_keystore_encryption():
password = window.password_dialog('An encrypted transaction was retrieved from cosigning pool.\nPlease enter your password to decrypt it.')
if not password:
return
else:
password = None
if not window.question(_("An encrypted transaction was retrieved from cosigning pool.\nDo you want to open it now?")):
return
xprv = wallet.keystore.get_master_private_key(password)
if not xprv:
return
try:
k = bh2u(bitcoin.deserialize_xprv(xprv)[-1])
EC = bitcoin.EC_KEY(bfh(k))
message = bh2u(EC.decrypt_message(message))
except Exception as e:
traceback.print_exc(file=sys.stdout)
window.show_message(str(e))
return
self.listener.clear(keyhash)
tx = transaction.Transaction(message)
show_transaction(tx, window, prompt_if_unsaved=True)
| true
| true
|
790e3bdf8b4dc471ace490a7934054d0cd52e6bb
| 376
|
py
|
Python
|
Desafios/Desafio 040.py
|
tiagosm1/Pyhton_CEV
|
67bae36169922fe2168505393cc47b1bab50c39b
|
[
"MIT"
] | null | null | null |
Desafios/Desafio 040.py
|
tiagosm1/Pyhton_CEV
|
67bae36169922fe2168505393cc47b1bab50c39b
|
[
"MIT"
] | null | null | null |
Desafios/Desafio 040.py
|
tiagosm1/Pyhton_CEV
|
67bae36169922fe2168505393cc47b1bab50c39b
|
[
"MIT"
] | null | null | null |
n1 = float(input('Digite sua primera nota: '))
n2 = float(input('Digite sua segunda nota: '))
media = (n1 + n2) / 2
if media <= 5:
print('Sua média é {} e você está REPROVADO!'.format(media))
elif media >= 7:
print('Sua média é {} e você está APROVADO!'.format(media))
elif media >5 or media <6.9:
print('Sua média é {} e você está de RECUPERAÇÃO '.format(media))
| 37.6
| 69
| 0.646277
|
n1 = float(input('Digite sua primera nota: '))
n2 = float(input('Digite sua segunda nota: '))
media = (n1 + n2) / 2
if media <= 5:
print('Sua média é {} e você está REPROVADO!'.format(media))
elif media >= 7:
print('Sua média é {} e você está APROVADO!'.format(media))
elif media >5 or media <6.9:
print('Sua média é {} e você está de RECUPERAÇÃO '.format(media))
| true
| true
|
790e3c6c1d1a3772687a9a748e4a4bba53b42c2c
| 3,039
|
py
|
Python
|
tests/test_mgear/test_core/test_vector.py
|
tk-aria/mgear4
|
eac1af6882dd7dc4cec1a4b71854040d376704ce
|
[
"MIT"
] | 72
|
2020-09-28T20:00:59.000Z
|
2022-03-25T14:35:14.000Z
|
tests/test_mgear/test_core/test_vector.py
|
Mikfr83/mgear4
|
2fa28080027f1004e8e0139ccf93f7ec2448b1fd
|
[
"MIT"
] | 101
|
2020-09-28T19:53:53.000Z
|
2022-03-31T01:44:41.000Z
|
tests/test_mgear/test_core/test_vector.py
|
Mikfr83/mgear4
|
2fa28080027f1004e8e0139ccf93f7ec2448b1fd
|
[
"MIT"
] | 32
|
2020-10-09T10:49:45.000Z
|
2022-03-31T08:27:37.000Z
|
"""mgear.core.vector test"""
def test_get_distance(run_with_maya_pymel, setup_path):
# Maya imports
from maya import OpenMaya
import pymel.core as pm
# mGear imports
from mgear.core.vector import get_distance
v_1 = [0, 0, 0]
v_2 = [1, 0, 0]
assert get_distance(v_1, v_2) == 1.0
v_1 = OpenMaya.MVector(0, 0, 0)
v_2 = OpenMaya.MVector(1, 0, 0)
assert get_distance(v_1, v_2) == 1.0
pm.newFile(force=True)
v_1 = pm.createNode("transform")
v_2 = pm.createNode("transform")
v_2.translate.set(10, 5, 7)
distance = pm.createNode("distanceBetween")
v_1.worldMatrix >> distance.inMatrix1
v_2.worldMatrix >> distance.inMatrix2
distance_value = distance.distance.get()
assert get_distance(v_1, v_2) == distance_value
def test_get_plane_binormal(run_with_maya_pymel, setup_path):
# Maya imports
from maya import OpenMaya
# mGear imports
from mgear.core.vector import get_plane_binormal
vector_a = OpenMaya.MVector(0, 0, 0)
vector_b = OpenMaya.MVector(-1, 0, 0)
vector_c = OpenMaya.MVector(0, 0, 1)
result = get_plane_binormal(vector_a, vector_b, vector_c)
assert type(result) == OpenMaya.MVector
assert [result[0], result[1], result[2]] == [0, 0, -1]
def test_get_plane_normal(run_with_maya_pymel, setup_path):
# Maya imports
from maya import OpenMaya
import pymel.core as pm
# mGear imports
from mgear.core.vector import get_plane_normal
vector_a = OpenMaya.MVector(0, 0, 0)
vector_b = OpenMaya.MVector(1, 0, 0)
vector_c = OpenMaya.MVector(0, 0, 1)
result = get_plane_normal(vector_a, vector_b, vector_c)
assert type(result) == OpenMaya.MVector
assert [result[0], result[1], result[2]] == [0, 1, 0]
pm.newFile(force=True)
vector_a = pm.createNode("transform")
vector_b = pm.createNode("transform")
vector_c = pm.createNode("transform")
vector_b.translate.set(-1, 0, 0)
vector_c.translate.set(0, 0, 1)
result = get_plane_normal(vector_a, vector_b, vector_c)
assert [result[0], result[1], result[2]] == [0, -1, 0]
result = get_plane_normal(list(vector_a.getTranslation()),
list(vector_b.getTranslation()),
list(vector_c.getTranslation()))
assert [result[0], result[1], result[2]] == [0, -1, 0]
def test_linear_interpolate(run_with_maya_pymel, setup_path):
# Maya imports
from maya import OpenMaya
import pymel.core as pm
# mGear imports
from mgear.core.vector import linear_interpolate
_value = [2, 5, 8]
v_1 = [0, 0, 0]
v_2 = _value
result = linear_interpolate(v_1, v_2)
assert type(result) == OpenMaya.MVector
assert [result[0], result[1], result[2]] == [1, 2.5, 4]
pm.newFile(force=True)
v_1 = pm.createNode("transform")
v_2 = pm.createNode("transform")
v_2.translate.set(_value[0], _value[1], _value[2])
result = linear_interpolate(v_1, v_2)
assert [result[0], result[1], result[2]] == [1, 2.5, 4]
| 31.989474
| 62
| 0.657782
|
def test_get_distance(run_with_maya_pymel, setup_path):
from maya import OpenMaya
import pymel.core as pm
from mgear.core.vector import get_distance
v_1 = [0, 0, 0]
v_2 = [1, 0, 0]
assert get_distance(v_1, v_2) == 1.0
v_1 = OpenMaya.MVector(0, 0, 0)
v_2 = OpenMaya.MVector(1, 0, 0)
assert get_distance(v_1, v_2) == 1.0
pm.newFile(force=True)
v_1 = pm.createNode("transform")
v_2 = pm.createNode("transform")
v_2.translate.set(10, 5, 7)
distance = pm.createNode("distanceBetween")
v_1.worldMatrix >> distance.inMatrix1
v_2.worldMatrix >> distance.inMatrix2
distance_value = distance.distance.get()
assert get_distance(v_1, v_2) == distance_value
def test_get_plane_binormal(run_with_maya_pymel, setup_path):
from maya import OpenMaya
from mgear.core.vector import get_plane_binormal
vector_a = OpenMaya.MVector(0, 0, 0)
vector_b = OpenMaya.MVector(-1, 0, 0)
vector_c = OpenMaya.MVector(0, 0, 1)
result = get_plane_binormal(vector_a, vector_b, vector_c)
assert type(result) == OpenMaya.MVector
assert [result[0], result[1], result[2]] == [0, 0, -1]
def test_get_plane_normal(run_with_maya_pymel, setup_path):
from maya import OpenMaya
import pymel.core as pm
from mgear.core.vector import get_plane_normal
vector_a = OpenMaya.MVector(0, 0, 0)
vector_b = OpenMaya.MVector(1, 0, 0)
vector_c = OpenMaya.MVector(0, 0, 1)
result = get_plane_normal(vector_a, vector_b, vector_c)
assert type(result) == OpenMaya.MVector
assert [result[0], result[1], result[2]] == [0, 1, 0]
pm.newFile(force=True)
vector_a = pm.createNode("transform")
vector_b = pm.createNode("transform")
vector_c = pm.createNode("transform")
vector_b.translate.set(-1, 0, 0)
vector_c.translate.set(0, 0, 1)
result = get_plane_normal(vector_a, vector_b, vector_c)
assert [result[0], result[1], result[2]] == [0, -1, 0]
result = get_plane_normal(list(vector_a.getTranslation()),
list(vector_b.getTranslation()),
list(vector_c.getTranslation()))
assert [result[0], result[1], result[2]] == [0, -1, 0]
def test_linear_interpolate(run_with_maya_pymel, setup_path):
from maya import OpenMaya
import pymel.core as pm
from mgear.core.vector import linear_interpolate
_value = [2, 5, 8]
v_1 = [0, 0, 0]
v_2 = _value
result = linear_interpolate(v_1, v_2)
assert type(result) == OpenMaya.MVector
assert [result[0], result[1], result[2]] == [1, 2.5, 4]
pm.newFile(force=True)
v_1 = pm.createNode("transform")
v_2 = pm.createNode("transform")
v_2.translate.set(_value[0], _value[1], _value[2])
result = linear_interpolate(v_1, v_2)
assert [result[0], result[1], result[2]] == [1, 2.5, 4]
| true
| true
|
790e3cc3c709b664fbdc0505d1a9e2e7cbc004fb
| 5,677
|
py
|
Python
|
TextSummarization/TF_IDF.py
|
hazim111/Data-Science-Meetup-Oxford
|
8b7ab85f30cdefe9f4f75c66e935efc422100742
|
[
"Apache-2.0"
] | 60
|
2020-02-27T11:00:10.000Z
|
2022-03-29T19:26:17.000Z
|
TextSummarization/TF_IDF.py
|
hazim111/Data-Science-Meetup-Oxford
|
8b7ab85f30cdefe9f4f75c66e935efc422100742
|
[
"Apache-2.0"
] | 8
|
2021-01-26T16:53:04.000Z
|
2022-02-17T21:04:33.000Z
|
TextSummarization/TF_IDF.py
|
hazim111/Data-Science-Meetup-Oxford
|
8b7ab85f30cdefe9f4f75c66e935efc422100742
|
[
"Apache-2.0"
] | 19
|
2020-03-09T11:43:39.000Z
|
2022-02-09T17:47:04.000Z
|
import math
import pandas as pd
import spacy # Requires: python -m spacy download en_core_web_sm
from spacy import displacy
from nltk import sent_tokenize, word_tokenize, PorterStemmer
from nltk.corpus import stopwords
from data import load_model
import streamlit as st
class tf_idf():
nlp = load_model('en_core_web_md')
def word_freq(self, text) -> dict:
"""
Create document word frequency table {w1:f1, ..., wN:fN}.
Remove stop words, punct, etc. and lowercase
:rtype: dict
"""
doc = self.nlp(text)
word_freq_table = {}
for token in doc:
ignore = token.is_stop or token.is_punct or token.is_quote or token.is_oov or token.text in ['.',',',';',':','%','-']
if not ignore and token.text in word_freq_table:
word_freq_table[token.lower_] += 1
elif not ignore:
word_freq_table[token.lower_] = 1
return word_freq_table
def sent_word_freq(self, text) -> dict:
"""
Create sentence word frequency table {s1:{w1:f1, ..., wN:fN}, ..., sN:{w1:f1, ..., wN:fN} }.
:rtype: dict
"""
doc = self.nlp(text)
sent_word_freq_table = {}
for sent in doc.sents:
word_freq_table = self.word_freq(sent.lower_)
sent_word_freq_table[sent.lower_[:15]] = word_freq_table
return sent_word_freq_table
def tf_matrix(self, sent_word_freq_table) -> dict:
tf_matrix = {}
for sent, word_freq_table in sent_word_freq_table.items():
tf_table = {}
sent_word_count = len(word_freq_table)
for word, freq in word_freq_table.items():
tf_table[word] = freq / sent_word_count
tf_matrix[sent] = tf_table
return tf_matrix
def global_word_freq(self, tf_matrix) -> dict:
tf_global_matrix = {}
for sent, f_table in tf_matrix.items():
for word, count in f_table.items():
if word in tf_global_matrix:
tf_global_matrix[word] += count
else:
tf_global_matrix[word] = count
return tf_global_matrix
def idf(self, tf_matrix, tf_global_matrix) -> dict:
total_documents = len(tf_matrix)
idf_matrix = {}
for sent, f_table in tf_matrix.items():
idf_table = {}
for word in f_table.keys():
idf_table[word] = math.log10(total_documents / float(tf_global_matrix[word]))
idf_matrix[sent] = idf_table
return idf_matrix
def tf_idf(self, tf_matrix, idf_matrix) -> dict:
tf_idf_matrix = {}
for (sent1, f_table1), (sent2, f_table2) in zip(tf_matrix.items(), idf_matrix.items()):
tf_idf_table = {}
for (word1, value1), (word2, value2) in zip(f_table1.items(),f_table2.items()): # here, keys are the same in both the table
tf_idf_table[word1] = float(value1 * value2)
tf_idf_matrix[sent1] = tf_idf_table
return tf_idf_matrix
def score_sentences(self, tf_idf_matrix) -> dict:
# Score sentences by their word TFs
# Algorithm: adds word TFs and divides by total no of words in sentence. Normalise scale in range [0..10]
sentenceScores = {}
for sent, f_table in tf_idf_matrix.items():
sent_word_count = len(f_table)
scores = [score for _word, score in f_table.items()]
if len(scores) > 0:
maxScore = max(scores)
normScores = [score/maxScore for score in scores]
total_sent_score = sum(normScores)
sentenceScores[sent] = total_sent_score / sent_word_count
else:
sentenceScores[sent] = 0.0
return sentenceScores
def average_score(self, sentenceScores) -> int:
sumScores = sum([sentenceScores[entry] for entry in sentenceScores])
# Average score of a sentence from original summary_text
average = sumScores / len(sentenceScores)
return average
def generate_summary(self, sents, sentenceScores, threshold) -> str:
summary = ' '.join([
sent.text.strip() for sent in sents
if ((sent.lower_[:15] in sentenceScores) and (sentenceScores[sent.lower_[:15]] <= (threshold)))
])
return summary
def summarize(self, text, threshold: float) -> str:
doc = self.nlp(text)
sents = doc.sents
'''
Term frequency (TF) is how often a word appears in the document, divided by how many words there are in the document.
'''
# 1 Calculate the term frequency matrix, by sentence
tf_matrix = self.sent_word_freq(text)
#st.write(pd.DataFrame(tf_matrix))
# 2 Calculate the term frequency matrix, global (all sentences)
tf_global_matrix = self.global_word_freq(tf_matrix)
#st.write(pd.DataFrame({'tf_global_matrix':tf_global_matrix}))
'''
Inverse document frequency (IDF) is how unique or rare a word is.
'''
# 3 Calculate IDF
idf_matrix = self.idf(tf_matrix, tf_global_matrix)
#st.write(pd.DataFrame(idf_matrix))
# 4 Calculate TF-IDF
tf_idf_matrix = self.tf_idf(tf_matrix, idf_matrix)
#st.write(pd.DataFrame(tf_idf_matrix))
# 5 Score sentences
sentence_scores = self.score_sentences(tf_idf_matrix)
#st.write(pd.DataFrame({'sentence_scores':sentence_scores}))
# 6 Generate summary
summary = self.generate_summary(sents, sentence_scores, threshold)
return summary
| 35.704403
| 136
| 0.611414
|
import math
import pandas as pd
import spacy
from spacy import displacy
from nltk import sent_tokenize, word_tokenize, PorterStemmer
from nltk.corpus import stopwords
from data import load_model
import streamlit as st
class tf_idf():
nlp = load_model('en_core_web_md')
def word_freq(self, text) -> dict:
doc = self.nlp(text)
word_freq_table = {}
for token in doc:
ignore = token.is_stop or token.is_punct or token.is_quote or token.is_oov or token.text in ['.',',',';',':','%','-']
if not ignore and token.text in word_freq_table:
word_freq_table[token.lower_] += 1
elif not ignore:
word_freq_table[token.lower_] = 1
return word_freq_table
def sent_word_freq(self, text) -> dict:
doc = self.nlp(text)
sent_word_freq_table = {}
for sent in doc.sents:
word_freq_table = self.word_freq(sent.lower_)
sent_word_freq_table[sent.lower_[:15]] = word_freq_table
return sent_word_freq_table
def tf_matrix(self, sent_word_freq_table) -> dict:
tf_matrix = {}
for sent, word_freq_table in sent_word_freq_table.items():
tf_table = {}
sent_word_count = len(word_freq_table)
for word, freq in word_freq_table.items():
tf_table[word] = freq / sent_word_count
tf_matrix[sent] = tf_table
return tf_matrix
def global_word_freq(self, tf_matrix) -> dict:
tf_global_matrix = {}
for sent, f_table in tf_matrix.items():
for word, count in f_table.items():
if word in tf_global_matrix:
tf_global_matrix[word] += count
else:
tf_global_matrix[word] = count
return tf_global_matrix
def idf(self, tf_matrix, tf_global_matrix) -> dict:
total_documents = len(tf_matrix)
idf_matrix = {}
for sent, f_table in tf_matrix.items():
idf_table = {}
for word in f_table.keys():
idf_table[word] = math.log10(total_documents / float(tf_global_matrix[word]))
idf_matrix[sent] = idf_table
return idf_matrix
def tf_idf(self, tf_matrix, idf_matrix) -> dict:
tf_idf_matrix = {}
for (sent1, f_table1), (sent2, f_table2) in zip(tf_matrix.items(), idf_matrix.items()):
tf_idf_table = {}
for (word1, value1), (word2, value2) in zip(f_table1.items(),f_table2.items()):
tf_idf_table[word1] = float(value1 * value2)
tf_idf_matrix[sent1] = tf_idf_table
return tf_idf_matrix
def score_sentences(self, tf_idf_matrix) -> dict:
sentenceScores = {}
for sent, f_table in tf_idf_matrix.items():
sent_word_count = len(f_table)
scores = [score for _word, score in f_table.items()]
if len(scores) > 0:
maxScore = max(scores)
normScores = [score/maxScore for score in scores]
total_sent_score = sum(normScores)
sentenceScores[sent] = total_sent_score / sent_word_count
else:
sentenceScores[sent] = 0.0
return sentenceScores
def average_score(self, sentenceScores) -> int:
sumScores = sum([sentenceScores[entry] for entry in sentenceScores])
average = sumScores / len(sentenceScores)
return average
def generate_summary(self, sents, sentenceScores, threshold) -> str:
summary = ' '.join([
sent.text.strip() for sent in sents
if ((sent.lower_[:15] in sentenceScores) and (sentenceScores[sent.lower_[:15]] <= (threshold)))
])
return summary
def summarize(self, text, threshold: float) -> str:
doc = self.nlp(text)
sents = doc.sents
tf_matrix = self.sent_word_freq(text)
tf_global_matrix = self.global_word_freq(tf_matrix)
idf_matrix = self.idf(tf_matrix, tf_global_matrix)
tf_idf_matrix = self.tf_idf(tf_matrix, idf_matrix)
sentence_scores = self.score_sentences(tf_idf_matrix)
summary = self.generate_summary(sents, sentence_scores, threshold)
return summary
| true
| true
|
790e3d01adaa9a953e524685db85d1ba218e9d78
| 277
|
py
|
Python
|
tests/test_import.py
|
MacHu-GWU/pytq_crawlib-project
|
ccb980574f698d481e8a8cb61e0888f4afef68df
|
[
"MIT"
] | null | null | null |
tests/test_import.py
|
MacHu-GWU/pytq_crawlib-project
|
ccb980574f698d481e8a8cb61e0888f4afef68df
|
[
"MIT"
] | 2
|
2018-01-31T19:32:03.000Z
|
2018-01-31T20:32:33.000Z
|
tests/test_import.py
|
MacHu-GWU/pytq_crawlib-project
|
ccb980574f698d481e8a8cb61e0888f4afef68df
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from pytest import raises, approx
def test():
import pytq_crawlib
pass
if __name__ == "__main__":
import os
basename = os.path.basename(__file__)
pytest.main([basename, "-s", "--tb=native"])
| 15.388889
| 48
| 0.638989
|
import pytest
from pytest import raises, approx
def test():
import pytq_crawlib
pass
if __name__ == "__main__":
import os
basename = os.path.basename(__file__)
pytest.main([basename, "-s", "--tb=native"])
| true
| true
|
790e3e536dd01d77260e85b0de8cfac011048480
| 8,702
|
py
|
Python
|
Outils/TRIOXDATA/XTriou/Extract_xdata.py
|
cea-trust-platform/trust-code
|
c4f42d8f8602a8cc5e0ead0e29dbf0be8ac52f72
|
[
"BSD-3-Clause"
] | 12
|
2021-06-30T18:50:38.000Z
|
2022-03-23T09:03:16.000Z
|
Outils/TRIOXDATA/XTriou/Extract_xdata.py
|
pledac/trust-code
|
46ab5c5da3f674185f53423090f526a38ecdbad1
|
[
"BSD-3-Clause"
] | null | null | null |
Outils/TRIOXDATA/XTriou/Extract_xdata.py
|
pledac/trust-code
|
46ab5c5da3f674185f53423090f526a38ecdbad1
|
[
"BSD-3-Clause"
] | 2
|
2021-10-04T09:19:39.000Z
|
2021-12-15T14:21:04.000Z
|
from optparse import OptionParser
import os,sys
import itertools
import re
def readSrc(src_dir):
lines=[]
for root, dirs, files in os.walk(src_dir):
for file in files:
if file.endswith(".cpp"):
lines+=["New_file "+ file]
lines_file = open(os.path.join(root, file)).read().splitlines()
lines+=lines_file
pass
pass
pass
return lines
def writeRunLog(dico, filename):
st=""
for clas in list(dico.keys()):
st+="class : "+clas+"\n"
st+="=======\n"
st+=" - Desc : "+dico[clas]["desc"]+"\n"
if (len(list(dico[clas]["parameters"].keys()))>0):
st+=" - Params : \n"
st+=" ********** \n"
pass
for param in list(dico[clas]["parameters"].keys()):
st+=" + Param : "+param+" ==> Desc : "+dico[clas]["parameters"][param]["desc"]+"\n"
st+=" -----\n"
if (len(list(dico[clas]["parameters"][param]["dict"].keys()))>0):
st+=" + Dicts : \n"
st+=" +++++ \n"
pass
for dic in list(dico[clas]["parameters"][param]["dict"].keys()):
st+=" Dict : "+dic+" ==> Desc : "+dico[clas]["parameters"][param]["dict"][dic]["desc"]+"\n"
st+=" ----\n"
pass
pass
pass
fi=open(filename, "w")
fi.write(st)
fi.close()
return
def getLinesWithRegExp(lines):
dico={}
for xd in ["XD","2XD","3XD"]:
debut=0
for line in lines:
# on rajoute un blanc pour avoir le dernier mot des commentaires
line+=" "
if ((len(line.strip())>=8) and (line.split()[0]=="New_file")):
debut=1
filename=line.split()[1]
# revoir les comm ne marchent pas pour mpcube
# elif (re.findall("//.*//[ ]*"+xd,line)):
# continue
elif (re.findall("//[ ]*"+xd+"[ ]+",line)):
# traitement des classes
li=re.findall(re.escape(xd)+"(.*)"+re.escape(' '),line)[0].split(' ')
li = [x for x in li if x.strip()]
desc=re.split("//[ ]*"+xd+"[ ]+",line)[-1]
if li[0]=="attr":
if (debut<2):
raise Exception("error in "+filename+" first line XD "+line)
# print dico[nameClass]
desc2=li[1:]
dico_p={"desc":' '.join(desc2)}
dico_p["dict"]={}
dico_p["numero"]=len(dico[nameClass]["parameters"])
dico[nameClass]['parameters'][li[1]]=dico_p
# print li
# print desc2
#1/0
elif li[0]=="ref":
if (debut<2):
raise Exception("error in "+filename+" first line XD "+line)
# print nameClass, line
dico[nameClass]["refs"].append([li[1],li[2]])
# 1/0
else:
nameClass=li[0]
dico[nameClass]={"desc":desc,"parameters":{},"refs":[]}
debut=2
pass
elif re.findall("//[ ]*"+xd+"_ADD_P+",line):
# traitement des parametres
if (debut<2):
raise Exception("error in "+filename+" first line XD "+line)
dico_param={}
optionnel=True
if (re.findall("Param::REQUIRED",line)):
optionnel=False
pass
print("line:",line)
param=line.split('"')[1].lower()
mparam=param.split("|")[0]
if mparam=="lambda":
mparam="lambda_u"
dico_param["mparm"]=mparam
dico_param["optionnel"]=optionnel
dr=line.split(xd+"_ADD_P")[-1].split()
desc=param+" "+dr[0]+" "+mparam+" "+str(int(optionnel))+" "+' '.join(dr[1:])
dico_param["desc"]=desc
dico_param["numero"]=len(dico[nameClass]["parameters"])
dico_param["dict"]={}
dico[nameClass]["parameters"][param]=dico_param
pass
elif re.findall("//[ ]*"+xd+"_ADD_DICO+",line):
# traitement des dictionnaires
if (debut<2):
raise 'jjjjjjjj'
dr=line.split(xd+"_ADD_P")[-1].split()
dico_dict={}
dico_dict["desc"]=line
dict_name=line.split('"')[1].lower()
dico[nameClass]["parameters"][param]["dict"][dict_name]=dico_dict
pass
pass
return dico
def writeOutPutFile(dico, filename,st_add=""):
st=""
for clas in list(dico.keys()):
st+=dico[clas]["desc"]+"\n"
Params=dico[clas]["parameters"]
for i in range(len(list(Params.keys()))):
ok=0
for j,param in enumerate(Params.keys()):
if (i==Params[param]["numero"]):
ok=1
break
if (ok==0):
print("pb",clas,"nmero",i,"params",Params)
1/0
if (len(list(Params[param]["dict"].keys()))==0):
st+=" attr "+Params[param]["desc"]+"\n"
pass
str_dico=" attr "+param+" chaine(into=["
for dic in list(Params[param]["dict"].keys()):
str_dico+='"'+dic+'",'
pass
if (len(list(Params[param]["dict"].keys()))>0):
desc=Params[param]["desc"].split()[2:]
st+=str_dico+"]) "+' '.join(desc)+"\n"
pass
pass
for ref in dico[clas]["refs"]:
st+=" ref "+ref[0]+" "+ref[1]+"\n"
pass
pass
st=st.replace(" double "," floattant ")
st=st.replace(" flag "," rien ")
st=st.replace(" int "," entier ")
st=st.replace(r"'",r"\'")
st=st.replace(r"\\'",r"\'")
#st="\\'".join(st.split("'"))
#st="\\'".join(st.split("\\\\'"))
fi=open(filename, "w")
fi.write(st_add)
fi.write(st)
fi.write("\n")
fi.close()
return
def run(result_dir, src_dir):
lines=readSrc(src_dir)
dico=getLinesWithRegExp(lines)
run_log=os.path.join(result_dir,"run.log")
writeRunLog(dico, run_log)
trad_org=os.path.join(result_dir,"TRAD_2.org")
fi=open(trad_org,"r")
st_org=fi.read()
fi.close()
st=st_org
trad_add=os.path.join(result_dir,"TRAD2_ajout0")
if (os.path.exists(trad_add)):
fi=open(trad_add,"r")
st+=fi.read()
fi.close()
trad_ajout=os.path.join(result_dir,"TRAD_2")
writeOutPutFile(dico,trad_ajout,st)
return
def options_script(argv):
parser = OptionParser(usage="usage: %prog [options]")
parser.add_option("-r", "--result", dest="result_dir", type="string",
metavar="<result_dir>",
help="choose results directory")
parser.add_option("-s", "--src", dest="src_dir", type="string",
metavar="<src_dir>",
help="choose src directory")
parser.set_defaults(result_dir=os.getcwd())
parser.set_defaults(src_dir=os.getcwd())
(options, args) = parser.parse_args(argv)
if len(args) > 0:
parser.print_help()
sys.exit(1)
pass
if options.result_dir != os.getcwd():
options.result_dir=os.path.join(os.getcwd(),options.result_dir)
if not os.path.isdir(options.result_dir):
os.mkdir(options.result_dir)
pass
pass
result_dir = os.path.expanduser(options.result_dir)
result_dir = os.path.expandvars(result_dir)
result_dir = os.path.abspath(result_dir)
if not os.path.isdir(result_dir):
sys.stderr.write('Error: result dir \"' + result_dir + '\" is not a directory\n')
sys.exit(1)
pass
src_dir = options.src_dir
if src_dir!=None:
os.path.expanduser(options.src_dir)
src_dir = os.path.expandvars(src_dir)
src_dir = os.path.abspath(src_dir)
if not os.path.isdir(src_dir):
sys.stderr.write('Error: source dir \"' + src_dir + '\" is not a directory\n')
sys.exit(1)
pass
pass
return result_dir, src_dir
def main(argv):
"""
Main function.
"""
result_dir, src_dir = options_script(argv)
run(result_dir, src_dir)
if __name__ == "__main__":
main(sys.argv[1:])
| 33.469231
| 119
| 0.478626
|
from optparse import OptionParser
import os,sys
import itertools
import re
def readSrc(src_dir):
lines=[]
for root, dirs, files in os.walk(src_dir):
for file in files:
if file.endswith(".cpp"):
lines+=["New_file "+ file]
lines_file = open(os.path.join(root, file)).read().splitlines()
lines+=lines_file
pass
pass
pass
return lines
def writeRunLog(dico, filename):
st=""
for clas in list(dico.keys()):
st+="class : "+clas+"\n"
st+="=======\n"
st+=" - Desc : "+dico[clas]["desc"]+"\n"
if (len(list(dico[clas]["parameters"].keys()))>0):
st+=" - Params : \n"
st+=" ********** \n"
pass
for param in list(dico[clas]["parameters"].keys()):
st+=" + Param : "+param+" ==> Desc : "+dico[clas]["parameters"][param]["desc"]+"\n"
st+=" -----\n"
if (len(list(dico[clas]["parameters"][param]["dict"].keys()))>0):
st+=" + Dicts : \n"
st+=" +++++ \n"
pass
for dic in list(dico[clas]["parameters"][param]["dict"].keys()):
st+=" Dict : "+dic+" ==> Desc : "+dico[clas]["parameters"][param]["dict"][dic]["desc"]+"\n"
st+=" ----\n"
pass
pass
pass
fi=open(filename, "w")
fi.write(st)
fi.close()
return
def getLinesWithRegExp(lines):
dico={}
for xd in ["XD","2XD","3XD"]:
debut=0
for line in lines:
line+=" "
if ((len(line.strip())>=8) and (line.split()[0]=="New_file")):
debut=1
filename=line.split()[1]
elif (re.findall("//[ ]*"+xd+"[ ]+",line)):
li=re.findall(re.escape(xd)+"(.*)"+re.escape(' '),line)[0].split(' ')
li = [x for x in li if x.strip()]
desc=re.split("//[ ]*"+xd+"[ ]+",line)[-1]
if li[0]=="attr":
if (debut<2):
raise Exception("error in "+filename+" first line XD "+line)
desc2=li[1:]
dico_p={"desc":' '.join(desc2)}
dico_p["dict"]={}
dico_p["numero"]=len(dico[nameClass]["parameters"])
dico[nameClass]['parameters'][li[1]]=dico_p
elif li[0]=="ref":
if (debut<2):
raise Exception("error in "+filename+" first line XD "+line)
dico[nameClass]["refs"].append([li[1],li[2]])
else:
nameClass=li[0]
dico[nameClass]={"desc":desc,"parameters":{},"refs":[]}
debut=2
pass
elif re.findall("//[ ]*"+xd+"_ADD_P+",line):
if (debut<2):
raise Exception("error in "+filename+" first line XD "+line)
dico_param={}
optionnel=True
if (re.findall("Param::REQUIRED",line)):
optionnel=False
pass
print("line:",line)
param=line.split('"')[1].lower()
mparam=param.split("|")[0]
if mparam=="lambda":
mparam="lambda_u"
dico_param["mparm"]=mparam
dico_param["optionnel"]=optionnel
dr=line.split(xd+"_ADD_P")[-1].split()
desc=param+" "+dr[0]+" "+mparam+" "+str(int(optionnel))+" "+' '.join(dr[1:])
dico_param["desc"]=desc
dico_param["numero"]=len(dico[nameClass]["parameters"])
dico_param["dict"]={}
dico[nameClass]["parameters"][param]=dico_param
pass
elif re.findall("//[ ]*"+xd+"_ADD_DICO+",line):
# traitement des dictionnaires
if (debut<2):
raise 'jjjjjjjj'
dr=line.split(xd+"_ADD_P")[-1].split()
dico_dict={}
dico_dict["desc"]=line
dict_name=line.split('"')[1].lower()
dico[nameClass]["parameters"][param]["dict"][dict_name]=dico_dict
pass
pass
return dico
def writeOutPutFile(dico, filename,st_add=""):
st=""
for clas in list(dico.keys()):
st+=dico[clas]["desc"]+"\n"
Params=dico[clas]["parameters"]
for i in range(len(list(Params.keys()))):
ok=0
for j,param in enumerate(Params.keys()):
if (i==Params[param]["numero"]):
ok=1
break
if (ok==0):
print("pb",clas,"nmero",i,"params",Params)
1/0
if (len(list(Params[param]["dict"].keys()))==0):
st+=" attr "+Params[param]["desc"]+"\n"
pass
str_dico=" attr "+param+" chaine(into=["
for dic in list(Params[param]["dict"].keys()):
str_dico+='"'+dic+'",'
pass
if (len(list(Params[param]["dict"].keys()))>0):
desc=Params[param]["desc"].split()[2:]
st+=str_dico+"]) "+' '.join(desc)+"\n"
pass
pass
for ref in dico[clas]["refs"]:
st+=" ref "+ref[0]+" "+ref[1]+"\n"
pass
pass
st=st.replace(" double "," floattant ")
st=st.replace(" flag "," rien ")
st=st.replace(" int "," entier ")
st=st.replace(r"'",r"\'")
st=st.replace(r"\\'",r"\'")
fi=open(filename, "w")
fi.write(st_add)
fi.write(st)
fi.write("\n")
fi.close()
return
def run(result_dir, src_dir):
lines=readSrc(src_dir)
dico=getLinesWithRegExp(lines)
run_log=os.path.join(result_dir,"run.log")
writeRunLog(dico, run_log)
trad_org=os.path.join(result_dir,"TRAD_2.org")
fi=open(trad_org,"r")
st_org=fi.read()
fi.close()
st=st_org
trad_add=os.path.join(result_dir,"TRAD2_ajout0")
if (os.path.exists(trad_add)):
fi=open(trad_add,"r")
st+=fi.read()
fi.close()
trad_ajout=os.path.join(result_dir,"TRAD_2")
writeOutPutFile(dico,trad_ajout,st)
return
def options_script(argv):
parser = OptionParser(usage="usage: %prog [options]")
parser.add_option("-r", "--result", dest="result_dir", type="string",
metavar="<result_dir>",
help="choose results directory")
parser.add_option("-s", "--src", dest="src_dir", type="string",
metavar="<src_dir>",
help="choose src directory")
parser.set_defaults(result_dir=os.getcwd())
parser.set_defaults(src_dir=os.getcwd())
(options, args) = parser.parse_args(argv)
if len(args) > 0:
parser.print_help()
sys.exit(1)
pass
if options.result_dir != os.getcwd():
options.result_dir=os.path.join(os.getcwd(),options.result_dir)
if not os.path.isdir(options.result_dir):
os.mkdir(options.result_dir)
pass
pass
result_dir = os.path.expanduser(options.result_dir)
result_dir = os.path.expandvars(result_dir)
result_dir = os.path.abspath(result_dir)
if not os.path.isdir(result_dir):
sys.stderr.write('Error: result dir \"' + result_dir + '\" is not a directory\n')
sys.exit(1)
pass
src_dir = options.src_dir
if src_dir!=None:
os.path.expanduser(options.src_dir)
src_dir = os.path.expandvars(src_dir)
src_dir = os.path.abspath(src_dir)
if not os.path.isdir(src_dir):
sys.stderr.write('Error: source dir \"' + src_dir + '\" is not a directory\n')
sys.exit(1)
pass
pass
return result_dir, src_dir
def main(argv):
result_dir, src_dir = options_script(argv)
run(result_dir, src_dir)
if __name__ == "__main__":
main(sys.argv[1:])
| true
| true
|
790e3e6b392afd742243686f2f2dd2c835a4afdb
| 5,832
|
py
|
Python
|
python/src/cm_api/endpoints/host_templates.py
|
cloudsoft/cm_api
|
85c7179044188c785c793a649677a22e427d2924
|
[
"Apache-2.0"
] | 329
|
2015-01-06T15:41:14.000Z
|
2022-03-12T15:28:20.000Z
|
python/src/cm_api/endpoints/host_templates.py
|
cloudsoft/cm_api
|
85c7179044188c785c793a649677a22e427d2924
|
[
"Apache-2.0"
] | 58
|
2015-02-10T11:43:42.000Z
|
2021-01-20T23:05:55.000Z
|
python/src/cm_api/endpoints/host_templates.py
|
cloudsoft/cm_api
|
85c7179044188c785c793a649677a22e427d2924
|
[
"Apache-2.0"
] | 257
|
2015-01-15T10:57:20.000Z
|
2022-03-09T12:13:57.000Z
|
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
from cm_api.endpoints.types import *
__docformat__ = "epytext"
HOST_TEMPLATES_PATH = "/clusters/%s/hostTemplates"
HOST_TEMPLATE_PATH = "/clusters/%s/hostTemplates/%s"
APPLY_HOST_TEMPLATE_PATH = HOST_TEMPLATE_PATH + "/commands/applyHostTemplate"
def create_host_template(resource_root, name, cluster_name):
"""
Create a host template.
@param resource_root: The root Resource object.
@param name: Host template name
@param cluster_name: Cluster name
@return: An ApiHostTemplate object for the created host template.
@since: API v3
"""
apitemplate = ApiHostTemplate(resource_root, name, [])
return call(resource_root.post,
HOST_TEMPLATES_PATH % (cluster_name,),
ApiHostTemplate, True, data=[apitemplate], api_version=3)[0]
def get_host_template(resource_root, name, cluster_name):
"""
Lookup a host template by name in the specified cluster.
@param resource_root: The root Resource object.
@param name: Host template name.
@param cluster_name: Cluster name.
@return: An ApiHostTemplate object.
@since: API v3
"""
return call(resource_root.get,
HOST_TEMPLATE_PATH % (cluster_name, name),
ApiHostTemplate, api_version=3)
def get_all_host_templates(resource_root, cluster_name="default"):
"""
Get all host templates in a cluster.
@param cluster_name: Cluster name.
@return: ApiList of ApiHostTemplate objects for all host templates in a cluster.
@since: API v3
"""
return call(resource_root.get,
HOST_TEMPLATES_PATH % (cluster_name,),
ApiHostTemplate, True, api_version=3)
def delete_host_template(resource_root, name, cluster_name):
"""
Delete a host template identified by name in the specified cluster.
@param resource_root: The root Resource object.
@param name: Host template name.
@param cluster_name: Cluster name.
@return: The deleted ApiHostTemplate object.
@since: API v3
"""
return call(resource_root.delete,
HOST_TEMPLATE_PATH % (cluster_name, name),
ApiHostTemplate, api_version=3)
def update_host_template(resource_root, name, cluster_name, api_host_template):
"""
Update a host template identified by name in the specified cluster.
@param resource_root: The root Resource object.
@param name: Host template name.
@param cluster_name: Cluster name.
@param api_host_template: The updated host template.
@return: The updated ApiHostTemplate.
@since: API v3
"""
return call(resource_root.put,
HOST_TEMPLATE_PATH % (cluster_name, name),
ApiHostTemplate, data=api_host_template, api_version=3)
def apply_host_template(resource_root, name, cluster_name, host_ids, start_roles):
"""
Apply a host template identified by name on the specified hosts and
optionally start them.
@param resource_root: The root Resource object.
@param name: Host template name.
@param cluster_name: Cluster name.
@param host_ids: List of host ids.
@param start_roles: Whether to start the created roles or not.
@return: An ApiCommand object.
@since: API v3
"""
host_refs = []
for host_id in host_ids:
host_refs.append(ApiHostRef(resource_root, host_id))
params = {"startRoles" : start_roles}
return call(resource_root.post,
APPLY_HOST_TEMPLATE_PATH % (cluster_name, name),
ApiCommand, data=host_refs, params=params, api_version=3)
class ApiHostTemplate(BaseApiResource):
_ATTRIBUTES = {
'name' : None,
'roleConfigGroupRefs' : Attr(ApiRoleConfigGroupRef),
'clusterRef' : ROAttr(ApiClusterRef),
}
def __init__(self, resource_root, name=None, roleConfigGroupRefs=None):
BaseApiObject.init(self, resource_root, locals())
def __str__(self):
return "<ApiHostTemplate>: %s (cluster %s)" % (self.name, self.clusterRef.clusterName)
def _api_version(self):
return 3
def _path(self):
return HOST_TEMPLATE_PATH % (self.clusterRef.clusterName, self.name)
def _do_update(self, update):
self._update(self._put('', ApiHostTemplate, data=update))
return self
def rename(self, new_name):
"""
Rename a host template.
@param new_name: New host template name.
@return: An ApiHostTemplate object.
"""
update = copy.copy(self)
update.name = new_name
return self._do_update(update)
def set_role_config_groups(self, role_config_group_refs):
"""
Updates the role config groups in a host template.
@param role_config_group_refs: List of role config group refs.
@return: An ApiHostTemplate object.
"""
update = copy.copy(self)
update.roleConfigGroupRefs = role_config_group_refs
return self._do_update(update)
def apply_host_template(self, host_ids, start_roles):
"""
Apply a host template identified by name on the specified hosts and
optionally start them.
@param host_ids: List of host ids.
@param start_roles: Whether to start the created roles or not.
@return: An ApiCommand object.
"""
return apply_host_template(self._get_resource_root(), self.name, self.clusterRef.clusterName, host_ids, start_roles)
| 35.345455
| 120
| 0.736968
|
import copy
from cm_api.endpoints.types import *
__docformat__ = "epytext"
HOST_TEMPLATES_PATH = "/clusters/%s/hostTemplates"
HOST_TEMPLATE_PATH = "/clusters/%s/hostTemplates/%s"
APPLY_HOST_TEMPLATE_PATH = HOST_TEMPLATE_PATH + "/commands/applyHostTemplate"
def create_host_template(resource_root, name, cluster_name):
apitemplate = ApiHostTemplate(resource_root, name, [])
return call(resource_root.post,
HOST_TEMPLATES_PATH % (cluster_name,),
ApiHostTemplate, True, data=[apitemplate], api_version=3)[0]
def get_host_template(resource_root, name, cluster_name):
return call(resource_root.get,
HOST_TEMPLATE_PATH % (cluster_name, name),
ApiHostTemplate, api_version=3)
def get_all_host_templates(resource_root, cluster_name="default"):
return call(resource_root.get,
HOST_TEMPLATES_PATH % (cluster_name,),
ApiHostTemplate, True, api_version=3)
def delete_host_template(resource_root, name, cluster_name):
return call(resource_root.delete,
HOST_TEMPLATE_PATH % (cluster_name, name),
ApiHostTemplate, api_version=3)
def update_host_template(resource_root, name, cluster_name, api_host_template):
return call(resource_root.put,
HOST_TEMPLATE_PATH % (cluster_name, name),
ApiHostTemplate, data=api_host_template, api_version=3)
def apply_host_template(resource_root, name, cluster_name, host_ids, start_roles):
host_refs = []
for host_id in host_ids:
host_refs.append(ApiHostRef(resource_root, host_id))
params = {"startRoles" : start_roles}
return call(resource_root.post,
APPLY_HOST_TEMPLATE_PATH % (cluster_name, name),
ApiCommand, data=host_refs, params=params, api_version=3)
class ApiHostTemplate(BaseApiResource):
_ATTRIBUTES = {
'name' : None,
'roleConfigGroupRefs' : Attr(ApiRoleConfigGroupRef),
'clusterRef' : ROAttr(ApiClusterRef),
}
def __init__(self, resource_root, name=None, roleConfigGroupRefs=None):
BaseApiObject.init(self, resource_root, locals())
def __str__(self):
return "<ApiHostTemplate>: %s (cluster %s)" % (self.name, self.clusterRef.clusterName)
def _api_version(self):
return 3
def _path(self):
return HOST_TEMPLATE_PATH % (self.clusterRef.clusterName, self.name)
def _do_update(self, update):
self._update(self._put('', ApiHostTemplate, data=update))
return self
def rename(self, new_name):
update = copy.copy(self)
update.name = new_name
return self._do_update(update)
def set_role_config_groups(self, role_config_group_refs):
update = copy.copy(self)
update.roleConfigGroupRefs = role_config_group_refs
return self._do_update(update)
def apply_host_template(self, host_ids, start_roles):
return apply_host_template(self._get_resource_root(), self.name, self.clusterRef.clusterName, host_ids, start_roles)
| true
| true
|
790e3e6f067d05367b89b6794a611617bc7cd257
| 5,379
|
py
|
Python
|
test/test_ping.py
|
velopaymentsapi/velo-python
|
59b39555e9714139b4bf697151cc7d15f6dd510e
|
[
"Apache-2.0"
] | null | null | null |
test/test_ping.py
|
velopaymentsapi/velo-python
|
59b39555e9714139b4bf697151cc7d15f6dd510e
|
[
"Apache-2.0"
] | null | null | null |
test/test_ping.py
|
velopaymentsapi/velo-python
|
59b39555e9714139b4bf697151cc7d15f6dd510e
|
[
"Apache-2.0"
] | null | null | null |
# coding: utf-8
"""
Velo Payments APIs
## Terms and Definitions Throughout this document and the Velo platform the following terms are used: * **Payor.** An entity (typically a corporation) which wishes to pay funds to one or more payees via a payout. * **Payee.** The recipient of funds paid out by a payor. * **Payment.** A single transfer of funds from a payor to a payee. * **Payout.** A batch of Payments, typically used by a payor to logically group payments (e.g. by business day). Technically there need be no relationship between the payments in a payout - a single payout can contain payments to multiple payees and/or multiple payments to a single payee. * **Sandbox.** An integration environment provided by Velo Payments which offers a similar API experience to the production environment, but all funding and payment events are simulated, along with many other services such as OFAC sanctions list checking. ## Overview The Velo Payments API allows a payor to perform a number of operations. The following is a list of the main capabilities in a natural order of execution: * Authenticate with the Velo platform * Maintain a collection of payees * Query the payor’s current balance of funds within the platform and perform additional funding * Issue payments to payees * Query the platform for a history of those payments This document describes the main concepts and APIs required to get up and running with the Velo Payments platform. It is not an exhaustive API reference. For that, please see the separate Velo Payments API Reference. ## API Considerations The Velo Payments API is REST based and uses the JSON format for requests and responses. Most calls are secured using OAuth 2 security and require a valid authentication access token for successful operation. See the Authentication section for details. Where a dynamic value is required in the examples below, the {token} format is used, suggesting that the caller needs to supply the appropriate value of the token in question (without including the { or } characters). Where curl examples are given, the –d @filename.json approach is used, indicating that the request body should be placed into a file named filename.json in the current directory. Each of the curl examples in this document should be considered a single line on the command-line, regardless of how they appear in print. ## Authenticating with the Velo Platform Once Velo backoffice staff have added your organization as a payor within the Velo platform sandbox, they will create you a payor Id, an API key and an API secret and share these with you in a secure manner. You will need to use these values to authenticate with the Velo platform in order to gain access to the APIs. The steps to take are explained in the following: create a string comprising the API key (e.g. 44a9537d-d55d-4b47-8082-14061c2bcdd8) and API secret (e.g. c396b26b-137a-44fd-87f5-34631f8fd529) with a colon between them. E.g. 44a9537d-d55d-4b47-8082-14061c2bcdd8:c396b26b-137a-44fd-87f5-34631f8fd529 base64 encode this string. E.g.: NDRhOTUzN2QtZDU1ZC00YjQ3LTgwODItMTQwNjFjMmJjZGQ4OmMzOTZiMjZiLTEzN2EtNDRmZC04N2Y1LTM0NjMxZjhmZDUyOQ== create an HTTP **Authorization** header with the value set to e.g. Basic NDRhOTUzN2QtZDU1ZC00YjQ3LTgwODItMTQwNjFjMmJjZGQ4OmMzOTZiMjZiLTEzN2EtNDRmZC04N2Y1LTM0NjMxZjhmZDUyOQ== perform the Velo authentication REST call using the HTTP header created above e.g. via curl: ``` curl -X POST \\ -H \"Content-Type: application/json\" \\ -H \"Authorization: Basic NDRhOTUzN2QtZDU1ZC00YjQ3LTgwODItMTQwNjFjMmJjZGQ4OmMzOTZiMjZiLTEzN2EtNDRmZC04N2Y1LTM0NjMxZjhmZDUyOQ==\" \\ 'https://api.sandbox.velopayments.com/v1/authenticate?grant_type=client_credentials' ``` If successful, this call will result in a **200** HTTP status code and a response body such as: ``` { \"access_token\":\"19f6bafd-93fd-4747-b229-00507bbc991f\", \"token_type\":\"bearer\", \"expires_in\":1799, \"scope\":\"...\" } ``` ## API access following authentication Following successful authentication, the value of the access_token field in the response (indicated in green above) should then be presented with all subsequent API calls to allow the Velo platform to validate that the caller is authenticated. This is achieved by setting the HTTP Authorization header with the value set to e.g. Bearer 19f6bafd-93fd-4747-b229-00507bbc991f such as the curl example below: ``` -H \"Authorization: Bearer 19f6bafd-93fd-4747-b229-00507bbc991f \" ``` If you make other Velo API calls which require authorization but the Authorization header is missing or invalid then you will get a **401** HTTP status response. # noqa: E501
The version of the OpenAPI document: 2.26.124
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import velo_payments
from velo_payments.models.ping import Ping # noqa: E501
from velo_payments.rest import ApiException
class TestPing(unittest.TestCase):
"""Ping unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testPing(self):
"""Test Ping"""
# FIXME: construct object with mandatory attributes with example values
# model = velo_payments.models.ping.Ping() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| 134.475
| 4,651
| 0.770961
|
from __future__ import absolute_import
import unittest
import velo_payments
from velo_payments.models.ping import Ping
from velo_payments.rest import ApiException
class TestPing(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testPing(self):
s
if __name__ == '__main__':
unittest.main()
| true
| true
|
790e3f3b10cc4554c59e1cd61e3f47851c4f1e89
| 1,300
|
py
|
Python
|
pgdrive/tests/vis_block/vis_t_intersection.py
|
gamecraftCZ/pgdrive
|
11fbb5a5ca1dc354d755f00eb282bcffe5720bcc
|
[
"Apache-2.0"
] | null | null | null |
pgdrive/tests/vis_block/vis_t_intersection.py
|
gamecraftCZ/pgdrive
|
11fbb5a5ca1dc354d755f00eb282bcffe5720bcc
|
[
"Apache-2.0"
] | null | null | null |
pgdrive/tests/vis_block/vis_t_intersection.py
|
gamecraftCZ/pgdrive
|
11fbb5a5ca1dc354d755f00eb282bcffe5720bcc
|
[
"Apache-2.0"
] | null | null | null |
from pgdrive.scene_creator.blocks.curve import Curve
from pgdrive.scene_creator.blocks.first_block import FirstBlock
from pgdrive.scene_creator.blocks.straight import Straight
from pgdrive.scene_creator.blocks.t_intersection import TInterSection
from pgdrive.scene_creator.road.road_network import RoadNetwork
from pgdrive.tests.vis_block.vis_block_base import TestBlock
if __name__ == "__main__":
test = TestBlock(True)
from pgdrive.utils.asset_loader import initialize_asset_loader
initialize_asset_loader(test)
global_network = RoadNetwork()
first = FirstBlock(global_network, 3.0, 2, test.render, test.world, 1)
curve = Curve(1, first.get_socket(0), global_network, 1)
curve.construct_block(test.render, test.world)
straight = Straight(2, curve.get_socket(0), global_network, 1)
straight.construct_block(test.render, test.world)
intersection = TInterSection(3, straight.get_socket(0), global_network, 1)
print(intersection.construct_block(test.render, test.world))
id = 4
for socket_idx in range(intersection.SOCKET_NUM):
block = Curve(id, intersection.get_socket(socket_idx), global_network, id + 1)
block.construct_block(test.render, test.world)
id += 1
test.show_bounding_box(global_network)
test.run()
| 40.625
| 86
| 0.766923
|
from pgdrive.scene_creator.blocks.curve import Curve
from pgdrive.scene_creator.blocks.first_block import FirstBlock
from pgdrive.scene_creator.blocks.straight import Straight
from pgdrive.scene_creator.blocks.t_intersection import TInterSection
from pgdrive.scene_creator.road.road_network import RoadNetwork
from pgdrive.tests.vis_block.vis_block_base import TestBlock
if __name__ == "__main__":
test = TestBlock(True)
from pgdrive.utils.asset_loader import initialize_asset_loader
initialize_asset_loader(test)
global_network = RoadNetwork()
first = FirstBlock(global_network, 3.0, 2, test.render, test.world, 1)
curve = Curve(1, first.get_socket(0), global_network, 1)
curve.construct_block(test.render, test.world)
straight = Straight(2, curve.get_socket(0), global_network, 1)
straight.construct_block(test.render, test.world)
intersection = TInterSection(3, straight.get_socket(0), global_network, 1)
print(intersection.construct_block(test.render, test.world))
id = 4
for socket_idx in range(intersection.SOCKET_NUM):
block = Curve(id, intersection.get_socket(socket_idx), global_network, id + 1)
block.construct_block(test.render, test.world)
id += 1
test.show_bounding_box(global_network)
test.run()
| true
| true
|
790e3f8ff78fefaceefc11289c245443f0e584c0
| 10,233
|
py
|
Python
|
tests/test_sns/test_application.py
|
mrucci/moto
|
076a6a7055ad18908b5661e599648c40b251cdc1
|
[
"Apache-2.0"
] | null | null | null |
tests/test_sns/test_application.py
|
mrucci/moto
|
076a6a7055ad18908b5661e599648c40b251cdc1
|
[
"Apache-2.0"
] | null | null | null |
tests/test_sns/test_application.py
|
mrucci/moto
|
076a6a7055ad18908b5661e599648c40b251cdc1
|
[
"Apache-2.0"
] | null | null | null |
from __future__ import unicode_literals
import boto
from boto.exception import BotoServerError
from moto import mock_sns
import sure # noqa
@mock_sns
def test_create_platform_application():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
application_arn.should.equal('arn:aws:sns:us-east-1:123456789012:app/APNS/my-application')
@mock_sns
def test_get_platform_application_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
attributes = conn.get_platform_application_attributes(arn)['GetPlatformApplicationAttributesResponse']['GetPlatformApplicationAttributesResult']['Attributes']
attributes.should.equal({
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
})
@mock_sns
def test_get_missing_platform_application_attributes():
conn = boto.connect_sns()
conn.get_platform_application_attributes.when.called_with("a-fake-arn").should.throw(BotoServerError)
@mock_sns
def test_set_platform_application_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
conn.set_platform_application_attributes(arn,
{"PlatformPrincipal": "other"}
)
attributes = conn.get_platform_application_attributes(arn)['GetPlatformApplicationAttributesResponse']['GetPlatformApplicationAttributesResult']['Attributes']
attributes.should.equal({
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "other",
})
@mock_sns
def test_list_platform_applications():
conn = boto.connect_sns()
conn.create_platform_application(
name="application1",
platform="APNS",
)
conn.create_platform_application(
name="application2",
platform="APNS",
)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['ListPlatformApplicationsResponse']['ListPlatformApplicationsResult']['PlatformApplications']
applications.should.have.length_of(2)
@mock_sns
def test_delete_platform_application():
conn = boto.connect_sns()
conn.create_platform_application(
name="application1",
platform="APNS",
)
conn.create_platform_application(
name="application2",
platform="APNS",
)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['ListPlatformApplicationsResponse']['ListPlatformApplicationsResult']['PlatformApplications']
applications.should.have.length_of(2)
application_arn = applications[0]['PlatformApplicationArn']
conn.delete_platform_application(application_arn)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['ListPlatformApplicationsResponse']['ListPlatformApplicationsResult']['PlatformApplications']
applications.should.have.length_of(1)
@mock_sns
def test_create_platform_endpoint():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
endpoint_arn.should.contain("arn:aws:sns:us-east-1:123456789012:endpoint/APNS/my-application/")
@mock_sns
def test_get_list_endpoints_by_platform_application():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
endpoint_list = conn.list_endpoints_by_platform_application(
platform_application_arn=application_arn
)['ListEndpointsByPlatformApplicationResponse']['ListEndpointsByPlatformApplicationResult']['Endpoints']
endpoint_list.should.have.length_of(1)
endpoint_list[0]['Attributes']['CustomUserData'].should.equal('some data')
endpoint_list[0]['EndpointArn'].should.equal(endpoint_arn)
@mock_sns
def test_get_endpoint_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
attributes = conn.get_endpoint_attributes(endpoint_arn)['GetEndpointAttributesResponse']['GetEndpointAttributesResult']['Attributes']
attributes.should.equal({
"Enabled": 'False',
"CustomUserData": "some data",
})
@mock_sns
def test_get_missing_endpoint_attributes():
conn = boto.connect_sns()
conn.get_endpoint_attributes.when.called_with("a-fake-arn").should.throw(BotoServerError)
@mock_sns
def test_set_endpoint_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
conn.set_endpoint_attributes(endpoint_arn,
{"CustomUserData": "other data"}
)
attributes = conn.get_endpoint_attributes(endpoint_arn)['GetEndpointAttributesResponse']['GetEndpointAttributesResult']['Attributes']
attributes.should.equal({
"Enabled": 'False',
"CustomUserData": "other data",
})
@mock_sns
def test_delete_endpoint():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
endpoint_list = conn.list_endpoints_by_platform_application(
platform_application_arn=application_arn
)['ListEndpointsByPlatformApplicationResponse']['ListEndpointsByPlatformApplicationResult']['Endpoints']
endpoint_list.should.have.length_of(1)
conn.delete_endpoint(endpoint_arn)
endpoint_list = conn.list_endpoints_by_platform_application(
platform_application_arn=application_arn
)['ListEndpointsByPlatformApplicationResponse']['ListEndpointsByPlatformApplicationResult']['Endpoints']
endpoint_list.should.have.length_of(0)
@mock_sns
def test_publish_to_platform_endpoint():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
conn.publish(message="some message", message_structure="json", target_arn=endpoint_arn)
| 36.546429
| 162
| 0.731262
|
from __future__ import unicode_literals
import boto
from boto.exception import BotoServerError
from moto import mock_sns
import sure
@mock_sns
def test_create_platform_application():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
application_arn.should.equal('arn:aws:sns:us-east-1:123456789012:app/APNS/my-application')
@mock_sns
def test_get_platform_application_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
attributes = conn.get_platform_application_attributes(arn)['GetPlatformApplicationAttributesResponse']['GetPlatformApplicationAttributesResult']['Attributes']
attributes.should.equal({
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
})
@mock_sns
def test_get_missing_platform_application_attributes():
conn = boto.connect_sns()
conn.get_platform_application_attributes.when.called_with("a-fake-arn").should.throw(BotoServerError)
@mock_sns
def test_set_platform_application_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
conn.set_platform_application_attributes(arn,
{"PlatformPrincipal": "other"}
)
attributes = conn.get_platform_application_attributes(arn)['GetPlatformApplicationAttributesResponse']['GetPlatformApplicationAttributesResult']['Attributes']
attributes.should.equal({
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "other",
})
@mock_sns
def test_list_platform_applications():
conn = boto.connect_sns()
conn.create_platform_application(
name="application1",
platform="APNS",
)
conn.create_platform_application(
name="application2",
platform="APNS",
)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['ListPlatformApplicationsResponse']['ListPlatformApplicationsResult']['PlatformApplications']
applications.should.have.length_of(2)
@mock_sns
def test_delete_platform_application():
conn = boto.connect_sns()
conn.create_platform_application(
name="application1",
platform="APNS",
)
conn.create_platform_application(
name="application2",
platform="APNS",
)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['ListPlatformApplicationsResponse']['ListPlatformApplicationsResult']['PlatformApplications']
applications.should.have.length_of(2)
application_arn = applications[0]['PlatformApplicationArn']
conn.delete_platform_application(application_arn)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['ListPlatformApplicationsResponse']['ListPlatformApplicationsResult']['PlatformApplications']
applications.should.have.length_of(1)
@mock_sns
def test_create_platform_endpoint():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
endpoint_arn.should.contain("arn:aws:sns:us-east-1:123456789012:endpoint/APNS/my-application/")
@mock_sns
def test_get_list_endpoints_by_platform_application():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
endpoint_list = conn.list_endpoints_by_platform_application(
platform_application_arn=application_arn
)['ListEndpointsByPlatformApplicationResponse']['ListEndpointsByPlatformApplicationResult']['Endpoints']
endpoint_list.should.have.length_of(1)
endpoint_list[0]['Attributes']['CustomUserData'].should.equal('some data')
endpoint_list[0]['EndpointArn'].should.equal(endpoint_arn)
@mock_sns
def test_get_endpoint_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
attributes = conn.get_endpoint_attributes(endpoint_arn)['GetEndpointAttributesResponse']['GetEndpointAttributesResult']['Attributes']
attributes.should.equal({
"Enabled": 'False',
"CustomUserData": "some data",
})
@mock_sns
def test_get_missing_endpoint_attributes():
conn = boto.connect_sns()
conn.get_endpoint_attributes.when.called_with("a-fake-arn").should.throw(BotoServerError)
@mock_sns
def test_set_endpoint_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
conn.set_endpoint_attributes(endpoint_arn,
{"CustomUserData": "other data"}
)
attributes = conn.get_endpoint_attributes(endpoint_arn)['GetEndpointAttributesResponse']['GetEndpointAttributesResult']['Attributes']
attributes.should.equal({
"Enabled": 'False',
"CustomUserData": "other data",
})
@mock_sns
def test_delete_endpoint():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
endpoint_list = conn.list_endpoints_by_platform_application(
platform_application_arn=application_arn
)['ListEndpointsByPlatformApplicationResponse']['ListEndpointsByPlatformApplicationResult']['Endpoints']
endpoint_list.should.have.length_of(1)
conn.delete_endpoint(endpoint_arn)
endpoint_list = conn.list_endpoints_by_platform_application(
platform_application_arn=application_arn
)['ListEndpointsByPlatformApplicationResponse']['ListEndpointsByPlatformApplicationResult']['Endpoints']
endpoint_list.should.have.length_of(0)
@mock_sns
def test_publish_to_platform_endpoint():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
conn.publish(message="some message", message_structure="json", target_arn=endpoint_arn)
| true
| true
|
790e44191bf61e44a3467f34f97652043db7963a
| 414
|
py
|
Python
|
pwncat/commands/exit.py
|
Mitul16/pwncat
|
b8d7876a9779c2c7796a9a29110d3f1cda721dff
|
[
"MIT"
] | 1,454
|
2020-05-07T02:20:52.000Z
|
2022-03-31T21:32:22.000Z
|
pwncat/commands/exit.py
|
akr3ch/pwncat
|
d67865bdaac60dd0761d0698062e7b443a62c6db
|
[
"MIT"
] | 187
|
2020-05-08T06:26:01.000Z
|
2022-03-07T21:15:29.000Z
|
pwncat/commands/exit.py
|
akr3ch/pwncat
|
d67865bdaac60dd0761d0698062e7b443a62c6db
|
[
"MIT"
] | 184
|
2020-05-07T02:31:58.000Z
|
2022-03-31T09:11:59.000Z
|
#!/usr/bin/env python3
import pwncat
from pwncat.commands import CommandDefinition
class Command(CommandDefinition):
"""
Exit the interactive prompt. If sessions are active, you will
be prompted to confirm. This shouldn't be run from a configuration
script.
"""
PROG = "exit"
ARGS = {}
LOCAL = True
def run(self, manager, args):
raise pwncat.manager.InteractiveExit
| 21.789474
| 70
| 0.683575
|
import pwncat
from pwncat.commands import CommandDefinition
class Command(CommandDefinition):
PROG = "exit"
ARGS = {}
LOCAL = True
def run(self, manager, args):
raise pwncat.manager.InteractiveExit
| true
| true
|
790e4520a95545a14ffacee45d176549735c05a2
| 1,983
|
py
|
Python
|
tests/patterns/test_patterns_Pn.py
|
butayama/supriya
|
0c197324ecee4232381221880d1f40e109bb756c
|
[
"MIT"
] | null | null | null |
tests/patterns/test_patterns_Pn.py
|
butayama/supriya
|
0c197324ecee4232381221880d1f40e109bb756c
|
[
"MIT"
] | null | null | null |
tests/patterns/test_patterns_Pn.py
|
butayama/supriya
|
0c197324ecee4232381221880d1f40e109bb756c
|
[
"MIT"
] | null | null | null |
import pytest
import uqbar.strings
import supriya.patterns
pattern_01 = supriya.patterns.Pn(
supriya.patterns.Pbind(foo=supriya.patterns.Pseq(["A", "B", "C"])), repetitions=2
)
pattern_02 = supriya.patterns.Pn(
supriya.patterns.Pbind(foo=supriya.patterns.Pseq(["A", "B", "C"])),
key="repeat",
repetitions=3,
)
def test___iter___01():
events = list(pattern_01)
assert pytest.helpers.get_objects_as_string(
events, replace_uuids=True
) == uqbar.strings.normalize(
"""
NoteEvent(
foo='A',
uuid=UUID('A'),
)
NoteEvent(
foo='B',
uuid=UUID('B'),
)
NoteEvent(
foo='C',
uuid=UUID('C'),
)
NoteEvent(
foo='A',
uuid=UUID('D'),
)
NoteEvent(
foo='B',
uuid=UUID('E'),
)
NoteEvent(
foo='C',
uuid=UUID('F'),
)
"""
)
def test___iter___02():
events = list(pattern_02)
assert pytest.helpers.get_objects_as_string(
events, replace_uuids=True
) == uqbar.strings.normalize(
"""
NoteEvent(
foo='A',
repeat=True,
uuid=UUID('A'),
)
NoteEvent(
foo='B',
uuid=UUID('B'),
)
NoteEvent(
foo='C',
uuid=UUID('C'),
)
NoteEvent(
foo='A',
repeat=True,
uuid=UUID('D'),
)
NoteEvent(
foo='B',
uuid=UUID('E'),
)
NoteEvent(
foo='C',
uuid=UUID('F'),
)
NoteEvent(
foo='A',
repeat=True,
uuid=UUID('G'),
)
NoteEvent(
foo='B',
uuid=UUID('H'),
)
NoteEvent(
foo='C',
uuid=UUID('I'),
)
"""
)
| 20.030303
| 85
| 0.420575
|
import pytest
import uqbar.strings
import supriya.patterns
pattern_01 = supriya.patterns.Pn(
supriya.patterns.Pbind(foo=supriya.patterns.Pseq(["A", "B", "C"])), repetitions=2
)
pattern_02 = supriya.patterns.Pn(
supriya.patterns.Pbind(foo=supriya.patterns.Pseq(["A", "B", "C"])),
key="repeat",
repetitions=3,
)
def test___iter___01():
events = list(pattern_01)
assert pytest.helpers.get_objects_as_string(
events, replace_uuids=True
) == uqbar.strings.normalize(
"""
NoteEvent(
foo='A',
uuid=UUID('A'),
)
NoteEvent(
foo='B',
uuid=UUID('B'),
)
NoteEvent(
foo='C',
uuid=UUID('C'),
)
NoteEvent(
foo='A',
uuid=UUID('D'),
)
NoteEvent(
foo='B',
uuid=UUID('E'),
)
NoteEvent(
foo='C',
uuid=UUID('F'),
)
"""
)
def test___iter___02():
events = list(pattern_02)
assert pytest.helpers.get_objects_as_string(
events, replace_uuids=True
) == uqbar.strings.normalize(
"""
NoteEvent(
foo='A',
repeat=True,
uuid=UUID('A'),
)
NoteEvent(
foo='B',
uuid=UUID('B'),
)
NoteEvent(
foo='C',
uuid=UUID('C'),
)
NoteEvent(
foo='A',
repeat=True,
uuid=UUID('D'),
)
NoteEvent(
foo='B',
uuid=UUID('E'),
)
NoteEvent(
foo='C',
uuid=UUID('F'),
)
NoteEvent(
foo='A',
repeat=True,
uuid=UUID('G'),
)
NoteEvent(
foo='B',
uuid=UUID('H'),
)
NoteEvent(
foo='C',
uuid=UUID('I'),
)
"""
)
| true
| true
|
790e4546d732c6ce113d26fdfabfb52f208a249d
| 24,018
|
py
|
Python
|
django/http/request.py
|
cutegony/django
|
5d654e1e7104d2ce86ec1b9fe52865a7dca4b4be
|
[
"CNRI-Python-GPL-Compatible",
"BSD-3-Clause"
] | 2
|
2015-11-08T11:32:49.000Z
|
2022-03-26T23:11:46.000Z
|
django/http/request.py
|
cutegony/django
|
5d654e1e7104d2ce86ec1b9fe52865a7dca4b4be
|
[
"CNRI-Python-GPL-Compatible",
"BSD-3-Clause"
] | null | null | null |
django/http/request.py
|
cutegony/django
|
5d654e1e7104d2ce86ec1b9fe52865a7dca4b4be
|
[
"CNRI-Python-GPL-Compatible",
"BSD-3-Clause"
] | null | null | null |
import cgi
import codecs
import copy
from io import BytesIO
from itertools import chain
from urllib.parse import quote, urlencode, urljoin, urlsplit
from django.conf import settings
from django.core import signing
from django.core.exceptions import (
DisallowedHost, ImproperlyConfigured, RequestDataTooBig,
)
from django.core.files import uploadhandler
from django.http.multipartparser import MultiPartParser, MultiPartParserError
from django.utils.datastructures import (
CaseInsensitiveMapping, ImmutableList, MultiValueDict,
)
from django.utils.encoding import escape_uri_path, iri_to_uri
from django.utils.functional import cached_property
from django.utils.http import is_same_domain, limited_parse_qsl
from django.utils.regex_helper import _lazy_re_compile
from .multipartparser import parse_header
RAISE_ERROR = object()
host_validation_re = _lazy_re_compile(r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])(:\d+)?$")
class UnreadablePostError(OSError):
pass
class RawPostDataException(Exception):
"""
You cannot access raw_post_data from a request that has
multipart/* POST data if it has been accessed via POST,
FILES, etc..
"""
pass
class HttpRequest:
"""A basic HTTP request."""
# The encoding used in GET/POST dicts. None means use default setting.
_encoding = None
_upload_handlers = []
def __init__(self):
# WARNING: The `WSGIRequest` subclass doesn't call `super`.
# Any variable assignment made here should also happen in
# `WSGIRequest.__init__()`.
self.GET = QueryDict(mutable=True)
self.POST = QueryDict(mutable=True)
self.COOKIES = {}
self.META = {}
self.FILES = MultiValueDict()
self.path = ''
self.path_info = ''
self.method = None
self.resolver_match = None
self.content_type = None
self.content_params = None
def __repr__(self):
if self.method is None or not self.get_full_path():
return '<%s>' % self.__class__.__name__
return '<%s: %s %r>' % (self.__class__.__name__, self.method, self.get_full_path())
@cached_property
def headers(self):
return HttpHeaders(self.META)
@cached_property
def accepted_types(self):
"""Return a list of MediaType instances."""
return parse_accept_header(self.headers.get('Accept', '*/*'))
def accepts(self, media_type):
return any(
accepted_type.match(media_type)
for accepted_type in self.accepted_types
)
def _set_content_type_params(self, meta):
"""Set content_type, content_params, and encoding."""
self.content_type, self.content_params = cgi.parse_header(meta.get('CONTENT_TYPE', ''))
if 'charset' in self.content_params:
try:
codecs.lookup(self.content_params['charset'])
except LookupError:
pass
else:
self.encoding = self.content_params['charset']
def _get_raw_host(self):
"""
Return the HTTP host using the environment or request headers. Skip
allowed hosts protection, so may return an insecure host.
"""
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in self.META):
host = self.META['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in self.META:
host = self.META['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = self.META['SERVER_NAME']
server_port = self.get_port()
if server_port != ('443' if self.is_secure() else '80'):
host = '%s:%s' % (host, server_port)
return host
def get_host(self):
"""Return the HTTP host using the environment or request headers."""
host = self._get_raw_host()
# Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
allowed_hosts = settings.ALLOWED_HOSTS
if settings.DEBUG and not allowed_hosts:
allowed_hosts = ['.localhost', '127.0.0.1', '[::1]']
domain, port = split_domain_port(host)
if domain and validate_host(domain, allowed_hosts):
return host
else:
msg = "Invalid HTTP_HOST header: %r." % host
if domain:
msg += " You may need to add %r to ALLOWED_HOSTS." % domain
else:
msg += " The domain name provided is not valid according to RFC 1034/1035."
raise DisallowedHost(msg)
def get_port(self):
"""Return the port number for the request as a string."""
if settings.USE_X_FORWARDED_PORT and 'HTTP_X_FORWARDED_PORT' in self.META:
port = self.META['HTTP_X_FORWARDED_PORT']
else:
port = self.META['SERVER_PORT']
return str(port)
def get_full_path(self, force_append_slash=False):
return self._get_full_path(self.path, force_append_slash)
def get_full_path_info(self, force_append_slash=False):
return self._get_full_path(self.path_info, force_append_slash)
def _get_full_path(self, path, force_append_slash):
# RFC 3986 requires query string arguments to be in the ASCII range.
# Rather than crash if this doesn't happen, we encode defensively.
return '%s%s%s' % (
escape_uri_path(path),
'/' if force_append_slash and not path.endswith('/') else '',
('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) if self.META.get('QUERY_STRING', '') else ''
)
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
"""
Attempt to return a signed cookie. If the signature fails or the
cookie has expired, raise an exception, unless the `default` argument
is provided, in which case return that value.
"""
try:
cookie_value = self.COOKIES[key]
except KeyError:
if default is not RAISE_ERROR:
return default
else:
raise
try:
value = signing.get_cookie_signer(salt=key + salt).unsign(
cookie_value, max_age=max_age)
except signing.BadSignature:
if default is not RAISE_ERROR:
return default
else:
raise
return value
def get_raw_uri(self):
"""
Return an absolute URI from variables available in this request. Skip
allowed hosts protection, so may return insecure URI.
"""
return '{scheme}://{host}{path}'.format(
scheme=self.scheme,
host=self._get_raw_host(),
path=self.get_full_path(),
)
def build_absolute_uri(self, location=None):
"""
Build an absolute URI from the location and the variables available in
this request. If no ``location`` is specified, build the absolute URI
using request.get_full_path(). If the location is absolute, convert it
to an RFC 3987 compliant URI and return it. If location is relative or
is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base
URL constructed from the request variables.
"""
if location is None:
# Make it an absolute url (but schemeless and domainless) for the
# edge case that the path starts with '//'.
location = '//%s' % self.get_full_path()
else:
# Coerce lazy locations.
location = str(location)
bits = urlsplit(location)
if not (bits.scheme and bits.netloc):
# Handle the simple, most common case. If the location is absolute
# and a scheme or host (netloc) isn't provided, skip an expensive
# urljoin() as long as no path segments are '.' or '..'.
if (bits.path.startswith('/') and not bits.scheme and not bits.netloc and
'/./' not in bits.path and '/../' not in bits.path):
# If location starts with '//' but has no netloc, reuse the
# schema and netloc from the current request. Strip the double
# slashes and continue as if it wasn't specified.
if location.startswith('//'):
location = location[2:]
location = self._current_scheme_host + location
else:
# Join the constructed URL with the provided location, which
# allows the provided location to apply query strings to the
# base path.
location = urljoin(self._current_scheme_host + self.path, location)
return iri_to_uri(location)
@cached_property
def _current_scheme_host(self):
return '{}://{}'.format(self.scheme, self.get_host())
def _get_scheme(self):
"""
Hook for subclasses like WSGIRequest to implement. Return 'http' by
default.
"""
return 'http'
@property
def scheme(self):
if settings.SECURE_PROXY_SSL_HEADER:
try:
header, secure_value = settings.SECURE_PROXY_SSL_HEADER
except ValueError:
raise ImproperlyConfigured(
'The SECURE_PROXY_SSL_HEADER setting must be a tuple containing two values.'
)
header_value = self.META.get(header)
if header_value is not None:
return 'https' if header_value == secure_value else 'http'
return self._get_scheme()
def is_secure(self):
return self.scheme == 'https'
def is_ajax(self):
return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
@property
def encoding(self):
return self._encoding
@encoding.setter
def encoding(self, val):
"""
Set the encoding used for GET/POST accesses. If the GET or POST
dictionary has already been created, remove and recreate it on the
next access (so that it is decoded correctly).
"""
self._encoding = val
if hasattr(self, 'GET'):
del self.GET
if hasattr(self, '_post'):
del self._post
def _initialize_handlers(self):
self._upload_handlers = [uploadhandler.load_handler(handler, self)
for handler in settings.FILE_UPLOAD_HANDLERS]
@property
def upload_handlers(self):
if not self._upload_handlers:
# If there are no upload handlers defined, initialize them from settings.
self._initialize_handlers()
return self._upload_handlers
@upload_handlers.setter
def upload_handlers(self, upload_handlers):
if hasattr(self, '_files'):
raise AttributeError("You cannot set the upload handlers after the upload has been processed.")
self._upload_handlers = upload_handlers
def parse_file_upload(self, META, post_data):
"""Return a tuple of (POST QueryDict, FILES MultiValueDict)."""
self.upload_handlers = ImmutableList(
self.upload_handlers,
warning="You cannot alter upload handlers after the upload has been processed."
)
parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
return parser.parse()
@property
def body(self):
if not hasattr(self, '_body'):
if self._read_started:
raise RawPostDataException("You cannot access body after reading from request's data stream")
# Limit the maximum request data size that will be handled in-memory.
if (settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and
int(self.META.get('CONTENT_LENGTH') or 0) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE):
raise RequestDataTooBig('Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.')
try:
self._body = self.read()
except OSError as e:
raise UnreadablePostError(*e.args) from e
self._stream = BytesIO(self._body)
return self._body
def _mark_post_parse_error(self):
self._post = QueryDict()
self._files = MultiValueDict()
def _load_post_and_files(self):
"""Populate self._post and self._files if the content-type is a form type"""
if self.method != 'POST':
self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
return
if self._read_started and not hasattr(self, '_body'):
self._mark_post_parse_error()
return
if self.content_type == 'multipart/form-data':
if hasattr(self, '_body'):
# Use already read data
data = BytesIO(self._body)
else:
data = self
try:
self._post, self._files = self.parse_file_upload(self.META, data)
except MultiPartParserError:
# An error occurred while parsing POST data. Since when
# formatting the error the request handler might access
# self.POST, set self._post and self._file to prevent
# attempts to parse POST data again.
self._mark_post_parse_error()
raise
elif self.content_type == 'application/x-www-form-urlencoded':
self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
else:
self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
def close(self):
if hasattr(self, '_files'):
for f in chain.from_iterable(l[1] for l in self._files.lists()):
f.close()
# File-like and iterator interface.
#
# Expects self._stream to be set to an appropriate source of bytes by
# a corresponding request subclass (e.g. WSGIRequest).
# Also when request data has already been read by request.POST or
# request.body, self._stream points to a BytesIO instance
# containing that data.
def read(self, *args, **kwargs):
self._read_started = True
try:
return self._stream.read(*args, **kwargs)
except OSError as e:
raise UnreadablePostError(*e.args) from e
def readline(self, *args, **kwargs):
self._read_started = True
try:
return self._stream.readline(*args, **kwargs)
except OSError as e:
raise UnreadablePostError(*e.args) from e
def __iter__(self):
return iter(self.readline, b'')
def readlines(self):
return list(self)
class HttpHeaders(CaseInsensitiveMapping):
HTTP_PREFIX = 'HTTP_'
# PEP 333 gives two headers which aren't prepended with HTTP_.
UNPREFIXED_HEADERS = {'CONTENT_TYPE', 'CONTENT_LENGTH'}
def __init__(self, environ):
headers = {}
for header, value in environ.items():
name = self.parse_header_name(header)
if name:
headers[name] = value
super().__init__(headers)
def __getitem__(self, key):
"""Allow header lookup using underscores in place of hyphens."""
return super().__getitem__(key.replace('_', '-'))
@classmethod
def parse_header_name(cls, header):
if header.startswith(cls.HTTP_PREFIX):
header = header[len(cls.HTTP_PREFIX):]
elif header not in cls.UNPREFIXED_HEADERS:
return None
return header.replace('_', '-').title()
class QueryDict(MultiValueDict):
"""
A specialized MultiValueDict which represents a query string.
A QueryDict can be used to represent GET or POST data. It subclasses
MultiValueDict since keys in such data can be repeated, for instance
in the data from a form with a <select multiple> field.
By default QueryDicts are immutable, though the copy() method
will always return a mutable copy.
Both keys and values set on this class are converted from the given encoding
(DEFAULT_CHARSET by default) to str.
"""
# These are both reset in __init__, but is specified here at the class
# level so that unpickling will have valid values
_mutable = True
_encoding = None
def __init__(self, query_string=None, mutable=False, encoding=None):
super().__init__()
self.encoding = encoding or settings.DEFAULT_CHARSET
query_string = query_string or ''
parse_qsl_kwargs = {
'keep_blank_values': True,
'fields_limit': settings.DATA_UPLOAD_MAX_NUMBER_FIELDS,
'encoding': self.encoding,
}
if isinstance(query_string, bytes):
# query_string normally contains URL-encoded data, a subset of ASCII.
try:
query_string = query_string.decode(self.encoding)
except UnicodeDecodeError:
# ... but some user agents are misbehaving :-(
query_string = query_string.decode('iso-8859-1')
for key, value in limited_parse_qsl(query_string, **parse_qsl_kwargs):
self.appendlist(key, value)
self._mutable = mutable
@classmethod
def fromkeys(cls, iterable, value='', mutable=False, encoding=None):
"""
Return a new QueryDict with keys (may be repeated) from an iterable and
values from value.
"""
q = cls('', mutable=True, encoding=encoding)
for key in iterable:
q.appendlist(key, value)
if not mutable:
q._mutable = False
return q
@property
def encoding(self):
if self._encoding is None:
self._encoding = settings.DEFAULT_CHARSET
return self._encoding
@encoding.setter
def encoding(self, value):
self._encoding = value
def _assert_mutable(self):
if not self._mutable:
raise AttributeError("This QueryDict instance is immutable")
def __setitem__(self, key, value):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
value = bytes_to_text(value, self.encoding)
super().__setitem__(key, value)
def __delitem__(self, key):
self._assert_mutable()
super().__delitem__(key)
def __copy__(self):
result = self.__class__('', mutable=True, encoding=self.encoding)
for key, value in self.lists():
result.setlist(key, value)
return result
def __deepcopy__(self, memo):
result = self.__class__('', mutable=True, encoding=self.encoding)
memo[id(self)] = result
for key, value in self.lists():
result.setlist(copy.deepcopy(key, memo), copy.deepcopy(value, memo))
return result
def setlist(self, key, list_):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
list_ = [bytes_to_text(elt, self.encoding) for elt in list_]
super().setlist(key, list_)
def setlistdefault(self, key, default_list=None):
self._assert_mutable()
return super().setlistdefault(key, default_list)
def appendlist(self, key, value):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
value = bytes_to_text(value, self.encoding)
super().appendlist(key, value)
def pop(self, key, *args):
self._assert_mutable()
return super().pop(key, *args)
def popitem(self):
self._assert_mutable()
return super().popitem()
def clear(self):
self._assert_mutable()
super().clear()
def setdefault(self, key, default=None):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
default = bytes_to_text(default, self.encoding)
return super().setdefault(key, default)
def copy(self):
"""Return a mutable copy of this object."""
return self.__deepcopy__({})
def urlencode(self, safe=None):
"""
Return an encoded string of all query string arguments.
`safe` specifies characters which don't require quoting, for example::
>>> q = QueryDict(mutable=True)
>>> q['next'] = '/a&b/'
>>> q.urlencode()
'next=%2Fa%26b%2F'
>>> q.urlencode(safe='/')
'next=/a%26b/'
"""
output = []
if safe:
safe = safe.encode(self.encoding)
def encode(k, v):
return '%s=%s' % ((quote(k, safe), quote(v, safe)))
else:
def encode(k, v):
return urlencode({k: v})
for k, list_ in self.lists():
output.extend(
encode(k.encode(self.encoding), str(v).encode(self.encoding))
for v in list_
)
return '&'.join(output)
class MediaType:
def __init__(self, media_type_raw_line):
full_type, self.params = parse_header(
media_type_raw_line.encode('ascii') if media_type_raw_line else b''
)
self.main_type, _, self.sub_type = full_type.partition('/')
def __str__(self):
params_str = ''.join(
'; %s=%s' % (k, v.decode('ascii'))
for k, v in self.params.items()
)
return '%s%s%s' % (
self.main_type,
('/%s' % self.sub_type) if self.sub_type else '',
params_str,
)
def __repr__(self):
return '<%s: %s>' % (self.__class__.__qualname__, self)
@property
def is_all_types(self):
return self.main_type == '*' and self.sub_type == '*'
def match(self, other):
if self.is_all_types:
return True
other = MediaType(other)
if self.main_type == other.main_type and self.sub_type in {'*', other.sub_type}:
return True
return False
# It's neither necessary nor appropriate to use
# django.utils.encoding.force_str() for parsing URLs and form inputs. Thus,
# this slightly more restricted function, used by QueryDict.
def bytes_to_text(s, encoding):
"""
Convert bytes objects to strings, using the given encoding. Illegally
encoded input characters are replaced with Unicode "unknown" codepoint
(\ufffd).
Return any non-bytes objects without change.
"""
if isinstance(s, bytes):
return str(s, encoding, 'replace')
else:
return s
def split_domain_port(host):
"""
Return a (domain, port) tuple from a given host.
Returned domain is lowercased. If the host is invalid, the domain will be
empty.
"""
host = host.lower()
if not host_validation_re.match(host):
return '', ''
if host[-1] == ']':
# It's an IPv6 address without a port.
return host, ''
bits = host.rsplit(':', 1)
domain, port = bits if len(bits) == 2 else (bits[0], '')
# Remove a trailing dot (if present) from the domain.
domain = domain[:-1] if domain.endswith('.') else domain
return domain, port
def validate_host(host, allowed_hosts):
"""
Validate the given host for this site.
Check that the host looks valid and matches a host or host pattern in the
given list of ``allowed_hosts``. Any pattern beginning with a period
matches a domain and all its subdomains (e.g. ``.example.com`` matches
``example.com`` and any subdomain), ``*`` matches anything, and anything
else must match exactly.
Note: This function assumes that the given host is lowercased and has
already had the port, if any, stripped off.
Return ``True`` for a valid host, ``False`` otherwise.
"""
return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts)
def parse_accept_header(header):
return [MediaType(token) for token in header.split(',') if token.strip()]
| 36.063063
| 110
| 0.616704
|
import cgi
import codecs
import copy
from io import BytesIO
from itertools import chain
from urllib.parse import quote, urlencode, urljoin, urlsplit
from django.conf import settings
from django.core import signing
from django.core.exceptions import (
DisallowedHost, ImproperlyConfigured, RequestDataTooBig,
)
from django.core.files import uploadhandler
from django.http.multipartparser import MultiPartParser, MultiPartParserError
from django.utils.datastructures import (
CaseInsensitiveMapping, ImmutableList, MultiValueDict,
)
from django.utils.encoding import escape_uri_path, iri_to_uri
from django.utils.functional import cached_property
from django.utils.http import is_same_domain, limited_parse_qsl
from django.utils.regex_helper import _lazy_re_compile
from .multipartparser import parse_header
RAISE_ERROR = object()
host_validation_re = _lazy_re_compile(r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])(:\d+)?$")
class UnreadablePostError(OSError):
pass
class RawPostDataException(Exception):
pass
class HttpRequest:
_encoding = None
_upload_handlers = []
def __init__(self):
# Any variable assignment made here should also happen in
# `WSGIRequest.__init__()`.
self.GET = QueryDict(mutable=True)
self.POST = QueryDict(mutable=True)
self.COOKIES = {}
self.META = {}
self.FILES = MultiValueDict()
self.path = ''
self.path_info = ''
self.method = None
self.resolver_match = None
self.content_type = None
self.content_params = None
def __repr__(self):
if self.method is None or not self.get_full_path():
return '<%s>' % self.__class__.__name__
return '<%s: %s %r>' % (self.__class__.__name__, self.method, self.get_full_path())
@cached_property
def headers(self):
return HttpHeaders(self.META)
@cached_property
def accepted_types(self):
return parse_accept_header(self.headers.get('Accept', '*/*'))
def accepts(self, media_type):
return any(
accepted_type.match(media_type)
for accepted_type in self.accepted_types
)
def _set_content_type_params(self, meta):
self.content_type, self.content_params = cgi.parse_header(meta.get('CONTENT_TYPE', ''))
if 'charset' in self.content_params:
try:
codecs.lookup(self.content_params['charset'])
except LookupError:
pass
else:
self.encoding = self.content_params['charset']
def _get_raw_host(self):
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in self.META):
host = self.META['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in self.META:
host = self.META['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = self.META['SERVER_NAME']
server_port = self.get_port()
if server_port != ('443' if self.is_secure() else '80'):
host = '%s:%s' % (host, server_port)
return host
def get_host(self):
host = self._get_raw_host()
# Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
allowed_hosts = settings.ALLOWED_HOSTS
if settings.DEBUG and not allowed_hosts:
allowed_hosts = ['.localhost', '127.0.0.1', '[::1]']
domain, port = split_domain_port(host)
if domain and validate_host(domain, allowed_hosts):
return host
else:
msg = "Invalid HTTP_HOST header: %r." % host
if domain:
msg += " You may need to add %r to ALLOWED_HOSTS." % domain
else:
msg += " The domain name provided is not valid according to RFC 1034/1035."
raise DisallowedHost(msg)
def get_port(self):
if settings.USE_X_FORWARDED_PORT and 'HTTP_X_FORWARDED_PORT' in self.META:
port = self.META['HTTP_X_FORWARDED_PORT']
else:
port = self.META['SERVER_PORT']
return str(port)
def get_full_path(self, force_append_slash=False):
return self._get_full_path(self.path, force_append_slash)
def get_full_path_info(self, force_append_slash=False):
return self._get_full_path(self.path_info, force_append_slash)
def _get_full_path(self, path, force_append_slash):
# RFC 3986 requires query string arguments to be in the ASCII range.
# Rather than crash if this doesn't happen, we encode defensively.
return '%s%s%s' % (
escape_uri_path(path),
'/' if force_append_slash and not path.endswith('/') else '',
('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) if self.META.get('QUERY_STRING', '') else ''
)
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
try:
cookie_value = self.COOKIES[key]
except KeyError:
if default is not RAISE_ERROR:
return default
else:
raise
try:
value = signing.get_cookie_signer(salt=key + salt).unsign(
cookie_value, max_age=max_age)
except signing.BadSignature:
if default is not RAISE_ERROR:
return default
else:
raise
return value
def get_raw_uri(self):
return '{scheme}://{host}{path}'.format(
scheme=self.scheme,
host=self._get_raw_host(),
path=self.get_full_path(),
)
def build_absolute_uri(self, location=None):
if location is None:
location = '//%s' % self.get_full_path()
else:
location = str(location)
bits = urlsplit(location)
if not (bits.scheme and bits.netloc):
# urljoin() as long as no path segments are '.' or '..'.
if (bits.path.startswith('/') and not bits.scheme and not bits.netloc and
'/./' not in bits.path and '/../' not in bits.path):
# If location starts with '//' but has no netloc, reuse the
# schema and netloc from the current request. Strip the double
# slashes and continue as if it wasn't specified.
if location.startswith('//'):
location = location[2:]
location = self._current_scheme_host + location
else:
location = urljoin(self._current_scheme_host + self.path, location)
return iri_to_uri(location)
@cached_property
def _current_scheme_host(self):
return '{}://{}'.format(self.scheme, self.get_host())
def _get_scheme(self):
return 'http'
@property
def scheme(self):
if settings.SECURE_PROXY_SSL_HEADER:
try:
header, secure_value = settings.SECURE_PROXY_SSL_HEADER
except ValueError:
raise ImproperlyConfigured(
'The SECURE_PROXY_SSL_HEADER setting must be a tuple containing two values.'
)
header_value = self.META.get(header)
if header_value is not None:
return 'https' if header_value == secure_value else 'http'
return self._get_scheme()
def is_secure(self):
return self.scheme == 'https'
def is_ajax(self):
return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
@property
def encoding(self):
return self._encoding
@encoding.setter
def encoding(self, val):
self._encoding = val
if hasattr(self, 'GET'):
del self.GET
if hasattr(self, '_post'):
del self._post
def _initialize_handlers(self):
self._upload_handlers = [uploadhandler.load_handler(handler, self)
for handler in settings.FILE_UPLOAD_HANDLERS]
@property
def upload_handlers(self):
if not self._upload_handlers:
self._initialize_handlers()
return self._upload_handlers
@upload_handlers.setter
def upload_handlers(self, upload_handlers):
if hasattr(self, '_files'):
raise AttributeError("You cannot set the upload handlers after the upload has been processed.")
self._upload_handlers = upload_handlers
def parse_file_upload(self, META, post_data):
self.upload_handlers = ImmutableList(
self.upload_handlers,
warning="You cannot alter upload handlers after the upload has been processed."
)
parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
return parser.parse()
@property
def body(self):
if not hasattr(self, '_body'):
if self._read_started:
raise RawPostDataException("You cannot access body after reading from request's data stream")
# Limit the maximum request data size that will be handled in-memory.
if (settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and
int(self.META.get('CONTENT_LENGTH') or 0) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE):
raise RequestDataTooBig('Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.')
try:
self._body = self.read()
except OSError as e:
raise UnreadablePostError(*e.args) from e
self._stream = BytesIO(self._body)
return self._body
def _mark_post_parse_error(self):
self._post = QueryDict()
self._files = MultiValueDict()
def _load_post_and_files(self):
if self.method != 'POST':
self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
return
if self._read_started and not hasattr(self, '_body'):
self._mark_post_parse_error()
return
if self.content_type == 'multipart/form-data':
if hasattr(self, '_body'):
# Use already read data
data = BytesIO(self._body)
else:
data = self
try:
self._post, self._files = self.parse_file_upload(self.META, data)
except MultiPartParserError:
# An error occurred while parsing POST data. Since when
# formatting the error the request handler might access
# self.POST, set self._post and self._file to prevent
# attempts to parse POST data again.
self._mark_post_parse_error()
raise
elif self.content_type == 'application/x-www-form-urlencoded':
self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
else:
self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
def close(self):
if hasattr(self, '_files'):
for f in chain.from_iterable(l[1] for l in self._files.lists()):
f.close()
# File-like and iterator interface.
#
# Expects self._stream to be set to an appropriate source of bytes by
# a corresponding request subclass (e.g. WSGIRequest).
# Also when request data has already been read by request.POST or
# request.body, self._stream points to a BytesIO instance
# containing that data.
def read(self, *args, **kwargs):
self._read_started = True
try:
return self._stream.read(*args, **kwargs)
except OSError as e:
raise UnreadablePostError(*e.args) from e
def readline(self, *args, **kwargs):
self._read_started = True
try:
return self._stream.readline(*args, **kwargs)
except OSError as e:
raise UnreadablePostError(*e.args) from e
def __iter__(self):
return iter(self.readline, b'')
def readlines(self):
return list(self)
class HttpHeaders(CaseInsensitiveMapping):
HTTP_PREFIX = 'HTTP_'
# PEP 333 gives two headers which aren't prepended with HTTP_.
UNPREFIXED_HEADERS = {'CONTENT_TYPE', 'CONTENT_LENGTH'}
def __init__(self, environ):
headers = {}
for header, value in environ.items():
name = self.parse_header_name(header)
if name:
headers[name] = value
super().__init__(headers)
def __getitem__(self, key):
return super().__getitem__(key.replace('_', '-'))
@classmethod
def parse_header_name(cls, header):
if header.startswith(cls.HTTP_PREFIX):
header = header[len(cls.HTTP_PREFIX):]
elif header not in cls.UNPREFIXED_HEADERS:
return None
return header.replace('_', '-').title()
class QueryDict(MultiValueDict):
_mutable = True
_encoding = None
def __init__(self, query_string=None, mutable=False, encoding=None):
super().__init__()
self.encoding = encoding or settings.DEFAULT_CHARSET
query_string = query_string or ''
parse_qsl_kwargs = {
'keep_blank_values': True,
'fields_limit': settings.DATA_UPLOAD_MAX_NUMBER_FIELDS,
'encoding': self.encoding,
}
if isinstance(query_string, bytes):
try:
query_string = query_string.decode(self.encoding)
except UnicodeDecodeError:
query_string = query_string.decode('iso-8859-1')
for key, value in limited_parse_qsl(query_string, **parse_qsl_kwargs):
self.appendlist(key, value)
self._mutable = mutable
@classmethod
def fromkeys(cls, iterable, value='', mutable=False, encoding=None):
q = cls('', mutable=True, encoding=encoding)
for key in iterable:
q.appendlist(key, value)
if not mutable:
q._mutable = False
return q
@property
def encoding(self):
if self._encoding is None:
self._encoding = settings.DEFAULT_CHARSET
return self._encoding
@encoding.setter
def encoding(self, value):
self._encoding = value
def _assert_mutable(self):
if not self._mutable:
raise AttributeError("This QueryDict instance is immutable")
def __setitem__(self, key, value):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
value = bytes_to_text(value, self.encoding)
super().__setitem__(key, value)
def __delitem__(self, key):
self._assert_mutable()
super().__delitem__(key)
def __copy__(self):
result = self.__class__('', mutable=True, encoding=self.encoding)
for key, value in self.lists():
result.setlist(key, value)
return result
def __deepcopy__(self, memo):
result = self.__class__('', mutable=True, encoding=self.encoding)
memo[id(self)] = result
for key, value in self.lists():
result.setlist(copy.deepcopy(key, memo), copy.deepcopy(value, memo))
return result
def setlist(self, key, list_):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
list_ = [bytes_to_text(elt, self.encoding) for elt in list_]
super().setlist(key, list_)
def setlistdefault(self, key, default_list=None):
self._assert_mutable()
return super().setlistdefault(key, default_list)
def appendlist(self, key, value):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
value = bytes_to_text(value, self.encoding)
super().appendlist(key, value)
def pop(self, key, *args):
self._assert_mutable()
return super().pop(key, *args)
def popitem(self):
self._assert_mutable()
return super().popitem()
def clear(self):
self._assert_mutable()
super().clear()
def setdefault(self, key, default=None):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
default = bytes_to_text(default, self.encoding)
return super().setdefault(key, default)
def copy(self):
return self.__deepcopy__({})
def urlencode(self, safe=None):
output = []
if safe:
safe = safe.encode(self.encoding)
def encode(k, v):
return '%s=%s' % ((quote(k, safe), quote(v, safe)))
else:
def encode(k, v):
return urlencode({k: v})
for k, list_ in self.lists():
output.extend(
encode(k.encode(self.encoding), str(v).encode(self.encoding))
for v in list_
)
return '&'.join(output)
class MediaType:
def __init__(self, media_type_raw_line):
full_type, self.params = parse_header(
media_type_raw_line.encode('ascii') if media_type_raw_line else b''
)
self.main_type, _, self.sub_type = full_type.partition('/')
def __str__(self):
params_str = ''.join(
'; %s=%s' % (k, v.decode('ascii'))
for k, v in self.params.items()
)
return '%s%s%s' % (
self.main_type,
('/%s' % self.sub_type) if self.sub_type else '',
params_str,
)
def __repr__(self):
return '<%s: %s>' % (self.__class__.__qualname__, self)
@property
def is_all_types(self):
return self.main_type == '*' and self.sub_type == '*'
def match(self, other):
if self.is_all_types:
return True
other = MediaType(other)
if self.main_type == other.main_type and self.sub_type in {'*', other.sub_type}:
return True
return False
# django.utils.encoding.force_str() for parsing URLs and form inputs. Thus,
# this slightly more restricted function, used by QueryDict.
def bytes_to_text(s, encoding):
if isinstance(s, bytes):
return str(s, encoding, 'replace')
else:
return s
def split_domain_port(host):
host = host.lower()
if not host_validation_re.match(host):
return '', ''
if host[-1] == ']':
# It's an IPv6 address without a port.
return host, ''
bits = host.rsplit(':', 1)
domain, port = bits if len(bits) == 2 else (bits[0], '')
domain = domain[:-1] if domain.endswith('.') else domain
return domain, port
def validate_host(host, allowed_hosts):
return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts)
def parse_accept_header(header):
return [MediaType(token) for token in header.split(',') if token.strip()]
| true
| true
|
790e455dd64429c97352e7ac01408784a583c481
| 1,883
|
py
|
Python
|
src/dinosaur/game/resources.py
|
lukDev/dinosaur
|
a585c64741a1639b520176bb26a611e59e59659d
|
[
"MIT"
] | null | null | null |
src/dinosaur/game/resources.py
|
lukDev/dinosaur
|
a585c64741a1639b520176bb26a611e59e59659d
|
[
"MIT"
] | null | null | null |
src/dinosaur/game/resources.py
|
lukDev/dinosaur
|
a585c64741a1639b520176bb26a611e59e59659d
|
[
"MIT"
] | null | null | null |
import pyglet
class Resources:
# --- Player Parameters ---
player_animation_started = False
player_images = []
player_animation_time = 1. / 9.
player_animation_index = 0
# --- Obstacle Parameters ---
obstacle_images = []
# --- Player Methods ---
# loads the images needed for the player animation if they haven't been loaded already
@staticmethod
def load_images():
if len(Resources.player_images) == 0:
Resources.player_images.append(pyglet.image.load("res/dinosaur_left.png"))
Resources.player_images.append(pyglet.image.load("res/dinosaur_right.png"))
Resources.player_images.append(pyglet.image.load("res/dinosaur_normal.png"))
if len(Resources.obstacle_images) == 0:
Resources.obstacle_images.append(pyglet.image.load("res/cactus_small.png"))
Resources.obstacle_images.append(pyglet.image.load("res/cactus_big.png"))
Resources.start_player_animation()
# starts the player's running animation by scheduling recurring updates to the player's image index
@staticmethod
def start_player_animation():
if not Resources.player_animation_started:
pyglet.clock.schedule_interval(Resources.trigger_player_update, Resources.player_animation_time)
Resources.player_animation_started = True
# updates the player's image index
@staticmethod
def trigger_player_update(_):
Resources.player_animation_index = 1 - Resources.player_animation_index
# returns the current image for the running player
@staticmethod
def player_running_image():
return Resources.player_images[Resources.player_animation_index]
# returns the image for the jumping player
@staticmethod
def player_jumping_image():
return Resources.player_images[2]
| 36.211538
| 108
| 0.698885
|
import pyglet
class Resources:
player_animation_started = False
player_images = []
player_animation_time = 1. / 9.
player_animation_index = 0
obstacle_images = []
@staticmethod
def load_images():
if len(Resources.player_images) == 0:
Resources.player_images.append(pyglet.image.load("res/dinosaur_left.png"))
Resources.player_images.append(pyglet.image.load("res/dinosaur_right.png"))
Resources.player_images.append(pyglet.image.load("res/dinosaur_normal.png"))
if len(Resources.obstacle_images) == 0:
Resources.obstacle_images.append(pyglet.image.load("res/cactus_small.png"))
Resources.obstacle_images.append(pyglet.image.load("res/cactus_big.png"))
Resources.start_player_animation()
# starts the player's running animation by scheduling recurring updates to the player's image index
@staticmethod
def start_player_animation():
if not Resources.player_animation_started:
pyglet.clock.schedule_interval(Resources.trigger_player_update, Resources.player_animation_time)
Resources.player_animation_started = True
# updates the player's image index
@staticmethod
def trigger_player_update(_):
Resources.player_animation_index = 1 - Resources.player_animation_index
@staticmethod
def player_running_image():
return Resources.player_images[Resources.player_animation_index]
@staticmethod
def player_jumping_image():
return Resources.player_images[2]
| true
| true
|
790e46918dd184f2c67478851f1a3679fe32bcd1
| 22,303
|
py
|
Python
|
olo/query.py
|
kadaliao/olo
|
29763264aec641e50448fc5f606244b7db3d5ad4
|
[
"Apache-2.0"
] | null | null | null |
olo/query.py
|
kadaliao/olo
|
29763264aec641e50448fc5f606244b7db3d5ad4
|
[
"Apache-2.0"
] | 1
|
2022-01-18T10:23:08.000Z
|
2022-01-18T10:23:08.000Z
|
olo/query.py
|
kadaliao/olo
|
29763264aec641e50448fc5f606244b7db3d5ad4
|
[
"Apache-2.0"
] | null | null | null |
from __future__ import annotations
import operator
import re
import sys
import types
from enum import Enum
from typing import TYPE_CHECKING, Optional, List, Union, Iterable, Type, Tuple
from olo.expression import UnaryExpression, BinaryExpression, Expression
from olo.funcs import DISTINCT, Function
if TYPE_CHECKING:
from olo.database import OLOCursor
from olo.model import Model, ModelMeta
from itertools import chain
from decorator import decorator
from olo.compat import izip, imap, str_types, iteritems, reduce
from olo.interfaces import SQLASTInterface
from olo.field import Field
from olo.errors import ExpressionError, OrderByError, SupportError, ORMError
from olo.libs.compiler.translators.func_translator import transform_func
from olo.session import QuerySession
from olo.utils import optimize_sql_ast, friendly_repr
PATTERN_NEG = re.compile(r'^\-')
PATTERN_BACKQUOTE = re.compile('^`(?P<name>.*)`$')
def _strip_backquote(s):
m = PATTERN_BACKQUOTE.search(s)
if not m:
return s
return m.group('name') # pragma: no cover
def _dict_to_expressions(model_class, dct):
return [
getattr(model_class, k) == v
for k, v in iteritems(dct)
]
def _process_order_by(model_class, order_by) -> List[UnaryExpression]:
new = []
for item in order_by:
if isinstance(item, str_types):
_item = item
_item = _strip_backquote(_item)
is_negative = bool(PATTERN_NEG.search(_item))
if is_negative:
_item = PATTERN_NEG.sub('', _item)
else:
_item, _, sort = _item.partition(' ')
is_negative = sort.lower() == 'desc'
if sort:
_item = _strip_backquote(_item)
f = getattr(model_class, _item, None)
if f is None:
raise OrderByError('`{}` is an invalid order_by'.format( # noqa pragma: no cover pylint: disable=W
item
))
item = f
item = item.desc() if is_negative else item.asc()
elif isinstance(item, Field):
item = item.asc()
elif not isinstance(item, UnaryExpression):
raise OrderByError('`{}` is an invalid order_by'.format( # noqa pragma: no cover pylint: disable=W
item
))
new.append(item)
return new
@decorator
def _lambda_eval(func, self, *args, **kwargs):
if len(args) == 1 and isinstance(args[0], types.FunctionType):
lamb = transform_func(args[0])
return func(self, lamb(self._model_class), **kwargs)
return func(self, *args, **kwargs)
def _check_aggregation(exp: Expression) -> bool:
if isinstance(exp, BinaryExpression):
if isinstance(exp.left, Function):
return True
if isinstance(exp.right, Function):
return True
if isinstance(exp.left, Expression) and _check_aggregation(exp.left):
return True
if isinstance(exp.right, Expression) and _check_aggregation(exp.right):
return True
return False
def _split_where_expression_and_having_expression(expression: BinaryExpression) -> Tuple[Optional[BinaryExpression],
Optional[BinaryExpression]]:
stack = [expression]
and_expressions = []
while stack:
exp = stack.pop()
if exp is None:
continue
if exp.operator == 'AND':
stack.append(exp.right)
stack.append(exp.left)
continue
and_expressions.append(exp)
where_expressions = []
having_expressions = []
for exp in and_expressions:
if _check_aggregation(exp):
having_expressions.append(exp)
else:
where_expressions.append(exp)
where_expression = None
having_expression = None
if where_expressions:
where_expression = reduce(operator.and_, where_expressions)
if having_expressions:
having_expression = reduce(operator.and_, having_expressions)
return where_expression, having_expression
class JoinType(Enum):
INNER = 0
LEFT = 1
RIGHT = 2
FULL = 3
class JoinChain(SQLASTInterface):
on_: Optional[BinaryExpression]
def __init__(self, type_: JoinType, left: Union[Model, JoinChain], right: Model) -> None:
self.type = type_
self.left = left
self.right = right
self.on_ = None
def on(self, on: BinaryExpression) -> None:
if self.on_ is None:
self.on_ = on
return
self.on_ = self.on_ & on
def get_sql_ast(self) -> List:
from olo.model import Model
if isinstance(self.left, type) and issubclass(self.left, Model):
left_ast = ['TABLE', self.left._get_table_name()]
else:
left_ast = self.left.get_sql_ast()
on_ast = self.on_.get_sql_ast() if self.on_ else []
return ['JOIN', self.type.name, left_ast, ['TABLE', self.right._get_table_name()], on_ast]
def clone(self) -> JoinChain:
cloned = JoinChain(self.type, self.left, self.right)
cloned.on(self.on_)
return cloned
if TYPE_CHECKING:
Entity = Union[Type[Model], Field, Function]
class Query(SQLASTInterface):
def __init__(self, model_class: Type[Model]):
self._model_class = model_class
self._expression: Optional[BinaryExpression] = None
self._having_expression: Optional[BinaryExpression] = None
self._offset = 0
self._limit = None
self._order_by: List[UnaryExpression] = []
self._group_by = []
self._entities: List[Entity] = [model_class]
self._raw = False
self._join_chain: Optional[JoinChain] = None
self._for_update = False
def _update(self, **kwargs):
inst = self.__class__(self._model_class)
inst.__dict__.update(self.__dict__)
inst.__dict__.update(kwargs)
return inst
def _get_entities(self, fields: Iterable[Union[Entity, str]]) -> List[Entity]:
from olo.model import ModelMeta
if not isinstance(fields, (list, tuple, set)):
fields = [fields]
res = []
for field in fields:
if isinstance(field, str_types):
field_ = self._model_class._olo_get_field(field)
if field_ is None:
raise ORMError(f'{friendly_repr(field)} is not a valid field in Model {self._model_class.__name__}')
field = field_
if not isinstance(field, (ModelMeta, Field, Function)):
raise ORMError(f'{field} is an not valid entity!')
res.append(field)
return res
@_lambda_eval
def map(self, *entities: Union[Entity, str], **kwargs):
from olo.model import ModelMeta
self._raw = kwargs.get('raw', False)
entities = self._get_entities(entities)
q = self._update(_entities=list(
chain.from_iterable(
x if isinstance(x, (list, tuple, set)) else (x,)
for x in entities
)
))
has_aggregation = False
first_field = None
for entity in q._entities:
if isinstance(entity, ModelMeta) and first_field is None:
first_field = self._model_class.get_singleness_pk_field()
if isinstance(entity, Field) and first_field is None:
first_field = entity
if isinstance(entity, Function):
has_aggregation = True
if has_aggregation and first_field is not None:
q = q.group_by(first_field)
return q
def __call__(self, *entities, **kwargs):
return self.map(*entities, **kwargs)
@_lambda_eval
def flat_map(self, query):
return self.join(query._model_class).on(
query._expression
).map(*query._entities)
def __getitem__(self, item):
if isinstance(item, slice):
q = self
start = item.start or 0
stop = item.stop
step = item.step
if step is not None:
raise SupportError(
'Cannot support step in __getitem__ now!'
)
if start:
q = q.offset(start)
if stop is not None and (start or stop != sys.maxsize):
q = q.limit(stop - start)
return q.all()
field = self._model_class.get_singleness_pk_field()
return self.filter(field == item).first()
@property
def db(self):
return self._model_class._get_db()
@property
def cq(self):
return self
query = cq
@_lambda_eval
def join(self, model_class):
left = self._join_chain if self._join_chain is not None else self._model_class
return self._update(_join_chain=JoinChain(JoinType.INNER, left, model_class))
@_lambda_eval
def left_join(self, model_class):
left = self._join_chain if self._join_chain is not None else self._model_class
return self._update(_join_chain=JoinChain(JoinType.LEFT, left, model_class))
@_lambda_eval
def right_join(self, model_class):
left = self._join_chain if self._join_chain is not None else self._model_class
return self._update(_join_chain=JoinChain(JoinType.RIGHT, left, model_class))
@_lambda_eval
def full_join(self, model_class):
left = self._join_chain if self._join_chain is not None else self._model_class
return self._update(_join_chain=JoinChain(JoinType.FULL, left, model_class))
@_lambda_eval
def filter(self, *expressions, **expression_dict):
self._model_class._check_attrs(expression_dict)
expression_dict = self._model_class._wash_attrs(
expression_dict
)
expressions = list(expressions) + list(
_dict_to_expressions(
self._model_class, expression_dict
)
)
expression = self._expression
if expressions:
_expression = reduce(
operator.and_,
expressions,
)
if expression is not None:
expression &= _expression
else:
expression = _expression
expression, having_expression = _split_where_expression_and_having_expression(expression)
q = self
if expression is not None:
q = q._update(_expression=expression)
if having_expression is not None:
q = q.having(having_expression)
return q
@_lambda_eval
def on(self, *on_expressions, **on_expression_dict):
if self._join_chain is None:
raise ORMError('this query does not have a join chain!')
self._model_class._check_attrs(on_expression_dict)
on_expression_dict = self._model_class._wash_attrs(
on_expression_dict
)
on_expressions = list(on_expressions) + list(
_dict_to_expressions(
self._model_class, on_expression_dict
)
)
on_expression = reduce(
operator.and_,
on_expressions
)
join_chain = self._join_chain.clone()
join_chain.on(on_expression)
return self._update(_join_chain=join_chain)
@_lambda_eval
def having(self, *having_expressions, **having_expression_dict):
self._model_class._check_attrs(having_expression_dict)
having_expression_dict = self._model_class._wash_attrs(
having_expression_dict
)
having_expressions = (
list(having_expressions) + list(
_dict_to_expressions(
self._model_class, having_expression_dict
)
)
)
q = self
if having_expressions:
having_expression = reduce(operator.and_, having_expressions)
if self._having_expression is not None:
having_expression = self._having_expression & having_expression
q = q._update(_having_expression=having_expression)
return q
def for_update(self):
return self._update(_for_update=True)
def offset(self, offset):
return self._update(_offset=offset)
def limit(self, limit):
return self._update(_limit=limit)
def order_by(self, *order_by):
order_by = _process_order_by(self._model_class, order_by)
_order_by = self._order_by + list(order_by)
return self._update(_order_by=_order_by)
def group_by(self, *group_by):
_group_by = self._group_by + list(group_by)
return self._update(_group_by=_group_by)
def first(self):
res = self.limit(1).all()
return res[0] if res else None
one = first
def __iter__(self):
rv = self._get_rv()
return self._iter_wrap_rv(rv)
def all(self):
return list(self.__iter__())
def count(self):
from olo.funcs import COUNT
return COUNT(self).first() # pylint: disable=E1101
def count_and_all(self):
base_sql_ast = self._get_base_sql_ast(
modifier='SQL_CALC_FOUND_ROWS'
)
with self.db.transaction():
cursor = self.db.get_cursor()
rv = self._get_rv(base_sql_ast=base_sql_ast,
cursor=cursor)
cursor.ast_execute(['SELECT', ['CALL', 'FOUND_ROWS']])
count = cursor.fetchone()[0]
items = list(self._iter_wrap_rv(rv))
return count, items
__len__ = count
def update(self, **values):
from olo import PostgreSQLDataBase
expression = self._get_expression()
if not expression:
raise ExpressionError('Cannot execute update because of '
'without expression')
assignments, _, _ = self._model_class._split_attrs(values)
update_sql_ast = [
'UPDATE',
['TABLE', self.table_name],
['SET',
['SERIES'] + [asg.get_sql_ast() for asg in assignments]],
]
db = self._model_class._get_db()
# FIXME(PG)
if isinstance(db, PostgreSQLDataBase):
pk = self._model_class.get_singleness_pk_field()
if self._order_by:
base_sql_ast = self.map(pk).for_update()._get_base_sql_ast()
sql_ast = self.get_sql_ast(
base_sql_ast=base_sql_ast,
)
update_sql_ast.append(
['WHERE', ['BINARY_OPERATE', 'IN', ['QUOTE', pk.name], ['BRACKET', sql_ast]]]
)
with self.db.transaction():
rows = self._get_rv_by_sql_ast(sql_ast=update_sql_ast)
else:
with self.db.transaction():
rows = self._get_rv(base_sql_ast=update_sql_ast)
else:
with self.db.transaction():
rows = self._get_rv(base_sql_ast=update_sql_ast)
return rows
def delete(self):
expression = self._get_expression()
if not expression:
raise ExpressionError('Cannot execute delete because of '
'without expression')
sql_ast = [
'DELETE',
['TABLE', self.table_name]
]
with self.db.transaction():
rows = self._get_rv(base_sql_ast=sql_ast)
return rows
@property
def table_name(self):
return self._model_class._get_table_name()
def _get_rv(self, base_sql_ast=None,
cursor=None):
return self.__get_rv(
base_sql_ast=base_sql_ast,
cursor=cursor,
)
def __get_rv(self, base_sql_ast=None,
cursor=None):
sql_ast = self.get_sql_ast(
base_sql_ast=base_sql_ast,
)
return self._get_rv_by_sql_ast(sql_ast, cursor=cursor)
def _get_rv_by_sql_ast(self, sql_ast, cursor: Optional[OLOCursor] = None):
if cursor is not None:
cursor.ast_execute(sql_ast)
return cursor.fetchall()
with self.db.transaction():
return self.db.ast_execute(sql_ast)
def get_sql_ast(self, base_sql_ast=None):
sql_ast = self.get_primitive_sql_ast(
base_sql_ast=base_sql_ast)
return optimize_sql_ast(sql_ast)
def get_primitive_sql_ast(self, base_sql_ast=None):
if base_sql_ast is None:
base_sql_ast = self._get_base_sql_ast()
return self._get_primitive_sql_ast(base_sql_ast)
def _entities_contains(self, field):
if len(self._entities) == 1 and self._entities[0] is self._model_class:
return True
for f in self._entities:
# f == field will return an Expression object, so must compare with True explicitly
if (f == field) is True:
return True
if getattr(f, 'name', 'f.name') == getattr(field, 'name', 'field.name'):
return True
return False
def _get_primitive_sql_ast(self, base_sql_ast):
sql_ast = list(base_sql_ast) # copy ast
if self._expression is not None:
sql_ast.append([
'WHERE',
self._expression.get_sql_ast()
])
if self._having_expression is not None and not self._group_by:
group_by = []
for entity in self._entities:
if entity is self._model_class:
pk = self._model_class.get_singleness_pk_field()
group_by.append(pk)
break
if isinstance(entity, Field):
group_by.append(entity)
self._group_by = group_by
if self._group_by:
entities = self._get_entities(self._group_by)
field_names = {getattr(f, 'name', '') for f in entities}
pk = self._model_class.get_singleness_pk_field()
# self._entities must casting to set or pk in self._entities will always be True!!!
if self._entities_contains(pk) and pk.name not in field_names:
entities.append(pk)
sql_ast.append([
'GROUP BY',
['SERIES'] + [f.get_sql_ast() for f in entities]
])
if self._having_expression is not None:
sql_ast.append([
'HAVING',
self._having_expression.get_sql_ast()
])
if self._order_by:
sql_ast.append([
'ORDER BY',
['SERIES'] + [f.get_sql_ast() for f in self._order_by]
])
if self._limit is not None:
limit_section = ['LIMIT', None, ['VALUE', self._limit]]
if self._offset is not None and self._offset != 0:
limit_section[1] = ['VALUE', self._offset]
sql_ast.append(limit_section)
if self._for_update:
sql_ast.append(['FOR UPDATE'])
return sql_ast
def _get_expression(self, is_having=False):
return self._having_expression if is_having else self._expression
def _get_base_sql_ast(self, modifier=None, entities=None):
entities = self._entities if entities is None else entities
if self._join_chain:
table_section = self._join_chain.get_sql_ast()
else:
table_section = ['TABLE', self.table_name]
contains_distinct = any(isinstance(entity, DISTINCT) for entity in entities)
# FIXME(PG)
if contains_distinct and self._order_by:
for ob in self._order_by:
if not self._entities_contains(ob.value):
entities = entities + [ob.value]
select_ast = [
'SERIES',
] + [e.get_sql_ast() if hasattr(e, 'get_sql_ast') else e
for e in entities]
if len(select_ast) == 2 and select_ast[1][0] == 'SERIES':
select_ast = select_ast[1]
if modifier is not None:
select_ast = ['MODIFIER', modifier, select_ast]
return ['SELECT', select_ast, ['FROM', table_section]]
# pylint: disable=E0602
def _iter_wrap_rv(self, rv):
from olo.model import ModelMeta
entity_count = len(self._entities)
raw = self._raw
producers = []
idx = -1
def make_field_producer(idx, v):
def producer(item):
if raw:
return item[idx]
model = v.get_model()
attrs = model._parse_attrs({
v.attr_name: item[idx]
})
return attrs[v.attr_name]
return producer
for v in self._entities:
idx += 1
if isinstance(v, ModelMeta):
fields_count = len(v.__fields__)
producers.append((
lambda idx, v:
lambda item: v._olo_instantiate(**dict(
izip(
v.__sorted_fields__,
item[idx: idx + fields_count]
) # pylint: disable=W
))
)(idx, v))
idx += fields_count - 1
continue
if isinstance(v, Field):
producers.append(make_field_producer(idx, v))
continue
producers.append((
lambda idx, v:
lambda item: item[idx]
)(idx, v))
session = QuerySession()
seen = set()
for idx, item in enumerate(rv):
new_item = tuple(imap(lambda f: f(item), producers)) # noqa pylint: disable=W
new_item = new_item[:entity_count]
if entity_count == 1:
new_item = new_item[0]
# TODO
if isinstance(self._entities[0], DISTINCT):
if new_item in seen:
continue
seen.add(new_item)
session.add_entity(new_item)
for entity in session.entities:
yield entity
| 32.464338
| 120
| 0.584092
|
from __future__ import annotations
import operator
import re
import sys
import types
from enum import Enum
from typing import TYPE_CHECKING, Optional, List, Union, Iterable, Type, Tuple
from olo.expression import UnaryExpression, BinaryExpression, Expression
from olo.funcs import DISTINCT, Function
if TYPE_CHECKING:
from olo.database import OLOCursor
from olo.model import Model, ModelMeta
from itertools import chain
from decorator import decorator
from olo.compat import izip, imap, str_types, iteritems, reduce
from olo.interfaces import SQLASTInterface
from olo.field import Field
from olo.errors import ExpressionError, OrderByError, SupportError, ORMError
from olo.libs.compiler.translators.func_translator import transform_func
from olo.session import QuerySession
from olo.utils import optimize_sql_ast, friendly_repr
PATTERN_NEG = re.compile(r'^\-')
PATTERN_BACKQUOTE = re.compile('^`(?P<name>.*)`$')
def _strip_backquote(s):
m = PATTERN_BACKQUOTE.search(s)
if not m:
return s
return m.group('name')
def _dict_to_expressions(model_class, dct):
return [
getattr(model_class, k) == v
for k, v in iteritems(dct)
]
def _process_order_by(model_class, order_by) -> List[UnaryExpression]:
new = []
for item in order_by:
if isinstance(item, str_types):
_item = item
_item = _strip_backquote(_item)
is_negative = bool(PATTERN_NEG.search(_item))
if is_negative:
_item = PATTERN_NEG.sub('', _item)
else:
_item, _, sort = _item.partition(' ')
is_negative = sort.lower() == 'desc'
if sort:
_item = _strip_backquote(_item)
f = getattr(model_class, _item, None)
if f is None:
raise OrderByError('`{}` is an invalid order_by'.format(
item
))
item = f
item = item.desc() if is_negative else item.asc()
elif isinstance(item, Field):
item = item.asc()
elif not isinstance(item, UnaryExpression):
raise OrderByError('`{}` is an invalid order_by'.format(
item
))
new.append(item)
return new
@decorator
def _lambda_eval(func, self, *args, **kwargs):
if len(args) == 1 and isinstance(args[0], types.FunctionType):
lamb = transform_func(args[0])
return func(self, lamb(self._model_class), **kwargs)
return func(self, *args, **kwargs)
def _check_aggregation(exp: Expression) -> bool:
if isinstance(exp, BinaryExpression):
if isinstance(exp.left, Function):
return True
if isinstance(exp.right, Function):
return True
if isinstance(exp.left, Expression) and _check_aggregation(exp.left):
return True
if isinstance(exp.right, Expression) and _check_aggregation(exp.right):
return True
return False
def _split_where_expression_and_having_expression(expression: BinaryExpression) -> Tuple[Optional[BinaryExpression],
Optional[BinaryExpression]]:
stack = [expression]
and_expressions = []
while stack:
exp = stack.pop()
if exp is None:
continue
if exp.operator == 'AND':
stack.append(exp.right)
stack.append(exp.left)
continue
and_expressions.append(exp)
where_expressions = []
having_expressions = []
for exp in and_expressions:
if _check_aggregation(exp):
having_expressions.append(exp)
else:
where_expressions.append(exp)
where_expression = None
having_expression = None
if where_expressions:
where_expression = reduce(operator.and_, where_expressions)
if having_expressions:
having_expression = reduce(operator.and_, having_expressions)
return where_expression, having_expression
class JoinType(Enum):
INNER = 0
LEFT = 1
RIGHT = 2
FULL = 3
class JoinChain(SQLASTInterface):
on_: Optional[BinaryExpression]
def __init__(self, type_: JoinType, left: Union[Model, JoinChain], right: Model) -> None:
self.type = type_
self.left = left
self.right = right
self.on_ = None
def on(self, on: BinaryExpression) -> None:
if self.on_ is None:
self.on_ = on
return
self.on_ = self.on_ & on
def get_sql_ast(self) -> List:
from olo.model import Model
if isinstance(self.left, type) and issubclass(self.left, Model):
left_ast = ['TABLE', self.left._get_table_name()]
else:
left_ast = self.left.get_sql_ast()
on_ast = self.on_.get_sql_ast() if self.on_ else []
return ['JOIN', self.type.name, left_ast, ['TABLE', self.right._get_table_name()], on_ast]
def clone(self) -> JoinChain:
cloned = JoinChain(self.type, self.left, self.right)
cloned.on(self.on_)
return cloned
if TYPE_CHECKING:
Entity = Union[Type[Model], Field, Function]
class Query(SQLASTInterface):
def __init__(self, model_class: Type[Model]):
self._model_class = model_class
self._expression: Optional[BinaryExpression] = None
self._having_expression: Optional[BinaryExpression] = None
self._offset = 0
self._limit = None
self._order_by: List[UnaryExpression] = []
self._group_by = []
self._entities: List[Entity] = [model_class]
self._raw = False
self._join_chain: Optional[JoinChain] = None
self._for_update = False
def _update(self, **kwargs):
inst = self.__class__(self._model_class)
inst.__dict__.update(self.__dict__)
inst.__dict__.update(kwargs)
return inst
def _get_entities(self, fields: Iterable[Union[Entity, str]]) -> List[Entity]:
from olo.model import ModelMeta
if not isinstance(fields, (list, tuple, set)):
fields = [fields]
res = []
for field in fields:
if isinstance(field, str_types):
field_ = self._model_class._olo_get_field(field)
if field_ is None:
raise ORMError(f'{friendly_repr(field)} is not a valid field in Model {self._model_class.__name__}')
field = field_
if not isinstance(field, (ModelMeta, Field, Function)):
raise ORMError(f'{field} is an not valid entity!')
res.append(field)
return res
@_lambda_eval
def map(self, *entities: Union[Entity, str], **kwargs):
from olo.model import ModelMeta
self._raw = kwargs.get('raw', False)
entities = self._get_entities(entities)
q = self._update(_entities=list(
chain.from_iterable(
x if isinstance(x, (list, tuple, set)) else (x,)
for x in entities
)
))
has_aggregation = False
first_field = None
for entity in q._entities:
if isinstance(entity, ModelMeta) and first_field is None:
first_field = self._model_class.get_singleness_pk_field()
if isinstance(entity, Field) and first_field is None:
first_field = entity
if isinstance(entity, Function):
has_aggregation = True
if has_aggregation and first_field is not None:
q = q.group_by(first_field)
return q
def __call__(self, *entities, **kwargs):
return self.map(*entities, **kwargs)
@_lambda_eval
def flat_map(self, query):
return self.join(query._model_class).on(
query._expression
).map(*query._entities)
def __getitem__(self, item):
if isinstance(item, slice):
q = self
start = item.start or 0
stop = item.stop
step = item.step
if step is not None:
raise SupportError(
'Cannot support step in __getitem__ now!'
)
if start:
q = q.offset(start)
if stop is not None and (start or stop != sys.maxsize):
q = q.limit(stop - start)
return q.all()
field = self._model_class.get_singleness_pk_field()
return self.filter(field == item).first()
@property
def db(self):
return self._model_class._get_db()
@property
def cq(self):
return self
query = cq
@_lambda_eval
def join(self, model_class):
left = self._join_chain if self._join_chain is not None else self._model_class
return self._update(_join_chain=JoinChain(JoinType.INNER, left, model_class))
@_lambda_eval
def left_join(self, model_class):
left = self._join_chain if self._join_chain is not None else self._model_class
return self._update(_join_chain=JoinChain(JoinType.LEFT, left, model_class))
@_lambda_eval
def right_join(self, model_class):
left = self._join_chain if self._join_chain is not None else self._model_class
return self._update(_join_chain=JoinChain(JoinType.RIGHT, left, model_class))
@_lambda_eval
def full_join(self, model_class):
left = self._join_chain if self._join_chain is not None else self._model_class
return self._update(_join_chain=JoinChain(JoinType.FULL, left, model_class))
@_lambda_eval
def filter(self, *expressions, **expression_dict):
self._model_class._check_attrs(expression_dict)
expression_dict = self._model_class._wash_attrs(
expression_dict
)
expressions = list(expressions) + list(
_dict_to_expressions(
self._model_class, expression_dict
)
)
expression = self._expression
if expressions:
_expression = reduce(
operator.and_,
expressions,
)
if expression is not None:
expression &= _expression
else:
expression = _expression
expression, having_expression = _split_where_expression_and_having_expression(expression)
q = self
if expression is not None:
q = q._update(_expression=expression)
if having_expression is not None:
q = q.having(having_expression)
return q
@_lambda_eval
def on(self, *on_expressions, **on_expression_dict):
if self._join_chain is None:
raise ORMError('this query does not have a join chain!')
self._model_class._check_attrs(on_expression_dict)
on_expression_dict = self._model_class._wash_attrs(
on_expression_dict
)
on_expressions = list(on_expressions) + list(
_dict_to_expressions(
self._model_class, on_expression_dict
)
)
on_expression = reduce(
operator.and_,
on_expressions
)
join_chain = self._join_chain.clone()
join_chain.on(on_expression)
return self._update(_join_chain=join_chain)
@_lambda_eval
def having(self, *having_expressions, **having_expression_dict):
self._model_class._check_attrs(having_expression_dict)
having_expression_dict = self._model_class._wash_attrs(
having_expression_dict
)
having_expressions = (
list(having_expressions) + list(
_dict_to_expressions(
self._model_class, having_expression_dict
)
)
)
q = self
if having_expressions:
having_expression = reduce(operator.and_, having_expressions)
if self._having_expression is not None:
having_expression = self._having_expression & having_expression
q = q._update(_having_expression=having_expression)
return q
def for_update(self):
return self._update(_for_update=True)
def offset(self, offset):
return self._update(_offset=offset)
def limit(self, limit):
return self._update(_limit=limit)
def order_by(self, *order_by):
order_by = _process_order_by(self._model_class, order_by)
_order_by = self._order_by + list(order_by)
return self._update(_order_by=_order_by)
def group_by(self, *group_by):
_group_by = self._group_by + list(group_by)
return self._update(_group_by=_group_by)
def first(self):
res = self.limit(1).all()
return res[0] if res else None
one = first
def __iter__(self):
rv = self._get_rv()
return self._iter_wrap_rv(rv)
def all(self):
return list(self.__iter__())
def count(self):
from olo.funcs import COUNT
return COUNT(self).first()
def count_and_all(self):
base_sql_ast = self._get_base_sql_ast(
modifier='SQL_CALC_FOUND_ROWS'
)
with self.db.transaction():
cursor = self.db.get_cursor()
rv = self._get_rv(base_sql_ast=base_sql_ast,
cursor=cursor)
cursor.ast_execute(['SELECT', ['CALL', 'FOUND_ROWS']])
count = cursor.fetchone()[0]
items = list(self._iter_wrap_rv(rv))
return count, items
__len__ = count
def update(self, **values):
from olo import PostgreSQLDataBase
expression = self._get_expression()
if not expression:
raise ExpressionError('Cannot execute update because of '
'without expression')
assignments, _, _ = self._model_class._split_attrs(values)
update_sql_ast = [
'UPDATE',
['TABLE', self.table_name],
['SET',
['SERIES'] + [asg.get_sql_ast() for asg in assignments]],
]
db = self._model_class._get_db()
if isinstance(db, PostgreSQLDataBase):
pk = self._model_class.get_singleness_pk_field()
if self._order_by:
base_sql_ast = self.map(pk).for_update()._get_base_sql_ast()
sql_ast = self.get_sql_ast(
base_sql_ast=base_sql_ast,
)
update_sql_ast.append(
['WHERE', ['BINARY_OPERATE', 'IN', ['QUOTE', pk.name], ['BRACKET', sql_ast]]]
)
with self.db.transaction():
rows = self._get_rv_by_sql_ast(sql_ast=update_sql_ast)
else:
with self.db.transaction():
rows = self._get_rv(base_sql_ast=update_sql_ast)
else:
with self.db.transaction():
rows = self._get_rv(base_sql_ast=update_sql_ast)
return rows
def delete(self):
expression = self._get_expression()
if not expression:
raise ExpressionError('Cannot execute delete because of '
'without expression')
sql_ast = [
'DELETE',
['TABLE', self.table_name]
]
with self.db.transaction():
rows = self._get_rv(base_sql_ast=sql_ast)
return rows
@property
def table_name(self):
return self._model_class._get_table_name()
def _get_rv(self, base_sql_ast=None,
cursor=None):
return self.__get_rv(
base_sql_ast=base_sql_ast,
cursor=cursor,
)
def __get_rv(self, base_sql_ast=None,
cursor=None):
sql_ast = self.get_sql_ast(
base_sql_ast=base_sql_ast,
)
return self._get_rv_by_sql_ast(sql_ast, cursor=cursor)
def _get_rv_by_sql_ast(self, sql_ast, cursor: Optional[OLOCursor] = None):
if cursor is not None:
cursor.ast_execute(sql_ast)
return cursor.fetchall()
with self.db.transaction():
return self.db.ast_execute(sql_ast)
def get_sql_ast(self, base_sql_ast=None):
sql_ast = self.get_primitive_sql_ast(
base_sql_ast=base_sql_ast)
return optimize_sql_ast(sql_ast)
def get_primitive_sql_ast(self, base_sql_ast=None):
if base_sql_ast is None:
base_sql_ast = self._get_base_sql_ast()
return self._get_primitive_sql_ast(base_sql_ast)
def _entities_contains(self, field):
if len(self._entities) == 1 and self._entities[0] is self._model_class:
return True
for f in self._entities:
if (f == field) is True:
return True
if getattr(f, 'name', 'f.name') == getattr(field, 'name', 'field.name'):
return True
return False
def _get_primitive_sql_ast(self, base_sql_ast):
sql_ast = list(base_sql_ast)
if self._expression is not None:
sql_ast.append([
'WHERE',
self._expression.get_sql_ast()
])
if self._having_expression is not None and not self._group_by:
group_by = []
for entity in self._entities:
if entity is self._model_class:
pk = self._model_class.get_singleness_pk_field()
group_by.append(pk)
break
if isinstance(entity, Field):
group_by.append(entity)
self._group_by = group_by
if self._group_by:
entities = self._get_entities(self._group_by)
field_names = {getattr(f, 'name', '') for f in entities}
pk = self._model_class.get_singleness_pk_field()
if self._entities_contains(pk) and pk.name not in field_names:
entities.append(pk)
sql_ast.append([
'GROUP BY',
['SERIES'] + [f.get_sql_ast() for f in entities]
])
if self._having_expression is not None:
sql_ast.append([
'HAVING',
self._having_expression.get_sql_ast()
])
if self._order_by:
sql_ast.append([
'ORDER BY',
['SERIES'] + [f.get_sql_ast() for f in self._order_by]
])
if self._limit is not None:
limit_section = ['LIMIT', None, ['VALUE', self._limit]]
if self._offset is not None and self._offset != 0:
limit_section[1] = ['VALUE', self._offset]
sql_ast.append(limit_section)
if self._for_update:
sql_ast.append(['FOR UPDATE'])
return sql_ast
def _get_expression(self, is_having=False):
return self._having_expression if is_having else self._expression
def _get_base_sql_ast(self, modifier=None, entities=None):
entities = self._entities if entities is None else entities
if self._join_chain:
table_section = self._join_chain.get_sql_ast()
else:
table_section = ['TABLE', self.table_name]
contains_distinct = any(isinstance(entity, DISTINCT) for entity in entities)
if contains_distinct and self._order_by:
for ob in self._order_by:
if not self._entities_contains(ob.value):
entities = entities + [ob.value]
select_ast = [
'SERIES',
] + [e.get_sql_ast() if hasattr(e, 'get_sql_ast') else e
for e in entities]
if len(select_ast) == 2 and select_ast[1][0] == 'SERIES':
select_ast = select_ast[1]
if modifier is not None:
select_ast = ['MODIFIER', modifier, select_ast]
return ['SELECT', select_ast, ['FROM', table_section]]
def _iter_wrap_rv(self, rv):
from olo.model import ModelMeta
entity_count = len(self._entities)
raw = self._raw
producers = []
idx = -1
def make_field_producer(idx, v):
def producer(item):
if raw:
return item[idx]
model = v.get_model()
attrs = model._parse_attrs({
v.attr_name: item[idx]
})
return attrs[v.attr_name]
return producer
for v in self._entities:
idx += 1
if isinstance(v, ModelMeta):
fields_count = len(v.__fields__)
producers.append((
lambda idx, v:
lambda item: v._olo_instantiate(**dict(
izip(
v.__sorted_fields__,
item[idx: idx + fields_count]
)
))
)(idx, v))
idx += fields_count - 1
continue
if isinstance(v, Field):
producers.append(make_field_producer(idx, v))
continue
producers.append((
lambda idx, v:
lambda item: item[idx]
)(idx, v))
session = QuerySession()
seen = set()
for idx, item in enumerate(rv):
new_item = tuple(imap(lambda f: f(item), producers))
new_item = new_item[:entity_count]
if entity_count == 1:
new_item = new_item[0]
if isinstance(self._entities[0], DISTINCT):
if new_item in seen:
continue
seen.add(new_item)
session.add_entity(new_item)
for entity in session.entities:
yield entity
| true
| true
|
790e47e65bd4bcbaa3061560d8b59f02e2d375b0
| 2,499
|
py
|
Python
|
laas/tests/test_action_get_task_list.py
|
opnfv/laas-reflab
|
ab24a8de07dac62569ec79425241a6b974ed32a9
|
[
"Apache-2.0"
] | 1
|
2021-03-29T12:33:52.000Z
|
2021-03-29T12:33:52.000Z
|
laas/tests/test_action_get_task_list.py
|
opnfv/laas-reflab
|
ab24a8de07dac62569ec79425241a6b974ed32a9
|
[
"Apache-2.0"
] | null | null | null |
laas/tests/test_action_get_task_list.py
|
opnfv/laas-reflab
|
ab24a8de07dac62569ec79425241a6b974ed32a9
|
[
"Apache-2.0"
] | null | null | null |
##############################################################################
# Copyright 2019 Parker Berberian and Others #
# #
# 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 st2tests.base import BaseActionTestCase
from actions.actions import get_task_list
import json
class GetTaskListTestCase(BaseActionTestCase):
action_cls = get_task_list.Task_List_Action
def setUp(self):
super(GetTaskListTestCase, self).setUp()
self.action = self.get_action_instance()
def test_tasklist_multiple_tasks(self):
self.action.action_service.set_value("job_1", json.dumps({
"access": {
"task1": "asdf",
"task2": "fdsa"
}
}), local=False)
result = self.action.run(job_id=1, type="access")
self.assertEqual(set(result), set(["task1", "task2"]))
def test_tasklist_single_task(self):
self.action.action_service.set_value("job_1", json.dumps({
"access": {"task1": "asdf"},
"hardware": {"task10": "asdf"}
}), local=False)
result = self.action.run(job_id=1, type="hardware")
self.assertEqual(set(result), set(["task10"]))
def test_empty_tasklist(self):
self.action.action_service.set_value("job_1", json.dumps({
"access": {"task1": "asdf"},
"hardware": {"task10": "asdf"}
}), local=False)
result = self.action.run(job_id=1, type="unknown")
self.assertFalse(result)
| 47.150943
| 78
| 0.502201
| true
| true
|
|
790e47e8d533aaf3195e7b0523a2e78693861069
| 4,463
|
py
|
Python
|
nsecpy/listing.py
|
MattBSG/Switch-REST
|
c16400ef540e1de954f24b2c7567c5debe740940
|
[
"MIT"
] | 2
|
2020-10-30T19:42:50.000Z
|
2020-10-30T20:46:25.000Z
|
nsecpy/listing.py
|
MattBSG/Switch-REST
|
c16400ef540e1de954f24b2c7567c5debe740940
|
[
"MIT"
] | 9
|
2021-02-17T02:54:40.000Z
|
2021-05-17T23:43:19.000Z
|
nsecpy/listing.py
|
MattBSG/Switch-REST
|
c16400ef540e1de954f24b2c7567c5debe740940
|
[
"MIT"
] | 1
|
2021-01-26T20:54:34.000Z
|
2021-01-26T20:54:34.000Z
|
from dataclasses import dataclass, field
from datetime import datetime # for typehinting
from typing import TYPE_CHECKING, Generator, List, Literal, Optional
import aiohttp
import dateparser
from .exceptions import UnsupportedRegionError
from .pricing import PriceQuery, query_price
COUNT = 30 # Items per page of paginated response
if TYPE_CHECKING:
from .regions import Region # pragma: no cover
@dataclass
class RatingContent:
id: int = None
name: str = None
type: Literal["descriptor", "interactive"] = None
image_url: Optional[str] = None # JP Field
svg_image_url: Optional[str] = None # JP Field
def __init__(self, data) -> None:
self.id = data['id']
self.name = data['name']
self.type = data['type']
if data.get('image_url'):
self.image_url = data['image_url']
if data.get('svg_image_url'):
self.svg_image_url = data['svg_image_url']
@dataclass
class Rating:
age: int = None
id: int = None
image_url: Optional[str] = None
name: str = None
provisional: bool = None
svg_image_url: str = None
def __init__(self, data) -> None:
if (data['id']) == 0:
return
self.age = data['age']
self.id = data['id']
if data.get('image_url'):
self.image_url = data['image_url']
self.provisional = data['provisional']
self.svg_image_url = data['svg_image_url']
@dataclass
class RatingSystem:
id: int = None
name: str = None
def __init__(self, data) -> None:
self.id = data['id']
self.name = data['name']
@dataclass
class Game:
region: "Region" = None
content_type: str = None # Literal["game", "bundle"] ??? expand and replace hint
dominant_colors: List[str] = None
formal_name: str = None
hero_banner_url: str = None
id: int = None
is_new: bool = None
membership_required: bool = None
public_status: Literal["public"] = None
rating_content: List[RatingContent] = field(default_factory=list)
rating: Rating = None
rating_system: RatingSystem = None
release_date_on_eshop: datetime = None
screenshots: List[str] = field(default_factory=list)
strong_disclaimer: str = None
tags: List = field(default_factory=list)
target_titles: List = field(default_factory=list)
def __init__(self, data, region) -> None:
self.region = region
self.content_type = data['content_type']
self.dominant_colors = data['dominant_colors']
self.formal_name = data['formal_name']
self.hero_banner_url = data['hero_banner_url']
self.id = data['id']
self.is_new = data['is_new']
self.membership_required = data['membership_required']
self.public_status = data['public_status']
self.rating_content = [RatingContent(c) for c in data['rating_info']['content_descriptors']]
self.rating = Rating(data['rating_info']['rating'])
self.rating_system = RatingSystem(data['rating_info']['rating_system'])
# TODO: is this dateparser correct?
self.release_date_on_eshop = dateparser.parse(data['release_date_on_eshop'], settings={'TIMEZONE': "UTC"})
self.screenshots = [s['images'][0]['url'] for s in data['screenshots']]
self.strong_disclaimer = data.get('strong_disclaimer', None)
self.tags = data['tags']
self.target_titles = data['target_titles']
async def query_price(self) -> PriceQuery:
return await query_price(self.region, self)
async def query_listing(region: "Region", type: Literal["sales", "new", "ranking"]) -> Generator[Game, None, None]:
if not region.supports_listing:
raise UnsupportedRegionError("Region does not support listings")
if type not in ["sales", "new", "ranking"]:
raise ValueError("Invalid type: " + type)
lang, reg = region.culture_code.split('_')
offset = 0
async with aiohttp.ClientSession() as session:
while True:
url = f'https://ec.nintendo.com/api/{reg}/{lang}/search/{type}?offset={offset}&count={COUNT}'
async with session.get(url) as request:
request.raise_for_status()
data = await request.json()
for game in data['contents']:
yield Game(game, region)
if (offset + COUNT) >= data['total']:
break
offset += COUNT
| 32.816176
| 115
| 0.636791
|
from dataclasses import dataclass, field
from datetime import datetime
from typing import TYPE_CHECKING, Generator, List, Literal, Optional
import aiohttp
import dateparser
from .exceptions import UnsupportedRegionError
from .pricing import PriceQuery, query_price
COUNT = 30
if TYPE_CHECKING:
from .regions import Region
@dataclass
class RatingContent:
id: int = None
name: str = None
type: Literal["descriptor", "interactive"] = None
image_url: Optional[str] = None
svg_image_url: Optional[str] = None
def __init__(self, data) -> None:
self.id = data['id']
self.name = data['name']
self.type = data['type']
if data.get('image_url'):
self.image_url = data['image_url']
if data.get('svg_image_url'):
self.svg_image_url = data['svg_image_url']
@dataclass
class Rating:
age: int = None
id: int = None
image_url: Optional[str] = None
name: str = None
provisional: bool = None
svg_image_url: str = None
def __init__(self, data) -> None:
if (data['id']) == 0:
return
self.age = data['age']
self.id = data['id']
if data.get('image_url'):
self.image_url = data['image_url']
self.provisional = data['provisional']
self.svg_image_url = data['svg_image_url']
@dataclass
class RatingSystem:
id: int = None
name: str = None
def __init__(self, data) -> None:
self.id = data['id']
self.name = data['name']
@dataclass
class Game:
region: "Region" = None
content_type: str = None
dominant_colors: List[str] = None
formal_name: str = None
hero_banner_url: str = None
id: int = None
is_new: bool = None
membership_required: bool = None
public_status: Literal["public"] = None
rating_content: List[RatingContent] = field(default_factory=list)
rating: Rating = None
rating_system: RatingSystem = None
release_date_on_eshop: datetime = None
screenshots: List[str] = field(default_factory=list)
strong_disclaimer: str = None
tags: List = field(default_factory=list)
target_titles: List = field(default_factory=list)
def __init__(self, data, region) -> None:
self.region = region
self.content_type = data['content_type']
self.dominant_colors = data['dominant_colors']
self.formal_name = data['formal_name']
self.hero_banner_url = data['hero_banner_url']
self.id = data['id']
self.is_new = data['is_new']
self.membership_required = data['membership_required']
self.public_status = data['public_status']
self.rating_content = [RatingContent(c) for c in data['rating_info']['content_descriptors']]
self.rating = Rating(data['rating_info']['rating'])
self.rating_system = RatingSystem(data['rating_info']['rating_system'])
self.release_date_on_eshop = dateparser.parse(data['release_date_on_eshop'], settings={'TIMEZONE': "UTC"})
self.screenshots = [s['images'][0]['url'] for s in data['screenshots']]
self.strong_disclaimer = data.get('strong_disclaimer', None)
self.tags = data['tags']
self.target_titles = data['target_titles']
async def query_price(self) -> PriceQuery:
return await query_price(self.region, self)
async def query_listing(region: "Region", type: Literal["sales", "new", "ranking"]) -> Generator[Game, None, None]:
if not region.supports_listing:
raise UnsupportedRegionError("Region does not support listings")
if type not in ["sales", "new", "ranking"]:
raise ValueError("Invalid type: " + type)
lang, reg = region.culture_code.split('_')
offset = 0
async with aiohttp.ClientSession() as session:
while True:
url = f'https://ec.nintendo.com/api/{reg}/{lang}/search/{type}?offset={offset}&count={COUNT}'
async with session.get(url) as request:
request.raise_for_status()
data = await request.json()
for game in data['contents']:
yield Game(game, region)
if (offset + COUNT) >= data['total']:
break
offset += COUNT
| true
| true
|
790e49961dfec24e92686a76dbe6e64c6826e0c3
| 4,236
|
py
|
Python
|
app/views.py
|
Bekarysalashybayev/Nomad
|
3dda626763fe2b57535717f223046e13340f6741
|
[
"MIT"
] | null | null | null |
app/views.py
|
Bekarysalashybayev/Nomad
|
3dda626763fe2b57535717f223046e13340f6741
|
[
"MIT"
] | null | null | null |
app/views.py
|
Bekarysalashybayev/Nomad
|
3dda626763fe2b57535717f223046e13340f6741
|
[
"MIT"
] | null | null | null |
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect
from django.template import loader
from django.http import HttpResponse
from django import template
from mainsite.forms import NewsCreate
from mainsite.models import News, ContactForm, Issue
@login_required(login_url="/admin-panel/login/")
def index(request):
context = {}
context['segment'] = 'index'
html_template = loader.get_template('index.html')
return HttpResponse(html_template.render(context, request))
@login_required(login_url="/admin-panel/login/")
def profile(request):
context = {}
context['segment'] = 'profile'
html_template = loader.get_template('page-user.html')
return HttpResponse(html_template.render(context, request))
@login_required(login_url="/admin-panel/login/")
def news(request):
list = News.objects.all()
context = {"list": list}
context['segment'] = 'news'
html_template = loader.get_template('news.html')
return HttpResponse(html_template.render(context, request))
def add_news(request):
upload = NewsCreate()
if request.method == 'POST':
upload = NewsCreate(request.POST, request.FILES)
if upload.is_valid():
upload.save()
return redirect('/admin-panel/news')
else:
return HttpResponse(
"""your form is wrong, reload on <a href = "{{ url : '/admin-panel/news'}}">reload</a>""")
else:
context = {
"upload_form": upload,
"action": "Добавить"
}
return render(request, 'add-news.html', context)
@login_required(login_url="/admin-panel/login/")
def update_news(request, news_id: int):
try:
news_sel = News.objects.get(pk=news_id)
except news.DoesNotExist:
return redirect('/admin-panel/news')
news_form = NewsCreate(request.POST, request.FILES or None, instance=news_sel)
if news_form.is_valid():
news_form.save()
return redirect('/admin-panel/news')
context = {
"ProductForm": news_form,
"ProductModel": news_sel,
"action": "Обновить"
}
return render(request, 'add-news.html', context)
@login_required(login_url="/admin-panel/login/")
def delete_news(request, news_id):
news_id = int(news_id)
try:
news_sel = News.objects.get(pk=news_id)
except news_id.DoesNotExist:
return redirect('/admin-panel/news')
news_sel.delete()
return redirect('/admin-panel/news')
@login_required(login_url="/admin-panel/login/")
def contactforms(request):
list = ContactForm.objects.all()
context = {"list": list}
context['segment'] = 'contactforms'
html_template = loader.get_template('contact-forms.html')
return HttpResponse(html_template.render(context, request))
@login_required(login_url="/admin-panel/login/")
def requests(request):
list = Issue.objects.all()
context = {"list": list}
context['segment'] = 'requests'
html_template = loader.get_template('requests.html')
return HttpResponse(html_template.render(context, request))
@login_required(login_url="/admin-panel/login/")
def delete_contact_form(request, contact_id):
contact_id = int(contact_id)
try:
contact_sel = ContactForm.objects.get(pk=contact_id)
except contact_id.DoesNotExist:
return redirect('/admin-panel/contacts')
contact_sel.delete()
return redirect('/admin-panel/contacts')
@login_required(login_url="/admin-panel/login/")
def pages(request):
context = {}
# All resource paths end in .html.
# Pick out the html file name from the url. And load that template.
try:
load_template = request.path.split('/')[-1]
context['segment'] = load_template
html_template = loader.get_template(load_template)
return HttpResponse(html_template.render(context, request))
except template.TemplateDoesNotExist:
html_template = loader.get_template('page-404.html')
return HttpResponse(html_template.render(context, request))
except:
html_template = loader.get_template('page-500.html')
return HttpResponse(html_template.render(context, request))
| 31.61194
| 106
| 0.684372
|
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect
from django.template import loader
from django.http import HttpResponse
from django import template
from mainsite.forms import NewsCreate
from mainsite.models import News, ContactForm, Issue
@login_required(login_url="/admin-panel/login/")
def index(request):
context = {}
context['segment'] = 'index'
html_template = loader.get_template('index.html')
return HttpResponse(html_template.render(context, request))
@login_required(login_url="/admin-panel/login/")
def profile(request):
context = {}
context['segment'] = 'profile'
html_template = loader.get_template('page-user.html')
return HttpResponse(html_template.render(context, request))
@login_required(login_url="/admin-panel/login/")
def news(request):
list = News.objects.all()
context = {"list": list}
context['segment'] = 'news'
html_template = loader.get_template('news.html')
return HttpResponse(html_template.render(context, request))
def add_news(request):
upload = NewsCreate()
if request.method == 'POST':
upload = NewsCreate(request.POST, request.FILES)
if upload.is_valid():
upload.save()
return redirect('/admin-panel/news')
else:
return HttpResponse(
"""your form is wrong, reload on <a href = "{{ url : '/admin-panel/news'}}">reload</a>""")
else:
context = {
"upload_form": upload,
"action": "Добавить"
}
return render(request, 'add-news.html', context)
@login_required(login_url="/admin-panel/login/")
def update_news(request, news_id: int):
try:
news_sel = News.objects.get(pk=news_id)
except news.DoesNotExist:
return redirect('/admin-panel/news')
news_form = NewsCreate(request.POST, request.FILES or None, instance=news_sel)
if news_form.is_valid():
news_form.save()
return redirect('/admin-panel/news')
context = {
"ProductForm": news_form,
"ProductModel": news_sel,
"action": "Обновить"
}
return render(request, 'add-news.html', context)
@login_required(login_url="/admin-panel/login/")
def delete_news(request, news_id):
news_id = int(news_id)
try:
news_sel = News.objects.get(pk=news_id)
except news_id.DoesNotExist:
return redirect('/admin-panel/news')
news_sel.delete()
return redirect('/admin-panel/news')
@login_required(login_url="/admin-panel/login/")
def contactforms(request):
list = ContactForm.objects.all()
context = {"list": list}
context['segment'] = 'contactforms'
html_template = loader.get_template('contact-forms.html')
return HttpResponse(html_template.render(context, request))
@login_required(login_url="/admin-panel/login/")
def requests(request):
list = Issue.objects.all()
context = {"list": list}
context['segment'] = 'requests'
html_template = loader.get_template('requests.html')
return HttpResponse(html_template.render(context, request))
@login_required(login_url="/admin-panel/login/")
def delete_contact_form(request, contact_id):
contact_id = int(contact_id)
try:
contact_sel = ContactForm.objects.get(pk=contact_id)
except contact_id.DoesNotExist:
return redirect('/admin-panel/contacts')
contact_sel.delete()
return redirect('/admin-panel/contacts')
@login_required(login_url="/admin-panel/login/")
def pages(request):
context = {}
try:
load_template = request.path.split('/')[-1]
context['segment'] = load_template
html_template = loader.get_template(load_template)
return HttpResponse(html_template.render(context, request))
except template.TemplateDoesNotExist:
html_template = loader.get_template('page-404.html')
return HttpResponse(html_template.render(context, request))
except:
html_template = loader.get_template('page-500.html')
return HttpResponse(html_template.render(context, request))
| true
| true
|
790e4a21bff540c4eae3e972412204fa5207e8a9
| 7,357
|
py
|
Python
|
test/sagemaker_tests/mxnet/training/resources/mnist/horovod_mnist.py
|
Elizaaaaa/deep-learning-containers
|
6274ecb264645070d11b27e5c7e60d2e4110537d
|
[
"Apache-2.0"
] | 383
|
2020-05-19T18:09:10.000Z
|
2022-03-29T22:41:05.000Z
|
test/sagemaker_tests/mxnet/training/resources/mnist/horovod_mnist.py
|
Elizaaaaa/deep-learning-containers
|
6274ecb264645070d11b27e5c7e60d2e4110537d
|
[
"Apache-2.0"
] | 551
|
2020-05-27T17:25:50.000Z
|
2022-03-31T18:00:35.000Z
|
test/sagemaker_tests/mxnet/training/resources/mnist/horovod_mnist.py
|
Elizaaaaa/deep-learning-containers
|
6274ecb264645070d11b27e5c7e60d2e4110537d
|
[
"Apache-2.0"
] | 263
|
2020-05-19T18:17:12.000Z
|
2022-03-29T22:41:10.000Z
|
# Copyright 2017-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.:wq
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import argparse
import logging
import os
import zipfile
import time
import mxnet as mx
import horovod.mxnet as hvd
from mxnet import autograd, gluon, nd
from mxnet.test_utils import download
def main():
# Function to get mnist iterator given a rank
def get_mnist_iterator(rank):
data_dir = "data-%d" % rank
if not os.path.isdir(data_dir):
os.makedirs(data_dir)
zip_file_path = download('http://data.mxnet.io/mxnet/data/mnist.zip',
dirname=data_dir)
with zipfile.ZipFile(zip_file_path) as zf:
zf.extractall(data_dir)
input_shape = (1, 28, 28)
batch_size = args.batch_size
train_iter = mx.io.MNISTIter(
image="%s/train-images-idx3-ubyte" % data_dir,
label="%s/train-labels-idx1-ubyte" % data_dir,
input_shape=input_shape,
batch_size=batch_size,
shuffle=True,
flat=False,
num_parts=hvd.size(),
part_index=hvd.rank()
)
val_iter = mx.io.MNISTIter(
image="%s/t10k-images-idx3-ubyte" % data_dir,
label="%s/t10k-labels-idx1-ubyte" % data_dir,
input_shape=input_shape,
batch_size=batch_size,
flat=False,
)
return train_iter, val_iter
kernel_size = 5
strides = 2
pool_size = 2
hidden_dim = 512
output_dim = 10
activation = 'relu'
# Function to define neural network
def conv_nets():
net = gluon.nn.HybridSequential()
with net.name_scope():
net.add(gluon.nn.Conv2D(channels=20, kernel_size=kernel_size, activation=activation))
net.add(gluon.nn.MaxPool2D(pool_size=pool_size, strides=strides))
net.add(gluon.nn.Conv2D(channels=50, kernel_size=kernel_size, activation=activation))
net.add(gluon.nn.MaxPool2D(pool_size=pool_size, strides=strides))
net.add(gluon.nn.Flatten())
net.add(gluon.nn.Dense(hidden_dim, activation=activation))
net.add(gluon.nn.Dense(output_dim))
return net
# Function to evaluate accuracy for a model
def evaluate(model, data_iter, context):
data_iter.reset()
metric = mx.metric.Accuracy()
for _, batch in enumerate(data_iter):
data = batch.data[0].as_in_context(context)
label = batch.label[0].as_in_context(context)
output = model(data.astype(args.dtype, copy=False))
metric.update([label], [output])
return metric.get()
# Initialize Horovod
hvd.init()
# Horovod: pin context to local rank
context = mx.cpu(hvd.local_rank()) if args.no_cuda else mx.gpu(hvd.local_rank())
num_workers = hvd.size()
# Load training and validation data
train_data, val_data = get_mnist_iterator(hvd.rank())
# Build model
model = conv_nets()
model.cast(args.dtype)
model.hybridize()
# Create optimizer
optimizer_params = {'momentum': args.momentum,
'learning_rate': args.lr * hvd.size()}
opt = mx.optimizer.create('sgd', **optimizer_params)
# Initialize parameters
initializer = mx.init.Xavier(rnd_type='gaussian', factor_type="in",
magnitude=2)
model.initialize(initializer, ctx=context)
# Horovod: fetch and broadcast parameters
params = model.collect_params()
if params is not None:
hvd.broadcast_parameters(params, root_rank=0)
# Horovod: create DistributedTrainer, a subclass of gluon.Trainer
trainer = hvd.DistributedTrainer(params, opt)
# Create loss function and train metric
loss_fn = gluon.loss.SoftmaxCrossEntropyLoss()
metric = mx.metric.Accuracy()
# Global training timing
if hvd.rank() == 0:
global_tic = time.time()
# Train model
for epoch in range(args.epochs):
tic = time.time()
train_data.reset()
metric.reset()
for nbatch, batch in enumerate(train_data, start=1):
data = batch.data[0].as_in_context(context)
label = batch.label[0].as_in_context(context)
with autograd.record():
output = model(data.astype(args.dtype, copy=False))
loss = loss_fn(output, label)
loss.backward()
trainer.step(args.batch_size)
metric.update([label], [output])
if nbatch % 100 == 0:
name, acc = metric.get()
logging.info('[Epoch %d Batch %d] Training: %s=%f' %
(epoch, nbatch, name, acc))
if hvd.rank() == 0:
elapsed = time.time() - tic
speed = nbatch * args.batch_size * hvd.size() / elapsed
logging.info('Epoch[%d]\tSpeed=%.2f samples/s\tTime cost=%f',
epoch, speed, elapsed)
# Evaluate model accuracy
_, train_acc = metric.get()
name, val_acc = evaluate(model, val_data, context)
if hvd.rank() == 0:
logging.info('Epoch[%d]\tTrain: %s=%f\tValidation: %s=%f', epoch, name,
train_acc, name, val_acc)
if hvd.rank() == 0 and epoch == args.epochs - 1:
assert val_acc > 0.96, "Achieved accuracy (%f) is lower than expected\
(0.96)" % val_acc
if hvd.rank()==0:
global_training_time =time.time() - global_tic
print("Global elpased time on training:{}".format(global_training_time))
device = context.device_type + str(num_workers)
logging.info('Device info: %s', device)
if __name__ == "__main__":
# Handling script arguments
parser = argparse.ArgumentParser(description='MXNet MNIST Distributed Example')
parser.add_argument('--batch-size', type=int, default=64,
help='training batch size (default: 64)')
parser.add_argument('--dtype', type=str, default='float32',
help='training data type (default: float32)')
parser.add_argument('--epochs', type=int, default=5,
help='number of training epochs (default: 5)')
parser.add_argument('--lr', type=float, default=0.01,
help='learning rate (default: 0.01)')
parser.add_argument('--momentum', type=float, default=0.9,
help='SGD momentum (default: 0.9)')
parser.add_argument('--no-cuda', action='store_true', help='disable training on GPU (default: False)')
args = parser.parse_args()
if not args.no_cuda:
# Disable CUDA if there are no GPUs.
if mx.context.num_gpus() == 0:
args.no_cuda = True
logging.basicConfig(level=logging.INFO)
logging.info(args)
main()
| 36.241379
| 106
| 0.610711
|
import argparse
import logging
import os
import zipfile
import time
import mxnet as mx
import horovod.mxnet as hvd
from mxnet import autograd, gluon, nd
from mxnet.test_utils import download
def main():
def get_mnist_iterator(rank):
data_dir = "data-%d" % rank
if not os.path.isdir(data_dir):
os.makedirs(data_dir)
zip_file_path = download('http://data.mxnet.io/mxnet/data/mnist.zip',
dirname=data_dir)
with zipfile.ZipFile(zip_file_path) as zf:
zf.extractall(data_dir)
input_shape = (1, 28, 28)
batch_size = args.batch_size
train_iter = mx.io.MNISTIter(
image="%s/train-images-idx3-ubyte" % data_dir,
label="%s/train-labels-idx1-ubyte" % data_dir,
input_shape=input_shape,
batch_size=batch_size,
shuffle=True,
flat=False,
num_parts=hvd.size(),
part_index=hvd.rank()
)
val_iter = mx.io.MNISTIter(
image="%s/t10k-images-idx3-ubyte" % data_dir,
label="%s/t10k-labels-idx1-ubyte" % data_dir,
input_shape=input_shape,
batch_size=batch_size,
flat=False,
)
return train_iter, val_iter
kernel_size = 5
strides = 2
pool_size = 2
hidden_dim = 512
output_dim = 10
activation = 'relu'
def conv_nets():
net = gluon.nn.HybridSequential()
with net.name_scope():
net.add(gluon.nn.Conv2D(channels=20, kernel_size=kernel_size, activation=activation))
net.add(gluon.nn.MaxPool2D(pool_size=pool_size, strides=strides))
net.add(gluon.nn.Conv2D(channels=50, kernel_size=kernel_size, activation=activation))
net.add(gluon.nn.MaxPool2D(pool_size=pool_size, strides=strides))
net.add(gluon.nn.Flatten())
net.add(gluon.nn.Dense(hidden_dim, activation=activation))
net.add(gluon.nn.Dense(output_dim))
return net
def evaluate(model, data_iter, context):
data_iter.reset()
metric = mx.metric.Accuracy()
for _, batch in enumerate(data_iter):
data = batch.data[0].as_in_context(context)
label = batch.label[0].as_in_context(context)
output = model(data.astype(args.dtype, copy=False))
metric.update([label], [output])
return metric.get()
hvd.init()
context = mx.cpu(hvd.local_rank()) if args.no_cuda else mx.gpu(hvd.local_rank())
num_workers = hvd.size()
train_data, val_data = get_mnist_iterator(hvd.rank())
model = conv_nets()
model.cast(args.dtype)
model.hybridize()
optimizer_params = {'momentum': args.momentum,
'learning_rate': args.lr * hvd.size()}
opt = mx.optimizer.create('sgd', **optimizer_params)
initializer = mx.init.Xavier(rnd_type='gaussian', factor_type="in",
magnitude=2)
model.initialize(initializer, ctx=context)
params = model.collect_params()
if params is not None:
hvd.broadcast_parameters(params, root_rank=0)
trainer = hvd.DistributedTrainer(params, opt)
loss_fn = gluon.loss.SoftmaxCrossEntropyLoss()
metric = mx.metric.Accuracy()
if hvd.rank() == 0:
global_tic = time.time()
for epoch in range(args.epochs):
tic = time.time()
train_data.reset()
metric.reset()
for nbatch, batch in enumerate(train_data, start=1):
data = batch.data[0].as_in_context(context)
label = batch.label[0].as_in_context(context)
with autograd.record():
output = model(data.astype(args.dtype, copy=False))
loss = loss_fn(output, label)
loss.backward()
trainer.step(args.batch_size)
metric.update([label], [output])
if nbatch % 100 == 0:
name, acc = metric.get()
logging.info('[Epoch %d Batch %d] Training: %s=%f' %
(epoch, nbatch, name, acc))
if hvd.rank() == 0:
elapsed = time.time() - tic
speed = nbatch * args.batch_size * hvd.size() / elapsed
logging.info('Epoch[%d]\tSpeed=%.2f samples/s\tTime cost=%f',
epoch, speed, elapsed)
_, train_acc = metric.get()
name, val_acc = evaluate(model, val_data, context)
if hvd.rank() == 0:
logging.info('Epoch[%d]\tTrain: %s=%f\tValidation: %s=%f', epoch, name,
train_acc, name, val_acc)
if hvd.rank() == 0 and epoch == args.epochs - 1:
assert val_acc > 0.96, "Achieved accuracy (%f) is lower than expected\
(0.96)" % val_acc
if hvd.rank()==0:
global_training_time =time.time() - global_tic
print("Global elpased time on training:{}".format(global_training_time))
device = context.device_type + str(num_workers)
logging.info('Device info: %s', device)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='MXNet MNIST Distributed Example')
parser.add_argument('--batch-size', type=int, default=64,
help='training batch size (default: 64)')
parser.add_argument('--dtype', type=str, default='float32',
help='training data type (default: float32)')
parser.add_argument('--epochs', type=int, default=5,
help='number of training epochs (default: 5)')
parser.add_argument('--lr', type=float, default=0.01,
help='learning rate (default: 0.01)')
parser.add_argument('--momentum', type=float, default=0.9,
help='SGD momentum (default: 0.9)')
parser.add_argument('--no-cuda', action='store_true', help='disable training on GPU (default: False)')
args = parser.parse_args()
if not args.no_cuda:
if mx.context.num_gpus() == 0:
args.no_cuda = True
logging.basicConfig(level=logging.INFO)
logging.info(args)
main()
| true
| true
|
790e4bc3353be242b1ecceaeedd41a8b07cdef24
| 1,149
|
py
|
Python
|
main_app/api/views.py
|
XOyarz/polstats-django
|
6bc383f4cae56c21a403a337d2f7d2488e3e7d57
|
[
"MIT"
] | null | null | null |
main_app/api/views.py
|
XOyarz/polstats-django
|
6bc383f4cae56c21a403a337d2f7d2488e3e7d57
|
[
"MIT"
] | 1
|
2021-05-21T07:05:41.000Z
|
2021-05-21T07:05:41.000Z
|
main_app/api/views.py
|
XOyarz/polstats-django
|
6bc383f4cae56c21a403a337d2f7d2488e3e7d57
|
[
"MIT"
] | 1
|
2021-04-30T17:27:57.000Z
|
2021-04-30T17:27:57.000Z
|
from rest_framework import generics
from ..models import Article, Country, Source
from .serializers import ArticleSerializer, CountrySerializer, SourceSerializer
class ArticleListView(generics.ListCreateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
permission_classes = []
class ArticleDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
permission_classes = []
class CountryListView(generics.ListCreateAPIView):
queryset = Country.objects.all()
serializer_class = CountrySerializer
permission_classes = []
class CountryDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Country.objects.all()
serializer_class = CountrySerializer
permission_classes = []
class SourceListView(generics.ListCreateAPIView):
queryset = Source.objects.all()
serializer_class = SourceSerializer
permission_classes = []
class SourceDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Source.objects.all()
serializer_class = SourceSerializer
permission_classes = []
| 28.725
| 79
| 0.781549
|
from rest_framework import generics
from ..models import Article, Country, Source
from .serializers import ArticleSerializer, CountrySerializer, SourceSerializer
class ArticleListView(generics.ListCreateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
permission_classes = []
class ArticleDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
permission_classes = []
class CountryListView(generics.ListCreateAPIView):
queryset = Country.objects.all()
serializer_class = CountrySerializer
permission_classes = []
class CountryDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Country.objects.all()
serializer_class = CountrySerializer
permission_classes = []
class SourceListView(generics.ListCreateAPIView):
queryset = Source.objects.all()
serializer_class = SourceSerializer
permission_classes = []
class SourceDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Source.objects.all()
serializer_class = SourceSerializer
permission_classes = []
| true
| true
|
790e4cb78e3a29f390a2b7dad549433c7cc743db
| 2,721
|
py
|
Python
|
pandapipes/plotting/geo.py
|
nsanina/pandapipes
|
b2daaca6b83e7d8934502796721846bd9d552364
|
[
"BSD-3-Clause"
] | null | null | null |
pandapipes/plotting/geo.py
|
nsanina/pandapipes
|
b2daaca6b83e7d8934502796721846bd9d552364
|
[
"BSD-3-Clause"
] | null | null | null |
pandapipes/plotting/geo.py
|
nsanina/pandapipes
|
b2daaca6b83e7d8934502796721846bd9d552364
|
[
"BSD-3-Clause"
] | null | null | null |
# Copyright (c) 2020 by Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
from pandapower.plotting.geo import _node_geometries_from_geodata, \
_transform_node_geometry_to_geodata, _branch_geometries_from_geodata, \
_transform_branch_geometry_to_coords, _convert_xy_epsg
def convert_gis_to_geodata(net, node_geodata=True, branch_geodata=True):
"""
Extracts information on bus and line geodata from the geometries of a geopandas geodataframe.
:param net: The net for which to convert the geodata
:type net: pandapowerNet
:param node_geodata: flag if to extract x and y values for bus geodata
:type node_geodata: bool, default True
:param branch_geodata: flag if to extract coordinates values for line geodata
:type branch_geodata: bool, default True
:return: No output.
"""
if node_geodata:
_transform_node_geometry_to_geodata(net.junction_geodata)
if branch_geodata:
_transform_branch_geometry_to_coords(net.pipe_geodata)
def convert_geodata_to_gis(net, epsg=31467, node_geodata=True, branch_geodata=True):
"""
Transforms the bus and line geodata of a net into a geopandaas geodataframe with the respective
geometries.
:param net: The net for which to convert the geodata
:type net: pandapowerNet
:param epsg: current epsg projection
:type epsg: int, default 4326 (= WGS84)
:param node_geodata: flag if to transform the bus geodata table
:type node_geodata: bool, default True
:param branch_geodata: flag if to transform the line geodata table
:type branch_geodata: bool, default True
:return: No output.
"""
if node_geodata:
net["bus_geodata"] = _node_geometries_from_geodata(net["bus_geodata"], epsg)
if branch_geodata:
net["line_geodata"] = _branch_geometries_from_geodata(net["line_geodata"], epsg)
net["gis_epsg_code"] = epsg
def convert_epsg_bus_geodata(net, epsg_in=4326, epsg_out=31467):
"""
Converts bus geodata in net from epsg_in to epsg_out
:param net: The pandapower network
:type net: pandapowerNet
:param epsg_in: current epsg projection
:type epsg_in: int, default 4326 (= WGS84)
:param epsg_out: epsg projection to be transformed to
:type epsg_out: int, default 31467 (= Gauss-Krüger Zone 3)
:return: net - the given pandapower network (no copy!)
"""
net['bus_geodata'].loc[:, "x"], net['bus_geodata'].loc[:, "y"] = _convert_xy_epsg(
net['bus_geodata'].loc[:, "x"], net['bus_geodata'].loc[:, "y"], epsg_in, epsg_out)
return net
| 41.861538
| 99
| 0.728776
|
from pandapower.plotting.geo import _node_geometries_from_geodata, \
_transform_node_geometry_to_geodata, _branch_geometries_from_geodata, \
_transform_branch_geometry_to_coords, _convert_xy_epsg
def convert_gis_to_geodata(net, node_geodata=True, branch_geodata=True):
if node_geodata:
_transform_node_geometry_to_geodata(net.junction_geodata)
if branch_geodata:
_transform_branch_geometry_to_coords(net.pipe_geodata)
def convert_geodata_to_gis(net, epsg=31467, node_geodata=True, branch_geodata=True):
if node_geodata:
net["bus_geodata"] = _node_geometries_from_geodata(net["bus_geodata"], epsg)
if branch_geodata:
net["line_geodata"] = _branch_geometries_from_geodata(net["line_geodata"], epsg)
net["gis_epsg_code"] = epsg
def convert_epsg_bus_geodata(net, epsg_in=4326, epsg_out=31467):
net['bus_geodata'].loc[:, "x"], net['bus_geodata'].loc[:, "y"] = _convert_xy_epsg(
net['bus_geodata'].loc[:, "x"], net['bus_geodata'].loc[:, "y"], epsg_in, epsg_out)
return net
| true
| true
|
790e4d05191f10fc75b9e2bde12747ba1af4297c
| 8,022
|
py
|
Python
|
model_aton/datasets.py
|
xuhongzuo/Outlier-Interpretation
|
9bc2dbedcb7b89d0e4ecf7cea2a60612ab19ae4a
|
[
"Apache-2.0"
] | 17
|
2021-04-21T08:44:02.000Z
|
2022-03-20T07:42:54.000Z
|
model_aton/datasets.py
|
xuhongzuo/outlier-Interpretation
|
9bc2dbedcb7b89d0e4ecf7cea2a60612ab19ae4a
|
[
"Apache-2.0"
] | null | null | null |
model_aton/datasets.py
|
xuhongzuo/outlier-Interpretation
|
9bc2dbedcb7b89d0e4ecf7cea2a60612ab19ae4a
|
[
"Apache-2.0"
] | 1
|
2021-06-08T20:40:12.000Z
|
2021-06-08T20:40:12.000Z
|
"""
This script implements an outlier interpretation method of the following paper:
"Beyond Outlier Detection: Outlier Interpretation by Attention-Guided Triplet Deviation Network". in WWW'21.
@ Author: Hongzuo Xu
@ email: hongzuo.xu@gmail.com or leogarcia@126.com or xuhongzuo13@nudt.edu.cn
"""
import numpy as np
import torch
from torch.utils.data import Dataset
from sklearn.neighbors import NearestNeighbors
class SingleTripletDataset(Dataset):
def __init__(self, anom_idx, x, y, triplets_selector, transform=None):
self.transform = transform
self.data = x
self.triplets = triplets_selector.get_triplets(anom_idx, x, y)
def __getitem__(self, index):
a_idx, p_idx, n_idx = self.triplets[index]
anchor, positive, negative = self.data[a_idx], self.data[p_idx], self.data[n_idx]
if self.transform is not None:
anchor = self.transform(anchor)
positive = self.transform(positive)
negative = self.transform(negative)
return anchor, positive, negative
def __len__(self):
return len(self.triplets)
class SingleDataset(Dataset):
def __init__(self, anom_idx, x, y, data_selector, transform=None):
self.transform = transform
self.selected_data = data_selector.get_data(anom_idx, x, y)
def __getitem__(self, index):
data = self.selected_data[0][index]
target = self.selected_data[1][index]
if self.transform is not None:
data = self.transform(data)
return data, target
def __len__(self):
return len(self.selected_data[0])
class SingleTripletDatasetClf(Dataset):
def __init__(self, anom_idx, x, y, triplets_selector, transform=None):
self.transform = transform
self.data = x
self.triplets, self.targets = triplets_selector.get_triplets(anom_idx, x, y)
def __getitem__(self, index):
a_idx, p_idx, n_idx = self.triplets[index]
a_target, p_target, n_target = self.targets[index]
anchor, positive, negative = self.data[a_idx], self.data[p_idx], self.data[n_idx]
if self.transform is not None:
anchor = self.transform(anchor)
positive = self.transform(positive)
negative = self.transform(negative)
return anchor, positive, negative, a_target, p_target, n_target
def __len__(self):
return len(self.triplets)
class MyHardSingleTripletSelector:
def __init__(self, nbrs_num, rand_num, nbr_indices):
self.x = None
self.y = None
self.nbrs_num = nbrs_num
self.rand_num = rand_num
self.nbr_indices = nbr_indices
def get_triplets(self, anom_idx, x, y, normal_label=0):
self.x = x.cpu().data.numpy()
self.y = y.cpu().data.numpy()
# anom_x = self.x[anom_idx]
# x_noml = self.x[noml_idx]
# n_neighbors = self.nbrs_num
# nbrs_local = NearestNeighbors(n_neighbors=n_neighbors).fit(x_noml)
# nbr_indices = noml_idx[nbrs_local.kneighbors([anom_x])[1].flatten()]
noml_idx = np.where(self.y == normal_label)[0]
nbr_indices = self.nbr_indices
rand_num = self.rand_num
rand_canddt = np.setdiff1d(noml_idx, nbr_indices)
rand_indices = np.random.choice(rand_canddt, rand_num, replace=False)
triplets = [[anchor, positive, anom_idx]
for anchor in rand_indices
for positive in nbr_indices]
return torch.LongTensor(np.array(triplets))
class MyHardSingleSelectorClf:
def __init__(self, nbrs_num, rand_num):
self.nbrs_num = nbrs_num
self.rand_num = rand_num
def get_data(self, anom_idx, x, y, normal_label=0):
x = x.cpu().data.numpy()
y = y.cpu().data.numpy()
anom_x = x[anom_idx]
noml_idx = np.where(y == normal_label)[0]
x_noml = x[noml_idx]
nbrs_local = NearestNeighbors(n_neighbors=self.nbrs_num).fit(x_noml)
nbr_indices = noml_idx[nbrs_local.kneighbors([anom_x])[1].flatten()]
rand_canddt = np.setdiff1d(noml_idx, nbr_indices)
rand_indices = np.random.choice(rand_canddt, self.rand_num, replace=False)
# perturbation to augment
dim = x.shape[1]
anom_lst = []
anom_lst.append(anom_x)
for i in range(self.rand_num + self.nbrs_num -1):
new_anom_x = anom_x.copy()
choose_f = np.random.choice(np.arange(dim), 3)
for a in choose_f:
new_anom_x[a] = anom_x[a] * 1.01
anom_lst.append(new_anom_x)
data_idx = np.hstack([rand_indices, nbr_indices])
norm_data = x[data_idx]
data = np.vstack([np.array(anom_lst), norm_data])
target = np.hstack([np.ones(10), np.zeros(len(rand_indices), dtype=int), np.zeros(len(nbr_indices), dtype=int)])
return torch.FloatTensor(data), torch.LongTensor(target)
class MyHardSingleTripletSelectorClf:
def __init__(self, nbrs_num, rand_num):
self.x = None
self.y = None
self.nbrs_num = nbrs_num
self.rand_num = rand_num
def get_triplets(self, anom_idx, x, y, normal_label=0):
self.x = x.cpu().data.numpy()
self.y = y.cpu().data.numpy()
anom_x = self.x[anom_idx]
noml_idx = np.where(self.y == normal_label)[0]
x_noml = self.x[noml_idx]
n_neighbors = self.nbrs_num
rand_num = self.rand_num
nbrs_local = NearestNeighbors(n_neighbors=n_neighbors).fit(x_noml)
nbr_indices = noml_idx[nbrs_local.kneighbors([anom_x])[1].flatten()]
# nbr_dist = nbrs_local.kneighbors([anom_x])[0].flatten()
rand_canddt = np.setdiff1d(noml_idx, nbr_indices)
rand_indices = np.random.choice(rand_canddt, rand_num, replace=False)
triplets = [[anchor, positive, anom_idx]
for anchor in rand_indices
for positive in nbr_indices]
# print("Generate triplets Num: [%d]" % len(triplets))
target = [[0, 0, 1]] * len(triplets)
return torch.LongTensor(np.array(triplets)), torch.LongTensor(np.array(target))
class MyHardSingleTripletSelector2:
def __init__(self, nbrs_num, rand_num):
self.x = None
self.y = None
self.nbrs_num = nbrs_num
self.rand_num = rand_num
def get_triplets(self, anom_idx, x, y, normal_label=0):
self.x = x.cpu().data.numpy()
self.y = y.cpu().data.numpy()
n_neighbors = self.nbrs_num
rand_num = self.rand_num
anom_x = self.x[anom_idx]
anom_indices = np.where(self.y != normal_label)[0]
noml_indices = np.where(self.y == normal_label)[0]
noml_x = self.x[noml_indices]
nbrs_local = NearestNeighbors(n_neighbors=n_neighbors).fit(noml_x)
nbr_indices = noml_indices[nbrs_local.kneighbors([anom_x])[1].flatten()]
# nbr_dist = nbrs_local.kneighbors([anom_x])[0].flatten()
rand_canddt_nor = np.setdiff1d(noml_indices, nbr_indices)
rand_nor_indices = np.random.choice(rand_canddt_nor, rand_num, replace=False)
triplets1 = [[anchor, positive, anom_idx]
for anchor in rand_nor_indices
for positive in nbr_indices]
rand_canddt_ano = np.setdiff1d(anom_indices, anom_idx)
if len(rand_canddt_ano) < rand_num:
rand_ano_indices = rand_canddt_ano
else:
rand_ano_indices = np.random.choice(rand_canddt_ano, rand_num, replace=False)
triplets2 = [[anchor, anom_idx, negative]
for anchor in rand_ano_indices
for negative in nbr_indices]
triplets = triplets1 + triplets2
# print("Generate triplets Num: [%d]" % len(triplets))
target1 = [[0, 0, 1]] * len(triplets1)
target2 = [[1, 1, 0]] * len(triplets2)
target = target1 + target2
return torch.LongTensor(np.array(triplets)), torch.LongTensor(np.array(target))
| 36.135135
| 120
| 0.639616
|
import numpy as np
import torch
from torch.utils.data import Dataset
from sklearn.neighbors import NearestNeighbors
class SingleTripletDataset(Dataset):
def __init__(self, anom_idx, x, y, triplets_selector, transform=None):
self.transform = transform
self.data = x
self.triplets = triplets_selector.get_triplets(anom_idx, x, y)
def __getitem__(self, index):
a_idx, p_idx, n_idx = self.triplets[index]
anchor, positive, negative = self.data[a_idx], self.data[p_idx], self.data[n_idx]
if self.transform is not None:
anchor = self.transform(anchor)
positive = self.transform(positive)
negative = self.transform(negative)
return anchor, positive, negative
def __len__(self):
return len(self.triplets)
class SingleDataset(Dataset):
def __init__(self, anom_idx, x, y, data_selector, transform=None):
self.transform = transform
self.selected_data = data_selector.get_data(anom_idx, x, y)
def __getitem__(self, index):
data = self.selected_data[0][index]
target = self.selected_data[1][index]
if self.transform is not None:
data = self.transform(data)
return data, target
def __len__(self):
return len(self.selected_data[0])
class SingleTripletDatasetClf(Dataset):
def __init__(self, anom_idx, x, y, triplets_selector, transform=None):
self.transform = transform
self.data = x
self.triplets, self.targets = triplets_selector.get_triplets(anom_idx, x, y)
def __getitem__(self, index):
a_idx, p_idx, n_idx = self.triplets[index]
a_target, p_target, n_target = self.targets[index]
anchor, positive, negative = self.data[a_idx], self.data[p_idx], self.data[n_idx]
if self.transform is not None:
anchor = self.transform(anchor)
positive = self.transform(positive)
negative = self.transform(negative)
return anchor, positive, negative, a_target, p_target, n_target
def __len__(self):
return len(self.triplets)
class MyHardSingleTripletSelector:
def __init__(self, nbrs_num, rand_num, nbr_indices):
self.x = None
self.y = None
self.nbrs_num = nbrs_num
self.rand_num = rand_num
self.nbr_indices = nbr_indices
def get_triplets(self, anom_idx, x, y, normal_label=0):
self.x = x.cpu().data.numpy()
self.y = y.cpu().data.numpy()
noml_idx = np.where(self.y == normal_label)[0]
nbr_indices = self.nbr_indices
rand_num = self.rand_num
rand_canddt = np.setdiff1d(noml_idx, nbr_indices)
rand_indices = np.random.choice(rand_canddt, rand_num, replace=False)
triplets = [[anchor, positive, anom_idx]
for anchor in rand_indices
for positive in nbr_indices]
return torch.LongTensor(np.array(triplets))
class MyHardSingleSelectorClf:
def __init__(self, nbrs_num, rand_num):
self.nbrs_num = nbrs_num
self.rand_num = rand_num
def get_data(self, anom_idx, x, y, normal_label=0):
x = x.cpu().data.numpy()
y = y.cpu().data.numpy()
anom_x = x[anom_idx]
noml_idx = np.where(y == normal_label)[0]
x_noml = x[noml_idx]
nbrs_local = NearestNeighbors(n_neighbors=self.nbrs_num).fit(x_noml)
nbr_indices = noml_idx[nbrs_local.kneighbors([anom_x])[1].flatten()]
rand_canddt = np.setdiff1d(noml_idx, nbr_indices)
rand_indices = np.random.choice(rand_canddt, self.rand_num, replace=False)
dim = x.shape[1]
anom_lst = []
anom_lst.append(anom_x)
for i in range(self.rand_num + self.nbrs_num -1):
new_anom_x = anom_x.copy()
choose_f = np.random.choice(np.arange(dim), 3)
for a in choose_f:
new_anom_x[a] = anom_x[a] * 1.01
anom_lst.append(new_anom_x)
data_idx = np.hstack([rand_indices, nbr_indices])
norm_data = x[data_idx]
data = np.vstack([np.array(anom_lst), norm_data])
target = np.hstack([np.ones(10), np.zeros(len(rand_indices), dtype=int), np.zeros(len(nbr_indices), dtype=int)])
return torch.FloatTensor(data), torch.LongTensor(target)
class MyHardSingleTripletSelectorClf:
def __init__(self, nbrs_num, rand_num):
self.x = None
self.y = None
self.nbrs_num = nbrs_num
self.rand_num = rand_num
def get_triplets(self, anom_idx, x, y, normal_label=0):
self.x = x.cpu().data.numpy()
self.y = y.cpu().data.numpy()
anom_x = self.x[anom_idx]
noml_idx = np.where(self.y == normal_label)[0]
x_noml = self.x[noml_idx]
n_neighbors = self.nbrs_num
rand_num = self.rand_num
nbrs_local = NearestNeighbors(n_neighbors=n_neighbors).fit(x_noml)
nbr_indices = noml_idx[nbrs_local.kneighbors([anom_x])[1].flatten()]
rand_canddt = np.setdiff1d(noml_idx, nbr_indices)
rand_indices = np.random.choice(rand_canddt, rand_num, replace=False)
triplets = [[anchor, positive, anom_idx]
for anchor in rand_indices
for positive in nbr_indices]
target = [[0, 0, 1]] * len(triplets)
return torch.LongTensor(np.array(triplets)), torch.LongTensor(np.array(target))
class MyHardSingleTripletSelector2:
def __init__(self, nbrs_num, rand_num):
self.x = None
self.y = None
self.nbrs_num = nbrs_num
self.rand_num = rand_num
def get_triplets(self, anom_idx, x, y, normal_label=0):
self.x = x.cpu().data.numpy()
self.y = y.cpu().data.numpy()
n_neighbors = self.nbrs_num
rand_num = self.rand_num
anom_x = self.x[anom_idx]
anom_indices = np.where(self.y != normal_label)[0]
noml_indices = np.where(self.y == normal_label)[0]
noml_x = self.x[noml_indices]
nbrs_local = NearestNeighbors(n_neighbors=n_neighbors).fit(noml_x)
nbr_indices = noml_indices[nbrs_local.kneighbors([anom_x])[1].flatten()]
rand_canddt_nor = np.setdiff1d(noml_indices, nbr_indices)
rand_nor_indices = np.random.choice(rand_canddt_nor, rand_num, replace=False)
triplets1 = [[anchor, positive, anom_idx]
for anchor in rand_nor_indices
for positive in nbr_indices]
rand_canddt_ano = np.setdiff1d(anom_indices, anom_idx)
if len(rand_canddt_ano) < rand_num:
rand_ano_indices = rand_canddt_ano
else:
rand_ano_indices = np.random.choice(rand_canddt_ano, rand_num, replace=False)
triplets2 = [[anchor, anom_idx, negative]
for anchor in rand_ano_indices
for negative in nbr_indices]
triplets = triplets1 + triplets2
target1 = [[0, 0, 1]] * len(triplets1)
target2 = [[1, 1, 0]] * len(triplets2)
target = target1 + target2
return torch.LongTensor(np.array(triplets)), torch.LongTensor(np.array(target))
| true
| true
|
790e5075de8a0f53c9d2821fac0ee766f920d684
| 2,798
|
py
|
Python
|
heat/tests/test_nokey.py
|
citrix-openstack-build/heat
|
fa31873529481472e037e3ce157b87f8057fe622
|
[
"Apache-2.0"
] | null | null | null |
heat/tests/test_nokey.py
|
citrix-openstack-build/heat
|
fa31873529481472e037e3ce157b87f8057fe622
|
[
"Apache-2.0"
] | null | null | null |
heat/tests/test_nokey.py
|
citrix-openstack-build/heat
|
fa31873529481472e037e3ce157b87f8057fe622
|
[
"Apache-2.0"
] | null | null | null |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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 heat.tests.v1_1 import fakes
from heat.engine.resources import instance as instances
from heat.engine.resources import nova_utils
from heat.common import template_format
from heat.engine import scheduler
from heat.tests.common import HeatTestCase
from heat.tests import utils
nokey_template = '''
{
"AWSTemplateFormatVersion" : "2010-09-09",
"Description" : "NoKey Test",
"Parameters" : {},
"Resources" : {
"WebServer": {
"Type": "AWS::EC2::Instance",
"Properties": {
"ImageId" : "foo",
"InstanceType" : "m1.large",
"UserData" : "some data"
}
}
}
}
'''
class nokeyTest(HeatTestCase):
def setUp(self):
super(nokeyTest, self).setUp()
self.fc = fakes.FakeClient()
utils.setup_dummy_db()
def test_nokey_create(self):
stack_name = 'instance_create_test_nokey_stack'
t = template_format.parse(nokey_template)
stack = utils.parse_stack(t, stack_name=stack_name)
t['Resources']['WebServer']['Properties']['ImageId'] = 'CentOS 5.2'
t['Resources']['WebServer']['Properties']['InstanceType'] = \
'256 MB Server'
instance = instances.Instance('create_instance_name',
t['Resources']['WebServer'], stack)
self.m.StubOutWithMock(instance, 'nova')
instance.nova().MultipleTimes().AndReturn(self.fc)
instance.t = instance.stack.resolve_runtime_data(instance.t)
# need to resolve the template functions
server_userdata = nova_utils.build_userdata(
instance,
instance.t['Properties']['UserData'])
instance.mime_string = server_userdata
self.m.StubOutWithMock(self.fc.servers, 'create')
self.fc.servers.create(
image=1, flavor=1, key_name=None,
name=utils.PhysName(stack_name, instance.name),
security_groups=None,
userdata=server_userdata, scheduler_hints=None,
meta=None, nics=None, availability_zone=None).AndReturn(
self.fc.servers.list()[1])
self.m.ReplayAll()
scheduler.TaskRunner(instance.create)()
| 34.121951
| 78
| 0.651894
|
from heat.tests.v1_1 import fakes
from heat.engine.resources import instance as instances
from heat.engine.resources import nova_utils
from heat.common import template_format
from heat.engine import scheduler
from heat.tests.common import HeatTestCase
from heat.tests import utils
nokey_template = '''
{
"AWSTemplateFormatVersion" : "2010-09-09",
"Description" : "NoKey Test",
"Parameters" : {},
"Resources" : {
"WebServer": {
"Type": "AWS::EC2::Instance",
"Properties": {
"ImageId" : "foo",
"InstanceType" : "m1.large",
"UserData" : "some data"
}
}
}
}
'''
class nokeyTest(HeatTestCase):
def setUp(self):
super(nokeyTest, self).setUp()
self.fc = fakes.FakeClient()
utils.setup_dummy_db()
def test_nokey_create(self):
stack_name = 'instance_create_test_nokey_stack'
t = template_format.parse(nokey_template)
stack = utils.parse_stack(t, stack_name=stack_name)
t['Resources']['WebServer']['Properties']['ImageId'] = 'CentOS 5.2'
t['Resources']['WebServer']['Properties']['InstanceType'] = \
'256 MB Server'
instance = instances.Instance('create_instance_name',
t['Resources']['WebServer'], stack)
self.m.StubOutWithMock(instance, 'nova')
instance.nova().MultipleTimes().AndReturn(self.fc)
instance.t = instance.stack.resolve_runtime_data(instance.t)
server_userdata = nova_utils.build_userdata(
instance,
instance.t['Properties']['UserData'])
instance.mime_string = server_userdata
self.m.StubOutWithMock(self.fc.servers, 'create')
self.fc.servers.create(
image=1, flavor=1, key_name=None,
name=utils.PhysName(stack_name, instance.name),
security_groups=None,
userdata=server_userdata, scheduler_hints=None,
meta=None, nics=None, availability_zone=None).AndReturn(
self.fc.servers.list()[1])
self.m.ReplayAll()
scheduler.TaskRunner(instance.create)()
| true
| true
|
790e508da25fc3efb1adca0872aa25ea29815d33
| 1,658
|
py
|
Python
|
test/test_meow_data.py
|
ttpro1995/CV_Assignment02
|
407205bd450243a85c52dee1b2c4b4664e833a24
|
[
"MIT"
] | null | null | null |
test/test_meow_data.py
|
ttpro1995/CV_Assignment02
|
407205bd450243a85c52dee1b2c4b4664e833a24
|
[
"MIT"
] | null | null | null |
test/test_meow_data.py
|
ttpro1995/CV_Assignment02
|
407205bd450243a85c52dee1b2c4b4664e833a24
|
[
"MIT"
] | null | null | null |
# Thai Thien
# 1351040
import pytest
import cv2
import sys
import sys, os
import numpy as np
import upload
# make sure it can find matcher.py file
sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/.."))
import util
from matcher import Matcher
# make sure it can find detector.py file
sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/.."))
from detector import Detector
prefix = './image/meowdata/'
chuot1_path = prefix + 'chuot1.jpg'
chuot2_path = prefix +'chuot1.jpg'
chuot3_path = prefix +'chuot1.jpg'
dau1_path = prefix +'dau1.jpg'
dau2_path = prefix +'dau2.jpg'
dau3_path = prefix +'dau3.jpg'
dau4_path = prefix +'dau4.jpg'
keyboard1_path = prefix +'keyboard1.jpg'
keyboard2_path = prefix +'keyboard2.jpg'
keyboard3_path = prefix +'keyboard3.jpg'
keyboard4_path = prefix +'keyboard4.jpg'
chuot1 = cv2.imread(chuot1_path)
chuot2 = cv2.imread(chuot2_path)
chuot3 = cv2.imread(chuot3_path)
dau1 = cv2.imread(dau1_path)
dau2 = cv2.imread(dau2_path)
keyboard1 = cv2.imread(keyboard1_path)
keyboard2 = cv2.imread(keyboard2_path)
isUpload = False
class TestMatcher():
def test_matches_dog_sift(self):
_matcher = Matcher()
_name = 'chuot1_2_dog_sift'
_file = './output/'+_name+'.png'
matches, result = _matcher.dog_match(chuot1, chuot2, 20)
cv2.imwrite(_file, result)
if (isUpload):
upload.imgur(_file,_name)
_name = 'keyboard1_2_dog_sift'
_file = './output/'+_name+'.png'
matches, result = _matcher.dog_match(chuot1, chuot2, 20)
cv2.imwrite(_file, result)
if (isUpload):
upload.imgur(_file, _name)
| 25.121212
| 66
| 0.693004
|
import pytest
import cv2
import sys
import sys, os
import numpy as np
import upload
sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/.."))
import util
from matcher import Matcher
sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/.."))
from detector import Detector
prefix = './image/meowdata/'
chuot1_path = prefix + 'chuot1.jpg'
chuot2_path = prefix +'chuot1.jpg'
chuot3_path = prefix +'chuot1.jpg'
dau1_path = prefix +'dau1.jpg'
dau2_path = prefix +'dau2.jpg'
dau3_path = prefix +'dau3.jpg'
dau4_path = prefix +'dau4.jpg'
keyboard1_path = prefix +'keyboard1.jpg'
keyboard2_path = prefix +'keyboard2.jpg'
keyboard3_path = prefix +'keyboard3.jpg'
keyboard4_path = prefix +'keyboard4.jpg'
chuot1 = cv2.imread(chuot1_path)
chuot2 = cv2.imread(chuot2_path)
chuot3 = cv2.imread(chuot3_path)
dau1 = cv2.imread(dau1_path)
dau2 = cv2.imread(dau2_path)
keyboard1 = cv2.imread(keyboard1_path)
keyboard2 = cv2.imread(keyboard2_path)
isUpload = False
class TestMatcher():
def test_matches_dog_sift(self):
_matcher = Matcher()
_name = 'chuot1_2_dog_sift'
_file = './output/'+_name+'.png'
matches, result = _matcher.dog_match(chuot1, chuot2, 20)
cv2.imwrite(_file, result)
if (isUpload):
upload.imgur(_file,_name)
_name = 'keyboard1_2_dog_sift'
_file = './output/'+_name+'.png'
matches, result = _matcher.dog_match(chuot1, chuot2, 20)
cv2.imwrite(_file, result)
if (isUpload):
upload.imgur(_file, _name)
| true
| true
|
790e50e9fe657a945302ad88e755c133d3d728ae
| 3,512
|
py
|
Python
|
backend/env/lib/python3.8/site-packages/werkzeug/wrappers/cors.py
|
lubitelpospat/CFM-source
|
4e6af33ee68c6f2f05b6952b64a6b3f0591d5b03
|
[
"MIT"
] | 32
|
2020-04-05T08:29:40.000Z
|
2022-01-08T03:10:00.000Z
|
backend/env/lib/python3.8/site-packages/werkzeug/wrappers/cors.py
|
lubitelpospat/CFM-source
|
4e6af33ee68c6f2f05b6952b64a6b3f0591d5b03
|
[
"MIT"
] | 9
|
2020-08-26T12:16:47.000Z
|
2021-09-22T19:40:22.000Z
|
backend/env/lib/python3.8/site-packages/werkzeug/wrappers/cors.py
|
lubitelpospat/CFM-source
|
4e6af33ee68c6f2f05b6952b64a6b3f0591d5b03
|
[
"MIT"
] | 5
|
2020-03-29T18:55:15.000Z
|
2020-12-13T09:34:21.000Z
|
from ..http import dump_header
from ..http import parse_set_header
from ..utils import environ_property
from ..utils import header_property
class CORSRequestMixin(object):
"""A mixin for :class:`~werkzeug.wrappers.BaseRequest` subclasses
that adds descriptors for Cross Origin Resource Sharing (CORS)
headers.
.. versionadded:: 1.0
"""
origin = environ_property(
"HTTP_ORIGIN",
doc=(
"The host that the request originated from. Set"
" :attr:`~CORSResponseMixin.access_control_allow_origin` on"
" the response to indicate which origins are allowed."
),
)
access_control_request_headers = environ_property(
"HTTP_ACCESS_CONTROL_REQUEST_HEADERS",
load_func=parse_set_header,
doc=(
"Sent with a preflight request to indicate which headers"
" will be sent with the cross origin request. Set"
" :attr:`~CORSResponseMixin.access_control_allow_headers`"
" on the response to indicate which headers are allowed."
),
)
access_control_request_method = environ_property(
"HTTP_ACCESS_CONTROL_REQUEST_METHOD",
doc=(
"Sent with a preflight request to indicate which method"
" will be used for the cross origin request. Set"
" :attr:`~CORSResponseMixin.access_control_allow_methods`"
" on the response to indicate which methods are allowed."
),
)
class CORSResponseMixin(object):
"""A mixin for :class:`~werkzeug.wrappers.BaseResponse` subclasses
that adds descriptors for Cross Origin Resource Sharing (CORS)
headers.
.. versionadded:: 1.0
"""
@property
def access_control_allow_credentials(self):
"""Whether credentials can be shared by the browser to
JavaScript code. As part of the preflight request it indicates
whether credentials can be used on the cross origin request.
"""
return "Access-Control-Allow-Credentials" in self.headers
@access_control_allow_credentials.setter
def access_control_allow_credentials(self, value):
if value is True:
self.headers["Access-Control-Allow-Credentials"] = "true"
else:
self.headers.pop("Access-Control-Allow-Credentials", None)
access_control_allow_headers = header_property(
"Access-Control-Allow-Headers",
load_func=parse_set_header,
dump_func=dump_header,
doc="Which headers can be sent with the cross origin request.",
)
access_control_allow_methods = header_property(
"Access-Control-Allow-Methods",
load_func=parse_set_header,
dump_func=dump_header,
doc="Which methods can be used for the cross origin request.",
)
access_control_allow_origin = header_property(
"Access-Control-Allow-Origin",
load_func=parse_set_header,
dump_func=dump_header,
doc="The origins that may make cross origin requests.",
)
access_control_expose_headers = header_property(
"Access-Control-Expose-Headers",
load_func=parse_set_header,
dump_func=dump_header,
doc="Which headers can be shared by the browser to JavaScript code.",
)
access_control_max_age = header_property(
"Access-Control-Max-Age",
load_func=int,
dump_func=str,
doc="The maximum age in seconds the access control settings can be cached for.",
)
| 34.097087
| 88
| 0.669989
|
from ..http import dump_header
from ..http import parse_set_header
from ..utils import environ_property
from ..utils import header_property
class CORSRequestMixin(object):
origin = environ_property(
"HTTP_ORIGIN",
doc=(
"The host that the request originated from. Set"
" :attr:`~CORSResponseMixin.access_control_allow_origin` on"
" the response to indicate which origins are allowed."
),
)
access_control_request_headers = environ_property(
"HTTP_ACCESS_CONTROL_REQUEST_HEADERS",
load_func=parse_set_header,
doc=(
"Sent with a preflight request to indicate which headers"
" will be sent with the cross origin request. Set"
" :attr:`~CORSResponseMixin.access_control_allow_headers`"
" on the response to indicate which headers are allowed."
),
)
access_control_request_method = environ_property(
"HTTP_ACCESS_CONTROL_REQUEST_METHOD",
doc=(
"Sent with a preflight request to indicate which method"
" will be used for the cross origin request. Set"
" :attr:`~CORSResponseMixin.access_control_allow_methods`"
" on the response to indicate which methods are allowed."
),
)
class CORSResponseMixin(object):
@property
def access_control_allow_credentials(self):
return "Access-Control-Allow-Credentials" in self.headers
@access_control_allow_credentials.setter
def access_control_allow_credentials(self, value):
if value is True:
self.headers["Access-Control-Allow-Credentials"] = "true"
else:
self.headers.pop("Access-Control-Allow-Credentials", None)
access_control_allow_headers = header_property(
"Access-Control-Allow-Headers",
load_func=parse_set_header,
dump_func=dump_header,
doc="Which headers can be sent with the cross origin request.",
)
access_control_allow_methods = header_property(
"Access-Control-Allow-Methods",
load_func=parse_set_header,
dump_func=dump_header,
doc="Which methods can be used for the cross origin request.",
)
access_control_allow_origin = header_property(
"Access-Control-Allow-Origin",
load_func=parse_set_header,
dump_func=dump_header,
doc="The origins that may make cross origin requests.",
)
access_control_expose_headers = header_property(
"Access-Control-Expose-Headers",
load_func=parse_set_header,
dump_func=dump_header,
doc="Which headers can be shared by the browser to JavaScript code.",
)
access_control_max_age = header_property(
"Access-Control-Max-Age",
load_func=int,
dump_func=str,
doc="The maximum age in seconds the access control settings can be cached for.",
)
| true
| true
|
790e50ee2e482a4ebdc785314c77848d4054b05d
| 6,224
|
py
|
Python
|
tf_agents/environments/random_py_environment_test.py
|
adammichaelwood/agents
|
66ad01b9ae909bc6c344b8f0cb356758cae95236
|
[
"Apache-2.0"
] | 16
|
2020-09-23T06:21:49.000Z
|
2022-03-28T05:45:04.000Z
|
tf_agents/environments/random_py_environment_test.py
|
adammichaelwood/agents
|
66ad01b9ae909bc6c344b8f0cb356758cae95236
|
[
"Apache-2.0"
] | 13
|
2019-06-18T03:36:39.000Z
|
2019-08-28T18:30:29.000Z
|
tf_agents/environments/random_py_environment_test.py
|
adammichaelwood/agents
|
66ad01b9ae909bc6c344b8f0cb356758cae95236
|
[
"Apache-2.0"
] | 6
|
2020-10-09T06:33:23.000Z
|
2022-02-03T16:16:36.000Z
|
# coding=utf-8
# Copyright 2018 The TF-Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for utils.random_py_environment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
from tf_agents.environments import random_py_environment
from tf_agents.specs import array_spec
from tf_agents.utils import test_utils
class RandomPyEnvironmentTest(parameterized.TestCase, test_utils.TestCase):
def testEnvResetAutomatically(self):
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(obs_spec)
time_step = env.step([0])
self.assertTrue(np.all(time_step.observation >= -10))
self.assertTrue(np.all(time_step.observation <= 10))
self.assertTrue(time_step.is_first())
while not time_step.is_last():
time_step = env.step([0])
self.assertTrue(np.all(time_step.observation >= -10))
self.assertTrue(np.all(time_step.observation <= 10))
time_step = env.step([0])
self.assertTrue(np.all(time_step.observation >= -10))
self.assertTrue(np.all(time_step.observation <= 10))
self.assertTrue(time_step.is_first())
@parameterized.named_parameters([
('OneStep', 1),
('FiveSteps', 5),
])
def testEnvMinDuration(self, min_duration):
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(
obs_spec, episode_end_probability=0.9, min_duration=min_duration)
num_episodes = 100
for _ in range(num_episodes):
time_step = env.step([0])
self.assertTrue(time_step.is_first())
num_steps = 0
while not time_step.is_last():
time_step = env.step([0])
num_steps += 1
self.assertGreaterEqual(num_steps, min_duration)
@parameterized.named_parameters([
('OneStep', 1),
('FiveSteps', 5),
])
def testEnvMaxDuration(self, max_duration):
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(
obs_spec, episode_end_probability=0.1, max_duration=max_duration)
num_episodes = 100
for _ in range(num_episodes):
time_step = env.step([0])
self.assertTrue(time_step.is_first())
num_steps = 0
while not time_step.is_last():
time_step = env.step([0])
num_steps += 1
self.assertLessEqual(num_steps, max_duration)
def testEnvChecksActions(self):
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
action_spec = array_spec.BoundedArraySpec((2, 2), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(
obs_spec, action_spec=action_spec)
env.step(np.array([[0, 0], [0, 0]]))
with self.assertRaises(ValueError):
env.step([0])
def testRewardFnCalled(self):
def reward_fn(unused_step_type, action, unused_observation):
return action
action_spec = array_spec.BoundedArraySpec((1,), np.int32, -10, 10)
observation_spec = array_spec.BoundedArraySpec((1,), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(
observation_spec, action_spec, reward_fn=reward_fn)
time_step = env.step(1) # No reward in first time_step
self.assertEqual(0.0, time_step.reward)
time_step = env.step(1)
self.assertEqual(1, time_step.reward)
def testRendersImage(self):
action_spec = array_spec.BoundedArraySpec((1,), np.int32, -10, 10)
observation_spec = array_spec.BoundedArraySpec((1,), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(
observation_spec, action_spec, render_size=(4, 4, 3))
env.reset()
img = env.render()
self.assertTrue(np.all(img < 256))
self.assertTrue(np.all(img >= 0))
self.assertEqual((4, 4, 3), img.shape)
self.assertEqual(np.uint8, img.dtype)
def testBatchSize(self):
batch_size = 3
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(obs_spec,
batch_size=batch_size)
time_step = env.step([0])
self.assertEqual(time_step.observation.shape, (3, 2, 3))
self.assertEqual(time_step.reward.shape[0], batch_size)
self.assertEqual(time_step.discount.shape[0], batch_size)
def testCustomRewardFn(self):
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
batch_size = 3
env = random_py_environment.RandomPyEnvironment(
obs_spec,
reward_fn=lambda *_: np.ones(batch_size),
batch_size=batch_size)
env._done = False
env.reset()
time_step = env.step([0])
self.assertSequenceAlmostEqual([1.0] * 3, time_step.reward)
def testRewardCheckerBatchSizeOne(self):
# Ensure batch size 1 with scalar reward works
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(
obs_spec,
reward_fn=lambda *_: np.array([1.0]),
batch_size=1)
env._done = False
env.reset()
time_step = env.step([0])
self.assertEqual(time_step.reward, 1.0)
def testRewardCheckerSizeMismatch(self):
# Ensure custom scalar reward with batch_size greater than 1 raises
# ValueError
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(
obs_spec,
reward_fn=lambda *_: 1.0,
batch_size=5)
env.reset()
env._done = False
with self.assertRaises(ValueError):
env.step([0])
if __name__ == '__main__':
test_utils.main()
| 34.77095
| 75
| 0.696497
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
from tf_agents.environments import random_py_environment
from tf_agents.specs import array_spec
from tf_agents.utils import test_utils
class RandomPyEnvironmentTest(parameterized.TestCase, test_utils.TestCase):
def testEnvResetAutomatically(self):
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(obs_spec)
time_step = env.step([0])
self.assertTrue(np.all(time_step.observation >= -10))
self.assertTrue(np.all(time_step.observation <= 10))
self.assertTrue(time_step.is_first())
while not time_step.is_last():
time_step = env.step([0])
self.assertTrue(np.all(time_step.observation >= -10))
self.assertTrue(np.all(time_step.observation <= 10))
time_step = env.step([0])
self.assertTrue(np.all(time_step.observation >= -10))
self.assertTrue(np.all(time_step.observation <= 10))
self.assertTrue(time_step.is_first())
@parameterized.named_parameters([
('OneStep', 1),
('FiveSteps', 5),
])
def testEnvMinDuration(self, min_duration):
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(
obs_spec, episode_end_probability=0.9, min_duration=min_duration)
num_episodes = 100
for _ in range(num_episodes):
time_step = env.step([0])
self.assertTrue(time_step.is_first())
num_steps = 0
while not time_step.is_last():
time_step = env.step([0])
num_steps += 1
self.assertGreaterEqual(num_steps, min_duration)
@parameterized.named_parameters([
('OneStep', 1),
('FiveSteps', 5),
])
def testEnvMaxDuration(self, max_duration):
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(
obs_spec, episode_end_probability=0.1, max_duration=max_duration)
num_episodes = 100
for _ in range(num_episodes):
time_step = env.step([0])
self.assertTrue(time_step.is_first())
num_steps = 0
while not time_step.is_last():
time_step = env.step([0])
num_steps += 1
self.assertLessEqual(num_steps, max_duration)
def testEnvChecksActions(self):
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
action_spec = array_spec.BoundedArraySpec((2, 2), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(
obs_spec, action_spec=action_spec)
env.step(np.array([[0, 0], [0, 0]]))
with self.assertRaises(ValueError):
env.step([0])
def testRewardFnCalled(self):
def reward_fn(unused_step_type, action, unused_observation):
return action
action_spec = array_spec.BoundedArraySpec((1,), np.int32, -10, 10)
observation_spec = array_spec.BoundedArraySpec((1,), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(
observation_spec, action_spec, reward_fn=reward_fn)
time_step = env.step(1)
self.assertEqual(0.0, time_step.reward)
time_step = env.step(1)
self.assertEqual(1, time_step.reward)
def testRendersImage(self):
action_spec = array_spec.BoundedArraySpec((1,), np.int32, -10, 10)
observation_spec = array_spec.BoundedArraySpec((1,), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(
observation_spec, action_spec, render_size=(4, 4, 3))
env.reset()
img = env.render()
self.assertTrue(np.all(img < 256))
self.assertTrue(np.all(img >= 0))
self.assertEqual((4, 4, 3), img.shape)
self.assertEqual(np.uint8, img.dtype)
def testBatchSize(self):
batch_size = 3
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(obs_spec,
batch_size=batch_size)
time_step = env.step([0])
self.assertEqual(time_step.observation.shape, (3, 2, 3))
self.assertEqual(time_step.reward.shape[0], batch_size)
self.assertEqual(time_step.discount.shape[0], batch_size)
def testCustomRewardFn(self):
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
batch_size = 3
env = random_py_environment.RandomPyEnvironment(
obs_spec,
reward_fn=lambda *_: np.ones(batch_size),
batch_size=batch_size)
env._done = False
env.reset()
time_step = env.step([0])
self.assertSequenceAlmostEqual([1.0] * 3, time_step.reward)
def testRewardCheckerBatchSizeOne(self):
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(
obs_spec,
reward_fn=lambda *_: np.array([1.0]),
batch_size=1)
env._done = False
env.reset()
time_step = env.step([0])
self.assertEqual(time_step.reward, 1.0)
def testRewardCheckerSizeMismatch(self):
obs_spec = array_spec.BoundedArraySpec((2, 3), np.int32, -10, 10)
env = random_py_environment.RandomPyEnvironment(
obs_spec,
reward_fn=lambda *_: 1.0,
batch_size=5)
env.reset()
env._done = False
with self.assertRaises(ValueError):
env.step([0])
if __name__ == '__main__':
test_utils.main()
| true
| true
|
790e50f085f96675619957c8359eeab6c7a1018f
| 808
|
py
|
Python
|
examples/dmrg/03-density_matrix.py
|
gmwang18/pyscf
|
fcd6877751661c8a9743c1c872a4a2b65f6dd7ac
|
[
"BSD-2-Clause"
] | null | null | null |
examples/dmrg/03-density_matrix.py
|
gmwang18/pyscf
|
fcd6877751661c8a9743c1c872a4a2b65f6dd7ac
|
[
"BSD-2-Clause"
] | null | null | null |
examples/dmrg/03-density_matrix.py
|
gmwang18/pyscf
|
fcd6877751661c8a9743c1c872a4a2b65f6dd7ac
|
[
"BSD-2-Clause"
] | null | null | null |
#!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
from pyscf import gto
from pyscf import scf
from pyscf import mcscf
from pyscf.dmrgscf import dmrgci
'''
Block code for active space N-particle density matrices.
'''
b = 1.2
mol = gto.M(
verbose = 4,
atom = 'N 0 0 0; N 0 0 %f'%b,
basis = 'cc-pvdz',
symmetry = True,
)
m = scf.RHF(mol)
m.kernel()
mc = mcscf.CASSCF(m, 8, 8)
mc.fcisolver = dmrgci.DMRGCI(mol)
mc.kernel()
dm1 = mc.fcisolver.make_rdm1(0, mc.ncas, mc.nelecas)
dm2 = mc.fcisolver.make_rdm12(0, mc.ncas, mc.nelecas)[1]
dm3 = mc.fcisolver.make_rdm123(0, mc.ncas, mc.nelecas)[2]
#
# or computing DMs all together in one DMRG call
#
dm1, dm2 = mc.fcisolver.make_rdm12(0, mc.ncas, mc.nelecas)
dm1, dm2, dm3 = mc.fcisolver.make_rdm123(0, mc.ncas, mc.nelecas)
| 20.2
| 64
| 0.679455
|
from pyscf import gto
from pyscf import scf
from pyscf import mcscf
from pyscf.dmrgscf import dmrgci
b = 1.2
mol = gto.M(
verbose = 4,
atom = 'N 0 0 0; N 0 0 %f'%b,
basis = 'cc-pvdz',
symmetry = True,
)
m = scf.RHF(mol)
m.kernel()
mc = mcscf.CASSCF(m, 8, 8)
mc.fcisolver = dmrgci.DMRGCI(mol)
mc.kernel()
dm1 = mc.fcisolver.make_rdm1(0, mc.ncas, mc.nelecas)
dm2 = mc.fcisolver.make_rdm12(0, mc.ncas, mc.nelecas)[1]
dm3 = mc.fcisolver.make_rdm123(0, mc.ncas, mc.nelecas)[2]
dm1, dm2 = mc.fcisolver.make_rdm12(0, mc.ncas, mc.nelecas)
dm1, dm2, dm3 = mc.fcisolver.make_rdm123(0, mc.ncas, mc.nelecas)
| true
| true
|
790e51c07371909390efb89febed60c1951094e7
| 5,648
|
py
|
Python
|
tests/test_update.py
|
lukaszlacinski/zstash
|
e2b1ab3166e468e7a0813c84a56032e7becbb6ec
|
[
"BSD-3-Clause"
] | 5
|
2019-08-19T22:58:17.000Z
|
2022-03-25T01:21:16.000Z
|
tests/test_update.py
|
lukaszlacinski/zstash
|
e2b1ab3166e468e7a0813c84a56032e7becbb6ec
|
[
"BSD-3-Clause"
] | 154
|
2018-08-29T17:15:56.000Z
|
2022-03-17T23:21:22.000Z
|
tests/test_update.py
|
lukaszlacinski/zstash
|
e2b1ab3166e468e7a0813c84a56032e7becbb6ec
|
[
"BSD-3-Clause"
] | 9
|
2019-05-01T19:04:10.000Z
|
2022-01-14T19:18:00.000Z
|
import os
import unittest
from tests.base import (
HPSS_ARCHIVE,
TOP_LEVEL,
ZSTASH_PATH,
TestZstash,
compare,
print_starred,
run_cmd,
write_file,
)
class TestUpdate(TestZstash):
"""
Test `zstash --update`.
"""
# x = on, no mark = off, b = both on and off tested
# option | Update | UpdateDryRun | UpdateKeep | UpdateCache | TestZstash.add_files (used in multiple tests)|
# --hpss |x|x|x|x|x|
# --cache | | | |x|b|
# --dry-run | |x| | | |
# --keep | | |x| |b|
# -v | | | | |b|
def helperUpdate(self, test_name, hpss_path, zstash_path=ZSTASH_PATH):
"""
Test `zstash update`.
"""
self.hpss_path = hpss_path
use_hpss = self.setupDirs(test_name)
self.create(use_hpss, zstash_path)
print_starred(
"Running update on the newly created directory, nothing should happen"
)
self.assertWorkspace()
os.chdir(self.test_dir)
cmd = "{}zstash update -v --hpss={}".format(zstash_path, self.hpss_path)
output, err = run_cmd(cmd)
os.chdir(TOP_LEVEL)
self.check_strings(cmd, output + err, ["Nothing to update"], ["ERROR"])
def helperUpdateDryRun(self, test_name, hpss_path, zstash_path=ZSTASH_PATH):
"""
Test `zstash update --dry-run`.
"""
self.hpss_path = hpss_path
use_hpss = self.setupDirs(test_name)
self.create(use_hpss, zstash_path)
print_starred("Testing update with an actual change")
self.assertWorkspace()
if not os.path.exists("{}/dir2".format(self.test_dir)):
os.mkdir("{}/dir2".format(self.test_dir))
write_file("{}/dir2/file2.txt".format(self.test_dir), "file2 stuff")
write_file("{}/dir/file1.txt".format(self.test_dir), "file1 stuff with changes")
os.chdir(self.test_dir)
cmd = "{}zstash update --dry-run --hpss={}".format(zstash_path, self.hpss_path)
output, err = run_cmd(cmd)
os.chdir(TOP_LEVEL)
expected_present = [
"List of files to be updated",
"dir/file1.txt",
"dir2/file2.txt",
]
# Make sure none of the old files or directories are moved.
expected_absent = [
"ERROR",
"file0",
"file_empty",
"empty_dir",
"INFO: Creating new tar archive",
]
self.check_strings(cmd, output + err, expected_present, expected_absent)
def helperUpdateKeep(self, test_name, hpss_path, zstash_path=ZSTASH_PATH):
"""
Test `zstash update --keep`.
"""
self.hpss_path = hpss_path
use_hpss = self.setupDirs(test_name)
# Not keeping the tar from `create`.
self.create(use_hpss, zstash_path)
self.add_files(use_hpss, zstash_path, keep=True)
files = os.listdir("{}/{}".format(self.test_dir, self.cache))
if use_hpss:
expected_files = [
"index.db",
"000003.tar",
"000004.tar",
"000001.tar",
"000002.tar",
]
else:
expected_files = [
"index.db",
"000003.tar",
"000004.tar",
"000000.tar",
"000001.tar",
"000002.tar",
]
if not compare(files, expected_files):
error_message = (
"The zstash cache does not contain expected files.\nIt has: {}".format(
files
)
)
self.stop(error_message)
os.chdir(TOP_LEVEL)
def helperUpdateCache(self, test_name, hpss_path, zstash_path=ZSTASH_PATH):
"""
Test `zstash update --cache`.
"""
self.hpss_path = hpss_path
self.cache = "my_cache"
use_hpss = self.setupDirs(test_name)
self.create(use_hpss, zstash_path, cache=self.cache)
self.add_files(use_hpss, zstash_path, cache=self.cache)
files = os.listdir("{}/{}".format(self.test_dir, self.cache))
if use_hpss:
expected_files = ["index.db"]
else:
expected_files = [
"index.db",
"000003.tar",
"000004.tar",
"000000.tar",
"000001.tar",
"000002.tar",
]
if not compare(files, expected_files):
error_message = (
"The zstash cache does not contain expected files.\nIt has: {}".format(
files
)
)
self.stop(error_message)
def testUpdate(self):
self.helperUpdate("testUpdate", "none")
def testUpdateHPSS(self):
self.conditional_hpss_skip()
self.helperUpdate("testUpdateHPSS", HPSS_ARCHIVE)
def testUpdateDryRun(self):
self.helperUpdateDryRun("testUpdateDryRun", "none")
def testUpdateDryRunHPSS(self):
self.conditional_hpss_skip()
self.helperUpdateDryRun("testUpdateDryRunHPSS", HPSS_ARCHIVE)
def testUpdateKeep(self):
self.helperUpdateKeep("testUpdateKeep", "none")
def testUpdateKeepHPSS(self):
self.conditional_hpss_skip()
self.helperUpdateKeep("testUpdateKeepHPSS", HPSS_ARCHIVE)
def testUpdateCache(self):
self.helperUpdateCache("testUpdateCache", "none")
def testUpdateCacheHPSS(self):
self.conditional_hpss_skip()
self.helperUpdateCache("testUpdateCacheHPSS", HPSS_ARCHIVE)
if __name__ == "__main__":
unittest.main()
| 32.274286
| 112
| 0.561969
|
import os
import unittest
from tests.base import (
HPSS_ARCHIVE,
TOP_LEVEL,
ZSTASH_PATH,
TestZstash,
compare,
print_starred,
run_cmd,
write_file,
)
class TestUpdate(TestZstash):
def helperUpdate(self, test_name, hpss_path, zstash_path=ZSTASH_PATH):
self.hpss_path = hpss_path
use_hpss = self.setupDirs(test_name)
self.create(use_hpss, zstash_path)
print_starred(
"Running update on the newly created directory, nothing should happen"
)
self.assertWorkspace()
os.chdir(self.test_dir)
cmd = "{}zstash update -v --hpss={}".format(zstash_path, self.hpss_path)
output, err = run_cmd(cmd)
os.chdir(TOP_LEVEL)
self.check_strings(cmd, output + err, ["Nothing to update"], ["ERROR"])
def helperUpdateDryRun(self, test_name, hpss_path, zstash_path=ZSTASH_PATH):
self.hpss_path = hpss_path
use_hpss = self.setupDirs(test_name)
self.create(use_hpss, zstash_path)
print_starred("Testing update with an actual change")
self.assertWorkspace()
if not os.path.exists("{}/dir2".format(self.test_dir)):
os.mkdir("{}/dir2".format(self.test_dir))
write_file("{}/dir2/file2.txt".format(self.test_dir), "file2 stuff")
write_file("{}/dir/file1.txt".format(self.test_dir), "file1 stuff with changes")
os.chdir(self.test_dir)
cmd = "{}zstash update --dry-run --hpss={}".format(zstash_path, self.hpss_path)
output, err = run_cmd(cmd)
os.chdir(TOP_LEVEL)
expected_present = [
"List of files to be updated",
"dir/file1.txt",
"dir2/file2.txt",
]
expected_absent = [
"ERROR",
"file0",
"file_empty",
"empty_dir",
"INFO: Creating new tar archive",
]
self.check_strings(cmd, output + err, expected_present, expected_absent)
def helperUpdateKeep(self, test_name, hpss_path, zstash_path=ZSTASH_PATH):
self.hpss_path = hpss_path
use_hpss = self.setupDirs(test_name)
self.create(use_hpss, zstash_path)
self.add_files(use_hpss, zstash_path, keep=True)
files = os.listdir("{}/{}".format(self.test_dir, self.cache))
if use_hpss:
expected_files = [
"index.db",
"000003.tar",
"000004.tar",
"000001.tar",
"000002.tar",
]
else:
expected_files = [
"index.db",
"000003.tar",
"000004.tar",
"000000.tar",
"000001.tar",
"000002.tar",
]
if not compare(files, expected_files):
error_message = (
"The zstash cache does not contain expected files.\nIt has: {}".format(
files
)
)
self.stop(error_message)
os.chdir(TOP_LEVEL)
def helperUpdateCache(self, test_name, hpss_path, zstash_path=ZSTASH_PATH):
self.hpss_path = hpss_path
self.cache = "my_cache"
use_hpss = self.setupDirs(test_name)
self.create(use_hpss, zstash_path, cache=self.cache)
self.add_files(use_hpss, zstash_path, cache=self.cache)
files = os.listdir("{}/{}".format(self.test_dir, self.cache))
if use_hpss:
expected_files = ["index.db"]
else:
expected_files = [
"index.db",
"000003.tar",
"000004.tar",
"000000.tar",
"000001.tar",
"000002.tar",
]
if not compare(files, expected_files):
error_message = (
"The zstash cache does not contain expected files.\nIt has: {}".format(
files
)
)
self.stop(error_message)
def testUpdate(self):
self.helperUpdate("testUpdate", "none")
def testUpdateHPSS(self):
self.conditional_hpss_skip()
self.helperUpdate("testUpdateHPSS", HPSS_ARCHIVE)
def testUpdateDryRun(self):
self.helperUpdateDryRun("testUpdateDryRun", "none")
def testUpdateDryRunHPSS(self):
self.conditional_hpss_skip()
self.helperUpdateDryRun("testUpdateDryRunHPSS", HPSS_ARCHIVE)
def testUpdateKeep(self):
self.helperUpdateKeep("testUpdateKeep", "none")
def testUpdateKeepHPSS(self):
self.conditional_hpss_skip()
self.helperUpdateKeep("testUpdateKeepHPSS", HPSS_ARCHIVE)
def testUpdateCache(self):
self.helperUpdateCache("testUpdateCache", "none")
def testUpdateCacheHPSS(self):
self.conditional_hpss_skip()
self.helperUpdateCache("testUpdateCacheHPSS", HPSS_ARCHIVE)
if __name__ == "__main__":
unittest.main()
| true
| true
|
790e51ca452c9f9b5b925fe3dd3dcaaa9a257ee3
| 1,452
|
py
|
Python
|
bentoml/yatai/repository/__init__.py
|
henrywu2019/BentoML
|
d3665f052374a1a419b2a3912b1986334fdae2ac
|
[
"Apache-2.0"
] | 3,451
|
2019-04-02T01:47:42.000Z
|
2022-03-31T16:20:49.000Z
|
bentoml/yatai/repository/__init__.py
|
henrywu2019/BentoML
|
d3665f052374a1a419b2a3912b1986334fdae2ac
|
[
"Apache-2.0"
] | 1,925
|
2019-04-03T00:19:05.000Z
|
2022-03-31T22:41:54.000Z
|
bentoml/yatai/repository/__init__.py
|
henrywu2019/BentoML
|
d3665f052374a1a419b2a3912b1986334fdae2ac
|
[
"Apache-2.0"
] | 451
|
2019-04-02T01:53:41.000Z
|
2022-03-29T08:49:06.000Z
|
# Copyright 2019 Atalaya Tech, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from bentoml.yatai.repository.base_repository import BaseRepository
from bentoml.yatai.repository.file_system_repository import FileSystemRepository
from bentoml.yatai.repository.s3_repository import S3Repository
from bentoml.yatai.repository.gcs_repository import GCSRepository
def create_repository(
repository_type: str,
file_system_directory=None,
s3_url=None,
s3_endpoint_url=None,
gcs_url=None,
) -> BaseRepository:
"""Creates a repository based on a provided type and parameters"""
if repository_type == "s3":
return S3Repository(s3_url, endpoint_url=s3_endpoint_url)
elif repository_type == "gcs":
return GCSRepository(gcs_url)
elif repository_type == "file_system":
return FileSystemRepository(file_system_directory)
else:
raise ValueError("Unrecognized repository type {}" % repository_type)
| 39.243243
| 80
| 0.769284
|
from bentoml.yatai.repository.base_repository import BaseRepository
from bentoml.yatai.repository.file_system_repository import FileSystemRepository
from bentoml.yatai.repository.s3_repository import S3Repository
from bentoml.yatai.repository.gcs_repository import GCSRepository
def create_repository(
repository_type: str,
file_system_directory=None,
s3_url=None,
s3_endpoint_url=None,
gcs_url=None,
) -> BaseRepository:
if repository_type == "s3":
return S3Repository(s3_url, endpoint_url=s3_endpoint_url)
elif repository_type == "gcs":
return GCSRepository(gcs_url)
elif repository_type == "file_system":
return FileSystemRepository(file_system_directory)
else:
raise ValueError("Unrecognized repository type {}" % repository_type)
| true
| true
|
790e51ee35e2f07744708831775bcdd4ccc9b250
| 159
|
py
|
Python
|
utils/image.py
|
Amjad50/Fyp
|
6bd934ef42edf7e355ade6cf5d2a151f098f2352
|
[
"BSD-3-Clause"
] | 1
|
2021-08-17T10:33:17.000Z
|
2021-08-17T10:33:17.000Z
|
utils/image.py
|
Amjad50/Fyp
|
6bd934ef42edf7e355ade6cf5d2a151f098f2352
|
[
"BSD-3-Clause"
] | null | null | null |
utils/image.py
|
Amjad50/Fyp
|
6bd934ef42edf7e355ade6cf5d2a151f098f2352
|
[
"BSD-3-Clause"
] | null | null | null |
from PIL import Image
def img_to_binary(img: Image, min_value=100) -> Image:
return img.convert('L').point(lambda p: p > min_value and 255).convert('1')
| 26.5
| 79
| 0.704403
|
from PIL import Image
def img_to_binary(img: Image, min_value=100) -> Image:
return img.convert('L').point(lambda p: p > min_value and 255).convert('1')
| true
| true
|
790e545878fcf0aed12e117eb2963dd0a8f29329
| 61,361
|
py
|
Python
|
lib/spack/spack/solver/asp.py
|
mtmiller/spack
|
c97c135f1dbe24955048fcc4f0f98281ef0c9300
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 2
|
2018-11-16T02:42:57.000Z
|
2019-06-06T19:18:50.000Z
|
lib/spack/spack/solver/asp.py
|
mtmiller/spack
|
c97c135f1dbe24955048fcc4f0f98281ef0c9300
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 18
|
2021-03-12T16:22:58.000Z
|
2022-03-02T17:07:08.000Z
|
lib/spack/spack/solver/asp.py
|
mtmiller/spack
|
c97c135f1dbe24955048fcc4f0f98281ef0c9300
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 1
|
2021-06-28T04:48:37.000Z
|
2021-06-28T04:48:37.000Z
|
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from __future__ import print_function
import collections
import copy
import itertools
import os
import pprint
import sys
import types
import warnings
from six import string_types
import archspec.cpu
try:
import clingo
# There may be a better way to detect this
clingo_cffi = hasattr(clingo.Symbol, '_rep')
except ImportError:
clingo = None # type: ignore
clingo_cffi = False
import llnl.util.lang
import llnl.util.tty as tty
import spack
import spack.architecture
import spack.bootstrap
import spack.cmd
import spack.compilers
import spack.config
import spack.dependency
import spack.directives
import spack.environment as ev
import spack.error
import spack.package
import spack.package_prefs
import spack.repo
import spack.spec
import spack.util.timer
import spack.variant
import spack.version
if sys.version_info >= (3, 3):
from collections.abc import Sequence # novm
else:
from collections import Sequence
#: Enumeration like object to mark version provenance
version_provenance = collections.namedtuple( # type: ignore
'VersionProvenance', ['external', 'packages_yaml', 'package_py', 'spec']
)(spec=0, external=1, packages_yaml=2, package_py=3)
#: String representation of version origins, to emit legible
# facts for the ASP solver
version_origin_str = {
0: 'spec',
1: 'external',
2: 'packages_yaml',
3: 'package_py'
}
#: Named tuple to contain information on declared versions
DeclaredVersion = collections.namedtuple(
'DeclaredVersion', ['version', 'idx', 'origin']
)
def issequence(obj):
if isinstance(obj, string_types):
return False
return isinstance(obj, (Sequence, types.GeneratorType))
def listify(args):
if len(args) == 1 and issequence(args[0]):
return list(args[0])
return list(args)
def packagize(pkg):
if isinstance(pkg, string_types):
return spack.repo.path.get_pkg_class(pkg)
else:
return pkg
def specify(spec):
if isinstance(spec, spack.spec.Spec):
return spec
return spack.spec.Spec(spec)
class AspObject(object):
"""Object representing a piece of ASP code."""
def _id(thing):
"""Quote string if needed for it to be a valid identifier."""
if isinstance(thing, AspObject):
return thing
elif isinstance(thing, bool):
return '"%s"' % str(thing)
elif isinstance(thing, int):
return str(thing)
else:
return '"%s"' % str(thing)
@llnl.util.lang.key_ordering
class AspFunction(AspObject):
def __init__(self, name, args=None):
self.name = name
self.args = () if args is None else args
def _cmp_key(self):
return (self.name, self.args)
def __call__(self, *args):
return AspFunction(self.name, args)
def symbol(self, positive=True):
def argify(arg):
if isinstance(arg, bool):
return clingo.String(str(arg))
elif isinstance(arg, int):
return clingo.Number(arg)
else:
return clingo.String(str(arg))
return clingo.Function(
self.name, [argify(arg) for arg in self.args], positive=positive)
def __str__(self):
return "%s(%s)" % (
self.name, ', '.join(str(_id(arg)) for arg in self.args))
def __repr__(self):
return str(self)
class AspFunctionBuilder(object):
def __getattr__(self, name):
return AspFunction(name)
fn = AspFunctionBuilder()
def all_compilers_in_config():
return spack.compilers.all_compilers()
def extend_flag_list(flag_list, new_flags):
"""Extend a list of flags, preserving order and precedence.
Add new_flags at the end of flag_list. If any flags in new_flags are
already in flag_list, they are moved to the end so that they take
higher precedence on the compile line.
"""
for flag in new_flags:
if flag in flag_list:
flag_list.remove(flag)
flag_list.append(flag)
def check_same_flags(flag_dict_1, flag_dict_2):
"""Return True if flag dicts contain the same flags regardless of order."""
types = set(flag_dict_1.keys()).union(set(flag_dict_2.keys()))
for t in types:
values1 = set(flag_dict_1.get(t, []))
values2 = set(flag_dict_2.get(t, []))
assert values1 == values2
def check_packages_exist(specs):
"""Ensure all packages mentioned in specs exist."""
repo = spack.repo.path
for spec in specs:
for s in spec.traverse():
try:
check_passed = repo.exists(s.name) or repo.is_virtual(s.name)
except Exception as e:
msg = 'Cannot find package: {0}'.format(str(e))
check_passed = False
tty.debug(msg)
if not check_passed:
raise spack.repo.UnknownPackageError(str(s.fullname))
class Result(object):
"""Result of an ASP solve."""
def __init__(self, specs, asp=None):
self.asp = asp
self.satisfiable = None
self.optimal = None
self.warnings = None
self.nmodels = 0
# specs ordered by optimization level
self.answers = []
self.cores = []
# names of optimization criteria
self.criteria = []
# Abstract user requests
self.abstract_specs = specs
# Concrete specs
self._concrete_specs = None
def print_cores(self):
for core in self.cores:
tty.msg(
"The following constraints are unsatisfiable:",
*sorted(str(symbol) for symbol in core))
@property
def specs(self):
"""List of concretized specs satisfying the initial
abstract request.
"""
# The specs were already computed, return them
if self._concrete_specs:
return self._concrete_specs
# Assert prerequisite
msg = 'cannot compute specs ["satisfiable" is not True ]'
assert self.satisfiable, msg
self._concrete_specs = []
best = min(self.answers)
opt, _, answer = best
for input_spec in self.abstract_specs:
key = input_spec.name
if input_spec.virtual:
providers = [spec.name for spec in answer.values()
if spec.package.provides(key)]
key = providers[0]
self._concrete_specs.append(answer[key])
return self._concrete_specs
def _normalize_packages_yaml(packages_yaml):
normalized_yaml = copy.copy(packages_yaml)
for pkg_name in packages_yaml:
is_virtual = spack.repo.path.is_virtual(pkg_name)
if pkg_name == 'all' or not is_virtual:
continue
# Remove the virtual entry from the normalized configuration
data = normalized_yaml.pop(pkg_name)
is_buildable = data.get('buildable', True)
if not is_buildable:
for provider in spack.repo.path.providers_for(pkg_name):
entry = normalized_yaml.setdefault(provider.name, {})
entry['buildable'] = False
externals = data.get('externals', [])
keyfn = lambda x: spack.spec.Spec(x['spec']).name
for provider, specs in itertools.groupby(externals, key=keyfn):
entry = normalized_yaml.setdefault(provider, {})
entry.setdefault('externals', []).extend(specs)
return normalized_yaml
class PyclingoDriver(object):
def __init__(self, cores=True, asp=None):
"""Driver for the Python clingo interface.
Arguments:
cores (bool): whether to generate unsatisfiable cores for better
error reporting.
asp (file-like): optional stream to write a text-based ASP program
for debugging or verification.
"""
global clingo
if not clingo:
with spack.bootstrap.ensure_bootstrap_configuration():
spack.bootstrap.ensure_clingo_importable_or_raise()
import clingo
self.out = asp or llnl.util.lang.Devnull()
self.cores = cores
def title(self, name, char):
self.out.write('\n')
self.out.write("%" + (char * 76))
self.out.write('\n')
self.out.write("%% %s\n" % name)
self.out.write("%" + (char * 76))
self.out.write('\n')
def h1(self, name):
self.title(name, "=")
def h2(self, name):
self.title(name, "-")
def newline(self):
self.out.write('\n')
def fact(self, head):
"""ASP fact (a rule without a body)."""
symbol = head.symbol() if hasattr(head, 'symbol') else head
self.out.write("%s.\n" % str(symbol))
atom = self.backend.add_atom(symbol)
self.backend.add_rule([atom], [], choice=self.cores)
if self.cores:
self.assumptions.append(atom)
def solve(
self, solver_setup, specs, dump=None, nmodels=0,
timers=False, stats=False, tests=False
):
timer = spack.util.timer.Timer()
# Initialize the control object for the solver
self.control = clingo.Control()
self.control.configuration.solve.models = nmodels
self.control.configuration.asp.trans_ext = 'all'
self.control.configuration.asp.eq = '5'
self.control.configuration.configuration = 'tweety'
self.control.configuration.solve.parallel_mode = '2'
self.control.configuration.solver.opt_strategy = "usc,one"
# set up the problem -- this generates facts and rules
self.assumptions = []
with self.control.backend() as backend:
self.backend = backend
solver_setup.setup(self, specs, tests=tests)
timer.phase("setup")
# read in the main ASP program and display logic -- these are
# handwritten, not generated, so we load them as resources
parent_dir = os.path.dirname(__file__)
self.control.load(os.path.join(parent_dir, 'concretize.lp'))
self.control.load(os.path.join(parent_dir, "display.lp"))
timer.phase("load")
# Grounding is the first step in the solve -- it turns our facts
# and first-order logic rules into propositional logic.
self.control.ground([("base", [])])
timer.phase("ground")
# With a grounded program, we can run the solve.
result = Result(specs)
models = [] # stable models if things go well
cores = [] # unsatisfiable cores if they do not
def on_model(model):
models.append((model.cost, model.symbols(shown=True, terms=True)))
solve_kwargs = {"assumptions": self.assumptions,
"on_model": on_model,
"on_core": cores.append}
if clingo_cffi:
solve_kwargs["on_unsat"] = cores.append
solve_result = self.control.solve(**solve_kwargs)
timer.phase("solve")
# once done, construct the solve result
result.satisfiable = solve_result.satisfiable
def stringify(x):
if clingo_cffi:
# Clingo w/ CFFI will throw an exception on failure
try:
return x.string
except RuntimeError:
return str(x)
else:
return x.string or str(x)
if result.satisfiable:
# build spec from the best model
builder = SpecBuilder(specs)
min_cost, best_model = min(models)
tuples = [
(sym.name, [stringify(a) for a in sym.arguments])
for sym in best_model
]
answers = builder.build_specs(tuples)
# add best spec to the results
result.answers.append((list(min_cost), 0, answers))
# pull optimization criteria names out of the solution
criteria = [
(int(args[0]), args[1]) for name, args in tuples
if name == "opt_criterion"
]
result.criteria = [t[1] for t in sorted(criteria, reverse=True)]
# record the number of models the solver considered
result.nmodels = len(models)
elif cores:
symbols = dict(
(a.literal, a.symbol)
for a in self.control.symbolic_atoms
)
for core in cores:
core_symbols = []
for atom in core:
sym = symbols[atom]
if sym.name == "rule":
sym = sym.arguments[0].string
core_symbols.append(sym)
result.cores.append(core_symbols)
if timers:
timer.write_tty()
print()
if stats:
print("Statistics:")
pprint.pprint(self.control.statistics)
return result
class SpackSolverSetup(object):
"""Class to set up and run a Spack concretization solve."""
def __init__(self):
self.gen = None # set by setup()
self.declared_versions = {}
self.possible_versions = {}
self.deprecated_versions = {}
self.possible_virtuals = None
self.possible_compilers = []
self.variant_values_from_specs = set()
self.version_constraints = set()
self.target_constraints = set()
self.compiler_version_constraints = set()
self.post_facts = []
# id for dummy variables
self._condition_id_counter = itertools.count()
# Caches to optimize the setup phase of the solver
self.target_specs_cache = None
def pkg_version_rules(self, pkg):
"""Output declared versions of a package.
This uses self.possible_versions so that we include any versions
that arise from a spec.
"""
def key_fn(version):
# Origins are sorted by order of importance:
# 1. Spec from command line
# 2. Externals
# 3. Package preferences
# 4. Directives in package.py
return version.origin, version.idx
pkg = packagize(pkg)
declared_versions = self.declared_versions[pkg.name]
most_to_least_preferred = sorted(declared_versions, key=key_fn)
for weight, declared_version in enumerate(most_to_least_preferred):
self.gen.fact(fn.version_declared(
pkg.name, declared_version.version, weight,
version_origin_str[declared_version.origin]
))
# Declare deprecated versions for this package, if any
deprecated = self.deprecated_versions[pkg.name]
for v in sorted(deprecated):
self.gen.fact(fn.deprecated_version(pkg.name, v))
def spec_versions(self, spec):
"""Return list of clauses expressing spec's version constraints."""
spec = specify(spec)
assert spec.name
if spec.concrete:
return [fn.version(spec.name, spec.version)]
if spec.versions == spack.version.ver(":"):
return []
# record all version constraints for later
self.version_constraints.add((spec.name, spec.versions))
return [fn.version_satisfies(spec.name, spec.versions)]
def target_ranges(self, spec, single_target_fn):
target = spec.architecture.target
# Check if the target is a concrete target
if str(target) in archspec.cpu.TARGETS:
return [single_target_fn(spec.name, target)]
self.target_constraints.add((spec.name, target))
return [fn.node_target_satisfies(spec.name, target)]
def conflict_rules(self, pkg):
for trigger, constraints in pkg.conflicts.items():
trigger_id = self.condition(spack.spec.Spec(trigger), name=pkg.name)
self.gen.fact(fn.conflict_trigger(trigger_id))
for constraint, _ in constraints:
constraint_id = self.condition(constraint, name=pkg.name)
self.gen.fact(fn.conflict(pkg.name, trigger_id, constraint_id))
self.gen.newline()
def available_compilers(self):
"""Facts about available compilers."""
self.gen.h2("Available compilers")
compilers = self.possible_compilers
compiler_versions = collections.defaultdict(lambda: set())
for compiler in compilers:
compiler_versions[compiler.name].add(compiler.version)
for compiler in sorted(compiler_versions):
for v in sorted(compiler_versions[compiler]):
self.gen.fact(fn.compiler_version(compiler, v))
self.gen.newline()
def compiler_defaults(self):
"""Set compiler defaults, given a list of possible compilers."""
self.gen.h2("Default compiler preferences")
compiler_list = self.possible_compilers.copy()
compiler_list = sorted(
compiler_list, key=lambda x: (x.name, x.version), reverse=True)
ppk = spack.package_prefs.PackagePrefs("all", 'compiler', all=False)
matches = sorted(compiler_list, key=ppk)
for i, cspec in enumerate(matches):
f = fn.default_compiler_preference(cspec.name, cspec.version, i)
self.gen.fact(f)
# Enumerate target families. This may be redundant, but compilers with
# custom versions will be able to concretize properly.
for entry in spack.compilers.all_compilers_config():
compiler_entry = entry['compiler']
cspec = spack.spec.CompilerSpec(compiler_entry['spec'])
if not compiler_entry.get('target', None):
continue
self.gen.fact(fn.compiler_supports_target(
cspec.name, cspec.version, compiler_entry['target']
))
def compiler_supports_os(self):
compilers_yaml = spack.compilers.all_compilers_config()
for entry in compilers_yaml:
c = spack.spec.CompilerSpec(entry['compiler']['spec'])
operating_system = entry['compiler']['operating_system']
self.gen.fact(fn.compiler_supports_os(
c.name, c.version, operating_system
))
def package_compiler_defaults(self, pkg):
"""Facts about packages' compiler prefs."""
packages = spack.config.get("packages")
pkg_prefs = packages.get(pkg.name)
if not pkg_prefs or "compiler" not in pkg_prefs:
return
compiler_list = self.possible_compilers.copy()
compiler_list = sorted(
compiler_list, key=lambda x: (x.name, x.version), reverse=True)
ppk = spack.package_prefs.PackagePrefs(pkg.name, 'compiler', all=False)
matches = sorted(compiler_list, key=ppk)
for i, cspec in enumerate(reversed(matches)):
self.gen.fact(fn.node_compiler_preference(
pkg.name, cspec.name, cspec.version, -i * 100
))
def pkg_rules(self, pkg, tests):
pkg = packagize(pkg)
# versions
self.pkg_version_rules(pkg)
self.gen.newline()
# variants
for name, variant in sorted(pkg.variants.items()):
self.gen.fact(fn.variant(pkg.name, name))
single_value = not variant.multi
if single_value:
self.gen.fact(fn.variant_single_value(pkg.name, name))
self.gen.fact(
fn.variant_default_value_from_package_py(
pkg.name, name, variant.default)
)
else:
spec_variant = variant.make_default()
defaults = spec_variant.value
for val in sorted(defaults):
self.gen.fact(
fn.variant_default_value_from_package_py(
pkg.name, name, val)
)
values = variant.values
if values is None:
values = []
elif isinstance(values, spack.variant.DisjointSetsOfValues):
union = set()
# Encode the disjoint sets in the logic program
for sid, s in enumerate(values.sets):
for value in s:
self.gen.fact(fn.variant_value_from_disjoint_sets(
pkg.name, name, value, sid
))
union.update(s)
values = union
# make sure that every variant has at least one possible value
if not values:
values = [variant.default]
for value in sorted(values):
self.gen.fact(fn.variant_possible_value(pkg.name, name, value))
self.gen.newline()
# conflicts
self.conflict_rules(pkg)
# default compilers for this package
self.package_compiler_defaults(pkg)
# virtuals
self.package_provider_rules(pkg)
# dependencies
self.package_dependencies_rules(pkg, tests)
# virtual preferences
self.virtual_preferences(
pkg.name,
lambda v, p, i: self.gen.fact(
fn.pkg_provider_preference(pkg.name, v, p, i)
)
)
def condition(self, required_spec, imposed_spec=None, name=None):
"""Generate facts for a dependency or virtual provider condition.
Arguments:
required_spec (spack.spec.Spec): the spec that triggers this condition
imposed_spec (spack.spec.Spec or None): the sepc with constraints that
are imposed when this condition is triggered
name (str or None): name for `required_spec` (required if
required_spec is anonymous, ignored if not)
Returns:
int: id of the condition created by this function
"""
named_cond = required_spec.copy()
named_cond.name = named_cond.name or name
assert named_cond.name, "must provide name for anonymous condtions!"
condition_id = next(self._condition_id_counter)
self.gen.fact(fn.condition(condition_id))
# requirements trigger the condition
requirements = self.checked_spec_clauses(
named_cond, body=True, required_from=name)
for pred in requirements:
self.gen.fact(
fn.condition_requirement(condition_id, pred.name, *pred.args)
)
if imposed_spec:
imposed_constraints = self.checked_spec_clauses(
imposed_spec, body=False, required_from=name)
for pred in imposed_constraints:
# imposed "node"-like conditions are no-ops
if pred.name in ("node", "virtual_node"):
continue
self.gen.fact(
fn.imposed_constraint(condition_id, pred.name, *pred.args)
)
return condition_id
def package_provider_rules(self, pkg):
for provider_name in sorted(set(s.name for s in pkg.provided.keys())):
self.gen.fact(fn.possible_provider(pkg.name, provider_name))
for provided, whens in pkg.provided.items():
for when in whens:
condition_id = self.condition(when, provided, pkg.name)
self.gen.fact(fn.provider_condition(
condition_id, when.name, provided.name
))
self.gen.newline()
def package_dependencies_rules(self, pkg, tests):
"""Translate 'depends_on' directives into ASP logic."""
for _, conditions in sorted(pkg.dependencies.items()):
for cond, dep in sorted(conditions.items()):
deptypes = dep.type.copy()
# Skip test dependencies if they're not requested
if not tests:
deptypes.discard("test")
# ... or if they are requested only for certain packages
if not isinstance(tests, bool) and pkg.name not in tests:
deptypes.discard("test")
# if there are no dependency types to be considered
# anymore, don't generate the dependency
if not deptypes:
continue
condition_id = self.condition(cond, dep.spec, pkg.name)
self.gen.fact(fn.dependency_condition(
condition_id, pkg.name, dep.spec.name
))
for t in sorted(deptypes):
# there is a declared dependency of type t
self.gen.fact(fn.dependency_type(condition_id, t))
self.gen.newline()
def virtual_preferences(self, pkg_name, func):
"""Call func(vspec, provider, i) for each of pkg's provider prefs."""
config = spack.config.get("packages")
pkg_prefs = config.get(pkg_name, {}).get("providers", {})
for vspec, providers in pkg_prefs.items():
if vspec not in self.possible_virtuals:
continue
for i, provider in enumerate(providers):
provider_name = spack.spec.Spec(provider).name
func(vspec, provider_name, i)
def provider_defaults(self):
self.gen.h2("Default virtual providers")
assert self.possible_virtuals is not None
self.virtual_preferences(
"all",
lambda v, p, i: self.gen.fact(
fn.default_provider_preference(v, p, i))
)
def external_packages(self):
"""Facts on external packages, as read from packages.yaml"""
# Read packages.yaml and normalize it, so that it
# will not contain entries referring to virtual
# packages.
packages_yaml = spack.config.get("packages")
packages_yaml = _normalize_packages_yaml(packages_yaml)
self.gen.h1('External packages')
for pkg_name, data in packages_yaml.items():
if pkg_name == 'all':
continue
# This package does not appear in any repository
if pkg_name not in spack.repo.path:
continue
self.gen.h2('External package: {0}'.format(pkg_name))
# Check if the external package is buildable. If it is
# not then "external(<pkg>)" is a fact.
external_buildable = data.get('buildable', True)
if not external_buildable:
self.gen.fact(fn.external_only(pkg_name))
# Read a list of all the specs for this package
externals = data.get('externals', [])
external_specs = [spack.spec.Spec(x['spec']) for x in externals]
# Order the external versions to prefer more recent versions
# even if specs in packages.yaml are not ordered that way
external_versions = [
(x.version, external_id)
for external_id, x in enumerate(external_specs)
]
external_versions = [
(v, idx, external_id)
for idx, (v, external_id) in
enumerate(sorted(external_versions, reverse=True))
]
for version, idx, external_id in external_versions:
self.declared_versions[pkg_name].append(DeclaredVersion(
version=version,
idx=idx,
origin=version_provenance.external
))
# Declare external conditions with a local index into packages.yaml
for local_idx, spec in enumerate(external_specs):
condition_id = self.condition(spec)
self.gen.fact(
fn.possible_external(condition_id, pkg_name, local_idx)
)
self.possible_versions[spec.name].add(spec.version)
self.gen.newline()
def preferred_variants(self, pkg_name):
"""Facts on concretization preferences, as read from packages.yaml"""
preferences = spack.package_prefs.PackagePrefs
preferred_variants = preferences.preferred_variants(pkg_name)
if not preferred_variants:
return
for variant_name in sorted(preferred_variants):
variant = preferred_variants[variant_name]
values = variant.value
if not isinstance(values, tuple):
values = (values,)
# perform validation of the variant and values
spec = spack.spec.Spec(pkg_name)
spec.update_variant_validate(variant_name, values)
for value in values:
self.variant_values_from_specs.add(
(pkg_name, variant.name, value)
)
self.gen.fact(fn.variant_default_value_from_packages_yaml(
pkg_name, variant.name, value
))
def preferred_targets(self, pkg_name):
key_fn = spack.package_prefs.PackagePrefs(pkg_name, 'target')
if not self.target_specs_cache:
self.target_specs_cache = [
spack.spec.Spec('target={0}'.format(target_name))
for target_name in archspec.cpu.TARGETS
]
target_specs = self.target_specs_cache
preferred_targets = [x for x in target_specs if key_fn(x) < 0]
if not preferred_targets:
return
preferred = preferred_targets[0]
self.gen.fact(fn.package_target_weight(
str(preferred.architecture.target), pkg_name, -30
))
def flag_defaults(self):
self.gen.h2("Compiler flag defaults")
# types of flags that can be on specs
for flag in spack.spec.FlagMap.valid_compiler_flags():
self.gen.fact(fn.flag_type(flag))
self.gen.newline()
# flags from compilers.yaml
compilers = all_compilers_in_config()
for compiler in compilers:
for name, flags in compiler.flags.items():
for flag in flags:
self.gen.fact(fn.compiler_version_flag(
compiler.name, compiler.version, name, flag))
def checked_spec_clauses(self, *args, **kwargs):
"""Wrap a call to spec clauses into a try/except block that raise
a comprehensible error message in case of failure.
"""
requestor = kwargs.pop('required_from', None)
try:
clauses = self.spec_clauses(*args, **kwargs)
except RuntimeError as exc:
msg = str(exc)
if requestor:
msg += ' [required from package "{0}"]'.format(requestor)
raise RuntimeError(msg)
return clauses
def spec_clauses(self, spec, body=False, transitive=True):
"""Return a list of clauses for a spec mandates are true.
Arguments:
spec (spack.spec.Spec): the spec to analyze
body (bool): if True, generate clauses to be used in rule bodies
(final values) instead of rule heads (setters).
transitive (bool): if False, don't generate clauses from
dependencies (default True)
"""
clauses = []
# TODO: do this with consistent suffixes.
class Head(object):
node = fn.node
virtual_node = fn.virtual_node
node_platform = fn.node_platform_set
node_os = fn.node_os_set
node_target = fn.node_target_set
variant_value = fn.variant_set
node_compiler = fn.node_compiler_set
node_compiler_version = fn.node_compiler_version_set
node_flag = fn.node_flag_set
class Body(object):
node = fn.node
virtual_node = fn.virtual_node
node_platform = fn.node_platform
node_os = fn.node_os
node_target = fn.node_target
variant_value = fn.variant_value
node_compiler = fn.node_compiler
node_compiler_version = fn.node_compiler_version
node_flag = fn.node_flag
f = Body if body else Head
if spec.name:
clauses.append(
f.node(spec.name) if not spec.virtual
else f.virtual_node(spec.name))
clauses.extend(self.spec_versions(spec))
# seed architecture at the root (we'll propagate later)
# TODO: use better semantics.
arch = spec.architecture
if arch:
if arch.platform:
clauses.append(f.node_platform(spec.name, arch.platform))
if arch.os:
clauses.append(f.node_os(spec.name, arch.os))
if arch.target:
clauses.extend(self.target_ranges(spec, f.node_target))
# variants
for vname, variant in sorted(spec.variants.items()):
values = variant.value
if not isinstance(values, (list, tuple)):
values = [values]
for value in values:
# * is meaningless for concretization -- just for matching
if value == '*':
continue
# validate variant value only if spec not concrete
if not spec.concrete:
reserved_names = spack.directives.reserved_names
if not spec.virtual and vname not in reserved_names:
try:
variant_def = spec.package.variants[vname]
except KeyError:
msg = 'variant "{0}" not found in package "{1}"'
raise RuntimeError(msg.format(vname, spec.name))
else:
variant_def.validate_or_raise(variant, spec.package)
clauses.append(f.variant_value(spec.name, vname, value))
# Tell the concretizer that this is a possible value for the
# variant, to account for things like int/str values where we
# can't enumerate the valid values
self.variant_values_from_specs.add((spec.name, vname, value))
# compiler and compiler version
if spec.compiler:
clauses.append(f.node_compiler(spec.name, spec.compiler.name))
if spec.compiler.concrete:
clauses.append(f.node_compiler_version(
spec.name, spec.compiler.name, spec.compiler.version))
elif spec.compiler.versions:
clauses.append(
fn.node_compiler_version_satisfies(
spec.name, spec.compiler.name, spec.compiler.versions))
self.compiler_version_constraints.add(
(spec.name, spec.compiler))
# compiler flags
for flag_type, flags in spec.compiler_flags.items():
for flag in flags:
clauses.append(f.node_flag(spec.name, flag_type, flag))
# dependencies
if spec.concrete:
clauses.append(fn.concrete(spec.name))
# TODO: add concrete depends_on() facts for concrete dependencies
# add all clauses from dependencies
if transitive:
for dep in spec.traverse(root=False):
clauses.extend(self.spec_clauses(dep, body, transitive=False))
return clauses
def build_version_dict(self, possible_pkgs, specs):
"""Declare any versions in specs not declared in packages."""
self.declared_versions = collections.defaultdict(list)
self.possible_versions = collections.defaultdict(set)
self.deprecated_versions = collections.defaultdict(set)
packages_yaml = spack.config.get("packages")
packages_yaml = _normalize_packages_yaml(packages_yaml)
for pkg_name in possible_pkgs:
pkg = spack.repo.get(pkg_name)
# All the versions from the corresponding package.py file. Since concepts
# like being a "develop" version or being preferred exist only at a
# package.py level, sort them in this partial list here
def key_fn(item):
version, info = item
# When COMPARING VERSIONS, the '@develop' version is always
# larger than other versions. BUT when CONCRETIZING, the largest
# NON-develop version is selected by default.
return info.get('preferred', False), not version.isdevelop(), version
for idx, item in enumerate(sorted(
pkg.versions.items(), key=key_fn, reverse=True
)):
v, version_info = item
self.possible_versions[pkg_name].add(v)
self.declared_versions[pkg_name].append(DeclaredVersion(
version=v, idx=idx, origin=version_provenance.package_py
))
deprecated = version_info.get('deprecated', False)
if deprecated:
self.deprecated_versions[pkg_name].add(v)
# All the preferred version from packages.yaml, versions in external
# specs will be computed later
version_preferences = packages_yaml.get(pkg_name, {}).get("version", [])
for idx, v in enumerate(version_preferences):
self.declared_versions[pkg_name].append(DeclaredVersion(
version=v, idx=idx, origin=version_provenance.packages_yaml
))
for spec in specs:
for dep in spec.traverse():
if dep.versions.concrete:
# Concrete versions used in abstract specs from cli. They
# all have idx equal to 0, which is the best possible. In
# any case they will be used due to being set from the cli.
self.declared_versions[dep.name].append(DeclaredVersion(
version=dep.version,
idx=0,
origin=version_provenance.spec
))
self.possible_versions[dep.name].add(dep.version)
def _supported_targets(self, compiler_name, compiler_version, targets):
"""Get a list of which targets are supported by the compiler.
Results are ordered most to least recent.
"""
supported = []
for target in targets:
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
target.optimization_flags(compiler_name, compiler_version)
supported.append(target)
except archspec.cpu.UnsupportedMicroarchitecture:
continue
except ValueError:
continue
return sorted(supported, reverse=True)
def platform_defaults(self):
self.gen.h2('Default platform')
platform = spack.architecture.platform()
self.gen.fact(fn.node_platform_default(platform))
def os_defaults(self, specs):
self.gen.h2('Possible operating systems')
platform = spack.architecture.platform()
# create set of OS's to consider
possible = set([
platform.front_os, platform.back_os, platform.default_os])
for spec in specs:
if spec.architecture and spec.architecture.os:
possible.add(spec.architecture.os)
# make directives for possible OS's
for possible_os in sorted(possible):
self.gen.fact(fn.os(possible_os))
# mark this one as default
self.gen.fact(fn.node_os_default(platform.default_os))
def target_defaults(self, specs):
"""Add facts about targets and target compatibility."""
self.gen.h2('Default target')
platform = spack.architecture.platform()
uarch = archspec.cpu.TARGETS.get(platform.default)
self.gen.h2('Target compatibility')
compatible_targets = [uarch] + uarch.ancestors
additional_targets_in_family = sorted([
t for t in archspec.cpu.TARGETS.values()
if (t.family.name == uarch.family.name and
t not in compatible_targets)
], key=lambda x: len(x.ancestors), reverse=True)
compatible_targets += additional_targets_in_family
compilers = self.possible_compilers
# this loop can be used to limit the number of targets
# considered. Right now we consider them all, but it seems that
# many targets can make things slow.
# TODO: investigate this.
best_targets = set([uarch.family.name])
for compiler in sorted(compilers):
supported = self._supported_targets(
compiler.name, compiler.version, compatible_targets
)
# If we can't find supported targets it may be due to custom
# versions in the spec, e.g. gcc@foo. Try to match the
# real_version from the compiler object to get more accurate
# results.
if not supported:
compiler_obj = spack.compilers.compilers_for_spec(compiler)
compiler_obj = compiler_obj[0]
supported = self._supported_targets(
compiler.name,
compiler_obj.real_version,
compatible_targets
)
if not supported:
continue
for target in supported:
best_targets.add(target.name)
self.gen.fact(fn.compiler_supports_target(
compiler.name, compiler.version, target.name))
self.gen.fact(fn.compiler_supports_target(
compiler.name, compiler.version, uarch.family.name))
# add any targets explicitly mentioned in specs
for spec in specs:
if not spec.architecture or not spec.architecture.target:
continue
target = archspec.cpu.TARGETS.get(spec.target.name)
if not target:
self.target_ranges(spec, None)
continue
if target not in compatible_targets:
compatible_targets.append(target)
i = 0
for target in compatible_targets:
self.gen.fact(fn.target(target.name))
self.gen.fact(fn.target_family(target.name, target.family.name))
for parent in sorted(target.parents):
self.gen.fact(fn.target_parent(target.name, parent.name))
# prefer best possible targets; weight others poorly so
# they're not used unless set explicitly
if target.name in best_targets:
self.gen.fact(fn.default_target_weight(target.name, i))
i += 1
else:
self.gen.fact(fn.default_target_weight(target.name, 100))
self.gen.newline()
def virtual_providers(self):
self.gen.h2("Virtual providers")
assert self.possible_virtuals is not None
# what provides what
for vspec in sorted(self.possible_virtuals):
self.gen.fact(fn.virtual(vspec))
self.gen.newline()
def generate_possible_compilers(self, specs):
compilers = all_compilers_in_config()
cspecs = set([c.spec for c in compilers])
# add compiler specs from the input line to possibilities if we
# don't require compilers to exist.
strict = spack.concretize.Concretizer().check_for_compiler_existence
for spec in specs:
for s in spec.traverse():
if not s.compiler or not s.compiler.concrete:
continue
if strict and s.compiler not in cspecs:
raise spack.concretize.UnavailableCompilerVersionError(
s.compiler
)
else:
cspecs.add(s.compiler)
self.gen.fact(fn.allow_compiler(
s.compiler.name, s.compiler.version
))
return cspecs
def define_version_constraints(self):
"""Define what version_satisfies(...) means in ASP logic."""
for pkg_name, versions in sorted(self.version_constraints):
# version must be *one* of the ones the spec allows.
allowed_versions = [
v for v in sorted(self.possible_versions[pkg_name])
if v.satisfies(versions)
]
# This is needed to account for a variable number of
# numbers e.g. if both 1.0 and 1.0.2 are possible versions
exact_match = [v for v in allowed_versions if v == versions]
if exact_match:
allowed_versions = exact_match
# generate facts for each package constraint and the version
# that satisfies it
for v in allowed_versions:
self.gen.fact(fn.version_satisfies(pkg_name, versions, v))
self.gen.newline()
def define_virtual_constraints(self):
"""Define versions for constraints on virtuals.
Must be called before define_version_constraints().
"""
# aggregate constraints into per-virtual sets
constraint_map = collections.defaultdict(lambda: set())
for pkg_name, versions in self.version_constraints:
if not spack.repo.path.is_virtual(pkg_name):
continue
constraint_map[pkg_name].add(versions)
# extract all the real versions mentioned in version ranges
def versions_for(v):
if isinstance(v, spack.version.Version):
return [v]
elif isinstance(v, spack.version.VersionRange):
result = [v.start] if v.start else []
result += [v.end] if v.end else []
return result
elif isinstance(v, spack.version.VersionList):
return sum((versions_for(e) for e in v), [])
else:
raise TypeError("expected version type, found: %s" % type(v))
# define a set of synthetic possible versions for virtuals, so
# that `version_satisfies(Package, Constraint, Version)` has the
# same semantics for virtuals as for regular packages.
for pkg_name, versions in sorted(constraint_map.items()):
possible_versions = set(
sum([versions_for(v) for v in versions], [])
)
for version in sorted(possible_versions):
self.possible_versions[pkg_name].add(version)
def define_compiler_version_constraints(self):
compiler_list = spack.compilers.all_compiler_specs()
compiler_list = list(sorted(set(compiler_list)))
for pkg_name, cspec in self.compiler_version_constraints:
for compiler in compiler_list:
if compiler.satisfies(cspec):
self.gen.fact(
fn.node_compiler_version_satisfies(
pkg_name,
cspec.name,
cspec.versions,
compiler.version
)
)
self.gen.newline()
def define_target_constraints(self):
def _all_targets_satisfiying(single_constraint):
allowed_targets = []
if ':' not in single_constraint:
return [single_constraint]
t_min, _, t_max = single_constraint.partition(':')
for test_target in archspec.cpu.TARGETS.values():
# Check lower bound
if t_min and not t_min <= test_target:
continue
# Check upper bound
if t_max and not t_max >= test_target:
continue
allowed_targets.append(test_target)
return allowed_targets
cache = {}
for spec_name, target_constraint in sorted(self.target_constraints):
# Construct the list of allowed targets for this constraint
allowed_targets = []
for single_constraint in str(target_constraint).split(','):
if single_constraint not in cache:
cache[single_constraint] = _all_targets_satisfiying(
single_constraint
)
allowed_targets.extend(cache[single_constraint])
for target in allowed_targets:
self.gen.fact(
fn.node_target_satisfies(
spec_name, target_constraint, target
)
)
self.gen.newline()
def define_variant_values(self):
"""Validate variant values from the command line.
Also add valid variant values from the command line to the
possible values for a variant.
"""
# Tell the concretizer about possible values from specs we saw in
# spec_clauses()
for pkg, variant, value in sorted(self.variant_values_from_specs):
self.gen.fact(fn.variant_possible_value(pkg, variant, value))
def setup(self, driver, specs, tests=False):
"""Generate an ASP program with relevant constraints for specs.
This calls methods on the solve driver to set up the problem with
facts and rules from all possible dependencies of the input
specs, as well as constraints from the specs themselves.
Arguments:
specs (list): list of Specs to solve
"""
self._condition_id_counter = itertools.count()
# preliminary checks
check_packages_exist(specs)
# get list of all possible dependencies
self.possible_virtuals = set(
x.name for x in specs if x.virtual
)
possible = spack.package.possible_dependencies(
*specs,
virtuals=self.possible_virtuals,
deptype=spack.dependency.all_deptypes
)
pkgs = set(possible)
# driver is used by all the functions below to add facts and
# rules to generate an ASP program.
self.gen = driver
# get possible compilers
self.possible_compilers = self.generate_possible_compilers(specs)
# traverse all specs and packages to build dict of possible versions
self.build_version_dict(possible, specs)
self.gen.h1('General Constraints')
self.available_compilers()
self.compiler_defaults()
self.compiler_supports_os()
# architecture defaults
self.platform_defaults()
self.os_defaults(specs)
self.target_defaults(specs)
self.virtual_providers()
self.provider_defaults()
self.external_packages()
self.flag_defaults()
self.gen.h1('Package Constraints')
for pkg in sorted(pkgs):
self.gen.h2('Package rules: %s' % pkg)
self.pkg_rules(pkg, tests=tests)
self.gen.h2('Package preferences: %s' % pkg)
self.preferred_variants(pkg)
self.preferred_targets(pkg)
# Inject dev_path from environment
env = ev.active_environment()
if env:
for spec in sorted(specs):
for dep in spec.traverse():
_develop_specs_from_env(dep, env)
self.gen.h1('Spec Constraints')
for spec in sorted(specs):
self.gen.h2('Spec: %s' % str(spec))
self.gen.fact(
fn.virtual_root(spec.name) if spec.virtual
else fn.root(spec.name)
)
for clause in self.spec_clauses(spec):
self.gen.fact(clause)
if clause.name == 'variant_set':
self.gen.fact(fn.variant_default_value_from_cli(
*clause.args
))
self.gen.h1("Variant Values defined in specs")
self.define_variant_values()
self.gen.h1("Virtual Constraints")
self.define_virtual_constraints()
self.gen.h1("Version Constraints")
self.define_version_constraints()
self.gen.h1("Compiler Version Constraints")
self.define_compiler_version_constraints()
self.gen.h1("Target Constraints")
self.define_target_constraints()
class SpecBuilder(object):
"""Class with actions to rebuild a spec from ASP results."""
def __init__(self, specs):
self._result = None
self._command_line_specs = specs
self._flag_sources = collections.defaultdict(lambda: set())
self._flag_compiler_defaults = set()
def node(self, pkg):
if pkg not in self._specs:
self._specs[pkg] = spack.spec.Spec(pkg)
def _arch(self, pkg):
arch = self._specs[pkg].architecture
if not arch:
arch = spack.spec.ArchSpec()
self._specs[pkg].architecture = arch
return arch
def node_platform(self, pkg, platform):
self._arch(pkg).platform = platform
def node_os(self, pkg, os):
self._arch(pkg).os = os
def node_target(self, pkg, target):
self._arch(pkg).target = target
def variant_value(self, pkg, name, value):
# FIXME: is there a way not to special case 'dev_path' everywhere?
if name == 'dev_path':
self._specs[pkg].variants.setdefault(
name,
spack.variant.SingleValuedVariant(name, value)
)
return
if name == 'patches':
self._specs[pkg].variants.setdefault(
name,
spack.variant.MultiValuedVariant(name, value)
)
return
self._specs[pkg].update_variant_validate(name, value)
def version(self, pkg, version):
self._specs[pkg].versions = spack.version.ver([version])
def node_compiler(self, pkg, compiler):
self._specs[pkg].compiler = spack.spec.CompilerSpec(compiler)
def node_compiler_version(self, pkg, compiler, version):
self._specs[pkg].compiler.versions = spack.version.VersionList(
[version])
def node_flag_compiler_default(self, pkg):
self._flag_compiler_defaults.add(pkg)
def node_flag(self, pkg, flag_type, flag):
self._specs[pkg].compiler_flags.setdefault(flag_type, []).append(flag)
def node_flag_source(self, pkg, source):
self._flag_sources[pkg].add(source)
def no_flags(self, pkg, flag_type):
self._specs[pkg].compiler_flags[flag_type] = []
def external_spec_selected(self, pkg, idx):
"""This means that the external spec and index idx
has been selected for this package.
"""
packages_yaml = spack.config.get('packages')
packages_yaml = _normalize_packages_yaml(packages_yaml)
spec_info = packages_yaml[pkg]['externals'][int(idx)]
self._specs[pkg].external_path = spec_info.get('prefix', None)
self._specs[pkg].external_modules = (
spack.spec.Spec._format_module_list(spec_info.get('modules', None))
)
self._specs[pkg].extra_attributes = spec_info.get(
'extra_attributes', {}
)
def depends_on(self, pkg, dep, type):
dependency = self._specs[pkg]._dependencies.get(dep)
if not dependency:
self._specs[pkg]._add_dependency(
self._specs[dep], (type,))
else:
dependency.add_type(type)
def reorder_flags(self):
"""Order compiler flags on specs in predefined order.
We order flags so that any node's flags will take priority over
those of its dependents. That is, the deepest node in the DAG's
flags will appear last on the compile line, in the order they
were specified.
The solver determines wihch flags are on nodes; this routine
imposes order afterwards.
"""
# nodes with no flags get flag order from compiler
compilers = dict((c.spec, c) for c in all_compilers_in_config())
for pkg in self._flag_compiler_defaults:
spec = self._specs[pkg]
compiler_flags = compilers[spec.compiler].flags
check_same_flags(spec.compiler_flags, compiler_flags)
spec.compiler_flags.update(compiler_flags)
# index of all specs (and deps) from the command line by name
cmd_specs = dict(
(s.name, s)
for spec in self._command_line_specs
for s in spec.traverse())
# iterate through specs with specified flags
for pkg, sources in self._flag_sources.items():
spec = self._specs[pkg]
# order is determined by the DAG. A spec's flags come after
# any from its ancestors on the compile line.
order = [
s.name
for s in spec.traverse(order='post', direction='parents')]
# sort the sources in our DAG order
sorted_sources = sorted(
sources, key=lambda s: order.index(s))
# add flags from each source, lowest to highest precedence
flags = collections.defaultdict(lambda: [])
for source_name in sorted_sources:
source = cmd_specs[source_name]
for name, flag_list in source.compiler_flags.items():
extend_flag_list(flags[name], flag_list)
check_same_flags(spec.compiler_flags, flags)
spec.compiler_flags.update(flags)
def deprecated(self, pkg, version):
msg = 'using "{0}@{1}" which is a deprecated version'
tty.warn(msg.format(pkg, version))
def build_specs(self, function_tuples):
# Functions don't seem to be in particular order in output. Sort
# them here so that directives that build objects (like node and
# node_compiler) are called in the right order.
function_tuples.sort(key=lambda f: {
"node": -2,
"node_compiler": -1,
}.get(f[0], 0))
self._specs = {}
for name, args in function_tuples:
action = getattr(self, name, None)
# print out unknown actions so we can display them for debugging
if not action:
msg = "%s(%s)" % (name, ", ".join(str(a) for a in args))
tty.debug(msg)
continue
assert action and callable(action)
# ignore predicates on virtual packages, as they're used for
# solving but don't construct anything
pkg = args[0]
if spack.repo.path.is_virtual(pkg):
continue
action(*args)
# namespace assignment is done after the fact, as it is not
# currently part of the solve
for spec in self._specs.values():
repo = spack.repo.path.repo_for_pkg(spec)
spec.namespace = repo.namespace
# fix flags after all specs are constructed
self.reorder_flags()
# inject patches -- note that we' can't use set() to unique the
# roots here, because the specs aren't complete, and the hash
# function will loop forever.
roots = [spec.root for spec in self._specs.values()]
roots = dict((id(r), r) for r in roots)
for root in roots.values():
spack.spec.Spec.inject_patches_variant(root)
# Add external paths to specs with just external modules
for s in self._specs.values():
spack.spec.Spec.ensure_external_path_if_external(s)
for s in self._specs.values():
_develop_specs_from_env(s, ev.active_environment())
for s in self._specs.values():
s._mark_concrete()
for s in self._specs.values():
spack.spec.Spec.ensure_no_deprecated(s)
return self._specs
def _develop_specs_from_env(spec, env):
dev_info = env.dev_specs.get(spec.name, {}) if env else {}
if not dev_info:
return
path = os.path.normpath(os.path.join(env.path, dev_info['path']))
if 'dev_path' in spec.variants:
assert spec.variants['dev_path'].value == path
else:
spec.variants.setdefault(
'dev_path', spack.variant.SingleValuedVariant('dev_path', path)
)
spec.constrain(dev_info['spec'])
#
# These are handwritten parts for the Spack ASP model.
#
def solve(specs, dump=(), models=0, timers=False, stats=False, tests=False):
"""Solve for a stable model of specs.
Arguments:
specs (list): list of Specs to solve.
dump (tuple): what to dump
models (int): number of models to search (default: 0)
"""
driver = PyclingoDriver()
if "asp" in dump:
driver.out = sys.stdout
# Check upfront that the variants are admissible
for root in specs:
for s in root.traverse():
if s.virtual:
continue
spack.spec.Spec.ensure_valid_variants(s)
setup = SpackSolverSetup()
return driver.solve(setup, specs, dump, models, timers, stats, tests)
| 36.265366
| 85
| 0.595264
|
from __future__ import print_function
import collections
import copy
import itertools
import os
import pprint
import sys
import types
import warnings
from six import string_types
import archspec.cpu
try:
import clingo
clingo_cffi = hasattr(clingo.Symbol, '_rep')
except ImportError:
clingo = None
clingo_cffi = False
import llnl.util.lang
import llnl.util.tty as tty
import spack
import spack.architecture
import spack.bootstrap
import spack.cmd
import spack.compilers
import spack.config
import spack.dependency
import spack.directives
import spack.environment as ev
import spack.error
import spack.package
import spack.package_prefs
import spack.repo
import spack.spec
import spack.util.timer
import spack.variant
import spack.version
if sys.version_info >= (3, 3):
from collections.abc import Sequence
else:
from collections import Sequence
version_provenance = collections.namedtuple(
'VersionProvenance', ['external', 'packages_yaml', 'package_py', 'spec']
)(spec=0, external=1, packages_yaml=2, package_py=3)
version_origin_str = {
0: 'spec',
1: 'external',
2: 'packages_yaml',
3: 'package_py'
}
DeclaredVersion = collections.namedtuple(
'DeclaredVersion', ['version', 'idx', 'origin']
)
def issequence(obj):
if isinstance(obj, string_types):
return False
return isinstance(obj, (Sequence, types.GeneratorType))
def listify(args):
if len(args) == 1 and issequence(args[0]):
return list(args[0])
return list(args)
def packagize(pkg):
if isinstance(pkg, string_types):
return spack.repo.path.get_pkg_class(pkg)
else:
return pkg
def specify(spec):
if isinstance(spec, spack.spec.Spec):
return spec
return spack.spec.Spec(spec)
class AspObject(object):
def _id(thing):
if isinstance(thing, AspObject):
return thing
elif isinstance(thing, bool):
return '"%s"' % str(thing)
elif isinstance(thing, int):
return str(thing)
else:
return '"%s"' % str(thing)
@llnl.util.lang.key_ordering
class AspFunction(AspObject):
def __init__(self, name, args=None):
self.name = name
self.args = () if args is None else args
def _cmp_key(self):
return (self.name, self.args)
def __call__(self, *args):
return AspFunction(self.name, args)
def symbol(self, positive=True):
def argify(arg):
if isinstance(arg, bool):
return clingo.String(str(arg))
elif isinstance(arg, int):
return clingo.Number(arg)
else:
return clingo.String(str(arg))
return clingo.Function(
self.name, [argify(arg) for arg in self.args], positive=positive)
def __str__(self):
return "%s(%s)" % (
self.name, ', '.join(str(_id(arg)) for arg in self.args))
def __repr__(self):
return str(self)
class AspFunctionBuilder(object):
def __getattr__(self, name):
return AspFunction(name)
fn = AspFunctionBuilder()
def all_compilers_in_config():
return spack.compilers.all_compilers()
def extend_flag_list(flag_list, new_flags):
for flag in new_flags:
if flag in flag_list:
flag_list.remove(flag)
flag_list.append(flag)
def check_same_flags(flag_dict_1, flag_dict_2):
types = set(flag_dict_1.keys()).union(set(flag_dict_2.keys()))
for t in types:
values1 = set(flag_dict_1.get(t, []))
values2 = set(flag_dict_2.get(t, []))
assert values1 == values2
def check_packages_exist(specs):
repo = spack.repo.path
for spec in specs:
for s in spec.traverse():
try:
check_passed = repo.exists(s.name) or repo.is_virtual(s.name)
except Exception as e:
msg = 'Cannot find package: {0}'.format(str(e))
check_passed = False
tty.debug(msg)
if not check_passed:
raise spack.repo.UnknownPackageError(str(s.fullname))
class Result(object):
def __init__(self, specs, asp=None):
self.asp = asp
self.satisfiable = None
self.optimal = None
self.warnings = None
self.nmodels = 0
self.answers = []
self.cores = []
self.criteria = []
self.abstract_specs = specs
self._concrete_specs = None
def print_cores(self):
for core in self.cores:
tty.msg(
"The following constraints are unsatisfiable:",
*sorted(str(symbol) for symbol in core))
@property
def specs(self):
if self._concrete_specs:
return self._concrete_specs
msg = 'cannot compute specs ["satisfiable" is not True ]'
assert self.satisfiable, msg
self._concrete_specs = []
best = min(self.answers)
opt, _, answer = best
for input_spec in self.abstract_specs:
key = input_spec.name
if input_spec.virtual:
providers = [spec.name for spec in answer.values()
if spec.package.provides(key)]
key = providers[0]
self._concrete_specs.append(answer[key])
return self._concrete_specs
def _normalize_packages_yaml(packages_yaml):
normalized_yaml = copy.copy(packages_yaml)
for pkg_name in packages_yaml:
is_virtual = spack.repo.path.is_virtual(pkg_name)
if pkg_name == 'all' or not is_virtual:
continue
data = normalized_yaml.pop(pkg_name)
is_buildable = data.get('buildable', True)
if not is_buildable:
for provider in spack.repo.path.providers_for(pkg_name):
entry = normalized_yaml.setdefault(provider.name, {})
entry['buildable'] = False
externals = data.get('externals', [])
keyfn = lambda x: spack.spec.Spec(x['spec']).name
for provider, specs in itertools.groupby(externals, key=keyfn):
entry = normalized_yaml.setdefault(provider, {})
entry.setdefault('externals', []).extend(specs)
return normalized_yaml
class PyclingoDriver(object):
def __init__(self, cores=True, asp=None):
global clingo
if not clingo:
with spack.bootstrap.ensure_bootstrap_configuration():
spack.bootstrap.ensure_clingo_importable_or_raise()
import clingo
self.out = asp or llnl.util.lang.Devnull()
self.cores = cores
def title(self, name, char):
self.out.write('\n')
self.out.write("%" + (char * 76))
self.out.write('\n')
self.out.write("%% %s\n" % name)
self.out.write("%" + (char * 76))
self.out.write('\n')
def h1(self, name):
self.title(name, "=")
def h2(self, name):
self.title(name, "-")
def newline(self):
self.out.write('\n')
def fact(self, head):
symbol = head.symbol() if hasattr(head, 'symbol') else head
self.out.write("%s.\n" % str(symbol))
atom = self.backend.add_atom(symbol)
self.backend.add_rule([atom], [], choice=self.cores)
if self.cores:
self.assumptions.append(atom)
def solve(
self, solver_setup, specs, dump=None, nmodels=0,
timers=False, stats=False, tests=False
):
timer = spack.util.timer.Timer()
self.control = clingo.Control()
self.control.configuration.solve.models = nmodels
self.control.configuration.asp.trans_ext = 'all'
self.control.configuration.asp.eq = '5'
self.control.configuration.configuration = 'tweety'
self.control.configuration.solve.parallel_mode = '2'
self.control.configuration.solver.opt_strategy = "usc,one"
self.assumptions = []
with self.control.backend() as backend:
self.backend = backend
solver_setup.setup(self, specs, tests=tests)
timer.phase("setup")
parent_dir = os.path.dirname(__file__)
self.control.load(os.path.join(parent_dir, 'concretize.lp'))
self.control.load(os.path.join(parent_dir, "display.lp"))
timer.phase("load")
self.control.ground([("base", [])])
timer.phase("ground")
result = Result(specs)
models = []
cores = []
def on_model(model):
models.append((model.cost, model.symbols(shown=True, terms=True)))
solve_kwargs = {"assumptions": self.assumptions,
"on_model": on_model,
"on_core": cores.append}
if clingo_cffi:
solve_kwargs["on_unsat"] = cores.append
solve_result = self.control.solve(**solve_kwargs)
timer.phase("solve")
result.satisfiable = solve_result.satisfiable
def stringify(x):
if clingo_cffi:
try:
return x.string
except RuntimeError:
return str(x)
else:
return x.string or str(x)
if result.satisfiable:
builder = SpecBuilder(specs)
min_cost, best_model = min(models)
tuples = [
(sym.name, [stringify(a) for a in sym.arguments])
for sym in best_model
]
answers = builder.build_specs(tuples)
result.answers.append((list(min_cost), 0, answers))
criteria = [
(int(args[0]), args[1]) for name, args in tuples
if name == "opt_criterion"
]
result.criteria = [t[1] for t in sorted(criteria, reverse=True)]
result.nmodels = len(models)
elif cores:
symbols = dict(
(a.literal, a.symbol)
for a in self.control.symbolic_atoms
)
for core in cores:
core_symbols = []
for atom in core:
sym = symbols[atom]
if sym.name == "rule":
sym = sym.arguments[0].string
core_symbols.append(sym)
result.cores.append(core_symbols)
if timers:
timer.write_tty()
print()
if stats:
print("Statistics:")
pprint.pprint(self.control.statistics)
return result
class SpackSolverSetup(object):
def __init__(self):
self.gen = None
self.declared_versions = {}
self.possible_versions = {}
self.deprecated_versions = {}
self.possible_virtuals = None
self.possible_compilers = []
self.variant_values_from_specs = set()
self.version_constraints = set()
self.target_constraints = set()
self.compiler_version_constraints = set()
self.post_facts = []
self._condition_id_counter = itertools.count()
self.target_specs_cache = None
def pkg_version_rules(self, pkg):
def key_fn(version):
return version.origin, version.idx
pkg = packagize(pkg)
declared_versions = self.declared_versions[pkg.name]
most_to_least_preferred = sorted(declared_versions, key=key_fn)
for weight, declared_version in enumerate(most_to_least_preferred):
self.gen.fact(fn.version_declared(
pkg.name, declared_version.version, weight,
version_origin_str[declared_version.origin]
))
deprecated = self.deprecated_versions[pkg.name]
for v in sorted(deprecated):
self.gen.fact(fn.deprecated_version(pkg.name, v))
def spec_versions(self, spec):
spec = specify(spec)
assert spec.name
if spec.concrete:
return [fn.version(spec.name, spec.version)]
if spec.versions == spack.version.ver(":"):
return []
self.version_constraints.add((spec.name, spec.versions))
return [fn.version_satisfies(spec.name, spec.versions)]
def target_ranges(self, spec, single_target_fn):
target = spec.architecture.target
if str(target) in archspec.cpu.TARGETS:
return [single_target_fn(spec.name, target)]
self.target_constraints.add((spec.name, target))
return [fn.node_target_satisfies(spec.name, target)]
def conflict_rules(self, pkg):
for trigger, constraints in pkg.conflicts.items():
trigger_id = self.condition(spack.spec.Spec(trigger), name=pkg.name)
self.gen.fact(fn.conflict_trigger(trigger_id))
for constraint, _ in constraints:
constraint_id = self.condition(constraint, name=pkg.name)
self.gen.fact(fn.conflict(pkg.name, trigger_id, constraint_id))
self.gen.newline()
def available_compilers(self):
self.gen.h2("Available compilers")
compilers = self.possible_compilers
compiler_versions = collections.defaultdict(lambda: set())
for compiler in compilers:
compiler_versions[compiler.name].add(compiler.version)
for compiler in sorted(compiler_versions):
for v in sorted(compiler_versions[compiler]):
self.gen.fact(fn.compiler_version(compiler, v))
self.gen.newline()
def compiler_defaults(self):
self.gen.h2("Default compiler preferences")
compiler_list = self.possible_compilers.copy()
compiler_list = sorted(
compiler_list, key=lambda x: (x.name, x.version), reverse=True)
ppk = spack.package_prefs.PackagePrefs("all", 'compiler', all=False)
matches = sorted(compiler_list, key=ppk)
for i, cspec in enumerate(matches):
f = fn.default_compiler_preference(cspec.name, cspec.version, i)
self.gen.fact(f)
for entry in spack.compilers.all_compilers_config():
compiler_entry = entry['compiler']
cspec = spack.spec.CompilerSpec(compiler_entry['spec'])
if not compiler_entry.get('target', None):
continue
self.gen.fact(fn.compiler_supports_target(
cspec.name, cspec.version, compiler_entry['target']
))
def compiler_supports_os(self):
compilers_yaml = spack.compilers.all_compilers_config()
for entry in compilers_yaml:
c = spack.spec.CompilerSpec(entry['compiler']['spec'])
operating_system = entry['compiler']['operating_system']
self.gen.fact(fn.compiler_supports_os(
c.name, c.version, operating_system
))
def package_compiler_defaults(self, pkg):
packages = spack.config.get("packages")
pkg_prefs = packages.get(pkg.name)
if not pkg_prefs or "compiler" not in pkg_prefs:
return
compiler_list = self.possible_compilers.copy()
compiler_list = sorted(
compiler_list, key=lambda x: (x.name, x.version), reverse=True)
ppk = spack.package_prefs.PackagePrefs(pkg.name, 'compiler', all=False)
matches = sorted(compiler_list, key=ppk)
for i, cspec in enumerate(reversed(matches)):
self.gen.fact(fn.node_compiler_preference(
pkg.name, cspec.name, cspec.version, -i * 100
))
def pkg_rules(self, pkg, tests):
pkg = packagize(pkg)
self.pkg_version_rules(pkg)
self.gen.newline()
for name, variant in sorted(pkg.variants.items()):
self.gen.fact(fn.variant(pkg.name, name))
single_value = not variant.multi
if single_value:
self.gen.fact(fn.variant_single_value(pkg.name, name))
self.gen.fact(
fn.variant_default_value_from_package_py(
pkg.name, name, variant.default)
)
else:
spec_variant = variant.make_default()
defaults = spec_variant.value
for val in sorted(defaults):
self.gen.fact(
fn.variant_default_value_from_package_py(
pkg.name, name, val)
)
values = variant.values
if values is None:
values = []
elif isinstance(values, spack.variant.DisjointSetsOfValues):
union = set()
for sid, s in enumerate(values.sets):
for value in s:
self.gen.fact(fn.variant_value_from_disjoint_sets(
pkg.name, name, value, sid
))
union.update(s)
values = union
if not values:
values = [variant.default]
for value in sorted(values):
self.gen.fact(fn.variant_possible_value(pkg.name, name, value))
self.gen.newline()
self.conflict_rules(pkg)
self.package_compiler_defaults(pkg)
self.package_provider_rules(pkg)
self.package_dependencies_rules(pkg, tests)
self.virtual_preferences(
pkg.name,
lambda v, p, i: self.gen.fact(
fn.pkg_provider_preference(pkg.name, v, p, i)
)
)
def condition(self, required_spec, imposed_spec=None, name=None):
named_cond = required_spec.copy()
named_cond.name = named_cond.name or name
assert named_cond.name, "must provide name for anonymous condtions!"
condition_id = next(self._condition_id_counter)
self.gen.fact(fn.condition(condition_id))
requirements = self.checked_spec_clauses(
named_cond, body=True, required_from=name)
for pred in requirements:
self.gen.fact(
fn.condition_requirement(condition_id, pred.name, *pred.args)
)
if imposed_spec:
imposed_constraints = self.checked_spec_clauses(
imposed_spec, body=False, required_from=name)
for pred in imposed_constraints:
if pred.name in ("node", "virtual_node"):
continue
self.gen.fact(
fn.imposed_constraint(condition_id, pred.name, *pred.args)
)
return condition_id
def package_provider_rules(self, pkg):
for provider_name in sorted(set(s.name for s in pkg.provided.keys())):
self.gen.fact(fn.possible_provider(pkg.name, provider_name))
for provided, whens in pkg.provided.items():
for when in whens:
condition_id = self.condition(when, provided, pkg.name)
self.gen.fact(fn.provider_condition(
condition_id, when.name, provided.name
))
self.gen.newline()
def package_dependencies_rules(self, pkg, tests):
for _, conditions in sorted(pkg.dependencies.items()):
for cond, dep in sorted(conditions.items()):
deptypes = dep.type.copy()
if not tests:
deptypes.discard("test")
# ... or if they are requested only for certain packages
if not isinstance(tests, bool) and pkg.name not in tests:
deptypes.discard("test")
# if there are no dependency types to be considered
# anymore, don't generate the dependency
if not deptypes:
continue
condition_id = self.condition(cond, dep.spec, pkg.name)
self.gen.fact(fn.dependency_condition(
condition_id, pkg.name, dep.spec.name
))
for t in sorted(deptypes):
self.gen.fact(fn.dependency_type(condition_id, t))
self.gen.newline()
def virtual_preferences(self, pkg_name, func):
config = spack.config.get("packages")
pkg_prefs = config.get(pkg_name, {}).get("providers", {})
for vspec, providers in pkg_prefs.items():
if vspec not in self.possible_virtuals:
continue
for i, provider in enumerate(providers):
provider_name = spack.spec.Spec(provider).name
func(vspec, provider_name, i)
def provider_defaults(self):
self.gen.h2("Default virtual providers")
assert self.possible_virtuals is not None
self.virtual_preferences(
"all",
lambda v, p, i: self.gen.fact(
fn.default_provider_preference(v, p, i))
)
def external_packages(self):
packages_yaml = spack.config.get("packages")
packages_yaml = _normalize_packages_yaml(packages_yaml)
self.gen.h1('External packages')
for pkg_name, data in packages_yaml.items():
if pkg_name == 'all':
continue
if pkg_name not in spack.repo.path:
continue
self.gen.h2('External package: {0}'.format(pkg_name))
external_buildable = data.get('buildable', True)
if not external_buildable:
self.gen.fact(fn.external_only(pkg_name))
externals = data.get('externals', [])
external_specs = [spack.spec.Spec(x['spec']) for x in externals]
external_versions = [
(x.version, external_id)
for external_id, x in enumerate(external_specs)
]
external_versions = [
(v, idx, external_id)
for idx, (v, external_id) in
enumerate(sorted(external_versions, reverse=True))
]
for version, idx, external_id in external_versions:
self.declared_versions[pkg_name].append(DeclaredVersion(
version=version,
idx=idx,
origin=version_provenance.external
))
for local_idx, spec in enumerate(external_specs):
condition_id = self.condition(spec)
self.gen.fact(
fn.possible_external(condition_id, pkg_name, local_idx)
)
self.possible_versions[spec.name].add(spec.version)
self.gen.newline()
def preferred_variants(self, pkg_name):
preferences = spack.package_prefs.PackagePrefs
preferred_variants = preferences.preferred_variants(pkg_name)
if not preferred_variants:
return
for variant_name in sorted(preferred_variants):
variant = preferred_variants[variant_name]
values = variant.value
if not isinstance(values, tuple):
values = (values,)
spec = spack.spec.Spec(pkg_name)
spec.update_variant_validate(variant_name, values)
for value in values:
self.variant_values_from_specs.add(
(pkg_name, variant.name, value)
)
self.gen.fact(fn.variant_default_value_from_packages_yaml(
pkg_name, variant.name, value
))
def preferred_targets(self, pkg_name):
key_fn = spack.package_prefs.PackagePrefs(pkg_name, 'target')
if not self.target_specs_cache:
self.target_specs_cache = [
spack.spec.Spec('target={0}'.format(target_name))
for target_name in archspec.cpu.TARGETS
]
target_specs = self.target_specs_cache
preferred_targets = [x for x in target_specs if key_fn(x) < 0]
if not preferred_targets:
return
preferred = preferred_targets[0]
self.gen.fact(fn.package_target_weight(
str(preferred.architecture.target), pkg_name, -30
))
def flag_defaults(self):
self.gen.h2("Compiler flag defaults")
for flag in spack.spec.FlagMap.valid_compiler_flags():
self.gen.fact(fn.flag_type(flag))
self.gen.newline()
compilers = all_compilers_in_config()
for compiler in compilers:
for name, flags in compiler.flags.items():
for flag in flags:
self.gen.fact(fn.compiler_version_flag(
compiler.name, compiler.version, name, flag))
def checked_spec_clauses(self, *args, **kwargs):
requestor = kwargs.pop('required_from', None)
try:
clauses = self.spec_clauses(*args, **kwargs)
except RuntimeError as exc:
msg = str(exc)
if requestor:
msg += ' [required from package "{0}"]'.format(requestor)
raise RuntimeError(msg)
return clauses
def spec_clauses(self, spec, body=False, transitive=True):
clauses = []
class Head(object):
node = fn.node
virtual_node = fn.virtual_node
node_platform = fn.node_platform_set
node_os = fn.node_os_set
node_target = fn.node_target_set
variant_value = fn.variant_set
node_compiler = fn.node_compiler_set
node_compiler_version = fn.node_compiler_version_set
node_flag = fn.node_flag_set
class Body(object):
node = fn.node
virtual_node = fn.virtual_node
node_platform = fn.node_platform
node_os = fn.node_os
node_target = fn.node_target
variant_value = fn.variant_value
node_compiler = fn.node_compiler
node_compiler_version = fn.node_compiler_version
node_flag = fn.node_flag
f = Body if body else Head
if spec.name:
clauses.append(
f.node(spec.name) if not spec.virtual
else f.virtual_node(spec.name))
clauses.extend(self.spec_versions(spec))
# TODO: use better semantics.
arch = spec.architecture
if arch:
if arch.platform:
clauses.append(f.node_platform(spec.name, arch.platform))
if arch.os:
clauses.append(f.node_os(spec.name, arch.os))
if arch.target:
clauses.extend(self.target_ranges(spec, f.node_target))
# variants
for vname, variant in sorted(spec.variants.items()):
values = variant.value
if not isinstance(values, (list, tuple)):
values = [values]
for value in values:
# * is meaningless for concretization -- just for matching
if value == '*':
continue
# validate variant value only if spec not concrete
if not spec.concrete:
reserved_names = spack.directives.reserved_names
if not spec.virtual and vname not in reserved_names:
try:
variant_def = spec.package.variants[vname]
except KeyError:
msg = 'variant "{0}" not found in package "{1}"'
raise RuntimeError(msg.format(vname, spec.name))
else:
variant_def.validate_or_raise(variant, spec.package)
clauses.append(f.variant_value(spec.name, vname, value))
# Tell the concretizer that this is a possible value for the
# variant, to account for things like int/str values where we
# can't enumerate the valid values
self.variant_values_from_specs.add((spec.name, vname, value))
if spec.compiler:
clauses.append(f.node_compiler(spec.name, spec.compiler.name))
if spec.compiler.concrete:
clauses.append(f.node_compiler_version(
spec.name, spec.compiler.name, spec.compiler.version))
elif spec.compiler.versions:
clauses.append(
fn.node_compiler_version_satisfies(
spec.name, spec.compiler.name, spec.compiler.versions))
self.compiler_version_constraints.add(
(spec.name, spec.compiler))
for flag_type, flags in spec.compiler_flags.items():
for flag in flags:
clauses.append(f.node_flag(spec.name, flag_type, flag))
if spec.concrete:
clauses.append(fn.concrete(spec.name))
if transitive:
for dep in spec.traverse(root=False):
clauses.extend(self.spec_clauses(dep, body, transitive=False))
return clauses
def build_version_dict(self, possible_pkgs, specs):
self.declared_versions = collections.defaultdict(list)
self.possible_versions = collections.defaultdict(set)
self.deprecated_versions = collections.defaultdict(set)
packages_yaml = spack.config.get("packages")
packages_yaml = _normalize_packages_yaml(packages_yaml)
for pkg_name in possible_pkgs:
pkg = spack.repo.get(pkg_name)
def key_fn(item):
version, info = item
return info.get('preferred', False), not version.isdevelop(), version
for idx, item in enumerate(sorted(
pkg.versions.items(), key=key_fn, reverse=True
)):
v, version_info = item
self.possible_versions[pkg_name].add(v)
self.declared_versions[pkg_name].append(DeclaredVersion(
version=v, idx=idx, origin=version_provenance.package_py
))
deprecated = version_info.get('deprecated', False)
if deprecated:
self.deprecated_versions[pkg_name].add(v)
version_preferences = packages_yaml.get(pkg_name, {}).get("version", [])
for idx, v in enumerate(version_preferences):
self.declared_versions[pkg_name].append(DeclaredVersion(
version=v, idx=idx, origin=version_provenance.packages_yaml
))
for spec in specs:
for dep in spec.traverse():
if dep.versions.concrete:
self.declared_versions[dep.name].append(DeclaredVersion(
version=dep.version,
idx=0,
origin=version_provenance.spec
))
self.possible_versions[dep.name].add(dep.version)
def _supported_targets(self, compiler_name, compiler_version, targets):
supported = []
for target in targets:
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
target.optimization_flags(compiler_name, compiler_version)
supported.append(target)
except archspec.cpu.UnsupportedMicroarchitecture:
continue
except ValueError:
continue
return sorted(supported, reverse=True)
def platform_defaults(self):
self.gen.h2('Default platform')
platform = spack.architecture.platform()
self.gen.fact(fn.node_platform_default(platform))
def os_defaults(self, specs):
self.gen.h2('Possible operating systems')
platform = spack.architecture.platform()
possible = set([
platform.front_os, platform.back_os, platform.default_os])
for spec in specs:
if spec.architecture and spec.architecture.os:
possible.add(spec.architecture.os)
# make directives for possible OS's
for possible_os in sorted(possible):
self.gen.fact(fn.os(possible_os))
self.gen.fact(fn.node_os_default(platform.default_os))
def target_defaults(self, specs):
self.gen.h2('Default target')
platform = spack.architecture.platform()
uarch = archspec.cpu.TARGETS.get(platform.default)
self.gen.h2('Target compatibility')
compatible_targets = [uarch] + uarch.ancestors
additional_targets_in_family = sorted([
t for t in archspec.cpu.TARGETS.values()
if (t.family.name == uarch.family.name and
t not in compatible_targets)
], key=lambda x: len(x.ancestors), reverse=True)
compatible_targets += additional_targets_in_family
compilers = self.possible_compilers
best_targets = set([uarch.family.name])
for compiler in sorted(compilers):
supported = self._supported_targets(
compiler.name, compiler.version, compatible_targets
)
# versions in the spec, e.g. gcc@foo. Try to match the
# real_version from the compiler object to get more accurate
# results.
if not supported:
compiler_obj = spack.compilers.compilers_for_spec(compiler)
compiler_obj = compiler_obj[0]
supported = self._supported_targets(
compiler.name,
compiler_obj.real_version,
compatible_targets
)
if not supported:
continue
for target in supported:
best_targets.add(target.name)
self.gen.fact(fn.compiler_supports_target(
compiler.name, compiler.version, target.name))
self.gen.fact(fn.compiler_supports_target(
compiler.name, compiler.version, uarch.family.name))
# add any targets explicitly mentioned in specs
for spec in specs:
if not spec.architecture or not spec.architecture.target:
continue
target = archspec.cpu.TARGETS.get(spec.target.name)
if not target:
self.target_ranges(spec, None)
continue
if target not in compatible_targets:
compatible_targets.append(target)
i = 0
for target in compatible_targets:
self.gen.fact(fn.target(target.name))
self.gen.fact(fn.target_family(target.name, target.family.name))
for parent in sorted(target.parents):
self.gen.fact(fn.target_parent(target.name, parent.name))
# prefer best possible targets; weight others poorly so
# they're not used unless set explicitly
if target.name in best_targets:
self.gen.fact(fn.default_target_weight(target.name, i))
i += 1
else:
self.gen.fact(fn.default_target_weight(target.name, 100))
self.gen.newline()
def virtual_providers(self):
self.gen.h2("Virtual providers")
assert self.possible_virtuals is not None
for vspec in sorted(self.possible_virtuals):
self.gen.fact(fn.virtual(vspec))
self.gen.newline()
def generate_possible_compilers(self, specs):
compilers = all_compilers_in_config()
cspecs = set([c.spec for c in compilers])
strict = spack.concretize.Concretizer().check_for_compiler_existence
for spec in specs:
for s in spec.traverse():
if not s.compiler or not s.compiler.concrete:
continue
if strict and s.compiler not in cspecs:
raise spack.concretize.UnavailableCompilerVersionError(
s.compiler
)
else:
cspecs.add(s.compiler)
self.gen.fact(fn.allow_compiler(
s.compiler.name, s.compiler.version
))
return cspecs
def define_version_constraints(self):
for pkg_name, versions in sorted(self.version_constraints):
# version must be *one* of the ones the spec allows.
allowed_versions = [
v for v in sorted(self.possible_versions[pkg_name])
if v.satisfies(versions)
]
# This is needed to account for a variable number of
# numbers e.g. if both 1.0 and 1.0.2 are possible versions
exact_match = [v for v in allowed_versions if v == versions]
if exact_match:
allowed_versions = exact_match
# generate facts for each package constraint and the version
# that satisfies it
for v in allowed_versions:
self.gen.fact(fn.version_satisfies(pkg_name, versions, v))
self.gen.newline()
def define_virtual_constraints(self):
# aggregate constraints into per-virtual sets
constraint_map = collections.defaultdict(lambda: set())
for pkg_name, versions in self.version_constraints:
if not spack.repo.path.is_virtual(pkg_name):
continue
constraint_map[pkg_name].add(versions)
# extract all the real versions mentioned in version ranges
def versions_for(v):
if isinstance(v, spack.version.Version):
return [v]
elif isinstance(v, spack.version.VersionRange):
result = [v.start] if v.start else []
result += [v.end] if v.end else []
return result
elif isinstance(v, spack.version.VersionList):
return sum((versions_for(e) for e in v), [])
else:
raise TypeError("expected version type, found: %s" % type(v))
# define a set of synthetic possible versions for virtuals, so
# that `version_satisfies(Package, Constraint, Version)` has the
# same semantics for virtuals as for regular packages.
for pkg_name, versions in sorted(constraint_map.items()):
possible_versions = set(
sum([versions_for(v) for v in versions], [])
)
for version in sorted(possible_versions):
self.possible_versions[pkg_name].add(version)
def define_compiler_version_constraints(self):
compiler_list = spack.compilers.all_compiler_specs()
compiler_list = list(sorted(set(compiler_list)))
for pkg_name, cspec in self.compiler_version_constraints:
for compiler in compiler_list:
if compiler.satisfies(cspec):
self.gen.fact(
fn.node_compiler_version_satisfies(
pkg_name,
cspec.name,
cspec.versions,
compiler.version
)
)
self.gen.newline()
def define_target_constraints(self):
def _all_targets_satisfiying(single_constraint):
allowed_targets = []
if ':' not in single_constraint:
return [single_constraint]
t_min, _, t_max = single_constraint.partition(':')
for test_target in archspec.cpu.TARGETS.values():
# Check lower bound
if t_min and not t_min <= test_target:
continue
# Check upper bound
if t_max and not t_max >= test_target:
continue
allowed_targets.append(test_target)
return allowed_targets
cache = {}
for spec_name, target_constraint in sorted(self.target_constraints):
# Construct the list of allowed targets for this constraint
allowed_targets = []
for single_constraint in str(target_constraint).split(','):
if single_constraint not in cache:
cache[single_constraint] = _all_targets_satisfiying(
single_constraint
)
allowed_targets.extend(cache[single_constraint])
for target in allowed_targets:
self.gen.fact(
fn.node_target_satisfies(
spec_name, target_constraint, target
)
)
self.gen.newline()
def define_variant_values(self):
# Tell the concretizer about possible values from specs we saw in
# spec_clauses()
for pkg, variant, value in sorted(self.variant_values_from_specs):
self.gen.fact(fn.variant_possible_value(pkg, variant, value))
def setup(self, driver, specs, tests=False):
self._condition_id_counter = itertools.count()
# preliminary checks
check_packages_exist(specs)
# get list of all possible dependencies
self.possible_virtuals = set(
x.name for x in specs if x.virtual
)
possible = spack.package.possible_dependencies(
*specs,
virtuals=self.possible_virtuals,
deptype=spack.dependency.all_deptypes
)
pkgs = set(possible)
# driver is used by all the functions below to add facts and
# rules to generate an ASP program.
self.gen = driver
# get possible compilers
self.possible_compilers = self.generate_possible_compilers(specs)
# traverse all specs and packages to build dict of possible versions
self.build_version_dict(possible, specs)
self.gen.h1('General Constraints')
self.available_compilers()
self.compiler_defaults()
self.compiler_supports_os()
# architecture defaults
self.platform_defaults()
self.os_defaults(specs)
self.target_defaults(specs)
self.virtual_providers()
self.provider_defaults()
self.external_packages()
self.flag_defaults()
self.gen.h1('Package Constraints')
for pkg in sorted(pkgs):
self.gen.h2('Package rules: %s' % pkg)
self.pkg_rules(pkg, tests=tests)
self.gen.h2('Package preferences: %s' % pkg)
self.preferred_variants(pkg)
self.preferred_targets(pkg)
# Inject dev_path from environment
env = ev.active_environment()
if env:
for spec in sorted(specs):
for dep in spec.traverse():
_develop_specs_from_env(dep, env)
self.gen.h1('Spec Constraints')
for spec in sorted(specs):
self.gen.h2('Spec: %s' % str(spec))
self.gen.fact(
fn.virtual_root(spec.name) if spec.virtual
else fn.root(spec.name)
)
for clause in self.spec_clauses(spec):
self.gen.fact(clause)
if clause.name == 'variant_set':
self.gen.fact(fn.variant_default_value_from_cli(
*clause.args
))
self.gen.h1("Variant Values defined in specs")
self.define_variant_values()
self.gen.h1("Virtual Constraints")
self.define_virtual_constraints()
self.gen.h1("Version Constraints")
self.define_version_constraints()
self.gen.h1("Compiler Version Constraints")
self.define_compiler_version_constraints()
self.gen.h1("Target Constraints")
self.define_target_constraints()
class SpecBuilder(object):
def __init__(self, specs):
self._result = None
self._command_line_specs = specs
self._flag_sources = collections.defaultdict(lambda: set())
self._flag_compiler_defaults = set()
def node(self, pkg):
if pkg not in self._specs:
self._specs[pkg] = spack.spec.Spec(pkg)
def _arch(self, pkg):
arch = self._specs[pkg].architecture
if not arch:
arch = spack.spec.ArchSpec()
self._specs[pkg].architecture = arch
return arch
def node_platform(self, pkg, platform):
self._arch(pkg).platform = platform
def node_os(self, pkg, os):
self._arch(pkg).os = os
def node_target(self, pkg, target):
self._arch(pkg).target = target
def variant_value(self, pkg, name, value):
# FIXME: is there a way not to special case 'dev_path' everywhere?
if name == 'dev_path':
self._specs[pkg].variants.setdefault(
name,
spack.variant.SingleValuedVariant(name, value)
)
return
if name == 'patches':
self._specs[pkg].variants.setdefault(
name,
spack.variant.MultiValuedVariant(name, value)
)
return
self._specs[pkg].update_variant_validate(name, value)
def version(self, pkg, version):
self._specs[pkg].versions = spack.version.ver([version])
def node_compiler(self, pkg, compiler):
self._specs[pkg].compiler = spack.spec.CompilerSpec(compiler)
def node_compiler_version(self, pkg, compiler, version):
self._specs[pkg].compiler.versions = spack.version.VersionList(
[version])
def node_flag_compiler_default(self, pkg):
self._flag_compiler_defaults.add(pkg)
def node_flag(self, pkg, flag_type, flag):
self._specs[pkg].compiler_flags.setdefault(flag_type, []).append(flag)
def node_flag_source(self, pkg, source):
self._flag_sources[pkg].add(source)
def no_flags(self, pkg, flag_type):
self._specs[pkg].compiler_flags[flag_type] = []
def external_spec_selected(self, pkg, idx):
packages_yaml = spack.config.get('packages')
packages_yaml = _normalize_packages_yaml(packages_yaml)
spec_info = packages_yaml[pkg]['externals'][int(idx)]
self._specs[pkg].external_path = spec_info.get('prefix', None)
self._specs[pkg].external_modules = (
spack.spec.Spec._format_module_list(spec_info.get('modules', None))
)
self._specs[pkg].extra_attributes = spec_info.get(
'extra_attributes', {}
)
def depends_on(self, pkg, dep, type):
dependency = self._specs[pkg]._dependencies.get(dep)
if not dependency:
self._specs[pkg]._add_dependency(
self._specs[dep], (type,))
else:
dependency.add_type(type)
def reorder_flags(self):
# nodes with no flags get flag order from compiler
compilers = dict((c.spec, c) for c in all_compilers_in_config())
for pkg in self._flag_compiler_defaults:
spec = self._specs[pkg]
compiler_flags = compilers[spec.compiler].flags
check_same_flags(spec.compiler_flags, compiler_flags)
spec.compiler_flags.update(compiler_flags)
# index of all specs (and deps) from the command line by name
cmd_specs = dict(
(s.name, s)
for spec in self._command_line_specs
for s in spec.traverse())
# iterate through specs with specified flags
for pkg, sources in self._flag_sources.items():
spec = self._specs[pkg]
# order is determined by the DAG. A spec's flags come after
order = [
s.name
for s in spec.traverse(order='post', direction='parents')]
sorted_sources = sorted(
sources, key=lambda s: order.index(s))
flags = collections.defaultdict(lambda: [])
for source_name in sorted_sources:
source = cmd_specs[source_name]
for name, flag_list in source.compiler_flags.items():
extend_flag_list(flags[name], flag_list)
check_same_flags(spec.compiler_flags, flags)
spec.compiler_flags.update(flags)
def deprecated(self, pkg, version):
msg = 'using "{0}@{1}" which is a deprecated version'
tty.warn(msg.format(pkg, version))
def build_specs(self, function_tuples):
# them here so that directives that build objects (like node and
# node_compiler) are called in the right order.
function_tuples.sort(key=lambda f: {
"node": -2,
"node_compiler": -1,
}.get(f[0], 0))
self._specs = {}
for name, args in function_tuples:
action = getattr(self, name, None)
# print out unknown actions so we can display them for debugging
if not action:
msg = "%s(%s)" % (name, ", ".join(str(a) for a in args))
tty.debug(msg)
continue
assert action and callable(action)
# ignore predicates on virtual packages, as they're used for
pkg = args[0]
if spack.repo.path.is_virtual(pkg):
continue
action(*args)
# namespace assignment is done after the fact, as it is not
# currently part of the solve
for spec in self._specs.values():
repo = spack.repo.path.repo_for_pkg(spec)
spec.namespace = repo.namespace
# fix flags after all specs are constructed
self.reorder_flags()
# inject patches -- note that we' can't use set() to unique the
# roots here, because the specs aren't complete, and the hash
roots = [spec.root for spec in self._specs.values()]
roots = dict((id(r), r) for r in roots)
for root in roots.values():
spack.spec.Spec.inject_patches_variant(root)
for s in self._specs.values():
spack.spec.Spec.ensure_external_path_if_external(s)
for s in self._specs.values():
_develop_specs_from_env(s, ev.active_environment())
for s in self._specs.values():
s._mark_concrete()
for s in self._specs.values():
spack.spec.Spec.ensure_no_deprecated(s)
return self._specs
def _develop_specs_from_env(spec, env):
dev_info = env.dev_specs.get(spec.name, {}) if env else {}
if not dev_info:
return
path = os.path.normpath(os.path.join(env.path, dev_info['path']))
if 'dev_path' in spec.variants:
assert spec.variants['dev_path'].value == path
else:
spec.variants.setdefault(
'dev_path', spack.variant.SingleValuedVariant('dev_path', path)
)
spec.constrain(dev_info['spec'])
def solve(specs, dump=(), models=0, timers=False, stats=False, tests=False):
driver = PyclingoDriver()
if "asp" in dump:
driver.out = sys.stdout
for root in specs:
for s in root.traverse():
if s.virtual:
continue
spack.spec.Spec.ensure_valid_variants(s)
setup = SpackSolverSetup()
return driver.solve(setup, specs, dump, models, timers, stats, tests)
| true
| true
|
790e546fbfa49f09a7db2613f15910a5cbedbf1e
| 1,905
|
py
|
Python
|
userbot/modules/sql_helper/welcome_sql.py
|
Thegreatfoxxgoddess/RemixGeng
|
67816ea61aba788a0f61884a55b3af9f1d6abc24
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 11
|
2020-07-16T10:50:06.000Z
|
2020-12-21T02:37:54.000Z
|
userbot/modules/sql_helper/welcome_sql.py
|
Thegreatfoxxgoddess/RemixGeng
|
67816ea61aba788a0f61884a55b3af9f1d6abc24
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 66
|
2020-07-19T02:17:08.000Z
|
2021-01-08T04:48:21.000Z
|
userbot/modules/sql_helper/welcome_sql.py
|
Thegreatfoxxgoddess/RemixGeng
|
67816ea61aba788a0f61884a55b3af9f1d6abc24
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 38
|
2020-06-02T10:09:48.000Z
|
2021-05-18T04:48:36.000Z
|
try:
from userbot.modules.sql_helper import SESSION, BASE
except ImportError:
raise AttributeError
from sqlalchemy import BigInteger, Column, Numeric, String, UnicodeText
class Welcome(BASE):
__tablename__ = "welcome"
chat_id = Column(String(14), primary_key=True)
previous_welcome = Column(BigInteger)
reply = Column(UnicodeText)
f_mesg_id = Column(Numeric)
def __init__(self, chat_id, previous_welcome, reply, f_mesg_id):
self.chat_id = str(chat_id)
self.previous_welcome = previous_welcome
self.reply = reply
self.f_mesg_id = f_mesg_id
Welcome.__table__.create(checkfirst=True)
def get_welcome(chat_id):
try:
return SESSION.query(Welcome).get(str(chat_id))
finally:
SESSION.close()
def get_current_welcome_settings(chat_id):
try:
return SESSION.query(Welcome).filter(
Welcome.chat_id == str(chat_id)).one()
except BaseException:
return None
finally:
SESSION.close()
def add_welcome_setting(chat_id, previous_welcome, reply, f_mesg_id):
to_check = get_welcome(chat_id)
if not to_check:
adder = Welcome(chat_id, previous_welcome, reply, f_mesg_id)
SESSION.add(adder)
SESSION.commit()
return True
rem = SESSION.query(Welcome).get(str(chat_id))
SESSION.delete(rem)
SESSION.commit()
adder = Welcome(chat_id, previous_welcome, reply, f_mesg_id)
SESSION.commit()
return False
def rm_welcome_setting(chat_id):
try:
rem = SESSION.query(Welcome).get(str(chat_id))
if rem:
SESSION.delete(rem)
SESSION.commit()
return True
except BaseException:
return False
def update_previous_welcome(chat_id, previous_welcome):
row = SESSION.query(Welcome).get(str(chat_id))
row.previous_welcome = previous_welcome
SESSION.commit()
| 26.09589
| 71
| 0.67979
|
try:
from userbot.modules.sql_helper import SESSION, BASE
except ImportError:
raise AttributeError
from sqlalchemy import BigInteger, Column, Numeric, String, UnicodeText
class Welcome(BASE):
__tablename__ = "welcome"
chat_id = Column(String(14), primary_key=True)
previous_welcome = Column(BigInteger)
reply = Column(UnicodeText)
f_mesg_id = Column(Numeric)
def __init__(self, chat_id, previous_welcome, reply, f_mesg_id):
self.chat_id = str(chat_id)
self.previous_welcome = previous_welcome
self.reply = reply
self.f_mesg_id = f_mesg_id
Welcome.__table__.create(checkfirst=True)
def get_welcome(chat_id):
try:
return SESSION.query(Welcome).get(str(chat_id))
finally:
SESSION.close()
def get_current_welcome_settings(chat_id):
try:
return SESSION.query(Welcome).filter(
Welcome.chat_id == str(chat_id)).one()
except BaseException:
return None
finally:
SESSION.close()
def add_welcome_setting(chat_id, previous_welcome, reply, f_mesg_id):
to_check = get_welcome(chat_id)
if not to_check:
adder = Welcome(chat_id, previous_welcome, reply, f_mesg_id)
SESSION.add(adder)
SESSION.commit()
return True
rem = SESSION.query(Welcome).get(str(chat_id))
SESSION.delete(rem)
SESSION.commit()
adder = Welcome(chat_id, previous_welcome, reply, f_mesg_id)
SESSION.commit()
return False
def rm_welcome_setting(chat_id):
try:
rem = SESSION.query(Welcome).get(str(chat_id))
if rem:
SESSION.delete(rem)
SESSION.commit()
return True
except BaseException:
return False
def update_previous_welcome(chat_id, previous_welcome):
row = SESSION.query(Welcome).get(str(chat_id))
row.previous_welcome = previous_welcome
SESSION.commit()
| true
| true
|
790e54ae1f4e470c330272bbe3f753a3dbe12b43
| 242
|
py
|
Python
|
lib/galaxy/model/unittest_utils/__init__.py
|
beatrizserrano/galaxy
|
e149d9d32e1bca6c07c38b1a9cdabfee60323610
|
[
"CC-BY-3.0"
] | null | null | null |
lib/galaxy/model/unittest_utils/__init__.py
|
beatrizserrano/galaxy
|
e149d9d32e1bca6c07c38b1a9cdabfee60323610
|
[
"CC-BY-3.0"
] | 6
|
2021-11-11T20:57:49.000Z
|
2021-12-10T15:30:33.000Z
|
lib/galaxy/model/unittest_utils/__init__.py
|
beatrizserrano/galaxy
|
e149d9d32e1bca6c07c38b1a9cdabfee60323610
|
[
"CC-BY-3.0"
] | null | null | null |
"""Interface provided by galaxy-data modules for unittest utilities for reuse by other modules."""
from .data_app import (
GalaxyDataTestApp,
GalaxyDataTestConfig,
)
__all__ = [
"GalaxyDataTestApp",
"GalaxyDataTestConfig",
]
| 22
| 98
| 0.731405
|
from .data_app import (
GalaxyDataTestApp,
GalaxyDataTestConfig,
)
__all__ = [
"GalaxyDataTestApp",
"GalaxyDataTestConfig",
]
| true
| true
|
790e54f88c52369fbfcded777bf392b5f89edb5b
| 898
|
py
|
Python
|
day-22/test.py
|
DallogFheir/aoc-2020
|
089bd45d5fbdf98b9729a23f3a142ca3b792567c
|
[
"MIT"
] | null | null | null |
day-22/test.py
|
DallogFheir/aoc-2020
|
089bd45d5fbdf98b9729a23f3a142ca3b792567c
|
[
"MIT"
] | null | null | null |
day-22/test.py
|
DallogFheir/aoc-2020
|
089bd45d5fbdf98b9729a23f3a142ca3b792567c
|
[
"MIT"
] | null | null | null |
from combat import Combat, RecursiveCombat
with open("test_input.txt") as f:
game = Combat.parse_from_file(f)
f.seek(0)
recursive_game = RecursiveCombat.parse_from_file(f)
# 1st round
round_1 = game[1]
assert round_1.player_1==[2, 6, 3, 1, 9, 5]
assert round_1.player_2==[8, 4, 7, 10]
# 28th round
round_28 = game[27]
assert round_28.player_1==[4, 1]
assert round_28.player_2==[9, 7, 3, 2, 10, 6, 8, 5]
# error if checking score/winner before end
caught_error = False
try:
game[12].score
except ValueError:
caught_error = True
assert caught_error
caught_error = False
try:
game[8].score
except ValueError:
caught_error = True
assert caught_error
# end
end = game.play()
assert end.player_1==[]
assert end.player_2==[3, 2, 10, 6, 8, 5, 9, 4, 7, 1]
assert end.score==306
assert end.winner==1
# recursive game
end = recursive_game.play()
assert end.score==291
| 18.326531
| 55
| 0.699332
|
from combat import Combat, RecursiveCombat
with open("test_input.txt") as f:
game = Combat.parse_from_file(f)
f.seek(0)
recursive_game = RecursiveCombat.parse_from_file(f)
round_1 = game[1]
assert round_1.player_1==[2, 6, 3, 1, 9, 5]
assert round_1.player_2==[8, 4, 7, 10]
round_28 = game[27]
assert round_28.player_1==[4, 1]
assert round_28.player_2==[9, 7, 3, 2, 10, 6, 8, 5]
caught_error = False
try:
game[12].score
except ValueError:
caught_error = True
assert caught_error
caught_error = False
try:
game[8].score
except ValueError:
caught_error = True
assert caught_error
end = game.play()
assert end.player_1==[]
assert end.player_2==[3, 2, 10, 6, 8, 5, 9, 4, 7, 1]
assert end.score==306
assert end.winner==1
end = recursive_game.play()
assert end.score==291
| true
| true
|
790e55db40617c7c8a7abcbcec7e1e8b5908d8db
| 10,840
|
py
|
Python
|
telegram_commands/getgame.py
|
SalamiArmy/TelegramSteamBotForGoogleAppEngine
|
1d6d1bb50fc8dd71e9a36682dbeca19ca44a2bf6
|
[
"Apache-2.0"
] | null | null | null |
telegram_commands/getgame.py
|
SalamiArmy/TelegramSteamBotForGoogleAppEngine
|
1d6d1bb50fc8dd71e9a36682dbeca19ca44a2bf6
|
[
"Apache-2.0"
] | null | null | null |
telegram_commands/getgame.py
|
SalamiArmy/TelegramSteamBotForGoogleAppEngine
|
1d6d1bb50fc8dd71e9a36682dbeca19ca44a2bf6
|
[
"Apache-2.0"
] | null | null | null |
# coding=utf-8
import json
import urllib
import urllib2
from bs4 import BeautifulSoup
def run(bot, chat_id, user, keyConfig='', message='', totalResults=1):
requestText = str(message)
if requestText == '':
totalSteamGames = int(Get_steam_total())
totalGOGGames = int(Get_GOG_total())
if totalSteamGames is not None and totalGOGGames is not None:
bot.sendMessage(chat_id=chat_id, text='I\'m sorry ' + (user if not user == '' else 'Dave') + \
', there are ' + str(int(totalSteamGames) + int(totalGOGGames)) +
' total games on Steam and GOG combined. Pick one.')
return True
retryCount = 3
appId = ''
while retryCount > 0 and appId == '':
retryCount -= 1
rawSteamSearchResultsMarkup = urllib.urlopen('http://store.steampowered.com/search/?category1=998&term=' + requestText).read()
appId = steam_results_parser(rawSteamSearchResultsMarkup)
if appId:
steamGameLink = 'http://store.steampowered.com/app/' + appId
bypassAgeGate = urllib2.build_opener()
#this bypasses the "mature content - continue/cancel" screen
bypassAgeGate.addheaders.append(('Cookie', 'mature_content=1; path=/; max-age=31536000;expires=Fri, 26 Mar 2027 20:00:00 GMT'))
bypassAgeGate.open(steamGameLink)
#this bypasses the "enter your date of birth" screen
bypassAgeGate.addheaders.append(('Cookie', 'birthtime=0; path=/; max-age=31536000;expires=Fri, 26 Mar 2027 20:00:00 GMT'))
code = bypassAgeGate.open(steamGameLink).read()
if 'id=\"agegate_wizard\"' in code:
gameTitle = steam_age_gate_parser(code)
bot.sendMessage(chat_id=chat_id, text='I\'m sorry ' + (user if not user == '' else 'Dave') + \
', I\'m afraid that \"' + gameTitle + '\" is protected by an age gate.\n' +
steamGameLink)
return False
gameResults = steam_game_parser(code, steamGameLink)
try:
bot.sendMessage(chat_id=chat_id, text=gameResults,
disable_web_page_preview=True, parse_mode='Markdown')
except:
bot.sendMessage(chat_id=chat_id, text=gameResults)
return True
else:
gogSearchData = json.load(urllib.urlopen('http://embed.gog.com/games/ajax/filtered?mediaType=game&search=' + requestText))
appId, price, discount = gog_results_parser(gogSearchData)
if appId:
gogGameLink = 'http://api.gog.com/products/' + str(appId) + '?expand=downloads,expanded_dlcs,description,screenshots,videos,related_products,changelog'
data = json.load(urllib.urlopen(gogGameLink))
gameResults = gog_game_parser(data, price, discount)
bot.sendMessage(chat_id=chat_id, text=gameResults,
disable_web_page_preview=True, parse_mode='Markdown')
else:
bot.sendMessage(chat_id=chat_id, text='I\'m sorry ' + (user if not user == '' else 'Dave') + \
', I\'m afraid I can\'t find the game ' + \
requestText.encode('utf-8'))
def steam_results_parser(rawMarkup):
soup = BeautifulSoup(rawMarkup, 'html.parser')
resultList = []
for resultRow in soup.findAll('a', attrs={'class':'search_result_row'}):
if 'data-ds-appid' in resultRow.attrs:
resultList.append(resultRow['data-ds-appid'])
if 'data-ds-bundleid' in resultRow.attrs:
resultList.append(resultRow['data-ds-bundleid'])
if len(resultList) > 0:
return resultList[0]
return ''
def Get_steam_total():
rawMarkup = urllib.urlopen('http://store.steampowered.com/search/?category1=998&term=#').read()
soup = BeautifulSoup(rawMarkup, 'html.parser')
findPaginationString = soup.find('div', attrs={'class': 'search_pagination_left'})
if findPaginationString:
rawPaginationString = findPaginationString.string
return rawPaginationString.replace('showing 1 - 25 of', '').strip()
return 'uncountable'
def Get_GOG_total():
GogSearchResultsData = json.load(urllib.urlopen('http://embed.gog.com/games/ajax/filtered?mediaType=game&sort=bestselling'))
if 'totalGamesFound' in GogSearchResultsData:
return GogSearchResultsData['totalGamesFound']
return 'uncountable'
def steam_age_gate_parser(rawMarkup):
soup = BeautifulSoup(rawMarkup, 'html.parser')
rawTitleString = soup.find('title').string
return rawTitleString.strip()
def steam_game_parser(code, link):
soup = BeautifulSoup(code, 'html.parser')
AllGameDetailsFormatted = ''
titleDiv = soup.find('div', attrs={'class':'apphub_AppName'})
if titleDiv:
gameTitle = titleDiv.string
AllGameDetailsFormatted += '*' + gameTitle
priceDiv = soup.find('div', attrs={'class':'game_purchase_price price'})
if priceDiv:
gamePrice = priceDiv.string
AllGameDetailsFormatted += ' - ' + gamePrice.strip()
else:
priceDiv = soup.find('div', attrs={'class':'discount_final_price'})
if priceDiv:
gamePrice = priceDiv.string
AllGameDetailsFormatted += ' - ' + gamePrice.strip()
discountPercentageDiv = soup.find('div', attrs={'class':'discount_pct'})
if discountPercentageDiv:
percentageDiscountedBy = discountPercentageDiv.string
AllGameDetailsFormatted += ' (at ' + percentageDiscountedBy.strip() + ' off)'
AllGameDetailsFormatted += '*\n'
else:
print('Cannot parse title as div with class apphub_AppName from Steam page for ' + link)
descriptionDiv = soup.find('div', attrs={'class':'game_description_snippet'})
if descriptionDiv:
descriptionSnippet = descriptionDiv.string.replace('\r', '').replace('\n', '').replace('\t', '').replace('_', ' ')
AllGameDetailsFormatted += descriptionSnippet + '\n'
if AllGameDetailsFormatted:
AllGameDetailsFormatted += link + '\n'
dateSpan = soup.find('div', attrs={'class':'date'})
if dateSpan:
releaseDate = dateSpan.string
AllGameDetailsFormatted += 'Release Date: ' + releaseDate + '\n'
featureList = ''
featureLinks = soup.findAll('a', attrs={'class':'name'})
if len(featureLinks) > 0:
for featureLink in featureLinks:
if featureLink.string != None:
featureList += ' ' + featureLink.string.replace('Seated', 'Seated VR') + '\n'
AllGameDetailsFormatted += 'Features:\n' + featureList
reviewRows = ''
reviewDivs = soup.findAll('div', attrs={'class':'user_reviews_summary_row'})
if len(reviewDivs) > 0:
for reviewRow in reviewDivs:
reviewSubtitleRawDiv = reviewRow.find('div', attrs={'class':'subtitle column'})
reviewSubtitleDiv = ''
if reviewSubtitleRawDiv is not None:
reviewSubtitleDiv = reviewSubtitleRawDiv.string
reviewSummaryRawDiv = reviewRow.find('div', attrs={'class':'summary column'})
reviewSummaryDiv = ''
if reviewSummaryRawDiv is not None:
reviewSummaryDiv = reviewSummaryRawDiv.string
if not reviewSummaryDiv:
findReviewSummaryDiv = reviewRow.find('span', attrs={'class':'game_review_summary'})
if findReviewSummaryDiv:
reviewSummaryDiv = findReviewSummaryDiv.string
reviewSummaryDiv = reviewSummaryDiv.replace('\r', '').replace('\n', '').replace('\t', '')
if reviewSummaryDiv != 'No user reviews':
reviewRows += ' ' + reviewSubtitleDiv + \
reviewSummaryDiv.replace('-', '')\
.replace(' user reviews', '')\
.replace(' of the ', ' of ') + '\n'
if reviewRows:
AllGameDetailsFormatted += 'Reviews:\n' + reviewRows.replace('Recent Reviews:', '')
if AllGameDetailsFormatted.endswith('\n'):
AllGameDetailsFormatted = AllGameDetailsFormatted[:AllGameDetailsFormatted.rfind('\n')]
tagList = ''
tagLinks = soup.findAll('a', attrs={'class':'app_tag'})
if len(tagLinks) > 0:
for tagLink in tagLinks:
tagList += tagLink.string.replace('\r', '').replace('\n', '').replace('\t', '') + ', '
AllGameDetailsFormatted += '\n' + 'Tags:\n`' + tagList
if AllGameDetailsFormatted.endswith(', '):
AllGameDetailsFormatted = AllGameDetailsFormatted[:AllGameDetailsFormatted.rfind(', ')]
AllGameDetailsFormatted += '`'
return AllGameDetailsFormatted
class NoRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
infourl = urllib.addinfourl(fp, headers, req.get_full_url())
infourl.status = code
infourl.code = code
return infourl
http_error_300 = http_error_302
http_error_301 = http_error_302
http_error_303 = http_error_302
http_error_307 = http_error_302
def gog_results_parser(searchData):
if len(searchData['products']) > 0:
firstResult = searchData['products'][0]
if 'id' in firstResult:
return firstResult['id'], firstResult['price']['finalAmount'], firstResult['price']['discountPercentage']
return '', '', ''
def gog_game_parser(data, price, discount):
AllGameDetailsFormatted = ''
if 'title' in data:
gameTitle = data['title']
AllGameDetailsFormatted += '*' + gameTitle
else:
raise Exception('Cannot parse title from gog api object for this game.')
if price > 0:
AllGameDetailsFormatted += ' - ' + str(price) + '$'
else:
AllGameDetailsFormatted += ' - free to play'
if discount > 0:
AllGameDetailsFormatted += ' (at ' + discount + '% off)'
AllGameDetailsFormatted += '*\n'
if 'description' in data and 'full' in data['description']:
descriptionSnippet = data['description']['full']
AllGameDetailsFormatted += descriptionSnippet\
.replace('*','')\
.replace('<br>', '')\
.replace('<b>', '*')\
.replace('</b>', '*') + '\n'
#if 'links' in data and 'product_card' in data['links']:
# AllGameDetailsFormatted += data['links']['product_card'] + '\n'
#if 'release_date' in data:
# AllGameDetailsFormatted += 'Release Date: ' + data['release_date'] + '\n'
return AllGameDetailsFormatted
| 46.724138
| 163
| 0.609502
|
import json
import urllib
import urllib2
from bs4 import BeautifulSoup
def run(bot, chat_id, user, keyConfig='', message='', totalResults=1):
requestText = str(message)
if requestText == '':
totalSteamGames = int(Get_steam_total())
totalGOGGames = int(Get_GOG_total())
if totalSteamGames is not None and totalGOGGames is not None:
bot.sendMessage(chat_id=chat_id, text='I\'m sorry ' + (user if not user == '' else 'Dave') + \
', there are ' + str(int(totalSteamGames) + int(totalGOGGames)) +
' total games on Steam and GOG combined. Pick one.')
return True
retryCount = 3
appId = ''
while retryCount > 0 and appId == '':
retryCount -= 1
rawSteamSearchResultsMarkup = urllib.urlopen('http://store.steampowered.com/search/?category1=998&term=' + requestText).read()
appId = steam_results_parser(rawSteamSearchResultsMarkup)
if appId:
steamGameLink = 'http://store.steampowered.com/app/' + appId
bypassAgeGate = urllib2.build_opener()
#this bypasses the "mature content - continue/cancel" screen
bypassAgeGate.addheaders.append(('Cookie', 'mature_content=1; path=/; max-age=31536000;expires=Fri, 26 Mar 2027 20:00:00 GMT'))
bypassAgeGate.open(steamGameLink)
#this bypasses the "enter your date of birth" screen
bypassAgeGate.addheaders.append(('Cookie', 'birthtime=0; path=/; max-age=31536000;expires=Fri, 26 Mar 2027 20:00:00 GMT'))
code = bypassAgeGate.open(steamGameLink).read()
if 'id=\"agegate_wizard\"' in code:
gameTitle = steam_age_gate_parser(code)
bot.sendMessage(chat_id=chat_id, text='I\'m sorry ' + (user if not user == '' else 'Dave') + \
', I\'m afraid that \"' + gameTitle + '\" is protected by an age gate.\n' +
steamGameLink)
return False
gameResults = steam_game_parser(code, steamGameLink)
try:
bot.sendMessage(chat_id=chat_id, text=gameResults,
disable_web_page_preview=True, parse_mode='Markdown')
except:
bot.sendMessage(chat_id=chat_id, text=gameResults)
return True
else:
gogSearchData = json.load(urllib.urlopen('http://embed.gog.com/games/ajax/filtered?mediaType=game&search=' + requestText))
appId, price, discount = gog_results_parser(gogSearchData)
if appId:
gogGameLink = 'http://api.gog.com/products/' + str(appId) + '?expand=downloads,expanded_dlcs,description,screenshots,videos,related_products,changelog'
data = json.load(urllib.urlopen(gogGameLink))
gameResults = gog_game_parser(data, price, discount)
bot.sendMessage(chat_id=chat_id, text=gameResults,
disable_web_page_preview=True, parse_mode='Markdown')
else:
bot.sendMessage(chat_id=chat_id, text='I\'m sorry ' + (user if not user == '' else 'Dave') + \
', I\'m afraid I can\'t find the game ' + \
requestText.encode('utf-8'))
def steam_results_parser(rawMarkup):
soup = BeautifulSoup(rawMarkup, 'html.parser')
resultList = []
for resultRow in soup.findAll('a', attrs={'class':'search_result_row'}):
if 'data-ds-appid' in resultRow.attrs:
resultList.append(resultRow['data-ds-appid'])
if 'data-ds-bundleid' in resultRow.attrs:
resultList.append(resultRow['data-ds-bundleid'])
if len(resultList) > 0:
return resultList[0]
return ''
def Get_steam_total():
rawMarkup = urllib.urlopen('http://store.steampowered.com/search/?category1=998&term=#').read()
soup = BeautifulSoup(rawMarkup, 'html.parser')
findPaginationString = soup.find('div', attrs={'class': 'search_pagination_left'})
if findPaginationString:
rawPaginationString = findPaginationString.string
return rawPaginationString.replace('showing 1 - 25 of', '').strip()
return 'uncountable'
def Get_GOG_total():
GogSearchResultsData = json.load(urllib.urlopen('http://embed.gog.com/games/ajax/filtered?mediaType=game&sort=bestselling'))
if 'totalGamesFound' in GogSearchResultsData:
return GogSearchResultsData['totalGamesFound']
return 'uncountable'
def steam_age_gate_parser(rawMarkup):
soup = BeautifulSoup(rawMarkup, 'html.parser')
rawTitleString = soup.find('title').string
return rawTitleString.strip()
def steam_game_parser(code, link):
soup = BeautifulSoup(code, 'html.parser')
AllGameDetailsFormatted = ''
titleDiv = soup.find('div', attrs={'class':'apphub_AppName'})
if titleDiv:
gameTitle = titleDiv.string
AllGameDetailsFormatted += '*' + gameTitle
priceDiv = soup.find('div', attrs={'class':'game_purchase_price price'})
if priceDiv:
gamePrice = priceDiv.string
AllGameDetailsFormatted += ' - ' + gamePrice.strip()
else:
priceDiv = soup.find('div', attrs={'class':'discount_final_price'})
if priceDiv:
gamePrice = priceDiv.string
AllGameDetailsFormatted += ' - ' + gamePrice.strip()
discountPercentageDiv = soup.find('div', attrs={'class':'discount_pct'})
if discountPercentageDiv:
percentageDiscountedBy = discountPercentageDiv.string
AllGameDetailsFormatted += ' (at ' + percentageDiscountedBy.strip() + ' off)'
AllGameDetailsFormatted += '*\n'
else:
print('Cannot parse title as div with class apphub_AppName from Steam page for ' + link)
descriptionDiv = soup.find('div', attrs={'class':'game_description_snippet'})
if descriptionDiv:
descriptionSnippet = descriptionDiv.string.replace('\r', '').replace('\n', '').replace('\t', '').replace('_', ' ')
AllGameDetailsFormatted += descriptionSnippet + '\n'
if AllGameDetailsFormatted:
AllGameDetailsFormatted += link + '\n'
dateSpan = soup.find('div', attrs={'class':'date'})
if dateSpan:
releaseDate = dateSpan.string
AllGameDetailsFormatted += 'Release Date: ' + releaseDate + '\n'
featureList = ''
featureLinks = soup.findAll('a', attrs={'class':'name'})
if len(featureLinks) > 0:
for featureLink in featureLinks:
if featureLink.string != None:
featureList += ' ' + featureLink.string.replace('Seated', 'Seated VR') + '\n'
AllGameDetailsFormatted += 'Features:\n' + featureList
reviewRows = ''
reviewDivs = soup.findAll('div', attrs={'class':'user_reviews_summary_row'})
if len(reviewDivs) > 0:
for reviewRow in reviewDivs:
reviewSubtitleRawDiv = reviewRow.find('div', attrs={'class':'subtitle column'})
reviewSubtitleDiv = ''
if reviewSubtitleRawDiv is not None:
reviewSubtitleDiv = reviewSubtitleRawDiv.string
reviewSummaryRawDiv = reviewRow.find('div', attrs={'class':'summary column'})
reviewSummaryDiv = ''
if reviewSummaryRawDiv is not None:
reviewSummaryDiv = reviewSummaryRawDiv.string
if not reviewSummaryDiv:
findReviewSummaryDiv = reviewRow.find('span', attrs={'class':'game_review_summary'})
if findReviewSummaryDiv:
reviewSummaryDiv = findReviewSummaryDiv.string
reviewSummaryDiv = reviewSummaryDiv.replace('\r', '').replace('\n', '').replace('\t', '')
if reviewSummaryDiv != 'No user reviews':
reviewRows += ' ' + reviewSubtitleDiv + \
reviewSummaryDiv.replace('-', '')\
.replace(' user reviews', '')\
.replace(' of the ', ' of ') + '\n'
if reviewRows:
AllGameDetailsFormatted += 'Reviews:\n' + reviewRows.replace('Recent Reviews:', '')
if AllGameDetailsFormatted.endswith('\n'):
AllGameDetailsFormatted = AllGameDetailsFormatted[:AllGameDetailsFormatted.rfind('\n')]
tagList = ''
tagLinks = soup.findAll('a', attrs={'class':'app_tag'})
if len(tagLinks) > 0:
for tagLink in tagLinks:
tagList += tagLink.string.replace('\r', '').replace('\n', '').replace('\t', '') + ', '
AllGameDetailsFormatted += '\n' + 'Tags:\n`' + tagList
if AllGameDetailsFormatted.endswith(', '):
AllGameDetailsFormatted = AllGameDetailsFormatted[:AllGameDetailsFormatted.rfind(', ')]
AllGameDetailsFormatted += '`'
return AllGameDetailsFormatted
class NoRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
infourl = urllib.addinfourl(fp, headers, req.get_full_url())
infourl.status = code
infourl.code = code
return infourl
http_error_300 = http_error_302
http_error_301 = http_error_302
http_error_303 = http_error_302
http_error_307 = http_error_302
def gog_results_parser(searchData):
if len(searchData['products']) > 0:
firstResult = searchData['products'][0]
if 'id' in firstResult:
return firstResult['id'], firstResult['price']['finalAmount'], firstResult['price']['discountPercentage']
return '', '', ''
def gog_game_parser(data, price, discount):
AllGameDetailsFormatted = ''
if 'title' in data:
gameTitle = data['title']
AllGameDetailsFormatted += '*' + gameTitle
else:
raise Exception('Cannot parse title from gog api object for this game.')
if price > 0:
AllGameDetailsFormatted += ' - ' + str(price) + '$'
else:
AllGameDetailsFormatted += ' - free to play'
if discount > 0:
AllGameDetailsFormatted += ' (at ' + discount + '% off)'
AllGameDetailsFormatted += '*\n'
if 'description' in data and 'full' in data['description']:
descriptionSnippet = data['description']['full']
AllGameDetailsFormatted += descriptionSnippet\
.replace('*','')\
.replace('<br>', '')\
.replace('<b>', '*')\
.replace('</b>', '*') + '\n'
return AllGameDetailsFormatted
| true
| true
|
790e5778f848762c7ce6987dc100d2fd2ea59abd
| 4,343
|
py
|
Python
|
utilities/connmanagermqtt.py
|
connax-utim/uhost-micropython
|
853d5e12d050715aadf20eb065cf0658ba95696a
|
[
"Apache-2.0"
] | 1
|
2018-10-28T18:38:40.000Z
|
2018-10-28T18:38:40.000Z
|
utilities/connmanagermqtt.py
|
connax-utim/uhost-micropython
|
853d5e12d050715aadf20eb065cf0658ba95696a
|
[
"Apache-2.0"
] | 1
|
2018-11-20T09:42:52.000Z
|
2018-11-20T09:42:52.000Z
|
utilities/connmanagermqtt.py
|
connax-utim/uhost-micropython
|
853d5e12d050715aadf20eb065cf0658ba95696a
|
[
"Apache-2.0"
] | null | null | null |
"""ConnManagerMQTT containing script"""
import _thread
import time
import random
import logging
from .uconn_mqtt import UConnMQTT
from . import exceptions
class ConnManagerMQTT(object):
"""
UconnMQTT wrapper that guarantee delivery to addressee
"""
_SENDER = 'sender'
_DESTINATION = 'destination'
_MESSAGE = 'message'
def __init__(self):
"""
Initialization of ConnManager
"""
logging.info('Initializing ConnmanagerMQTT')
self.__connection = UConnMQTT()
self.__message_number = random.randint(0, 65536)
self.__sent_messages = dict()
self.__callback = None
self.__callback_object = None
def disconnect(self):
"""
Disconnection from server
"""
logging.info('Disconnecting...')
self.__connection.disconnect()
def subscribe(self, topic, callback_object, callback):
"""
Subscribe on topic
:param str topic: Topic for subscription
:param method callback: Callback for received message
"""
logging.info("Subscribing for {0}".format(topic))
if not callable(callback):
raise exceptions.UtimUncallableCallbackError
self.__callback = callback
self.__callback_object = callback_object
self.__connection.subscribe(topic, self, ConnManagerMQTT._on_message)
def unsubscribe(self, topic):
"""
Unsubscribe from topic
:param str topic: Topic for subscription cancelling
"""
logging.info("Unsubscribing from {0}".format(topic))
self.__connection.unsubscribe(topic)
def publish(self, sender, destination, message):
"""
Publish message
:param sender: Message sender
:param destination: Message destination
:param message: The message
"""
id = self.__message_number
self.__message_number = (self.__message_number + 1) % 65536
out_message = b'\x01' + id.to_bytes(2, 'big') + message
logging.info("Publishing {0} to topic {1}".format(message, destination))
self.__connection.publish(sender, destination, out_message)
self.__sent_messages[id] = {self._SENDER: sender,
self._DESTINATION: destination,
self._MESSAGE: message}
_thread.start_new_thread(self._republish, (id,))
def _republish(self, id):
"""
Check if message was delivered and republish if not
:param id: Message ID
"""
logging.info("_publish for {0} started".format(id))
time.sleep(10)
while id in self.__sent_messages.keys():
try:
logging.info("Message {0} wasn\'t delivered".format(id))
message = self.__sent_messages[id]
self.__connection.publish(message[self._SENDER], message[self._DESTINATION],
b'\x01' + id.to_bytes(2, 'big') + message[self._MESSAGE])
time.sleep(5)
except KeyError:
logging.error("Message was already deleted from republish")
break
logging.info("Message {0} was delivered".format(id))
def _on_message(self, sender, message):
"""
Message receiving callback
:param sender: Message sender
:param message: The message
"""
logging.info("Received message {0} from {1}".format(message, sender))
if len(message) < 3:
logging.info('Message is too short to be something!')
else:
if message[:1] == b'\x02':
try:
logging.info('Received ack, deleting message from sent')
id = int.from_bytes(message[1:3], 'big')
if id in self.__sent_messages.keys():
self.__sent_messages.pop(id)
except KeyError:
logging.error("Message was already deleted from republish")
else:
logging.info('Received message, sending ack...')
ack_message = b'\x02' + message[1:3]
self.__connection.publish(b'ack', sender.decode(), ack_message)
self.__callback(self.__callback_object, sender, message[3:])
| 35.024194
| 99
| 0.588994
|
import _thread
import time
import random
import logging
from .uconn_mqtt import UConnMQTT
from . import exceptions
class ConnManagerMQTT(object):
_SENDER = 'sender'
_DESTINATION = 'destination'
_MESSAGE = 'message'
def __init__(self):
logging.info('Initializing ConnmanagerMQTT')
self.__connection = UConnMQTT()
self.__message_number = random.randint(0, 65536)
self.__sent_messages = dict()
self.__callback = None
self.__callback_object = None
def disconnect(self):
logging.info('Disconnecting...')
self.__connection.disconnect()
def subscribe(self, topic, callback_object, callback):
logging.info("Subscribing for {0}".format(topic))
if not callable(callback):
raise exceptions.UtimUncallableCallbackError
self.__callback = callback
self.__callback_object = callback_object
self.__connection.subscribe(topic, self, ConnManagerMQTT._on_message)
def unsubscribe(self, topic):
logging.info("Unsubscribing from {0}".format(topic))
self.__connection.unsubscribe(topic)
def publish(self, sender, destination, message):
id = self.__message_number
self.__message_number = (self.__message_number + 1) % 65536
out_message = b'\x01' + id.to_bytes(2, 'big') + message
logging.info("Publishing {0} to topic {1}".format(message, destination))
self.__connection.publish(sender, destination, out_message)
self.__sent_messages[id] = {self._SENDER: sender,
self._DESTINATION: destination,
self._MESSAGE: message}
_thread.start_new_thread(self._republish, (id,))
def _republish(self, id):
logging.info("_publish for {0} started".format(id))
time.sleep(10)
while id in self.__sent_messages.keys():
try:
logging.info("Message {0} wasn\'t delivered".format(id))
message = self.__sent_messages[id]
self.__connection.publish(message[self._SENDER], message[self._DESTINATION],
b'\x01' + id.to_bytes(2, 'big') + message[self._MESSAGE])
time.sleep(5)
except KeyError:
logging.error("Message was already deleted from republish")
break
logging.info("Message {0} was delivered".format(id))
def _on_message(self, sender, message):
logging.info("Received message {0} from {1}".format(message, sender))
if len(message) < 3:
logging.info('Message is too short to be something!')
else:
if message[:1] == b'\x02':
try:
logging.info('Received ack, deleting message from sent')
id = int.from_bytes(message[1:3], 'big')
if id in self.__sent_messages.keys():
self.__sent_messages.pop(id)
except KeyError:
logging.error("Message was already deleted from republish")
else:
logging.info('Received message, sending ack...')
ack_message = b'\x02' + message[1:3]
self.__connection.publish(b'ack', sender.decode(), ack_message)
self.__callback(self.__callback_object, sender, message[3:])
| true
| true
|
790e585d98a2c69da340d368be90e40711f59e3f
| 9,033
|
py
|
Python
|
pyinsteon/topics.py
|
michaeldavie/pyinsteon
|
e5b2e2910f4eff1474f158051fa71f75c2077dd6
|
[
"MIT"
] | 15
|
2020-07-08T05:29:14.000Z
|
2022-03-24T18:56:26.000Z
|
pyinsteon/topics.py
|
michaeldavie/pyinsteon
|
e5b2e2910f4eff1474f158051fa71f75c2077dd6
|
[
"MIT"
] | 107
|
2019-06-03T09:23:02.000Z
|
2022-03-31T23:12:38.000Z
|
pyinsteon/topics.py
|
teharris1/pyinsteon
|
9476473676d714a62f0cfcc5124f7cd7e96de98b
|
[
"MIT"
] | 16
|
2019-01-24T01:09:49.000Z
|
2022-02-24T03:48:42.000Z
|
"""Constants used to ensure topic consistantancy."""
STANDARD_RECEIVED = "standard_received"
EXTENDED_RECEIVED = "extended_received"
X10_RECEIVED = "x10_received"
ALL_LINKING_COMPLETED = "all_linking_completed"
BUTTON_EVENT_REPORT = "button_event_report"
USER_RESET_DETECTED = "user_reset_detected"
ALL_LINK_CLEANUP_FAILURE_REPORT = "all_link_cleanup_failure_report"
ALL_LINK_RECORD_RESPONSE = "all_link_record_response"
ALL_LINK_CLEANUP_STATUS_REPORT = "all_link_cleanup_status_report"
GET_IM_INFO = "get_im_info"
SEND_ALL_LINK_COMMAND = "send_all_link_command"
SEND_STANDARD = "send_standard"
SEND_EXTENDED = "send_extended"
X10_SEND = "x10_send"
START_ALL_LINKING = "start_all_linking"
CANCEL_ALL_LINKING = "cancel_all_linking"
SET_HOST_DEV_CAT = "set_host_dev_cat"
RESET_IM = "reset_im"
SET_ACK_MESSAGE_BYTE = "set_ack_message_byte"
GET_FIRST_ALL_LINK_RECORD = "get_first_all_link_record"
GET_NEXT_ALL_LINK_RECORD = "get_next_all_link_record"
SET_IM_CONFIGURATION = "set_im_configuration"
GET_ALL_LINK_RECORD_FOR_SENDER = "get_all_link_record_for_sender"
LED_ON = "led_on"
LED_OFF = "led_off"
MANAGE_ALL_LINK_RECORD = "manage_all_link_record"
SET_NAK_MESSAGE_BYTE = "set_nak_message_byte"
SET_ACK_MESSAGE_TWO_BYTES = "set_ack_message_two_bytes"
RF_SLEEP = "rf_sleep"
GET_IM_CONFIGURATION = "get_im_configuration"
# Command Topics
ASSIGN_TO_ALL_LINK_GROUP = "assign_to_all_link_group"
DELETE_FROM_ALL_LINK_GROUP = "delete_from_all_link_group"
PRODUCT_DATA_REQUEST = "product_data_request"
FX_USERNAME = "fx_username"
DEVICE_TEXT_STRING_REQUEST = "device_text_string_request"
SET_DEVICE_TEXT_STRING = "set_device_text_string"
SET_ALL_LINK_COMMAND_ALIAS = "set_all_link_command_alias"
SET_ALL_LINK = "set_all_link"
ENTER_LINKING_MODE = "enter_linking_mode"
ENTER_UNLINKING_MODE = "enter_unlinking_mode"
GET_INSTEON_ENGINE_VERSION = "get_insteon_engine_version"
PING = "ping"
ID_REQUEST = "id_request"
ID_REQUEST_RESPONSE = "id_request_response"
ON = "on"
ON_FAST = "on_fast"
OFF = "off"
OFF_FAST = "off_fast"
BRIGHTEN_ONE_STEP = "brighten_one_step"
DIM_ONE_STEP = "dim_one_step"
START_MANUAL_CHANGE_DOWN = "start_manual_change_down"
START_MANUAL_CHANGE_UP = "start_manual_change_up"
STOP_MANUAL_CHANGE = "stop_manual_change"
STATUS_REQUEST = "status_request"
GET_OPERATING_FLAGS = "get_operating_flags"
SET_OPERATING_FLAGS = "set_operating_flags"
INSTANT_CHANGE = "instant_change"
MANUALLY_TURNED_OFF = "manually_turned_off"
MANUALLY_TURNED_ON = "manually_turned_on"
REMOTE_SET_BUTTON_TAP1_TAP = "remote_set_button_tap1_tap"
REMOTE_SET_BUTTON_TAP2_TAP = "remote_set_button_tap2_tap"
SET_STATUS = "set_status"
SET_ADDRESS_MSB = "set_address_msb"
POKE_ONE_BYTE = "poke_one_byte"
PEEK_ONE_BYTE = "peek_one_byte"
PEEK_ONE_BYTE_INTERNAL = "peek_one_byte_internal"
POKE_ONE_BYTE_INTERNAL = "poke_one_byte_internal"
ON_AT_RAMP_RATE = "on_at_ramp_rate"
EXTENDED_GET_SET = "extended_get_set"
EXTENDED_GET_RESPONSE = "extended_get_response"
THERMOSTAT_SET_POINT_RESPONSE = "thermostat_set_point_response"
THERMOSTAT_STATUS_RESPONSE = "thermostat_status_response"
EXTENDED_GET_SET_2 = "extended_get_set_2"
OFF_AT_RAMP_RATE = "off_at_ramp_rate"
EXTENDED_READ_WRITE_ALDB = "extended_read_write_aldb"
EXTENDED_TRIGGER_ALL_LINK = "extended_trigger_all_link"
BEEP = "beep"
SPRINKLER_VALVE_ON = "sprinkler_valve_on"
SPRINKLER_VALVE_OFF = "sprinkler_valve_off"
SPRINKLER_PROGRAM_ON = "sprinkler_program_on"
SPRINKLER_PROGRAM_OFF = "sprinkler_program_off"
SPRINKLER_LOAD_INITIALIZATION_VALUES = "sprinkler_load_initialization_values"
SPRINKLER_LOAD_EEPROM_FROM_RAM = "sprinkler_load_eeprom_from_ram"
SPRINKLER_GET_VALVE_STATUS = "sprinkler_get_valve_status"
SPRINKLER_INHIBIT_COMMAND_ACCEPTANCE = "sprinkler_inhibit_command_acceptance"
SPRINKLER_RESUME_COMMAND_ACCEPTANCE = "sprinkler_resume_command_acceptance"
SPRINKLER_SKIP_FORWARD = "sprinkler_skip_forward"
SPRINKLER_SKIP_BACK = "sprinkler_skip_back"
SPRINKLER_ENABLE_PUMP_ON_V8 = "sprinkler_enable_pump_on_v8"
SPRINKLER_DISABLE_PUMP_ON_V8 = "sprinkler_disable_pump_on_v8"
SPRINKLER_BROADCAST_ON = "sprinkler_broadcast_on"
SPRINKLER_BROADCAST_OFF = "sprinkler_broadcast_off"
SPRINKLER_LOAD_RAM_FROM_EEPROM = "sprinkler_load_ram_from_eeprom"
SPRINKLER_SENSOR_ON = "sprinkler_sensor_on"
SPRINKLER_SENSOR_OFF = "sprinkler_sensor_off"
SPRINKLER_DIAGNOSTICS_ON = "sprinkler_diagnostics_on"
SPRINKLER_DIAGNOSTICS_OFF = "sprinkler_diagnostics_off"
SPRINKLER_GET_PROGRAM_REQUEST = "sprinkler_get_program_request"
IO_OUTPUT_ON = "io_output_on"
IO_OUTPUT_OFF = "io_output_off"
IO_ALARM_DATA_REQUEST = "io_alarm_data_request"
IO_WRITE_OUTPUT_PORT = "io_write_output_port"
IO_READ_INPUT_PORT = "io_read_input_port"
IO_GET_SENSOR_VALUE = "io_get_sensor_value"
IO_SET_SENSOR_1_NOMINAL_VALUE = "io_set_sensor_1_nominal_value"
IO_GET_SENSOR_ALARM_DELTA = "io_get_sensor_alarm_delta"
FAN_STATUS_REPORT = "fan_status_report"
IO_WRITE_CONFIGURATION_PORT = "io_write_configuration_port"
IO_READ_CONFIGURATION_PORT = "io_read_configuration_port"
IO_MODULE_LOAD_INITIALIZATION_VALUES = "io_module_load_initialization_values"
IO_MODULE_LOAD_EEPROM_FROM_RAM = "io_module_load_eeprom_from_ram"
IO_MODULE_STATUS_REQUEST = "io_module_status_request"
IO_MODULE_READ_ANALOG_ONCE = "io_module_read_analog_once"
IO_MODULE_READ_ANALOG_ALWAYS = "io_module_read_analog_always"
IO_MODULE_ENABLE_STATUS_CHANGE_MESSAGE = "io_module_enable_status_change_message"
IO_MODULE_DISABLE_STATUS_CHANGE_MESSAGE = "io_module_disable_status_change_message"
IO_MODULE_LOAD_RAM_FROM_EEPROM = "io_module_load_ram_from_eeprom"
IO_MODULE_SENSOR_ON = "io_module_sensor_on"
IO_MODULE_SENSOR_OFF = "io_module_sensor_off"
IO_MODULE_DIAGNOSTICS_ON = "io_module_diagnostics_on"
IO_MODULE_DIAGNOSTICS_OFF = "io_module_diagnostics_off"
POOL_DEVICE_ON = "pool_device_on"
POOL_DEVICE_OFF = "pool_device_off"
POOL_TEMPERATURE_UP = "pool_temperature_up"
POOL_TEMPERATURE_DOWN = "pool_temperature_down"
POOL_LOAD_INITIALIZATION_VALUES = "pool_load_initialization_values"
POOL_LOAD_EEPROM_FROM_RAM = "pool_load_eeprom_from_ram"
POOL_GET_POOL_MODE = "pool_get_pool_mode"
POOL_GET_AMBIENT_TEMPERATURE = "pool_get_ambient_temperature"
POOL_GET_WATER_TEMPERATURE = "pool_get_water_temperature"
POOL_GET_PH = "pool_get_ph"
DOOR_MOVE_RAISE_DOOR = "door_move_raise_door"
DOOR_MOVE_LOWER_DOOR = "door_move_lower_door"
DOOR_MOVE_OPEN_DOOR = "door_move_open_door"
DOOR_MOVE_CLOSE_DOOR = "door_move_close_door"
DOOR_MOVE_STOP_DOOR = "door_move_stop_door"
DOOR_MOVE_SINGLE_DOOR_OPEN = "door_move_single_door_open"
DOOR_MOVE_SINGLE_DOOR_CLOSE = "door_move_single_door_close"
DOOR_STATUS_REPORT_RAISE_DOOR = "door_status_report_raise_door"
DOOR_STATUS_REPORT_LOWER_DOOR = "door_status_report_lower_door"
DOOR_STATUS_REPORT_OPEN_DOOR = "door_status_report_open_door"
DOOR_STATUS_REPORT_CLOSE_DOOR = "door_status_report_close_door"
DOOR_STATUS_REPORT_STOP_DOOR = "door_status_report_stop_door"
DOOR_STATUS_REPORT_SINGLE_DOOR_OPEN = "door_status_report_single_door_open"
DOOR_STATUS_REPORT_SINGLE_DOOR_CLOSE = "door_status_report_single_door_close"
WINDOW_COVERING_OPEN = "window_covering_open"
WINDOW_COVERING_CLOSE = "window_covering_close"
WINDOW_COVERING_STOP = "window_covering_stop"
WINDOW_COVERING_PROGRAM = "window_covering_program"
WINDOW_COVERING_POSITION = "window_covering_position"
THERMOSTAT_TEMPERATURE_UP = "thermostat_temperature_up"
THERMOSTAT_TEMPERATURE_DOWN = "thermostat_temperature_down"
THERMOSTAT_GET_ZONE_INFORMATION = "thermostat_get_zone_information"
THERMOSTAT_CONTROL = "thermostat_control"
THERMOSTAT_SET_COOL_SETPOINT = "thermostat_set_cool_setpoint"
THERMOSTAT_SET_HEAT_SETPOINT = "thermostat_set_heat_setpoint"
THERMOSTAT_EXTENDED_STATUS = "thermostat_extended_status"
THERMOSTAT_TEMPERATURE_STATUS = "thermostat_temperature_status"
THERMOSTAT_HUMIDITY_STATUS = "thermostat_humidity_status"
THERMOSTAT_MODE_STATUS = "thermostat_mode_status"
THERMOSTAT_COOL_SET_POINT_STATUS = "thermostat_cool_set_point_status"
THERMOSTAT_HEAT_SET_POINT_STATUS = "thermostat_heat_set_point_status"
LEAK_DETECTOR_ANNOUNCE = "leak_detector_announce"
ASSIGN_TO_COMPANION_GROUP = "assign_to_companion_group"
SET_SPRINKLER_PROGRAM = "set_sprinkler_program"
SPRINKLER_GET_PROGRAM_RESPONSE = "sprinkler_get_program_response"
IO_SET_SENSOR_NOMINAL_VALUE = "io_set_sensor_nominal_value"
IO_ALARM_DATA_RESPONSE = "io_alarm_data_response"
POOL_SET_DEVICE_TEMPERATURE = "pool_set_device_temperature"
POOL_SET_DEVICE_HYSTERESIS = "pool_set_device_hysteresis"
THERMOSTAT_ZONE_TEMPERATURE_UP = "thermostat_zone_temperature_up"
THERMOSTAT_ZONE_TEMPERATURE_DOWN = "thermostat_zone_temperature_down"
THERMOSTAT_SET_ZONE_HEAT_SETPOINT = "thermostat_set_zone_heat_setpoint"
THERMOSTAT_SET_ZONE_COOL_SETPOINT = "thermostat_set_zone_cool_setpoint"
DEVICE_LINK_CONTROLLER_CREATED = "device_link_controller_created"
DEVICE_LINK_CONTROLLER_REMOVED = "device_link_controller_removed"
DEVICE_LINK_RESPONDER_CREATED = "device_link_responder_created"
DEVICE_LINK_RESPONDER_REMOVED = "device_link_responder_removed"
ALDB_VERSION = "aldb_version"
ALDB_STATUS_CHANGED = "aldb_status_changed"
| 48.564516
| 83
| 0.878224
|
STANDARD_RECEIVED = "standard_received"
EXTENDED_RECEIVED = "extended_received"
X10_RECEIVED = "x10_received"
ALL_LINKING_COMPLETED = "all_linking_completed"
BUTTON_EVENT_REPORT = "button_event_report"
USER_RESET_DETECTED = "user_reset_detected"
ALL_LINK_CLEANUP_FAILURE_REPORT = "all_link_cleanup_failure_report"
ALL_LINK_RECORD_RESPONSE = "all_link_record_response"
ALL_LINK_CLEANUP_STATUS_REPORT = "all_link_cleanup_status_report"
GET_IM_INFO = "get_im_info"
SEND_ALL_LINK_COMMAND = "send_all_link_command"
SEND_STANDARD = "send_standard"
SEND_EXTENDED = "send_extended"
X10_SEND = "x10_send"
START_ALL_LINKING = "start_all_linking"
CANCEL_ALL_LINKING = "cancel_all_linking"
SET_HOST_DEV_CAT = "set_host_dev_cat"
RESET_IM = "reset_im"
SET_ACK_MESSAGE_BYTE = "set_ack_message_byte"
GET_FIRST_ALL_LINK_RECORD = "get_first_all_link_record"
GET_NEXT_ALL_LINK_RECORD = "get_next_all_link_record"
SET_IM_CONFIGURATION = "set_im_configuration"
GET_ALL_LINK_RECORD_FOR_SENDER = "get_all_link_record_for_sender"
LED_ON = "led_on"
LED_OFF = "led_off"
MANAGE_ALL_LINK_RECORD = "manage_all_link_record"
SET_NAK_MESSAGE_BYTE = "set_nak_message_byte"
SET_ACK_MESSAGE_TWO_BYTES = "set_ack_message_two_bytes"
RF_SLEEP = "rf_sleep"
GET_IM_CONFIGURATION = "get_im_configuration"
ASSIGN_TO_ALL_LINK_GROUP = "assign_to_all_link_group"
DELETE_FROM_ALL_LINK_GROUP = "delete_from_all_link_group"
PRODUCT_DATA_REQUEST = "product_data_request"
FX_USERNAME = "fx_username"
DEVICE_TEXT_STRING_REQUEST = "device_text_string_request"
SET_DEVICE_TEXT_STRING = "set_device_text_string"
SET_ALL_LINK_COMMAND_ALIAS = "set_all_link_command_alias"
SET_ALL_LINK = "set_all_link"
ENTER_LINKING_MODE = "enter_linking_mode"
ENTER_UNLINKING_MODE = "enter_unlinking_mode"
GET_INSTEON_ENGINE_VERSION = "get_insteon_engine_version"
PING = "ping"
ID_REQUEST = "id_request"
ID_REQUEST_RESPONSE = "id_request_response"
ON = "on"
ON_FAST = "on_fast"
OFF = "off"
OFF_FAST = "off_fast"
BRIGHTEN_ONE_STEP = "brighten_one_step"
DIM_ONE_STEP = "dim_one_step"
START_MANUAL_CHANGE_DOWN = "start_manual_change_down"
START_MANUAL_CHANGE_UP = "start_manual_change_up"
STOP_MANUAL_CHANGE = "stop_manual_change"
STATUS_REQUEST = "status_request"
GET_OPERATING_FLAGS = "get_operating_flags"
SET_OPERATING_FLAGS = "set_operating_flags"
INSTANT_CHANGE = "instant_change"
MANUALLY_TURNED_OFF = "manually_turned_off"
MANUALLY_TURNED_ON = "manually_turned_on"
REMOTE_SET_BUTTON_TAP1_TAP = "remote_set_button_tap1_tap"
REMOTE_SET_BUTTON_TAP2_TAP = "remote_set_button_tap2_tap"
SET_STATUS = "set_status"
SET_ADDRESS_MSB = "set_address_msb"
POKE_ONE_BYTE = "poke_one_byte"
PEEK_ONE_BYTE = "peek_one_byte"
PEEK_ONE_BYTE_INTERNAL = "peek_one_byte_internal"
POKE_ONE_BYTE_INTERNAL = "poke_one_byte_internal"
ON_AT_RAMP_RATE = "on_at_ramp_rate"
EXTENDED_GET_SET = "extended_get_set"
EXTENDED_GET_RESPONSE = "extended_get_response"
THERMOSTAT_SET_POINT_RESPONSE = "thermostat_set_point_response"
THERMOSTAT_STATUS_RESPONSE = "thermostat_status_response"
EXTENDED_GET_SET_2 = "extended_get_set_2"
OFF_AT_RAMP_RATE = "off_at_ramp_rate"
EXTENDED_READ_WRITE_ALDB = "extended_read_write_aldb"
EXTENDED_TRIGGER_ALL_LINK = "extended_trigger_all_link"
BEEP = "beep"
SPRINKLER_VALVE_ON = "sprinkler_valve_on"
SPRINKLER_VALVE_OFF = "sprinkler_valve_off"
SPRINKLER_PROGRAM_ON = "sprinkler_program_on"
SPRINKLER_PROGRAM_OFF = "sprinkler_program_off"
SPRINKLER_LOAD_INITIALIZATION_VALUES = "sprinkler_load_initialization_values"
SPRINKLER_LOAD_EEPROM_FROM_RAM = "sprinkler_load_eeprom_from_ram"
SPRINKLER_GET_VALVE_STATUS = "sprinkler_get_valve_status"
SPRINKLER_INHIBIT_COMMAND_ACCEPTANCE = "sprinkler_inhibit_command_acceptance"
SPRINKLER_RESUME_COMMAND_ACCEPTANCE = "sprinkler_resume_command_acceptance"
SPRINKLER_SKIP_FORWARD = "sprinkler_skip_forward"
SPRINKLER_SKIP_BACK = "sprinkler_skip_back"
SPRINKLER_ENABLE_PUMP_ON_V8 = "sprinkler_enable_pump_on_v8"
SPRINKLER_DISABLE_PUMP_ON_V8 = "sprinkler_disable_pump_on_v8"
SPRINKLER_BROADCAST_ON = "sprinkler_broadcast_on"
SPRINKLER_BROADCAST_OFF = "sprinkler_broadcast_off"
SPRINKLER_LOAD_RAM_FROM_EEPROM = "sprinkler_load_ram_from_eeprom"
SPRINKLER_SENSOR_ON = "sprinkler_sensor_on"
SPRINKLER_SENSOR_OFF = "sprinkler_sensor_off"
SPRINKLER_DIAGNOSTICS_ON = "sprinkler_diagnostics_on"
SPRINKLER_DIAGNOSTICS_OFF = "sprinkler_diagnostics_off"
SPRINKLER_GET_PROGRAM_REQUEST = "sprinkler_get_program_request"
IO_OUTPUT_ON = "io_output_on"
IO_OUTPUT_OFF = "io_output_off"
IO_ALARM_DATA_REQUEST = "io_alarm_data_request"
IO_WRITE_OUTPUT_PORT = "io_write_output_port"
IO_READ_INPUT_PORT = "io_read_input_port"
IO_GET_SENSOR_VALUE = "io_get_sensor_value"
IO_SET_SENSOR_1_NOMINAL_VALUE = "io_set_sensor_1_nominal_value"
IO_GET_SENSOR_ALARM_DELTA = "io_get_sensor_alarm_delta"
FAN_STATUS_REPORT = "fan_status_report"
IO_WRITE_CONFIGURATION_PORT = "io_write_configuration_port"
IO_READ_CONFIGURATION_PORT = "io_read_configuration_port"
IO_MODULE_LOAD_INITIALIZATION_VALUES = "io_module_load_initialization_values"
IO_MODULE_LOAD_EEPROM_FROM_RAM = "io_module_load_eeprom_from_ram"
IO_MODULE_STATUS_REQUEST = "io_module_status_request"
IO_MODULE_READ_ANALOG_ONCE = "io_module_read_analog_once"
IO_MODULE_READ_ANALOG_ALWAYS = "io_module_read_analog_always"
IO_MODULE_ENABLE_STATUS_CHANGE_MESSAGE = "io_module_enable_status_change_message"
IO_MODULE_DISABLE_STATUS_CHANGE_MESSAGE = "io_module_disable_status_change_message"
IO_MODULE_LOAD_RAM_FROM_EEPROM = "io_module_load_ram_from_eeprom"
IO_MODULE_SENSOR_ON = "io_module_sensor_on"
IO_MODULE_SENSOR_OFF = "io_module_sensor_off"
IO_MODULE_DIAGNOSTICS_ON = "io_module_diagnostics_on"
IO_MODULE_DIAGNOSTICS_OFF = "io_module_diagnostics_off"
POOL_DEVICE_ON = "pool_device_on"
POOL_DEVICE_OFF = "pool_device_off"
POOL_TEMPERATURE_UP = "pool_temperature_up"
POOL_TEMPERATURE_DOWN = "pool_temperature_down"
POOL_LOAD_INITIALIZATION_VALUES = "pool_load_initialization_values"
POOL_LOAD_EEPROM_FROM_RAM = "pool_load_eeprom_from_ram"
POOL_GET_POOL_MODE = "pool_get_pool_mode"
POOL_GET_AMBIENT_TEMPERATURE = "pool_get_ambient_temperature"
POOL_GET_WATER_TEMPERATURE = "pool_get_water_temperature"
POOL_GET_PH = "pool_get_ph"
DOOR_MOVE_RAISE_DOOR = "door_move_raise_door"
DOOR_MOVE_LOWER_DOOR = "door_move_lower_door"
DOOR_MOVE_OPEN_DOOR = "door_move_open_door"
DOOR_MOVE_CLOSE_DOOR = "door_move_close_door"
DOOR_MOVE_STOP_DOOR = "door_move_stop_door"
DOOR_MOVE_SINGLE_DOOR_OPEN = "door_move_single_door_open"
DOOR_MOVE_SINGLE_DOOR_CLOSE = "door_move_single_door_close"
DOOR_STATUS_REPORT_RAISE_DOOR = "door_status_report_raise_door"
DOOR_STATUS_REPORT_LOWER_DOOR = "door_status_report_lower_door"
DOOR_STATUS_REPORT_OPEN_DOOR = "door_status_report_open_door"
DOOR_STATUS_REPORT_CLOSE_DOOR = "door_status_report_close_door"
DOOR_STATUS_REPORT_STOP_DOOR = "door_status_report_stop_door"
DOOR_STATUS_REPORT_SINGLE_DOOR_OPEN = "door_status_report_single_door_open"
DOOR_STATUS_REPORT_SINGLE_DOOR_CLOSE = "door_status_report_single_door_close"
WINDOW_COVERING_OPEN = "window_covering_open"
WINDOW_COVERING_CLOSE = "window_covering_close"
WINDOW_COVERING_STOP = "window_covering_stop"
WINDOW_COVERING_PROGRAM = "window_covering_program"
WINDOW_COVERING_POSITION = "window_covering_position"
THERMOSTAT_TEMPERATURE_UP = "thermostat_temperature_up"
THERMOSTAT_TEMPERATURE_DOWN = "thermostat_temperature_down"
THERMOSTAT_GET_ZONE_INFORMATION = "thermostat_get_zone_information"
THERMOSTAT_CONTROL = "thermostat_control"
THERMOSTAT_SET_COOL_SETPOINT = "thermostat_set_cool_setpoint"
THERMOSTAT_SET_HEAT_SETPOINT = "thermostat_set_heat_setpoint"
THERMOSTAT_EXTENDED_STATUS = "thermostat_extended_status"
THERMOSTAT_TEMPERATURE_STATUS = "thermostat_temperature_status"
THERMOSTAT_HUMIDITY_STATUS = "thermostat_humidity_status"
THERMOSTAT_MODE_STATUS = "thermostat_mode_status"
THERMOSTAT_COOL_SET_POINT_STATUS = "thermostat_cool_set_point_status"
THERMOSTAT_HEAT_SET_POINT_STATUS = "thermostat_heat_set_point_status"
LEAK_DETECTOR_ANNOUNCE = "leak_detector_announce"
ASSIGN_TO_COMPANION_GROUP = "assign_to_companion_group"
SET_SPRINKLER_PROGRAM = "set_sprinkler_program"
SPRINKLER_GET_PROGRAM_RESPONSE = "sprinkler_get_program_response"
IO_SET_SENSOR_NOMINAL_VALUE = "io_set_sensor_nominal_value"
IO_ALARM_DATA_RESPONSE = "io_alarm_data_response"
POOL_SET_DEVICE_TEMPERATURE = "pool_set_device_temperature"
POOL_SET_DEVICE_HYSTERESIS = "pool_set_device_hysteresis"
THERMOSTAT_ZONE_TEMPERATURE_UP = "thermostat_zone_temperature_up"
THERMOSTAT_ZONE_TEMPERATURE_DOWN = "thermostat_zone_temperature_down"
THERMOSTAT_SET_ZONE_HEAT_SETPOINT = "thermostat_set_zone_heat_setpoint"
THERMOSTAT_SET_ZONE_COOL_SETPOINT = "thermostat_set_zone_cool_setpoint"
DEVICE_LINK_CONTROLLER_CREATED = "device_link_controller_created"
DEVICE_LINK_CONTROLLER_REMOVED = "device_link_controller_removed"
DEVICE_LINK_RESPONDER_CREATED = "device_link_responder_created"
DEVICE_LINK_RESPONDER_REMOVED = "device_link_responder_removed"
ALDB_VERSION = "aldb_version"
ALDB_STATUS_CHANGED = "aldb_status_changed"
| true
| true
|
790e59397dcef942cdcb90c1bca35ebe3af98ab2
| 4,500
|
py
|
Python
|
setup.py
|
Yanshang1991/espnet
|
174bc42814036cfa42ea133f937f59d7a89ecf5d
|
[
"Apache-2.0"
] | null | null | null |
setup.py
|
Yanshang1991/espnet
|
174bc42814036cfa42ea133f937f59d7a89ecf5d
|
[
"Apache-2.0"
] | null | null | null |
setup.py
|
Yanshang1991/espnet
|
174bc42814036cfa42ea133f937f59d7a89ecf5d
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python3
"""ESPnet setup script."""
import os
from distutils.version import LooseVersion
from setuptools import find_packages
from setuptools import setup
requirements = {
"install": [
"setuptools>=38.5.1",
"configargparse>=1.2.1",
"typeguard>=2.7.0",
"humanfriendly",
"scipy>=1.4.1",
"matplotlib==3.1.0",
"pillow>=6.1.0",
"editdistance==0.5.2",
"ctc-segmentation<1.8,>=1.6.6",
"wandb==0.12.2",
"filelock",
# The dependencies on chainer are optional now.
# "chainer==6.0.0",
# 'cupy==6.0.0',
"tensorboard>=1.14", # For pytorch>=1.1.0
# Signal processing related
"librosa>=0.8.0",
# Natural language processing related
"sentencepiece",
"nltk>=3.4.5",
"jamo==0.4.1", # For kss
# File IO related
"PyYAML>=5.1.2",
"soundfile>=0.10.2",
"h5py>=2.10.0",
"kaldiio>=2.17.0",
# TTS related
"pyworld>=0.2.10",
"espnet_tts_frontend",
# ASR frontend related
"nara_wpe>=0.0.5",
"torch>=1.3.0",
"torch_complex",
"pytorch_wpe",
"ci_sdr",
"sacrebleu>=1.5.1",
],
# all: The modules should be optionally installled due to some reason.
# Please consider moving them to "install" occasionally
"all": [
# NOTE(kamo): Append modules requiring specific pytorch version or torch>1.3.0
"torchaudio",
"torch_optimizer",
"fairscale",
"fairseq",
"transformers",
# FIXME(kamo): espnet_model_zoo can be moved to "install"?
"espnet_model_zoo",
],
# recipe: The modules actually are not invoked in the main module of espnet,
# but are invoked for the python scripts in each recipe
"recipe": [
"espnet_model_zoo",
"gdown",
"resampy",
"pysptk>=0.1.17",
"morfessor", # for zeroth-korean
"youtube_dl", # for laborotv
"nnmnkwii",
"museval>=0.2.1",
"pystoi>=0.2.2",
"mir-eval>=0.6",
"fastdtw",
],
"setup": ["numpy", "pytest-runner"],
"test": [
"pytest>=3.3.0",
"pytest-timeouts>=1.2.1",
"pytest-pythonpath>=0.7.3",
"pytest-cov>=2.7.1",
"hacking>=2.0.0",
"mock>=2.0.0",
"pycodestyle",
"jsondiff>=1.2.0",
"flake8>=3.7.8",
"flake8-docstrings>=1.3.1",
"black",
],
"doc": [
"Sphinx==2.1.2",
"sphinx-rtd-theme>=0.2.4",
"sphinx-argparse>=0.2.5",
"commonmark==0.8.1",
"recommonmark>=0.4.0",
"nbsphinx>=0.4.2",
"sphinx-markdown-tables>=0.0.12",
],
}
install_requires = requirements["install"]
setup_requires = requirements["setup"]
tests_require = requirements["test"]
extras_require = {
k: v for k, v in requirements.items() if k not in ["install", "setup"]
}
dirname = os.path.dirname(__file__)
version_file = os.path.join(dirname, "espnet", "version.txt")
with open(version_file, "r") as f:
version = f.read().strip()
setup(
name="espnet",
version=version,
url="http://github.com/espnet/espnet",
author="Shinji Watanabe",
author_email="shinjiw@ieee.org",
description="ESPnet: end-to-end speech processing toolkit",
long_description=open(os.path.join(dirname, "README.md"), encoding="utf-8").read(),
long_description_content_type="text/markdown",
license="Apache Software License",
packages=find_packages(include=["espnet*"]),
package_data={"espnet": ["version.txt"]},
# #448: "scripts" is inconvenient for developping because they are copied
# scripts=get_all_scripts('espnet/bin'),
install_requires=install_requires,
setup_requires=setup_requires,
tests_require=tests_require,
extras_require=extras_require,
python_requires=">=3.7.0",
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"Operating System :: POSIX :: Linux",
"License :: OSI Approved :: Apache Software License",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
| 30.821918
| 87
| 0.572667
|
import os
from distutils.version import LooseVersion
from setuptools import find_packages
from setuptools import setup
requirements = {
"install": [
"setuptools>=38.5.1",
"configargparse>=1.2.1",
"typeguard>=2.7.0",
"humanfriendly",
"scipy>=1.4.1",
"matplotlib==3.1.0",
"pillow>=6.1.0",
"editdistance==0.5.2",
"ctc-segmentation<1.8,>=1.6.6",
"wandb==0.12.2",
"filelock",
"tensorboard>=1.14",
"librosa>=0.8.0",
"sentencepiece",
"nltk>=3.4.5",
"jamo==0.4.1",
"PyYAML>=5.1.2",
"soundfile>=0.10.2",
"h5py>=2.10.0",
"kaldiio>=2.17.0",
"pyworld>=0.2.10",
"espnet_tts_frontend",
"nara_wpe>=0.0.5",
"torch>=1.3.0",
"torch_complex",
"pytorch_wpe",
"ci_sdr",
"sacrebleu>=1.5.1",
],
"all": [
"torchaudio",
"torch_optimizer",
"fairscale",
"fairseq",
"transformers",
"espnet_model_zoo",
],
"recipe": [
"espnet_model_zoo",
"gdown",
"resampy",
"pysptk>=0.1.17",
"morfessor",
"youtube_dl",
"nnmnkwii",
"museval>=0.2.1",
"pystoi>=0.2.2",
"mir-eval>=0.6",
"fastdtw",
],
"setup": ["numpy", "pytest-runner"],
"test": [
"pytest>=3.3.0",
"pytest-timeouts>=1.2.1",
"pytest-pythonpath>=0.7.3",
"pytest-cov>=2.7.1",
"hacking>=2.0.0",
"mock>=2.0.0",
"pycodestyle",
"jsondiff>=1.2.0",
"flake8>=3.7.8",
"flake8-docstrings>=1.3.1",
"black",
],
"doc": [
"Sphinx==2.1.2",
"sphinx-rtd-theme>=0.2.4",
"sphinx-argparse>=0.2.5",
"commonmark==0.8.1",
"recommonmark>=0.4.0",
"nbsphinx>=0.4.2",
"sphinx-markdown-tables>=0.0.12",
],
}
install_requires = requirements["install"]
setup_requires = requirements["setup"]
tests_require = requirements["test"]
extras_require = {
k: v for k, v in requirements.items() if k not in ["install", "setup"]
}
dirname = os.path.dirname(__file__)
version_file = os.path.join(dirname, "espnet", "version.txt")
with open(version_file, "r") as f:
version = f.read().strip()
setup(
name="espnet",
version=version,
url="http://github.com/espnet/espnet",
author="Shinji Watanabe",
author_email="shinjiw@ieee.org",
description="ESPnet: end-to-end speech processing toolkit",
long_description=open(os.path.join(dirname, "README.md"), encoding="utf-8").read(),
long_description_content_type="text/markdown",
license="Apache Software License",
packages=find_packages(include=["espnet*"]),
package_data={"espnet": ["version.txt"]},
equires,
tests_require=tests_require,
extras_require=extras_require,
python_requires=">=3.7.0",
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"Operating System :: POSIX :: Linux",
"License :: OSI Approved :: Apache Software License",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
| true
| true
|
790e5977e01b613959d5f6ef80e325921d5aa3ff
| 6,509
|
py
|
Python
|
neuralhydrology/modelzoo/ealstm.py
|
visr/neuralhydrology
|
77f6c9214945c8e857e3b9545afe8470da751cab
|
[
"BSD-3-Clause"
] | null | null | null |
neuralhydrology/modelzoo/ealstm.py
|
visr/neuralhydrology
|
77f6c9214945c8e857e3b9545afe8470da751cab
|
[
"BSD-3-Clause"
] | null | null | null |
neuralhydrology/modelzoo/ealstm.py
|
visr/neuralhydrology
|
77f6c9214945c8e857e3b9545afe8470da751cab
|
[
"BSD-3-Clause"
] | null | null | null |
from typing import Dict, Tuple
import torch
import torch.nn as nn
from neuralhydrology.modelzoo.basemodel import BaseModel
from neuralhydrology.modelzoo.fc import FC
from neuralhydrology.modelzoo.head import get_head
from neuralhydrology.utils.config import Config
class EALSTM(BaseModel):
"""Entity-Aware LSTM (EA-LSTM) model class.
This model has been proposed by Kratzert et al. [#]_ as a variant of the standard LSTM. The main difference is that
the input gate of the EA-LSTM is modulated using only the static inputs, while the dynamic (time series) inputs are
used in all other parts of the model (i.e. forget gate, cell update gate and output gate).
To control the initial forget gate bias, use the config argument `initial_forget_bias`. Often it is useful to set
this value to a positive value at the start of the model training, to keep the forget gate closed and to facilitate
the gradient flow.
The `EALSTM` class does only support single timescale predictions. Use `MTSLSTM` to train an LSTM-based model and
get predictions on multiple temporal resolutions at the same time.
Parameters
----------
cfg : Config
The run configuration.
References
----------
.. [#] Kratzert, F., Klotz, D., Shalev, G., Klambauer, G., Hochreiter, S., and Nearing, G.: Towards learning
universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets,
Hydrol. Earth Syst. Sci., 23, 5089–5110, https://doi.org/10.5194/hess-23-5089-2019, 2019.
"""
# specify submodules of the model that can later be used for finetuning. Names must match class attributes
module_parts = ['input_gate', 'dynamic_gates', 'head']
def __init__(self, cfg: Config):
super(EALSTM, self).__init__(cfg=cfg)
self._hidden_size = cfg.hidden_size
input_size_stat = len(cfg.static_inputs + cfg.camels_attributes + cfg.hydroatlas_attributes)
if cfg.use_basin_id_encoding:
input_size_stat += cfg.number_of_basins
# If hidden units for a embedding network are specified, create FC, otherwise single linear layer
if cfg.embedding_hiddens:
self.input_gate = FC(cfg=cfg)
else:
self.input_gate = nn.Linear(input_size_stat, cfg.hidden_size)
# create tensors of learnable parameters
self.dynamic_gates = _DynamicGates(cfg=cfg)
self.dropout = nn.Dropout(p=cfg.output_dropout)
self.head = get_head(cfg=cfg, n_in=cfg.hidden_size, n_out=self.output_size)
def _cell(self, x: torch.Tensor, i: torch.Tensor,
states: Tuple[torch.Tensor, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:
"""Single time step logic of EA-LSTM cell"""
h_0, c_0 = states
# calculate gates
gates = self.dynamic_gates(h_0, x)
f, o, g = gates.chunk(3, 1)
c_1 = torch.sigmoid(f) * c_0 + i * torch.tanh(g)
h_1 = torch.sigmoid(o) * torch.tanh(c_1)
return h_1, c_1
def forward(self, data: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""Perform a forward pass on the EA-LSTM model.
Parameters
----------
data : Dict[str, torch.Tensor]
Dictionary, containing input features as key-value pairs.
Returns
-------
Dict[str, torch.Tensor]
Model outputs and intermediate states as a dictionary.
- `y_hat`: model predictions of shape [batch size, sequence length, number of target variables].
- `h_n`: hidden state at the last time step of the sequence of shape
[batch size, sequence length, number of target variables].
- `c_n`: cell state at the last time step of the sequence of shape
[batch size, sequence length, number of target variables].
"""
# transpose to [seq_length, batch_size, n_features]
x_d = data['x_d'].transpose(0, 1)
if 'x_s' in data and 'x_one_hot' in data:
x_s = torch.cat([data['x_s'], data['x_one_hot']], dim=-1)
elif 'x_s' in data:
x_s = data['x_s']
elif 'x_one_hot' in data:
x_s = data['x_one_hot']
else:
raise ValueError('Need x_s or x_one_hot in forward pass.')
# TODO: move hidden and cell state initialization to init and only reset states in forward pass to zero.
h_t = x_d.data.new(x_d.shape[1], self._hidden_size).zero_()
c_t = x_d.data.new(x_d.shape[1], self._hidden_size).zero_()
# empty lists to temporally store all intermediate hidden/cell states
h_n, c_n = [], []
# calculate input gate only once because inputs are static
i = torch.sigmoid(self.input_gate(x_s))
# perform forward steps over input sequence
for x_dt in x_d:
h_t, c_t = self._cell(x_dt, i, (h_t, c_t))
# store intermediate hidden/cell state in list
h_n.append(h_t)
c_n.append(c_t)
h_n = torch.stack(h_n, 0).transpose(0, 1)
c_n = torch.stack(c_n, 0).transpose(0, 1)
pred = {'h_n': h_n, 'c_n': c_n}
pred.update(self.head(self.dropout(h_n)))
return pred
class _DynamicGates(nn.Module):
"""Internal class to wrap the dynamic gate parameters into a dedicated PyTorch Module"""
def __init__(self, cfg: Config):
super(_DynamicGates, self).__init__()
self.cfg = cfg
self.weight_ih = nn.Parameter(torch.FloatTensor(len(cfg.dynamic_inputs), 3 * cfg.hidden_size))
self.weight_hh = nn.Parameter(torch.FloatTensor(cfg.hidden_size, 3 * cfg.hidden_size))
self.bias = nn.Parameter(torch.FloatTensor(3 * cfg.hidden_size))
# initialize parameters
self._reset_parameters()
def _reset_parameters(self):
"""Special initialization of certain model weights."""
nn.init.orthogonal_(self.weight_ih.data)
weight_hh_data = torch.eye(self.cfg.hidden_size)
weight_hh_data = weight_hh_data.repeat(1, 3)
self.weight_hh.data = weight_hh_data
nn.init.constant_(self.bias.data, val=0)
if self.cfg.initial_forget_bias is not None:
self.bias.data[:self.cfg.hidden_size] = self.cfg.initial_forget_bias
def forward(self, h: torch.Tensor, x_d: torch.Tensor):
gates = h @ self.weight_hh + x_d @ self.weight_ih + self.bias
return gates
| 40.937107
| 119
| 0.649101
|
from typing import Dict, Tuple
import torch
import torch.nn as nn
from neuralhydrology.modelzoo.basemodel import BaseModel
from neuralhydrology.modelzoo.fc import FC
from neuralhydrology.modelzoo.head import get_head
from neuralhydrology.utils.config import Config
class EALSTM(BaseModel):
module_parts = ['input_gate', 'dynamic_gates', 'head']
def __init__(self, cfg: Config):
super(EALSTM, self).__init__(cfg=cfg)
self._hidden_size = cfg.hidden_size
input_size_stat = len(cfg.static_inputs + cfg.camels_attributes + cfg.hydroatlas_attributes)
if cfg.use_basin_id_encoding:
input_size_stat += cfg.number_of_basins
if cfg.embedding_hiddens:
self.input_gate = FC(cfg=cfg)
else:
self.input_gate = nn.Linear(input_size_stat, cfg.hidden_size)
self.dynamic_gates = _DynamicGates(cfg=cfg)
self.dropout = nn.Dropout(p=cfg.output_dropout)
self.head = get_head(cfg=cfg, n_in=cfg.hidden_size, n_out=self.output_size)
def _cell(self, x: torch.Tensor, i: torch.Tensor,
states: Tuple[torch.Tensor, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:
h_0, c_0 = states
gates = self.dynamic_gates(h_0, x)
f, o, g = gates.chunk(3, 1)
c_1 = torch.sigmoid(f) * c_0 + i * torch.tanh(g)
h_1 = torch.sigmoid(o) * torch.tanh(c_1)
return h_1, c_1
def forward(self, data: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
x_d = data['x_d'].transpose(0, 1)
if 'x_s' in data and 'x_one_hot' in data:
x_s = torch.cat([data['x_s'], data['x_one_hot']], dim=-1)
elif 'x_s' in data:
x_s = data['x_s']
elif 'x_one_hot' in data:
x_s = data['x_one_hot']
else:
raise ValueError('Need x_s or x_one_hot in forward pass.')
h_t = x_d.data.new(x_d.shape[1], self._hidden_size).zero_()
c_t = x_d.data.new(x_d.shape[1], self._hidden_size).zero_()
h_n, c_n = [], []
i = torch.sigmoid(self.input_gate(x_s))
for x_dt in x_d:
h_t, c_t = self._cell(x_dt, i, (h_t, c_t))
h_n.append(h_t)
c_n.append(c_t)
h_n = torch.stack(h_n, 0).transpose(0, 1)
c_n = torch.stack(c_n, 0).transpose(0, 1)
pred = {'h_n': h_n, 'c_n': c_n}
pred.update(self.head(self.dropout(h_n)))
return pred
class _DynamicGates(nn.Module):
def __init__(self, cfg: Config):
super(_DynamicGates, self).__init__()
self.cfg = cfg
self.weight_ih = nn.Parameter(torch.FloatTensor(len(cfg.dynamic_inputs), 3 * cfg.hidden_size))
self.weight_hh = nn.Parameter(torch.FloatTensor(cfg.hidden_size, 3 * cfg.hidden_size))
self.bias = nn.Parameter(torch.FloatTensor(3 * cfg.hidden_size))
self._reset_parameters()
def _reset_parameters(self):
nn.init.orthogonal_(self.weight_ih.data)
weight_hh_data = torch.eye(self.cfg.hidden_size)
weight_hh_data = weight_hh_data.repeat(1, 3)
self.weight_hh.data = weight_hh_data
nn.init.constant_(self.bias.data, val=0)
if self.cfg.initial_forget_bias is not None:
self.bias.data[:self.cfg.hidden_size] = self.cfg.initial_forget_bias
def forward(self, h: torch.Tensor, x_d: torch.Tensor):
gates = h @ self.weight_hh + x_d @ self.weight_ih + self.bias
return gates
| true
| true
|
790e59e8577def6088dd6be0c6089fab686dad2b
| 503
|
py
|
Python
|
env/Lib/site-packages/plotly/validators/choroplethmapbox/hoverlabel/font/_color.py
|
andresgreen-byte/Laboratorio-1--Inversion-de-Capital
|
8a4707301d19c3826c31026c4077930bcd6a8182
|
[
"MIT"
] | 11,750
|
2015-10-12T07:03:39.000Z
|
2022-03-31T20:43:15.000Z
|
venv/Lib/site-packages/plotly/validators/choroplethmapbox/hoverlabel/font/_color.py
|
wakisalvador/constructed-misdirection
|
74779e9ec640a11bc08d5d1967c85ac4fa44ea5e
|
[
"Unlicense"
] | 2,951
|
2015-10-12T00:41:25.000Z
|
2022-03-31T22:19:26.000Z
|
venv/Lib/site-packages/plotly/validators/choroplethmapbox/hoverlabel/font/_color.py
|
wakisalvador/constructed-misdirection
|
74779e9ec640a11bc08d5d1967c85ac4fa44ea5e
|
[
"Unlicense"
] | 2,623
|
2015-10-15T14:40:27.000Z
|
2022-03-28T16:05:50.000Z
|
import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self,
plotly_name="color",
parent_name="choroplethmapbox.hoverlabel.font",
**kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.pop("edit_type", "none"),
**kwargs
)
| 27.944444
| 66
| 0.620278
|
import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self,
plotly_name="color",
parent_name="choroplethmapbox.hoverlabel.font",
**kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.pop("edit_type", "none"),
**kwargs
)
| true
| true
|
790e5d0d53be79fd7df36cb0ca4ecc96f552c5b0
| 9,572
|
py
|
Python
|
django/contrib/auth/tests/test_remote_user.py
|
benjaoming/django
|
6dbe979b4d9396e1b307c7d27388c97c13beb21c
|
[
"BSD-3-Clause"
] | 2
|
2015-01-21T15:45:07.000Z
|
2015-02-21T02:38:13.000Z
|
django/contrib/auth/tests/test_remote_user.py
|
HenriqueLR/django
|
d1ca70110f49f0be90206c8da516ac16aebc8c75
|
[
"BSD-3-Clause"
] | null | null | null |
django/contrib/auth/tests/test_remote_user.py
|
HenriqueLR/django
|
d1ca70110f49f0be90206c8da516ac16aebc8c75
|
[
"BSD-3-Clause"
] | 1
|
2020-05-25T08:55:19.000Z
|
2020-05-25T08:55:19.000Z
|
from datetime import datetime
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth.backends import RemoteUserBackend
from django.contrib.auth.middleware import RemoteUserMiddleware
from django.contrib.auth.models import User
from django.contrib.auth.tests.utils import skipIfCustomUser
from django.test import TestCase, override_settings
from django.utils import timezone
@skipIfCustomUser
@override_settings(ROOT_URLCONF='django.contrib.auth.tests.urls')
class RemoteUserTest(TestCase):
middleware = 'django.contrib.auth.middleware.RemoteUserMiddleware'
backend = 'django.contrib.auth.backends.RemoteUserBackend'
header = 'REMOTE_USER'
# Usernames to be passed in REMOTE_USER for the test_known_user test case.
known_user = 'knownuser'
known_user2 = 'knownuser2'
def setUp(self):
self.curr_middleware = settings.MIDDLEWARE_CLASSES
self.curr_auth = settings.AUTHENTICATION_BACKENDS
settings.MIDDLEWARE_CLASSES += (self.middleware,)
settings.AUTHENTICATION_BACKENDS += (self.backend,)
def test_no_remote_user(self):
"""
Tests requests where no remote user is specified and insures that no
users get created.
"""
num_users = User.objects.count()
response = self.client.get('/remote_user/')
self.assertTrue(response.context['user'].is_anonymous())
self.assertEqual(User.objects.count(), num_users)
response = self.client.get('/remote_user/', **{self.header: None})
self.assertTrue(response.context['user'].is_anonymous())
self.assertEqual(User.objects.count(), num_users)
response = self.client.get('/remote_user/', **{self.header: ''})
self.assertTrue(response.context['user'].is_anonymous())
self.assertEqual(User.objects.count(), num_users)
def test_unknown_user(self):
"""
Tests the case where the username passed in the header does not exist
as a User.
"""
num_users = User.objects.count()
response = self.client.get('/remote_user/', **{self.header: 'newuser'})
self.assertEqual(response.context['user'].username, 'newuser')
self.assertEqual(User.objects.count(), num_users + 1)
User.objects.get(username='newuser')
# Another request with same user should not create any new users.
response = self.client.get('/remote_user/', **{self.header: 'newuser'})
self.assertEqual(User.objects.count(), num_users + 1)
def test_known_user(self):
"""
Tests the case where the username passed in the header is a valid User.
"""
User.objects.create(username='knownuser')
User.objects.create(username='knownuser2')
num_users = User.objects.count()
response = self.client.get('/remote_user/',
**{self.header: self.known_user})
self.assertEqual(response.context['user'].username, 'knownuser')
self.assertEqual(User.objects.count(), num_users)
# Test that a different user passed in the headers causes the new user
# to be logged in.
response = self.client.get('/remote_user/',
**{self.header: self.known_user2})
self.assertEqual(response.context['user'].username, 'knownuser2')
self.assertEqual(User.objects.count(), num_users)
def test_last_login(self):
"""
Tests that a user's last_login is set the first time they make a
request but not updated in subsequent requests with the same session.
"""
user = User.objects.create(username='knownuser')
# Set last_login to something so we can determine if it changes.
default_login = datetime(2000, 1, 1)
if settings.USE_TZ:
default_login = default_login.replace(tzinfo=timezone.utc)
user.last_login = default_login
user.save()
response = self.client.get('/remote_user/',
**{self.header: self.known_user})
self.assertNotEqual(default_login, response.context['user'].last_login)
user = User.objects.get(username='knownuser')
user.last_login = default_login
user.save()
response = self.client.get('/remote_user/',
**{self.header: self.known_user})
self.assertEqual(default_login, response.context['user'].last_login)
def test_header_disappears(self):
"""
Tests that a logged in user is logged out automatically when
the REMOTE_USER header disappears during the same browser session.
"""
User.objects.create(username='knownuser')
# Known user authenticates
response = self.client.get('/remote_user/',
**{self.header: self.known_user})
self.assertEqual(response.context['user'].username, 'knownuser')
# During the session, the REMOTE_USER header disappears. Should trigger logout.
response = self.client.get('/remote_user/')
self.assertEqual(response.context['user'].is_anonymous(), True)
# verify the remoteuser middleware will not remove a user
# authenticated via another backend
User.objects.create_user(username='modeluser', password='foo')
self.client.login(username='modeluser', password='foo')
authenticate(username='modeluser', password='foo')
response = self.client.get('/remote_user/')
self.assertEqual(response.context['user'].username, 'modeluser')
def test_user_switch_forces_new_login(self):
"""
Tests that if the username in the header changes between requests
that the original user is logged out
"""
User.objects.create(username='knownuser')
# Known user authenticates
response = self.client.get('/remote_user/',
**{self.header: self.known_user})
self.assertEqual(response.context['user'].username, 'knownuser')
# During the session, the REMOTE_USER changes to a different user.
response = self.client.get('/remote_user/',
**{self.header: "newnewuser"})
# Ensure that the current user is not the prior remote_user
# In backends that create a new user, username is "newnewuser"
# In backends that do not create new users, it is '' (anonymous user)
self.assertNotEqual(response.context['user'].username, 'knownuser')
def tearDown(self):
"""Restores settings to avoid breaking other tests."""
settings.MIDDLEWARE_CLASSES = self.curr_middleware
settings.AUTHENTICATION_BACKENDS = self.curr_auth
class RemoteUserNoCreateBackend(RemoteUserBackend):
"""Backend that doesn't create unknown users."""
create_unknown_user = False
@skipIfCustomUser
class RemoteUserNoCreateTest(RemoteUserTest):
"""
Contains the same tests as RemoteUserTest, but using a custom auth backend
class that doesn't create unknown users.
"""
backend = 'django.contrib.auth.tests.test_remote_user.RemoteUserNoCreateBackend'
def test_unknown_user(self):
num_users = User.objects.count()
response = self.client.get('/remote_user/', **{self.header: 'newuser'})
self.assertTrue(response.context['user'].is_anonymous())
self.assertEqual(User.objects.count(), num_users)
class CustomRemoteUserBackend(RemoteUserBackend):
"""
Backend that overrides RemoteUserBackend methods.
"""
def clean_username(self, username):
"""
Grabs username before the @ character.
"""
return username.split('@')[0]
def configure_user(self, user):
"""
Sets user's email address.
"""
user.email = 'user@example.com'
user.save()
return user
@skipIfCustomUser
class RemoteUserCustomTest(RemoteUserTest):
"""
Tests a custom RemoteUserBackend subclass that overrides the clean_username
and configure_user methods.
"""
backend = 'django.contrib.auth.tests.test_remote_user.CustomRemoteUserBackend'
# REMOTE_USER strings with email addresses for the custom backend to
# clean.
known_user = 'knownuser@example.com'
known_user2 = 'knownuser2@example.com'
def test_known_user(self):
"""
The strings passed in REMOTE_USER should be cleaned and the known users
should not have been configured with an email address.
"""
super(RemoteUserCustomTest, self).test_known_user()
self.assertEqual(User.objects.get(username='knownuser').email, '')
self.assertEqual(User.objects.get(username='knownuser2').email, '')
def test_unknown_user(self):
"""
The unknown user created should be configured with an email address.
"""
super(RemoteUserCustomTest, self).test_unknown_user()
newuser = User.objects.get(username='newuser')
self.assertEqual(newuser.email, 'user@example.com')
class CustomHeaderMiddleware(RemoteUserMiddleware):
"""
Middleware that overrides custom HTTP auth user header.
"""
header = 'HTTP_AUTHUSER'
@skipIfCustomUser
class CustomHeaderRemoteUserTest(RemoteUserTest):
"""
Tests a custom RemoteUserMiddleware subclass with custom HTTP auth user
header.
"""
middleware = (
'django.contrib.auth.tests.test_remote_user.CustomHeaderMiddleware'
)
header = 'HTTP_AUTHUSER'
| 39.717842
| 87
| 0.66496
|
from datetime import datetime
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth.backends import RemoteUserBackend
from django.contrib.auth.middleware import RemoteUserMiddleware
from django.contrib.auth.models import User
from django.contrib.auth.tests.utils import skipIfCustomUser
from django.test import TestCase, override_settings
from django.utils import timezone
@skipIfCustomUser
@override_settings(ROOT_URLCONF='django.contrib.auth.tests.urls')
class RemoteUserTest(TestCase):
middleware = 'django.contrib.auth.middleware.RemoteUserMiddleware'
backend = 'django.contrib.auth.backends.RemoteUserBackend'
header = 'REMOTE_USER'
known_user = 'knownuser'
known_user2 = 'knownuser2'
def setUp(self):
self.curr_middleware = settings.MIDDLEWARE_CLASSES
self.curr_auth = settings.AUTHENTICATION_BACKENDS
settings.MIDDLEWARE_CLASSES += (self.middleware,)
settings.AUTHENTICATION_BACKENDS += (self.backend,)
def test_no_remote_user(self):
num_users = User.objects.count()
response = self.client.get('/remote_user/')
self.assertTrue(response.context['user'].is_anonymous())
self.assertEqual(User.objects.count(), num_users)
response = self.client.get('/remote_user/', **{self.header: None})
self.assertTrue(response.context['user'].is_anonymous())
self.assertEqual(User.objects.count(), num_users)
response = self.client.get('/remote_user/', **{self.header: ''})
self.assertTrue(response.context['user'].is_anonymous())
self.assertEqual(User.objects.count(), num_users)
def test_unknown_user(self):
num_users = User.objects.count()
response = self.client.get('/remote_user/', **{self.header: 'newuser'})
self.assertEqual(response.context['user'].username, 'newuser')
self.assertEqual(User.objects.count(), num_users + 1)
User.objects.get(username='newuser')
response = self.client.get('/remote_user/', **{self.header: 'newuser'})
self.assertEqual(User.objects.count(), num_users + 1)
def test_known_user(self):
User.objects.create(username='knownuser')
User.objects.create(username='knownuser2')
num_users = User.objects.count()
response = self.client.get('/remote_user/',
**{self.header: self.known_user})
self.assertEqual(response.context['user'].username, 'knownuser')
self.assertEqual(User.objects.count(), num_users)
response = self.client.get('/remote_user/',
**{self.header: self.known_user2})
self.assertEqual(response.context['user'].username, 'knownuser2')
self.assertEqual(User.objects.count(), num_users)
def test_last_login(self):
user = User.objects.create(username='knownuser')
default_login = datetime(2000, 1, 1)
if settings.USE_TZ:
default_login = default_login.replace(tzinfo=timezone.utc)
user.last_login = default_login
user.save()
response = self.client.get('/remote_user/',
**{self.header: self.known_user})
self.assertNotEqual(default_login, response.context['user'].last_login)
user = User.objects.get(username='knownuser')
user.last_login = default_login
user.save()
response = self.client.get('/remote_user/',
**{self.header: self.known_user})
self.assertEqual(default_login, response.context['user'].last_login)
def test_header_disappears(self):
User.objects.create(username='knownuser')
response = self.client.get('/remote_user/',
**{self.header: self.known_user})
self.assertEqual(response.context['user'].username, 'knownuser')
response = self.client.get('/remote_user/')
self.assertEqual(response.context['user'].is_anonymous(), True)
User.objects.create_user(username='modeluser', password='foo')
self.client.login(username='modeluser', password='foo')
authenticate(username='modeluser', password='foo')
response = self.client.get('/remote_user/')
self.assertEqual(response.context['user'].username, 'modeluser')
def test_user_switch_forces_new_login(self):
User.objects.create(username='knownuser')
response = self.client.get('/remote_user/',
**{self.header: self.known_user})
self.assertEqual(response.context['user'].username, 'knownuser')
response = self.client.get('/remote_user/',
**{self.header: "newnewuser"})
self.assertNotEqual(response.context['user'].username, 'knownuser')
def tearDown(self):
settings.MIDDLEWARE_CLASSES = self.curr_middleware
settings.AUTHENTICATION_BACKENDS = self.curr_auth
class RemoteUserNoCreateBackend(RemoteUserBackend):
create_unknown_user = False
@skipIfCustomUser
class RemoteUserNoCreateTest(RemoteUserTest):
backend = 'django.contrib.auth.tests.test_remote_user.RemoteUserNoCreateBackend'
def test_unknown_user(self):
num_users = User.objects.count()
response = self.client.get('/remote_user/', **{self.header: 'newuser'})
self.assertTrue(response.context['user'].is_anonymous())
self.assertEqual(User.objects.count(), num_users)
class CustomRemoteUserBackend(RemoteUserBackend):
def clean_username(self, username):
return username.split('@')[0]
def configure_user(self, user):
user.email = 'user@example.com'
user.save()
return user
@skipIfCustomUser
class RemoteUserCustomTest(RemoteUserTest):
backend = 'django.contrib.auth.tests.test_remote_user.CustomRemoteUserBackend'
known_user = 'knownuser@example.com'
known_user2 = 'knownuser2@example.com'
def test_known_user(self):
super(RemoteUserCustomTest, self).test_known_user()
self.assertEqual(User.objects.get(username='knownuser').email, '')
self.assertEqual(User.objects.get(username='knownuser2').email, '')
def test_unknown_user(self):
super(RemoteUserCustomTest, self).test_unknown_user()
newuser = User.objects.get(username='newuser')
self.assertEqual(newuser.email, 'user@example.com')
class CustomHeaderMiddleware(RemoteUserMiddleware):
header = 'HTTP_AUTHUSER'
@skipIfCustomUser
class CustomHeaderRemoteUserTest(RemoteUserTest):
middleware = (
'django.contrib.auth.tests.test_remote_user.CustomHeaderMiddleware'
)
header = 'HTTP_AUTHUSER'
| true
| true
|
790e5ddd622bac946e3a162d790ba18695bc6ec7
| 1,673
|
py
|
Python
|
13/00/finditer.py
|
pylangstudy/201708
|
126b1af96a1d1f57522d5a1d435b58597bea2e57
|
[
"CC0-1.0"
] | null | null | null |
13/00/finditer.py
|
pylangstudy/201708
|
126b1af96a1d1f57522d5a1d435b58597bea2e57
|
[
"CC0-1.0"
] | 39
|
2017-07-31T22:54:01.000Z
|
2017-08-31T00:19:03.000Z
|
13/00/finditer.py
|
pylangstudy/201708
|
126b1af96a1d1f57522d5a1d435b58597bea2e57
|
[
"CC0-1.0"
] | null | null | null |
#!python3.6
#coding:utf-8
#regex.finditer(string[, pos[, endpos]])
import re
regex = re.compile(r'^ab')
print(regex)
for target in ['abcdefg', 'cdefg', 'abcdabcd', 'cdabAB', 'ABcd']:
print(target, regex.finditer(target))
print()
regex = re.compile(r'^ab', re.IGNORECASE)
print(regex)
for target in ['abcdefg', 'cdefg', 'abcdabcd', 'cdabAB', 'ABcd']:
print(target, regex.finditer(target))
print()
regex = re.compile(r'ab', re.IGNORECASE)
print(regex)
for target in ['abcdefg', 'cdefg', 'abcdabcd', 'cdabAB', 'ABcd']:
print(target, regex.finditer(target))
print()
regex = re.compile(r'ab', re.IGNORECASE)
print(regex)
pos = 2
for target in ['abcdefg', 'cdefg', 'abcdabcd', 'cdabAB']:
print(target, regex.finditer(target, pos, endpos=len(target)))
print()
regex = re.compile(r'ab', re.IGNORECASE)
print(regex)
for target in ['abcdefg', 'cdefg', 'abcdabcd', 'cdabAB']:
match = regex.finditer(target, pos, endpos=len(target))
print(target, match)
if match:
print(' match.expand():', match.expand('XY'))#AttributeError: 'list' object has no attribute 'expand'
print(' match.group():', match.group())
print(' match.groups():', match.groups())
print(' match.groupdict():', match.groupdict())
print(' match.start():', match.start())
print(' match.end():', match.end())
print(' match.span():', match.span())
print(' match.pos:', match.pos)
print(' match.endpos:', match.endpos)
print(' match.lastindex:', match.lastindex)
print(' match.lastgroup:', match.lastgroup)
print(' match.re:', match.re)
print(' match.string:', match.string)
| 34.142857
| 110
| 0.62642
|
import re
regex = re.compile(r'^ab')
print(regex)
for target in ['abcdefg', 'cdefg', 'abcdabcd', 'cdabAB', 'ABcd']:
print(target, regex.finditer(target))
print()
regex = re.compile(r'^ab', re.IGNORECASE)
print(regex)
for target in ['abcdefg', 'cdefg', 'abcdabcd', 'cdabAB', 'ABcd']:
print(target, regex.finditer(target))
print()
regex = re.compile(r'ab', re.IGNORECASE)
print(regex)
for target in ['abcdefg', 'cdefg', 'abcdabcd', 'cdabAB', 'ABcd']:
print(target, regex.finditer(target))
print()
regex = re.compile(r'ab', re.IGNORECASE)
print(regex)
pos = 2
for target in ['abcdefg', 'cdefg', 'abcdabcd', 'cdabAB']:
print(target, regex.finditer(target, pos, endpos=len(target)))
print()
regex = re.compile(r'ab', re.IGNORECASE)
print(regex)
for target in ['abcdefg', 'cdefg', 'abcdabcd', 'cdabAB']:
match = regex.finditer(target, pos, endpos=len(target))
print(target, match)
if match:
print(' match.expand():', match.expand('XY'))
print(' match.group():', match.group())
print(' match.groups():', match.groups())
print(' match.groupdict():', match.groupdict())
print(' match.start():', match.start())
print(' match.end():', match.end())
print(' match.span():', match.span())
print(' match.pos:', match.pos)
print(' match.endpos:', match.endpos)
print(' match.lastindex:', match.lastindex)
print(' match.lastgroup:', match.lastgroup)
print(' match.re:', match.re)
print(' match.string:', match.string)
| true
| true
|
790e5e0dc7393e5ba2a65abbb2a62d4cd9da9543
| 2,713
|
py
|
Python
|
squareconnect/models/v1_retrieve_business_request.py
|
shaminmeerankutty/connect-python-sdk
|
524c8fe344bc3c0340833984970a07d519c4f5be
|
[
"Apache-2.0"
] | 53
|
2016-08-06T17:12:16.000Z
|
2020-08-02T19:43:58.000Z
|
squareconnect/models/v1_retrieve_business_request.py
|
shaminmeerankutty/connect-python-sdk
|
524c8fe344bc3c0340833984970a07d519c4f5be
|
[
"Apache-2.0"
] | 32
|
2016-08-19T16:32:30.000Z
|
2020-01-14T18:01:37.000Z
|
squareconnect/models/v1_retrieve_business_request.py
|
shaminmeerankutty/connect-python-sdk
|
524c8fe344bc3c0340833984970a07d519c4f5be
|
[
"Apache-2.0"
] | 45
|
2016-09-05T11:58:09.000Z
|
2020-11-15T16:26:41.000Z
|
# coding: utf-8
"""
Copyright 2017 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from pprint import pformat
from six import iteritems
import re
class V1RetrieveBusinessRequest(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
V1RetrieveBusinessRequest - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
}
self.attribute_map = {
}
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| 28.260417
| 77
| 0.555474
|
from pprint import pformat
from six import iteritems
import re
class V1RetrieveBusinessRequest(object):
def __init__(self):
self.swagger_types = {
}
self.attribute_map = {
}
def to_dict(self):
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
return pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true
| true
|
790e5ec257778133a9ac30ca59887a817c05e144
| 14,150
|
py
|
Python
|
src/qa4sm_preprocessing/nc_image_reader/transpose.py
|
s-scherrer/qa4sm-preprocessing
|
dbb6dea8e4d34b69ee4d5f82f0a0028294d45170
|
[
"MIT"
] | null | null | null |
src/qa4sm_preprocessing/nc_image_reader/transpose.py
|
s-scherrer/qa4sm-preprocessing
|
dbb6dea8e4d34b69ee4d5f82f0a0028294d45170
|
[
"MIT"
] | 5
|
2021-07-29T11:41:24.000Z
|
2022-01-18T14:34:38.000Z
|
src/qa4sm_preprocessing/nc_image_reader/transpose.py
|
s-scherrer/qa4sm-preprocessing
|
dbb6dea8e4d34b69ee4d5f82f0a0028294d45170
|
[
"MIT"
] | 3
|
2021-07-28T13:56:05.000Z
|
2021-11-15T07:39:45.000Z
|
import copy
import dask
import dask.array as da
from dask.distributed import Client
import datetime
import logging
import math
from multiprocessing.pool import ThreadPool
import numpy as np
from pathlib import Path
from tqdm.auto import tqdm
from typing import Union, TypeVar, Tuple
import xarray as xr
import shutil
import warnings
import zarr
from .utils import infer_chunks
from .readers import DirectoryImageReader
Reader = TypeVar("Reader")
def write_transposed_dataset(
reader: Reader,
outfname: Union[Path, str],
start: datetime.datetime = None,
end: datetime.datetime = None,
chunks: dict = None,
memory: float = 2,
n_threads: int = 4,
zlib: bool = True,
complevel: int = 4,
distributed: Union[bool, Client] = False,
use_dask: bool = True,
):
"""
Creates a stacked and transposed netCDF file from a given reader.
WARNING: very experimental!
Parameters
----------
reader : XarrayImageReaderBase
Reader for the dataset.
outfname : str or Path
Output filename. Must end with ".nc" for netCDF output or with ".zarr"
for zarr output.
start : datetime.datetime, optional
If not given, start at first timestamp in dataset.
end : datetime.datetime, optional
If not given, end at last timestamp in dataset.
chunks : dictionary, optional
The chunk sizes that are used for the transposed file. If none are
given, chunks with a size of 1MB are used for netCDF, and chunks with a
size of 50MB are used for zarr output.
memory : float, optional
The amount of memory to be used for buffering in GB. Default is 2.
Higher is faster.
n_threads : int, optional
The amount of threads to use. Default is 4.
zlib : bool, optional
Whether to use compression when storing the files. Reduces file size,
but strongly increases write time, and maybe also access time. Default
is ``False``.
complevel : int, optional
Compression level to use. Default is 4. Range is from 1 (low) to 9
(high).
distributed : bool or Client, optional
Whether to use the local or the distributed dask scheduler. If a client
for a distributed scheduler is used, this is used instead.
use_dask : bool, optional
Whether to use dask for the transposing. Default is True, but sometimes
(especially with large datasets) this fails. If set to False, the data
is written to an intermediate zarr store.
"""
dask_config = {
"array.slicing.split_large_chunks": False,
}
args = (reader, outfname)
kwargs = {
"start": start,
"end": end,
"memory": memory,
"zlib": zlib,
"complevel": complevel,
"chunks": chunks,
}
if not use_dask:
_transpose_no_dask(*args, **kwargs)
elif isinstance(distributed, Client) or not distributed:
if not distributed:
dask_config.update(
{"scheduler": "threads", "pool": ThreadPool(n_threads)}
)
with dask.config.set(**dask_config):
_transpose(*args, **kwargs)
elif distributed:
with dask.config.set(**dask_config), Client(
n_workers=1,
threads_per_worker=n_threads,
memory_limit=f"{memory}GB",
) as client:
print("Dask dashboard accessible at:", client.dashboard_link)
_transpose(*args, **kwargs)
def _get_intermediate_chunks(array, chunks, new_last_dim, zarr_output, memory):
"""
Calculates chunk sizes for the given array for the intermediate output
files.
Parameters
----------
array : xr.DataArray
Array to rechunk and transpose
chunks : dict or None
Chunks passed to write_transposed_dataset, None if none were given.
new_last_dim : str
Name of the new last dimension, normally "time".
zarr_output : bool
Whether the final file will be a zarr file (True) or a netCDf (False).
memory : float
The amount of memory to be used for buffering in GB.
Returns
-------
tmp_chunks : dict
Chunks to be used for rechunking the array to a temporary file. The
order of keys corresponds to the order of dimensions in the transposed
array.
"""
dtype = array.dtype
dims = dict(zip(array.dims, array.shape))
transposed_shape = [
length for dim, length in dims.items() if dim != new_last_dim
]
transposed_shape.append(dims[new_last_dim])
# If the chunks argument was not given, we have to infer the spatial
# and temporal chunks for the intermediate file.
# The spatial chunks will be set such that for a continuous time
# dimension the chunk size is still reasonable.
if chunks is None:
if zarr_output:
chunksizes = infer_chunks(transposed_shape, 100, dtype)[:-1]
else:
chunksizes = infer_chunks(transposed_shape, 1, dtype)[:-1]
chunks = dict(
zip([dim for dim in dims if dim != new_last_dim], chunksizes)
)
chunks[new_last_dim] = -1
else:
chunks = copy.copy(chunks)
tmp_chunks = {dim: chunks[dim] for dim in dims if dim != new_last_dim}
# figure out temporary chunk sizes based on image size and available memory
size = dtype.itemsize
chunksizes = [size if size != -1 else dims[dim] for dim, size in chunks.items()]
chunksize_MB = np.prod(chunksizes) * size / 1024 ** 2
img_shape = transposed_shape[:-1]
len_time = transposed_shape[-1]
imagesize_GB = np.prod(img_shape) * size / 1024 ** 3
# we need to divide by two, because we need intermediate storage for
# the transposing
stepsize = int(math.floor(memory / imagesize_GB)) // 2
stepsize = min(stepsize, len_time)
tmp_chunks[new_last_dim] = stepsize
tmp_chunks_str = str(tuple(tmp_chunks.values()))
logging.info(
f"write_transposed_dataset: Creating chunks {tmp_chunks_str}"
f" with chunksize {chunksize_MB:.2f} MB"
)
return tmp_chunks
def _transpose(
reader: Reader,
outfname: Union[Path, str],
start: datetime.datetime = None,
end: datetime.datetime = None,
chunks: dict = None,
memory: float = 2,
zlib: bool = True,
complevel: int = 4,
):
zarr_output = str(outfname).endswith(".zarr")
new_last_dim = reader.timename
if isinstance(reader, DirectoryImageReader) and reader.chunks is None:
logging.info(
"You are using DirectoryImageReader without dask. If you run into"
" memory issues or have large datasets to transpose, consider"
" setting use_dask=True in the constructor of DirectoryImageReader."
)
ds = reader.read_block(start, end)
# We process each variable separately and store them as intermediately
# chunked temporary files. The chunk size in time dimension is inferred
# from the given memory.
variable_chunks = {}
variable_intermediate_fnames = {}
for var in reader.varnames:
tmp_outfname = str(outfname) + f".{var}.zarr"
variable_intermediate_fnames[var] = tmp_outfname
if Path(tmp_outfname).exists():
logging.info(
"Skipping generating intermediate file {tmp_outfname}"
" because it exists"
)
continue
tmp_chunks = _get_intermediate_chunks(
ds[var], chunks, new_last_dim, zarr_output, memory
)
# make sure that the time dimension will be continuous in the final
# output
chunks = copy.copy(tmp_chunks)
chunks[new_last_dim] = len(ds[var].time)
variable_chunks[var] = chunks
# now we can rechunk and transpose using xarray
rechunked_transposed = ds[var].chunk(tmp_chunks).transpose(
..., new_last_dim
)
rechunked_transposed.to_dataset().to_zarr(
tmp_outfname, consolidated=True
)
# Now we have to reassemble all variables to a single dataset and write the
# final chunks
variable_ds = []
variable_chunksizes = {}
for var in reader.varnames:
ds = xr.open_zarr(variable_intermediate_fnames[var], consolidated=True)
variable_ds.append(ds)
# for the encoding variable below we need the chunks as tuple in the
# right order, it's easier to get this here were we have easy access to
# the transposed DataArray
transposed_dims = ds[var].dims
variable_chunksizes[var] = tuple(
chunks[dim] for dim in transposed_dims
)
ds = xr.merge(
variable_ds,
compat="override",
join="override",
combine_attrs="override",
)
ds.attrs.update(reader.global_attrs)
encoding = {
var: {
"chunksizes": variable_chunksizes[var],
"zlib": zlib,
"complevel": complevel,
}
for var in reader.varnames
}
if not zarr_output:
ds.to_netcdf(outfname, encoding=encoding)
else:
for var in reader.varnames:
del ds[var].encoding["chunks"]
del ds[var].encoding["preferred_chunks"]
ds[var] = ds[var].chunk(variable_chunksizes[var])
ds.to_zarr(outfname, mode="w", consolidated=True)
for var in reader.varnames:
shutil.rmtree(variable_intermediate_fnames[var])
logging.info("write_transposed_dataset: Finished writing transposed file.")
def _transpose_no_dask(
reader: Reader,
outfname: Union[Path, str],
start: datetime.datetime = None,
end: datetime.datetime = None,
chunks: Tuple = None,
memory: float = 2,
zlib: bool = True,
complevel: int = 4,
):
warnings.warn(
"This is an experimental function and not yet ready for public use!"
)
zarr_output = str(outfname).endswith(".zarr")
new_last_dim = reader.timename
timestamps = reader.tstamps_for_daterange(start, end)
variable_fnames = {}
variable_dims = {}
for varname in reader.varnames:
tmp_outfname = str(outfname) + f".{varname}.zarr"
variable_fnames[varname] = tmp_outfname
# first, get some info about structure of the input file
first_img = reader.read_block(start=timestamps[0], end=timestamps[0])[
varname
]
tmp_chunks = _get_intermediate_chunks(
first_img, chunks, new_last_dim, zarr_output, memory
)
# get new dim names in the correct order
new_dim_names = list(tmp_chunks)
variable_dims[varname] = new_dim_names
# this happens this late because we need to set
# `variable_dims[varname]` in any case
if Path(tmp_outfname).exists():
logging.info(f"{str(tmp_outfname)} already exists, skipping.")
continue
logging.debug(
f"write_transposed_dataset: starting zarr array creation"
f" for {len(timestamps)} timestamps"
)
# get shape of transposed target array
dims = dict(zip(first_img.dims, first_img.shape))
transposed_shape = tuple(dims[dim] for dim in tmp_chunks.keys())
zarr_array = zarr.create(
tuple(new_dim_sizes),
chunks=tuple(size for size in tmp_chunks.values()),
store=tmp_outfname,
overwrite=True,
fill_value=np.nan,
)
logging.debug(f"write_transposed_dataset: Writing {tmp_outfname}")
print(f"Constructing array stack for {varname}:")
pbar = tqdm(range(0, len(timestamps), stepsize))
stepsize = tmp_chunks[new_last_dim]
for start_idx in pbar:
pbar.set_description("Reading")
end_idx = min(start_idx + stepsize - 1, len(timestamps) - 1)
block = reader.read_block(
timestamps[start_idx], timestamps[end_idx]
)[varname]
block = block.transpose(..., new_last_dim)
pbar.set_description("Writing")
zarr_array[..., start_idx : end_idx + 1] = block.values
variable_arrays = {}
encoding = {}
for varname, fname in variable_fnames.items():
logging.debug(f"Reading {str(fname)}")
arr = da.from_zarr(fname)
dims = variable_dims[varname]
metadata = reader.array_attrs[varname]
if chunks is None:
if zarr_output:
chunks = infer_chunks(new_dim_sizes, 100, dtype)
else:
# netCDF chunks should be about 1MB
chunks = infer_chunks(new_dim_sizes, 1, dtype)
encoding[varname] = {
"chunksizes": chunks,
"zlib": zlib,
"complevel": complevel,
}
chunk_dict = dict(zip(dims, chunks))
arr = xr.DataArray(data=arr, dims=dims, attrs=metadata)
arr = arr.chunk(chunk_dict)
arr.encoding = encoding[varname]
# we're writing again to a temporary file, because otherwise the
# dataset creation fails because dask sucks
# arr.to_dataset(name=varname).to_zarr(fname + ".tmp", consolidated=True)
# variable_arrays[varname] = xr.open_zarr(fname + ".tmp", consolidated=True)
variable_arrays[varname] = arr
logging.debug("Reading test image")
test_img = reader.read_block(start=timestamps[0], end=timestamps[0])[
reader.varnames[0]
]
coords = {
c: test_img.coords[c] for c in test_img.coords if c != reader.timename
}
coords[reader.timename] = timestamps
logging.debug("Creating dataset")
ds = xr.Dataset(
variable_arrays,
coords=coords,
)
ds.attrs.update(reader.global_attrs)
logging.info(
f"write_transposed_dataset: Writing combined file to {str(outfname)}"
)
if not zarr_output:
ds.to_netcdf(outfname, encoding=encoding)
else:
ds.to_zarr(outfname, mode="w", consolidated=True)
for fname in variable_fnames.values():
shutil.rmtree(fname)
logging.info("write_transposed_dataset: Finished writing transposed file.")
| 34.681373
| 84
| 0.637597
|
import copy
import dask
import dask.array as da
from dask.distributed import Client
import datetime
import logging
import math
from multiprocessing.pool import ThreadPool
import numpy as np
from pathlib import Path
from tqdm.auto import tqdm
from typing import Union, TypeVar, Tuple
import xarray as xr
import shutil
import warnings
import zarr
from .utils import infer_chunks
from .readers import DirectoryImageReader
Reader = TypeVar("Reader")
def write_transposed_dataset(
reader: Reader,
outfname: Union[Path, str],
start: datetime.datetime = None,
end: datetime.datetime = None,
chunks: dict = None,
memory: float = 2,
n_threads: int = 4,
zlib: bool = True,
complevel: int = 4,
distributed: Union[bool, Client] = False,
use_dask: bool = True,
):
dask_config = {
"array.slicing.split_large_chunks": False,
}
args = (reader, outfname)
kwargs = {
"start": start,
"end": end,
"memory": memory,
"zlib": zlib,
"complevel": complevel,
"chunks": chunks,
}
if not use_dask:
_transpose_no_dask(*args, **kwargs)
elif isinstance(distributed, Client) or not distributed:
if not distributed:
dask_config.update(
{"scheduler": "threads", "pool": ThreadPool(n_threads)}
)
with dask.config.set(**dask_config):
_transpose(*args, **kwargs)
elif distributed:
with dask.config.set(**dask_config), Client(
n_workers=1,
threads_per_worker=n_threads,
memory_limit=f"{memory}GB",
) as client:
print("Dask dashboard accessible at:", client.dashboard_link)
_transpose(*args, **kwargs)
def _get_intermediate_chunks(array, chunks, new_last_dim, zarr_output, memory):
dtype = array.dtype
dims = dict(zip(array.dims, array.shape))
transposed_shape = [
length for dim, length in dims.items() if dim != new_last_dim
]
transposed_shape.append(dims[new_last_dim])
if chunks is None:
if zarr_output:
chunksizes = infer_chunks(transposed_shape, 100, dtype)[:-1]
else:
chunksizes = infer_chunks(transposed_shape, 1, dtype)[:-1]
chunks = dict(
zip([dim for dim in dims if dim != new_last_dim], chunksizes)
)
chunks[new_last_dim] = -1
else:
chunks = copy.copy(chunks)
tmp_chunks = {dim: chunks[dim] for dim in dims if dim != new_last_dim}
size = dtype.itemsize
chunksizes = [size if size != -1 else dims[dim] for dim, size in chunks.items()]
chunksize_MB = np.prod(chunksizes) * size / 1024 ** 2
img_shape = transposed_shape[:-1]
len_time = transposed_shape[-1]
imagesize_GB = np.prod(img_shape) * size / 1024 ** 3
stepsize = int(math.floor(memory / imagesize_GB)) // 2
stepsize = min(stepsize, len_time)
tmp_chunks[new_last_dim] = stepsize
tmp_chunks_str = str(tuple(tmp_chunks.values()))
logging.info(
f"write_transposed_dataset: Creating chunks {tmp_chunks_str}"
f" with chunksize {chunksize_MB:.2f} MB"
)
return tmp_chunks
def _transpose(
reader: Reader,
outfname: Union[Path, str],
start: datetime.datetime = None,
end: datetime.datetime = None,
chunks: dict = None,
memory: float = 2,
zlib: bool = True,
complevel: int = 4,
):
zarr_output = str(outfname).endswith(".zarr")
new_last_dim = reader.timename
if isinstance(reader, DirectoryImageReader) and reader.chunks is None:
logging.info(
"You are using DirectoryImageReader without dask. If you run into"
" memory issues or have large datasets to transpose, consider"
" setting use_dask=True in the constructor of DirectoryImageReader."
)
ds = reader.read_block(start, end)
variable_chunks = {}
variable_intermediate_fnames = {}
for var in reader.varnames:
tmp_outfname = str(outfname) + f".{var}.zarr"
variable_intermediate_fnames[var] = tmp_outfname
if Path(tmp_outfname).exists():
logging.info(
"Skipping generating intermediate file {tmp_outfname}"
" because it exists"
)
continue
tmp_chunks = _get_intermediate_chunks(
ds[var], chunks, new_last_dim, zarr_output, memory
)
chunks = copy.copy(tmp_chunks)
chunks[new_last_dim] = len(ds[var].time)
variable_chunks[var] = chunks
rechunked_transposed = ds[var].chunk(tmp_chunks).transpose(
..., new_last_dim
)
rechunked_transposed.to_dataset().to_zarr(
tmp_outfname, consolidated=True
)
variable_ds = []
variable_chunksizes = {}
for var in reader.varnames:
ds = xr.open_zarr(variable_intermediate_fnames[var], consolidated=True)
variable_ds.append(ds)
# the transposed DataArray
transposed_dims = ds[var].dims
variable_chunksizes[var] = tuple(
chunks[dim] for dim in transposed_dims
)
ds = xr.merge(
variable_ds,
compat="override",
join="override",
combine_attrs="override",
)
ds.attrs.update(reader.global_attrs)
encoding = {
var: {
"chunksizes": variable_chunksizes[var],
"zlib": zlib,
"complevel": complevel,
}
for var in reader.varnames
}
if not zarr_output:
ds.to_netcdf(outfname, encoding=encoding)
else:
for var in reader.varnames:
del ds[var].encoding["chunks"]
del ds[var].encoding["preferred_chunks"]
ds[var] = ds[var].chunk(variable_chunksizes[var])
ds.to_zarr(outfname, mode="w", consolidated=True)
for var in reader.varnames:
shutil.rmtree(variable_intermediate_fnames[var])
logging.info("write_transposed_dataset: Finished writing transposed file.")
def _transpose_no_dask(
reader: Reader,
outfname: Union[Path, str],
start: datetime.datetime = None,
end: datetime.datetime = None,
chunks: Tuple = None,
memory: float = 2,
zlib: bool = True,
complevel: int = 4,
):
warnings.warn(
"This is an experimental function and not yet ready for public use!"
)
zarr_output = str(outfname).endswith(".zarr")
new_last_dim = reader.timename
timestamps = reader.tstamps_for_daterange(start, end)
variable_fnames = {}
variable_dims = {}
for varname in reader.varnames:
tmp_outfname = str(outfname) + f".{varname}.zarr"
variable_fnames[varname] = tmp_outfname
# first, get some info about structure of the input file
first_img = reader.read_block(start=timestamps[0], end=timestamps[0])[
varname
]
tmp_chunks = _get_intermediate_chunks(
first_img, chunks, new_last_dim, zarr_output, memory
)
# get new dim names in the correct order
new_dim_names = list(tmp_chunks)
variable_dims[varname] = new_dim_names
# this happens this late because we need to set
# `variable_dims[varname]` in any case
if Path(tmp_outfname).exists():
logging.info(f"{str(tmp_outfname)} already exists, skipping.")
continue
logging.debug(
f"write_transposed_dataset: starting zarr array creation"
f" for {len(timestamps)} timestamps"
)
# get shape of transposed target array
dims = dict(zip(first_img.dims, first_img.shape))
transposed_shape = tuple(dims[dim] for dim in tmp_chunks.keys())
zarr_array = zarr.create(
tuple(new_dim_sizes),
chunks=tuple(size for size in tmp_chunks.values()),
store=tmp_outfname,
overwrite=True,
fill_value=np.nan,
)
logging.debug(f"write_transposed_dataset: Writing {tmp_outfname}")
print(f"Constructing array stack for {varname}:")
pbar = tqdm(range(0, len(timestamps), stepsize))
stepsize = tmp_chunks[new_last_dim]
for start_idx in pbar:
pbar.set_description("Reading")
end_idx = min(start_idx + stepsize - 1, len(timestamps) - 1)
block = reader.read_block(
timestamps[start_idx], timestamps[end_idx]
)[varname]
block = block.transpose(..., new_last_dim)
pbar.set_description("Writing")
zarr_array[..., start_idx : end_idx + 1] = block.values
variable_arrays = {}
encoding = {}
for varname, fname in variable_fnames.items():
logging.debug(f"Reading {str(fname)}")
arr = da.from_zarr(fname)
dims = variable_dims[varname]
metadata = reader.array_attrs[varname]
if chunks is None:
if zarr_output:
chunks = infer_chunks(new_dim_sizes, 100, dtype)
else:
# netCDF chunks should be about 1MB
chunks = infer_chunks(new_dim_sizes, 1, dtype)
encoding[varname] = {
"chunksizes": chunks,
"zlib": zlib,
"complevel": complevel,
}
chunk_dict = dict(zip(dims, chunks))
arr = xr.DataArray(data=arr, dims=dims, attrs=metadata)
arr = arr.chunk(chunk_dict)
arr.encoding = encoding[varname]
# we're writing again to a temporary file, because otherwise the
variable_arrays[varname] = arr
logging.debug("Reading test image")
test_img = reader.read_block(start=timestamps[0], end=timestamps[0])[
reader.varnames[0]
]
coords = {
c: test_img.coords[c] for c in test_img.coords if c != reader.timename
}
coords[reader.timename] = timestamps
logging.debug("Creating dataset")
ds = xr.Dataset(
variable_arrays,
coords=coords,
)
ds.attrs.update(reader.global_attrs)
logging.info(
f"write_transposed_dataset: Writing combined file to {str(outfname)}"
)
if not zarr_output:
ds.to_netcdf(outfname, encoding=encoding)
else:
ds.to_zarr(outfname, mode="w", consolidated=True)
for fname in variable_fnames.values():
shutil.rmtree(fname)
logging.info("write_transposed_dataset: Finished writing transposed file.")
| true
| true
|
790e5ec333865c7a8b4e9f1508d99ef7ab507008
| 205
|
py
|
Python
|
maxixe/decorators.py
|
tswicegood/maxixe
|
680fc8e92bf34e5b825ee0685659e40e992b0328
|
[
"Apache-2.0"
] | 1
|
2020-07-09T04:30:52.000Z
|
2020-07-09T04:30:52.000Z
|
maxixe/decorators.py
|
tswicegood/maxixe
|
680fc8e92bf34e5b825ee0685659e40e992b0328
|
[
"Apache-2.0"
] | null | null | null |
maxixe/decorators.py
|
tswicegood/maxixe
|
680fc8e92bf34e5b825ee0685659e40e992b0328
|
[
"Apache-2.0"
] | null | null | null |
from . import registry
def step(match):
def outer(func):
registry.add(match, func)
def inner(*args, **kwargs):
func(*args, **kwargs)
return inner
return outer
| 18.636364
| 35
| 0.565854
|
from . import registry
def step(match):
def outer(func):
registry.add(match, func)
def inner(*args, **kwargs):
func(*args, **kwargs)
return inner
return outer
| true
| true
|
790e5ec55cf44098cc2983ef4a97e0c2dde08281
| 14,466
|
py
|
Python
|
processlib/activity.py
|
RaphaelKimmig/processlib
|
3eb5a3c9e2999e782b5a740bd5747d62a1c35077
|
[
"BSD-3-Clause"
] | 1
|
2020-07-14T10:42:55.000Z
|
2020-07-14T10:42:55.000Z
|
processlib/activity.py
|
RaphaelKimmig/processlib
|
3eb5a3c9e2999e782b5a740bd5747d62a1c35077
|
[
"BSD-3-Clause"
] | 2
|
2019-07-12T14:22:11.000Z
|
2019-07-30T07:27:20.000Z
|
processlib/activity.py
|
RaphaelKimmig/processlib
|
3eb5a3c9e2999e782b5a740bd5747d62a1c35077
|
[
"BSD-3-Clause"
] | 2
|
2018-08-22T11:09:06.000Z
|
2019-07-12T14:16:00.000Z
|
import django
import six
from django.http import HttpResponseRedirect
if django.VERSION[0] < 2:
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
from django.db import transaction
from django.utils import timezone
import logging
from processlib.assignment import inherit
from processlib.tasks import run_async_activity
logger = logging.getLogger(__name__)
@six.python_2_unicode_compatible
class Activity(object):
def __init__(
self,
flow,
process,
instance,
name,
verbose_name=None,
permission=None,
auto_create_permission=True,
permission_name=None,
skip_if=None,
assign_to=inherit,
):
self.flow = flow
self.process = process
self.verbose_name = verbose_name
self.permission = permission
self.auto_create_permission = auto_create_permission
self.permission_name = permission_name or verbose_name or name
self.name = name
self.instance = instance
# ensure that we have a single referenced process object
if self.instance:
self.instance.process = self.process
self._skip = skip_if
self._get_assignment = assign_to
def should_skip(self):
if not self._skip:
return False
return self._skip(self)
def should_wait(self):
return False
def has_view(self):
return False
def __str__(self):
return six.text_type(self.verbose_name or self.name)
def __repr__(self):
return '{}(name="{}")'.format(self.__class__.__name__, self.name)
def instantiate(
self, predecessor=None, instance_kwargs=None, request=None, **kwargs
):
assert not self.instance
instance_kwargs = instance_kwargs or {}
request_user = (
request.user if request and request.user.is_authenticated else None
)
user, group = self._get_assignment(
request_user=request_user, predecessor=predecessor
)
if "assigned_user" not in instance_kwargs:
instance_kwargs["assigned_user"] = user
if "assigned_group" not in instance_kwargs:
instance_kwargs["assigned_group"] = group
self.instance = self.flow.activity_model(
process=self.process, activity_name=self.name, **(instance_kwargs or {})
)
self.instance.save()
if predecessor:
self.instance.predecessors.add(predecessor.instance)
def assign_to(self, user, group):
self.instance.assigned_user = user
self.instance.assigned_group = group
self.instance.save()
def start(self, **kwargs):
assert self.instance.status in (
self.instance.STATUS_INSTANTIATED,
self.instance.STATUS_SCHEDULED,
)
if not self.instance.started_at:
self.instance.started_at = timezone.now()
self.instance.status = self.instance.STATUS_STARTED
def finish(self, **kwargs):
assert self.instance.status == self.instance.STATUS_STARTED
if not self.instance.finished_at:
self.instance.finished_at = timezone.now()
self.instance.status = self.instance.STATUS_DONE
self.instance.modified_by = kwargs.get("user", None)
self.instance.save()
self._instantiate_next_activities()
def cancel(self, **kwargs):
assert self.instance.status in (
self.instance.STATUS_INSTANTIATED,
self.instance.STATUS_ERROR,
)
self.instance.status = self.instance.STATUS_CANCELED
self.instance.modified_by = kwargs.get("user", None)
self.instance.save()
def undo(self, **kwargs):
assert self.instance.status == self.instance.STATUS_DONE
self.instance.finished_at = None
self.instance.status = self.instance.STATUS_INSTANTIATED
self.instance.modified_by = kwargs.get("user", None)
self.instance.save()
undo_callback = getattr(self.process, "undo_{}".format(self.name), None)
if undo_callback is not None:
undo_callback()
def error(self, **kwargs):
assert self.instance.status != self.instance.STATUS_DONE
self.instance.status = self.instance.STATUS_ERROR
self.instance.finished_at = timezone.now()
self.instance.modified_by = kwargs.get("user", None)
self.instance.save()
def _get_next_activities(self):
for activity_name in self.flow._out_edges[self.name]:
activity = self.flow._get_activity_by_name(
process=self.process, activity_name=activity_name
)
if activity.should_skip():
for later_activity in activity._get_next_activities():
yield later_activity
else:
yield activity
def _instantiate_next_activities(self):
for activity in self._get_next_activities():
activity.instantiate(predecessor=self)
class State(Activity):
"""
An activity that simple serves as a marker for a certain state being reached, e.g.
if the activity before it was conditional.
"""
def instantiate(self, **kwargs):
super(State, self).instantiate(**kwargs)
self.start()
self.finish()
class ViewActivity(Activity):
def __init__(self, view=None, **kwargs):
super(ViewActivity, self).__init__(**kwargs)
if view is None:
raise ValueError(
"A ViewActivity requires a view, non given for {}.{}".format(
self.flow.label, self.name
)
)
self.view = view
def has_view(self):
return True
def get_absolute_url(self):
return reverse(
"processlib:process-activity",
kwargs={"flow_label": self.flow.label, "activity_id": self.instance.pk},
)
def dispatch(self, request, *args, **kwargs):
kwargs["activity"] = self
return self.view(request, *args, **kwargs)
class FunctionActivity(Activity):
def __init__(self, callback=None, **kwargs):
self.callback = callback
super(FunctionActivity, self).__init__(**kwargs)
def instantiate(self, **kwargs):
super(FunctionActivity, self).instantiate(**kwargs)
self.start()
def start(self, **kwargs):
super(FunctionActivity, self).start(**kwargs)
try:
self.callback(self)
except Exception as e:
logger.exception(e)
self.error(exception=e)
return
self.finish()
def retry(self):
assert self.instance.status == self.instance.STATUS_ERROR
self.instance.status = self.instance.STATUS_INSTANTIATED
self.instance.finished_at = None
self.instance.save()
self.start()
class AsyncActivity(Activity):
def __init__(self, callback=None, **kwargs):
self.callback = callback
super(AsyncActivity, self).__init__(**kwargs)
def instantiate(self, **kwargs):
super(AsyncActivity, self).instantiate(**kwargs)
self.schedule()
def schedule(self, **kwargs):
self.instance.status = self.instance.STATUS_SCHEDULED
self.instance.scheduled_at = timezone.now()
self.instance.save()
transaction.on_commit(
lambda: run_async_activity.delay(self.flow.label, self.instance.pk)
)
def retry(self, **kwargs):
assert self.instance.status == self.instance.STATUS_ERROR
self.instance.status = self.instance.STATUS_INSTANTIATED
self.instance.finished_at = None
self.schedule(**kwargs)
def start(self, **kwargs):
super(AsyncActivity, self).start(**kwargs)
self.callback(self)
class AsyncViewActivity(AsyncActivity):
"""
An async activity that renders a view while the async task is running.
The view could be AsyncActivityView with a custom template_name
"""
def __init__(self, view=None, **kwargs):
super(AsyncViewActivity, self).__init__(**kwargs)
if view is None:
raise ValueError(
"An AsyncViewActivity requires a view, non given for {}.{}".format(
self.flow.label, self.name
)
)
self.view = view
def has_view(self):
return True
def get_absolute_url(self):
return reverse(
"processlib:process-activity",
kwargs={"flow_label": self.flow.label, "activity_id": self.instance.pk},
)
def dispatch(self, request, *args, **kwargs):
kwargs["activity"] = self
return self.view(request, *args, **kwargs)
class StartMixin(Activity):
def instantiate(
self, predecessor=None, instance_kwargs=None, request=None, **kwargs
):
assert not self.instance
assert not predecessor
instance_kwargs = instance_kwargs or {}
request_user = (
request.user if request and request.user.is_authenticated else None
)
user, group = self._get_assignment(
request_user=request_user, predecessor=predecessor
)
if "assigned_user" not in instance_kwargs:
instance_kwargs["assigned_user"] = user
if "assigned_group" not in instance_kwargs:
instance_kwargs["assigned_group"] = group
self.instance = self.flow.activity_model(
process=self.process, activity_name=self.name, **(instance_kwargs or {})
)
def finish(self, **kwargs):
assert self.instance.status == self.instance.STATUS_STARTED
if not self.instance.finished_at:
self.instance.finished_at = timezone.now()
self.process.save()
self.instance.process = self.process
self.instance.status = self.instance.STATUS_DONE
self.instance.modified_by = kwargs.get("user", None)
self.instance.save()
self._instantiate_next_activities()
class StartActivity(StartMixin, Activity):
pass
class StartViewActivity(StartMixin, ViewActivity):
pass
class EndActivity(Activity):
def instantiate(self, **kwargs):
super(EndActivity, self).instantiate(**kwargs)
self.start()
self.finish()
def finish(self, **kwargs):
super(EndActivity, self).finish(**kwargs)
update_fields = []
if not self.process.finished_at:
self.process.finished_at = self.instance.finished_at
update_fields.append("finished_at")
if not self.process.status == self.process.STATUS_DONE:
self.process.status = self.process.STATUS_DONE
update_fields.append("status")
self.process.save(update_fields=update_fields)
class EndRedirectActivity(EndActivity):
def __init__(self, redirect_url_callback=None, **kwargs):
self.redirect_url_callback = redirect_url_callback
super(EndActivity, self).__init__(**kwargs)
def instantiate(self, **kwargs):
# HACK: we skip the EndActivity implementation
# because it would finish the activity right away
super(EndActivity, self).instantiate(**kwargs)
def has_view(self):
return True
def get_absolute_url(self):
return reverse(
"processlib:process-activity",
kwargs={"flow_label": self.flow.label, "activity_id": self.instance.pk},
)
def dispatch(self, request, *args, **kwargs):
self.start()
url = reverse(
"processlib:process-detail", kwargs={"pk": self.instance.process.pk}
)
try:
if self.redirect_url_callback:
url = self.redirect_url_callback(self)
self.finish()
except Exception as e:
logger.exception(e)
self.error(exception=e)
return HttpResponseRedirect(url)
class FormActivity(Activity):
def __init__(self, form_class=None, **kwargs):
self.form_class = form_class
super(FormActivity, self).__init__(**kwargs)
def get_form(self, **kwargs):
return self.form_class(**kwargs)
class StartFormActivity(StartMixin, FormActivity):
pass
class IfElse(Activity):
def __init__(self, flow, process, instance, name, **kwargs):
super(IfElse, self).__init__(flow, process, instance, name, **kwargs)
class Wait(Activity):
def __init__(self, flow, process, instance, name, **kwargs):
wait_for = kwargs.pop("wait_for", None)
if not wait_for:
raise ValueError("Wait activity needs to wait for something.")
super(Wait, self).__init__(flow, process, instance, name, **kwargs)
self._wait_for = set(wait_for) if wait_for else None
def _find_existing_instance(self, predecessor):
candidates = list(
self.flow.activity_model.objects.filter(
process=self.process, activity_name=self.name
)
)
for candidate in candidates:
# FIXME this only corrects for simple loops, may fail with more complex scenarios
if not candidate.successors.filter(
status=candidate.STATUS_DONE, activity_name=self.name
).exists():
return candidate
raise self.flow.activity_model.DoesNotExist()
def instantiate(self, predecessor=None, instance_kwargs=None, **kwargs):
if predecessor is None:
raise ValueError("Can't wait for something without a predecessor.")
# find the instance
try:
self.instance = self._find_existing_instance(predecessor)
except self.flow.activity_model.DoesNotExist:
self.instance = self.flow.activity_model(
process=self.process, activity_name=self.name, **(instance_kwargs or {})
)
self.instance.save()
self.instance.predecessors.add(predecessor.instance)
self.start()
def start(self, **kwargs):
if not self.instance.started_at:
self.instance.started_at = timezone.now()
self.instance.status = self.instance.STATUS_STARTED
self.instance.save()
predecessor_names = {
instance.activity_name for instance in self.instance.predecessors.all()
}
if self._wait_for.issubset(predecessor_names):
self.finish()
| 31.793407
| 93
| 0.635144
|
import django
import six
from django.http import HttpResponseRedirect
if django.VERSION[0] < 2:
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
from django.db import transaction
from django.utils import timezone
import logging
from processlib.assignment import inherit
from processlib.tasks import run_async_activity
logger = logging.getLogger(__name__)
@six.python_2_unicode_compatible
class Activity(object):
def __init__(
self,
flow,
process,
instance,
name,
verbose_name=None,
permission=None,
auto_create_permission=True,
permission_name=None,
skip_if=None,
assign_to=inherit,
):
self.flow = flow
self.process = process
self.verbose_name = verbose_name
self.permission = permission
self.auto_create_permission = auto_create_permission
self.permission_name = permission_name or verbose_name or name
self.name = name
self.instance = instance
if self.instance:
self.instance.process = self.process
self._skip = skip_if
self._get_assignment = assign_to
def should_skip(self):
if not self._skip:
return False
return self._skip(self)
def should_wait(self):
return False
def has_view(self):
return False
def __str__(self):
return six.text_type(self.verbose_name or self.name)
def __repr__(self):
return '{}(name="{}")'.format(self.__class__.__name__, self.name)
def instantiate(
self, predecessor=None, instance_kwargs=None, request=None, **kwargs
):
assert not self.instance
instance_kwargs = instance_kwargs or {}
request_user = (
request.user if request and request.user.is_authenticated else None
)
user, group = self._get_assignment(
request_user=request_user, predecessor=predecessor
)
if "assigned_user" not in instance_kwargs:
instance_kwargs["assigned_user"] = user
if "assigned_group" not in instance_kwargs:
instance_kwargs["assigned_group"] = group
self.instance = self.flow.activity_model(
process=self.process, activity_name=self.name, **(instance_kwargs or {})
)
self.instance.save()
if predecessor:
self.instance.predecessors.add(predecessor.instance)
def assign_to(self, user, group):
self.instance.assigned_user = user
self.instance.assigned_group = group
self.instance.save()
def start(self, **kwargs):
assert self.instance.status in (
self.instance.STATUS_INSTANTIATED,
self.instance.STATUS_SCHEDULED,
)
if not self.instance.started_at:
self.instance.started_at = timezone.now()
self.instance.status = self.instance.STATUS_STARTED
def finish(self, **kwargs):
assert self.instance.status == self.instance.STATUS_STARTED
if not self.instance.finished_at:
self.instance.finished_at = timezone.now()
self.instance.status = self.instance.STATUS_DONE
self.instance.modified_by = kwargs.get("user", None)
self.instance.save()
self._instantiate_next_activities()
def cancel(self, **kwargs):
assert self.instance.status in (
self.instance.STATUS_INSTANTIATED,
self.instance.STATUS_ERROR,
)
self.instance.status = self.instance.STATUS_CANCELED
self.instance.modified_by = kwargs.get("user", None)
self.instance.save()
def undo(self, **kwargs):
assert self.instance.status == self.instance.STATUS_DONE
self.instance.finished_at = None
self.instance.status = self.instance.STATUS_INSTANTIATED
self.instance.modified_by = kwargs.get("user", None)
self.instance.save()
undo_callback = getattr(self.process, "undo_{}".format(self.name), None)
if undo_callback is not None:
undo_callback()
def error(self, **kwargs):
assert self.instance.status != self.instance.STATUS_DONE
self.instance.status = self.instance.STATUS_ERROR
self.instance.finished_at = timezone.now()
self.instance.modified_by = kwargs.get("user", None)
self.instance.save()
def _get_next_activities(self):
for activity_name in self.flow._out_edges[self.name]:
activity = self.flow._get_activity_by_name(
process=self.process, activity_name=activity_name
)
if activity.should_skip():
for later_activity in activity._get_next_activities():
yield later_activity
else:
yield activity
def _instantiate_next_activities(self):
for activity in self._get_next_activities():
activity.instantiate(predecessor=self)
class State(Activity):
def instantiate(self, **kwargs):
super(State, self).instantiate(**kwargs)
self.start()
self.finish()
class ViewActivity(Activity):
def __init__(self, view=None, **kwargs):
super(ViewActivity, self).__init__(**kwargs)
if view is None:
raise ValueError(
"A ViewActivity requires a view, non given for {}.{}".format(
self.flow.label, self.name
)
)
self.view = view
def has_view(self):
return True
def get_absolute_url(self):
return reverse(
"processlib:process-activity",
kwargs={"flow_label": self.flow.label, "activity_id": self.instance.pk},
)
def dispatch(self, request, *args, **kwargs):
kwargs["activity"] = self
return self.view(request, *args, **kwargs)
class FunctionActivity(Activity):
def __init__(self, callback=None, **kwargs):
self.callback = callback
super(FunctionActivity, self).__init__(**kwargs)
def instantiate(self, **kwargs):
super(FunctionActivity, self).instantiate(**kwargs)
self.start()
def start(self, **kwargs):
super(FunctionActivity, self).start(**kwargs)
try:
self.callback(self)
except Exception as e:
logger.exception(e)
self.error(exception=e)
return
self.finish()
def retry(self):
assert self.instance.status == self.instance.STATUS_ERROR
self.instance.status = self.instance.STATUS_INSTANTIATED
self.instance.finished_at = None
self.instance.save()
self.start()
class AsyncActivity(Activity):
def __init__(self, callback=None, **kwargs):
self.callback = callback
super(AsyncActivity, self).__init__(**kwargs)
def instantiate(self, **kwargs):
super(AsyncActivity, self).instantiate(**kwargs)
self.schedule()
def schedule(self, **kwargs):
self.instance.status = self.instance.STATUS_SCHEDULED
self.instance.scheduled_at = timezone.now()
self.instance.save()
transaction.on_commit(
lambda: run_async_activity.delay(self.flow.label, self.instance.pk)
)
def retry(self, **kwargs):
assert self.instance.status == self.instance.STATUS_ERROR
self.instance.status = self.instance.STATUS_INSTANTIATED
self.instance.finished_at = None
self.schedule(**kwargs)
def start(self, **kwargs):
super(AsyncActivity, self).start(**kwargs)
self.callback(self)
class AsyncViewActivity(AsyncActivity):
def __init__(self, view=None, **kwargs):
super(AsyncViewActivity, self).__init__(**kwargs)
if view is None:
raise ValueError(
"An AsyncViewActivity requires a view, non given for {}.{}".format(
self.flow.label, self.name
)
)
self.view = view
def has_view(self):
return True
def get_absolute_url(self):
return reverse(
"processlib:process-activity",
kwargs={"flow_label": self.flow.label, "activity_id": self.instance.pk},
)
def dispatch(self, request, *args, **kwargs):
kwargs["activity"] = self
return self.view(request, *args, **kwargs)
class StartMixin(Activity):
def instantiate(
self, predecessor=None, instance_kwargs=None, request=None, **kwargs
):
assert not self.instance
assert not predecessor
instance_kwargs = instance_kwargs or {}
request_user = (
request.user if request and request.user.is_authenticated else None
)
user, group = self._get_assignment(
request_user=request_user, predecessor=predecessor
)
if "assigned_user" not in instance_kwargs:
instance_kwargs["assigned_user"] = user
if "assigned_group" not in instance_kwargs:
instance_kwargs["assigned_group"] = group
self.instance = self.flow.activity_model(
process=self.process, activity_name=self.name, **(instance_kwargs or {})
)
def finish(self, **kwargs):
assert self.instance.status == self.instance.STATUS_STARTED
if not self.instance.finished_at:
self.instance.finished_at = timezone.now()
self.process.save()
self.instance.process = self.process
self.instance.status = self.instance.STATUS_DONE
self.instance.modified_by = kwargs.get("user", None)
self.instance.save()
self._instantiate_next_activities()
class StartActivity(StartMixin, Activity):
pass
class StartViewActivity(StartMixin, ViewActivity):
pass
class EndActivity(Activity):
def instantiate(self, **kwargs):
super(EndActivity, self).instantiate(**kwargs)
self.start()
self.finish()
def finish(self, **kwargs):
super(EndActivity, self).finish(**kwargs)
update_fields = []
if not self.process.finished_at:
self.process.finished_at = self.instance.finished_at
update_fields.append("finished_at")
if not self.process.status == self.process.STATUS_DONE:
self.process.status = self.process.STATUS_DONE
update_fields.append("status")
self.process.save(update_fields=update_fields)
class EndRedirectActivity(EndActivity):
def __init__(self, redirect_url_callback=None, **kwargs):
self.redirect_url_callback = redirect_url_callback
super(EndActivity, self).__init__(**kwargs)
def instantiate(self, **kwargs):
super(EndActivity, self).instantiate(**kwargs)
def has_view(self):
return True
def get_absolute_url(self):
return reverse(
"processlib:process-activity",
kwargs={"flow_label": self.flow.label, "activity_id": self.instance.pk},
)
def dispatch(self, request, *args, **kwargs):
self.start()
url = reverse(
"processlib:process-detail", kwargs={"pk": self.instance.process.pk}
)
try:
if self.redirect_url_callback:
url = self.redirect_url_callback(self)
self.finish()
except Exception as e:
logger.exception(e)
self.error(exception=e)
return HttpResponseRedirect(url)
class FormActivity(Activity):
def __init__(self, form_class=None, **kwargs):
self.form_class = form_class
super(FormActivity, self).__init__(**kwargs)
def get_form(self, **kwargs):
return self.form_class(**kwargs)
class StartFormActivity(StartMixin, FormActivity):
pass
class IfElse(Activity):
def __init__(self, flow, process, instance, name, **kwargs):
super(IfElse, self).__init__(flow, process, instance, name, **kwargs)
class Wait(Activity):
def __init__(self, flow, process, instance, name, **kwargs):
wait_for = kwargs.pop("wait_for", None)
if not wait_for:
raise ValueError("Wait activity needs to wait for something.")
super(Wait, self).__init__(flow, process, instance, name, **kwargs)
self._wait_for = set(wait_for) if wait_for else None
def _find_existing_instance(self, predecessor):
candidates = list(
self.flow.activity_model.objects.filter(
process=self.process, activity_name=self.name
)
)
for candidate in candidates:
if not candidate.successors.filter(
status=candidate.STATUS_DONE, activity_name=self.name
).exists():
return candidate
raise self.flow.activity_model.DoesNotExist()
def instantiate(self, predecessor=None, instance_kwargs=None, **kwargs):
if predecessor is None:
raise ValueError("Can't wait for something without a predecessor.")
# find the instance
try:
self.instance = self._find_existing_instance(predecessor)
except self.flow.activity_model.DoesNotExist:
self.instance = self.flow.activity_model(
process=self.process, activity_name=self.name, **(instance_kwargs or {})
)
self.instance.save()
self.instance.predecessors.add(predecessor.instance)
self.start()
def start(self, **kwargs):
if not self.instance.started_at:
self.instance.started_at = timezone.now()
self.instance.status = self.instance.STATUS_STARTED
self.instance.save()
predecessor_names = {
instance.activity_name for instance in self.instance.predecessors.all()
}
if self._wait_for.issubset(predecessor_names):
self.finish()
| true
| true
|
790e5f1b0df53c72c03c75628c8a50d0925777d6
| 251
|
py
|
Python
|
src/components/api/wrappers/test.py
|
ghsecuritylab/comanche
|
a8862eaed59045377874b95b120832a0cba42193
|
[
"Apache-2.0"
] | 19
|
2017-10-03T16:01:49.000Z
|
2021-06-07T10:21:46.000Z
|
src/components/api/wrappers/test.py
|
dnbaker/comanche
|
121cd0fa16e55d461b366e83511d3810ea2b11c9
|
[
"Apache-2.0"
] | 25
|
2018-02-21T23:43:03.000Z
|
2020-09-02T08:47:32.000Z
|
src/components/api/wrappers/test.py
|
dnbaker/comanche
|
121cd0fa16e55d461b366e83511d3810ea2b11c9
|
[
"Apache-2.0"
] | 19
|
2017-10-24T17:41:40.000Z
|
2022-02-22T02:17:18.000Z
|
#!/usr/bin/python -i
import Block
import rlcompleter, readline
readline.parse_and_bind("tab: complete")
device = Block.Block("86:00.0",2,"libcomanche-blknvme.so")
buffer = device.allocate_io_buffer(4096,32,-1)
info = device.get_volume_info()
info
| 19.307692
| 58
| 0.756972
|
import Block
import rlcompleter, readline
readline.parse_and_bind("tab: complete")
device = Block.Block("86:00.0",2,"libcomanche-blknvme.so")
buffer = device.allocate_io_buffer(4096,32,-1)
info = device.get_volume_info()
info
| true
| true
|
790e5fde9f6d2a34f208992d40c79984032e5703
| 6,715
|
py
|
Python
|
python/cuml/dask/preprocessing/label.py
|
codereport/cuml
|
7225fadb72ef5408af58ab16ce062762b64f2c79
|
[
"Apache-2.0"
] | null | null | null |
python/cuml/dask/preprocessing/label.py
|
codereport/cuml
|
7225fadb72ef5408af58ab16ce062762b64f2c79
|
[
"Apache-2.0"
] | null | null | null |
python/cuml/dask/preprocessing/label.py
|
codereport/cuml
|
7225fadb72ef5408af58ab16ce062762b64f2c79
|
[
"Apache-2.0"
] | null | null | null |
# Copyright (c) 2020, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from cuml.preprocessing.label import LabelBinarizer as LB
from dask.distributed import default_client
from cuml.dask.common.input_utils import _extract_partitions
from cuml.common import rmm_cupy_ary
import dask
import cupy as cp
class LabelBinarizer(object):
"""
A distributed version of LabelBinarizer for one-hot encoding
a collection of labels.
Examples
--------
Examples
--------
Create an array with labels and dummy encode them
.. code-block:: python
import cupy as cp
from cuml.dask.preprocessing import LabelBinarizer
from dask_cuda import LocalCUDACluster
from dask.distributed import Client
import dask
cluster = LocalCUDACluster()
client = Client(cluster)
labels = cp.asarray([0, 5, 10, 7, 2, 4, 1, 0, 0, 4, 3, 2, 1],
dtype=cp.int32)
labels = dask.array.from_array(labels)
lb = LabelBinarizer()
encoded = lb.fit_transform(labels)
print(str(encoded.compute())
decoded = lb.inverse_transform(encoded)
print(str(decoded.compute())
Output:
.. code-block::
[[1 0 0 0 0 0 0 0]
[0 0 0 0 0 1 0 0]
[0 0 0 0 0 0 0 1]
[0 0 0 0 0 0 1 0]
[0 0 1 0 0 0 0 0]
[0 0 0 0 1 0 0 0]
[0 1 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0]
[0 0 0 0 1 0 0 0]
[0 0 0 1 0 0 0 0]
[0 0 1 0 0 0 0 0]
[0 1 0 0 0 0 0 0]]
[ 0 5 10 7 2 4 1 0 0 4 3 2 1]
"""
def __init__(self, client=None, **kwargs):
"""
Initialize new LabelBinarizer instance
Parameters
----------
client : dask.Client optional client to use
kwargs : dict of arguments to proxy to underlying single-process
LabelBinarizer
"""
self.client_ = client if client is not None else default_client()
self.kwargs = kwargs
# Sparse output will be added once sparse CuPy arrays are supported
# by Dask.Array: https://github.com/rapidsai/cuml/issues/1665
if "sparse_output" in self.kwargs and \
self.kwargs["sparse_output"] is True:
raise ValueError("Sparse output not yet "
"supported in distributed mode")
@staticmethod
def _func_create_model(**kwargs):
return LB(**kwargs)
@staticmethod
def _func_unique_classes(y):
return rmm_cupy_ary(cp.unique, y)
@staticmethod
def _func_xform(model, y):
xform_in = rmm_cupy_ary(cp.asarray, y, dtype=y.dtype)
return model.transform(xform_in)
@staticmethod
def _func_inv_xform(model, y, threshold):
y = rmm_cupy_ary(cp.asarray, y, dtype=y.dtype)
return model.inverse_transform(y, threshold)
def fit(self, y):
"""Fit label binarizer
Parameters
----------
y : Dask.Array of shape [n_samples,] or [n_samples, n_classes]
chunked by row.
Target values. The 2-d matrix should only contain 0 and 1,
represents multilabel classification.
Returns
-------
self : returns an instance of self.
"""
# Take the unique classes and broadcast them all around the cluster.
futures = self.client_.sync(_extract_partitions, y)
unique = [self.client_.submit(LabelBinarizer._func_unique_classes, f)
for w, f in futures]
classes = self.client_.compute(unique, True)
self.classes_ = rmm_cupy_ary(cp.unique,
rmm_cupy_ary(cp.stack,
classes,
axis=0))
self.model = LB(**self.kwargs).fit(self.classes_)
return self
def fit_transform(self, y):
"""
Fit the label encoder and return transformed labels
Parameters
----------
y : Dask.Array of shape [n_samples,] or [n_samples, n_classes]
target values. The 2-d matrix should only contain 0 and 1,
represents multilabel classification.
Returns
-------
arr : Dask.Array backed by CuPy arrays containing encoded labels
"""
return self.fit(y).transform(y)
def transform(self, y):
"""
Transform and return encoded labels
Parameters
----------
y : Dask.Array of shape [n_samples,] or [n_samples, n_classes]
Returns
-------
arr : Dask.Array backed by CuPy arrays containing encoded labels
"""
parts = self.client_.sync(_extract_partitions, y)
xform_func = dask.delayed(LabelBinarizer._func_xform)
meta = rmm_cupy_ary(cp.zeros, 1)
if self.model.sparse_output:
meta = cp.sparse.csr_matrix(meta)
f = [dask.array.from_delayed(xform_func(self.model, part),
meta=meta, dtype=cp.float32,
shape=(len(y), len(self.classes_))) for w, part in parts]
arr = dask.array.asarray(f)
return arr.reshape(arr.shape[1:])
def inverse_transform(self, y, threshold=None):
"""
Invert a set of encoded labels back to original labels
Parameters
----------
y : Dask.Array of shape [n_samples, n_classes] containing encoded
labels
threshold : float This value is currently ignored
Returns
-------
arr : Dask.Array backed by CuPy arrays containing original labels
"""
parts = self.client_.sync(_extract_partitions, y)
inv_func = dask.delayed(LabelBinarizer._func_inv_xform)
dtype = self.classes_.dtype
meta = rmm_cupy_ary(cp.zeros, 1, dtype=dtype)
f = [dask.array.from_delayed(
inv_func(self.model, part, threshold),
dtype=dtype, shape=(y.shape[0],), meta=meta)
for w, part in parts]
ret = dask.array.stack(f, axis=0)
return ret.reshape(ret.shape[1:])
| 28.696581
| 77
| 0.586746
|
from cuml.preprocessing.label import LabelBinarizer as LB
from dask.distributed import default_client
from cuml.dask.common.input_utils import _extract_partitions
from cuml.common import rmm_cupy_ary
import dask
import cupy as cp
class LabelBinarizer(object):
def __init__(self, client=None, **kwargs):
self.client_ = client if client is not None else default_client()
self.kwargs = kwargs
if "sparse_output" in self.kwargs and \
self.kwargs["sparse_output"] is True:
raise ValueError("Sparse output not yet "
"supported in distributed mode")
@staticmethod
def _func_create_model(**kwargs):
return LB(**kwargs)
@staticmethod
def _func_unique_classes(y):
return rmm_cupy_ary(cp.unique, y)
@staticmethod
def _func_xform(model, y):
xform_in = rmm_cupy_ary(cp.asarray, y, dtype=y.dtype)
return model.transform(xform_in)
@staticmethod
def _func_inv_xform(model, y, threshold):
y = rmm_cupy_ary(cp.asarray, y, dtype=y.dtype)
return model.inverse_transform(y, threshold)
def fit(self, y):
futures = self.client_.sync(_extract_partitions, y)
unique = [self.client_.submit(LabelBinarizer._func_unique_classes, f)
for w, f in futures]
classes = self.client_.compute(unique, True)
self.classes_ = rmm_cupy_ary(cp.unique,
rmm_cupy_ary(cp.stack,
classes,
axis=0))
self.model = LB(**self.kwargs).fit(self.classes_)
return self
def fit_transform(self, y):
return self.fit(y).transform(y)
def transform(self, y):
parts = self.client_.sync(_extract_partitions, y)
xform_func = dask.delayed(LabelBinarizer._func_xform)
meta = rmm_cupy_ary(cp.zeros, 1)
if self.model.sparse_output:
meta = cp.sparse.csr_matrix(meta)
f = [dask.array.from_delayed(xform_func(self.model, part),
meta=meta, dtype=cp.float32,
shape=(len(y), len(self.classes_))) for w, part in parts]
arr = dask.array.asarray(f)
return arr.reshape(arr.shape[1:])
def inverse_transform(self, y, threshold=None):
parts = self.client_.sync(_extract_partitions, y)
inv_func = dask.delayed(LabelBinarizer._func_inv_xform)
dtype = self.classes_.dtype
meta = rmm_cupy_ary(cp.zeros, 1, dtype=dtype)
f = [dask.array.from_delayed(
inv_func(self.model, part, threshold),
dtype=dtype, shape=(y.shape[0],), meta=meta)
for w, part in parts]
ret = dask.array.stack(f, axis=0)
return ret.reshape(ret.shape[1:])
| true
| true
|
790e6026009666cf369fded3d07108280c0bf789
| 7,582
|
py
|
Python
|
tests/test_feedback.py
|
slarse/repobee-feedback
|
a3a059dd04a81ff0ed9979839b8cc0c2ce90220b
|
[
"MIT"
] | null | null | null |
tests/test_feedback.py
|
slarse/repobee-feedback
|
a3a059dd04a81ff0ed9979839b8cc0c2ce90220b
|
[
"MIT"
] | 2
|
2019-09-11T14:10:03.000Z
|
2019-09-11T22:24:08.000Z
|
tests/test_feedback.py
|
slarse/repobee-feedback
|
a3a059dd04a81ff0ed9979839b8cc0c2ce90220b
|
[
"MIT"
] | null | null | null |
import argparse
import sys
import pathlib
import random
from unittest import mock
import pytest
from _repobee import plugin
import repobee_plug as plug
from repobee_feedback import feedback
ASSIGNMENT_NAMES = ("task-1", "task-2")
STUDENT_TEAMS = tuple(
[
plug.StudentTeam(members=members)
for members in (["slarse"], ["glassey"], ["grundb", "glennol"])
]
)
STUDENT_TEAM_NAMES = tuple(map(str, STUDENT_TEAMS))
PASS_ISSUE = plug.Issue(title="Pass", body="Well done!\nAbsolutely flawless!")
KOMP_ISSUE = plug.Issue(
title="Komplettering", body="Not perfect, you need to fix this."
)
FAIL_ISSUE = plug.Issue(
title="Fail", body="Unfortunately, there are severe errors."
)
ISSUES = (PASS_ISSUE, KOMP_ISSUE, FAIL_ISSUE)
random.seed(512)
def _write_issue(issue: plug.Issue, path: pathlib.Path):
text = "{}\n{}".format(issue.title, issue.body)
path.write_text(text, encoding=sys.getdefaultencoding())
def _write_multi_issues_file(repos_and_issues, path):
with open(str(path), mode="w", encoding=sys.getdefaultencoding()) as file:
cur = 0
for repo_name, issue in repos_and_issues:
if cur:
file.write("\n")
file.write("#ISSUE#{}#{}\n".format(repo_name, issue.title))
file.write(issue.body)
cur += 1
def test_register():
"""Just test that there is no crash"""
plugin.register_plugins([feedback])
@pytest.fixture
def parsed_args_issues_dir(tmp_path):
return argparse.Namespace(
students=list(STUDENT_TEAMS),
assignments=list(ASSIGNMENT_NAMES),
batch_mode=True,
issues_dir=str(tmp_path),
multi_issues_file=None,
truncation_length=50,
allow_missing=False,
)
@pytest.fixture
def parsed_args_multi_issues_file(with_multi_issues_file):
issues_file, _ = with_multi_issues_file
return argparse.Namespace(
students=list(STUDENT_TEAMS),
assignments=list(ASSIGNMENT_NAMES),
batch_mode=True,
issues_dir=None,
multi_issues_file=str(issues_file),
truncation_length=50,
allow_missing=False,
)
@pytest.fixture
def api_mock():
return mock.MagicMock(spec=plug.PlatformAPI)
@pytest.fixture
def with_issues(tmp_path):
"""Create issue files in a temporary directory and return a list of (team,
issue) tuples.
"""
repo_names = plug.generate_repo_names(STUDENT_TEAM_NAMES, ASSIGNMENT_NAMES)
existing_issues = []
for repo_name in repo_names:
issue_file = tmp_path / "{}.md".format(repo_name)
issue = random.choice(ISSUES)
_write_issue(issue, issue_file)
existing_issues.append((repo_name, issue))
return existing_issues
@pytest.fixture
def with_multi_issues_file(tmp_path):
"""Create the multi issues file."""
repo_names = plug.generate_repo_names(STUDENT_TEAM_NAMES, ASSIGNMENT_NAMES)
repos_and_issues = [
(repo_name, random.choice(ISSUES)) for repo_name in repo_names
]
issues_file = tmp_path / "issues.md"
_write_multi_issues_file(repos_and_issues, issues_file)
return issues_file, repos_and_issues
class TestCallback:
"""Tests for the primary callback."""
def test_opens_issues_from_issues_dir(
self, with_issues, parsed_args_issues_dir, api_mock
):
"""Test that the callback calls the API.open_issue for the expected
repos and issues, when the issues all exist and are well formed.
"""
expected_calls = [
mock.call(issue.title, issue.body, mock.ANY)
for repo_name, issue in with_issues
]
feedback.callback(args=parsed_args_issues_dir, api=api_mock)
api_mock.create_issue.assert_has_calls(expected_calls, any_order=True)
def test_aborts_if_issue_is_missing(
self, with_issues, parsed_args_issues_dir, api_mock, tmp_path
):
"""Test that the callback exits with a plug.PlugError if any of the
expected issues is not found.
"""
repo_without_issue = plug.generate_repo_name(
STUDENT_TEAM_NAMES[-1], ASSIGNMENT_NAMES[0]
)
missing_file = tmp_path / "{}.md".format(repo_without_issue)
missing_file.unlink()
with pytest.raises(plug.PlugError) as exc_info:
feedback.callback(args=parsed_args_issues_dir, api=api_mock)
assert repo_without_issue in str(exc_info.value)
assert not api_mock.create_issue.called
def test_ignores_missing_issue_if_allow_missing(
self, with_issues, parsed_args_issues_dir, api_mock, tmp_path
):
"""Test that missing issues are ignored if --allow-mising is set."""
repo_without_issue = plug.generate_repo_name(
STUDENT_TEAM_NAMES[-1], ASSIGNMENT_NAMES[0]
)
(tmp_path / "{}.md".format(repo_without_issue)).unlink()
expected_calls = [
mock.call(issue.title, issue.body, mock.ANY)
for repo_name, issue in with_issues
if repo_name != repo_without_issue
]
args_dict = vars(parsed_args_issues_dir)
args_dict["allow_missing"] = True
args = argparse.Namespace(**args_dict)
feedback.callback(args=args, api=api_mock)
api_mock.create_issue.assert_has_calls(expected_calls, any_order=True)
def test_opens_nothing_if_open_prompt_returns_false(
self, with_issues, parsed_args_issues_dir, api_mock
):
"""Test that the callback does not attempt to open any issues if the
'may I open' prompt returns false.
"""
args_dict = vars(parsed_args_issues_dir)
args_dict["batch_mode"] = False
parsed_args_interactive = argparse.Namespace(**args_dict)
with mock.patch("builtins.input", return_value="n", autospec=True):
feedback.callback(args=parsed_args_interactive, api=api_mock)
assert not api_mock.create_issue.called
def test_opens_issues_from_multi_issues_file(
self, with_multi_issues_file, api_mock, parsed_args_multi_issues_file
):
"""Test that the callback opens issues correctly when they are all
contained in a multi issues file.
"""
issues_file, repos_and_issues = with_multi_issues_file
expected_calls = [
mock.call(issue.title, issue.body, mock.ANY)
for repo_name, issue in repos_and_issues
]
feedback.callback(args=parsed_args_multi_issues_file, api=api_mock)
api_mock.create_issue.assert_has_calls(expected_calls)
def test_skips_unexpected_issues_in_multi_issues_file(
self, with_multi_issues_file, parsed_args_multi_issues_file, api_mock
):
"""Test that an exception is raised if one or more issues are found
relating to student repos that ar not in prod(assignments, students).
"""
student_teams = parsed_args_multi_issues_file.students
args_dict = vars(parsed_args_multi_issues_file)
args_dict["students"] = student_teams[:-1]
args = argparse.Namespace(**args_dict)
unexpected_repos = plug.generate_repo_names(
student_teams[-1:], ASSIGNMENT_NAMES
)
_, repos_and_issues = with_multi_issues_file
expected_calls = [
mock.call(issue.title, issue.body, mock.ANY)
for repo_name, issue in repos_and_issues
if repo_name not in unexpected_repos
]
feedback.callback(args=args, api=api_mock)
api_mock.create_issue.assert_has_calls(expected_calls, any_order=True)
| 33.548673
| 79
| 0.684648
|
import argparse
import sys
import pathlib
import random
from unittest import mock
import pytest
from _repobee import plugin
import repobee_plug as plug
from repobee_feedback import feedback
ASSIGNMENT_NAMES = ("task-1", "task-2")
STUDENT_TEAMS = tuple(
[
plug.StudentTeam(members=members)
for members in (["slarse"], ["glassey"], ["grundb", "glennol"])
]
)
STUDENT_TEAM_NAMES = tuple(map(str, STUDENT_TEAMS))
PASS_ISSUE = plug.Issue(title="Pass", body="Well done!\nAbsolutely flawless!")
KOMP_ISSUE = plug.Issue(
title="Komplettering", body="Not perfect, you need to fix this."
)
FAIL_ISSUE = plug.Issue(
title="Fail", body="Unfortunately, there are severe errors."
)
ISSUES = (PASS_ISSUE, KOMP_ISSUE, FAIL_ISSUE)
random.seed(512)
def _write_issue(issue: plug.Issue, path: pathlib.Path):
text = "{}\n{}".format(issue.title, issue.body)
path.write_text(text, encoding=sys.getdefaultencoding())
def _write_multi_issues_file(repos_and_issues, path):
with open(str(path), mode="w", encoding=sys.getdefaultencoding()) as file:
cur = 0
for repo_name, issue in repos_and_issues:
if cur:
file.write("\n")
file.write("#ISSUE#{}#{}\n".format(repo_name, issue.title))
file.write(issue.body)
cur += 1
def test_register():
plugin.register_plugins([feedback])
@pytest.fixture
def parsed_args_issues_dir(tmp_path):
return argparse.Namespace(
students=list(STUDENT_TEAMS),
assignments=list(ASSIGNMENT_NAMES),
batch_mode=True,
issues_dir=str(tmp_path),
multi_issues_file=None,
truncation_length=50,
allow_missing=False,
)
@pytest.fixture
def parsed_args_multi_issues_file(with_multi_issues_file):
issues_file, _ = with_multi_issues_file
return argparse.Namespace(
students=list(STUDENT_TEAMS),
assignments=list(ASSIGNMENT_NAMES),
batch_mode=True,
issues_dir=None,
multi_issues_file=str(issues_file),
truncation_length=50,
allow_missing=False,
)
@pytest.fixture
def api_mock():
return mock.MagicMock(spec=plug.PlatformAPI)
@pytest.fixture
def with_issues(tmp_path):
repo_names = plug.generate_repo_names(STUDENT_TEAM_NAMES, ASSIGNMENT_NAMES)
existing_issues = []
for repo_name in repo_names:
issue_file = tmp_path / "{}.md".format(repo_name)
issue = random.choice(ISSUES)
_write_issue(issue, issue_file)
existing_issues.append((repo_name, issue))
return existing_issues
@pytest.fixture
def with_multi_issues_file(tmp_path):
repo_names = plug.generate_repo_names(STUDENT_TEAM_NAMES, ASSIGNMENT_NAMES)
repos_and_issues = [
(repo_name, random.choice(ISSUES)) for repo_name in repo_names
]
issues_file = tmp_path / "issues.md"
_write_multi_issues_file(repos_and_issues, issues_file)
return issues_file, repos_and_issues
class TestCallback:
def test_opens_issues_from_issues_dir(
self, with_issues, parsed_args_issues_dir, api_mock
):
expected_calls = [
mock.call(issue.title, issue.body, mock.ANY)
for repo_name, issue in with_issues
]
feedback.callback(args=parsed_args_issues_dir, api=api_mock)
api_mock.create_issue.assert_has_calls(expected_calls, any_order=True)
def test_aborts_if_issue_is_missing(
self, with_issues, parsed_args_issues_dir, api_mock, tmp_path
):
repo_without_issue = plug.generate_repo_name(
STUDENT_TEAM_NAMES[-1], ASSIGNMENT_NAMES[0]
)
missing_file = tmp_path / "{}.md".format(repo_without_issue)
missing_file.unlink()
with pytest.raises(plug.PlugError) as exc_info:
feedback.callback(args=parsed_args_issues_dir, api=api_mock)
assert repo_without_issue in str(exc_info.value)
assert not api_mock.create_issue.called
def test_ignores_missing_issue_if_allow_missing(
self, with_issues, parsed_args_issues_dir, api_mock, tmp_path
):
repo_without_issue = plug.generate_repo_name(
STUDENT_TEAM_NAMES[-1], ASSIGNMENT_NAMES[0]
)
(tmp_path / "{}.md".format(repo_without_issue)).unlink()
expected_calls = [
mock.call(issue.title, issue.body, mock.ANY)
for repo_name, issue in with_issues
if repo_name != repo_without_issue
]
args_dict = vars(parsed_args_issues_dir)
args_dict["allow_missing"] = True
args = argparse.Namespace(**args_dict)
feedback.callback(args=args, api=api_mock)
api_mock.create_issue.assert_has_calls(expected_calls, any_order=True)
def test_opens_nothing_if_open_prompt_returns_false(
self, with_issues, parsed_args_issues_dir, api_mock
):
args_dict = vars(parsed_args_issues_dir)
args_dict["batch_mode"] = False
parsed_args_interactive = argparse.Namespace(**args_dict)
with mock.patch("builtins.input", return_value="n", autospec=True):
feedback.callback(args=parsed_args_interactive, api=api_mock)
assert not api_mock.create_issue.called
def test_opens_issues_from_multi_issues_file(
self, with_multi_issues_file, api_mock, parsed_args_multi_issues_file
):
issues_file, repos_and_issues = with_multi_issues_file
expected_calls = [
mock.call(issue.title, issue.body, mock.ANY)
for repo_name, issue in repos_and_issues
]
feedback.callback(args=parsed_args_multi_issues_file, api=api_mock)
api_mock.create_issue.assert_has_calls(expected_calls)
def test_skips_unexpected_issues_in_multi_issues_file(
self, with_multi_issues_file, parsed_args_multi_issues_file, api_mock
):
student_teams = parsed_args_multi_issues_file.students
args_dict = vars(parsed_args_multi_issues_file)
args_dict["students"] = student_teams[:-1]
args = argparse.Namespace(**args_dict)
unexpected_repos = plug.generate_repo_names(
student_teams[-1:], ASSIGNMENT_NAMES
)
_, repos_and_issues = with_multi_issues_file
expected_calls = [
mock.call(issue.title, issue.body, mock.ANY)
for repo_name, issue in repos_and_issues
if repo_name not in unexpected_repos
]
feedback.callback(args=args, api=api_mock)
api_mock.create_issue.assert_has_calls(expected_calls, any_order=True)
| true
| true
|
790e622afb9411d289cf87fa112c25e164c1e4a2
| 7,768
|
py
|
Python
|
racecar-code/labs/test_utils.py
|
abhatia25/Beaverworks-Racecar
|
7c579e27de3688d58f280ff260897f77efa5fb4a
|
[
"MIT"
] | null | null | null |
racecar-code/labs/test_utils.py
|
abhatia25/Beaverworks-Racecar
|
7c579e27de3688d58f280ff260897f77efa5fb4a
|
[
"MIT"
] | 1
|
2021-03-06T21:24:28.000Z
|
2021-03-06T21:24:28.000Z
|
racecar-code/labs/test_utils.py
|
abhatia25/Beaverworks-Racecar
|
7c579e27de3688d58f280ff260897f77efa5fb4a
|
[
"MIT"
] | 1
|
2021-03-06T21:04:55.000Z
|
2021-03-06T21:04:55.000Z
|
"""
Copyright MIT and Harvey Mudd College
MIT License
Summer 2020
A simple program which can be used to manually test racecar_utils functionality.
"""
########################################################################################
# Imports
########################################################################################
import math
import sys
sys.path.insert(1, "../library")
import racecar_core
import racecar_utils as rc_utils
########################################################################################
# Global variables
########################################################################################
rc = racecar_core.create_racecar()
RED = ((170, 50, 50), (10, 255, 255))
max_speed = 0
show_triggers = False
show_joysticks = False
########################################################################################
# Functions
########################################################################################
def start():
"""
This function is run once every time the start button is pressed
"""
global max_speed
global show_triggers
global show_joysticks
print("Start function called")
rc.set_update_slow_time(0.5)
rc.drive.stop()
max_speed = 0.25
show_triggers = False
show_joysticks = False
# Test numeric functions
assert rc_utils.remap_range(5, 0, 10, 0, 50) == 25
assert rc_utils.remap_range(5, 0, 20, 1000, 900) == 975
assert rc_utils.remap_range(2, 0, 1, -10, 10) == 30
assert rc_utils.remap_range(2, 0, 1, -10, 10, True) == 10
assert rc_utils.clamp(3, 0, 10) == 3
assert rc_utils.clamp(-2, 0, 10) == 0
assert rc_utils.clamp(11, 0, 10) == 10
# Print start message
print(
">> Test Utils: A testing program for the racecar_utils library.\n"
"\n"
"Controls:\n"
" Right trigger = accelerate forward\n"
" Left trigger = accelerate backward\n"
" Left joystick = turn front wheels\n"
" A button = Take a color image and crop it to the top left\n"
" B button = Take a color image and identify the largest red contour\n"
" X button = Take a depth image and print several statistics\n"
" Y button = Take a lidar scan and print several statistics\n"
)
def update():
"""
After start() is run, this function is run every frame until the back button
is pressed
"""
# Display the color image cropped to the top left
if rc.controller.was_pressed(rc.controller.Button.A):
image = rc.camera.get_color_image()
cropped = rc_utils.crop(
image, (0, 0), (rc.camera.get_height() // 2, rc.camera.get_width() // 2)
)
rc.display.show_color_image(cropped)
# Find and display the largest red contour in the color image
if rc.controller.was_pressed(rc.controller.Button.B):
image = rc.camera.get_color_image()
contours = rc_utils.find_contours(image, RED[0], RED[1])
largest_contour = rc_utils.get_largest_contour(contours)
if largest_contour is not None:
center = rc_utils.get_contour_center(largest_contour)
area = rc_utils.get_contour_area(largest_contour)
print("Largest red contour: center={}, area={:.2f}".format(center, area))
rc_utils.draw_contour(image, largest_contour, rc_utils.ColorBGR.green.value)
rc_utils.draw_circle(image, center, rc_utils.ColorBGR.yellow.value)
rc.display.show_color_image(image)
else:
print("No red contours found")
# Print depth image statistics and show the cropped upper half
if rc.controller.was_pressed(rc.controller.Button.X):
depth_image = rc.camera.get_depth_image()
# Measure average distance at several points
left_distance = rc_utils.get_pixel_average_distance(
depth_image, (rc.camera.get_height() // 2, rc.camera.get_width() // 4),
)
center_distance = rc_utils.get_depth_image_center_distance(depth_image)
center_distance_raw = rc_utils.get_depth_image_center_distance(depth_image, 1)
right_distance = rc_utils.get_pixel_average_distance(
depth_image, (rc.camera.get_height() // 2, 3 * rc.camera.get_width() // 4),
)
print(f"Depth image left distance: {left_distance:.2f} cm")
print(f"Depth image center distance: {center_distance:.2f} cm")
print(f"Depth image raw center distance: {center_distance_raw:.2f} cm")
print(f"Depth image right distance: {right_distance:.2f} cm")
# Measure pixels where the kernel falls off the edge of the photo
upper_left_distance = rc_utils.get_pixel_average_distance(
depth_image, (2, 1), 11
)
lower_right_distance = rc_utils.get_pixel_average_distance(
depth_image, (rc.camera.get_height() - 2, rc.camera.get_width() - 5), 13
)
print(f"Depth image upper left distance: {upper_left_distance:.2f} cm")
print(f"Depth image lower right distance: {lower_right_distance:.2f} cm")
# Find closest point in bottom third
cropped = rc_utils.crop(
depth_image,
(0, 0),
(rc.camera.get_height() * 2 // 3, rc.camera.get_width()),
)
closest_point = rc_utils.get_closest_pixel(cropped)
closest_distance = cropped[closest_point[0]][closest_point[1]]
print(
f"Depth image closest point (upper half): (row={closest_point[0]}, col={closest_point[1]}), distance={closest_distance:.2f} cm"
)
rc.display.show_depth_image(cropped, points=[closest_point])
# Print lidar statistics and show visualization with closest point highlighted
if rc.controller.was_pressed(rc.controller.Button.Y):
lidar = rc.lidar.get_samples()
front_distance = rc_utils.get_lidar_average_distance(lidar, 0)
right_distance = rc_utils.get_lidar_average_distance(lidar, 90)
back_distance = rc_utils.get_lidar_average_distance(lidar, 180)
left_distance = rc_utils.get_lidar_average_distance(lidar, 270)
print(f"Front LIDAR distance: {front_distance:.2f} cm")
print(f"Right LIDAR distance: {right_distance:.2f} cm")
print(f"Back LIDAR distance: {back_distance:.2f} cm")
print(f"Left LIDAR distance: {left_distance:.2f} cm")
closest_sample = rc_utils.get_lidar_closest_point(lidar)
print(
f"Closest LIDAR point: {closest_sample[0]:.2f} degrees, {closest_sample[1]:.2f} cm"
)
rc.display.show_lidar(lidar, highlighted_samples=[closest_sample])
# Print lidar distance in the direction the right joystick is pointed
rjoy_x, rjoy_y = rc.controller.get_joystick(rc.controller.Joystick.RIGHT)
if abs(rjoy_x) > 0 or abs(rjoy_y) > 0:
lidar = rc.lidar.get_samples()
angle = (math.atan2(rjoy_x, rjoy_y) * 180 / math.pi) % 360
distance = rc_utils.get_lidar_average_distance(lidar, angle)
print(f"LIDAR distance at angle {angle:.2f} = {distance:.2f} cm")
# Default drive-style controls
left_trigger = rc.controller.get_trigger(rc.controller.Trigger.LEFT)
right_trigger = rc.controller.get_trigger(rc.controller.Trigger.RIGHT)
left_joystick = rc.controller.get_joystick(rc.controller.Joystick.LEFT)
rc.drive.set_speed_angle(right_trigger - left_trigger, left_joystick[0])
########################################################################################
# DO NOT MODIFY: Register start and update and begin execution
########################################################################################
if __name__ == "__main__":
rc.set_start_update(start, update, None)
rc.go()
| 41.319149
| 139
| 0.609166
| true
| true
|
|
790e62a5c151bac56ff72c68dada6b0f35c59d2f
| 7,082
|
py
|
Python
|
summarizer/bert.py
|
stungkit/bert-extractive-summarizer
|
84f27333aef33629444589c24933b76448777d4f
|
[
"MIT"
] | null | null | null |
summarizer/bert.py
|
stungkit/bert-extractive-summarizer
|
84f27333aef33629444589c24933b76448777d4f
|
[
"MIT"
] | null | null | null |
summarizer/bert.py
|
stungkit/bert-extractive-summarizer
|
84f27333aef33629444589c24933b76448777d4f
|
[
"MIT"
] | null | null | null |
from functools import partial
from typing import List, Optional, Union
from transformers import (AlbertModel, AlbertTokenizer, BartModel, BigBirdModel, BigBirdTokenizer,
BartTokenizer, BertModel, BertTokenizer,
CamembertModel, CamembertTokenizer, CTRLModel,
CTRLTokenizer, DistilBertModel, DistilBertTokenizer,
GPT2Model, GPT2Tokenizer, LongformerModel,
LongformerTokenizer, OpenAIGPTModel,
OpenAIGPTTokenizer, PreTrainedModel,
PreTrainedTokenizer, RobertaModel, RobertaTokenizer,
TransfoXLModel, TransfoXLTokenizer, XLMModel,
XLMTokenizer, XLNetModel, XLNetTokenizer)
from summarizer.summary_processor import SummaryProcessor
from summarizer.text_processors.sentence_handler import SentenceHandler
from summarizer.transformer_embeddings.bert_embedding import BertEmbedding
class BertSummarizer(SummaryProcessor):
"""Summarizer based on the BERT model."""
def __init__(
self,
model: Optional[str] = 'bert-large-uncased',
custom_model: PreTrainedModel = None,
custom_tokenizer: PreTrainedTokenizer = None,
hidden: Union[List[int], int] = -2,
reduce_option: str = 'mean',
sentence_handler: SentenceHandler = SentenceHandler(),
random_state: int = 12345,
hidden_concat: bool = False,
gpu_id: int = 0,
):
"""
This is the parent Bert Summarizer model. New methods should implement this class.
:param model: This parameter is associated with the inherit string parameters from the transformers library.
:param custom_model: If you have a pre-trained model, you can add the model class here.
:param custom_tokenizer: If you have a custom tokenizer, you can add the tokenizer here.
:param hidden: This signifies which layer(s) of the BERT model you would like to use as embeddings.
:param reduce_option: Given the output of the bert model, this param determines how you want to reduce results.
:param sentence_handler: The handler to process sentences. If want to use coreference, instantiate and pass.
CoreferenceHandler instance
:param random_state: The random state to reproduce summarizations.
:param hidden_concat: Whether or not to concat multiple hidden layers.
:param gpu_id: GPU device index if CUDA is available.
"""
model = BertEmbedding(model, custom_model, custom_tokenizer, gpu_id)
model_func = partial(model, hidden=hidden, reduce_option=reduce_option, hidden_concat=hidden_concat)
super().__init__(model_func, sentence_handler, random_state)
class Summarizer(BertSummarizer):
def __init__(
self,
model: str = 'bert-large-uncased',
custom_model: PreTrainedModel = None,
custom_tokenizer: PreTrainedTokenizer = None,
hidden: Union[List[int], int] = -2,
reduce_option: str = 'mean',
sentence_handler: SentenceHandler = SentenceHandler(),
random_state: int = 12345,
hidden_concat: bool = False,
gpu_id: int = 0,
):
"""
This is the main Bert Summarizer class.
:param model: This parameter is associated with the inherit string parameters from the transformers library.
:param custom_model: If you have a pre-trained model, you can add the model class here.
:param custom_tokenizer: If you have a custom tokenizer, you can add the tokenizer here.
:param hidden: This signifies which layer of the BERT model you would like to use as embeddings.
:param reduce_option: Given the output of the bert model, this param determines how you want to reduce results.
:param random_state: The random state to reproduce summarizations.
:param hidden_concat: Whether or not to concat multiple hidden layers.
:param gpu_id: GPU device index if CUDA is available.
"""
super(Summarizer, self).__init__(
model, custom_model, custom_tokenizer, hidden, reduce_option, sentence_handler, random_state, hidden_concat,
gpu_id
)
class TransformerSummarizer(BertSummarizer):
"""
Newer style that has keywords for models and tokenizers, but allows the user to change the type.
"""
MODEL_DICT = {
'Bert': (BertModel, BertTokenizer),
'OpenAIGPT': (OpenAIGPTModel, OpenAIGPTTokenizer),
'GPT2': (GPT2Model, GPT2Tokenizer),
'CTRL': (CTRLModel, CTRLTokenizer),
'TransfoXL': (TransfoXLModel, TransfoXLTokenizer),
'XLNet': (XLNetModel, XLNetTokenizer),
'XLM': (XLMModel, XLMTokenizer),
'DistilBert': (DistilBertModel, DistilBertTokenizer),
}
def __init__(
self,
transformer_type: str = 'Bert',
transformer_model_key: str = 'bert-base-uncased',
transformer_tokenizer_key: str = None,
hidden: Union[List[int], int] = -2,
reduce_option: str = 'mean',
sentence_handler: SentenceHandler = SentenceHandler(),
random_state: int = 12345,
hidden_concat: bool = False,
gpu_id: int = 0,
):
"""
:param transformer_type: The Transformer type, such as Bert, GPT2, DistilBert, etc.
:param transformer_model_key: The transformer model key. This is the directory for the model.
:param transformer_tokenizer_key: The transformer tokenizer key. This is the tokenizer directory.
:param hidden: The hidden output layers to use for the summarization.
:param reduce_option: The reduce option, such as mean, max, min, median, etc.
:param sentence_handler: The sentence handler class to process the raw text.
:param random_state: The random state to use.
:param hidden_concat: Deprecated hidden concat option.
:param gpu_id: GPU device index if CUDA is available.
"""
try:
self.MODEL_DICT['Roberta'] = (RobertaModel, RobertaTokenizer)
self.MODEL_DICT['Albert'] = (AlbertModel, AlbertTokenizer)
self.MODEL_DICT['Camembert'] = (CamembertModel, CamembertTokenizer)
self.MODEL_DICT['Bart'] = (BartModel, BartTokenizer)
self.MODEL_DICT['Longformer'] = (LongformerModel, LongformerTokenizer)
self.MODEL_DICT['BigBird'] = (BigBirdModel, BigBirdTokenizer)
except Exception:
pass # older transformer version
model_clz, tokenizer_clz = self.MODEL_DICT[transformer_type]
model = model_clz.from_pretrained(
transformer_model_key, output_hidden_states=True)
tokenizer = tokenizer_clz.from_pretrained(
transformer_tokenizer_key if transformer_tokenizer_key is not None else transformer_model_key
)
super().__init__(
None, model, tokenizer, hidden, reduce_option, sentence_handler, random_state, hidden_concat, gpu_id
)
| 48.176871
| 120
| 0.673539
|
from functools import partial
from typing import List, Optional, Union
from transformers import (AlbertModel, AlbertTokenizer, BartModel, BigBirdModel, BigBirdTokenizer,
BartTokenizer, BertModel, BertTokenizer,
CamembertModel, CamembertTokenizer, CTRLModel,
CTRLTokenizer, DistilBertModel, DistilBertTokenizer,
GPT2Model, GPT2Tokenizer, LongformerModel,
LongformerTokenizer, OpenAIGPTModel,
OpenAIGPTTokenizer, PreTrainedModel,
PreTrainedTokenizer, RobertaModel, RobertaTokenizer,
TransfoXLModel, TransfoXLTokenizer, XLMModel,
XLMTokenizer, XLNetModel, XLNetTokenizer)
from summarizer.summary_processor import SummaryProcessor
from summarizer.text_processors.sentence_handler import SentenceHandler
from summarizer.transformer_embeddings.bert_embedding import BertEmbedding
class BertSummarizer(SummaryProcessor):
def __init__(
self,
model: Optional[str] = 'bert-large-uncased',
custom_model: PreTrainedModel = None,
custom_tokenizer: PreTrainedTokenizer = None,
hidden: Union[List[int], int] = -2,
reduce_option: str = 'mean',
sentence_handler: SentenceHandler = SentenceHandler(),
random_state: int = 12345,
hidden_concat: bool = False,
gpu_id: int = 0,
):
model = BertEmbedding(model, custom_model, custom_tokenizer, gpu_id)
model_func = partial(model, hidden=hidden, reduce_option=reduce_option, hidden_concat=hidden_concat)
super().__init__(model_func, sentence_handler, random_state)
class Summarizer(BertSummarizer):
def __init__(
self,
model: str = 'bert-large-uncased',
custom_model: PreTrainedModel = None,
custom_tokenizer: PreTrainedTokenizer = None,
hidden: Union[List[int], int] = -2,
reduce_option: str = 'mean',
sentence_handler: SentenceHandler = SentenceHandler(),
random_state: int = 12345,
hidden_concat: bool = False,
gpu_id: int = 0,
):
super(Summarizer, self).__init__(
model, custom_model, custom_tokenizer, hidden, reduce_option, sentence_handler, random_state, hidden_concat,
gpu_id
)
class TransformerSummarizer(BertSummarizer):
MODEL_DICT = {
'Bert': (BertModel, BertTokenizer),
'OpenAIGPT': (OpenAIGPTModel, OpenAIGPTTokenizer),
'GPT2': (GPT2Model, GPT2Tokenizer),
'CTRL': (CTRLModel, CTRLTokenizer),
'TransfoXL': (TransfoXLModel, TransfoXLTokenizer),
'XLNet': (XLNetModel, XLNetTokenizer),
'XLM': (XLMModel, XLMTokenizer),
'DistilBert': (DistilBertModel, DistilBertTokenizer),
}
def __init__(
self,
transformer_type: str = 'Bert',
transformer_model_key: str = 'bert-base-uncased',
transformer_tokenizer_key: str = None,
hidden: Union[List[int], int] = -2,
reduce_option: str = 'mean',
sentence_handler: SentenceHandler = SentenceHandler(),
random_state: int = 12345,
hidden_concat: bool = False,
gpu_id: int = 0,
):
try:
self.MODEL_DICT['Roberta'] = (RobertaModel, RobertaTokenizer)
self.MODEL_DICT['Albert'] = (AlbertModel, AlbertTokenizer)
self.MODEL_DICT['Camembert'] = (CamembertModel, CamembertTokenizer)
self.MODEL_DICT['Bart'] = (BartModel, BartTokenizer)
self.MODEL_DICT['Longformer'] = (LongformerModel, LongformerTokenizer)
self.MODEL_DICT['BigBird'] = (BigBirdModel, BigBirdTokenizer)
except Exception:
pass
model_clz, tokenizer_clz = self.MODEL_DICT[transformer_type]
model = model_clz.from_pretrained(
transformer_model_key, output_hidden_states=True)
tokenizer = tokenizer_clz.from_pretrained(
transformer_tokenizer_key if transformer_tokenizer_key is not None else transformer_model_key
)
super().__init__(
None, model, tokenizer, hidden, reduce_option, sentence_handler, random_state, hidden_concat, gpu_id
)
| true
| true
|
790e63a10493bf287298406333fe7d5c1754ea94
| 775
|
py
|
Python
|
src/advent_2021/day_12/part_1.py
|
mgesbert/advent
|
5768691b110a954f834686147432657dcb63e59f
|
[
"MIT"
] | null | null | null |
src/advent_2021/day_12/part_1.py
|
mgesbert/advent
|
5768691b110a954f834686147432657dcb63e59f
|
[
"MIT"
] | null | null | null |
src/advent_2021/day_12/part_1.py
|
mgesbert/advent
|
5768691b110a954f834686147432657dcb63e59f
|
[
"MIT"
] | null | null | null |
from collections import defaultdict
from advent_2021.helpers import get_input
def dfs(
caves: dict[str, list[str]],
current: str,
visited: set[str] | None = None,
) -> int:
if current == "end":
return 1
nb_paths = 0
if visited is None:
visited = set()
for cave in caves[current]:
if cave in visited:
continue
nb_paths += dfs(
caves, cave, visited | {current} if current.islower() else visited
)
return nb_paths
if __name__ == "__main__":
caves: dict[str, list[str]] = defaultdict(list)
for line in get_input():
caves[line.split("-")[0]].append(line.split("-")[1])
caves[line.split("-")[1]].append(line.split("-")[0])
print(dfs(caves, "start"))
| 23.484848
| 78
| 0.580645
|
from collections import defaultdict
from advent_2021.helpers import get_input
def dfs(
caves: dict[str, list[str]],
current: str,
visited: set[str] | None = None,
) -> int:
if current == "end":
return 1
nb_paths = 0
if visited is None:
visited = set()
for cave in caves[current]:
if cave in visited:
continue
nb_paths += dfs(
caves, cave, visited | {current} if current.islower() else visited
)
return nb_paths
if __name__ == "__main__":
caves: dict[str, list[str]] = defaultdict(list)
for line in get_input():
caves[line.split("-")[0]].append(line.split("-")[1])
caves[line.split("-")[1]].append(line.split("-")[0])
print(dfs(caves, "start"))
| true
| true
|
790e67b4a0130e236418657be57ccbb358b26c43
| 119
|
py
|
Python
|
prometheus_manager/database.py
|
wikimedia/cloud-metricsinfra-prometheus-manager
|
ad42e8e1173cabb0d9333cb07d3e1506f5729380
|
[
"BSD-3-Clause"
] | null | null | null |
prometheus_manager/database.py
|
wikimedia/cloud-metricsinfra-prometheus-manager
|
ad42e8e1173cabb0d9333cb07d3e1506f5729380
|
[
"BSD-3-Clause"
] | null | null | null |
prometheus_manager/database.py
|
wikimedia/cloud-metricsinfra-prometheus-manager
|
ad42e8e1173cabb0d9333cb07d3e1506f5729380
|
[
"BSD-3-Clause"
] | null | null | null |
from flask_alembic import Alembic
from flask_sqlalchemy import SQLAlchemy
database = SQLAlchemy()
alembic = Alembic()
| 19.833333
| 39
| 0.823529
|
from flask_alembic import Alembic
from flask_sqlalchemy import SQLAlchemy
database = SQLAlchemy()
alembic = Alembic()
| true
| true
|
790e684ea71bd28eb7fa097fe3844b1b6a49fcee
| 4,568
|
py
|
Python
|
LW-UI/authosm/models.py
|
5g-media/OIDC_ON_OSMr5
|
cd4cb104e32352d030b349c7d36711482394d283
|
[
"Apache-2.0"
] | null | null | null |
LW-UI/authosm/models.py
|
5g-media/OIDC_ON_OSMr5
|
cd4cb104e32352d030b349c7d36711482394d283
|
[
"Apache-2.0"
] | 1
|
2020-02-12T03:23:39.000Z
|
2020-02-12T03:23:39.000Z
|
LW-UI_MODIFIED/authosm/models.py
|
5g-media/OIDC_ON_OSMr5
|
cd4cb104e32352d030b349c7d36711482394d283
|
[
"Apache-2.0"
] | null | null | null |
#
# Copyright 2018 EveryUP Srl
#
# 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 BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User, AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.utils import timezone
from authosm.exceptions import OSMAuthException
from lib.osm.osmclient.clientv2 import Client
import utils
class OsmUserManager(BaseUserManager):
"""Custom manager for OsmUser."""
def _create_user(self, username, password, is_staff, is_superuser, **extra_fields):
"""Create and save a CustomUser with the given username and password. """
now = timezone.now()
if not username:
raise ValueError('The given username must be set')
is_active = extra_fields.pop("is_active", True)
user = self.model(username=username, is_staff=is_staff, is_active=is_active,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
"""Create and save an OsmUser with the given username and password."""
def create_superuser(self, username, password, **extra_fields):
return self._create_user(username, password, True, True, is_admin=True,
**extra_fields)
class AbstractOsmUser(AbstractBaseUser, PermissionsMixin):
"""Abstract User with the same behaviour as Django's default User.
Inherits from both the AbstractBaseUser and PermissionMixin.
The following attributes are inherited from the superclasses:
* password
* last_login
* is_superuser
"""
username = models.CharField(_('username'), primary_key=True, max_length=255, unique=True, db_index=True)
is_admin = models.BooleanField(_('admin status'), default=False)
is_basic_user = models.BooleanField(_('basic_user status'), default=False)
current_project = models.CharField(_('project_id'), max_length=255)
psw = models.CharField(_('psw'), max_length=36)
token = models.CharField(_('token'), max_length=36)
project_id = models.CharField(_('project_id'), max_length=36)
token_expires = models.FloatField(_('token_expires'), max_length=36)
objects = OsmUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
@property
def is_authenticated(self):
"""Checks for a valid authentication."""
if self.token is not None and utils.is_token_valid({'expires': self.token_expires}):
return True
else:
return False
def get_token(self):
if self.is_authenticated:
return {'id': self.token, 'expires': self.token_expires, 'project_id': self.project_id}
return None
def get_projects(self):
client = Client()
result = client.get_user_info(self.get_token(), self.username)
if 'error' in result and result['error'] is True:
return []
else:
return result['data']['projects']
def switch_project(self, project_id):
client = Client()
result = client.switch_project({'project_id': project_id, 'username': self.username, 'password': self.psw})
if 'error' in result and result['error'] is True:
raise OSMAuthException(result['data'])
else:
self.token = result['data']['id']
self.project_id = result['data']['project_id']
self.token_expires = result['data']['expires']
self.save()
return True
return False
class Meta:
verbose_name = _('custom user')
verbose_name_plural = _('custom users')
abstract = True
class OsmUser(AbstractOsmUser):
"""
Concrete class of AbstractCustomUser.
Use this if you don't need to extend CustomUser.
"""
class Meta(AbstractOsmUser.Meta):
swappable = 'AUTH_USER_MODEL'
| 35.138462
| 115
| 0.669002
|
from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User, AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.utils import timezone
from authosm.exceptions import OSMAuthException
from lib.osm.osmclient.clientv2 import Client
import utils
class OsmUserManager(BaseUserManager):
def _create_user(self, username, password, is_staff, is_superuser, **extra_fields):
now = timezone.now()
if not username:
raise ValueError('The given username must be set')
is_active = extra_fields.pop("is_active", True)
user = self.model(username=username, is_staff=is_staff, is_active=is_active,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, password, **extra_fields):
return self._create_user(username, password, True, True, is_admin=True,
**extra_fields)
class AbstractOsmUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(_('username'), primary_key=True, max_length=255, unique=True, db_index=True)
is_admin = models.BooleanField(_('admin status'), default=False)
is_basic_user = models.BooleanField(_('basic_user status'), default=False)
current_project = models.CharField(_('project_id'), max_length=255)
psw = models.CharField(_('psw'), max_length=36)
token = models.CharField(_('token'), max_length=36)
project_id = models.CharField(_('project_id'), max_length=36)
token_expires = models.FloatField(_('token_expires'), max_length=36)
objects = OsmUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
@property
def is_authenticated(self):
if self.token is not None and utils.is_token_valid({'expires': self.token_expires}):
return True
else:
return False
def get_token(self):
if self.is_authenticated:
return {'id': self.token, 'expires': self.token_expires, 'project_id': self.project_id}
return None
def get_projects(self):
client = Client()
result = client.get_user_info(self.get_token(), self.username)
if 'error' in result and result['error'] is True:
return []
else:
return result['data']['projects']
def switch_project(self, project_id):
client = Client()
result = client.switch_project({'project_id': project_id, 'username': self.username, 'password': self.psw})
if 'error' in result and result['error'] is True:
raise OSMAuthException(result['data'])
else:
self.token = result['data']['id']
self.project_id = result['data']['project_id']
self.token_expires = result['data']['expires']
self.save()
return True
return False
class Meta:
verbose_name = _('custom user')
verbose_name_plural = _('custom users')
abstract = True
class OsmUser(AbstractOsmUser):
class Meta(AbstractOsmUser.Meta):
swappable = 'AUTH_USER_MODEL'
| true
| true
|
790e6890758163cd3fda1f0c4496ccae14411aed
| 8,311
|
py
|
Python
|
pypy/module/test_lib_pypy/ctypes_tests/test_bitfields.py
|
microvm/pypy-mu
|
6b03fbe93052d0eb3a4c67152c987c16837b3484
|
[
"Apache-2.0",
"OpenSSL"
] | 4
|
2019-02-11T06:58:43.000Z
|
2020-03-15T14:12:32.000Z
|
pypy/module/test_lib_pypy/ctypes_tests/test_bitfields.py
|
microvm/pypy-mu
|
6b03fbe93052d0eb3a4c67152c987c16837b3484
|
[
"Apache-2.0",
"OpenSSL"
] | null | null | null |
pypy/module/test_lib_pypy/ctypes_tests/test_bitfields.py
|
microvm/pypy-mu
|
6b03fbe93052d0eb3a4c67152c987c16837b3484
|
[
"Apache-2.0",
"OpenSSL"
] | null | null | null |
import py
from ctypes import *
from support import BaseCTypesTestChecker
import os
import ctypes
signed_int_types = (c_byte, c_short, c_int, c_long, c_longlong)
unsigned_int_types = (c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong)
int_types = unsigned_int_types + signed_int_types
def setup_module(mod):
import conftest
_ctypes_test = str(conftest.sofile)
func = CDLL(_ctypes_test).unpack_bitfields
func.argtypes = POINTER(BITS), c_char
mod.func = func
class BITS(Structure):
_fields_ = [("A", c_int, 1),
("B", c_int, 2),
("C", c_int, 3),
("D", c_int, 4),
("E", c_int, 5),
("F", c_int, 6),
("G", c_int, 7),
("H", c_int, 8),
("I", c_int, 9),
("M", c_short, 1),
("N", c_short, 2),
("O", c_short, 3),
("P", c_short, 4),
("Q", c_short, 5),
("R", c_short, 6),
("S", c_short, 7)]
class TestC:
def test_ints(self):
for i in range(512):
for name in "ABCDEFGHI":
b = BITS()
setattr(b, name, i)
assert (name, i, getattr(b, name)) == (name, i, func(byref(b), name))
def test_shorts(self):
for i in range(256):
for name in "MNOPQRS":
b = BITS()
setattr(b, name, i)
assert (name, i, getattr(b, name)) == (name, i, func(byref(b), name))
class TestBitField:
def test_longlong(self):
class X(Structure):
_fields_ = [("a", c_longlong, 1),
("b", c_longlong, 62),
("c", c_longlong, 1)]
assert sizeof(X) == sizeof(c_longlong)
x = X()
x.a, x.b, x.c = -1, 7, -1
assert (x.a, x.b, x.c) == (-1, 7, -1)
x = X()
x.a, x.b, x.c = -1, -7, -1
assert (x.a, x.b, x.c) == (-1, -7, -1)
def test_ulonglong(self):
class X(Structure):
_fields_ = [("a", c_ulonglong, 1),
("b", c_ulonglong, 62),
("c", c_ulonglong, 1)]
assert sizeof(X) == sizeof(c_longlong)
x = X()
assert (x.a, x.b, x.c) == (0, 0, 0)
x.a, x.b, x.c = 7, 2305843009213693953, 7
assert (x.a, x.b, x.c) == (1, 2305843009213693953, 1)
def test_signed(self):
for c_typ in signed_int_types:
class X(Structure):
_fields_ = [("dummy", c_typ),
("a", c_typ, 3),
("b", c_typ, 3),
("c", c_typ, 1)]
assert sizeof(X) == sizeof(c_typ)*2
x = X()
assert (c_typ, x.a, x.b, x.c) == (c_typ, 0, 0, 0)
x.a = -1
assert (c_typ, x.a, x.b, x.c) == (c_typ, -1, 0, 0)
x.a, x.b = 0, -1
assert (c_typ, x.a, x.b, x.c) == (c_typ, 0, -1, 0)
def test_unsigned(self):
for c_typ in unsigned_int_types:
class X(Structure):
_fields_ = [("a", c_typ, 3),
("b", c_typ, 3),
("c", c_typ, 1)]
assert sizeof(X) == sizeof(c_typ)
x = X()
assert (c_typ, x.a, x.b, x.c) == (c_typ, 0, 0, 0)
x.a = -1
assert (c_typ, x.a, x.b, x.c) == (c_typ, 7, 0, 0)
x.a, x.b = 0, -1
assert (c_typ, x.a, x.b, x.c) == (c_typ, 0, 7, 0)
def fail_fields(self, *fields):
return self.get_except(type(Structure), "X", (),
{"_fields_": fields})
def test_nonint_types(self):
# bit fields are not allowed on non-integer types.
result = self.fail_fields(("a", c_char_p, 1))
assert result == (TypeError, 'bit fields not allowed for type c_char_p')
result = self.fail_fields(("a", c_void_p, 1))
assert result == (TypeError, 'bit fields not allowed for type c_void_p')
if c_int != c_long:
result = self.fail_fields(("a", POINTER(c_int), 1))
assert result == (TypeError, 'bit fields not allowed for type LP_c_int')
result = self.fail_fields(("a", c_char, 1))
assert result == (TypeError, 'bit fields not allowed for type c_char')
try:
c_wchar
except NameError:
pass
else:
result = self.fail_fields(("a", c_wchar, 1))
assert result == (TypeError, 'bit fields not allowed for type c_wchar')
class Dummy(Structure):
_fields_ = []
result = self.fail_fields(("a", Dummy, 1))
assert result == (TypeError, 'bit fields not allowed for type Dummy')
def test_single_bitfield_size(self):
for c_typ in int_types:
result = self.fail_fields(("a", c_typ, -1))
assert result == (ValueError, 'number of bits invalid for bit field')
result = self.fail_fields(("a", c_typ, 0))
assert result == (ValueError, 'number of bits invalid for bit field')
class X(Structure):
_fields_ = [("a", c_typ, 1)]
assert sizeof(X) == sizeof(c_typ)
class X(Structure):
_fields_ = [("a", c_typ, sizeof(c_typ)*8)]
assert sizeof(X) == sizeof(c_typ)
result = self.fail_fields(("a", c_typ, sizeof(c_typ)*8 + 1))
assert result == (ValueError, 'number of bits invalid for bit field')
def test_multi_bitfields_size(self):
class X(Structure):
_fields_ = [("a", c_short, 1),
("b", c_short, 14),
("c", c_short, 1)]
assert sizeof(X) == sizeof(c_short)
class X(Structure):
_fields_ = [("a", c_short, 1),
("a1", c_short),
("b", c_short, 14),
("c", c_short, 1)]
assert sizeof(X) == sizeof(c_short)*3
assert X.a.offset == 0
assert X.a1.offset == sizeof(c_short)
assert X.b.offset == sizeof(c_short)*2
assert X.c.offset == sizeof(c_short)*2
class X(Structure):
_fields_ = [("a", c_short, 3),
("b", c_short, 14),
("c", c_short, 14)]
assert sizeof(X) == sizeof(c_short)*3
assert X.a.offset == sizeof(c_short)*0
assert X.b.offset == sizeof(c_short)*1
assert X.c.offset == sizeof(c_short)*2
def get_except(self, func, *args, **kw):
try:
func(*args, **kw)
except Exception as detail:
import traceback
traceback.print_exc()
return detail.__class__, str(detail)
def test_mixed_1(self):
class X(Structure):
_fields_ = [("a", c_byte, 4),
("b", c_int, 4)]
if os.name in ("nt", "ce"):
assert sizeof(X) == sizeof(c_int)*2
else:
assert sizeof(X) == sizeof(c_int)
def test_mixed_2(self):
class X(Structure):
_fields_ = [("a", c_byte, 4),
("b", c_int, 32)]
assert sizeof(X) == sizeof(c_int)*2
def test_mixed_3(self):
class X(Structure):
_fields_ = [("a", c_byte, 4),
("b", c_ubyte, 4)]
assert sizeof(X) == sizeof(c_byte)
def test_anon_bitfields(self):
# anonymous bit-fields gave a strange error message
class X(Structure):
_fields_ = [("a", c_byte, 4),
("b", c_ubyte, 4)]
class Y(Structure):
_anonymous_ = ["_"]
_fields_ = [("_", X)]
def test_set_fields_attr(self):
class A(Structure):
pass
A._fields_ = [("a", c_byte),
("b", c_ubyte)]
def test_set_fields_attr_bitfields(self):
class A(Structure):
pass
A._fields_ = [("a", POINTER(A)),
("b", c_ubyte, 4)]
def test_set_fields_cycle_fails(self):
class A(Structure):
pass
import pytest
pytest.raises(AttributeError, """
A._fields_ = [("a", A)]
""")
| 32.980159
| 85
| 0.47395
|
import py
from ctypes import *
from support import BaseCTypesTestChecker
import os
import ctypes
signed_int_types = (c_byte, c_short, c_int, c_long, c_longlong)
unsigned_int_types = (c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong)
int_types = unsigned_int_types + signed_int_types
def setup_module(mod):
import conftest
_ctypes_test = str(conftest.sofile)
func = CDLL(_ctypes_test).unpack_bitfields
func.argtypes = POINTER(BITS), c_char
mod.func = func
class BITS(Structure):
_fields_ = [("A", c_int, 1),
("B", c_int, 2),
("C", c_int, 3),
("D", c_int, 4),
("E", c_int, 5),
("F", c_int, 6),
("G", c_int, 7),
("H", c_int, 8),
("I", c_int, 9),
("M", c_short, 1),
("N", c_short, 2),
("O", c_short, 3),
("P", c_short, 4),
("Q", c_short, 5),
("R", c_short, 6),
("S", c_short, 7)]
class TestC:
def test_ints(self):
for i in range(512):
for name in "ABCDEFGHI":
b = BITS()
setattr(b, name, i)
assert (name, i, getattr(b, name)) == (name, i, func(byref(b), name))
def test_shorts(self):
for i in range(256):
for name in "MNOPQRS":
b = BITS()
setattr(b, name, i)
assert (name, i, getattr(b, name)) == (name, i, func(byref(b), name))
class TestBitField:
def test_longlong(self):
class X(Structure):
_fields_ = [("a", c_longlong, 1),
("b", c_longlong, 62),
("c", c_longlong, 1)]
assert sizeof(X) == sizeof(c_longlong)
x = X()
x.a, x.b, x.c = -1, 7, -1
assert (x.a, x.b, x.c) == (-1, 7, -1)
x = X()
x.a, x.b, x.c = -1, -7, -1
assert (x.a, x.b, x.c) == (-1, -7, -1)
def test_ulonglong(self):
class X(Structure):
_fields_ = [("a", c_ulonglong, 1),
("b", c_ulonglong, 62),
("c", c_ulonglong, 1)]
assert sizeof(X) == sizeof(c_longlong)
x = X()
assert (x.a, x.b, x.c) == (0, 0, 0)
x.a, x.b, x.c = 7, 2305843009213693953, 7
assert (x.a, x.b, x.c) == (1, 2305843009213693953, 1)
def test_signed(self):
for c_typ in signed_int_types:
class X(Structure):
_fields_ = [("dummy", c_typ),
("a", c_typ, 3),
("b", c_typ, 3),
("c", c_typ, 1)]
assert sizeof(X) == sizeof(c_typ)*2
x = X()
assert (c_typ, x.a, x.b, x.c) == (c_typ, 0, 0, 0)
x.a = -1
assert (c_typ, x.a, x.b, x.c) == (c_typ, -1, 0, 0)
x.a, x.b = 0, -1
assert (c_typ, x.a, x.b, x.c) == (c_typ, 0, -1, 0)
def test_unsigned(self):
for c_typ in unsigned_int_types:
class X(Structure):
_fields_ = [("a", c_typ, 3),
("b", c_typ, 3),
("c", c_typ, 1)]
assert sizeof(X) == sizeof(c_typ)
x = X()
assert (c_typ, x.a, x.b, x.c) == (c_typ, 0, 0, 0)
x.a = -1
assert (c_typ, x.a, x.b, x.c) == (c_typ, 7, 0, 0)
x.a, x.b = 0, -1
assert (c_typ, x.a, x.b, x.c) == (c_typ, 0, 7, 0)
def fail_fields(self, *fields):
return self.get_except(type(Structure), "X", (),
{"_fields_": fields})
def test_nonint_types(self):
result = self.fail_fields(("a", c_char_p, 1))
assert result == (TypeError, 'bit fields not allowed for type c_char_p')
result = self.fail_fields(("a", c_void_p, 1))
assert result == (TypeError, 'bit fields not allowed for type c_void_p')
if c_int != c_long:
result = self.fail_fields(("a", POINTER(c_int), 1))
assert result == (TypeError, 'bit fields not allowed for type LP_c_int')
result = self.fail_fields(("a", c_char, 1))
assert result == (TypeError, 'bit fields not allowed for type c_char')
try:
c_wchar
except NameError:
pass
else:
result = self.fail_fields(("a", c_wchar, 1))
assert result == (TypeError, 'bit fields not allowed for type c_wchar')
class Dummy(Structure):
_fields_ = []
result = self.fail_fields(("a", Dummy, 1))
assert result == (TypeError, 'bit fields not allowed for type Dummy')
def test_single_bitfield_size(self):
for c_typ in int_types:
result = self.fail_fields(("a", c_typ, -1))
assert result == (ValueError, 'number of bits invalid for bit field')
result = self.fail_fields(("a", c_typ, 0))
assert result == (ValueError, 'number of bits invalid for bit field')
class X(Structure):
_fields_ = [("a", c_typ, 1)]
assert sizeof(X) == sizeof(c_typ)
class X(Structure):
_fields_ = [("a", c_typ, sizeof(c_typ)*8)]
assert sizeof(X) == sizeof(c_typ)
result = self.fail_fields(("a", c_typ, sizeof(c_typ)*8 + 1))
assert result == (ValueError, 'number of bits invalid for bit field')
def test_multi_bitfields_size(self):
class X(Structure):
_fields_ = [("a", c_short, 1),
("b", c_short, 14),
("c", c_short, 1)]
assert sizeof(X) == sizeof(c_short)
class X(Structure):
_fields_ = [("a", c_short, 1),
("a1", c_short),
("b", c_short, 14),
("c", c_short, 1)]
assert sizeof(X) == sizeof(c_short)*3
assert X.a.offset == 0
assert X.a1.offset == sizeof(c_short)
assert X.b.offset == sizeof(c_short)*2
assert X.c.offset == sizeof(c_short)*2
class X(Structure):
_fields_ = [("a", c_short, 3),
("b", c_short, 14),
("c", c_short, 14)]
assert sizeof(X) == sizeof(c_short)*3
assert X.a.offset == sizeof(c_short)*0
assert X.b.offset == sizeof(c_short)*1
assert X.c.offset == sizeof(c_short)*2
def get_except(self, func, *args, **kw):
try:
func(*args, **kw)
except Exception as detail:
import traceback
traceback.print_exc()
return detail.__class__, str(detail)
def test_mixed_1(self):
class X(Structure):
_fields_ = [("a", c_byte, 4),
("b", c_int, 4)]
if os.name in ("nt", "ce"):
assert sizeof(X) == sizeof(c_int)*2
else:
assert sizeof(X) == sizeof(c_int)
def test_mixed_2(self):
class X(Structure):
_fields_ = [("a", c_byte, 4),
("b", c_int, 32)]
assert sizeof(X) == sizeof(c_int)*2
def test_mixed_3(self):
class X(Structure):
_fields_ = [("a", c_byte, 4),
("b", c_ubyte, 4)]
assert sizeof(X) == sizeof(c_byte)
def test_anon_bitfields(self):
class X(Structure):
_fields_ = [("a", c_byte, 4),
("b", c_ubyte, 4)]
class Y(Structure):
_anonymous_ = ["_"]
_fields_ = [("_", X)]
def test_set_fields_attr(self):
class A(Structure):
pass
A._fields_ = [("a", c_byte),
("b", c_ubyte)]
def test_set_fields_attr_bitfields(self):
class A(Structure):
pass
A._fields_ = [("a", POINTER(A)),
("b", c_ubyte, 4)]
def test_set_fields_cycle_fails(self):
class A(Structure):
pass
import pytest
pytest.raises(AttributeError, """
A._fields_ = [("a", A)]
""")
| true
| true
|
790e69307b517e5850779f3ab10406fbba52eff4
| 2,582
|
py
|
Python
|
tests/test_prep_manager.py
|
Transcranial-Solutions/t-bears
|
4712b8bb425814c444ee75f3220a31df934982aa
|
[
"Apache-2.0"
] | 35
|
2018-08-24T03:39:35.000Z
|
2021-08-21T23:35:57.000Z
|
tests/test_prep_manager.py
|
Transcranial-Solutions/t-bears
|
4712b8bb425814c444ee75f3220a31df934982aa
|
[
"Apache-2.0"
] | 40
|
2018-08-24T05:35:54.000Z
|
2021-12-15T08:23:38.000Z
|
tests/test_prep_manager.py
|
Transcranial-Solutions/t-bears
|
4712b8bb425814c444ee75f3220a31df934982aa
|
[
"Apache-2.0"
] | 22
|
2018-08-28T15:11:46.000Z
|
2021-12-01T23:34:45.000Z
|
# -*- coding: utf-8 -*-
# Copyright 2017-2018 ICON Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from tbears.block_manager.block_manager import PRepManager
from tbears.config.tbears_config import keystore_test1
PREP_LIST = [
{
"id": "hx86aba2210918a9b116973f3c4b27c41a54d5dafe",
"publicKey": "04a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26",
"p2pEndPoint": "target://123.45.67.89:7100"
},
{
"id": "hx13aca3210918a9b116973f3c4b27c41a54d5dad1",
"publicKey": "0483ae642ca89c9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281e3a27",
"p2pEndPoint": "target://210.34.56.17:7100"
}
]
class TestTBearsPRepManager(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_get_prev_block_contributors_info(self):
# There is no P-Reps
manager = PRepManager(is_generator_rotation=True, gen_count_per_leader=1)
info = manager.get_prev_block_contributors_info()
self.assertEqual(keystore_test1.get('address'), info.get('prevBlockGenerator'))
self.assertEqual(0, len(info.get('prevBlockValidators')))
# There is 2 P-Reps
manager = PRepManager(is_generator_rotation=True, gen_count_per_leader=1, prep_list=PREP_LIST)
info = manager.get_prev_block_contributors_info()
self.assertEqual(PREP_LIST[0].get('id'), info.get('prevBlockGenerator'))
self.assertEqual(len(PREP_LIST) - 1, len(info.get('prevBlockValidators')))
self.assertEqual(PREP_LIST[1].get('id'), info.get('prevBlockValidators')[0])
# after rotate
info = manager.get_prev_block_contributors_info()
self.assertEqual(PREP_LIST[1].get('id'), info.get('prevBlockGenerator'))
self.assertEqual(len(PREP_LIST) - 1, len(info.get('prevBlockValidators')))
self.assertEqual(PREP_LIST[0].get('id'), info.get('prevBlockValidators')[0])
| 41.645161
| 154
| 0.731603
|
import unittest
from tbears.block_manager.block_manager import PRepManager
from tbears.config.tbears_config import keystore_test1
PREP_LIST = [
{
"id": "hx86aba2210918a9b116973f3c4b27c41a54d5dafe",
"publicKey": "04a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26",
"p2pEndPoint": "target://123.45.67.89:7100"
},
{
"id": "hx13aca3210918a9b116973f3c4b27c41a54d5dad1",
"publicKey": "0483ae642ca89c9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281e3a27",
"p2pEndPoint": "target://210.34.56.17:7100"
}
]
class TestTBearsPRepManager(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_get_prev_block_contributors_info(self):
manager = PRepManager(is_generator_rotation=True, gen_count_per_leader=1)
info = manager.get_prev_block_contributors_info()
self.assertEqual(keystore_test1.get('address'), info.get('prevBlockGenerator'))
self.assertEqual(0, len(info.get('prevBlockValidators')))
manager = PRepManager(is_generator_rotation=True, gen_count_per_leader=1, prep_list=PREP_LIST)
info = manager.get_prev_block_contributors_info()
self.assertEqual(PREP_LIST[0].get('id'), info.get('prevBlockGenerator'))
self.assertEqual(len(PREP_LIST) - 1, len(info.get('prevBlockValidators')))
self.assertEqual(PREP_LIST[1].get('id'), info.get('prevBlockValidators')[0])
info = manager.get_prev_block_contributors_info()
self.assertEqual(PREP_LIST[1].get('id'), info.get('prevBlockGenerator'))
self.assertEqual(len(PREP_LIST) - 1, len(info.get('prevBlockValidators')))
self.assertEqual(PREP_LIST[0].get('id'), info.get('prevBlockValidators')[0])
| true
| true
|
790e694a4377c119090144e982153fce7e3aaae2
| 814
|
py
|
Python
|
gooddata-afm-client/gooddata_afm_client/__init__.py
|
jaceksan/gooddata-python-sdk
|
640bd8b679e00a5f0eb627bdf6143de078f8b59b
|
[
"MIT"
] | null | null | null |
gooddata-afm-client/gooddata_afm_client/__init__.py
|
jaceksan/gooddata-python-sdk
|
640bd8b679e00a5f0eb627bdf6143de078f8b59b
|
[
"MIT"
] | null | null | null |
gooddata-afm-client/gooddata_afm_client/__init__.py
|
jaceksan/gooddata-python-sdk
|
640bd8b679e00a5f0eb627bdf6143de078f8b59b
|
[
"MIT"
] | null | null | null |
# flake8: noqa
"""
OpenAPI definition
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v0
Generated by: https://openapi-generator.tech
"""
__version__ = "0.6.0"
# import ApiClient
from gooddata_afm_client.api_client import ApiClient
# import Configuration
from gooddata_afm_client.configuration import Configuration
# import exceptions
from gooddata_afm_client.exceptions import OpenApiException
from gooddata_afm_client.exceptions import ApiAttributeError
from gooddata_afm_client.exceptions import ApiTypeError
from gooddata_afm_client.exceptions import ApiValueError
from gooddata_afm_client.exceptions import ApiKeyError
from gooddata_afm_client.exceptions import ApiException
| 29.071429
| 124
| 0.829238
|
__version__ = "0.6.0"
from gooddata_afm_client.api_client import ApiClient
from gooddata_afm_client.configuration import Configuration
from gooddata_afm_client.exceptions import OpenApiException
from gooddata_afm_client.exceptions import ApiAttributeError
from gooddata_afm_client.exceptions import ApiTypeError
from gooddata_afm_client.exceptions import ApiValueError
from gooddata_afm_client.exceptions import ApiKeyError
from gooddata_afm_client.exceptions import ApiException
| true
| true
|
790e6aeaed48e237d93e3acae13c96381715b42a
| 1,558
|
py
|
Python
|
pytglib/api/types/page_block_related_article.py
|
iTeam-co/pytglib
|
e5e75e0a85f89b77762209b32a61b0a883c0ae61
|
[
"MIT"
] | 6
|
2019-10-30T08:57:27.000Z
|
2021-02-08T14:17:43.000Z
|
pytglib/api/types/page_block_related_article.py
|
iTeam-co/python-telegram
|
e5e75e0a85f89b77762209b32a61b0a883c0ae61
|
[
"MIT"
] | 1
|
2021-08-19T05:44:10.000Z
|
2021-08-19T07:14:56.000Z
|
pytglib/api/types/page_block_related_article.py
|
iTeam-co/python-telegram
|
e5e75e0a85f89b77762209b32a61b0a883c0ae61
|
[
"MIT"
] | 5
|
2019-12-04T05:30:39.000Z
|
2021-05-21T18:23:32.000Z
|
from ..utils import Object
class PageBlockRelatedArticle(Object):
"""
Contains information about a related article
Attributes:
ID (:obj:`str`): ``PageBlockRelatedArticle``
Args:
url (:obj:`str`):
Related article URL
title (:obj:`str`):
Article title; may be empty
description (:obj:`str`):
Article description; may be empty
photo (:class:`telegram.api.types.photo`):
Article photo; may be null
author (:obj:`str`):
Article author; may be empty
publish_date (:obj:`int`):
Point in time (Unix timestamp) when the article was published; 0 if unknown
Returns:
PageBlockRelatedArticle
Raises:
:class:`telegram.Error`
"""
ID = "pageBlockRelatedArticle"
def __init__(self, url, title, description, photo, author, publish_date, **kwargs):
self.url = url # str
self.title = title # str
self.description = description # str
self.photo = photo # Photo
self.author = author # str
self.publish_date = publish_date # int
@staticmethod
def read(q: dict, *args) -> "PageBlockRelatedArticle":
url = q.get('url')
title = q.get('title')
description = q.get('description')
photo = Object.read(q.get('photo'))
author = q.get('author')
publish_date = q.get('publish_date')
return PageBlockRelatedArticle(url, title, description, photo, author, publish_date)
| 29.396226
| 92
| 0.589217
|
from ..utils import Object
class PageBlockRelatedArticle(Object):
ID = "pageBlockRelatedArticle"
def __init__(self, url, title, description, photo, author, publish_date, **kwargs):
self.url = url
self.title = title
self.description = description
self.photo = photo
self.author = author
self.publish_date = publish_date
@staticmethod
def read(q: dict, *args) -> "PageBlockRelatedArticle":
url = q.get('url')
title = q.get('title')
description = q.get('description')
photo = Object.read(q.get('photo'))
author = q.get('author')
publish_date = q.get('publish_date')
return PageBlockRelatedArticle(url, title, description, photo, author, publish_date)
| true
| true
|
790e6afe5f02236b00d9c67b7b25a881e07abace
| 2,853
|
py
|
Python
|
python/paddle/fluid/tests/unittests/test_while_op.py
|
skylarch/Paddle
|
d58d8df6f5f7aa6fd2f0780f87475055db57a80d
|
[
"Apache-2.0"
] | null | null | null |
python/paddle/fluid/tests/unittests/test_while_op.py
|
skylarch/Paddle
|
d58d8df6f5f7aa6fd2f0780f87475055db57a80d
|
[
"Apache-2.0"
] | null | null | null |
python/paddle/fluid/tests/unittests/test_while_op.py
|
skylarch/Paddle
|
d58d8df6f5f7aa6fd2f0780f87475055db57a80d
|
[
"Apache-2.0"
] | null | null | null |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import paddle.fluid.layers as layers
from paddle.fluid.executor import Executor
import paddle.fluid.core as core
from paddle.fluid.backward import append_backward
import numpy
class TestWhileOp(unittest.TestCase):
def test_simple_forward(self):
d0 = layers.data(
"d0", shape=[10], append_batch_size=False, dtype='float32')
d1 = layers.data(
"d1", shape=[10], append_batch_size=False, dtype='float32')
d2 = layers.data(
"d2", shape=[10], append_batch_size=False, dtype='float32')
i = layers.zeros(shape=[1], dtype='int64')
i.stop_gradient = True
init = layers.zeros(shape=[10], dtype='float32')
mem_array = layers.array_write(x=init, i=i)
data_array = layers.array_write(x=d0, i=i)
i = layers.increment(i)
layers.array_write(d1, i, array=data_array)
i = layers.increment(i)
layers.array_write(d2, i, array=data_array)
i = layers.zeros(shape=[1], dtype='int64')
i.stop_gradient = True
array_len = layers.fill_constant(shape=[1], dtype='int64', value=3)
array_len.stop_gradient = True
cond = layers.less_than(x=i, y=array_len)
while_op = layers.While(cond=cond)
with while_op.block():
d = layers.array_read(array=data_array, i=i)
prev = layers.array_read(array=mem_array, i=i)
result = layers.sums(input=[d, prev])
i = layers.increment(x=i, in_place=True)
layers.array_write(result, i=i, array=mem_array)
layers.less_than(x=i, y=array_len, cond=cond)
sum_result = layers.array_read(array=mem_array, i=i)
loss = layers.mean(sum_result)
append_backward(loss)
cpu = core.CPUPlace()
exe = Executor(cpu)
d = []
for i in range(3):
d.append(numpy.random.random(size=[10]).astype('float32'))
outs = exe.run(feed={'d0': d[0],
'd1': d[1],
'd2': d[2]},
fetch_list=[sum_result])
self.assertAlmostEqual(numpy.sum(d), numpy.sum(outs[0]), delta=0.01)
if __name__ == '__main__':
unittest.main()
| 35.222222
| 76
| 0.629513
|
import unittest
import paddle.fluid.layers as layers
from paddle.fluid.executor import Executor
import paddle.fluid.core as core
from paddle.fluid.backward import append_backward
import numpy
class TestWhileOp(unittest.TestCase):
def test_simple_forward(self):
d0 = layers.data(
"d0", shape=[10], append_batch_size=False, dtype='float32')
d1 = layers.data(
"d1", shape=[10], append_batch_size=False, dtype='float32')
d2 = layers.data(
"d2", shape=[10], append_batch_size=False, dtype='float32')
i = layers.zeros(shape=[1], dtype='int64')
i.stop_gradient = True
init = layers.zeros(shape=[10], dtype='float32')
mem_array = layers.array_write(x=init, i=i)
data_array = layers.array_write(x=d0, i=i)
i = layers.increment(i)
layers.array_write(d1, i, array=data_array)
i = layers.increment(i)
layers.array_write(d2, i, array=data_array)
i = layers.zeros(shape=[1], dtype='int64')
i.stop_gradient = True
array_len = layers.fill_constant(shape=[1], dtype='int64', value=3)
array_len.stop_gradient = True
cond = layers.less_than(x=i, y=array_len)
while_op = layers.While(cond=cond)
with while_op.block():
d = layers.array_read(array=data_array, i=i)
prev = layers.array_read(array=mem_array, i=i)
result = layers.sums(input=[d, prev])
i = layers.increment(x=i, in_place=True)
layers.array_write(result, i=i, array=mem_array)
layers.less_than(x=i, y=array_len, cond=cond)
sum_result = layers.array_read(array=mem_array, i=i)
loss = layers.mean(sum_result)
append_backward(loss)
cpu = core.CPUPlace()
exe = Executor(cpu)
d = []
for i in range(3):
d.append(numpy.random.random(size=[10]).astype('float32'))
outs = exe.run(feed={'d0': d[0],
'd1': d[1],
'd2': d[2]},
fetch_list=[sum_result])
self.assertAlmostEqual(numpy.sum(d), numpy.sum(outs[0]), delta=0.01)
if __name__ == '__main__':
unittest.main()
| true
| true
|
790e6b341b98fcabe4870ecf271e0c5e7fe03c82
| 3,467
|
py
|
Python
|
baselines/scripts/segvae/models/networks/normalization.py
|
atmacvit/meronymnet
|
47e1a7caadc0f770439bb26a93b885f790f62804
|
[
"MIT"
] | 1
|
2021-11-02T05:13:12.000Z
|
2021-11-02T05:13:12.000Z
|
baselines/scripts/segvae/models/networks/normalization.py
|
atmacvit/meronymnet
|
47e1a7caadc0f770439bb26a93b885f790f62804
|
[
"MIT"
] | 1
|
2021-12-17T14:29:18.000Z
|
2021-12-17T14:29:18.000Z
|
baselines/scripts/segvae/models/networks/normalization.py
|
atmacvit/meronymnet
|
47e1a7caadc0f770439bb26a93b885f790f62804
|
[
"MIT"
] | null | null | null |
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.networks.sync_batchnorm import SynchronizedBatchNorm2d
import torch.nn.utils.spectral_norm as spectral_norm
# Returns a function that creates a normalization function
# that does not condition on semantic map
def get_nonspade_norm_layer(opt, norm_type='instance'):
# helper function to get # output channels of the previous layer
def get_out_channel(layer):
if hasattr(layer, 'out_channels'):
return getattr(layer, 'out_channels')
return layer.weight.size(0)
# this function will be returned
def add_norm_layer(layer):
nonlocal norm_type
if norm_type.startswith('spectral'):
layer = spectral_norm(layer)
subnorm_type = norm_type[len('spectral'):]
if subnorm_type == 'none' or len(subnorm_type) == 0:
return layer
# remove bias in the previous layer, which is meaningless
# since it has no effect after normalization
if getattr(layer, 'bias', None) is not None:
delattr(layer, 'bias')
layer.register_parameter('bias', None)
if subnorm_type == 'batch':
norm_layer = nn.BatchNorm2d(get_out_channel(layer), affine=True)
elif subnorm_type == 'sync_batch':
norm_layer = SynchronizedBatchNorm2d(get_out_channel(layer), affine=True)
elif subnorm_type == 'instance':
norm_layer = nn.InstanceNorm2d(get_out_channel(layer), affine=False)
else:
raise ValueError('normalization layer %s is not recognized' % subnorm_type)
return nn.Sequential(layer, norm_layer)
return add_norm_layer
class SPADE(nn.Module):
def __init__(self, config_text, norm_nc, label_nc):
super().__init__()
assert config_text.startswith('spade')
parsed = re.search('spade(\D+)(\d)x\d', config_text)
param_free_norm_type = str(parsed.group(1))
ks = int(parsed.group(2))
if param_free_norm_type == 'instance':
self.param_free_norm = nn.InstanceNorm2d(norm_nc, affine=False)
elif param_free_norm_type == 'syncbatch':
self.param_free_norm = SynchronizedBatchNorm2d(norm_nc, affine=False)
elif param_free_norm_type == 'batch':
self.param_free_norm = nn.BatchNorm2d(norm_nc, affine=False)
else:
raise ValueError('%s is not a recognized param-free norm type in SPADE'
% param_free_norm_type)
# The dimension of the intermediate embedding space. Yes, hardcoded.
nhidden = 128
pw = ks // 2
self.mlp_shared = nn.Sequential(
nn.Conv2d(label_nc, nhidden, kernel_size=ks, padding=pw),
nn.ReLU()
)
self.mlp_gamma = nn.Conv2d(nhidden, norm_nc, kernel_size=ks, padding=pw)
self.mlp_beta = nn.Conv2d(nhidden, norm_nc, kernel_size=ks, padding=pw)
def forward(self, x, segmap):
# Part 1. generate parameter-free normalized activations
normalized = self.param_free_norm(x)
# Part 2. produce scaling and bias conditioned on semantic map
segmap = F.interpolate(segmap, size=x.size()[2:], mode='nearest')
actv = self.mlp_shared(segmap)
gamma = self.mlp_gamma(actv)
beta = self.mlp_beta(actv)
# apply scale and bias
out = normalized * (1 + gamma) + beta
return out
| 38.098901
| 87
| 0.651284
|
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.networks.sync_batchnorm import SynchronizedBatchNorm2d
import torch.nn.utils.spectral_norm as spectral_norm
def get_nonspade_norm_layer(opt, norm_type='instance'):
if hasattr(layer, 'out_channels'):
return getattr(layer, 'out_channels')
return layer.weight.size(0)
def add_norm_layer(layer):
nonlocal norm_type
if norm_type.startswith('spectral'):
layer = spectral_norm(layer)
subnorm_type = norm_type[len('spectral'):]
if subnorm_type == 'none' or len(subnorm_type) == 0:
return layer
if getattr(layer, 'bias', None) is not None:
delattr(layer, 'bias')
layer.register_parameter('bias', None)
if subnorm_type == 'batch':
norm_layer = nn.BatchNorm2d(get_out_channel(layer), affine=True)
elif subnorm_type == 'sync_batch':
norm_layer = SynchronizedBatchNorm2d(get_out_channel(layer), affine=True)
elif subnorm_type == 'instance':
norm_layer = nn.InstanceNorm2d(get_out_channel(layer), affine=False)
else:
raise ValueError('normalization layer %s is not recognized' % subnorm_type)
return nn.Sequential(layer, norm_layer)
return add_norm_layer
class SPADE(nn.Module):
def __init__(self, config_text, norm_nc, label_nc):
super().__init__()
assert config_text.startswith('spade')
parsed = re.search('spade(\D+)(\d)x\d', config_text)
param_free_norm_type = str(parsed.group(1))
ks = int(parsed.group(2))
if param_free_norm_type == 'instance':
self.param_free_norm = nn.InstanceNorm2d(norm_nc, affine=False)
elif param_free_norm_type == 'syncbatch':
self.param_free_norm = SynchronizedBatchNorm2d(norm_nc, affine=False)
elif param_free_norm_type == 'batch':
self.param_free_norm = nn.BatchNorm2d(norm_nc, affine=False)
else:
raise ValueError('%s is not a recognized param-free norm type in SPADE'
% param_free_norm_type)
nhidden = 128
pw = ks // 2
self.mlp_shared = nn.Sequential(
nn.Conv2d(label_nc, nhidden, kernel_size=ks, padding=pw),
nn.ReLU()
)
self.mlp_gamma = nn.Conv2d(nhidden, norm_nc, kernel_size=ks, padding=pw)
self.mlp_beta = nn.Conv2d(nhidden, norm_nc, kernel_size=ks, padding=pw)
def forward(self, x, segmap):
normalized = self.param_free_norm(x)
segmap = F.interpolate(segmap, size=x.size()[2:], mode='nearest')
actv = self.mlp_shared(segmap)
gamma = self.mlp_gamma(actv)
beta = self.mlp_beta(actv)
out = normalized * (1 + gamma) + beta
return out
| true
| true
|
790e6b57221b260f6e51419db22576bea765eb79
| 1,547
|
py
|
Python
|
src/wallet/wallet.py
|
MikitaSaladukha/my-blockchain
|
c09091762dc559d41b8aa29fbe8267aff834a57c
|
[
"Apache-2.0"
] | null | null | null |
src/wallet/wallet.py
|
MikitaSaladukha/my-blockchain
|
c09091762dc559d41b8aa29fbe8267aff834a57c
|
[
"Apache-2.0"
] | null | null | null |
src/wallet/wallet.py
|
MikitaSaladukha/my-blockchain
|
c09091762dc559d41b8aa29fbe8267aff834a57c
|
[
"Apache-2.0"
] | null | null | null |
import binascii
import requests
from Crypto.PublicKey import RSA
from common.transaction import Transaction
from common.transaction_input import TransactionInput
from common.transaction_output import TransactionOutput
from common.utils import calculate_hash
class Owner:
def __init__(self, private_key: str = ""):
if private_key:
self.private_key = RSA.importKey(private_key)
else:
self.private_key = RSA.generate(2048)
public_key = self.private_key.publickey().export_key("DER")
self.public_key_hex = binascii.hexlify(public_key).decode("utf-8")
self.public_key_hash = calculate_hash(calculate_hash(self.public_key_hex, hash_function="sha256"),
hash_function="ripemd160")
class Node:
def __init__(self):
ip = "127.0.0.1"
port = 5000
self.base_url = f"http://{ip}:{port}/"
def send(self, transaction_data: dict) -> requests.Response:
url = f"{self.base_url}transactions"
req_return = requests.post(url, json=transaction_data)
req_return.raise_for_status()
return req_return
class Wallet:
def __init__(self, owner: Owner):
self.owner = owner
self.node = Node()
def process_transaction(self, inputs: [TransactionInput], outputs: [TransactionOutput]) -> requests.Response:
transaction = Transaction(inputs, outputs)
transaction.sign(self.owner)
return self.node.send({"transaction": transaction.transaction_data})
| 33.630435
| 113
| 0.678087
|
import binascii
import requests
from Crypto.PublicKey import RSA
from common.transaction import Transaction
from common.transaction_input import TransactionInput
from common.transaction_output import TransactionOutput
from common.utils import calculate_hash
class Owner:
def __init__(self, private_key: str = ""):
if private_key:
self.private_key = RSA.importKey(private_key)
else:
self.private_key = RSA.generate(2048)
public_key = self.private_key.publickey().export_key("DER")
self.public_key_hex = binascii.hexlify(public_key).decode("utf-8")
self.public_key_hash = calculate_hash(calculate_hash(self.public_key_hex, hash_function="sha256"),
hash_function="ripemd160")
class Node:
def __init__(self):
ip = "127.0.0.1"
port = 5000
self.base_url = f"http://{ip}:{port}/"
def send(self, transaction_data: dict) -> requests.Response:
url = f"{self.base_url}transactions"
req_return = requests.post(url, json=transaction_data)
req_return.raise_for_status()
return req_return
class Wallet:
def __init__(self, owner: Owner):
self.owner = owner
self.node = Node()
def process_transaction(self, inputs: [TransactionInput], outputs: [TransactionOutput]) -> requests.Response:
transaction = Transaction(inputs, outputs)
transaction.sign(self.owner)
return self.node.send({"transaction": transaction.transaction_data})
| true
| true
|
790e6c0828b1fab68913cce7fbb1b9224435ad13
| 364
|
py
|
Python
|
third_party/antlr_grammars_v4/sql/plsql/Python3/PlSqlBaseParser.py
|
mikhan808/rsyntaxtextarea-antlr4-extension
|
be6a7881e0f6e1a5e8c8e65f7ca4898a2298aa77
|
[
"BSD-3-Clause"
] | 4
|
2020-10-14T13:44:57.000Z
|
2021-07-08T00:54:33.000Z
|
third_party/antlr_grammars_v4/sql/plsql/Python3/PlSqlBaseParser.py
|
mikhan808/rsyntaxtextarea-antlr4-extension
|
be6a7881e0f6e1a5e8c8e65f7ca4898a2298aa77
|
[
"BSD-3-Clause"
] | null | null | null |
third_party/antlr_grammars_v4/sql/plsql/Python3/PlSqlBaseParser.py
|
mikhan808/rsyntaxtextarea-antlr4-extension
|
be6a7881e0f6e1a5e8c8e65f7ca4898a2298aa77
|
[
"BSD-3-Clause"
] | 2
|
2021-09-06T08:50:58.000Z
|
2021-09-16T11:37:27.000Z
|
from antlr4 import *
class PlSqlBaseParser(Parser):
_isVersion10 = False
_isVersion12 = True
def isVersion10(self):
return self._isVersion10
def isVersion12(self):
return self._isVersion12
def setVersion10(self, value):
self._isVersion10 = value
def setVersion12(self, value):
self._isVersion12 = value
| 20.222222
| 34
| 0.673077
|
from antlr4 import *
class PlSqlBaseParser(Parser):
_isVersion10 = False
_isVersion12 = True
def isVersion10(self):
return self._isVersion10
def isVersion12(self):
return self._isVersion12
def setVersion10(self, value):
self._isVersion10 = value
def setVersion12(self, value):
self._isVersion12 = value
| true
| true
|
790e6d438e22ff30321e479ffbce3f43c0e787a0
| 3,826
|
py
|
Python
|
varfish_cli/__main__.py
|
bihealth/varfish-cli
|
e2b56ef8a158cc7fbe523cbd1c02f13cff8682e5
|
[
"MIT"
] | 2
|
2020-09-24T08:01:03.000Z
|
2022-03-23T15:49:13.000Z
|
varfish_cli/__main__.py
|
bihealth/varfish-cli
|
e2b56ef8a158cc7fbe523cbd1c02f13cff8682e5
|
[
"MIT"
] | 9
|
2021-02-16T21:07:35.000Z
|
2022-03-24T13:36:07.000Z
|
varfish_cli/__main__.py
|
bihealth/varfish-cli
|
e2b56ef8a158cc7fbe523cbd1c02f13cff8682e5
|
[
"MIT"
] | 2
|
2022-03-23T15:06:19.000Z
|
2022-03-23T15:49:17.000Z
|
"""Main entry point for VarFish CLI."""
import argparse
import logging
import os
import sys
import logzero
import toml
from logzero import logger
from varfish_cli import __version__
from .common import run_nocmd, CommonConfig
from .case import setup_argparse as setup_argparse_case
from .case import run as run_case
#: Paths to search the global configuration in.
GLOBAL_CONFIG_PATHS = ("~/.varfishrc.toml",)
def setup_argparse_only(): # pragma: nocover
"""Wrapper for ``setup_argparse()`` that only returns the parser.
Only used in sphinx documentation via ``sphinx-argparse``.
"""
return setup_argparse()[0]
def setup_argparse():
"""Create argument parser."""
# Construct argument parser and set global options.
parser = argparse.ArgumentParser(prog="varfish-cli")
parser.add_argument("--verbose", action="store_true", default=False, help="Increase verbosity.")
parser.add_argument("--version", action="version", version="%%(prog)s %s" % __version__)
group = parser.add_argument_group("Basic Configuration")
group.add_argument(
"--no-verify-ssl",
dest="verify_ssl",
default=True,
action="store_false",
help="Disable HTTPS SSL verification",
)
group.add_argument(
"--config",
default=os.environ.get("VARFISH_CONFIG_PATH", None),
help="Path to configuration file.",
)
group.add_argument(
"--varfish-server-url",
default=os.environ.get("VARFISH_SERVER_URL", None),
help="VarFish server URL key to use, defaults to env VARFISH_SERVER_URL.",
)
group.add_argument(
"--varfish-api-token",
default=os.environ.get("VARFISH_API_TOKEN", None),
help="VarFish API token to use, defaults to env VARFISH_API_TOKEN.",
)
# Add sub parsers for each argument.
subparsers = parser.add_subparsers(dest="cmd")
setup_argparse_case(subparsers.add_parser("case", help="Work with cases."))
return parser, subparsers
def main(argv=None):
"""Main entry point before parsing command line arguments."""
# Setup command line parser.
parser, subparsers = setup_argparse()
# Actually parse command line arguments.
args = parser.parse_args(argv)
# Setup logging incl. verbosity.
if args.verbose: # pragma: no cover
level = logging.DEBUG
else:
# Remove module name and line number if not running in debug mode.s
formatter = logzero.LogFormatter(
fmt="%(color)s[%(levelname)1.1s %(asctime)s]%(end_color)s %(message)s"
)
logzero.formatter(formatter)
level = logging.INFO
logzero.loglevel(level=level)
# Load configuration, if any.
if args.config:
config_paths = (args.config,)
else:
config_paths = GLOBAL_CONFIG_PATHS
for config_path in config_paths:
config_path = os.path.expanduser(os.path.expandvars(config_path))
if os.path.exists(config_path):
with open(config_path, "rt") as tomlf:
toml_config = toml.load(tomlf)
break
else:
toml_config = None
logger.info("Could not find any of the global configuration files %s.", config_paths)
# Merge configuration from command line/environment args and configuration file.
config = CommonConfig.create(args, toml_config)
# Handle the actual command line.
cmds = {None: run_nocmd, "case": run_case}
res = cmds[args.cmd](
config, toml_config, args, parser, subparsers.choices[args.cmd] if args.cmd else None
)
if not res:
logger.info("All done. Have a nice day!")
else: # pragma: nocover
logger.error("Something did not work out correctly.")
return res
if __name__ == "__main__": # pragma: no cover
sys.exit(main(sys.argv))
| 31.619835
| 100
| 0.669106
|
import argparse
import logging
import os
import sys
import logzero
import toml
from logzero import logger
from varfish_cli import __version__
from .common import run_nocmd, CommonConfig
from .case import setup_argparse as setup_argparse_case
from .case import run as run_case
GLOBAL_CONFIG_PATHS = ("~/.varfishrc.toml",)
def setup_argparse_only():
return setup_argparse()[0]
def setup_argparse():
parser = argparse.ArgumentParser(prog="varfish-cli")
parser.add_argument("--verbose", action="store_true", default=False, help="Increase verbosity.")
parser.add_argument("--version", action="version", version="%%(prog)s %s" % __version__)
group = parser.add_argument_group("Basic Configuration")
group.add_argument(
"--no-verify-ssl",
dest="verify_ssl",
default=True,
action="store_false",
help="Disable HTTPS SSL verification",
)
group.add_argument(
"--config",
default=os.environ.get("VARFISH_CONFIG_PATH", None),
help="Path to configuration file.",
)
group.add_argument(
"--varfish-server-url",
default=os.environ.get("VARFISH_SERVER_URL", None),
help="VarFish server URL key to use, defaults to env VARFISH_SERVER_URL.",
)
group.add_argument(
"--varfish-api-token",
default=os.environ.get("VARFISH_API_TOKEN", None),
help="VarFish API token to use, defaults to env VARFISH_API_TOKEN.",
)
subparsers = parser.add_subparsers(dest="cmd")
setup_argparse_case(subparsers.add_parser("case", help="Work with cases."))
return parser, subparsers
def main(argv=None):
parser, subparsers = setup_argparse()
args = parser.parse_args(argv)
if args.verbose:
level = logging.DEBUG
else:
formatter = logzero.LogFormatter(
fmt="%(color)s[%(levelname)1.1s %(asctime)s]%(end_color)s %(message)s"
)
logzero.formatter(formatter)
level = logging.INFO
logzero.loglevel(level=level)
if args.config:
config_paths = (args.config,)
else:
config_paths = GLOBAL_CONFIG_PATHS
for config_path in config_paths:
config_path = os.path.expanduser(os.path.expandvars(config_path))
if os.path.exists(config_path):
with open(config_path, "rt") as tomlf:
toml_config = toml.load(tomlf)
break
else:
toml_config = None
logger.info("Could not find any of the global configuration files %s.", config_paths)
config = CommonConfig.create(args, toml_config)
cmds = {None: run_nocmd, "case": run_case}
res = cmds[args.cmd](
config, toml_config, args, parser, subparsers.choices[args.cmd] if args.cmd else None
)
if not res:
logger.info("All done. Have a nice day!")
else:
logger.error("Something did not work out correctly.")
return res
if __name__ == "__main__":
sys.exit(main(sys.argv))
| true
| true
|
790e6d5d485d8a9cf391ffe0a4445dca116402f4
| 2,044
|
py
|
Python
|
tests/core/test_fragment.py
|
trumanw/ScaffoldGraph
|
a594e5c5effe6c5e45c0061a235ccbeb64e416f9
|
[
"MIT"
] | null | null | null |
tests/core/test_fragment.py
|
trumanw/ScaffoldGraph
|
a594e5c5effe6c5e45c0061a235ccbeb64e416f9
|
[
"MIT"
] | null | null | null |
tests/core/test_fragment.py
|
trumanw/ScaffoldGraph
|
a594e5c5effe6c5e45c0061a235ccbeb64e416f9
|
[
"MIT"
] | null | null | null |
"""
scaffoldgraph tests.core.test_fragment
"""
import pytest
from rdkit import Chem
from scaffoldgraph.core.fragment import *
@pytest.fixture(name='mol')
def test_molecule():
smiles = 'CCN1CCc2c(C1)sc(NC(=O)Nc3ccc(Cl)cc3)c2C#N'
return Chem.MolFromSmiles(smiles)
def canon(smiles):
"""Canonicalize SMILES for safety. If canonicalization ever changes this should remain consistent"""
return Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
def test_murcko(mol):
murcko = get_murcko_scaffold(mol, generic=False)
assert Chem.MolToSmiles(murcko) == canon('O=C(Nc1ccccc1)Nc1cc2c(s1)CNCC2')
murcko = get_murcko_scaffold(mol, generic=True)
assert Chem.MolToSmiles(murcko) == canon('CC(CC1CCCCC1)CC1CC2CCCCC2C1')
def test_annotation(mol):
annotation = Chem.MolToSmiles(get_annotated_murcko_scaffold(mol))
annotation = annotation.replace('1*', '*')
annotation = annotation.replace('2*', '*')
annotation = annotation.replace('3*', '*')
assert annotation.count('*') == 3
def test_murcko_all(mol):
frags = get_all_murcko_fragments(mol, break_fused_rings=True)
assert len(frags) == 6
frags = get_all_murcko_fragments(mol, break_fused_rings=False)
assert len(frags) == 3
def test_murcko_next(mol):
scf = get_murcko_scaffold(mol)
frags_1 = get_next_murcko_fragments(scf, break_fused_rings=True)
frags_1 = {Chem.MolToSmiles(x) for x in frags_1}
assert len(frags_1) == 2
frags_2 = get_next_murcko_fragments(scf, break_fused_rings=False)
frags_2 = {Chem.MolToSmiles(x) for x in frags_2}
assert len(frags_2) == 2
assert len(frags_1.intersection(frags_2)) == 1
def test_collect_linker_atoms():
mol = Chem.MolFromSmiles('CCCCCCCCCc1ccccc1')
remove_atoms = set()
a = collect_linker_atoms(mol.GetAtomWithIdx(0), remove_atoms, True)
assert len(a) == 1
assert len(remove_atoms) == 9
remove_atoms.clear()
a = collect_linker_atoms(mol.GetAtomWithIdx(0), remove_atoms, False)
assert len(a) == 1
assert len(remove_atoms) == 8
| 31.446154
| 104
| 0.719667
|
import pytest
from rdkit import Chem
from scaffoldgraph.core.fragment import *
@pytest.fixture(name='mol')
def test_molecule():
smiles = 'CCN1CCc2c(C1)sc(NC(=O)Nc3ccc(Cl)cc3)c2C#N'
return Chem.MolFromSmiles(smiles)
def canon(smiles):
return Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
def test_murcko(mol):
murcko = get_murcko_scaffold(mol, generic=False)
assert Chem.MolToSmiles(murcko) == canon('O=C(Nc1ccccc1)Nc1cc2c(s1)CNCC2')
murcko = get_murcko_scaffold(mol, generic=True)
assert Chem.MolToSmiles(murcko) == canon('CC(CC1CCCCC1)CC1CC2CCCCC2C1')
def test_annotation(mol):
annotation = Chem.MolToSmiles(get_annotated_murcko_scaffold(mol))
annotation = annotation.replace('1*', '*')
annotation = annotation.replace('2*', '*')
annotation = annotation.replace('3*', '*')
assert annotation.count('*') == 3
def test_murcko_all(mol):
frags = get_all_murcko_fragments(mol, break_fused_rings=True)
assert len(frags) == 6
frags = get_all_murcko_fragments(mol, break_fused_rings=False)
assert len(frags) == 3
def test_murcko_next(mol):
scf = get_murcko_scaffold(mol)
frags_1 = get_next_murcko_fragments(scf, break_fused_rings=True)
frags_1 = {Chem.MolToSmiles(x) for x in frags_1}
assert len(frags_1) == 2
frags_2 = get_next_murcko_fragments(scf, break_fused_rings=False)
frags_2 = {Chem.MolToSmiles(x) for x in frags_2}
assert len(frags_2) == 2
assert len(frags_1.intersection(frags_2)) == 1
def test_collect_linker_atoms():
mol = Chem.MolFromSmiles('CCCCCCCCCc1ccccc1')
remove_atoms = set()
a = collect_linker_atoms(mol.GetAtomWithIdx(0), remove_atoms, True)
assert len(a) == 1
assert len(remove_atoms) == 9
remove_atoms.clear()
a = collect_linker_atoms(mol.GetAtomWithIdx(0), remove_atoms, False)
assert len(a) == 1
assert len(remove_atoms) == 8
| true
| true
|
790e6f0c2ddcc586747397ef7be1a6248ef7817f
| 138
|
py
|
Python
|
condominios/apps.py
|
mpeyrotc/govector
|
5429d538d0bcee4d95d9069dd397b3b5b35b504c
|
[
"MIT"
] | null | null | null |
condominios/apps.py
|
mpeyrotc/govector
|
5429d538d0bcee4d95d9069dd397b3b5b35b504c
|
[
"MIT"
] | null | null | null |
condominios/apps.py
|
mpeyrotc/govector
|
5429d538d0bcee4d95d9069dd397b3b5b35b504c
|
[
"MIT"
] | null | null | null |
from __future__ import unicode_literals
from django.apps import AppConfig
class CondominiosConfig(AppConfig):
name = 'condominios'
| 17.25
| 39
| 0.804348
|
from __future__ import unicode_literals
from django.apps import AppConfig
class CondominiosConfig(AppConfig):
name = 'condominios'
| true
| true
|
790e708e4fd42df30662fd05e0fd27cb6d2b56ae
| 1,525
|
py
|
Python
|
gdsfactory/components/cdsem_straight.py
|
jorgepadilla19/gdsfactory
|
68e1c18257a75d4418279851baea417c8899a165
|
[
"MIT"
] | 42
|
2020-05-25T09:33:45.000Z
|
2022-03-29T03:41:19.000Z
|
gdsfactory/components/cdsem_straight.py
|
jorgepadilla19/gdsfactory
|
68e1c18257a75d4418279851baea417c8899a165
|
[
"MIT"
] | 133
|
2020-05-28T18:29:04.000Z
|
2022-03-31T22:21:42.000Z
|
gdsfactory/components/cdsem_straight.py
|
jorgepadilla19/gdsfactory
|
68e1c18257a75d4418279851baea417c8899a165
|
[
"MIT"
] | 17
|
2020-06-30T07:07:50.000Z
|
2022-03-17T15:45:27.000Z
|
"""CD SEM structures."""
from functools import partial
from typing import Optional, Tuple
from gdsfactory.cell import cell
from gdsfactory.component import Component
from gdsfactory.components.straight import straight as straight_function
from gdsfactory.components.text_rectangular import text_rectangular
from gdsfactory.cross_section import strip
from gdsfactory.grid import grid
from gdsfactory.types import ComponentFactory, CrossSectionFactory
text_rectangular_mini = partial(text_rectangular, size=1)
LINE_LENGTH = 420.0
@cell
def cdsem_straight(
widths: Tuple[float, ...] = (0.4, 0.45, 0.5, 0.6, 0.8, 1.0),
length: float = LINE_LENGTH,
cross_section: CrossSectionFactory = strip,
text: Optional[ComponentFactory] = text_rectangular_mini,
spacing: float = 3,
) -> Component:
"""Returns straight waveguide lines width sweep.
Args:
widths: for the sweep
length: for the line
cross_section: for the lines
text: optional text for labels
spacing: edge to edge spacing
"""
lines = []
for width in widths:
cross_section = partial(cross_section, width=width)
line = straight_function(length=length, cross_section=cross_section)
if text:
line = line.copy()
t = line << text(str(int(width * 1e3)))
t.xmin = line.xmax + 5
t.y = 0
lines.append(line)
return grid(lines, spacing=(0, spacing))
if __name__ == "__main__":
c = cdsem_straight()
c.show()
| 28.773585
| 76
| 0.685902
|
from functools import partial
from typing import Optional, Tuple
from gdsfactory.cell import cell
from gdsfactory.component import Component
from gdsfactory.components.straight import straight as straight_function
from gdsfactory.components.text_rectangular import text_rectangular
from gdsfactory.cross_section import strip
from gdsfactory.grid import grid
from gdsfactory.types import ComponentFactory, CrossSectionFactory
text_rectangular_mini = partial(text_rectangular, size=1)
LINE_LENGTH = 420.0
@cell
def cdsem_straight(
widths: Tuple[float, ...] = (0.4, 0.45, 0.5, 0.6, 0.8, 1.0),
length: float = LINE_LENGTH,
cross_section: CrossSectionFactory = strip,
text: Optional[ComponentFactory] = text_rectangular_mini,
spacing: float = 3,
) -> Component:
lines = []
for width in widths:
cross_section = partial(cross_section, width=width)
line = straight_function(length=length, cross_section=cross_section)
if text:
line = line.copy()
t = line << text(str(int(width * 1e3)))
t.xmin = line.xmax + 5
t.y = 0
lines.append(line)
return grid(lines, spacing=(0, spacing))
if __name__ == "__main__":
c = cdsem_straight()
c.show()
| true
| true
|
790e70f9e9c6e39d9007e0b280f55ffda2cb3bfb
| 484
|
py
|
Python
|
demo_snippets/15_Bootstrap/main.py
|
fabod/pro2_demos
|
6ff1babf07eefa90db2a6d36727c290c7085c588
|
[
"MIT"
] | 3
|
2021-04-27T09:42:00.000Z
|
2022-03-03T13:21:33.000Z
|
demo_snippets/15_Bootstrap/main.py
|
hackerman7000/pro2_demos
|
6ff1babf07eefa90db2a6d36727c290c7085c588
|
[
"MIT"
] | null | null | null |
demo_snippets/15_Bootstrap/main.py
|
hackerman7000/pro2_demos
|
6ff1babf07eefa90db2a6d36727c290c7085c588
|
[
"MIT"
] | 1
|
2022-03-03T12:49:27.000Z
|
2022-03-03T12:49:27.000Z
|
from flask import Flask
from flask import render_template
app = Flask("Boostrap_Demo")
@app.route("/")
def start():
name = "Fabian"
cards = [
{"titel": "Card 0", "inhalt": "Blubber"},
{"titel": "Card 1", "inhalt": "Bla"},
{"titel": "Card 2", "inhalt": "Käsekuchen"},
{"titel": "Card 2", "inhalt": "Sülze"}
]
return render_template("start.html", name=name, cards=cards)
if __name__ == "__main__":
app.run(debug=True, port=5000)
| 23.047619
| 64
| 0.578512
|
from flask import Flask
from flask import render_template
app = Flask("Boostrap_Demo")
@app.route("/")
def start():
name = "Fabian"
cards = [
{"titel": "Card 0", "inhalt": "Blubber"},
{"titel": "Card 1", "inhalt": "Bla"},
{"titel": "Card 2", "inhalt": "Käsekuchen"},
{"titel": "Card 2", "inhalt": "Sülze"}
]
return render_template("start.html", name=name, cards=cards)
if __name__ == "__main__":
app.run(debug=True, port=5000)
| true
| true
|
790e7118041275c984e663ed66d4fddc0b7a1fae
| 1,084
|
py
|
Python
|
examples/decoupledibpm/flatplate3dRe100AoA30_GPU/scripts/createBody.py
|
CFD-lab-ZJU/PetIBM
|
a6578217ec1022b380f3f2a5972c8d2868ea3202
|
[
"BSD-3-Clause"
] | 71
|
2015-01-19T18:22:12.000Z
|
2022-03-29T01:46:14.000Z
|
examples/decoupledibpm/flatplate3dRe100AoA30_GPU/scripts/createBody.py
|
CFD-lab-ZJU/PetIBM
|
a6578217ec1022b380f3f2a5972c8d2868ea3202
|
[
"BSD-3-Clause"
] | 105
|
2015-03-02T18:10:27.000Z
|
2022-03-31T21:06:01.000Z
|
examples/decoupledibpm/flatplate3dRe100AoA30_GPU/scripts/createBody.py
|
piyueh/PetIBM
|
59c9ddd7373c2f4659761ca425db05491069c601
|
[
"MIT"
] | 45
|
2015-01-22T16:32:07.000Z
|
2022-02-09T02:41:26.000Z
|
"""
Create a flat plate of length 1.0 with aspect ratio 2.0 and a 30-degree
inclination.
The plate is discretized with spacing 0.04 in the x-y plane and with spacing
0.04 along the z-direction.
"""
import math
import pathlib
import numpy
# Flat-plate's parameters.
L = 1.0 # chord length
AR = 2.0 # aspect ratio
xc, yc, zc = 0.0, 0.0, 0.0 # center's coordinates
aoa = 30.0 # angle of inclination in degrees
ds = 0.04 # mesh spacing
simu_dir = pathlib.Path(__file__).absolute().parents[1]
# Generate coordinates of the flat plate.
n = math.ceil(L / ds)
s = numpy.linspace(xc - L / 2, xc + L / 2, num=n + 1)
x = xc + numpy.cos(numpy.radians(-aoa)) * s
y = yc + numpy.sin(numpy.radians(-aoa)) * s
nz = math.ceil(L * AR / ds)
z = numpy.linspace(zc - L * AR / 2, zc + L * AR / 2, num=nz + 1)
# Write coordinates into file.
filepath = simu_dir / 'flatplate.body'
with open(filepath, 'w') as outfile:
outfile.write('{}\n'.format(x.size * z.size))
for zi in z:
with open(filepath, 'ab') as outfile:
numpy.savetxt(outfile, numpy.c_[x, y, zi * numpy.ones(x.size)])
| 27.794872
| 76
| 0.657749
|
import math
import pathlib
import numpy
L = 1.0 # chord length
AR = 2.0 # aspect ratio
xc, yc, zc = 0.0, 0.0, 0.0 # center's coordinates
aoa = 30.0
ds = 0.04
simu_dir = pathlib.Path(__file__).absolute().parents[1]
n = math.ceil(L / ds)
s = numpy.linspace(xc - L / 2, xc + L / 2, num=n + 1)
x = xc + numpy.cos(numpy.radians(-aoa)) * s
y = yc + numpy.sin(numpy.radians(-aoa)) * s
nz = math.ceil(L * AR / ds)
z = numpy.linspace(zc - L * AR / 2, zc + L * AR / 2, num=nz + 1)
filepath = simu_dir / 'flatplate.body'
with open(filepath, 'w') as outfile:
outfile.write('{}\n'.format(x.size * z.size))
for zi in z:
with open(filepath, 'ab') as outfile:
numpy.savetxt(outfile, numpy.c_[x, y, zi * numpy.ones(x.size)])
| true
| true
|
790e713f9b9db9c56828ed101058ef1722be48bc
| 7,322
|
py
|
Python
|
Lib3/bsddb/test/test_db.py
|
wchangque/bsddb3
|
477f9defcf61b47d2cc769374afff468e4b4a248
|
[
"BSD-3-Clause"
] | null | null | null |
Lib3/bsddb/test/test_db.py
|
wchangque/bsddb3
|
477f9defcf61b47d2cc769374afff468e4b4a248
|
[
"BSD-3-Clause"
] | null | null | null |
Lib3/bsddb/test/test_db.py
|
wchangque/bsddb3
|
477f9defcf61b47d2cc769374afff468e4b4a248
|
[
"BSD-3-Clause"
] | null | null | null |
"""
Copyright (c) 2008-2020, Jesus Cea Avion <jcea@jcea.es>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
3. Neither the name of Jesus Cea Avion nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
"""
import unittest
import os, glob
from .test_all import db, test_support, get_new_environment_path, \
get_new_database_path
#----------------------------------------------------------------------
class DB(unittest.TestCase):
def setUp(self):
self.path = get_new_database_path()
self.db = db.DB()
def tearDown(self):
self.db.close()
del self.db
test_support.unlink(self.path)
class DB_general(DB) :
def test_get_open_flags(self) :
self.db.open(self.path, dbtype=db.DB_HASH, flags = db.DB_CREATE)
self.assertEqual(db.DB_CREATE, self.db.get_open_flags())
def test_get_open_flags2(self) :
self.db.open(self.path, dbtype=db.DB_HASH, flags = db.DB_CREATE |
db.DB_THREAD)
self.assertEqual(db.DB_CREATE | db.DB_THREAD, self.db.get_open_flags())
def test_get_dbname_filename(self) :
self.db.open(self.path, dbtype=db.DB_HASH, flags = db.DB_CREATE)
self.assertEqual((self.path, None), self.db.get_dbname())
def test_get_dbname_filename_database(self) :
name = "jcea-random-name"
self.db.open(self.path, dbname=name, dbtype=db.DB_HASH,
flags = db.DB_CREATE)
self.assertEqual((self.path, name), self.db.get_dbname())
def test_bt_minkey(self) :
for i in [17, 108, 1030] :
self.db.set_bt_minkey(i)
self.assertEqual(i, self.db.get_bt_minkey())
def test_lorder(self) :
self.db.set_lorder(1234)
self.assertEqual(1234, self.db.get_lorder())
self.db.set_lorder(4321)
self.assertEqual(4321, self.db.get_lorder())
self.assertRaises(db.DBInvalidArgError, self.db.set_lorder, 9182)
def test_priority(self) :
flags = [db.DB_PRIORITY_VERY_LOW, db.DB_PRIORITY_LOW,
db.DB_PRIORITY_DEFAULT, db.DB_PRIORITY_HIGH,
db.DB_PRIORITY_VERY_HIGH]
for flag in flags :
self.db.set_priority(flag)
self.assertEqual(flag, self.db.get_priority())
def test_get_transactional(self) :
self.assertFalse(self.db.get_transactional())
self.db.open(self.path, dbtype=db.DB_HASH, flags = db.DB_CREATE)
self.assertFalse(self.db.get_transactional())
class DB_hash(DB) :
def test_h_ffactor(self) :
for ffactor in [4, 16, 256] :
self.db.set_h_ffactor(ffactor)
self.assertEqual(ffactor, self.db.get_h_ffactor())
def test_h_nelem(self) :
for nelem in [1, 2, 4] :
nelem = nelem*1024*1024 # Millions
self.db.set_h_nelem(nelem)
self.assertEqual(nelem, self.db.get_h_nelem())
def test_pagesize(self) :
for i in range(9, 17) : # From 512 to 65536
i = 1<<i
self.db.set_pagesize(i)
self.assertEqual(i, self.db.get_pagesize())
# The valid values goes from 512 to 65536
# Test 131072 bytes...
self.assertRaises(db.DBInvalidArgError, self.db.set_pagesize, 1<<17)
# Test 256 bytes...
self.assertRaises(db.DBInvalidArgError, self.db.set_pagesize, 1<<8)
class DB_txn(DB) :
def setUp(self) :
self.homeDir = get_new_environment_path()
self.env = db.DBEnv()
self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL |
db.DB_INIT_LOG | db.DB_INIT_TXN)
self.db = db.DB(self.env)
def tearDown(self) :
self.db.close()
del self.db
self.env.close()
del self.env
test_support.rmtree(self.homeDir)
def test_flags(self) :
self.db.set_flags(db.DB_CHKSUM)
self.assertEqual(db.DB_CHKSUM, self.db.get_flags())
self.db.set_flags(db.DB_TXN_NOT_DURABLE)
self.assertEqual(db.DB_TXN_NOT_DURABLE | db.DB_CHKSUM,
self.db.get_flags())
def test_get_transactional(self) :
self.assertFalse(self.db.get_transactional())
# DB_AUTO_COMMIT = Implicit transaction
self.db.open("XXX", dbtype=db.DB_HASH,
flags = db.DB_CREATE | db.DB_AUTO_COMMIT)
self.assertTrue(self.db.get_transactional())
class DB_recno(DB) :
def test_re_pad(self) :
for i in [' ', '*'] : # Check chars
self.db.set_re_pad(i)
self.assertEqual(ord(i), self.db.get_re_pad())
for i in [97, 65] : # Check integers
self.db.set_re_pad(i)
self.assertEqual(i, self.db.get_re_pad())
def test_re_delim(self) :
for i in [' ', '*'] : # Check chars
self.db.set_re_delim(i)
self.assertEqual(ord(i), self.db.get_re_delim())
for i in [97, 65] : # Check integers
self.db.set_re_delim(i)
self.assertEqual(i, self.db.get_re_delim())
def test_re_source(self) :
for i in ["test", "test2", "test3"] :
self.db.set_re_source(i)
self.assertEqual(i, self.db.get_re_source())
class DB_queue(DB) :
def test_re_len(self) :
for i in [33, 65, 300, 2000] :
self.db.set_re_len(i)
self.assertEqual(i, self.db.get_re_len())
def test_q_extentsize(self) :
for i in [1, 60, 100] :
self.db.set_q_extentsize(i)
self.assertEqual(i, self.db.get_q_extentsize())
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(DB_general))
suite.addTest(unittest.makeSuite(DB_txn))
suite.addTest(unittest.makeSuite(DB_hash))
suite.addTest(unittest.makeSuite(DB_recno))
suite.addTest(unittest.makeSuite(DB_queue))
return suite
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
| 36.979798
| 79
| 0.642721
|
import unittest
import os, glob
from .test_all import db, test_support, get_new_environment_path, \
get_new_database_path
class DB(unittest.TestCase):
def setUp(self):
self.path = get_new_database_path()
self.db = db.DB()
def tearDown(self):
self.db.close()
del self.db
test_support.unlink(self.path)
class DB_general(DB) :
def test_get_open_flags(self) :
self.db.open(self.path, dbtype=db.DB_HASH, flags = db.DB_CREATE)
self.assertEqual(db.DB_CREATE, self.db.get_open_flags())
def test_get_open_flags2(self) :
self.db.open(self.path, dbtype=db.DB_HASH, flags = db.DB_CREATE |
db.DB_THREAD)
self.assertEqual(db.DB_CREATE | db.DB_THREAD, self.db.get_open_flags())
def test_get_dbname_filename(self) :
self.db.open(self.path, dbtype=db.DB_HASH, flags = db.DB_CREATE)
self.assertEqual((self.path, None), self.db.get_dbname())
def test_get_dbname_filename_database(self) :
name = "jcea-random-name"
self.db.open(self.path, dbname=name, dbtype=db.DB_HASH,
flags = db.DB_CREATE)
self.assertEqual((self.path, name), self.db.get_dbname())
def test_bt_minkey(self) :
for i in [17, 108, 1030] :
self.db.set_bt_minkey(i)
self.assertEqual(i, self.db.get_bt_minkey())
def test_lorder(self) :
self.db.set_lorder(1234)
self.assertEqual(1234, self.db.get_lorder())
self.db.set_lorder(4321)
self.assertEqual(4321, self.db.get_lorder())
self.assertRaises(db.DBInvalidArgError, self.db.set_lorder, 9182)
def test_priority(self) :
flags = [db.DB_PRIORITY_VERY_LOW, db.DB_PRIORITY_LOW,
db.DB_PRIORITY_DEFAULT, db.DB_PRIORITY_HIGH,
db.DB_PRIORITY_VERY_HIGH]
for flag in flags :
self.db.set_priority(flag)
self.assertEqual(flag, self.db.get_priority())
def test_get_transactional(self) :
self.assertFalse(self.db.get_transactional())
self.db.open(self.path, dbtype=db.DB_HASH, flags = db.DB_CREATE)
self.assertFalse(self.db.get_transactional())
class DB_hash(DB) :
def test_h_ffactor(self) :
for ffactor in [4, 16, 256] :
self.db.set_h_ffactor(ffactor)
self.assertEqual(ffactor, self.db.get_h_ffactor())
def test_h_nelem(self) :
for nelem in [1, 2, 4] :
nelem = nelem*1024*1024
self.db.set_h_nelem(nelem)
self.assertEqual(nelem, self.db.get_h_nelem())
def test_pagesize(self) :
for i in range(9, 17) :
i = 1<<i
self.db.set_pagesize(i)
self.assertEqual(i, self.db.get_pagesize())
self.assertRaises(db.DBInvalidArgError, self.db.set_pagesize, 1<<17)
self.assertRaises(db.DBInvalidArgError, self.db.set_pagesize, 1<<8)
class DB_txn(DB) :
def setUp(self) :
self.homeDir = get_new_environment_path()
self.env = db.DBEnv()
self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL |
db.DB_INIT_LOG | db.DB_INIT_TXN)
self.db = db.DB(self.env)
def tearDown(self) :
self.db.close()
del self.db
self.env.close()
del self.env
test_support.rmtree(self.homeDir)
def test_flags(self) :
self.db.set_flags(db.DB_CHKSUM)
self.assertEqual(db.DB_CHKSUM, self.db.get_flags())
self.db.set_flags(db.DB_TXN_NOT_DURABLE)
self.assertEqual(db.DB_TXN_NOT_DURABLE | db.DB_CHKSUM,
self.db.get_flags())
def test_get_transactional(self) :
self.assertFalse(self.db.get_transactional())
self.db.open("XXX", dbtype=db.DB_HASH,
flags = db.DB_CREATE | db.DB_AUTO_COMMIT)
self.assertTrue(self.db.get_transactional())
class DB_recno(DB) :
def test_re_pad(self) :
for i in [' ', '*'] :
self.db.set_re_pad(i)
self.assertEqual(ord(i), self.db.get_re_pad())
for i in [97, 65] :
self.db.set_re_pad(i)
self.assertEqual(i, self.db.get_re_pad())
def test_re_delim(self) :
for i in [' ', '*'] :
self.db.set_re_delim(i)
self.assertEqual(ord(i), self.db.get_re_delim())
for i in [97, 65] :
self.db.set_re_delim(i)
self.assertEqual(i, self.db.get_re_delim())
def test_re_source(self) :
for i in ["test", "test2", "test3"] :
self.db.set_re_source(i)
self.assertEqual(i, self.db.get_re_source())
class DB_queue(DB) :
def test_re_len(self) :
for i in [33, 65, 300, 2000] :
self.db.set_re_len(i)
self.assertEqual(i, self.db.get_re_len())
def test_q_extentsize(self) :
for i in [1, 60, 100] :
self.db.set_q_extentsize(i)
self.assertEqual(i, self.db.get_q_extentsize())
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(DB_general))
suite.addTest(unittest.makeSuite(DB_txn))
suite.addTest(unittest.makeSuite(DB_hash))
suite.addTest(unittest.makeSuite(DB_recno))
suite.addTest(unittest.makeSuite(DB_queue))
return suite
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
| true
| true
|
790e71563257e0b2ab4a36cb3403c7b30a3b5499
| 7,381
|
py
|
Python
|
skyblock/object/object.py
|
peter-hunt/skyblock
|
a3ef6329e2579940f39944544d02f49727247f44
|
[
"MIT"
] | 13
|
2021-05-29T09:59:16.000Z
|
2022-03-16T13:19:28.000Z
|
skyblock/object/object.py
|
peter-hunt/skyblock
|
a3ef6329e2579940f39944544d02f49727247f44
|
[
"MIT"
] | 4
|
2021-07-11T00:33:53.000Z
|
2022-01-28T08:16:52.000Z
|
skyblock/object/object.py
|
peter-hunt/skyblock
|
a3ef6329e2579940f39944544d02f49727247f44
|
[
"MIT"
] | 2
|
2021-07-24T05:18:14.000Z
|
2021-08-06T06:45:11.000Z
|
from typing import Dict, Iterator, List, Optional, Tuple, Union
from ..constant.util import Amount, ItemPointer, Number
from .item_wrapper import item_type
from .other_wrapper import *
__all__ = [
'ItemType', 'Item', 'Empty',
'Accessory', 'EnchantedBook', 'ReforgeStone', 'TravelScroll',
'Bow', 'Sword',
'Axe', 'Pickaxe', 'Drill', 'Hoe', 'FishingRod', 'Armor', 'Pet', 'Minion',
'Resource',
'Crop', 'Mineral', 'Log', 'Mob',
'Recipe', 'RecipeGroup', 'Collection',
'load_item',
]
class ItemType:
pass
@item_type
class Item(ItemType):
name: str
count: int = 1
# common | uncommon | rare | epic | legendary |
# mythic | supreme | special | very_special
rarity: str = 'common'
abilities: List[str] = []
@item_type
class Empty(ItemType):
def __repr__(self):
return '{}'
@item_type
class Accessory(ItemType):
name: str
rarity: str = 'common'
modifier: Optional[str] = None
abilities: List[str] = []
@item_type
class Armor(ItemType):
name: str
rarity: str
# helmet | chestplate | leggings | boots
part: str
strength: int = 0
crit_chance: int = 0
crit_damage: int = 0
health: int = 0
defense: int = 0
intelligence: int = 0
speed: int = 0
magic_find: int = 0
mining_speed: int = 0
mining_fortune: int = 0
true_defense: int = 0
ferocity: int = 0
sea_creature_chance: int = 0
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
hot_potato: int = 0
stars: Optional[int] = None
combat_skill_req: Optional[int] = None
dungeon_skill_req: Optional[int] = None
dungeon_completion_req: Optional[int] = None
abilities: List[str] = []
@item_type
class Axe(ItemType):
name: str
rarity: str
tool_speed: int
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
abilities: List[str] = []
@item_type
class Bow(ItemType):
name: str
rarity: str
damage: int
count: int = 1
strength: int = 0
crit_chance: int = 0
crit_damage: int = 0
attack_speed: int = 0
intelligence: int = 0
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
hot_potato: int = 0
stars: Optional[int] = None
combat_skill_req: Optional[int] = None
dungeon_skill_req: Optional[int] = None
dungeon_completion_req: Optional[int] = None
abilities: List[str] = []
@item_type
class Drill(ItemType):
name: str
rarity: str
breaking_power: int
mining_speed: int
mining_fortune: int = 0
damage: int = 0
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
abilities: List[str] = []
@enchanted_book_type
@item_type
class EnchantedBook(ItemType):
enchantments: Dict[str, int] = {}
name: str = 'enchanted_book'
rarity: str = 'common'
@item_type
class FishingRod(ItemType):
name: str
rarity: str
damage: int = 0
strength: int = 0
ferocity: int = 0
fishing_speed: int = 0
sea_creature_chance: int = 0
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
hot_potato: int = 0
stars: Optional[int] = None
fishing_skill_req: Optional[int] = None
abilities: List[str] = []
@item_type
class Hoe(ItemType):
name: str
rarity: str
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
@item_type
class Minion(ItemType):
name: str
tier: str
cooldown: Number
slots: int
@item_type
class Pet(ItemType):
name: str
rarity: str
category: str = None
exp: float = 0.0
candy_used: int = 0
active: bool = False
health: int = 0
defense: int = 0
speed: int = 0
true_defense: int = 0
intelligence: int = 0
strength: int = 0
crit_chance: int = 0
crit_damage: int = 0
damage: int = 0
magic_find: int = 0
attack_speed: int = 0
ferocity: int = 0
sea_creature_chance: int = 0
abilities: List = []
@item_type
class Pickaxe(ItemType):
name: str
rarity: str
breaking_power: int
mining_speed: int
damage: int = 0
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
abilities: List[str] = []
@item_type
class ReforgeStone(ItemType):
name: str
modifier: Optional[str] = None
category: Optional[str] = None
rarity: str = 'common'
cost: Tuple[int] = (0, 0, 0, 0, 0, 0)
mining_skill_req: Optional[int] = None
@item_type
class Sword(ItemType):
name: str
rarity: str
count: int = 1
damage: int = 0
strength: int = 0
crit_chance: int = 0
crit_damage: int = 0
attack_speed: int = 0
defense: int = 0
intelligence: int = 0
true_defense: int = 0
ferocity: int = 0
speed: int = 0
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
hot_potato: int = 0
stars: Optional[int] = None
combat_skill_req: Optional[int] = None
dungeon_skill_req: Optional[int] = None
dungeon_completion_req: Optional[int] = None
abilities: List[str] = []
@item_type
class TravelScroll(ItemType):
name: str
island: str
zone: Optional[str] = None
rarity: str = 'rare'
OBJECT_NAMES = {
'item': Item,
'empty': Empty,
'accessory': Accessory,
'armor': Armor,
'axe': Axe,
'bow': Bow,
'drill': Drill,
'enchanted_book': EnchantedBook,
'fishing_rod': FishingRod,
'hoe': Hoe,
'minion': Minion,
'pet': Pet,
'pickaxe': Pickaxe,
'reforge_stone': ReforgeStone,
'sword': Sword,
'travel_scroll': TravelScroll,
}
class Resource:
def type(self):
return type(self).__name__
@resource_type
class Crop(Resource):
name: str
amount: int = 1
farming_exp: Number = 1
@resource_type
class Log(Resource):
name: str
hardness: int = 2
foraging_exp: Number = 1
@resource_type
class Mineral(Resource):
name: str
drop: str
amount: int = 1
breaking_power: int = 0
hardness: Number = 2
exp: Amount = 1
mining_exp: Number = 1
mithril_powder: Amount = 0
@mob_type
class Mob:
name: str
level: int
health: int
defense: int = 0
damage: int = 0
true_damage: int = 0
coins: int = 0
exp: int = 0
farming_exp: int = 0
combat_exp: int = 0
fishing_exp: int = 0
drops: List[Tuple[ItemPointer, Amount, str, Number]] = []
@recipe_type
class Recipe:
name: str
category: str
ingredients: List[ItemPointer]
result: ItemPointer
collection_req: Optional[Tuple[str, int]] = None
# slayer_req: Optional[Tuple[str, int]] = None
@recipe_group_type
class RecipeGroup:
name: str
category: str
recipes: List[str]
collection_req: Optional[Tuple[str, int]] = None
# slayer_req: Optional[Tuple[str, int]] = None
@collection_type
class Collection:
name: str
category: str
levels: List[Tuple[int, Union[str, Tuple[str], Number]]]
def __iter__(self, /) -> Iterator:
return iter(self.levels)
def load_item(obj, /):
if isinstance(obj, ItemType):
return obj
elif 'type' not in obj:
return Empty()
for name, cls in OBJECT_NAMES.items():
if obj['type'] == name:
return cls.from_obj(obj)
else:
raise ValueError(f"invalid item obj type: {obj['type']!r}")
| 19.423684
| 77
| 0.618886
|
from typing import Dict, Iterator, List, Optional, Tuple, Union
from ..constant.util import Amount, ItemPointer, Number
from .item_wrapper import item_type
from .other_wrapper import *
__all__ = [
'ItemType', 'Item', 'Empty',
'Accessory', 'EnchantedBook', 'ReforgeStone', 'TravelScroll',
'Bow', 'Sword',
'Axe', 'Pickaxe', 'Drill', 'Hoe', 'FishingRod', 'Armor', 'Pet', 'Minion',
'Resource',
'Crop', 'Mineral', 'Log', 'Mob',
'Recipe', 'RecipeGroup', 'Collection',
'load_item',
]
class ItemType:
pass
@item_type
class Item(ItemType):
name: str
count: int = 1
rarity: str = 'common'
abilities: List[str] = []
@item_type
class Empty(ItemType):
def __repr__(self):
return '{}'
@item_type
class Accessory(ItemType):
name: str
rarity: str = 'common'
modifier: Optional[str] = None
abilities: List[str] = []
@item_type
class Armor(ItemType):
name: str
rarity: str
part: str
strength: int = 0
crit_chance: int = 0
crit_damage: int = 0
health: int = 0
defense: int = 0
intelligence: int = 0
speed: int = 0
magic_find: int = 0
mining_speed: int = 0
mining_fortune: int = 0
true_defense: int = 0
ferocity: int = 0
sea_creature_chance: int = 0
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
hot_potato: int = 0
stars: Optional[int] = None
combat_skill_req: Optional[int] = None
dungeon_skill_req: Optional[int] = None
dungeon_completion_req: Optional[int] = None
abilities: List[str] = []
@item_type
class Axe(ItemType):
name: str
rarity: str
tool_speed: int
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
abilities: List[str] = []
@item_type
class Bow(ItemType):
name: str
rarity: str
damage: int
count: int = 1
strength: int = 0
crit_chance: int = 0
crit_damage: int = 0
attack_speed: int = 0
intelligence: int = 0
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
hot_potato: int = 0
stars: Optional[int] = None
combat_skill_req: Optional[int] = None
dungeon_skill_req: Optional[int] = None
dungeon_completion_req: Optional[int] = None
abilities: List[str] = []
@item_type
class Drill(ItemType):
name: str
rarity: str
breaking_power: int
mining_speed: int
mining_fortune: int = 0
damage: int = 0
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
abilities: List[str] = []
@enchanted_book_type
@item_type
class EnchantedBook(ItemType):
enchantments: Dict[str, int] = {}
name: str = 'enchanted_book'
rarity: str = 'common'
@item_type
class FishingRod(ItemType):
name: str
rarity: str
damage: int = 0
strength: int = 0
ferocity: int = 0
fishing_speed: int = 0
sea_creature_chance: int = 0
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
hot_potato: int = 0
stars: Optional[int] = None
fishing_skill_req: Optional[int] = None
abilities: List[str] = []
@item_type
class Hoe(ItemType):
name: str
rarity: str
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
@item_type
class Minion(ItemType):
name: str
tier: str
cooldown: Number
slots: int
@item_type
class Pet(ItemType):
name: str
rarity: str
category: str = None
exp: float = 0.0
candy_used: int = 0
active: bool = False
health: int = 0
defense: int = 0
speed: int = 0
true_defense: int = 0
intelligence: int = 0
strength: int = 0
crit_chance: int = 0
crit_damage: int = 0
damage: int = 0
magic_find: int = 0
attack_speed: int = 0
ferocity: int = 0
sea_creature_chance: int = 0
abilities: List = []
@item_type
class Pickaxe(ItemType):
name: str
rarity: str
breaking_power: int
mining_speed: int
damage: int = 0
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
abilities: List[str] = []
@item_type
class ReforgeStone(ItemType):
name: str
modifier: Optional[str] = None
category: Optional[str] = None
rarity: str = 'common'
cost: Tuple[int] = (0, 0, 0, 0, 0, 0)
mining_skill_req: Optional[int] = None
@item_type
class Sword(ItemType):
name: str
rarity: str
count: int = 1
damage: int = 0
strength: int = 0
crit_chance: int = 0
crit_damage: int = 0
attack_speed: int = 0
defense: int = 0
intelligence: int = 0
true_defense: int = 0
ferocity: int = 0
speed: int = 0
modifier: Optional[str] = None
enchantments: Dict[str, int] = {}
hot_potato: int = 0
stars: Optional[int] = None
combat_skill_req: Optional[int] = None
dungeon_skill_req: Optional[int] = None
dungeon_completion_req: Optional[int] = None
abilities: List[str] = []
@item_type
class TravelScroll(ItemType):
name: str
island: str
zone: Optional[str] = None
rarity: str = 'rare'
OBJECT_NAMES = {
'item': Item,
'empty': Empty,
'accessory': Accessory,
'armor': Armor,
'axe': Axe,
'bow': Bow,
'drill': Drill,
'enchanted_book': EnchantedBook,
'fishing_rod': FishingRod,
'hoe': Hoe,
'minion': Minion,
'pet': Pet,
'pickaxe': Pickaxe,
'reforge_stone': ReforgeStone,
'sword': Sword,
'travel_scroll': TravelScroll,
}
class Resource:
def type(self):
return type(self).__name__
@resource_type
class Crop(Resource):
name: str
amount: int = 1
farming_exp: Number = 1
@resource_type
class Log(Resource):
name: str
hardness: int = 2
foraging_exp: Number = 1
@resource_type
class Mineral(Resource):
name: str
drop: str
amount: int = 1
breaking_power: int = 0
hardness: Number = 2
exp: Amount = 1
mining_exp: Number = 1
mithril_powder: Amount = 0
@mob_type
class Mob:
name: str
level: int
health: int
defense: int = 0
damage: int = 0
true_damage: int = 0
coins: int = 0
exp: int = 0
farming_exp: int = 0
combat_exp: int = 0
fishing_exp: int = 0
drops: List[Tuple[ItemPointer, Amount, str, Number]] = []
@recipe_type
class Recipe:
name: str
category: str
ingredients: List[ItemPointer]
result: ItemPointer
collection_req: Optional[Tuple[str, int]] = None
@recipe_group_type
class RecipeGroup:
name: str
category: str
recipes: List[str]
collection_req: Optional[Tuple[str, int]] = None
@collection_type
class Collection:
name: str
category: str
levels: List[Tuple[int, Union[str, Tuple[str], Number]]]
def __iter__(self, /) -> Iterator:
return iter(self.levels)
def load_item(obj, /):
if isinstance(obj, ItemType):
return obj
elif 'type' not in obj:
return Empty()
for name, cls in OBJECT_NAMES.items():
if obj['type'] == name:
return cls.from_obj(obj)
else:
raise ValueError(f"invalid item obj type: {obj['type']!r}")
| true
| true
|
790e717eaac52736abd2a5e6bee89fa90e8b38de
| 10,101
|
py
|
Python
|
main.py
|
capjamesg/indieweb-search
|
856ac117974bba593549136dfc17c3402c9f0066
|
[
"MIT"
] | 14
|
2021-08-31T14:36:55.000Z
|
2022-03-14T15:14:14.000Z
|
main.py
|
capjamesg/indieweb-search
|
856ac117974bba593549136dfc17c3402c9f0066
|
[
"MIT"
] | 22
|
2021-09-24T06:21:49.000Z
|
2022-02-13T15:41:57.000Z
|
main.py
|
capjamesg/indieweb-search
|
856ac117974bba593549136dfc17c3402c9f0066
|
[
"MIT"
] | 1
|
2021-09-24T09:40:14.000Z
|
2021-09-24T09:40:14.000Z
|
from flask import render_template, request, redirect, send_from_directory, jsonify, Blueprint
from direct_answers import choose_direct_answer
from direct_answers import search_result_features
import indieweb_utils
import search_helpers, config, search_page_feeds
import requests
import json
import math
import spacy
import mf2py
main = Blueprint("main", __name__, static_folder="static", static_url_path="")
nlp = spacy.load('en_core_web_sm')
@main.route("/")
def home():
q = request.args.get("q")
return render_template("search/submit.html", title="IndieWeb Search", query=q)
@main.route("/autocomplete")
def search_autocomplete():
query = request.args.get("q")
suggest = requests.get("https://es-indieweb-search.jamesg.blog/suggest?q={}&pw={}".format(query, config.ELASTICSEARCH_PASSWORD))
return jsonify(suggest.json()), 200
@main.route("/results", methods=["GET", "POST"])
def results_page():
page = request.args.get("page")
site = request.args.get("site")
if site and site == "jamesg.blog":
# used for special jamesg.blog search redirect, not for open use
site = "".join([x for x in site if x.isalpha() or x == "."])
return redirect('/results?query=site:"{}"%20{}'.format(site, request.args.get("query")))
special_result = False
if not request.args.get("query"):
return redirect("/")
query_with_handled_spaces = request.args.get("query").replace("--", "").replace(" ", " ").strip()
allowed_chars = [" ", '"', ":", "-", "/", ".", "=", ","]
cleaned_value_for_query = ''.join(e for e in query_with_handled_spaces if e.isalnum() or e in allowed_chars).strip()
query_values_in_list, query_with_handled_spaces = search_helpers.handle_advanced_search(query_with_handled_spaces)
if cleaned_value_for_query.startswith("xray https://") or cleaned_value_for_query.startswith("xray http://"):
return redirect("https://xray.p3k.io/parse?url={}".format(cleaned_value_for_query.replace("xray ", "")))
session = requests.Session()
if cleaned_value_for_query == "random":
random_site = session.get("https://es-indieweb-search.jamesg.blog/random?pw={}".format(config.ELASTICSEARCH_PASSWORD)).json()["domain"]
return redirect("https://{}/".format(random_site))
if not request.args.get("query"):
return redirect("/")
full_query_with_full_stops = ''.join(e for e in query_with_handled_spaces if e.isalnum() or e == " " or e == ".")
if len(cleaned_value_for_query) == 0:
return redirect("/")
do_i_use = ""
pagination = "0"
if page:
# If page cannot be converted into an integer, redirect to homepage
try:
if int(page) > 1:
pagination = (int(page) - 1) * 10
except:
return redirect("/")
else:
page = 1
order = "score"
minimal = "false"
if request.args.get("order") == "date_asc":
order = "date_asc"
elif request.args.get("order") == "date_desc":
order = "date_desc"
cleaned_value_for_query = cleaned_value_for_query.replace("what is", "")
if request.args.get("format") and (request.args.get("format") == "json_feed" or request.args.get("format") == "jf2"):
minimal = "true"
query_params = ""
if query_values_in_list.get("site"):
query_params += "&site={}".format(query_values_in_list.get("site").replace("%", ""))
if request.args.get("query").startswith("discover"):
query_params += "&discover=true"
if "js:none" in request.args.get("query"):
query_params += "&js=false"
if query_values_in_list.get("category"):
query_params += "&category={}".format(query_values_in_list.get("category"))
if query_values_in_list.get("mf2prop"):
query_params += "&mf2_property={}".format(query_values_in_list.get("mf2prop"))
rows = session.get("https://es-indieweb-search.jamesg.blog/?pw={}&q={}&sort={}&from={}&minimal={}{}".format(
config.ELASTICSEARCH_PASSWORD,
cleaned_value_for_query.replace("who is", "").replace("code", "").replace("discover ", "").strip(),
order, str(pagination),
minimal,
query_params)
).json()
num_of_results = rows["hits"]["total"]["value"]
rows = rows["hits"]["hits"]
for r in rows:
if r["_source"].get("h_card"):
r["_source"]["h_card"] = json.loads(r["_source"]["h_card"])
else:
r["_source"]["h_card"] = None
cleaned_value = cleaned_value_for_query.lower()
if page == 1:
do_i_use, special_result = choose_direct_answer.choose_featured_snippet(
cleaned_value,
cleaned_value_for_query,
rows,
special_result,
full_query_with_full_stops,
session,
nlp
)
if len(rows) == 0:
out_of_bounds_page = True
final_query = cleaned_value_for_query
# this code doesn't work right now
# identify_mistakes = spell.unknown(cleaned_value.split('"')[-1].split(" "))
# final_query = ""
# suggestion = False
# cleaned_items = cleaned_value.split('"')[-1].split(" ")
# for w in range(0, len(cleaned_items)):
# if cleaned_items[w] in identify_mistakes and cleaned_items[w] != "":
# final_query += spell.correction(cleaned_items[w]) + " "
# suggestion = True
# final_query = " " + final_query
# else:
# final_query += cleaned_items[w] + " "
# final_query = "".join(cleaned_value.split('"')[:-1]) + '" ' + final_query
else:
out_of_bounds_page = False
suggestion = False
final_query = ""
if "random aeropress" in cleaned_value or "generate aeropress" in cleaned_value and request.args.get("type") != "image":
special_result = search_result_features.aeropress_recipe()
format = request.args.get("format")
if format == "json_feed":
json_feed = search_page_feeds.process_json_feed(rows, cleaned_value, page, format)
return json_feed
elif format == "jf2":
jf2_feed = search_page_feeds.process_jf2_feed(rows)
return jf2_feed
elif format == "rss":
rss_feed = search_page_feeds.process_rss_feed(rows, cleaned_value, page, format)
return rss_feed
elif format == "direct_serp_json":
if special_result:
return jsonify({"text": do_i_use, "featured_serp": special_result})
else:
return jsonify({"message": "no custom serp available on this search"})
elif format == "results_page_json":
return jsonify({"results": [r["_source"] for r in rows]})
# show one result if a featured snippet is available, even if there are no other results to show
if not special_result and not do_i_use and int(num_of_results) == 0:
num_of_results = 0
out_of_bounds_page = True
else:
out_of_bounds_page = False
return render_template("search/results.html",
results=rows,
number_of_results=int(num_of_results),
page=int(page),
page_count=int(math.ceil(num_of_results / 10)),
query=cleaned_value,
results_type=request.args.get("type"),
out_of_bounds_page=out_of_bounds_page,
ordered_by=request.args.get("order"),
base_results_query="/results?query=" + cleaned_value_for_query,
corrected_text=final_query,
suggestion_made=suggestion,
special_result=special_result,
do_i_use=do_i_use,
title="Search results for '{}' query".format(cleaned_value)
)
@main.route("/robots.txt")
def robots():
return send_from_directory(main.static_folder, "robots.txt")
@main.route('/assets/<path:path>')
def send_static_images(path):
return send_from_directory("static/", path)
@main.route("/changelog")
def changelog():
return render_template("changelog.html", title="IndieWeb Search Changelog")
@main.route("/advanced")
def advanced_search():
return render_template(
"search/advanced_search.html",
title="IndieWeb Search Advanced Search Options"
)
@main.route("/api/post-type")
def get_original_post_type():
page_to_check = request.args.get("url")
mf2_parsed = mf2py.parse(page_to_check)
if not mf2_parsed:
return jsonify({"status": "failed", "result": ""})
if not mf2_parsed["items"]:
return jsonify({"status": "failed", "result": ""})
# get h_entry
h_entry = [i for i in mf2_parsed["items"] if i["type"] == ["h-entry"]]
result = indieweb_utils.get_post_type(h_entry)
return jsonify({"status": "success", "result": result})
@main.route("/api/authorship")
def get_post_author():
page_to_check = request.args.get("url")
mf2_parsed = mf2py.parse(page_to_check)
if not mf2_parsed:
return jsonify({"status": "failed", "message": "No microformats could be found on this page", "author": []})
if not mf2_parsed["items"]:
return jsonify({"status": "failed", "message": "No microformats could be found on this page", "author": []})
# get h_entry
h_entry = [i for i in mf2_parsed["items"] if i["type"] == ["h-entry"]]
h_card = [i for i in mf2_parsed["items"] if i["type"] == ["h-card"]]
if not h_entry and h_card == []:
return jsonify({"status": "failed", "message": "No h-entry could be found on this page", "author": []})
if h_card == []:
for i in h_entry["items"]:
if i['type'] == ['h-entry']:
if i['properties'].get('author'):
# if author is h_card
if type(i['properties']['author'][0]) == dict and i['properties']['author'][0].get('type') == ['h-card']:
h_card = i['properties']['author'][0]
elif type(i['properties']['author']) == list:
h_card = i['properties']['author'][0]
result = indieweb_utils.discover_author(h_card, h_entry, page_to_check, [])
return jsonify({"status": "success", "result": result})
@main.route("/stats")
def stats():
count_request = requests.get("https://es-indieweb-search.jamesg.blog/count").json()
count = count_request["es_count"]["count"]
domains = count_request["domains"]
headers = {
"Authorization": config.ELASTICSEARCH_API_TOKEN
}
feed_breakdown_request = requests.get("https://es-indieweb-search.jamesg.blog/feed_breakdown", headers=headers).json()
special_stats = requests.get("https://es-indieweb-search.jamesg.blog/special_stats", headers=headers).json()
top_linked_assets = special_stats["top_ten_links"]
link_types = special_stats["link_microformat_instances"]
return render_template(
"search/stats.html",
count=count,
domains=domains,
title="IndieWeb Search Index Stats",
feed_breakdown=feed_breakdown_request,
top_linked_assets=top_linked_assets,
link_types=link_types
)
@main.route("/about")
def about():
return render_template("search/about.html", title="About IndieWeb Search")
| 30.242515
| 137
| 0.701416
|
from flask import render_template, request, redirect, send_from_directory, jsonify, Blueprint
from direct_answers import choose_direct_answer
from direct_answers import search_result_features
import indieweb_utils
import search_helpers, config, search_page_feeds
import requests
import json
import math
import spacy
import mf2py
main = Blueprint("main", __name__, static_folder="static", static_url_path="")
nlp = spacy.load('en_core_web_sm')
@main.route("/")
def home():
q = request.args.get("q")
return render_template("search/submit.html", title="IndieWeb Search", query=q)
@main.route("/autocomplete")
def search_autocomplete():
query = request.args.get("q")
suggest = requests.get("https://es-indieweb-search.jamesg.blog/suggest?q={}&pw={}".format(query, config.ELASTICSEARCH_PASSWORD))
return jsonify(suggest.json()), 200
@main.route("/results", methods=["GET", "POST"])
def results_page():
page = request.args.get("page")
site = request.args.get("site")
if site and site == "jamesg.blog":
site = "".join([x for x in site if x.isalpha() or x == "."])
return redirect('/results?query=site:"{}"%20{}'.format(site, request.args.get("query")))
special_result = False
if not request.args.get("query"):
return redirect("/")
query_with_handled_spaces = request.args.get("query").replace("--", "").replace(" ", " ").strip()
allowed_chars = [" ", '"', ":", "-", "/", ".", "=", ","]
cleaned_value_for_query = ''.join(e for e in query_with_handled_spaces if e.isalnum() or e in allowed_chars).strip()
query_values_in_list, query_with_handled_spaces = search_helpers.handle_advanced_search(query_with_handled_spaces)
if cleaned_value_for_query.startswith("xray https://") or cleaned_value_for_query.startswith("xray http://"):
return redirect("https://xray.p3k.io/parse?url={}".format(cleaned_value_for_query.replace("xray ", "")))
session = requests.Session()
if cleaned_value_for_query == "random":
random_site = session.get("https://es-indieweb-search.jamesg.blog/random?pw={}".format(config.ELASTICSEARCH_PASSWORD)).json()["domain"]
return redirect("https://{}/".format(random_site))
if not request.args.get("query"):
return redirect("/")
full_query_with_full_stops = ''.join(e for e in query_with_handled_spaces if e.isalnum() or e == " " or e == ".")
if len(cleaned_value_for_query) == 0:
return redirect("/")
do_i_use = ""
pagination = "0"
if page:
# If page cannot be converted into an integer, redirect to homepage
try:
if int(page) > 1:
pagination = (int(page) - 1) * 10
except:
return redirect("/")
else:
page = 1
order = "score"
minimal = "false"
if request.args.get("order") == "date_asc":
order = "date_asc"
elif request.args.get("order") == "date_desc":
order = "date_desc"
cleaned_value_for_query = cleaned_value_for_query.replace("what is", "")
if request.args.get("format") and (request.args.get("format") == "json_feed" or request.args.get("format") == "jf2"):
minimal = "true"
query_params = ""
if query_values_in_list.get("site"):
query_params += "&site={}".format(query_values_in_list.get("site").replace("%", ""))
if request.args.get("query").startswith("discover"):
query_params += "&discover=true"
if "js:none" in request.args.get("query"):
query_params += "&js=false"
if query_values_in_list.get("category"):
query_params += "&category={}".format(query_values_in_list.get("category"))
if query_values_in_list.get("mf2prop"):
query_params += "&mf2_property={}".format(query_values_in_list.get("mf2prop"))
rows = session.get("https://es-indieweb-search.jamesg.blog/?pw={}&q={}&sort={}&from={}&minimal={}{}".format(
config.ELASTICSEARCH_PASSWORD,
cleaned_value_for_query.replace("who is", "").replace("code", "").replace("discover ", "").strip(),
order, str(pagination),
minimal,
query_params)
).json()
num_of_results = rows["hits"]["total"]["value"]
rows = rows["hits"]["hits"]
for r in rows:
if r["_source"].get("h_card"):
r["_source"]["h_card"] = json.loads(r["_source"]["h_card"])
else:
r["_source"]["h_card"] = None
cleaned_value = cleaned_value_for_query.lower()
if page == 1:
do_i_use, special_result = choose_direct_answer.choose_featured_snippet(
cleaned_value,
cleaned_value_for_query,
rows,
special_result,
full_query_with_full_stops,
session,
nlp
)
if len(rows) == 0:
out_of_bounds_page = True
final_query = cleaned_value_for_query
# this code doesn't work right now
# identify_mistakes = spell.unknown(cleaned_value.split('"')[-1].split(" "))
# final_query = ""
# suggestion = False
# cleaned_items = cleaned_value.split('"')[-1].split(" ")
# for w in range(0, len(cleaned_items)):
# if cleaned_items[w] in identify_mistakes and cleaned_items[w] != "":
# final_query += spell.correction(cleaned_items[w]) + " "
# suggestion = True
# final_query = " " + final_query
# else:
# final_query += cleaned_items[w] + " "
# final_query = "".join(cleaned_value.split('"')[:-1]) + '" ' + final_query
else:
out_of_bounds_page = False
suggestion = False
final_query = ""
if "random aeropress" in cleaned_value or "generate aeropress" in cleaned_value and request.args.get("type") != "image":
special_result = search_result_features.aeropress_recipe()
format = request.args.get("format")
if format == "json_feed":
json_feed = search_page_feeds.process_json_feed(rows, cleaned_value, page, format)
return json_feed
elif format == "jf2":
jf2_feed = search_page_feeds.process_jf2_feed(rows)
return jf2_feed
elif format == "rss":
rss_feed = search_page_feeds.process_rss_feed(rows, cleaned_value, page, format)
return rss_feed
elif format == "direct_serp_json":
if special_result:
return jsonify({"text": do_i_use, "featured_serp": special_result})
else:
return jsonify({"message": "no custom serp available on this search"})
elif format == "results_page_json":
return jsonify({"results": [r["_source"] for r in rows]})
# show one result if a featured snippet is available, even if there are no other results to show
if not special_result and not do_i_use and int(num_of_results) == 0:
num_of_results = 0
out_of_bounds_page = True
else:
out_of_bounds_page = False
return render_template("search/results.html",
results=rows,
number_of_results=int(num_of_results),
page=int(page),
page_count=int(math.ceil(num_of_results / 10)),
query=cleaned_value,
results_type=request.args.get("type"),
out_of_bounds_page=out_of_bounds_page,
ordered_by=request.args.get("order"),
base_results_query="/results?query=" + cleaned_value_for_query,
corrected_text=final_query,
suggestion_made=suggestion,
special_result=special_result,
do_i_use=do_i_use,
title="Search results for '{}' query".format(cleaned_value)
)
@main.route("/robots.txt")
def robots():
return send_from_directory(main.static_folder, "robots.txt")
@main.route('/assets/<path:path>')
def send_static_images(path):
return send_from_directory("static/", path)
@main.route("/changelog")
def changelog():
return render_template("changelog.html", title="IndieWeb Search Changelog")
@main.route("/advanced")
def advanced_search():
return render_template(
"search/advanced_search.html",
title="IndieWeb Search Advanced Search Options"
)
@main.route("/api/post-type")
def get_original_post_type():
page_to_check = request.args.get("url")
mf2_parsed = mf2py.parse(page_to_check)
if not mf2_parsed:
return jsonify({"status": "failed", "result": ""})
if not mf2_parsed["items"]:
return jsonify({"status": "failed", "result": ""})
# get h_entry
h_entry = [i for i in mf2_parsed["items"] if i["type"] == ["h-entry"]]
result = indieweb_utils.get_post_type(h_entry)
return jsonify({"status": "success", "result": result})
@main.route("/api/authorship")
def get_post_author():
page_to_check = request.args.get("url")
mf2_parsed = mf2py.parse(page_to_check)
if not mf2_parsed:
return jsonify({"status": "failed", "message": "No microformats could be found on this page", "author": []})
if not mf2_parsed["items"]:
return jsonify({"status": "failed", "message": "No microformats could be found on this page", "author": []})
# get h_entry
h_entry = [i for i in mf2_parsed["items"] if i["type"] == ["h-entry"]]
h_card = [i for i in mf2_parsed["items"] if i["type"] == ["h-card"]]
if not h_entry and h_card == []:
return jsonify({"status": "failed", "message": "No h-entry could be found on this page", "author": []})
if h_card == []:
for i in h_entry["items"]:
if i['type'] == ['h-entry']:
if i['properties'].get('author'):
# if author is h_card
if type(i['properties']['author'][0]) == dict and i['properties']['author'][0].get('type') == ['h-card']:
h_card = i['properties']['author'][0]
elif type(i['properties']['author']) == list:
h_card = i['properties']['author'][0]
result = indieweb_utils.discover_author(h_card, h_entry, page_to_check, [])
return jsonify({"status": "success", "result": result})
@main.route("/stats")
def stats():
count_request = requests.get("https://es-indieweb-search.jamesg.blog/count").json()
count = count_request["es_count"]["count"]
domains = count_request["domains"]
headers = {
"Authorization": config.ELASTICSEARCH_API_TOKEN
}
feed_breakdown_request = requests.get("https://es-indieweb-search.jamesg.blog/feed_breakdown", headers=headers).json()
special_stats = requests.get("https://es-indieweb-search.jamesg.blog/special_stats", headers=headers).json()
top_linked_assets = special_stats["top_ten_links"]
link_types = special_stats["link_microformat_instances"]
return render_template(
"search/stats.html",
count=count,
domains=domains,
title="IndieWeb Search Index Stats",
feed_breakdown=feed_breakdown_request,
top_linked_assets=top_linked_assets,
link_types=link_types
)
@main.route("/about")
def about():
return render_template("search/about.html", title="About IndieWeb Search")
| true
| true
|
790e7285e09d46500a56e5d22afa96479369a23f
| 6,048
|
py
|
Python
|
plotly/validators/violin/hoverlabel/__init__.py
|
piyush1301/plotly.py
|
50cd5c4cd4732042422751c7760acbab8dd8a50d
|
[
"MIT"
] | 6
|
2019-05-03T02:12:04.000Z
|
2020-03-01T06:33:21.000Z
|
plotly/validators/violin/hoverlabel/__init__.py
|
piyush1301/plotly.py
|
50cd5c4cd4732042422751c7760acbab8dd8a50d
|
[
"MIT"
] | null | null | null |
plotly/validators/violin/hoverlabel/__init__.py
|
piyush1301/plotly.py
|
50cd5c4cd4732042422751c7760acbab8dd8a50d
|
[
"MIT"
] | 5
|
2019-05-18T16:50:11.000Z
|
2021-07-06T21:14:36.000Z
|
import _plotly_utils.basevalidators
class NamelengthsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name='namelengthsrc',
parent_name='violin.hoverlabel',
**kwargs
):
super(NamelengthsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'none'),
role=kwargs.pop('role', 'info'),
**kwargs
)
import _plotly_utils.basevalidators
class NamelengthValidator(_plotly_utils.basevalidators.IntegerValidator):
def __init__(
self,
plotly_name='namelength',
parent_name='violin.hoverlabel',
**kwargs
):
super(NamelengthValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop('array_ok', True),
edit_type=kwargs.pop('edit_type', 'none'),
min=kwargs.pop('min', -1),
role=kwargs.pop('role', 'style'),
**kwargs
)
import _plotly_utils.basevalidators
class FontValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(
self, plotly_name='font', parent_name='violin.hoverlabel', **kwargs
):
super(FontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop('data_class_str', 'Font'),
data_docs=kwargs.pop(
'data_docs', """
color
colorsrc
Sets the source reference on plot.ly for color
.
family
HTML font family - the typeface that will be
applied by the web browser. The web browser
will only be able to apply a font if it is
available on the system which it operates.
Provide multiple font families, separated by
commas, to indicate the preference in which to
apply fonts if they aren't available on the
system. The plotly service (at https://plot.ly
or on-premise) generates images on a server,
where only a select number of fonts are
installed and supported. These include "Arial",
"Balto", "Courier New", "Droid Sans",, "Droid
Serif", "Droid Sans Mono", "Gravitas One", "Old
Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on plot.ly for
family .
size
sizesrc
Sets the source reference on plot.ly for size
.
"""
),
**kwargs
)
import _plotly_utils.basevalidators
class BordercolorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name='bordercolorsrc',
parent_name='violin.hoverlabel',
**kwargs
):
super(BordercolorsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'none'),
role=kwargs.pop('role', 'info'),
**kwargs
)
import _plotly_utils.basevalidators
class BordercolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self,
plotly_name='bordercolor',
parent_name='violin.hoverlabel',
**kwargs
):
super(BordercolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop('array_ok', True),
edit_type=kwargs.pop('edit_type', 'none'),
role=kwargs.pop('role', 'style'),
**kwargs
)
import _plotly_utils.basevalidators
class BgcolorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name='bgcolorsrc',
parent_name='violin.hoverlabel',
**kwargs
):
super(BgcolorsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'none'),
role=kwargs.pop('role', 'info'),
**kwargs
)
import _plotly_utils.basevalidators
class BgcolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name='bgcolor', parent_name='violin.hoverlabel', **kwargs
):
super(BgcolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop('array_ok', True),
edit_type=kwargs.pop('edit_type', 'none'),
role=kwargs.pop('role', 'style'),
**kwargs
)
import _plotly_utils.basevalidators
class AlignsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name='alignsrc',
parent_name='violin.hoverlabel',
**kwargs
):
super(AlignsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'none'),
role=kwargs.pop('role', 'info'),
**kwargs
)
import _plotly_utils.basevalidators
class AlignValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name='align', parent_name='violin.hoverlabel', **kwargs
):
super(AlignValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop('array_ok', True),
edit_type=kwargs.pop('edit_type', 'none'),
role=kwargs.pop('role', 'style'),
values=kwargs.pop('values', ['left', 'right', 'auto']),
**kwargs
)
| 28.8
| 78
| 0.590112
|
import _plotly_utils.basevalidators
class NamelengthsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name='namelengthsrc',
parent_name='violin.hoverlabel',
**kwargs
):
super(NamelengthsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'none'),
role=kwargs.pop('role', 'info'),
**kwargs
)
import _plotly_utils.basevalidators
class NamelengthValidator(_plotly_utils.basevalidators.IntegerValidator):
def __init__(
self,
plotly_name='namelength',
parent_name='violin.hoverlabel',
**kwargs
):
super(NamelengthValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop('array_ok', True),
edit_type=kwargs.pop('edit_type', 'none'),
min=kwargs.pop('min', -1),
role=kwargs.pop('role', 'style'),
**kwargs
)
import _plotly_utils.basevalidators
class FontValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(
self, plotly_name='font', parent_name='violin.hoverlabel', **kwargs
):
super(FontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop('data_class_str', 'Font'),
data_docs=kwargs.pop(
'data_docs', """
color
colorsrc
Sets the source reference on plot.ly for color
.
family
HTML font family - the typeface that will be
applied by the web browser. The web browser
will only be able to apply a font if it is
available on the system which it operates.
Provide multiple font families, separated by
commas, to indicate the preference in which to
apply fonts if they aren't available on the
system. The plotly service (at https://plot.ly
or on-premise) generates images on a server,
where only a select number of fonts are
installed and supported. These include "Arial",
"Balto", "Courier New", "Droid Sans",, "Droid
Serif", "Droid Sans Mono", "Gravitas One", "Old
Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on plot.ly for
family .
size
sizesrc
Sets the source reference on plot.ly for size
.
"""
),
**kwargs
)
import _plotly_utils.basevalidators
class BordercolorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name='bordercolorsrc',
parent_name='violin.hoverlabel',
**kwargs
):
super(BordercolorsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'none'),
role=kwargs.pop('role', 'info'),
**kwargs
)
import _plotly_utils.basevalidators
class BordercolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self,
plotly_name='bordercolor',
parent_name='violin.hoverlabel',
**kwargs
):
super(BordercolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop('array_ok', True),
edit_type=kwargs.pop('edit_type', 'none'),
role=kwargs.pop('role', 'style'),
**kwargs
)
import _plotly_utils.basevalidators
class BgcolorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name='bgcolorsrc',
parent_name='violin.hoverlabel',
**kwargs
):
super(BgcolorsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'none'),
role=kwargs.pop('role', 'info'),
**kwargs
)
import _plotly_utils.basevalidators
class BgcolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name='bgcolor', parent_name='violin.hoverlabel', **kwargs
):
super(BgcolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop('array_ok', True),
edit_type=kwargs.pop('edit_type', 'none'),
role=kwargs.pop('role', 'style'),
**kwargs
)
import _plotly_utils.basevalidators
class AlignsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name='alignsrc',
parent_name='violin.hoverlabel',
**kwargs
):
super(AlignsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'none'),
role=kwargs.pop('role', 'info'),
**kwargs
)
import _plotly_utils.basevalidators
class AlignValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name='align', parent_name='violin.hoverlabel', **kwargs
):
super(AlignValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop('array_ok', True),
edit_type=kwargs.pop('edit_type', 'none'),
role=kwargs.pop('role', 'style'),
values=kwargs.pop('values', ['left', 'right', 'auto']),
**kwargs
)
| true
| true
|
790e72f872c82ca6398e4e0770eef1c3e634e5d4
| 3,724
|
py
|
Python
|
bindsnet_master/examples/breakout/random_network_baseline.py
|
Singular-Brain/ProjectBrain
|
2d22d45c13a86825c0dcaf517a59e02f2c4f6164
|
[
"MIT"
] | null | null | null |
bindsnet_master/examples/breakout/random_network_baseline.py
|
Singular-Brain/ProjectBrain
|
2d22d45c13a86825c0dcaf517a59e02f2c4f6164
|
[
"MIT"
] | null | null | null |
bindsnet_master/examples/breakout/random_network_baseline.py
|
Singular-Brain/ProjectBrain
|
2d22d45c13a86825c0dcaf517a59e02f2c4f6164
|
[
"MIT"
] | null | null | null |
import torch
import argparse
from bindsnet.network import Network
from bindsnet.learning import Hebbian
from bindsnet.pipeline import EnvironmentPipeline
from bindsnet.encoding import bernoulli
from bindsnet.network.monitors import Monitor
from bindsnet.environment import GymEnvironment
from bindsnet.network.topology import Connection
from bindsnet.network.nodes import Input, LIFNodes
from bindsnet.pipeline.action import select_multinomial
parser = argparse.ArgumentParser()
parser.add_argument("-n", type=int, default=1000000)
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--n_neurons", type=int, default=100)
parser.add_argument("--dt", type=float, default=1.0)
parser.add_argument("--plot_interval", type=int, default=10)
parser.add_argument("--render_interval", type=int, default=10)
parser.add_argument("--print_interval", type=int, default=100)
parser.add_argument("--gpu", dest="gpu", action="store_true")
parser.set_defaults(plot=False, render=False, gpu=False)
args = parser.parse_args()
n = args.n
seed = args.seed
n_neurons = args.n_neurons
dt = args.dt
plot_interval = args.plot_interval
render_interval = args.render_interval
print_interval = args.print_interval
gpu = args.gpu
if gpu:
torch.set_default_tensor_type("torch.cuda.FloatTensor")
torch.cuda.manual_seed_all(seed)
else:
torch.manual_seed(seed)
# Build network.
network = Network(dt=dt)
# Layers of neurons.
inpt = Input(shape=(1, 1, 1, 80, 80), traces=True) # Input layer
exc = LIFNodes(n=n_neurons, refrac=0, traces=True) # Excitatory layer
readout = LIFNodes(n=4, refrac=0, traces=True) # Readout layer
layers = {"X": inpt, "E": exc, "R": readout}
# Connections between layers.
# Input -> excitatory.
w = 0.01 * torch.rand(layers["X"].n, layers["E"].n)
input_exc_conn = Connection(
source=layers["X"],
target=layers["E"],
w=0.01 * torch.rand(layers["X"].n, layers["E"].n),
wmax=0.02,
norm=0.01 * layers["X"].n,
)
# Excitatory -> readout.
exc_readout_conn = Connection(
source=layers["E"],
target=layers["R"],
w=0.01 * torch.rand(layers["E"].n, layers["R"].n),
update_rule=Hebbian,
nu=[1e-2, 1e-2],
norm=0.5 * layers["E"].n,
)
# Spike recordings for all layers.
spikes = {}
for layer in layers:
spikes[layer] = Monitor(layers[layer], ["s"], time=plot_interval)
# Voltage recordings for excitatory and readout layers.
voltages = {}
for layer in set(layers.keys()) - {"X"}:
voltages[layer] = Monitor(layers[layer], ["v"], time=plot_interval)
# Add all layers and connections to the network.
for layer in layers:
network.add_layer(layers[layer], name=layer)
network.add_connection(input_exc_conn, source="X", target="E")
network.add_connection(exc_readout_conn, source="E", target="R")
# Add all monitors to the network.
for layer in layers:
network.add_monitor(spikes[layer], name="%s_spikes" % layer)
if layer in voltages:
network.add_monitor(voltages[layer], name="%s_voltages" % layer)
# Load the Breakout environment.
environment = GymEnvironment("BreakoutDeterministic-v4")
environment.reset()
pipeline = EnvironmentPipeline(
network,
environment,
encoding=bernoulli,
time=1,
history=5,
delta=10,
plot_interval=plot_interval,
print_interval=print_interval,
render_interval=render_interval,
action_function=select_multinomial,
output="R",
)
total = 0
rewards = []
avg_rewards = []
lengths = []
avg_lengths = []
i = 0
try:
while i < n:
result = pipeline.env_step()
pipeline.step(result)
is_done = result[2]
if is_done:
pipeline.reset_state_variables()
i += 1
except KeyboardInterrupt:
environment.close()
| 27.791045
| 72
| 0.713212
|
import torch
import argparse
from bindsnet.network import Network
from bindsnet.learning import Hebbian
from bindsnet.pipeline import EnvironmentPipeline
from bindsnet.encoding import bernoulli
from bindsnet.network.monitors import Monitor
from bindsnet.environment import GymEnvironment
from bindsnet.network.topology import Connection
from bindsnet.network.nodes import Input, LIFNodes
from bindsnet.pipeline.action import select_multinomial
parser = argparse.ArgumentParser()
parser.add_argument("-n", type=int, default=1000000)
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--n_neurons", type=int, default=100)
parser.add_argument("--dt", type=float, default=1.0)
parser.add_argument("--plot_interval", type=int, default=10)
parser.add_argument("--render_interval", type=int, default=10)
parser.add_argument("--print_interval", type=int, default=100)
parser.add_argument("--gpu", dest="gpu", action="store_true")
parser.set_defaults(plot=False, render=False, gpu=False)
args = parser.parse_args()
n = args.n
seed = args.seed
n_neurons = args.n_neurons
dt = args.dt
plot_interval = args.plot_interval
render_interval = args.render_interval
print_interval = args.print_interval
gpu = args.gpu
if gpu:
torch.set_default_tensor_type("torch.cuda.FloatTensor")
torch.cuda.manual_seed_all(seed)
else:
torch.manual_seed(seed)
network = Network(dt=dt)
inpt = Input(shape=(1, 1, 1, 80, 80), traces=True)
exc = LIFNodes(n=n_neurons, refrac=0, traces=True)
readout = LIFNodes(n=4, refrac=0, traces=True)
layers = {"X": inpt, "E": exc, "R": readout}
w = 0.01 * torch.rand(layers["X"].n, layers["E"].n)
input_exc_conn = Connection(
source=layers["X"],
target=layers["E"],
w=0.01 * torch.rand(layers["X"].n, layers["E"].n),
wmax=0.02,
norm=0.01 * layers["X"].n,
)
exc_readout_conn = Connection(
source=layers["E"],
target=layers["R"],
w=0.01 * torch.rand(layers["E"].n, layers["R"].n),
update_rule=Hebbian,
nu=[1e-2, 1e-2],
norm=0.5 * layers["E"].n,
)
spikes = {}
for layer in layers:
spikes[layer] = Monitor(layers[layer], ["s"], time=plot_interval)
voltages = {}
for layer in set(layers.keys()) - {"X"}:
voltages[layer] = Monitor(layers[layer], ["v"], time=plot_interval)
for layer in layers:
network.add_layer(layers[layer], name=layer)
network.add_connection(input_exc_conn, source="X", target="E")
network.add_connection(exc_readout_conn, source="E", target="R")
for layer in layers:
network.add_monitor(spikes[layer], name="%s_spikes" % layer)
if layer in voltages:
network.add_monitor(voltages[layer], name="%s_voltages" % layer)
environment = GymEnvironment("BreakoutDeterministic-v4")
environment.reset()
pipeline = EnvironmentPipeline(
network,
environment,
encoding=bernoulli,
time=1,
history=5,
delta=10,
plot_interval=plot_interval,
print_interval=print_interval,
render_interval=render_interval,
action_function=select_multinomial,
output="R",
)
total = 0
rewards = []
avg_rewards = []
lengths = []
avg_lengths = []
i = 0
try:
while i < n:
result = pipeline.env_step()
pipeline.step(result)
is_done = result[2]
if is_done:
pipeline.reset_state_variables()
i += 1
except KeyboardInterrupt:
environment.close()
| true
| true
|
790e7337f486d034d1c34e7f36b05469c5a79ef6
| 274
|
py
|
Python
|
python/itertools-product.py
|
gajubadge11/HackerRank-1
|
7b136ccaa1ed47ae737467ace6b494c720ccb942
|
[
"MIT"
] | 340
|
2018-06-17T19:45:56.000Z
|
2022-03-22T02:26:15.000Z
|
python/itertools-product.py
|
gajubadge11/HackerRank-1
|
7b136ccaa1ed47ae737467ace6b494c720ccb942
|
[
"MIT"
] | 3
|
2021-02-02T17:17:29.000Z
|
2021-05-18T10:06:04.000Z
|
python/itertools-product.py
|
gajubadge11/HackerRank-1
|
7b136ccaa1ed47ae737467ace6b494c720ccb942
|
[
"MIT"
] | 229
|
2019-04-20T08:28:49.000Z
|
2022-03-31T04:23:52.000Z
|
#!/usr/bin/env python3
from itertools import product
if __name__ == "__main__":
arr1 = list(map(int, input().strip().split(' ')))
arr2 = list(map(int, input().strip().split(' ')))
for el in product(arr1, arr2):
print("{} ".format(el), end='')
| 24.909091
| 53
| 0.569343
|
from itertools import product
if __name__ == "__main__":
arr1 = list(map(int, input().strip().split(' ')))
arr2 = list(map(int, input().strip().split(' ')))
for el in product(arr1, arr2):
print("{} ".format(el), end='')
| true
| true
|
790e73a7152d3b0e4f788b230eb22120fd104d5c
| 45,576
|
py
|
Python
|
wokkel/muc.py
|
Gandi/wokkel
|
74631b43f5016ac32443468fd608a9baa1ecce39
|
[
"MIT"
] | null | null | null |
wokkel/muc.py
|
Gandi/wokkel
|
74631b43f5016ac32443468fd608a9baa1ecce39
|
[
"MIT"
] | null | null | null |
wokkel/muc.py
|
Gandi/wokkel
|
74631b43f5016ac32443468fd608a9baa1ecce39
|
[
"MIT"
] | null | null | null |
# -*- test-case-name: wokkel.test.test_muc -*-
#
# Copyright (c) Ralph Meijer.
# See LICENSE for details.
"""
XMPP Multi-User Chat protocol.
This protocol is specified in
U{XEP-0045<http://xmpp.org/extensions/xep-0045.html>}.
"""
from dateutil.tz import tzutc
from zope.interface import implements
from twisted.internet import defer
from twisted.words.protocols.jabber import jid, error, xmlstream
from twisted.words.xish import domish
from wokkel import data_form, generic, iwokkel, xmppim
from wokkel.compat import Values, ValueConstant
from wokkel.delay import Delay, DelayMixin
from wokkel.subprotocols import XMPPHandler
from wokkel.iwokkel import IMUCClient
# Multi User Chat namespaces
NS_MUC = 'http://jabber.org/protocol/muc'
NS_MUC_USER = NS_MUC + '#user'
NS_MUC_ADMIN = NS_MUC + '#admin'
NS_MUC_OWNER = NS_MUC + '#owner'
NS_MUC_ROOMINFO = NS_MUC + '#roominfo'
NS_MUC_CONFIG = NS_MUC + '#roomconfig'
NS_MUC_REQUEST = NS_MUC + '#request'
NS_MUC_REGISTER = NS_MUC + '#register'
NS_REGISTER = 'jabber:iq:register'
MESSAGE = '/message'
PRESENCE = '/presence'
GROUPCHAT = MESSAGE +'[@type="groupchat"]'
DEFER_TIMEOUT = 30 # basic timeout is 30 seconds
class STATUS_CODE(Values):
REALJID_PUBLIC = ValueConstant(100)
AFFILIATION_CHANGED = ValueConstant(101)
UNAVAILABLE_SHOWN = ValueConstant(102)
UNAVAILABLE_NOT_SHOWN = ValueConstant(103)
CONFIGURATION_CHANGED = ValueConstant(104)
SELF_PRESENCE = ValueConstant(110)
LOGGING_ENABLED = ValueConstant(170)
LOGGING_DISABLED = ValueConstant(171)
NON_ANONYMOUS = ValueConstant(172)
SEMI_ANONYMOUS = ValueConstant(173)
FULLY_ANONYMOUS = ValueConstant(174)
ROOM_CREATED = ValueConstant(201)
NICK_ASSIGNED = ValueConstant(210)
BANNED = ValueConstant(301)
NEW_NICK = ValueConstant(303)
KICKED = ValueConstant(307)
REMOVED_AFFILIATION = ValueConstant(321)
REMOVED_MEMBERSHIP = ValueConstant(322)
REMOVED_SHUTDOWN = ValueConstant(332)
class Statuses(set):
"""
Container of MUC status conditions.
This is currently implemented as a set of constant values from
L{STATUS_CODE}. Instances of this class provide L{IMUCStatuses}, that
defines the supported operations. Even though this class currently derives
from C{set}, future versions might not. This provides an upgrade path to
cater for extensible status conditions, as defined in
U{XEP-0306<http://xmpp.org/extensions/xep-0306.html>}.
"""
implements(iwokkel.IMUCStatuses)
class _FormRequest(generic.Request):
"""
Base class for form exchange requests.
"""
requestNamespace = None
formNamespace = None
def __init__(self, recipient, sender=None, options=None):
if options is None:
stanzaType = 'get'
else:
stanzaType = 'set'
generic.Request.__init__(self, recipient, sender, stanzaType)
self.options = options
def toElement(self):
element = generic.Request.toElement(self)
query = element.addElement((self.requestNamespace, 'query'))
if self.options is None:
# This is a request for the configuration form.
form = None
elif self.options is False:
form = data_form.Form(formType='cancel')
else:
form = data_form.Form(formType='submit',
formNamespace=self.formNamespace)
form.makeFields(self.options)
if form is not None:
query.addChild(form.toElement())
return element
class ConfigureRequest(_FormRequest):
"""
Configure MUC room request.
http://xmpp.org/extensions/xep-0045.html#roomconfig
"""
requestNamespace = NS_MUC_OWNER
formNamespace = NS_MUC_CONFIG
class RegisterRequest(_FormRequest):
"""
Register request.
http://xmpp.org/extensions/xep-0045.html#register
"""
requestNamespace = NS_REGISTER
formNamespace = NS_MUC_REGISTER
class AdminItem(object):
"""
Item representing role and/or affiliation for admin request.
"""
def __init__(self, affiliation=None, role=None, entity=None, nick=None,
reason=None):
self.affiliation = affiliation
self.role = role
self.entity = entity
self.nick = nick
self.reason = reason
def toElement(self):
element = domish.Element((NS_MUC_ADMIN, 'item'))
if self.entity:
element['jid'] = self.entity.full()
if self.nick:
element['nick'] = self.nick
if self.affiliation:
element['affiliation'] = self.affiliation
if self.role:
element['role'] = self.role
if self.reason:
element.addElement('reason', content=self.reason)
return element
@classmethod
def fromElement(Class, element):
item = Class()
if element.hasAttribute('jid'):
item.entity = jid.JID(element['jid'])
item.nick = element.getAttribute('nick')
item.affiliation = element.getAttribute('affiliation')
item.role = element.getAttribute('role')
for child in element.elements(NS_MUC_ADMIN, 'reason'):
item.reason = unicode(child)
return item
class AdminStanza(generic.Request):
"""
An admin request or response.
"""
childParsers = {(NS_MUC_ADMIN, 'query'): '_childParser_query'}
def toElement(self):
element = generic.Request.toElement(self)
element.addElement((NS_MUC_ADMIN, 'query'))
if self.items:
for item in self.items:
element.query.addChild(item.toElement())
return element
def _childParser_query(self, element):
self.items = []
for child in element.elements(NS_MUC_ADMIN, 'item'):
self.items.append(AdminItem.fromElement(child))
class DestructionRequest(generic.Request):
"""
Room destruction request.
@param reason: Optional reason for the destruction of this room.
@type reason: C{unicode}.
@param alternate: Optional room JID of an alternate venue.
@type alternate: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param password: Optional password for entering the alternate venue.
@type password: C{unicode}
"""
stanzaType = 'set'
def __init__(self, recipient, sender=None, reason=None, alternate=None,
password=None):
generic.Request.__init__(self, recipient, sender)
self.reason = reason
self.alternate = alternate
self.password = password
def toElement(self):
element = generic.Request.toElement(self)
element.addElement((NS_MUC_OWNER, 'query'))
element.query.addElement('destroy')
if self.alternate:
element.query.destroy['jid'] = self.alternate.full()
if self.password:
element.query.destroy.addElement('password',
content=self.password)
if self.reason:
element.query.destroy.addElement('reason', content=self.reason)
return element
class GroupChat(xmppim.Message, DelayMixin):
"""
A groupchat message.
"""
stanzaType = 'groupchat'
def toElement(self, legacyDelay=False):
"""
Render into a domish Element.
@param legacyDelay: If C{True} send the delayed delivery information
in legacy format.
"""
element = xmppim.Message.toElement(self)
if self.delay:
element.addChild(self.delay.toElement(legacy=legacyDelay))
return element
class PrivateChat(xmppim.Message):
"""
A chat message.
"""
stanzaType = 'chat'
class InviteMessage(xmppim.Message):
def __init__(self, recipient=None, sender=None, invitee=None, reason=None):
xmppim.Message.__init__(self, recipient, sender)
self.invitee = invitee
self.reason = reason
def toElement(self):
element = xmppim.Message.toElement(self)
child = element.addElement((NS_MUC_USER, 'x'))
child.addElement('invite')
child.invite['to'] = self.invitee.full()
if self.reason:
child.invite.addElement('reason', content=self.reason)
return element
class HistoryOptions(object):
"""
A history configuration object.
@ivar maxchars: Limit the total number of characters in the history to "X"
(where the character count is the characters of the complete XML
stanzas, not only their XML character data).
@type maxchars: C{int}
@ivar maxstanzas: Limit the total number of messages in the history to "X".
@type mazstanzas: C{int}
@ivar seconds: Send only the messages received in the last "X" seconds.
@type seconds: C{int}
@ivar since: Send only the messages received since the datetime specified.
Note that this must be an offset-aware instance.
@type since: L{datetime.datetime}
"""
attributes = ['maxChars', 'maxStanzas', 'seconds', 'since']
def __init__(self, maxChars=None, maxStanzas=None, seconds=None,
since=None):
self.maxChars = maxChars
self.maxStanzas = maxStanzas
self.seconds = seconds
self.since = since
def toElement(self):
"""
Returns a L{domish.Element} representing the history options.
"""
element = domish.Element((NS_MUC, 'history'))
for key in self.attributes:
value = getattr(self, key, None)
if value is not None:
if key == 'since':
stamp = value.astimezone(tzutc())
element[key] = stamp.strftime('%Y-%m-%dT%H:%M:%SZ')
else:
element[key.lower()] = str(value)
return element
class BasicPresence(xmppim.AvailabilityPresence):
"""
Availability presence sent from MUC client to service.
@type history: L{HistoryOptions}
"""
history = None
password = None
def toElement(self):
element = xmppim.AvailabilityPresence.toElement(self)
muc = element.addElement((NS_MUC, 'x'))
if self.password:
muc.addElement('password', content=self.password)
if self.history:
muc.addChild(self.history.toElement())
return element
class UserPresence(xmppim.AvailabilityPresence):
"""
Availability presence sent from MUC service to client.
@ivar affiliation: Affiliation of the entity to the room.
@type affiliation: C{unicode}
@ivar role: Role of the entity in the room.
@type role: C{unicode}
@ivar entity: The real JID of the entity this presence is from.
@type entity: L{JID<twisted.words.protocols.jabber.jid.JID>}
@ivar mucStatuses: Set of one or more status codes from L{STATUS_CODE}.
See L{Statuses} for usage notes.
@type mucStatuses: L{Statuses}
@ivar nick: The nick name of the entity in the room.
@type nick: C{unicode}
"""
affiliation = None
role = None
entity = None
nick = None
mucStatuses = None
childParsers = {(NS_MUC_USER, 'x'): '_childParser_mucUser'}
def __init__(self, *args, **kwargs):
self.mucStatuses = Statuses()
xmppim.AvailabilityPresence.__init__(self, *args, **kwargs)
def _childParser_mucUser(self, element):
"""
Parse the MUC user extension element.
"""
for child in element.elements():
if child.uri != NS_MUC_USER:
continue
elif child.name == 'status':
try:
value = int(child.getAttribute('code'))
statusCode = STATUS_CODE.lookupByValue(value)
except (TypeError, ValueError):
continue
self.mucStatuses.add(statusCode)
elif child.name == 'item':
if child.hasAttribute('jid'):
self.entity = jid.JID(child['jid'])
self.nick = child.getAttribute('nick')
self.affiliation = child.getAttribute('affiliation')
self.role = child.getAttribute('role')
for reason in child.elements(NS_MUC_ADMIN, 'reason'):
self.reason = unicode(reason)
# TODO: destroy
class VoiceRequest(xmppim.Message):
"""
Voice request message.
"""
def toElement(self):
element = xmppim.Message.toElement(self)
# build data form
form = data_form.Form('submit', formNamespace=NS_MUC_REQUEST)
form.addField(data_form.Field(var='muc#role',
value='participant',
label='Requested role'))
element.addChild(form.toElement())
return element
class MUCClientProtocol(xmppim.BasePresenceProtocol):
"""
Multi-User Chat client protocol.
"""
timeout = None
presenceTypeParserMap = {
'error': generic.ErrorStanza,
'available': UserPresence,
'unavailable': UserPresence,
}
def __init__(self, reactor=None):
XMPPHandler.__init__(self)
if reactor:
self._reactor = reactor
else:
from twisted.internet import reactor
self._reactor = reactor
def connectionInitialized(self):
"""
Called when the XML stream has been initialized.
It initializes several XPath events to handle MUC stanzas that come
in.
"""
xmppim.BasePresenceProtocol.connectionInitialized(self)
self.xmlstream.addObserver(GROUPCHAT, self._onGroupChat)
self._roomOccupantMap = {}
def _onGroupChat(self, element):
"""
A group chat message has been received from a MUC room.
There are a few event methods that may get called here.
L{receivedGroupChat}, L{receivedSubject} or L{receivedHistory}.
"""
message = GroupChat.fromElement(element)
self.groupChatReceived(message)
def groupChatReceived(self, message):
"""
Called when a groupchat message was received.
This method is called with a parsed representation of a received
groupchat message and can be overridden for further processing.
For regular groupchat message, the C{body} attribute contains the
message body. Conversation history sent by the room upon joining, will
have the C{delay} attribute set, room subject changes the C{subject}
attribute. See L{GroupChat} for details.
@param message: Groupchat message.
@type message: L{GroupChat}
"""
pass
def _sendDeferred(self, stanza):
"""
Send presence stanza, adding a deferred with a timeout.
@param stanza: The presence stanza to send over the wire.
@type stanza: L{generic.Stanza}
@param timeout: The number of seconds to wait before the deferred is
timed out.
@type timeout: C{int}
The deferred object L{defer.Deferred} is returned.
"""
def onResponse(element):
if element.getAttribute('type') == 'error':
d.errback(error.exceptionFromStanza(element))
else:
d.callback(UserPresence.fromElement(element))
def onTimeout():
d.errback(xmlstream.TimeoutError("Timeout waiting for response."))
def cancelTimeout(result):
if call.active():
call.cancel()
return result
def recordOccupant(presence):
occupantJID = presence.sender
roomJID = occupantJID.userhostJID()
self._roomOccupantMap[roomJID] = occupantJID
return presence
call = self._reactor.callLater(DEFER_TIMEOUT, onTimeout)
d = defer.Deferred()
d.addBoth(cancelTimeout)
d.addCallback(recordOccupant)
query = "/presence[@from='%s' or (@from='%s' and @type='error')]" % (
stanza.recipient.full(), stanza.recipient.userhost())
self.xmlstream.addOnetimeObserver(query, onResponse, priority=-1)
self.xmlstream.send(stanza.toElement())
return d
def join(self, roomJID, nick, historyOptions=None, password=None):
"""
Join a MUC room by sending presence to it.
@param roomJID: The JID of the room the entity is joining.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param nick: The nick name for the entitity joining the room.
@type nick: C{unicode}
@param historyOptions: Options for conversation history sent by the
room upon joining.
@type historyOptions: L{HistoryOptions}
@param password: Optional password for the room.
@type password: C{unicode}
@return: A deferred that fires when the entity is in the room or an
error has occurred.
"""
occupantJID = jid.JID(tuple=(roomJID.user, roomJID.host, nick))
presence = BasicPresence(recipient=occupantJID)
if password:
presence.password = password
if historyOptions:
presence.history = historyOptions
return self._sendDeferred(presence)
def nick(self, roomJID, nick):
"""
Change an entity's nick name in a MUC room.
See: http://xmpp.org/extensions/xep-0045.html#changenick
@param roomJID: The JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param nick: The new nick name within the room.
@type nick: C{unicode}
"""
occupantJID = jid.JID(tuple=(roomJID.user, roomJID.host, nick))
presence = BasicPresence(recipient=occupantJID)
return self._sendDeferred(presence)
def status(self, roomJID, show=None, status=None):
"""
Change user status.
See: http://xmpp.org/extensions/xep-0045.html#changepres
@param roomJID: The Room JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param show: The availability of the entity. Common values are xa,
available, etc
@type show: C{unicode}
@param status: The current status of the entity.
@type status: C{unicode}
"""
occupantJID = self._roomOccupantMap[roomJID]
presence = BasicPresence(recipient=occupantJID, show=show,
status=status)
return self._sendDeferred(presence)
def leave(self, roomJID):
"""
Leave a MUC room.
See: http://xmpp.org/extensions/xep-0045.html#exit
@param roomJID: The JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
occupantJID = self._roomOccupantMap[roomJID]
presence = xmppim.AvailabilityPresence(recipient=occupantJID,
available=False)
return self._sendDeferred(presence)
def groupChat(self, roomJID, body):
"""
Send a groupchat message.
"""
message = GroupChat(recipient=roomJID, body=body)
self.send(message.toElement())
def chat(self, occupantJID, body):
"""
Send a private chat message to a user in a MUC room.
See: http://xmpp.org/extensions/xep-0045.html#privatemessage
@param occupantJID: The Room JID of the other user.
@type occupantJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
message = PrivateChat(recipient=occupantJID, body=body)
self.send(message.toElement())
def subject(self, roomJID, subject):
"""
Change the subject of a MUC room.
See: http://xmpp.org/extensions/xep-0045.html#subject-mod
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param subject: The subject you want to set.
@type subject: C{unicode}
"""
message = GroupChat(roomJID.userhostJID(), subject=subject)
self.send(message.toElement())
def invite(self, roomJID, invitee, reason=None):
"""
Invite a xmpp entity to a MUC room.
See: http://xmpp.org/extensions/xep-0045.html#invite
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param invitee: The entity that is being invited.
@type invitee: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param reason: The reason for the invite.
@type reason: C{unicode}
"""
message = InviteMessage(recipient=roomJID, invitee=invitee,
reason=reason)
self.send(message.toElement())
def getRegisterForm(self, roomJID):
"""
Grab the registration form for a MUC room.
@param room: The room jabber/xmpp entity id for the requested
registration form.
@type room: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
def cb(response):
form = data_form.findForm(response.query, NS_MUC_REGISTER)
return form
request = RegisterRequest(recipient=roomJID, options=None)
d = self.request(request)
d.addCallback(cb)
return d
def register(self, roomJID, options):
"""
Send a request to register for a room.
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param options: A mapping of field names to values, or C{None} to
cancel.
@type options: C{dict}
"""
if options is None:
options = False
request = RegisterRequest(recipient=roomJID, options=options)
return self.request(request)
def voice(self, roomJID):
"""
Request voice for a moderated room.
@param roomJID: The room jabber/xmpp entity id.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
message = VoiceRequest(recipient=roomJID)
self.xmlstream.send(message.toElement())
def history(self, roomJID, messages):
"""
Send history to create a MUC based on a one on one chat.
See: http://xmpp.org/extensions/xep-0045.html#continue
@param roomJID: The room jabber/xmpp entity id.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param messages: The history to send to the room as an ordered list of
message, represented by a dictionary with the keys
C{'stanza'}, holding the original stanza a
L{domish.Element}, and C{'timestamp'} with the
timestamp.
@type messages: C{list} of L{domish.Element}
"""
for message in messages:
stanza = message['stanza']
stanza['type'] = 'groupchat'
delay = Delay(stamp=message['timestamp'])
sender = stanza.getAttribute('from')
if sender is not None:
delay.sender = jid.JID(sender)
stanza.addChild(delay.toElement())
stanza['to'] = roomJID.userhost()
if stanza.hasAttribute('from'):
del stanza['from']
self.xmlstream.send(stanza)
def getConfiguration(self, roomJID):
"""
Grab the configuration from the room.
This sends an iq request to the room.
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@return: A deferred that fires with the room's configuration form as
a L{data_form.Form} or C{None} if there are no configuration
options available.
"""
def cb(response):
form = data_form.findForm(response.query, NS_MUC_CONFIG)
return form
request = ConfigureRequest(recipient=roomJID, options=None)
d = self.request(request)
d.addCallback(cb)
return d
def configure(self, roomJID, options):
"""
Configure a room.
@param roomJID: The room to configure.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param options: A mapping of field names to values, or C{None} to
cancel.
@type options: C{dict}
"""
if options is None:
options = False
request = ConfigureRequest(recipient=roomJID, options=options)
return self.request(request)
def _getAffiliationList(self, roomJID, affiliation):
"""
Send a request for an affiliation list in a room.
"""
def cb(response):
stanza = AdminStanza.fromElement(response)
return stanza.items
request = AdminStanza(recipient=roomJID, stanzaType='get')
request.items = [AdminItem(affiliation=affiliation)]
d = self.request(request)
d.addCallback(cb)
return d
def _getRoleList(self, roomJID, role):
"""
Send a request for a role list in a room.
"""
def cb(response):
stanza = AdminStanza.fromElement(response)
return stanza.items
request = AdminStanza(recipient=roomJID, stanzaType='get')
request.items = [AdminItem(role=role)]
d = self.request(request)
d.addCallback(cb)
return d
def getMemberList(self, roomJID):
"""
Get the member list of a room.
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
return self._getAffiliationList(roomJID, 'member')
def getAdminList(self, roomJID):
"""
Get the admin list of a room.
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
return self._getAffiliationList(roomJID, 'admin')
def getBanList(self, roomJID):
"""
Get an outcast list from a room.
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
return self._getAffiliationList(roomJID, 'outcast')
def getOwnerList(self, roomJID):
"""
Get an owner list from a room.
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
return self._getAffiliationList(roomJID, 'owner')
def getModeratorList(self, roomJID):
"""
Get the moderator list of a room.
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
d = self._getRoleList(roomJID, 'moderator')
return d
def _setAffiliation(self, roomJID, entity, affiliation,
reason=None, sender=None):
"""
Send a request to change an entity's affiliation to a MUC room.
"""
request = AdminStanza(recipient=roomJID, sender=sender,
stanzaType='set')
item = AdminItem(entity=entity, affiliation=affiliation, reason=reason)
request.items = [item]
return self.request(request)
def _setRole(self, roomJID, nick, role,
reason=None, sender=None):
"""
Send a request to change an occupant's role in a MUC room.
"""
request = AdminStanza(recipient=roomJID, sender=sender,
stanzaType='set')
item = AdminItem(nick=nick, role=role, reason=reason)
request.items = [item]
return self.request(request)
def modifyAffiliationList(self, roomJID, entities, affiliation,
sender=None):
"""
Modify an affiliation list.
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param entities: The list of entities to change for a room.
@type entities: C{list} of
L{JID<twisted.words.protocols.jabber.jid.JID>}
@param affiliation: The affilation to the entities will acquire.
@type affiliation: C{unicode}
@param sender: The entity sending the request.
@type sender: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
request = AdminStanza(recipient=roomJID, sender=sender,
stanzaType='set')
request.items = [AdminItem(entity=entity, affiliation=affiliation)
for entity in entities]
return self.request(request)
def grantVoice(self, roomJID, nick, reason=None, sender=None):
"""
Grant voice to an entity.
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param nick: The nick name for the user in this room.
@type nick: C{unicode}
@param reason: The reason for granting voice to the entity.
@type reason: C{unicode}
@param sender: The entity sending the request.
@type sender: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
return self._setRole(roomJID, nick=nick,
role='participant',
reason=reason, sender=sender)
def revokeVoice(self, roomJID, nick, reason=None, sender=None):
"""
Revoke voice from a participant.
This will disallow the entity to send messages to a moderated room.
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param nick: The nick name for the user in this room.
@type nick: C{unicode}
@param reason: The reason for revoking voice from the entity.
@type reason: C{unicode}
@param sender: The entity sending the request.
@type sender: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
return self._setRole(roomJID, nick=nick, role='visitor',
reason=reason, sender=sender)
def grantModerator(self, roomJID, nick, reason=None, sender=None):
"""
Grant moderator privileges to a MUC room.
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param nick: The nick name for the user in this room.
@type nick: C{unicode}
@param reason: The reason for granting moderation to the entity.
@type reason: C{unicode}
@param sender: The entity sending the request.
@type sender: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
return self._setRole(roomJID, nick=nick, role='moderator',
reason=reason, sender=sender)
def ban(self, roomJID, entity, reason=None, sender=None):
"""
Ban a user from a MUC room.
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param entity: The bare JID of the entity to be banned.
@type entity: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param reason: The reason for banning the entity.
@type reason: C{unicode}
@param sender: The entity sending the request.
@type sender: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
return self._setAffiliation(roomJID, entity, 'outcast',
reason=reason, sender=sender)
def kick(self, roomJID, nick, reason=None, sender=None):
"""
Kick a user from a MUC room.
@param roomJID: The bare JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param nick: The occupant to be banned.
@type nick: C{unicode}
@param reason: The reason given for the kick.
@type reason: C{unicode}
@param sender: The entity sending the request.
@type sender: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
return self._setRole(roomJID, nick, 'none',
reason=reason, sender=sender)
def destroy(self, roomJID, reason=None, alternate=None, password=None):
"""
Destroy a room.
@param roomJID: The JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param reason: The reason for the destruction of the room.
@type reason: C{unicode}
@param alternate: The JID of the room suggested as an alternate venue.
@type alternate: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
request = DestructionRequest(recipient=roomJID, reason=reason,
alternate=alternate, password=password)
return self.request(request)
class User(object):
"""
A user/entity in a multi-user chat room.
"""
def __init__(self, nick, entity=None):
self.nick = nick
self.entity = entity
self.affiliation = 'none'
self.role = 'none'
self.status = None
self.show = None
class Room(object):
"""
A Multi User Chat Room.
An in memory object representing a MUC room from the perspective of
a client.
@ivar roomJID: The Room JID of the MUC room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@ivar nick: The nick name for the client in this room.
@type nick: C{unicode}
@ivar occupantJID: The JID of the occupant in the room. Generated from
roomJID and nick.
@type occupantJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@ivar locked: Flag signalling a locked room. A locked room first needs
to be configured before it can be used. See
L{MUCClientProtocol.getConfiguration} and
L{MUCClientProtocol.configure}.
@type locked: C{bool}
"""
locked = False
def __init__(self, roomJID, nick):
"""
Initialize the room.
"""
self.roomJID = roomJID
self.setNick(nick)
self.roster = {}
def setNick(self, nick):
self.occupantJID = jid.internJID(u"%s/%s" % (self.roomJID, nick))
self.nick = nick
def addUser(self, user):
"""
Add a user to the room roster.
@param user: The user object that is being added to the room.
@type user: L{User}
"""
self.roster[user.nick] = user
def inRoster(self, user):
"""
Check if a user is in the MUC room.
@param user: The user object to check.
@type user: L{User}
"""
return user.nick in self.roster
def getUser(self, nick):
"""
Get a user from the room's roster.
@param nick: The nick for the user in the MUC room.
@type nick: C{unicode}
"""
return self.roster.get(nick)
def removeUser(self, user):
"""
Remove a user from the MUC room's roster.
@param user: The user object to check.
@type user: L{User}
"""
if self.inRoster(user):
del self.roster[user.nick]
class MUCClient(MUCClientProtocol):
"""
Multi-User Chat client protocol.
This is a subclass of L{XMPPHandler} and implements L{IMUCClient}.
@ivar _rooms: Collection of occupied rooms, keyed by the bare JID of the
room. Note that a particular entity can only join a room once
at a time.
@type _rooms: C{dict}
"""
implements(IMUCClient)
def __init__(self, reactor=None):
MUCClientProtocol.__init__(self, reactor)
self._rooms = {}
def _addRoom(self, room):
"""
Add a room to the room collection.
Rooms are stored by the JID of the room itself. I.e. it uses the Room
ID and service parts of the Room JID.
@note: An entity can only join a particular room once.
"""
roomJID = room.occupantJID.userhostJID()
self._rooms[roomJID] = room
def _getRoom(self, roomJID):
"""
Grab a room from the room collection.
This uses the Room ID and service parts of the given JID to look up
the L{Room} instance associated with it.
@type occupantJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
return self._rooms.get(roomJID)
def _removeRoom(self, roomJID):
"""
Delete a room from the room collection.
"""
if roomJID in self._rooms:
del self._rooms[roomJID]
def _getRoomUser(self, stanza):
"""
Lookup the room and user associated with the stanza's sender.
"""
occupantJID = stanza.sender
if not occupantJID:
return None, None
# when a user leaves a room we need to update it
room = self._getRoom(occupantJID.userhostJID())
if room is None:
# not in the room yet
return None, None
# Check if user is in roster
nick = occupantJID.resource
user = room.getUser(nick)
return room, user
def unavailableReceived(self, presence):
"""
Unavailable presence was received.
If this was received from a MUC room occupant JID, that occupant has
left the room.
"""
room, user = self._getRoomUser(presence)
if room is None or user is None:
return
room.removeUser(user)
self.userLeftRoom(room, user)
def availableReceived(self, presence):
"""
Available presence was received.
"""
room, user = self._getRoomUser(presence)
if room is None:
return
if user is None:
nick = presence.sender.resource
user = User(nick, presence.entity)
# Update user status
user.status = presence.status
user.show = presence.show
if room.inRoster(user):
self.userUpdatedStatus(room, user, presence.show, presence.status)
else:
room.addUser(user)
self.userJoinedRoom(room, user)
def groupChatReceived(self, message):
"""
A group chat message has been received from a MUC room.
There are a few event methods that may get called here.
L{receivedGroupChat}, L{receivedSubject} or L{receivedHistory}.
"""
room, user = self._getRoomUser(message)
if room is None:
return
if message.subject:
self.receivedSubject(room, user, message.subject)
elif message.delay is None:
self.receivedGroupChat(room, user, message)
else:
self.receivedHistory(room, user, message)
def userJoinedRoom(self, room, user):
"""
User has joined a MUC room.
This method will need to be modified inorder for clients to
do something when this event occurs.
@param room: The room the user has joined.
@type room: L{Room}
@param user: The user that joined the MUC room.
@type user: L{User}
"""
pass
def userLeftRoom(self, room, user):
"""
User has left a room.
This method will need to be modified inorder for clients to
do something when this event occurs.
@param room: The room the user has joined.
@type room: L{Room}
@param user: The user that left the MUC room.
@type user: L{User}
"""
pass
def userUpdatedStatus(self, room, user, show, status):
"""
User Presence has been received.
This method will need to be modified inorder for clients to
do something when this event occurs.
"""
pass
def receivedSubject(self, room, user, subject):
"""
A (new) room subject has been received.
This method will need to be modified inorder for clients to
do something when this event occurs.
"""
pass
def receivedGroupChat(self, room, user, message):
"""
A groupchat message was received.
@param room: The room the message was received from.
@type room: L{Room}
@param user: The user that sent the message, or C{None} if it was a
message from the room itself.
@type user: L{User}
@param message: The message.
@type message: L{GroupChat}
"""
pass
def receivedHistory(self, room, user, message):
"""
A groupchat message from the room's discussion history was received.
This is identical to L{receivedGroupChat}, with the delayed delivery
information (timestamp and original sender) in C{message.delay}. For
anonymous rooms, C{message.delay.sender} is the room's address.
@param room: The room the message was received from.
@type room: L{Room}
@param user: The user that sent the message, or C{None} if it was a
message from the room itself.
@type user: L{User}
@param message: The message.
@type message: L{GroupChat}
"""
pass
def join(self, roomJID, nick, historyOptions=None,
password=None):
"""
Join a MUC room by sending presence to it.
@param roomJID: The JID of the room the entity is joining.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param nick: The nick name for the entitity joining the room.
@type nick: C{unicode}
@param historyOptions: Options for conversation history sent by the
room upon joining.
@type historyOptions: L{HistoryOptions}
@param password: Optional password for the room.
@type password: C{unicode}
@return: A deferred that fires with the room when the entity is in the
room, or with a failure if an error has occurred.
"""
def cb(presence):
"""
We have presence that says we joined a room.
"""
if STATUS_CODE.ROOM_CREATED in presence.mucStatuses:
room.locked = True
return room
def eb(failure):
self._removeRoom(roomJID)
return failure
room = Room(roomJID, nick)
self._addRoom(room)
d = MUCClientProtocol.join(self, roomJID, nick, historyOptions,
password)
d.addCallbacks(cb, eb)
return d
def nick(self, roomJID, nick):
"""
Change an entity's nick name in a MUC room.
See: http://xmpp.org/extensions/xep-0045.html#changenick
@param roomJID: The JID of the room, i.e. without a resource.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param nick: The new nick name within the room.
@type nick: C{unicode}
"""
def cb(presence):
# Presence confirmation, change the nickname.
room.setNick(nick)
return room
room = self._getRoom(roomJID)
d = MUCClientProtocol.nick(self, roomJID, nick)
d.addCallback(cb)
return d
def leave(self, roomJID):
"""
Leave a MUC room.
See: http://xmpp.org/extensions/xep-0045.html#exit
@param roomJID: The Room JID of the room to leave.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
def cb(presence):
self._removeRoom(roomJID)
d = MUCClientProtocol.leave(self, roomJID)
d.addCallback(cb)
return d
def status(self, roomJID, show=None, status=None):
"""
Change user status.
See: http://xmpp.org/extensions/xep-0045.html#changepres
@param roomJID: The Room JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param show: The availability of the entity. Common values are xa,
available, etc
@type show: C{unicode}
@param status: The current status of the entity.
@type status: C{unicode}
"""
room = self._getRoom(roomJID)
d = MUCClientProtocol.status(self, roomJID, show, status)
d.addCallback(lambda _: room)
return d
def destroy(self, roomJID, reason=None, alternate=None, password=None):
"""
Destroy a room.
@param roomJID: The JID of the room.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param reason: The reason for the destruction of the room.
@type reason: C{unicode}
@param alternate: The JID of the room suggested as an alternate venue.
@type alternate: L{JID<twisted.words.protocols.jabber.jid.JID>}
"""
def destroyed(iq):
self._removeRoom(roomJID)
d = MUCClientProtocol.destroy(self, roomJID, reason, alternate)
d.addCallback(destroyed)
return d
| 29.234124
| 79
| 0.607447
|
from dateutil.tz import tzutc
from zope.interface import implements
from twisted.internet import defer
from twisted.words.protocols.jabber import jid, error, xmlstream
from twisted.words.xish import domish
from wokkel import data_form, generic, iwokkel, xmppim
from wokkel.compat import Values, ValueConstant
from wokkel.delay import Delay, DelayMixin
from wokkel.subprotocols import XMPPHandler
from wokkel.iwokkel import IMUCClient
NS_MUC = 'http://jabber.org/protocol/muc'
NS_MUC_USER = NS_MUC + '#user'
NS_MUC_ADMIN = NS_MUC + '#admin'
NS_MUC_OWNER = NS_MUC + '#owner'
NS_MUC_ROOMINFO = NS_MUC + '#roominfo'
NS_MUC_CONFIG = NS_MUC + '#roomconfig'
NS_MUC_REQUEST = NS_MUC + '#request'
NS_MUC_REGISTER = NS_MUC + '#register'
NS_REGISTER = 'jabber:iq:register'
MESSAGE = '/message'
PRESENCE = '/presence'
GROUPCHAT = MESSAGE +'[@type="groupchat"]'
DEFER_TIMEOUT = 30
class STATUS_CODE(Values):
REALJID_PUBLIC = ValueConstant(100)
AFFILIATION_CHANGED = ValueConstant(101)
UNAVAILABLE_SHOWN = ValueConstant(102)
UNAVAILABLE_NOT_SHOWN = ValueConstant(103)
CONFIGURATION_CHANGED = ValueConstant(104)
SELF_PRESENCE = ValueConstant(110)
LOGGING_ENABLED = ValueConstant(170)
LOGGING_DISABLED = ValueConstant(171)
NON_ANONYMOUS = ValueConstant(172)
SEMI_ANONYMOUS = ValueConstant(173)
FULLY_ANONYMOUS = ValueConstant(174)
ROOM_CREATED = ValueConstant(201)
NICK_ASSIGNED = ValueConstant(210)
BANNED = ValueConstant(301)
NEW_NICK = ValueConstant(303)
KICKED = ValueConstant(307)
REMOVED_AFFILIATION = ValueConstant(321)
REMOVED_MEMBERSHIP = ValueConstant(322)
REMOVED_SHUTDOWN = ValueConstant(332)
class Statuses(set):
implements(iwokkel.IMUCStatuses)
class _FormRequest(generic.Request):
requestNamespace = None
formNamespace = None
def __init__(self, recipient, sender=None, options=None):
if options is None:
stanzaType = 'get'
else:
stanzaType = 'set'
generic.Request.__init__(self, recipient, sender, stanzaType)
self.options = options
def toElement(self):
element = generic.Request.toElement(self)
query = element.addElement((self.requestNamespace, 'query'))
if self.options is None:
form = None
elif self.options is False:
form = data_form.Form(formType='cancel')
else:
form = data_form.Form(formType='submit',
formNamespace=self.formNamespace)
form.makeFields(self.options)
if form is not None:
query.addChild(form.toElement())
return element
class ConfigureRequest(_FormRequest):
requestNamespace = NS_MUC_OWNER
formNamespace = NS_MUC_CONFIG
class RegisterRequest(_FormRequest):
requestNamespace = NS_REGISTER
formNamespace = NS_MUC_REGISTER
class AdminItem(object):
def __init__(self, affiliation=None, role=None, entity=None, nick=None,
reason=None):
self.affiliation = affiliation
self.role = role
self.entity = entity
self.nick = nick
self.reason = reason
def toElement(self):
element = domish.Element((NS_MUC_ADMIN, 'item'))
if self.entity:
element['jid'] = self.entity.full()
if self.nick:
element['nick'] = self.nick
if self.affiliation:
element['affiliation'] = self.affiliation
if self.role:
element['role'] = self.role
if self.reason:
element.addElement('reason', content=self.reason)
return element
@classmethod
def fromElement(Class, element):
item = Class()
if element.hasAttribute('jid'):
item.entity = jid.JID(element['jid'])
item.nick = element.getAttribute('nick')
item.affiliation = element.getAttribute('affiliation')
item.role = element.getAttribute('role')
for child in element.elements(NS_MUC_ADMIN, 'reason'):
item.reason = unicode(child)
return item
class AdminStanza(generic.Request):
childParsers = {(NS_MUC_ADMIN, 'query'): '_childParser_query'}
def toElement(self):
element = generic.Request.toElement(self)
element.addElement((NS_MUC_ADMIN, 'query'))
if self.items:
for item in self.items:
element.query.addChild(item.toElement())
return element
def _childParser_query(self, element):
self.items = []
for child in element.elements(NS_MUC_ADMIN, 'item'):
self.items.append(AdminItem.fromElement(child))
class DestructionRequest(generic.Request):
stanzaType = 'set'
def __init__(self, recipient, sender=None, reason=None, alternate=None,
password=None):
generic.Request.__init__(self, recipient, sender)
self.reason = reason
self.alternate = alternate
self.password = password
def toElement(self):
element = generic.Request.toElement(self)
element.addElement((NS_MUC_OWNER, 'query'))
element.query.addElement('destroy')
if self.alternate:
element.query.destroy['jid'] = self.alternate.full()
if self.password:
element.query.destroy.addElement('password',
content=self.password)
if self.reason:
element.query.destroy.addElement('reason', content=self.reason)
return element
class GroupChat(xmppim.Message, DelayMixin):
stanzaType = 'groupchat'
def toElement(self, legacyDelay=False):
element = xmppim.Message.toElement(self)
if self.delay:
element.addChild(self.delay.toElement(legacy=legacyDelay))
return element
class PrivateChat(xmppim.Message):
stanzaType = 'chat'
class InviteMessage(xmppim.Message):
def __init__(self, recipient=None, sender=None, invitee=None, reason=None):
xmppim.Message.__init__(self, recipient, sender)
self.invitee = invitee
self.reason = reason
def toElement(self):
element = xmppim.Message.toElement(self)
child = element.addElement((NS_MUC_USER, 'x'))
child.addElement('invite')
child.invite['to'] = self.invitee.full()
if self.reason:
child.invite.addElement('reason', content=self.reason)
return element
class HistoryOptions(object):
attributes = ['maxChars', 'maxStanzas', 'seconds', 'since']
def __init__(self, maxChars=None, maxStanzas=None, seconds=None,
since=None):
self.maxChars = maxChars
self.maxStanzas = maxStanzas
self.seconds = seconds
self.since = since
def toElement(self):
element = domish.Element((NS_MUC, 'history'))
for key in self.attributes:
value = getattr(self, key, None)
if value is not None:
if key == 'since':
stamp = value.astimezone(tzutc())
element[key] = stamp.strftime('%Y-%m-%dT%H:%M:%SZ')
else:
element[key.lower()] = str(value)
return element
class BasicPresence(xmppim.AvailabilityPresence):
history = None
password = None
def toElement(self):
element = xmppim.AvailabilityPresence.toElement(self)
muc = element.addElement((NS_MUC, 'x'))
if self.password:
muc.addElement('password', content=self.password)
if self.history:
muc.addChild(self.history.toElement())
return element
class UserPresence(xmppim.AvailabilityPresence):
affiliation = None
role = None
entity = None
nick = None
mucStatuses = None
childParsers = {(NS_MUC_USER, 'x'): '_childParser_mucUser'}
def __init__(self, *args, **kwargs):
self.mucStatuses = Statuses()
xmppim.AvailabilityPresence.__init__(self, *args, **kwargs)
def _childParser_mucUser(self, element):
for child in element.elements():
if child.uri != NS_MUC_USER:
continue
elif child.name == 'status':
try:
value = int(child.getAttribute('code'))
statusCode = STATUS_CODE.lookupByValue(value)
except (TypeError, ValueError):
continue
self.mucStatuses.add(statusCode)
elif child.name == 'item':
if child.hasAttribute('jid'):
self.entity = jid.JID(child['jid'])
self.nick = child.getAttribute('nick')
self.affiliation = child.getAttribute('affiliation')
self.role = child.getAttribute('role')
for reason in child.elements(NS_MUC_ADMIN, 'reason'):
self.reason = unicode(reason)
class VoiceRequest(xmppim.Message):
def toElement(self):
element = xmppim.Message.toElement(self)
form = data_form.Form('submit', formNamespace=NS_MUC_REQUEST)
form.addField(data_form.Field(var='muc#role',
value='participant',
label='Requested role'))
element.addChild(form.toElement())
return element
class MUCClientProtocol(xmppim.BasePresenceProtocol):
timeout = None
presenceTypeParserMap = {
'error': generic.ErrorStanza,
'available': UserPresence,
'unavailable': UserPresence,
}
def __init__(self, reactor=None):
XMPPHandler.__init__(self)
if reactor:
self._reactor = reactor
else:
from twisted.internet import reactor
self._reactor = reactor
def connectionInitialized(self):
xmppim.BasePresenceProtocol.connectionInitialized(self)
self.xmlstream.addObserver(GROUPCHAT, self._onGroupChat)
self._roomOccupantMap = {}
def _onGroupChat(self, element):
message = GroupChat.fromElement(element)
self.groupChatReceived(message)
def groupChatReceived(self, message):
pass
def _sendDeferred(self, stanza):
def onResponse(element):
if element.getAttribute('type') == 'error':
d.errback(error.exceptionFromStanza(element))
else:
d.callback(UserPresence.fromElement(element))
def onTimeout():
d.errback(xmlstream.TimeoutError("Timeout waiting for response."))
def cancelTimeout(result):
if call.active():
call.cancel()
return result
def recordOccupant(presence):
occupantJID = presence.sender
roomJID = occupantJID.userhostJID()
self._roomOccupantMap[roomJID] = occupantJID
return presence
call = self._reactor.callLater(DEFER_TIMEOUT, onTimeout)
d = defer.Deferred()
d.addBoth(cancelTimeout)
d.addCallback(recordOccupant)
query = "/presence[@from='%s' or (@from='%s' and @type='error')]" % (
stanza.recipient.full(), stanza.recipient.userhost())
self.xmlstream.addOnetimeObserver(query, onResponse, priority=-1)
self.xmlstream.send(stanza.toElement())
return d
def join(self, roomJID, nick, historyOptions=None, password=None):
occupantJID = jid.JID(tuple=(roomJID.user, roomJID.host, nick))
presence = BasicPresence(recipient=occupantJID)
if password:
presence.password = password
if historyOptions:
presence.history = historyOptions
return self._sendDeferred(presence)
def nick(self, roomJID, nick):
occupantJID = jid.JID(tuple=(roomJID.user, roomJID.host, nick))
presence = BasicPresence(recipient=occupantJID)
return self._sendDeferred(presence)
def status(self, roomJID, show=None, status=None):
occupantJID = self._roomOccupantMap[roomJID]
presence = BasicPresence(recipient=occupantJID, show=show,
status=status)
return self._sendDeferred(presence)
def leave(self, roomJID):
occupantJID = self._roomOccupantMap[roomJID]
presence = xmppim.AvailabilityPresence(recipient=occupantJID,
available=False)
return self._sendDeferred(presence)
def groupChat(self, roomJID, body):
message = GroupChat(recipient=roomJID, body=body)
self.send(message.toElement())
def chat(self, occupantJID, body):
message = PrivateChat(recipient=occupantJID, body=body)
self.send(message.toElement())
def subject(self, roomJID, subject):
message = GroupChat(roomJID.userhostJID(), subject=subject)
self.send(message.toElement())
def invite(self, roomJID, invitee, reason=None):
message = InviteMessage(recipient=roomJID, invitee=invitee,
reason=reason)
self.send(message.toElement())
def getRegisterForm(self, roomJID):
def cb(response):
form = data_form.findForm(response.query, NS_MUC_REGISTER)
return form
request = RegisterRequest(recipient=roomJID, options=None)
d = self.request(request)
d.addCallback(cb)
return d
def register(self, roomJID, options):
if options is None:
options = False
request = RegisterRequest(recipient=roomJID, options=options)
return self.request(request)
def voice(self, roomJID):
message = VoiceRequest(recipient=roomJID)
self.xmlstream.send(message.toElement())
def history(self, roomJID, messages):
for message in messages:
stanza = message['stanza']
stanza['type'] = 'groupchat'
delay = Delay(stamp=message['timestamp'])
sender = stanza.getAttribute('from')
if sender is not None:
delay.sender = jid.JID(sender)
stanza.addChild(delay.toElement())
stanza['to'] = roomJID.userhost()
if stanza.hasAttribute('from'):
del stanza['from']
self.xmlstream.send(stanza)
def getConfiguration(self, roomJID):
def cb(response):
form = data_form.findForm(response.query, NS_MUC_CONFIG)
return form
request = ConfigureRequest(recipient=roomJID, options=None)
d = self.request(request)
d.addCallback(cb)
return d
def configure(self, roomJID, options):
if options is None:
options = False
request = ConfigureRequest(recipient=roomJID, options=options)
return self.request(request)
def _getAffiliationList(self, roomJID, affiliation):
def cb(response):
stanza = AdminStanza.fromElement(response)
return stanza.items
request = AdminStanza(recipient=roomJID, stanzaType='get')
request.items = [AdminItem(affiliation=affiliation)]
d = self.request(request)
d.addCallback(cb)
return d
def _getRoleList(self, roomJID, role):
def cb(response):
stanza = AdminStanza.fromElement(response)
return stanza.items
request = AdminStanza(recipient=roomJID, stanzaType='get')
request.items = [AdminItem(role=role)]
d = self.request(request)
d.addCallback(cb)
return d
def getMemberList(self, roomJID):
return self._getAffiliationList(roomJID, 'member')
def getAdminList(self, roomJID):
return self._getAffiliationList(roomJID, 'admin')
def getBanList(self, roomJID):
return self._getAffiliationList(roomJID, 'outcast')
def getOwnerList(self, roomJID):
return self._getAffiliationList(roomJID, 'owner')
def getModeratorList(self, roomJID):
d = self._getRoleList(roomJID, 'moderator')
return d
def _setAffiliation(self, roomJID, entity, affiliation,
reason=None, sender=None):
request = AdminStanza(recipient=roomJID, sender=sender,
stanzaType='set')
item = AdminItem(entity=entity, affiliation=affiliation, reason=reason)
request.items = [item]
return self.request(request)
def _setRole(self, roomJID, nick, role,
reason=None, sender=None):
request = AdminStanza(recipient=roomJID, sender=sender,
stanzaType='set')
item = AdminItem(nick=nick, role=role, reason=reason)
request.items = [item]
return self.request(request)
def modifyAffiliationList(self, roomJID, entities, affiliation,
sender=None):
request = AdminStanza(recipient=roomJID, sender=sender,
stanzaType='set')
request.items = [AdminItem(entity=entity, affiliation=affiliation)
for entity in entities]
return self.request(request)
def grantVoice(self, roomJID, nick, reason=None, sender=None):
return self._setRole(roomJID, nick=nick,
role='participant',
reason=reason, sender=sender)
def revokeVoice(self, roomJID, nick, reason=None, sender=None):
return self._setRole(roomJID, nick=nick, role='visitor',
reason=reason, sender=sender)
def grantModerator(self, roomJID, nick, reason=None, sender=None):
return self._setRole(roomJID, nick=nick, role='moderator',
reason=reason, sender=sender)
def ban(self, roomJID, entity, reason=None, sender=None):
return self._setAffiliation(roomJID, entity, 'outcast',
reason=reason, sender=sender)
def kick(self, roomJID, nick, reason=None, sender=None):
return self._setRole(roomJID, nick, 'none',
reason=reason, sender=sender)
def destroy(self, roomJID, reason=None, alternate=None, password=None):
request = DestructionRequest(recipient=roomJID, reason=reason,
alternate=alternate, password=password)
return self.request(request)
class User(object):
def __init__(self, nick, entity=None):
self.nick = nick
self.entity = entity
self.affiliation = 'none'
self.role = 'none'
self.status = None
self.show = None
class Room(object):
locked = False
def __init__(self, roomJID, nick):
self.roomJID = roomJID
self.setNick(nick)
self.roster = {}
def setNick(self, nick):
self.occupantJID = jid.internJID(u"%s/%s" % (self.roomJID, nick))
self.nick = nick
def addUser(self, user):
self.roster[user.nick] = user
def inRoster(self, user):
return user.nick in self.roster
def getUser(self, nick):
return self.roster.get(nick)
def removeUser(self, user):
if self.inRoster(user):
del self.roster[user.nick]
class MUCClient(MUCClientProtocol):
implements(IMUCClient)
def __init__(self, reactor=None):
MUCClientProtocol.__init__(self, reactor)
self._rooms = {}
def _addRoom(self, room):
roomJID = room.occupantJID.userhostJID()
self._rooms[roomJID] = room
def _getRoom(self, roomJID):
return self._rooms.get(roomJID)
def _removeRoom(self, roomJID):
if roomJID in self._rooms:
del self._rooms[roomJID]
def _getRoomUser(self, stanza):
occupantJID = stanza.sender
if not occupantJID:
return None, None
room = self._getRoom(occupantJID.userhostJID())
if room is None:
return None, None
nick = occupantJID.resource
user = room.getUser(nick)
return room, user
def unavailableReceived(self, presence):
room, user = self._getRoomUser(presence)
if room is None or user is None:
return
room.removeUser(user)
self.userLeftRoom(room, user)
def availableReceived(self, presence):
room, user = self._getRoomUser(presence)
if room is None:
return
if user is None:
nick = presence.sender.resource
user = User(nick, presence.entity)
user.status = presence.status
user.show = presence.show
if room.inRoster(user):
self.userUpdatedStatus(room, user, presence.show, presence.status)
else:
room.addUser(user)
self.userJoinedRoom(room, user)
def groupChatReceived(self, message):
room, user = self._getRoomUser(message)
if room is None:
return
if message.subject:
self.receivedSubject(room, user, message.subject)
elif message.delay is None:
self.receivedGroupChat(room, user, message)
else:
self.receivedHistory(room, user, message)
def userJoinedRoom(self, room, user):
pass
def userLeftRoom(self, room, user):
pass
def userUpdatedStatus(self, room, user, show, status):
pass
def receivedSubject(self, room, user, subject):
pass
def receivedGroupChat(self, room, user, message):
pass
def receivedHistory(self, room, user, message):
pass
def join(self, roomJID, nick, historyOptions=None,
password=None):
def cb(presence):
if STATUS_CODE.ROOM_CREATED in presence.mucStatuses:
room.locked = True
return room
def eb(failure):
self._removeRoom(roomJID)
return failure
room = Room(roomJID, nick)
self._addRoom(room)
d = MUCClientProtocol.join(self, roomJID, nick, historyOptions,
password)
d.addCallbacks(cb, eb)
return d
def nick(self, roomJID, nick):
def cb(presence):
room.setNick(nick)
return room
room = self._getRoom(roomJID)
d = MUCClientProtocol.nick(self, roomJID, nick)
d.addCallback(cb)
return d
def leave(self, roomJID):
def cb(presence):
self._removeRoom(roomJID)
d = MUCClientProtocol.leave(self, roomJID)
d.addCallback(cb)
return d
def status(self, roomJID, show=None, status=None):
room = self._getRoom(roomJID)
d = MUCClientProtocol.status(self, roomJID, show, status)
d.addCallback(lambda _: room)
return d
def destroy(self, roomJID, reason=None, alternate=None, password=None):
def destroyed(iq):
self._removeRoom(roomJID)
d = MUCClientProtocol.destroy(self, roomJID, reason, alternate)
d.addCallback(destroyed)
return d
| true
| true
|
790e74c8370be5ee794d9d226bcc2a00fa272636
| 7,563
|
py
|
Python
|
pybind/slxos/v16r_1_00b/brocade_mpls_rpc/show_mpls_lsp_extensive/output/lsp/show_mpls_lsp_extensive_info/show_mpls_lsp_sec_path_info/sec_path/lsp_sec_path_config_admin_groups/lsp_admin_group/lsp_admin_group_include_any/__init__.py
|
shivharis/pybind
|
4e1c6d54b9fd722ccec25546ba2413d79ce337e6
|
[
"Apache-2.0"
] | null | null | null |
pybind/slxos/v16r_1_00b/brocade_mpls_rpc/show_mpls_lsp_extensive/output/lsp/show_mpls_lsp_extensive_info/show_mpls_lsp_sec_path_info/sec_path/lsp_sec_path_config_admin_groups/lsp_admin_group/lsp_admin_group_include_any/__init__.py
|
shivharis/pybind
|
4e1c6d54b9fd722ccec25546ba2413d79ce337e6
|
[
"Apache-2.0"
] | null | null | null |
pybind/slxos/v16r_1_00b/brocade_mpls_rpc/show_mpls_lsp_extensive/output/lsp/show_mpls_lsp_extensive_info/show_mpls_lsp_sec_path_info/sec_path/lsp_sec_path_config_admin_groups/lsp_admin_group/lsp_admin_group_include_any/__init__.py
|
shivharis/pybind
|
4e1c6d54b9fd722ccec25546ba2413d79ce337e6
|
[
"Apache-2.0"
] | 1
|
2021-11-05T22:15:42.000Z
|
2021-11-05T22:15:42.000Z
|
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from decimal import Decimal
from bitarray import bitarray
import __builtin__
class lsp_admin_group_include_any(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-mpls - based on the path /brocade_mpls_rpc/show-mpls-lsp-extensive/output/lsp/show-mpls-lsp-extensive-info/show-mpls-lsp-sec-path-info/sec-path/lsp-sec-path-config-admin-groups/lsp-admin-group/lsp-admin-group-include-any. Each member element of
the container is represented as a class variable - with a specific
YANG type.
"""
__slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__lsp_admin_group_include_any_group_id',)
_yang_name = 'lsp-admin-group-include-any'
_rest_name = 'lsp-admin-group-include-any'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
path_helper_ = kwargs.pop("path_helper", None)
if path_helper_ is False:
self._path_helper = False
elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper):
self._path_helper = path_helper_
elif hasattr(self, "_parent"):
path_helper_ = getattr(self._parent, "_path_helper", False)
self._path_helper = path_helper_
else:
self._path_helper = False
extmethods = kwargs.pop("extmethods", None)
if extmethods is False:
self._extmethods = False
elif extmethods is not None and isinstance(extmethods, dict):
self._extmethods = extmethods
elif hasattr(self, "_parent"):
extmethods = getattr(self._parent, "_extmethods", None)
self._extmethods = extmethods
else:
self._extmethods = False
self.__lsp_admin_group_include_any_group_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lsp-admin-group-include-any-group-id", rest_name="lsp-admin-group-include-any-group-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='uint32', is_config=True)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path()+[self._yang_name]
else:
return [u'brocade_mpls_rpc', u'show-mpls-lsp-extensive', u'output', u'lsp', u'show-mpls-lsp-extensive-info', u'show-mpls-lsp-sec-path-info', u'sec-path', u'lsp-sec-path-config-admin-groups', u'lsp-admin-group', u'lsp-admin-group-include-any']
def _rest_path(self):
if hasattr(self, "_parent"):
if self._rest_name:
return self._parent._rest_path()+[self._rest_name]
else:
return self._parent._rest_path()
else:
return [u'show-mpls-lsp-extensive', u'output', u'lsp', u'sec-path', u'lsp-sec-path-config-admin-groups', u'lsp-admin-group-include-any']
def _get_lsp_admin_group_include_any_group_id(self):
"""
Getter method for lsp_admin_group_include_any_group_id, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_extensive/output/lsp/show_mpls_lsp_extensive_info/show_mpls_lsp_sec_path_info/sec_path/lsp_sec_path_config_admin_groups/lsp_admin_group/lsp_admin_group_include_any/lsp_admin_group_include_any_group_id (uint32)
YANG Description: Include any admin group id
"""
return self.__lsp_admin_group_include_any_group_id
def _set_lsp_admin_group_include_any_group_id(self, v, load=False):
"""
Setter method for lsp_admin_group_include_any_group_id, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_extensive/output/lsp/show_mpls_lsp_extensive_info/show_mpls_lsp_sec_path_info/sec_path/lsp_sec_path_config_admin_groups/lsp_admin_group/lsp_admin_group_include_any/lsp_admin_group_include_any_group_id (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_lsp_admin_group_include_any_group_id is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_lsp_admin_group_include_any_group_id() directly.
YANG Description: Include any admin group id
"""
parent = getattr(self, "_parent", None)
if parent is not None and load is False:
raise AttributeError("Cannot set keys directly when" +
" within an instantiated list")
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lsp-admin-group-include-any-group-id", rest_name="lsp-admin-group-include-any-group-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='uint32', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """lsp_admin_group_include_any_group_id must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lsp-admin-group-include-any-group-id", rest_name="lsp-admin-group-include-any-group-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='uint32', is_config=True)""",
})
self.__lsp_admin_group_include_any_group_id = t
if hasattr(self, '_set'):
self._set()
def _unset_lsp_admin_group_include_any_group_id(self):
self.__lsp_admin_group_include_any_group_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lsp-admin-group-include-any-group-id", rest_name="lsp-admin-group-include-any-group-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='uint32', is_config=True)
lsp_admin_group_include_any_group_id = __builtin__.property(_get_lsp_admin_group_include_any_group_id, _set_lsp_admin_group_include_any_group_id)
_pyangbind_elements = {'lsp_admin_group_include_any_group_id': lsp_admin_group_include_any_group_id, }
| 57.295455
| 504
| 0.74838
|
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from decimal import Decimal
from bitarray import bitarray
import __builtin__
class lsp_admin_group_include_any(PybindBase):
__slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__lsp_admin_group_include_any_group_id',)
_yang_name = 'lsp-admin-group-include-any'
_rest_name = 'lsp-admin-group-include-any'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
path_helper_ = kwargs.pop("path_helper", None)
if path_helper_ is False:
self._path_helper = False
elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper):
self._path_helper = path_helper_
elif hasattr(self, "_parent"):
path_helper_ = getattr(self._parent, "_path_helper", False)
self._path_helper = path_helper_
else:
self._path_helper = False
extmethods = kwargs.pop("extmethods", None)
if extmethods is False:
self._extmethods = False
elif extmethods is not None and isinstance(extmethods, dict):
self._extmethods = extmethods
elif hasattr(self, "_parent"):
extmethods = getattr(self._parent, "_extmethods", None)
self._extmethods = extmethods
else:
self._extmethods = False
self.__lsp_admin_group_include_any_group_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lsp-admin-group-include-any-group-id", rest_name="lsp-admin-group-include-any-group-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='uint32', is_config=True)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path()+[self._yang_name]
else:
return [u'brocade_mpls_rpc', u'show-mpls-lsp-extensive', u'output', u'lsp', u'show-mpls-lsp-extensive-info', u'show-mpls-lsp-sec-path-info', u'sec-path', u'lsp-sec-path-config-admin-groups', u'lsp-admin-group', u'lsp-admin-group-include-any']
def _rest_path(self):
if hasattr(self, "_parent"):
if self._rest_name:
return self._parent._rest_path()+[self._rest_name]
else:
return self._parent._rest_path()
else:
return [u'show-mpls-lsp-extensive', u'output', u'lsp', u'sec-path', u'lsp-sec-path-config-admin-groups', u'lsp-admin-group-include-any']
def _get_lsp_admin_group_include_any_group_id(self):
return self.__lsp_admin_group_include_any_group_id
def _set_lsp_admin_group_include_any_group_id(self, v, load=False):
parent = getattr(self, "_parent", None)
if parent is not None and load is False:
raise AttributeError("Cannot set keys directly when" +
" within an instantiated list")
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lsp-admin-group-include-any-group-id", rest_name="lsp-admin-group-include-any-group-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='uint32', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """lsp_admin_group_include_any_group_id must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lsp-admin-group-include-any-group-id", rest_name="lsp-admin-group-include-any-group-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='uint32', is_config=True)""",
})
self.__lsp_admin_group_include_any_group_id = t
if hasattr(self, '_set'):
self._set()
def _unset_lsp_admin_group_include_any_group_id(self):
self.__lsp_admin_group_include_any_group_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lsp-admin-group-include-any-group-id", rest_name="lsp-admin-group-include-any-group-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='uint32', is_config=True)
lsp_admin_group_include_any_group_id = __builtin__.property(_get_lsp_admin_group_include_any_group_id, _set_lsp_admin_group_include_any_group_id)
_pyangbind_elements = {'lsp_admin_group_include_any_group_id': lsp_admin_group_include_any_group_id, }
| true
| true
|
790e7546f4b2894ee4a4ed5d525dc89c0e953b69
| 65
|
py
|
Python
|
Wellington_python/exemplo_listas.py
|
jwellington58/Wellingtonlp220172vacation
|
c246c6d9604f93a6d846eeb4af34a4065b3f3c4d
|
[
"MIT"
] | null | null | null |
Wellington_python/exemplo_listas.py
|
jwellington58/Wellingtonlp220172vacation
|
c246c6d9604f93a6d846eeb4af34a4065b3f3c4d
|
[
"MIT"
] | null | null | null |
Wellington_python/exemplo_listas.py
|
jwellington58/Wellingtonlp220172vacation
|
c246c6d9604f93a6d846eeb4af34a4065b3f3c4d
|
[
"MIT"
] | null | null | null |
lista = [1,2,3,4,5]
for i in range(0,5):
print(lista[i])
| 16.25
| 20
| 0.523077
|
lista = [1,2,3,4,5]
for i in range(0,5):
print(lista[i])
| true
| true
|
790e76ced01e61aad876b2c1d9379ac88c777b97
| 11,572
|
py
|
Python
|
kombu/tests/test_compat.py
|
chartbeat/kombu
|
e73033b38899f2300f50100ade1d5a8d652a6864
|
[
"BSD-3-Clause"
] | 1
|
2016-04-26T10:09:35.000Z
|
2016-04-26T10:09:35.000Z
|
kombu/tests/test_compat.py
|
serverdensity/kombu
|
a48dc5b55141f021a47912c73d2c20498c593795
|
[
"BSD-3-Clause"
] | null | null | null |
kombu/tests/test_compat.py
|
serverdensity/kombu
|
a48dc5b55141f021a47912c73d2c20498c593795
|
[
"BSD-3-Clause"
] | null | null | null |
from __future__ import absolute_import
from mock import patch
from kombu import Connection, Exchange, Queue
from kombu import compat
from .mocks import Transport, Channel
from .utils import TestCase
from .utils import Mock
class test_misc(TestCase):
def test_iterconsume(self):
class MyConnection(object):
drained = 0
def drain_events(self, *args, **kwargs):
self.drained += 1
return self.drained
class Consumer(object):
active = False
def consume(self, *args, **kwargs):
self.active = True
conn = MyConnection()
consumer = Consumer()
it = compat._iterconsume(conn, consumer)
self.assertEqual(next(it), 1)
self.assertTrue(consumer.active)
it2 = compat._iterconsume(conn, consumer, limit=10)
self.assertEqual(list(it2), [2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
def test_Queue_from_dict(self):
defs = {'binding_key': 'foo.#',
'exchange': 'fooex',
'exchange_type': 'topic',
'durable': True,
'auto_delete': False}
q1 = Queue.from_dict('foo', **dict(defs))
self.assertEqual(q1.name, 'foo')
self.assertEqual(q1.routing_key, 'foo.#')
self.assertEqual(q1.exchange.name, 'fooex')
self.assertEqual(q1.exchange.type, 'topic')
self.assertTrue(q1.durable)
self.assertTrue(q1.exchange.durable)
self.assertFalse(q1.auto_delete)
self.assertFalse(q1.exchange.auto_delete)
q2 = Queue.from_dict('foo', **dict(defs,
exchange_durable=False))
self.assertTrue(q2.durable)
self.assertFalse(q2.exchange.durable)
q3 = Queue.from_dict('foo', **dict(defs,
exchange_auto_delete=True))
self.assertFalse(q3.auto_delete)
self.assertTrue(q3.exchange.auto_delete)
q4 = Queue.from_dict('foo', **dict(defs,
queue_durable=False))
self.assertFalse(q4.durable)
self.assertTrue(q4.exchange.durable)
q5 = Queue.from_dict('foo', **dict(defs,
queue_auto_delete=True))
self.assertTrue(q5.auto_delete)
self.assertFalse(q5.exchange.auto_delete)
self.assertEqual(Queue.from_dict('foo', **dict(defs)),
Queue.from_dict('foo', **dict(defs)))
class test_Publisher(TestCase):
def setUp(self):
self.connection = Connection(transport=Transport)
def test_constructor(self):
pub = compat.Publisher(self.connection,
exchange='test_Publisher_constructor',
routing_key='rkey')
self.assertIsInstance(pub.backend, Channel)
self.assertEqual(pub.exchange.name, 'test_Publisher_constructor')
self.assertTrue(pub.exchange.durable)
self.assertFalse(pub.exchange.auto_delete)
self.assertEqual(pub.exchange.type, 'direct')
pub2 = compat.Publisher(self.connection,
exchange='test_Publisher_constructor2',
routing_key='rkey',
auto_delete=True,
durable=False)
self.assertTrue(pub2.exchange.auto_delete)
self.assertFalse(pub2.exchange.durable)
explicit = Exchange('test_Publisher_constructor_explicit',
type='topic')
pub3 = compat.Publisher(self.connection,
exchange=explicit)
self.assertEqual(pub3.exchange, explicit)
compat.Publisher(self.connection,
exchange='test_Publisher_constructor3',
channel=self.connection.default_channel)
def test_send(self):
pub = compat.Publisher(self.connection,
exchange='test_Publisher_send',
routing_key='rkey')
pub.send({'foo': 'bar'})
self.assertIn('basic_publish', pub.backend)
pub.close()
def test__enter__exit__(self):
pub = compat.Publisher(self.connection,
exchange='test_Publisher_send',
routing_key='rkey')
x = pub.__enter__()
self.assertIs(x, pub)
x.__exit__()
self.assertTrue(pub._closed)
class test_Consumer(TestCase):
def setUp(self):
self.connection = Connection(transport=Transport)
@patch('kombu.compat._iterconsume')
def test_iterconsume_calls__iterconsume(self, it, n='test_iterconsume'):
c = compat.Consumer(self.connection, queue=n, exchange=n)
c.iterconsume(limit=10, no_ack=True)
it.assert_called_with(c.connection, c, True, 10)
def test_constructor(self, n='test_Consumer_constructor'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
self.assertIsInstance(c.backend, Channel)
q = c.queues[0]
self.assertTrue(q.durable)
self.assertTrue(q.exchange.durable)
self.assertFalse(q.auto_delete)
self.assertFalse(q.exchange.auto_delete)
self.assertEqual(q.name, n)
self.assertEqual(q.exchange.name, n)
c2 = compat.Consumer(self.connection, queue=n + '2',
exchange=n + '2',
routing_key='rkey', durable=False,
auto_delete=True, exclusive=True)
q2 = c2.queues[0]
self.assertFalse(q2.durable)
self.assertFalse(q2.exchange.durable)
self.assertTrue(q2.auto_delete)
self.assertTrue(q2.exchange.auto_delete)
def test__enter__exit__(self, n='test__enter__exit__'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
x = c.__enter__()
self.assertIs(x, c)
x.__exit__()
self.assertTrue(c._closed)
def test_revive(self, n='test_revive'):
c = compat.Consumer(self.connection, queue=n, exchange=n)
with self.connection.channel() as c2:
c.revive(c2)
self.assertIs(c.backend, c2)
def test__iter__(self, n='test__iter__'):
c = compat.Consumer(self.connection, queue=n, exchange=n)
c.iterqueue = Mock()
c.__iter__()
c.iterqueue.assert_called_with(infinite=True)
def test_iter(self, n='test_iterqueue'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
c.close()
def test_process_next(self, n='test_process_next'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
with self.assertRaises(NotImplementedError):
c.process_next()
c.close()
def test_iterconsume(self, n='test_iterconsume'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
c.close()
def test_discard_all(self, n='test_discard_all'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
c.discard_all()
self.assertIn('queue_purge', c.backend)
def test_fetch(self, n='test_fetch'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
self.assertIsNone(c.fetch())
self.assertIsNone(c.fetch(no_ack=True))
self.assertIn('basic_get', c.backend)
callback_called = [False]
def receive(payload, message):
callback_called[0] = True
c.backend.to_deliver.append('42')
self.assertEqual(c.fetch().payload, '42')
c.backend.to_deliver.append('46')
c.register_callback(receive)
self.assertEqual(c.fetch(enable_callbacks=True).payload, '46')
self.assertTrue(callback_called[0])
def test_discard_all_filterfunc_not_supported(self, n='xjf21j21'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
with self.assertRaises(NotImplementedError):
c.discard_all(filterfunc=lambda x: x)
c.close()
def test_wait(self, n='test_wait'):
class C(compat.Consumer):
def iterconsume(self, limit=None):
for i in range(limit):
yield i
c = C(self.connection,
queue=n, exchange=n, routing_key='rkey')
self.assertEqual(c.wait(10), list(range(10)))
c.close()
def test_iterqueue(self, n='test_iterqueue'):
i = [0]
class C(compat.Consumer):
def fetch(self, limit=None):
z = i[0]
i[0] += 1
return z
c = C(self.connection,
queue=n, exchange=n, routing_key='rkey')
self.assertEqual(list(c.iterqueue(limit=10)), list(range(10)))
c.close()
class test_ConsumerSet(TestCase):
def setUp(self):
self.connection = Connection(transport=Transport)
@patch('kombu.compat._iterconsume')
def test_iterconsume(self, _iterconsume, n='test_iterconsume'):
c = compat.Consumer(self.connection, queue=n, exchange=n)
cs = compat.ConsumerSet(self.connection, consumers=[c])
cs.iterconsume(limit=10, no_ack=True)
_iterconsume.assert_called_with(c.connection, cs, True, 10)
def test_revive(self, n='test_revive'):
c = compat.Consumer(self.connection, queue=n, exchange=n)
cs = compat.ConsumerSet(self.connection, consumers=[c])
with self.connection.channel() as c2:
cs.revive(c2)
self.assertIs(cs.backend, c2)
def test_constructor(self, prefix='0daf8h21'):
dcon = {'%s.xyx' % prefix: {'exchange': '%s.xyx' % prefix,
'routing_key': 'xyx'},
'%s.xyz' % prefix: {'exchange': '%s.xyz' % prefix,
'routing_key': 'xyz'}}
consumers = [compat.Consumer(self.connection, queue=prefix + str(i),
exchange=prefix + str(i))
for i in range(3)]
c = compat.ConsumerSet(self.connection, consumers=consumers)
c2 = compat.ConsumerSet(self.connection, from_dict=dcon)
self.assertEqual(len(c.queues), 3)
self.assertEqual(len(c2.queues), 2)
c.add_consumer(compat.Consumer(self.connection,
queue=prefix + 'xaxxxa',
exchange=prefix + 'xaxxxa'))
self.assertEqual(len(c.queues), 4)
for cq in c.queues:
self.assertIs(cq.channel, c.channel)
c2.add_consumer_from_dict({
'%s.xxx' % prefix: {
'exchange': '%s.xxx' % prefix,
'routing_key': 'xxx',
},
})
self.assertEqual(len(c2.queues), 3)
for c2q in c2.queues:
self.assertIs(c2q.channel, c2.channel)
c.discard_all()
self.assertEqual(c.channel.called.count('queue_purge'), 4)
c.consume()
c.close()
c2.close()
self.assertIn('basic_cancel', c.channel)
self.assertIn('close', c.channel)
self.assertIn('close', c2.channel)
| 35.716049
| 76
| 0.571638
|
from __future__ import absolute_import
from mock import patch
from kombu import Connection, Exchange, Queue
from kombu import compat
from .mocks import Transport, Channel
from .utils import TestCase
from .utils import Mock
class test_misc(TestCase):
def test_iterconsume(self):
class MyConnection(object):
drained = 0
def drain_events(self, *args, **kwargs):
self.drained += 1
return self.drained
class Consumer(object):
active = False
def consume(self, *args, **kwargs):
self.active = True
conn = MyConnection()
consumer = Consumer()
it = compat._iterconsume(conn, consumer)
self.assertEqual(next(it), 1)
self.assertTrue(consumer.active)
it2 = compat._iterconsume(conn, consumer, limit=10)
self.assertEqual(list(it2), [2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
def test_Queue_from_dict(self):
defs = {'binding_key': 'foo.#',
'exchange': 'fooex',
'exchange_type': 'topic',
'durable': True,
'auto_delete': False}
q1 = Queue.from_dict('foo', **dict(defs))
self.assertEqual(q1.name, 'foo')
self.assertEqual(q1.routing_key, 'foo.#')
self.assertEqual(q1.exchange.name, 'fooex')
self.assertEqual(q1.exchange.type, 'topic')
self.assertTrue(q1.durable)
self.assertTrue(q1.exchange.durable)
self.assertFalse(q1.auto_delete)
self.assertFalse(q1.exchange.auto_delete)
q2 = Queue.from_dict('foo', **dict(defs,
exchange_durable=False))
self.assertTrue(q2.durable)
self.assertFalse(q2.exchange.durable)
q3 = Queue.from_dict('foo', **dict(defs,
exchange_auto_delete=True))
self.assertFalse(q3.auto_delete)
self.assertTrue(q3.exchange.auto_delete)
q4 = Queue.from_dict('foo', **dict(defs,
queue_durable=False))
self.assertFalse(q4.durable)
self.assertTrue(q4.exchange.durable)
q5 = Queue.from_dict('foo', **dict(defs,
queue_auto_delete=True))
self.assertTrue(q5.auto_delete)
self.assertFalse(q5.exchange.auto_delete)
self.assertEqual(Queue.from_dict('foo', **dict(defs)),
Queue.from_dict('foo', **dict(defs)))
class test_Publisher(TestCase):
def setUp(self):
self.connection = Connection(transport=Transport)
def test_constructor(self):
pub = compat.Publisher(self.connection,
exchange='test_Publisher_constructor',
routing_key='rkey')
self.assertIsInstance(pub.backend, Channel)
self.assertEqual(pub.exchange.name, 'test_Publisher_constructor')
self.assertTrue(pub.exchange.durable)
self.assertFalse(pub.exchange.auto_delete)
self.assertEqual(pub.exchange.type, 'direct')
pub2 = compat.Publisher(self.connection,
exchange='test_Publisher_constructor2',
routing_key='rkey',
auto_delete=True,
durable=False)
self.assertTrue(pub2.exchange.auto_delete)
self.assertFalse(pub2.exchange.durable)
explicit = Exchange('test_Publisher_constructor_explicit',
type='topic')
pub3 = compat.Publisher(self.connection,
exchange=explicit)
self.assertEqual(pub3.exchange, explicit)
compat.Publisher(self.connection,
exchange='test_Publisher_constructor3',
channel=self.connection.default_channel)
def test_send(self):
pub = compat.Publisher(self.connection,
exchange='test_Publisher_send',
routing_key='rkey')
pub.send({'foo': 'bar'})
self.assertIn('basic_publish', pub.backend)
pub.close()
def test__enter__exit__(self):
pub = compat.Publisher(self.connection,
exchange='test_Publisher_send',
routing_key='rkey')
x = pub.__enter__()
self.assertIs(x, pub)
x.__exit__()
self.assertTrue(pub._closed)
class test_Consumer(TestCase):
def setUp(self):
self.connection = Connection(transport=Transport)
@patch('kombu.compat._iterconsume')
def test_iterconsume_calls__iterconsume(self, it, n='test_iterconsume'):
c = compat.Consumer(self.connection, queue=n, exchange=n)
c.iterconsume(limit=10, no_ack=True)
it.assert_called_with(c.connection, c, True, 10)
def test_constructor(self, n='test_Consumer_constructor'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
self.assertIsInstance(c.backend, Channel)
q = c.queues[0]
self.assertTrue(q.durable)
self.assertTrue(q.exchange.durable)
self.assertFalse(q.auto_delete)
self.assertFalse(q.exchange.auto_delete)
self.assertEqual(q.name, n)
self.assertEqual(q.exchange.name, n)
c2 = compat.Consumer(self.connection, queue=n + '2',
exchange=n + '2',
routing_key='rkey', durable=False,
auto_delete=True, exclusive=True)
q2 = c2.queues[0]
self.assertFalse(q2.durable)
self.assertFalse(q2.exchange.durable)
self.assertTrue(q2.auto_delete)
self.assertTrue(q2.exchange.auto_delete)
def test__enter__exit__(self, n='test__enter__exit__'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
x = c.__enter__()
self.assertIs(x, c)
x.__exit__()
self.assertTrue(c._closed)
def test_revive(self, n='test_revive'):
c = compat.Consumer(self.connection, queue=n, exchange=n)
with self.connection.channel() as c2:
c.revive(c2)
self.assertIs(c.backend, c2)
def test__iter__(self, n='test__iter__'):
c = compat.Consumer(self.connection, queue=n, exchange=n)
c.iterqueue = Mock()
c.__iter__()
c.iterqueue.assert_called_with(infinite=True)
def test_iter(self, n='test_iterqueue'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
c.close()
def test_process_next(self, n='test_process_next'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
with self.assertRaises(NotImplementedError):
c.process_next()
c.close()
def test_iterconsume(self, n='test_iterconsume'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
c.close()
def test_discard_all(self, n='test_discard_all'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
c.discard_all()
self.assertIn('queue_purge', c.backend)
def test_fetch(self, n='test_fetch'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
self.assertIsNone(c.fetch())
self.assertIsNone(c.fetch(no_ack=True))
self.assertIn('basic_get', c.backend)
callback_called = [False]
def receive(payload, message):
callback_called[0] = True
c.backend.to_deliver.append('42')
self.assertEqual(c.fetch().payload, '42')
c.backend.to_deliver.append('46')
c.register_callback(receive)
self.assertEqual(c.fetch(enable_callbacks=True).payload, '46')
self.assertTrue(callback_called[0])
def test_discard_all_filterfunc_not_supported(self, n='xjf21j21'):
c = compat.Consumer(self.connection, queue=n, exchange=n,
routing_key='rkey')
with self.assertRaises(NotImplementedError):
c.discard_all(filterfunc=lambda x: x)
c.close()
def test_wait(self, n='test_wait'):
class C(compat.Consumer):
def iterconsume(self, limit=None):
for i in range(limit):
yield i
c = C(self.connection,
queue=n, exchange=n, routing_key='rkey')
self.assertEqual(c.wait(10), list(range(10)))
c.close()
def test_iterqueue(self, n='test_iterqueue'):
i = [0]
class C(compat.Consumer):
def fetch(self, limit=None):
z = i[0]
i[0] += 1
return z
c = C(self.connection,
queue=n, exchange=n, routing_key='rkey')
self.assertEqual(list(c.iterqueue(limit=10)), list(range(10)))
c.close()
class test_ConsumerSet(TestCase):
def setUp(self):
self.connection = Connection(transport=Transport)
@patch('kombu.compat._iterconsume')
def test_iterconsume(self, _iterconsume, n='test_iterconsume'):
c = compat.Consumer(self.connection, queue=n, exchange=n)
cs = compat.ConsumerSet(self.connection, consumers=[c])
cs.iterconsume(limit=10, no_ack=True)
_iterconsume.assert_called_with(c.connection, cs, True, 10)
def test_revive(self, n='test_revive'):
c = compat.Consumer(self.connection, queue=n, exchange=n)
cs = compat.ConsumerSet(self.connection, consumers=[c])
with self.connection.channel() as c2:
cs.revive(c2)
self.assertIs(cs.backend, c2)
def test_constructor(self, prefix='0daf8h21'):
dcon = {'%s.xyx' % prefix: {'exchange': '%s.xyx' % prefix,
'routing_key': 'xyx'},
'%s.xyz' % prefix: {'exchange': '%s.xyz' % prefix,
'routing_key': 'xyz'}}
consumers = [compat.Consumer(self.connection, queue=prefix + str(i),
exchange=prefix + str(i))
for i in range(3)]
c = compat.ConsumerSet(self.connection, consumers=consumers)
c2 = compat.ConsumerSet(self.connection, from_dict=dcon)
self.assertEqual(len(c.queues), 3)
self.assertEqual(len(c2.queues), 2)
c.add_consumer(compat.Consumer(self.connection,
queue=prefix + 'xaxxxa',
exchange=prefix + 'xaxxxa'))
self.assertEqual(len(c.queues), 4)
for cq in c.queues:
self.assertIs(cq.channel, c.channel)
c2.add_consumer_from_dict({
'%s.xxx' % prefix: {
'exchange': '%s.xxx' % prefix,
'routing_key': 'xxx',
},
})
self.assertEqual(len(c2.queues), 3)
for c2q in c2.queues:
self.assertIs(c2q.channel, c2.channel)
c.discard_all()
self.assertEqual(c.channel.called.count('queue_purge'), 4)
c.consume()
c.close()
c2.close()
self.assertIn('basic_cancel', c.channel)
self.assertIn('close', c.channel)
self.assertIn('close', c2.channel)
| true
| true
|
790e7920cc465ce6604d5a02d4a3e1aefa47b008
| 508
|
py
|
Python
|
tools/unpool_test.py
|
rcmalli/polimi-dl-project
|
5bf26a8e930dc98fe59a74bc473ddc74ff7dd201
|
[
"MIT"
] | 4
|
2018-09-03T13:36:43.000Z
|
2020-02-13T18:52:09.000Z
|
tools/unpool_test.py
|
rcmalli/polimi-dl-project
|
5bf26a8e930dc98fe59a74bc473ddc74ff7dd201
|
[
"MIT"
] | null | null | null |
tools/unpool_test.py
|
rcmalli/polimi-dl-project
|
5bf26a8e930dc98fe59a74bc473ddc74ff7dd201
|
[
"MIT"
] | 1
|
2019-01-09T04:02:49.000Z
|
2019-01-09T04:02:49.000Z
|
from src.model import unpool_resize,unpool_deconv, unpool_checkerboard, unpool_simple
from tensorflow.keras.layers import Input, UpSampling2D
from tensorflow.keras.models import Model
input = Input(shape=(20, 20, 3))
out1 = unpool_resize(input)
model1 = Model(inputs=input, outputs=out1)
print("")
out2 = unpool_deconv(input,512)
model2 = Model(inputs=input, outputs=out2)
print("")
out3 = UpSampling2D((2,2))(input)
out3 = unpool_checkerboard(out3)
model3 = Model(inputs=input, outputs=out3)
print("")
| 25.4
| 85
| 0.769685
|
from src.model import unpool_resize,unpool_deconv, unpool_checkerboard, unpool_simple
from tensorflow.keras.layers import Input, UpSampling2D
from tensorflow.keras.models import Model
input = Input(shape=(20, 20, 3))
out1 = unpool_resize(input)
model1 = Model(inputs=input, outputs=out1)
print("")
out2 = unpool_deconv(input,512)
model2 = Model(inputs=input, outputs=out2)
print("")
out3 = UpSampling2D((2,2))(input)
out3 = unpool_checkerboard(out3)
model3 = Model(inputs=input, outputs=out3)
print("")
| true
| true
|
790e793a4accee9fcf2281ab1385405585257fb9
| 4,847
|
py
|
Python
|
wandb/sdk/service/service.py
|
TachikakaMin/client
|
27d1ef98285e3cb94881b370a8c37bfb310000c1
|
[
"MIT"
] | 1
|
2021-11-15T08:26:28.000Z
|
2021-11-15T08:26:28.000Z
|
wandb/sdk/service/service.py
|
webclinic017/client
|
8225a30e2db2094d817d3048a66edfaa8803941c
|
[
"MIT"
] | null | null | null |
wandb/sdk/service/service.py
|
webclinic017/client
|
8225a30e2db2094d817d3048a66edfaa8803941c
|
[
"MIT"
] | null | null | null |
"""grpc service.
Reliably launch and connect to grpc process.
"""
import datetime
import enum
import logging
import os
import subprocess
import sys
import tempfile
import time
from typing import Any, Dict, Optional
from typing import TYPE_CHECKING
import grpc
from wandb.proto import wandb_server_pb2 as spb
from wandb.proto import wandb_server_pb2_grpc as pbgrpc
from wandb.sdk.wandb_settings import Settings
if TYPE_CHECKING:
from google.protobuf.internal.containers import MessageMap
def _pbmap_apply_dict(
m: "MessageMap[str, spb.SettingsValue]", d: Dict[str, Any]
) -> None:
for k, v in d.items():
if isinstance(v, datetime.datetime):
continue
if isinstance(v, enum.Enum):
continue
sv = spb.SettingsValue()
if v is None:
sv.null_value = True
elif isinstance(v, int):
sv.int_value = v
elif isinstance(v, float):
sv.float_value = v
elif isinstance(v, str):
sv.string_value = v
elif isinstance(v, bool):
sv.bool_value = v
elif isinstance(v, tuple):
sv.tuple_value.string_values.extend(v)
m[k].CopyFrom(sv)
class _Service:
_stub: Optional[pbgrpc.InternalServiceStub]
def __init__(self) -> None:
self._stub = None
def _grpc_wait_for_port(
self, fname: str, proc: subprocess.Popen = None
) -> Optional[int]:
time_max = time.time() + 30
port = None
while time.time() < time_max:
if proc and proc.poll():
# process finished
print("proc exited with", proc.returncode)
return None
if not os.path.isfile(fname):
time.sleep(0.2)
continue
try:
f = open(fname)
port = int(f.read())
except Exception as e:
print("Error:", e)
return port
return None
def _grpc_launch_server(self) -> Optional[int]:
"""Launch grpc server and return port."""
# References for starting processes
# - https://github.com/wandb/client/blob/archive/old-cli/wandb/__init__.py
# - https://stackoverflow.com/questions/1196074/how-to-start-a-background-process-in-python
kwargs: Dict[str, Any] = dict(close_fds=True)
pid = os.getpid()
with tempfile.TemporaryDirectory() as tmpdir:
fname = os.path.join(tmpdir, f"port-{pid}.txt")
pid_str = str(os.getpid())
exec_cmd_list = [sys.executable, "-m"]
# Add coverage collection if needed
if os.environ.get("COVERAGE_RCFILE"):
exec_cmd_list += ["coverage", "run", "-m"]
internal_proc = subprocess.Popen(
exec_cmd_list
+ [
"wandb",
"service",
"--port-filename",
fname,
"--pid",
pid_str,
"--debug",
"true",
],
env=os.environ,
**kwargs,
)
port = self._grpc_wait_for_port(fname, proc=internal_proc)
return port
def start(self) -> Optional[int]:
port = self._grpc_launch_server()
return port
def connect(self, port: int) -> None:
channel = grpc.insecure_channel("localhost:{}".format(port))
stub = pbgrpc.InternalServiceStub(channel)
self._stub = stub
# TODO: make sure service is up
def _get_stub(self) -> Optional[pbgrpc.InternalServiceStub]:
return self._stub
def _svc_inform_init(self, settings: Settings, run_id: str) -> None:
assert self._stub
inform_init = spb.ServerInformInitRequest()
settings_dict = dict(settings)
settings_dict["_log_level"] = logging.DEBUG
_pbmap_apply_dict(inform_init._settings_map, settings_dict)
inform_init._info.stream_id = run_id
_ = self._stub.ServerInformInit(inform_init)
def _svc_inform_finish(self, run_id: str = None) -> None:
assert self._stub
assert run_id
inform_fin = spb.ServerInformFinishRequest()
inform_fin._info.stream_id = run_id
_ = self._stub.ServerInformFinish(inform_fin)
def _svc_inform_attach(self, attach_id: str) -> None:
assert self._stub
inform_attach = spb.ServerInformAttachRequest()
inform_attach._info.stream_id = attach_id
_ = self._stub.ServerInformAttach(inform_attach)
def _svc_inform_teardown(self, exit_code: int) -> None:
assert self._stub
inform_fin = spb.ServerInformTeardownRequest(exit_code=exit_code)
_ = self._stub.ServerInformTeardown(inform_fin)
| 31.070513
| 99
| 0.592119
|
import datetime
import enum
import logging
import os
import subprocess
import sys
import tempfile
import time
from typing import Any, Dict, Optional
from typing import TYPE_CHECKING
import grpc
from wandb.proto import wandb_server_pb2 as spb
from wandb.proto import wandb_server_pb2_grpc as pbgrpc
from wandb.sdk.wandb_settings import Settings
if TYPE_CHECKING:
from google.protobuf.internal.containers import MessageMap
def _pbmap_apply_dict(
m: "MessageMap[str, spb.SettingsValue]", d: Dict[str, Any]
) -> None:
for k, v in d.items():
if isinstance(v, datetime.datetime):
continue
if isinstance(v, enum.Enum):
continue
sv = spb.SettingsValue()
if v is None:
sv.null_value = True
elif isinstance(v, int):
sv.int_value = v
elif isinstance(v, float):
sv.float_value = v
elif isinstance(v, str):
sv.string_value = v
elif isinstance(v, bool):
sv.bool_value = v
elif isinstance(v, tuple):
sv.tuple_value.string_values.extend(v)
m[k].CopyFrom(sv)
class _Service:
_stub: Optional[pbgrpc.InternalServiceStub]
def __init__(self) -> None:
self._stub = None
def _grpc_wait_for_port(
self, fname: str, proc: subprocess.Popen = None
) -> Optional[int]:
time_max = time.time() + 30
port = None
while time.time() < time_max:
if proc and proc.poll():
print("proc exited with", proc.returncode)
return None
if not os.path.isfile(fname):
time.sleep(0.2)
continue
try:
f = open(fname)
port = int(f.read())
except Exception as e:
print("Error:", e)
return port
return None
def _grpc_launch_server(self) -> Optional[int]:
kwargs: Dict[str, Any] = dict(close_fds=True)
pid = os.getpid()
with tempfile.TemporaryDirectory() as tmpdir:
fname = os.path.join(tmpdir, f"port-{pid}.txt")
pid_str = str(os.getpid())
exec_cmd_list = [sys.executable, "-m"]
if os.environ.get("COVERAGE_RCFILE"):
exec_cmd_list += ["coverage", "run", "-m"]
internal_proc = subprocess.Popen(
exec_cmd_list
+ [
"wandb",
"service",
"--port-filename",
fname,
"--pid",
pid_str,
"--debug",
"true",
],
env=os.environ,
**kwargs,
)
port = self._grpc_wait_for_port(fname, proc=internal_proc)
return port
def start(self) -> Optional[int]:
port = self._grpc_launch_server()
return port
def connect(self, port: int) -> None:
channel = grpc.insecure_channel("localhost:{}".format(port))
stub = pbgrpc.InternalServiceStub(channel)
self._stub = stub
def _get_stub(self) -> Optional[pbgrpc.InternalServiceStub]:
return self._stub
def _svc_inform_init(self, settings: Settings, run_id: str) -> None:
assert self._stub
inform_init = spb.ServerInformInitRequest()
settings_dict = dict(settings)
settings_dict["_log_level"] = logging.DEBUG
_pbmap_apply_dict(inform_init._settings_map, settings_dict)
inform_init._info.stream_id = run_id
_ = self._stub.ServerInformInit(inform_init)
def _svc_inform_finish(self, run_id: str = None) -> None:
assert self._stub
assert run_id
inform_fin = spb.ServerInformFinishRequest()
inform_fin._info.stream_id = run_id
_ = self._stub.ServerInformFinish(inform_fin)
def _svc_inform_attach(self, attach_id: str) -> None:
assert self._stub
inform_attach = spb.ServerInformAttachRequest()
inform_attach._info.stream_id = attach_id
_ = self._stub.ServerInformAttach(inform_attach)
def _svc_inform_teardown(self, exit_code: int) -> None:
assert self._stub
inform_fin = spb.ServerInformTeardownRequest(exit_code=exit_code)
_ = self._stub.ServerInformTeardown(inform_fin)
| true
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.